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

Method parse_if_statement

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

Parses an `if` statement. # Panics If the parser isn't positioned at an `if` token. See:

(&mut self)

Source from the content-addressed store, hash-verified

1435 ///
1436 /// See: <https://docs.python.org/3/reference/compound_stmts.html#the-if-statement>
1437 fn parse_if_statement(&mut self) -> ast::StmtIf {
1438 let start = self.node_start();
1439 self.bump(TokenKind::If);
1440
1441 // test_err if_stmt_invalid_test_expr
1442 // if *x: ...
1443 // if yield x: ...
1444 // if yield from x: ...
1445
1446 // test_err if_stmt_missing_test
1447 // if : ...
1448 let test = self.parse_named_expression_or_higher(ExpressionContext::default());
1449
1450 // test_err if_stmt_missing_colon
1451 // if x
1452 // if x
1453 // pass
1454 // a = 1
1455 self.expect(TokenKind::Colon);
1456
1457 // test_err if_stmt_empty_body
1458 // if True:
1459 // 1 + 1
1460 let body = self.parse_body(Clause::If);
1461
1462 // test_err if_stmt_misspelled_elif
1463 // if True:
1464 // pass
1465 // elf:
1466 // pass
1467 // else:
1468 // pass
1469 let elif_else_snapshot = self.elif_else_scratch.snapshot();
1470 self.parse_clauses(Clause::ElIf, |parser| {
1471 let clause = parser.parse_elif_or_else_clause(ElifOrElse::Elif);
1472 parser.elif_else_scratch.push(clause);
1473 });
1474
1475 if self.at(TokenKind::Else) {
1476 let clause = self.parse_elif_or_else_clause(ElifOrElse::Else);
1477 self.elif_else_scratch.push(clause);
1478 }
1479
1480 ast::StmtIf {
1481 test: Box::new(test.expr),
1482 body,
1483 elif_else_clauses: self.elif_else_scratch.take(elif_else_snapshot),
1484 range: self.node_range(start),
1485 node_index: AtomicNodeIndex::NONE,
1486 }
1487 }
1488
1489 /// Parses an `elif` or `else` clause.
1490 ///

Callers 1

parse_statementMethod · 0.80

Calls 13

node_startMethod · 0.80
expectMethod · 0.80
parse_bodyMethod · 0.80
parse_clausesMethod · 0.80
node_rangeMethod · 0.80
defaultFunction · 0.50
bumpMethod · 0.45
snapshotMethod · 0.45
pushMethod · 0.45
atMethod · 0.45

Tested by

no test coverage detected