MCPcopy Create free account
hub / github.com/astral-sh/ruff / try_parse_match_statement

Method try_parse_match_statement

crates/ruff_python_parser/src/parser/statement.rs:2587–2644  ·  view source on GitHub ↗

Try parsing a `match` statement. This uses speculative parsing to remove the ambiguity of whether the `match` token is used as a keyword or an identifier. This ambiguity arises only in if the `match` token is followed by certain tokens. For example, if `match` is followed by `[`, we can't know if it's used in the context of a subscript expression or as a list expression: ```python # Subscript ex

(&mut self)

Source from the content-addressed store, hash-verified

2585 ///
2586 /// See: <https://docs.python.org/3/reference/compound_stmts.html#the-match-statement>
2587 fn try_parse_match_statement(&mut self) -> Option<ast::StmtMatch> {
2588 let checkpoint = self.checkpoint();
2589
2590 let start = self.node_start();
2591 self.bump_match_statement_keyword();
2592
2593 let subject = self.parse_match_subject_expression();
2594
2595 match self.current_token_kind() {
2596 // test_ok match_annotated_assignment
2597 // match[0]: int
2598 // match [x, y, z]: dict
2599 TokenKind::Colon if self.peek() == TokenKind::Newline => {
2600 // `match` is a keyword — colon followed by newline confirms
2601 // this is a match statement, not an annotated assignment like
2602 // `match [x, y, z]: {dict}` or `match[0]: int`.
2603 self.bump(TokenKind::Colon);
2604
2605 let cases = self.parse_match_body();
2606
2607 Some(ast::StmtMatch {
2608 subject: Box::new(subject),
2609 cases,
2610 range: self.node_range(start),
2611 node_index: AtomicNodeIndex::NONE,
2612 })
2613 }
2614 TokenKind::Newline if matches!(self.peek2(), (TokenKind::Indent, TokenKind::Case)) => {
2615 // `match` is a keyword
2616
2617 // test_err match_expected_colon
2618 // match [1, 2]
2619 // case _: ...
2620 self.add_error(
2621 ParseErrorType::ExpectedToken {
2622 found: self.current_token_kind(),
2623 expected: TokenKind::Colon,
2624 },
2625 self.current_token_range(),
2626 );
2627
2628 let cases = self.parse_match_body();
2629
2630 Some(ast::StmtMatch {
2631 subject: Box::new(subject),
2632 cases,
2633 range: self.node_range(start),
2634 node_index: AtomicNodeIndex::NONE,
2635 })
2636 }
2637 _ => {
2638 // `match` is an identifier
2639 self.rewind(checkpoint);
2640
2641 None
2642 }
2643 }
2644 }

Callers 1

parse_statementMethod · 0.80

Calls 12

node_startMethod · 0.80
current_token_kindMethod · 0.80
parse_match_bodyMethod · 0.80
node_rangeMethod · 0.80
current_token_rangeMethod · 0.80
checkpointMethod · 0.45
peekMethod · 0.45
bumpMethod · 0.45
add_errorMethod · 0.45
rewindMethod · 0.45

Tested by

no test coverage detected