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

Method parse_slice

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

Parses a slice expression. See:

(&mut self)

Source from the content-addressed store, hash-verified

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

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