Convert the given [`Pattern`] to an [`Expr`]. This is used to convert an invalid use of pattern to their equivalent expression to preserve the structure of the pattern. The conversion is done as follows: - `PatternMatchSingleton`: Boolean and None literals - `PatternMatchValue`: The value itself - `PatternMatchSequence`: List literal - `PatternMatchMapping`: Dictionary literal - `PatternMatchCla
(pattern: Pattern)
| 26 | /// with both the pattern and name present. This is because it cannot be converted to an expression |
| 27 | /// without dropping one of them as there's no way to represent `x as y` as a valid expression. |
| 28 | pub(super) fn pattern_to_expr(pattern: Pattern) -> Expr { |
| 29 | match pattern { |
| 30 | Pattern::MatchSingleton(ast::PatternMatchSingleton { |
| 31 | range, |
| 32 | node_index, |
| 33 | value, |
| 34 | }) => match value { |
| 35 | ast::Singleton::True => Expr::BooleanLiteral(ast::ExprBooleanLiteral { |
| 36 | value: true, |
| 37 | range, |
| 38 | node_index, |
| 39 | }), |
| 40 | ast::Singleton::False => Expr::BooleanLiteral(ast::ExprBooleanLiteral { |
| 41 | value: false, |
| 42 | range, |
| 43 | node_index, |
| 44 | }), |
| 45 | ast::Singleton::None => Expr::NoneLiteral(ast::ExprNoneLiteral { range, node_index }), |
| 46 | }, |
| 47 | Pattern::MatchValue(ast::PatternMatchValue { value, .. }) => *value, |
| 48 | // We don't know which kind of sequence this is: `case [1, 2]:` or `case (1, 2):`. |
| 49 | Pattern::MatchSequence(ast::PatternMatchSequence { |
| 50 | range, |
| 51 | node_index, |
| 52 | patterns, |
| 53 | }) => Expr::List(ast::ExprList { |
| 54 | elts: patterns.into_iter().map(pattern_to_expr).collect(), |
| 55 | ctx: ExprContext::Store, |
| 56 | range, |
| 57 | node_index, |
| 58 | }), |
| 59 | Pattern::MatchMapping(ast::PatternMatchMapping { |
| 60 | range, |
| 61 | node_index, |
| 62 | keys, |
| 63 | patterns, |
| 64 | rest, |
| 65 | }) => { |
| 66 | let mut items: Vec<ast::DictItem> = keys |
| 67 | .into_iter() |
| 68 | .zip(patterns) |
| 69 | .map(|(key, pattern)| ast::DictItem { |
| 70 | key: Some(key), |
| 71 | value: pattern_to_expr(pattern), |
| 72 | }) |
| 73 | .collect(); |
| 74 | if let Some(rest) = rest { |
| 75 | let value = Expr::Name(ast::ExprName { |
| 76 | range: rest.range, |
| 77 | node_index: node_index.clone(), |
| 78 | id: rest.id, |
| 79 | ctx: ExprContext::Store, |
| 80 | }); |
| 81 | items.push(ast::DictItem { key: None, value }); |
| 82 | } |
| 83 | items.shrink_to_fit(); |
| 84 | |
| 85 | Expr::Dict(ast::ExprDict { |
no test coverage detected