Parse subscript expression, i.e. either an index value or slice range.
(&mut self, expr: Expr<Raw>)
| 1428 | |
| 1429 | /// Parse subscript expression, i.e. either an index value or slice range. |
| 1430 | fn parse_subscript(&mut self, expr: Expr<Raw>) -> Result<Expr<Raw>, ParserError> { |
| 1431 | let mut positions = Vec::new(); |
| 1432 | |
| 1433 | while self.consume_token(&Token::LBracket) { |
| 1434 | let start = if self.peek_token() == Some(Token::Colon) { |
| 1435 | None |
| 1436 | } else { |
| 1437 | Some(self.parse_expr()?) |
| 1438 | }; |
| 1439 | |
| 1440 | let (end, explicit_slice) = if self.consume_token(&Token::Colon) { |
| 1441 | // Presence of a colon means these positions were explicit |
| 1442 | ( |
| 1443 | // Terminated expr |
| 1444 | if self.peek_token() == Some(Token::RBracket) { |
| 1445 | None |
| 1446 | } else { |
| 1447 | Some(self.parse_expr()?) |
| 1448 | }, |
| 1449 | true, |
| 1450 | ) |
| 1451 | } else { |
| 1452 | (None, false) |
| 1453 | }; |
| 1454 | |
| 1455 | assert!( |
| 1456 | start.is_some() || explicit_slice, |
| 1457 | "user typed something between brackets" |
| 1458 | ); |
| 1459 | |
| 1460 | assert!( |
| 1461 | explicit_slice || end.is_none(), |
| 1462 | "if end is some, must have an explicit slice" |
| 1463 | ); |
| 1464 | |
| 1465 | positions.push(SubscriptPosition { |
| 1466 | start, |
| 1467 | end, |
| 1468 | explicit_slice, |
| 1469 | }); |
| 1470 | self.expect_token(&Token::RBracket)?; |
| 1471 | } |
| 1472 | |
| 1473 | // If the expression that is being cast can end with a type name, then let's parenthesize |
| 1474 | // it. Otherwise, the `[...]` would melt into the type name (making it an array type). |
| 1475 | // Specifically, the only expressions whose printing can end with a type name are casts, so |
| 1476 | // check for that. |
| 1477 | if matches!(expr, Expr::Cast { .. }) { |
| 1478 | Ok(Expr::Subscript { |
| 1479 | expr: Box::new(Expr::Nested(Box::new(expr))), |
| 1480 | positions, |
| 1481 | }) |
| 1482 | } else { |
| 1483 | Ok(Expr::Subscript { |
| 1484 | expr: Box::new(expr), |
| 1485 | positions, |
| 1486 | }) |
| 1487 | } |
no test coverage detected