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

Method parse_slice

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

Parses a slice expression. See:

(&mut self)

Source from the content-addressed store, hash-verified

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

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