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

Method parse_slice

crates/ruff_python_parser/src/parser/expression.rs:1086–1178  ·  view source on GitHub ↗

Parses a slice expression. See:

(&mut self)

Source from the content-addressed store, hash-verified

1084 ///
1085 /// See: <https://docs.python.org/3/reference/expressions.html#slicings>
1086 fn parse_slice(&mut self) -> Expr {
1087 const UPPER_END_SET: TokenSet =
1088 TokenSet::new([TokenKind::Comma, TokenKind::Colon, TokenKind::Rsqb])
1089 .union(NEWLINE_EOF_SET);
1090 const STEP_END_SET: TokenSet =
1091 TokenSet::new([TokenKind::Comma, TokenKind::Rsqb]).union(NEWLINE_EOF_SET);
1092
1093 // test_err named_expr_slice
1094 // # even after 3.9, an unparenthesized named expression is not allowed in a slice
1095 // lst[x:=1:-1]
1096 // lst[1:x:=1]
1097 // lst[1:3:x:=1]
1098
1099 // test_err named_expr_slice_parse_error
1100 // # parse_options: {"target-version": "3.8"}
1101 // # before 3.9, only emit the parse error, not the unsupported syntax error
1102 // lst[x:=1:-1]
1103
1104 let start = self.node_start();
1105
1106 let lower = if self.at_expr() {
1107 let lower =
1108 self.parse_named_expression_or_higher(ExpressionContext::starred_conditional());
1109
1110 // This means we're in a subscript.
1111 if self.at_ts(NEWLINE_EOF_SET.union([TokenKind::Rsqb, TokenKind::Comma].into())) {
1112 // test_ok parenthesized_named_expr_index_py38
1113 // # parse_options: {"target-version": "3.8"}
1114 // lst[(x:=1)]
1115
1116 // test_ok unparenthesized_named_expr_index_py39
1117 // # parse_options: {"target-version": "3.9"}
1118 // lst[x:=1]
1119
1120 // test_err unparenthesized_named_expr_index_py38
1121 // # parse_options: {"target-version": "3.8"}
1122 // lst[x:=1]
1123 if lower.is_unparenthesized_named_expr() {
1124 self.add_unsupported_syntax_error(
1125 UnsupportedSyntaxErrorKind::UnparenthesizedNamedExpr(
1126 UnparenthesizedNamedExprKind::SequenceIndex,
1127 ),
1128 lower.range(),
1129 );
1130 }
1131 return lower.expr;
1132 }
1133
1134 // Now we know we're in a slice.
1135 if !lower.is_parenthesized {
1136 match lower.expr {
1137 Expr::Starred(_) => {
1138 self.add_error(ParseErrorType::InvalidStarredExpressionUsage, &lower);
1139 }
1140 Expr::Named(_) => {
1141 self.add_error(ParseErrorType::UnparenthesizedNamedExpression, &lower);
1142 }
1143 _ => {}

Callers 1

Calls 14

node_startMethod · 0.80
at_exprMethod · 0.80
at_tsMethod · 0.80
expectMethod · 0.80
node_rangeMethod · 0.80
unionMethod · 0.45
rangeMethod · 0.45
add_errorMethod · 0.45

Tested by

no test coverage detected