Skip to content

Commit

Permalink
Use parse_parenthesized_expression_range in red-knot
Browse files Browse the repository at this point in the history
  • Loading branch information
Glyphack committed Jan 13, 2025
1 parent 3ca0e49 commit edc7345
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -173,3 +173,27 @@ p: "call()"
r: "[1, 2]"
s: "(1, 2)"
```

## Multi line annotation

Quoted type annotations should be parsed as if surrounded by parentheses.

```py
def f(
a1: """Literal[None]""",
a2: """(Literal[None])""",
a3: """(
int |
str
)
""",
a4: """
int |
str
""",
):
reveal_type(a1) # revealed: None
reveal_type(a2) # revealed: None
reveal_type(a3) # revealed: int | str
reveal_type(a4) # revealed: int | str
```
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use ruff_db::source::source_text;
use ruff_python_ast::str::raw_contents;
use ruff_python_ast::{self as ast, ModExpression, StringFlags};
use ruff_python_parser::{parse_expression_range, Parsed};
use ruff_python_parser::{parse_parenthesized_expression_range, Parsed};
use ruff_text_size::Ranged;

use crate::declare_lint;
Expand Down Expand Up @@ -165,7 +165,7 @@ pub(crate) fn parse_string_annotation(
// | float
// """ = 1
// ```
match parse_expression_range(source.as_str(), range_excluding_quotes) {
match parse_parenthesized_expression_range(source.as_str(), range_excluding_quotes) {
Ok(parsed) => return Some(parsed),
Err(parse_error) => context.report_lint(
&INVALID_SYNTAX_IN_FORWARD_ANNOTATION,
Expand Down
2 changes: 0 additions & 2 deletions crates/ruff_linter/resources/test/fixtures/pyflakes/F722.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,11 @@ def g() -> "///":
int |
str
"""

z: """(
int |
str
)
"""
14 changes: 14 additions & 0 deletions crates/ruff_python_parser/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,20 @@ pub fn parse_expression_range(
.into_result()
}

/// Parses a Python expression as if it is parenthesized.
///
/// It behaves similarly to [`parse_expression_range`] but allows what would be valid within parenthesis
///
/// # Example
///
/// Parsing a parenthesized expression from a larger expression:
///
/// ```
/// use ruff_python_parser::parse_parenthesized_expression_range;
/// # use ruff_text_size::{TextRange, TextSize};
///
/// let parsed = parse_parenthesized_expression_range("\n int | str", TextRange::new(TextSize::new(4), TextSize::new(11)));
/// assert!(parsed.is_ok());
pub fn parse_parenthesized_expression_range(
source: &str,
range: TextRange,
Expand Down

0 comments on commit edc7345

Please sign in to comment.