Parses an `if` statement. # Panics If the parser isn't positioned at an `if` token. See:
(&mut self)
| 1421 | /// |
| 1422 | /// See: <https://docs.python.org/3/reference/compound_stmts.html#the-if-statement> |
| 1423 | fn parse_if_statement(&mut self) -> ast::StmtIf { |
| 1424 | let start = self.node_start(); |
| 1425 | self.bump(TokenKind::If); |
| 1426 | |
| 1427 | // test_err if_stmt_invalid_test_expr |
| 1428 | // if *x: ... |
| 1429 | // if yield x: ... |
| 1430 | // if yield from x: ... |
| 1431 | |
| 1432 | // test_err if_stmt_missing_test |
| 1433 | // if : ... |
| 1434 | let test = self.parse_named_expression_or_higher(ExpressionContext::default()); |
| 1435 | |
| 1436 | // test_err if_stmt_missing_colon |
| 1437 | // if x |
| 1438 | // if x |
| 1439 | // pass |
| 1440 | // a = 1 |
| 1441 | self.expect(TokenKind::Colon); |
| 1442 | |
| 1443 | // test_err if_stmt_empty_body |
| 1444 | // if True: |
| 1445 | // 1 + 1 |
| 1446 | let body = self.parse_body(Clause::If); |
| 1447 | |
| 1448 | // test_err if_stmt_misspelled_elif |
| 1449 | // if True: |
| 1450 | // pass |
| 1451 | // elf: |
| 1452 | // pass |
| 1453 | // else: |
| 1454 | // pass |
| 1455 | let mut elif_else_clauses = self.parse_clauses(Clause::ElIf, |p| { |
| 1456 | p.parse_elif_or_else_clause(ElifOrElse::Elif) |
| 1457 | }); |
| 1458 | |
| 1459 | if self.at(TokenKind::Else) { |
| 1460 | if elif_else_clauses.is_empty() { |
| 1461 | elif_else_clauses.reserve_exact(1); |
| 1462 | } |
| 1463 | elif_else_clauses.push(self.parse_elif_or_else_clause(ElifOrElse::Else)); |
| 1464 | } |
| 1465 | |
| 1466 | elif_else_clauses.shrink_to_fit(); |
| 1467 | |
| 1468 | ast::StmtIf { |
| 1469 | test: Box::new(test.expr), |
| 1470 | body, |
| 1471 | elif_else_clauses, |
| 1472 | range: self.node_range(start), |
| 1473 | node_index: AtomicNodeIndex::NONE, |
| 1474 | } |
| 1475 | } |
| 1476 | |
| 1477 | /// Parses an `elif` or `else` clause. |
| 1478 | /// |
no test coverage detected