New Singleton enum for PatternMatchSingleton node (#8063)

## Summary

This PR adds a new `Singleton` enum for the `PatternMatchSingleton`
node.

Earlier the node was using the `Constant` enum but the value for this
pattern can only be either `None`, `True` or `False`. With the coming PR
to remove the `Constant`, this node required a new type to fill in.

This also has the benefit of narrowing the type down to only the
possible values for the node as evident by the removal of `unreachable`.

## Test Plan

Update the AST snapshots and run `cargo test`.
This commit is contained in:
Dhruv Manilawala 2023-10-30 11:18:53 +05:30 committed by GitHub
parent ee7d445ef5
commit 78bbf6d403
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
10 changed files with 70 additions and 28 deletions

View file

@ -185,8 +185,8 @@ pub struct PatternMatchValue<'a> {
} }
#[derive(Debug, PartialEq, Eq, Hash)] #[derive(Debug, PartialEq, Eq, Hash)]
pub struct PatternMatchSingleton<'a> { pub struct PatternMatchSingleton {
value: ComparableConstant<'a>, value: ComparableSingleton,
} }
#[derive(Debug, PartialEq, Eq, Hash)] #[derive(Debug, PartialEq, Eq, Hash)]
@ -227,7 +227,7 @@ pub struct PatternMatchOr<'a> {
#[derive(Debug, PartialEq, Eq, Hash)] #[derive(Debug, PartialEq, Eq, Hash)]
pub enum ComparablePattern<'a> { pub enum ComparablePattern<'a> {
MatchValue(PatternMatchValue<'a>), MatchValue(PatternMatchValue<'a>),
MatchSingleton(PatternMatchSingleton<'a>), MatchSingleton(PatternMatchSingleton),
MatchSequence(PatternMatchSequence<'a>), MatchSequence(PatternMatchSequence<'a>),
MatchMapping(PatternMatchMapping<'a>), MatchMapping(PatternMatchMapping<'a>),
MatchClass(PatternMatchClass<'a>), MatchClass(PatternMatchClass<'a>),
@ -326,6 +326,23 @@ impl<'a> From<&'a ast::Decorator> for ComparableDecorator<'a> {
} }
} }
#[derive(Debug, PartialEq, Eq, Hash)]
pub enum ComparableSingleton {
None,
True,
False,
}
impl From<&ast::Singleton> for ComparableSingleton {
fn from(singleton: &ast::Singleton) -> Self {
match singleton {
ast::Singleton::None => Self::None,
ast::Singleton::True => Self::True,
ast::Singleton::False => Self::False,
}
}
}
#[derive(Debug, PartialEq, Eq, Hash)] #[derive(Debug, PartialEq, Eq, Hash)]
pub enum ComparableConstant<'a> { pub enum ComparableConstant<'a> {
None, None,

View file

@ -3139,7 +3139,7 @@ impl AstNode for ast::PatternMatchSingleton {
V: PreorderVisitor<'a> + ?Sized, V: PreorderVisitor<'a> + ?Sized,
{ {
let ast::PatternMatchSingleton { value, range: _ } = self; let ast::PatternMatchSingleton { value, range: _ } = self;
visitor.visit_constant(value); visitor.visit_singleton(value);
} }
} }
impl AstNode for ast::PatternMatchSequence { impl AstNode for ast::PatternMatchSequence {

View file

@ -1923,7 +1923,7 @@ impl From<PatternMatchValue> for Pattern {
#[derive(Clone, Debug, PartialEq)] #[derive(Clone, Debug, PartialEq)]
pub struct PatternMatchSingleton { pub struct PatternMatchSingleton {
pub range: TextRange, pub range: TextRange,
pub value: Constant, pub value: Singleton,
} }
impl From<PatternMatchSingleton> for Pattern { impl From<PatternMatchSingleton> for Pattern {
@ -2578,6 +2578,23 @@ impl Ranged for Identifier {
} }
} }
#[derive(Clone, Debug, PartialEq)]
pub enum Singleton {
None,
True,
False,
}
impl From<bool> for Singleton {
fn from(value: bool) -> Self {
if value {
Singleton::True
} else {
Singleton::False
}
}
}
#[derive(Clone, Debug, PartialEq, is_macro::Is)] #[derive(Clone, Debug, PartialEq, is_macro::Is)]
pub enum Constant { pub enum Constant {
None, None,

View file

@ -1,8 +1,8 @@
use crate::{ use crate::{
Alias, Arguments, BoolOp, CmpOp, Comprehension, Constant, Decorator, ElifElseClause, Alias, Arguments, BoolOp, CmpOp, Comprehension, Constant, Decorator, ElifElseClause,
ExceptHandler, Expr, Keyword, MatchCase, Mod, Operator, Parameter, ParameterWithDefault, ExceptHandler, Expr, Keyword, MatchCase, Mod, Operator, Parameter, ParameterWithDefault,
Parameters, Pattern, PatternArguments, PatternKeyword, Stmt, TypeParam, TypeParams, UnaryOp, Parameters, Pattern, PatternArguments, PatternKeyword, Singleton, Stmt, TypeParam, TypeParams,
WithItem, UnaryOp, WithItem,
}; };
use crate::{AnyNodeRef, AstNode}; use crate::{AnyNodeRef, AstNode};
@ -44,6 +44,9 @@ pub trait PreorderVisitor<'a> {
#[inline] #[inline]
fn visit_constant(&mut self, _constant: &'a Constant) {} fn visit_constant(&mut self, _constant: &'a Constant) {}
#[inline]
fn visit_singleton(&mut self, _singleton: &'a Singleton) {}
#[inline] #[inline]
fn visit_bool_op(&mut self, bool_op: &'a BoolOp) { fn visit_bool_op(&mut self, bool_op: &'a BoolOp) {
walk_bool_op(self, bool_op); walk_bool_op(self, bool_op);

View file

@ -10,7 +10,7 @@ use ruff_python_ast::visitor::preorder::{
use ruff_python_ast::AnyNodeRef; use ruff_python_ast::AnyNodeRef;
use ruff_python_ast::{ use ruff_python_ast::{
Alias, BoolOp, CmpOp, Comprehension, Constant, ExceptHandler, Expr, Keyword, MatchCase, Mod, Alias, BoolOp, CmpOp, Comprehension, Constant, ExceptHandler, Expr, Keyword, MatchCase, Mod,
Operator, Parameter, Parameters, Pattern, Stmt, TypeParam, UnaryOp, WithItem, Operator, Parameter, Parameters, Pattern, Singleton, Stmt, TypeParam, UnaryOp, WithItem,
}; };
use ruff_python_parser::lexer::lex; use ruff_python_parser::lexer::lex;
use ruff_python_parser::{parse_tokens, Mode}; use ruff_python_parser::{parse_tokens, Mode};
@ -197,6 +197,10 @@ impl PreorderVisitor<'_> for RecordVisitor {
self.emit(&constant); self.emit(&constant);
} }
fn visit_singleton(&mut self, singleton: &Singleton) {
self.emit(&singleton);
}
fn visit_bool_op(&mut self, bool_op: &BoolOp) { fn visit_bool_op(&mut self, bool_op: &BoolOp) {
self.emit(&bool_op); self.emit(&bool_op);
} }

View file

@ -5,8 +5,8 @@ use std::ops::Deref;
use ruff_python_ast::{ use ruff_python_ast::{
self as ast, Alias, ArgOrKeyword, BoolOp, CmpOp, Comprehension, Constant, ConversionFlag, self as ast, Alias, ArgOrKeyword, BoolOp, CmpOp, Comprehension, Constant, ConversionFlag,
DebugText, ExceptHandler, Expr, Identifier, MatchCase, Operator, Parameter, Parameters, DebugText, ExceptHandler, Expr, Identifier, MatchCase, Operator, Parameter, Parameters,
Pattern, Stmt, Suite, TypeParam, TypeParamParamSpec, TypeParamTypeVar, TypeParamTypeVarTuple, Pattern, Singleton, Stmt, Suite, TypeParam, TypeParamParamSpec, TypeParamTypeVar,
WithItem, TypeParamTypeVarTuple, WithItem,
}; };
use ruff_python_ast::{ParameterWithDefault, TypeParams}; use ruff_python_ast::{ParameterWithDefault, TypeParams};
use ruff_python_literal::escape::{AsciiEscape, Escape, UnicodeEscape}; use ruff_python_literal::escape::{AsciiEscape, Escape, UnicodeEscape};
@ -672,7 +672,7 @@ impl<'a> Generator<'a> {
self.unparse_expr(value, precedence::MAX); self.unparse_expr(value, precedence::MAX);
} }
Pattern::MatchSingleton(ast::PatternMatchSingleton { value, range: _ }) => { Pattern::MatchSingleton(ast::PatternMatchSingleton { value, range: _ }) => {
self.unparse_constant(value); self.unparse_singleton(value);
} }
Pattern::MatchSequence(ast::PatternMatchSequence { patterns, range: _ }) => { Pattern::MatchSequence(ast::PatternMatchSequence { patterns, range: _ }) => {
self.p("["); self.p("[");
@ -1166,6 +1166,14 @@ impl<'a> Generator<'a> {
} }
} }
pub(crate) fn unparse_singleton(&mut self, singleton: &Singleton) {
match singleton {
Singleton::None => self.p("None"),
Singleton::True => self.p("True"),
Singleton::False => self.p("False"),
}
}
pub(crate) fn unparse_constant(&mut self, constant: &Constant) { pub(crate) fn unparse_constant(&mut self, constant: &Constant) {
assert_eq!(f64::MAX_10_EXP, 308); assert_eq!(f64::MAX_10_EXP, 308);
let inf_str = "1e309"; let inf_str = "1e309";

View file

@ -1,5 +1,5 @@
use ruff_python_ast::AnyNodeRef; use ruff_python_ast::AnyNodeRef;
use ruff_python_ast::{Constant, PatternMatchSingleton}; use ruff_python_ast::{PatternMatchSingleton, Singleton};
use crate::expression::parentheses::{NeedsParentheses, OptionalParentheses}; use crate::expression::parentheses::{NeedsParentheses, OptionalParentheses};
use crate::prelude::*; use crate::prelude::*;
@ -10,10 +10,9 @@ pub struct FormatPatternMatchSingleton;
impl FormatNodeRule<PatternMatchSingleton> for FormatPatternMatchSingleton { impl FormatNodeRule<PatternMatchSingleton> for FormatPatternMatchSingleton {
fn fmt_fields(&self, item: &PatternMatchSingleton, f: &mut PyFormatter) -> FormatResult<()> { fn fmt_fields(&self, item: &PatternMatchSingleton, f: &mut PyFormatter) -> FormatResult<()> {
match item.value { match item.value {
Constant::None => token("None").fmt(f), Singleton::None => token("None").fmt(f),
Constant::Bool(true) => token("True").fmt(f), Singleton::True => token("True").fmt(f),
Constant::Bool(false) => token("False").fmt(f), Singleton::False => token("False").fmt(f),
_ => unreachable!(),
} }
} }
} }

View file

@ -655,7 +655,7 @@ AddOpExpr: ast::ParenthesizedExpr = {
LiteralPattern: ast::Pattern = { LiteralPattern: ast::Pattern = {
<location:@L> "None" <end_location:@R> => ast::PatternMatchSingleton { <location:@L> "None" <end_location:@R> => ast::PatternMatchSingleton {
value: ast::Constant::None, value: ast::Singleton::None,
range: (location..end_location).into() range: (location..end_location).into()
}.into(), }.into(),
<location:@L> "True" <end_location:@R> => ast::PatternMatchSingleton { <location:@L> "True" <end_location:@R> => ast::PatternMatchSingleton {

View file

@ -1,5 +1,5 @@
// auto-generated: "lalrpop 0.20.0" // auto-generated: "lalrpop 0.20.0"
// sha3: 01c7c57ce067fcf07c9a5450511cc48a2dd08cf821a5ff3b0f649e87d3c67022 // sha3: 5c061590e81d6c0a6b543c9e8d8d30e7d7a44ed6b20f2ac72ca61a0e33d0e647
use ruff_text_size::{Ranged, TextLen, TextRange, TextSize}; use ruff_text_size::{Ranged, TextLen, TextRange, TextSize};
use ruff_python_ast::{self as ast, Int, IpyEscapeKind}; use ruff_python_ast::{self as ast, Int, IpyEscapeKind};
use crate::{ use crate::{
@ -34346,7 +34346,7 @@ fn __action115<
) -> ast::Pattern ) -> ast::Pattern
{ {
ast::PatternMatchSingleton { ast::PatternMatchSingleton {
value: ast::Constant::None, value: ast::Singleton::None,
range: (location..end_location).into() range: (location..end_location).into()
}.into() }.into()
} }

View file

@ -719,9 +719,7 @@ expression: parse_ast
MatchSingleton( MatchSingleton(
PatternMatchSingleton { PatternMatchSingleton {
range: 621..625, range: 621..625,
value: Bool( value: True,
true,
),
}, },
), ),
], ],
@ -2402,9 +2400,7 @@ expression: parse_ast
pattern: MatchSingleton( pattern: MatchSingleton(
PatternMatchSingleton { PatternMatchSingleton {
range: 1947..1952, range: 1947..1952,
value: Bool( value: False,
false,
),
}, },
), ),
guard: None, guard: None,
@ -3051,9 +3047,7 @@ expression: parse_ast
MatchSingleton( MatchSingleton(
PatternMatchSingleton { PatternMatchSingleton {
range: 2405..2410, range: 2405..2410,
value: Bool( value: False,
false,
),
}, },
), ),
], ],