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

Method parse_match_pattern_mapping

crates/ruff_python_parser/src/parser/pattern.rs:184–266  ·  view source on GitHub ↗

Parses a mapping pattern. # Panics If the parser isn't positioned at a `{` token. See:

(&mut self)

Source from the content-addressed store, hash-verified

182 ///
183 /// See: <https://docs.python.org/3/reference/compound_stmts.html#mapping-patterns>
184 fn parse_match_pattern_mapping(&mut self) -> ast::PatternMatchMapping {
185 let start = self.node_start();
186 self.bump(TokenKind::Lbrace);
187
188 let mut keys = PatternKeys::new();
189 let mut patterns = Patterns::new();
190 let mut rest = None;
191
192 self.parse_comma_separated_list(RecoveryContextKind::MatchPatternMapping, |parser| {
193 let mapping_item_start = parser.node_start();
194
195 if parser.eat(TokenKind::DoubleStar) {
196 let identifier = parser.parse_match_pattern_target();
197 if rest.is_some() {
198 parser.add_error(
199 ParseErrorType::OtherError(
200 "Only one double star pattern is allowed".to_string(),
201 ),
202 parser.node_range(mapping_item_start),
203 );
204 }
205 // TODO(dhruvmanila): It's not possible to retain multiple double starred
206 // patterns because of the way the mapping node is represented in the grammar.
207 // The last value will always win. Update the AST representation.
208 // See: https://github.com/astral-sh/ruff/pull/10477#discussion_r1535143536
209 rest = Some(identifier);
210 } else {
211 let key = match parser.parse_match_pattern_lhs(AllowStarPattern::No) {
212 Pattern::MatchValue(ast::PatternMatchValue { value, .. }) => *value,
213 Pattern::MatchSingleton(ast::PatternMatchSingleton {
214 value,
215 range,
216 node_index,
217 }) => match value {
218 Singleton::None => {
219 Expr::NoneLiteral(ast::ExprNoneLiteral { range, node_index })
220 }
221 Singleton::True => Expr::BooleanLiteral(ast::ExprBooleanLiteral {
222 value: true,
223 range,
224 node_index,
225 }),
226 Singleton::False => Expr::BooleanLiteral(ast::ExprBooleanLiteral {
227 value: false,
228 range,
229 node_index,
230 }),
231 },
232 pattern => {
233 parser.add_error(
234 ParseErrorType::OtherError("Invalid mapping pattern key".to_string()),
235 &pattern,
236 );
237 recovery::pattern_to_expr(pattern)
238 }
239 };
240 keys.push(key);
241

Callers 1

Calls 13

pattern_to_exprFunction · 0.85
node_startMethod · 0.80
node_rangeMethod · 0.80
expectMethod · 0.80
parse_match_patternMethod · 0.80
bumpMethod · 0.45
eatMethod · 0.45
add_errorMethod · 0.45
to_stringMethod · 0.45

Tested by

no test coverage detected