id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
4,880
import re import typing from tokenize import ( Floatnumber as FLOATNUMBER_RE, Imagnumber as IMAGNUMBER_RE, Intnumber as INTNUMBER_RE, ) from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Arg, Asynchronous, Attribute, Await, BinaryOperation, BooleanOperation, Call, Comparison, ComparisonTarget, CompFor, CompIf, ConcatenatedString, Dict, DictComp, DictElement, Element, Ellipsis, Float, FormattedString, FormattedStringExpression, FormattedStringText, From, GeneratorExp, IfExp, Imaginary, Index, Integer, Lambda, LeftCurlyBrace, LeftParen, LeftSquareBracket, List, ListComp, Name, NamedExpr, Param, Parameters, RightCurlyBrace, RightParen, RightSquareBracket, Set, SetComp, Slice, StarredDictElement, StarredElement, Subscript, SubscriptElement, Tuple, UnaryOperation, Yield, ) from libcst._nodes.op import ( Add, And, AssignEqual, BaseBinaryOp, BaseBooleanOp, BaseCompOp, BitAnd, BitInvert, BitOr, BitXor, Colon, Comma, Divide, Dot, Equal, FloorDivide, GreaterThan, GreaterThanEqual, In, Is, IsNot, LeftShift, LessThan, LessThanEqual, MatrixMultiply, Minus, Modulo, Multiply, Not, NotEqual, NotIn, Or, Plus, Power, RightShift, Subtract, ) from libcst._nodes.whitespace import SimpleWhitespace from libcst._parser.custom_itertools import grouper from libcst._parser.production_decorator import with_production from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import ( ArglistPartial, AttributePartial, CallPartial, FormattedStringConversionPartial, FormattedStringFormatSpecPartial, SlicePartial, SubscriptPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace class StarredElement(BaseElement, BaseExpression, _BaseParenthesizedNode): """ A starred ``*value`` element that expands to represent multiple values in a literal :class:`List`, :class:`Tuple`, or :class:`Set`. If you're using a literal :class:`Dict`, see :class:`StarredDictElement` instead. If this node owns parenthesis, those parenthesis wrap the leading asterisk, but not the trailing comma. For example:: StarredElement( cst.Name("el"), comma=cst.Comma(), lpar=[cst.LeftParen()], rpar=[cst.RightParen()], ) will generate:: (*el), """ value: BaseExpression #: A trailing comma. By default, we'll only insert a comma if one is required. comma: Union[Comma, MaybeSentinel] = MaybeSentinel.DEFAULT #: Parenthesis at the beginning of the node, before the leading asterisk. lpar: Sequence[LeftParen] = () #: Parentheses after the value, but before a comma (if there is one). rpar: Sequence[RightParen] = () #: Whitespace between the leading asterisk and the value expression. whitespace_before_value: BaseParenthesizableWhitespace = SimpleWhitespace.field("") def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "StarredElement": return StarredElement( lpar=visit_sequence(self, "lpar", self.lpar, visitor), whitespace_before_value=visit_required( self, "whitespace_before_value", self.whitespace_before_value, visitor ), value=visit_required(self, "value", self.value, visitor), rpar=visit_sequence(self, "rpar", self.rpar, visitor), comma=visit_sentinel(self, "comma", self.comma, visitor), ) def _codegen_impl( self, state: CodegenState, default_comma: bool = False, default_comma_whitespace: bool = False, ) -> None: with self._parenthesize(state): state.add_token("*") self.whitespace_before_value._codegen(state) self.value._codegen(state) self._codegen_comma(state, default_comma, default_comma_whitespace) ParserConfig = config_mod.ParserConfig class WithLeadingWhitespace(Generic[_T]): value: _T whitespace_before: WhitespaceState parse_parenthesizable_whitespace = mod.parse_parenthesizable_whitespace def convert_star_expr( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: star, expr = children return WithLeadingWhitespace( StarredElement( expr.value, whitespace_before_value=parse_parenthesizable_whitespace( config, expr.whitespace_before ), # atom is responsible for parenthesis and trailing_whitespace if they exist # testlist_comp, exprlist, dictorsetmaker, etc are responsible for the comma # if it exists. ), whitespace_before=star.whitespace_before, )
null
4,881
import re import typing from tokenize import ( Floatnumber as FLOATNUMBER_RE, Imagnumber as IMAGNUMBER_RE, Intnumber as INTNUMBER_RE, ) from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Arg, Asynchronous, Attribute, Await, BinaryOperation, BooleanOperation, Call, Comparison, ComparisonTarget, CompFor, CompIf, ConcatenatedString, Dict, DictComp, DictElement, Element, Ellipsis, Float, FormattedString, FormattedStringExpression, FormattedStringText, From, GeneratorExp, IfExp, Imaginary, Index, Integer, Lambda, LeftCurlyBrace, LeftParen, LeftSquareBracket, List, ListComp, Name, NamedExpr, Param, Parameters, RightCurlyBrace, RightParen, RightSquareBracket, Set, SetComp, Slice, StarredDictElement, StarredElement, Subscript, SubscriptElement, Tuple, UnaryOperation, Yield, ) from libcst._nodes.op import ( Add, And, AssignEqual, BaseBinaryOp, BaseBooleanOp, BaseCompOp, BitAnd, BitInvert, BitOr, BitXor, Colon, Comma, Divide, Dot, Equal, FloorDivide, GreaterThan, GreaterThanEqual, In, Is, IsNot, LeftShift, LessThan, LessThanEqual, MatrixMultiply, Minus, Modulo, Multiply, Not, NotEqual, NotIn, Or, Plus, Power, RightShift, Subtract, ) from libcst._nodes.whitespace import SimpleWhitespace from libcst._parser.custom_itertools import grouper from libcst._parser.production_decorator import with_production from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import ( ArglistPartial, AttributePartial, CallPartial, FormattedStringConversionPartial, FormattedStringFormatSpecPartial, SlicePartial, SubscriptPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace BINOP_TOKEN_LUT: typing.Dict[str, typing.Type[BaseBinaryOp]] = { "*": Multiply, "@": MatrixMultiply, "/": Divide, "%": Modulo, "//": FloorDivide, "+": Add, "-": Subtract, "<<": LeftShift, ">>": RightShift, "&": BitAnd, "^": BitXor, "|": BitOr, } class BinaryOperation(BaseExpression): def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "BinaryOperation": def _safe_to_use_with_word_operator(self, position: ExpressionPosition) -> bool: def _codegen_impl(self, state: CodegenState) -> None: def grouper(iterable: Iterable[_T], n: int, fillvalue: _T = None) -> Iterator[_T]: ParserConfig = config_mod.ParserConfig class WithLeadingWhitespace(Generic[_T]): parse_parenthesizable_whitespace = mod.parse_parenthesizable_whitespace def convert_binop( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: leftexpr, *rightexprs = children if len(rightexprs) == 0: return leftexpr whitespace_before = leftexpr.whitespace_before leftexpr = leftexpr.value # Convert all of the operations that have no precedence in a loop for op, rightexpr in grouper(rightexprs, 2): if op.string not in BINOP_TOKEN_LUT: raise Exception(f"Unexpected token '{op.string}'!") leftexpr = BinaryOperation( left=leftexpr, # pyre-ignore Pyre thinks that the type of the LUT is CSTNode. operator=BINOP_TOKEN_LUT[op.string]( whitespace_before=parse_parenthesizable_whitespace( config, op.whitespace_before ), whitespace_after=parse_parenthesizable_whitespace( config, op.whitespace_after ), ), right=rightexpr.value, ) return WithLeadingWhitespace(leftexpr, whitespace_before)
null
4,882
import re import typing from tokenize import ( Floatnumber as FLOATNUMBER_RE, Imagnumber as IMAGNUMBER_RE, Intnumber as INTNUMBER_RE, ) from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Arg, Asynchronous, Attribute, Await, BinaryOperation, BooleanOperation, Call, Comparison, ComparisonTarget, CompFor, CompIf, ConcatenatedString, Dict, DictComp, DictElement, Element, Ellipsis, Float, FormattedString, FormattedStringExpression, FormattedStringText, From, GeneratorExp, IfExp, Imaginary, Index, Integer, Lambda, LeftCurlyBrace, LeftParen, LeftSquareBracket, List, ListComp, Name, NamedExpr, Param, Parameters, RightCurlyBrace, RightParen, RightSquareBracket, Set, SetComp, Slice, StarredDictElement, StarredElement, Subscript, SubscriptElement, Tuple, UnaryOperation, Yield, ) from libcst._nodes.op import ( Add, And, AssignEqual, BaseBinaryOp, BaseBooleanOp, BaseCompOp, BitAnd, BitInvert, BitOr, BitXor, Colon, Comma, Divide, Dot, Equal, FloorDivide, GreaterThan, GreaterThanEqual, In, Is, IsNot, LeftShift, LessThan, LessThanEqual, MatrixMultiply, Minus, Modulo, Multiply, Not, NotEqual, NotIn, Or, Plus, Power, RightShift, Subtract, ) from libcst._nodes.whitespace import SimpleWhitespace from libcst._parser.custom_itertools import grouper from libcst._parser.production_decorator import with_production from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import ( ArglistPartial, AttributePartial, CallPartial, FormattedStringConversionPartial, FormattedStringFormatSpecPartial, SlicePartial, SubscriptPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace class UnaryOperation(BaseExpression): """ Any generic unary expression, such as ``not x`` or ``-x``. :class:`UnaryOperation` nodes apply a :class:`BaseUnaryOp` to an expression. """ #: The unary operator that applies some operation (e.g. negation) to the #: ``expression``. operator: BaseUnaryOp #: The expression that should be transformed (e.g. negated) by the operator to #: create a new value. expression: BaseExpression lpar: Sequence[LeftParen] = () #: Sequence of parenthesis for precedence dictation. rpar: Sequence[RightParen] = () def _validate(self) -> None: # Perform any validation on base type super(UnaryOperation, self)._validate() if ( isinstance(self.operator, Not) and self.operator.whitespace_after.empty and not self.expression._safe_to_use_with_word_operator( ExpressionPosition.RIGHT ) ): raise CSTValidationError("Must have at least one space after not operator.") def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "UnaryOperation": return UnaryOperation( lpar=visit_sequence(self, "lpar", self.lpar, visitor), operator=visit_required(self, "operator", self.operator, visitor), expression=visit_required(self, "expression", self.expression, visitor), rpar=visit_sequence(self, "rpar", self.rpar, visitor), ) def _safe_to_use_with_word_operator(self, position: ExpressionPosition) -> bool: """ As long as we aren't comprised of the Not unary operator, we are safe to use without space. """ if super(UnaryOperation, self)._safe_to_use_with_word_operator(position): return True if position == ExpressionPosition.RIGHT: return not isinstance(self.operator, Not) if position == ExpressionPosition.LEFT: return self.expression._safe_to_use_with_word_operator( ExpressionPosition.LEFT ) return False def _codegen_impl(self, state: CodegenState) -> None: with self._parenthesize(state): self.operator._codegen(state) self.expression._codegen(state) class Plus(BaseUnaryOp): """ A unary operator that can be used in a :class:`UnaryOperation` expression. """ #: Any space that appears directly after this operator. whitespace_after: BaseParenthesizableWhitespace = SimpleWhitespace.field("") def _get_token(self) -> str: return "+" class Minus(BaseUnaryOp): """ A unary operator that can be used in a :class:`UnaryOperation` expression. """ #: Any space that appears directly after this operator. whitespace_after: BaseParenthesizableWhitespace = SimpleWhitespace.field("") def _get_token(self) -> str: return "-" class BitInvert(BaseUnaryOp): """ A unary operator that can be used in a :class:`UnaryOperation` expression. """ #: Any space that appears directly after this operator. whitespace_after: BaseParenthesizableWhitespace = SimpleWhitespace.field("") def _get_token(self) -> str: return "~" ParserConfig = config_mod.ParserConfig class WithLeadingWhitespace(Generic[_T]): value: _T whitespace_before: WhitespaceState parse_parenthesizable_whitespace = mod.parse_parenthesizable_whitespace def convert_factor( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: if len(children) == 1: (child,) = children return child op, factor = children # First, tokenize the unary operator if op.string == "+": opnode = Plus( whitespace_after=parse_parenthesizable_whitespace( config, op.whitespace_after ) ) elif op.string == "-": opnode = Minus( whitespace_after=parse_parenthesizable_whitespace( config, op.whitespace_after ) ) elif op.string == "~": opnode = BitInvert( whitespace_after=parse_parenthesizable_whitespace( config, op.whitespace_after ) ) else: raise Exception(f"Unexpected token '{op.string}'!") return WithLeadingWhitespace( UnaryOperation(operator=opnode, expression=factor.value), op.whitespace_before )
null
4,883
import re import typing from tokenize import ( Floatnumber as FLOATNUMBER_RE, Imagnumber as IMAGNUMBER_RE, Intnumber as INTNUMBER_RE, ) from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Arg, Asynchronous, Attribute, Await, BinaryOperation, BooleanOperation, Call, Comparison, ComparisonTarget, CompFor, CompIf, ConcatenatedString, Dict, DictComp, DictElement, Element, Ellipsis, Float, FormattedString, FormattedStringExpression, FormattedStringText, From, GeneratorExp, IfExp, Imaginary, Index, Integer, Lambda, LeftCurlyBrace, LeftParen, LeftSquareBracket, List, ListComp, Name, NamedExpr, Param, Parameters, RightCurlyBrace, RightParen, RightSquareBracket, Set, SetComp, Slice, StarredDictElement, StarredElement, Subscript, SubscriptElement, Tuple, UnaryOperation, Yield, ) from libcst._nodes.op import ( Add, And, AssignEqual, BaseBinaryOp, BaseBooleanOp, BaseCompOp, BitAnd, BitInvert, BitOr, BitXor, Colon, Comma, Divide, Dot, Equal, FloorDivide, GreaterThan, GreaterThanEqual, In, Is, IsNot, LeftShift, LessThan, LessThanEqual, MatrixMultiply, Minus, Modulo, Multiply, Not, NotEqual, NotIn, Or, Plus, Power, RightShift, Subtract, ) from libcst._nodes.whitespace import SimpleWhitespace from libcst._parser.custom_itertools import grouper from libcst._parser.production_decorator import with_production from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import ( ArglistPartial, AttributePartial, CallPartial, FormattedStringConversionPartial, FormattedStringFormatSpecPartial, SlicePartial, SubscriptPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace class BinaryOperation(BaseExpression): """ An operation that combines two expression such as ``x << y`` or ``y + z``. :class:`BinaryOperation` nodes apply a :class:`BaseBinaryOp` to an expression. Binary operations do not include operations performed with :class:`BaseBooleanOp` nodes, such as ``and`` or ``or``. Instead, those operations are provided by :class:`BooleanOperation`. It also does not include support for comparision operators performed with :class:`BaseCompOp`, such as ``<``, ``>=``, ``==``, ``is``, or ``in``. Instead, those operations are provided by :class:`Comparison`. """ #: The left hand side of the operation. left: BaseExpression #: The actual operator such as ``<<`` or ``+`` that combines the ``left`` and #: ``right`` expressions. operator: BaseBinaryOp #: The right hand side of the operation. right: BaseExpression lpar: Sequence[LeftParen] = () #: Sequence of parenthesis for precedence dictation. rpar: Sequence[RightParen] = () def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "BinaryOperation": return BinaryOperation( lpar=visit_sequence(self, "lpar", self.lpar, visitor), left=visit_required(self, "left", self.left, visitor), operator=visit_required(self, "operator", self.operator, visitor), right=visit_required(self, "right", self.right, visitor), rpar=visit_sequence(self, "rpar", self.rpar, visitor), ) def _safe_to_use_with_word_operator(self, position: ExpressionPosition) -> bool: if super(BinaryOperation, self)._safe_to_use_with_word_operator(position): return True return self._check_left_right_word_concatenation_safety( position, self.left, self.right ) def _codegen_impl(self, state: CodegenState) -> None: with self._parenthesize(state): self.left._codegen(state) self.operator._codegen(state) self.right._codegen(state) class Power(BaseBinaryOp, _BaseOneTokenOp): """ A binary operator that can be used in a :class:`BinaryOperation` expression. """ #: Any space that appears directly before this operator. whitespace_before: BaseParenthesizableWhitespace = SimpleWhitespace.field(" ") #: Any space that appears directly after this operator. whitespace_after: BaseParenthesizableWhitespace = SimpleWhitespace.field(" ") def _get_token(self) -> str: return "**" ParserConfig = config_mod.ParserConfig class WithLeadingWhitespace(Generic[_T]): value: _T whitespace_before: WhitespaceState parse_parenthesizable_whitespace = mod.parse_parenthesizable_whitespace def convert_power( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: if len(children) == 1: (child,) = children return child left, power, right = children return WithLeadingWhitespace( BinaryOperation( left=left.value, operator=Power( whitespace_before=parse_parenthesizable_whitespace( config, power.whitespace_before ), whitespace_after=parse_parenthesizable_whitespace( config, power.whitespace_after ), ), right=right.value, ), left.whitespace_before, )
null
4,884
import re import typing from tokenize import ( Floatnumber as FLOATNUMBER_RE, Imagnumber as IMAGNUMBER_RE, Intnumber as INTNUMBER_RE, ) from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Arg, Asynchronous, Attribute, Await, BinaryOperation, BooleanOperation, Call, Comparison, ComparisonTarget, CompFor, CompIf, ConcatenatedString, Dict, DictComp, DictElement, Element, Ellipsis, Float, FormattedString, FormattedStringExpression, FormattedStringText, From, GeneratorExp, IfExp, Imaginary, Index, Integer, Lambda, LeftCurlyBrace, LeftParen, LeftSquareBracket, List, ListComp, Name, NamedExpr, Param, Parameters, RightCurlyBrace, RightParen, RightSquareBracket, Set, SetComp, Slice, StarredDictElement, StarredElement, Subscript, SubscriptElement, Tuple, UnaryOperation, Yield, ) from libcst._nodes.op import ( Add, And, AssignEqual, BaseBinaryOp, BaseBooleanOp, BaseCompOp, BitAnd, BitInvert, BitOr, BitXor, Colon, Comma, Divide, Dot, Equal, FloorDivide, GreaterThan, GreaterThanEqual, In, Is, IsNot, LeftShift, LessThan, LessThanEqual, MatrixMultiply, Minus, Modulo, Multiply, Not, NotEqual, NotIn, Or, Plus, Power, RightShift, Subtract, ) from libcst._nodes.whitespace import SimpleWhitespace from libcst._parser.custom_itertools import grouper from libcst._parser.production_decorator import with_production from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import ( ArglistPartial, AttributePartial, CallPartial, FormattedStringConversionPartial, FormattedStringFormatSpecPartial, SlicePartial, SubscriptPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace ParserConfig = config_mod.ParserConfig def convert_atom_expr( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: (child,) = children return child
null
4,885
import re import typing from tokenize import ( Floatnumber as FLOATNUMBER_RE, Imagnumber as IMAGNUMBER_RE, Intnumber as INTNUMBER_RE, ) from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Arg, Asynchronous, Attribute, Await, BinaryOperation, BooleanOperation, Call, Comparison, ComparisonTarget, CompFor, CompIf, ConcatenatedString, Dict, DictComp, DictElement, Element, Ellipsis, Float, FormattedString, FormattedStringExpression, FormattedStringText, From, GeneratorExp, IfExp, Imaginary, Index, Integer, Lambda, LeftCurlyBrace, LeftParen, LeftSquareBracket, List, ListComp, Name, NamedExpr, Param, Parameters, RightCurlyBrace, RightParen, RightSquareBracket, Set, SetComp, Slice, StarredDictElement, StarredElement, Subscript, SubscriptElement, Tuple, UnaryOperation, Yield, ) from libcst._nodes.op import ( Add, And, AssignEqual, BaseBinaryOp, BaseBooleanOp, BaseCompOp, BitAnd, BitInvert, BitOr, BitXor, Colon, Comma, Divide, Dot, Equal, FloorDivide, GreaterThan, GreaterThanEqual, In, Is, IsNot, LeftShift, LessThan, LessThanEqual, MatrixMultiply, Minus, Modulo, Multiply, Not, NotEqual, NotIn, Or, Plus, Power, RightShift, Subtract, ) from libcst._nodes.whitespace import SimpleWhitespace from libcst._parser.custom_itertools import grouper from libcst._parser.production_decorator import with_production from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import ( ArglistPartial, AttributePartial, CallPartial, FormattedStringConversionPartial, FormattedStringFormatSpecPartial, SlicePartial, SubscriptPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace class Await(BaseExpression): """ An await expression. Await expressions are only valid inside the body of an asynchronous :class:`FunctionDef` or (as of Python 3.7) inside of an asynchronous :class:`GeneratorExp` nodes. """ #: The actual expression we need to wait for. expression: BaseExpression lpar: Sequence[LeftParen] = () #: Sequence of parenthesis for precedence dictation. rpar: Sequence[RightParen] = () #: Whitespace that appears after the ``async`` keyword, but before the inner #: ``expression``. whitespace_after_await: BaseParenthesizableWhitespace = SimpleWhitespace.field(" ") def _validate(self) -> None: # Validate any super-class stuff, whatever it may be. super(Await, self)._validate() # Make sure we don't run identifiers together. if ( self.whitespace_after_await.empty and not self.expression._safe_to_use_with_word_operator( ExpressionPosition.RIGHT ) ): raise CSTValidationError("Must have at least one space after await") def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Await": return Await( lpar=visit_sequence(self, "lpar", self.lpar, visitor), whitespace_after_await=visit_required( self, "whitespace_after_await", self.whitespace_after_await, visitor ), expression=visit_required(self, "expression", self.expression, visitor), rpar=visit_sequence(self, "rpar", self.rpar, visitor), ) def _codegen_impl(self, state: CodegenState) -> None: with self._parenthesize(state): state.add_token("await") self.whitespace_after_await._codegen(state) self.expression._codegen(state) ParserConfig = config_mod.ParserConfig class WithLeadingWhitespace(Generic[_T]): value: _T whitespace_before: WhitespaceState parse_parenthesizable_whitespace = mod.parse_parenthesizable_whitespace def convert_atom_expr_await( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: keyword, expr = children return WithLeadingWhitespace( Await( whitespace_after_await=parse_parenthesizable_whitespace( config, keyword.whitespace_after ), expression=expr.value, ), keyword.whitespace_before, )
null
4,886
import re import typing from tokenize import ( Floatnumber as FLOATNUMBER_RE, Imagnumber as IMAGNUMBER_RE, Intnumber as INTNUMBER_RE, ) from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Arg, Asynchronous, Attribute, Await, BinaryOperation, BooleanOperation, Call, Comparison, ComparisonTarget, CompFor, CompIf, ConcatenatedString, Dict, DictComp, DictElement, Element, Ellipsis, Float, FormattedString, FormattedStringExpression, FormattedStringText, From, GeneratorExp, IfExp, Imaginary, Index, Integer, Lambda, LeftCurlyBrace, LeftParen, LeftSquareBracket, List, ListComp, Name, NamedExpr, Param, Parameters, RightCurlyBrace, RightParen, RightSquareBracket, Set, SetComp, Slice, StarredDictElement, StarredElement, Subscript, SubscriptElement, Tuple, UnaryOperation, Yield, ) from libcst._nodes.op import ( Add, And, AssignEqual, BaseBinaryOp, BaseBooleanOp, BaseCompOp, BitAnd, BitInvert, BitOr, BitXor, Colon, Comma, Divide, Dot, Equal, FloorDivide, GreaterThan, GreaterThanEqual, In, Is, IsNot, LeftShift, LessThan, LessThanEqual, MatrixMultiply, Minus, Modulo, Multiply, Not, NotEqual, NotIn, Or, Plus, Power, RightShift, Subtract, ) from libcst._nodes.whitespace import SimpleWhitespace from libcst._parser.custom_itertools import grouper from libcst._parser.production_decorator import with_production from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import ( ArglistPartial, AttributePartial, CallPartial, FormattedStringConversionPartial, FormattedStringFormatSpecPartial, SlicePartial, SubscriptPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace class MaybeSentinel(Enum): def __repr__(self) -> str: class Attribute(BaseAssignTargetExpression, BaseDelTargetExpression): def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Attribute": def _safe_to_use_with_word_operator(self, position: ExpressionPosition) -> bool: def _codegen_impl(self, state: CodegenState) -> None: class Subscript(BaseAssignTargetExpression, BaseDelTargetExpression): def _validate(self) -> None: def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Subscript": def _safe_to_use_with_word_operator(self, position: ExpressionPosition) -> bool: def _codegen_impl(self, state: CodegenState) -> None: class Call(_BaseExpressionWithArgs): def _safe_to_use_with_word_operator(self, position: ExpressionPosition) -> bool: def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Call": def _codegen_impl(self, state: CodegenState) -> None: ParserConfig = config_mod.ParserConfig class WithLeadingWhitespace(Generic[_T]): class AttributePartial: class CallPartial: class SubscriptPartial: parse_parenthesizable_whitespace = mod.parse_parenthesizable_whitespace def convert_atom_expr_trailer( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: atom, *trailers = children whitespace_before = atom.whitespace_before atom = atom.value # Need to walk through all trailers from left to right and construct # a series of nodes based on each partial type. We can't do this with # left recursion due to limits in the parser. for trailer in trailers: if isinstance(trailer, SubscriptPartial): atom = Subscript( value=atom, whitespace_after_value=parse_parenthesizable_whitespace( config, trailer.whitespace_before ), lbracket=trailer.lbracket, # pyre-fixme[6]: Expected `Sequence[SubscriptElement]` for 4th param # but got `Union[typing.Sequence[SubscriptElement], Index, Slice]`. slice=trailer.slice, rbracket=trailer.rbracket, ) elif isinstance(trailer, AttributePartial): atom = Attribute(value=atom, dot=trailer.dot, attr=trailer.attr) elif isinstance(trailer, CallPartial): # If the trailing argument doesn't have a comma, then it owns the # trailing whitespace before the rpar. Otherwise, the comma owns # it. if ( len(trailer.args) > 0 and trailer.args[-1].comma == MaybeSentinel.DEFAULT ): args = ( *trailer.args[:-1], trailer.args[-1].with_changes( whitespace_after_arg=trailer.rpar.whitespace_before ), ) else: args = trailer.args atom = Call( func=atom, whitespace_after_func=parse_parenthesizable_whitespace( config, trailer.lpar.whitespace_before ), whitespace_before_args=trailer.lpar.value.whitespace_after, # pyre-fixme[6]: Expected `Sequence[Arg]` for 4th param but got # `Tuple[object, ...]`. args=tuple(args), ) else: # This is an invalid trailer, so lets give up raise Exception("Logic error!") return WithLeadingWhitespace(atom, whitespace_before)
null
4,887
import re import typing from tokenize import ( Floatnumber as FLOATNUMBER_RE, Imagnumber as IMAGNUMBER_RE, Intnumber as INTNUMBER_RE, ) from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Arg, Asynchronous, Attribute, Await, BinaryOperation, BooleanOperation, Call, Comparison, ComparisonTarget, CompFor, CompIf, ConcatenatedString, Dict, DictComp, DictElement, Element, Ellipsis, Float, FormattedString, FormattedStringExpression, FormattedStringText, From, GeneratorExp, IfExp, Imaginary, Index, Integer, Lambda, LeftCurlyBrace, LeftParen, LeftSquareBracket, List, ListComp, Name, NamedExpr, Param, Parameters, RightCurlyBrace, RightParen, RightSquareBracket, Set, SetComp, Slice, StarredDictElement, StarredElement, Subscript, SubscriptElement, Tuple, UnaryOperation, Yield, ) from libcst._nodes.op import ( Add, And, AssignEqual, BaseBinaryOp, BaseBooleanOp, BaseCompOp, BitAnd, BitInvert, BitOr, BitXor, Colon, Comma, Divide, Dot, Equal, FloorDivide, GreaterThan, GreaterThanEqual, In, Is, IsNot, LeftShift, LessThan, LessThanEqual, MatrixMultiply, Minus, Modulo, Multiply, Not, NotEqual, NotIn, Or, Plus, Power, RightShift, Subtract, ) from libcst._nodes.whitespace import SimpleWhitespace from libcst._parser.custom_itertools import grouper from libcst._parser.production_decorator import with_production from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import ( ArglistPartial, AttributePartial, CallPartial, FormattedStringConversionPartial, FormattedStringFormatSpecPartial, SlicePartial, SubscriptPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace ParserConfig = config_mod.ParserConfig def convert_trailer( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: (child,) = children return child
null
4,888
import re import typing from tokenize import ( Floatnumber as FLOATNUMBER_RE, Imagnumber as IMAGNUMBER_RE, Intnumber as INTNUMBER_RE, ) from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Arg, Asynchronous, Attribute, Await, BinaryOperation, BooleanOperation, Call, Comparison, ComparisonTarget, CompFor, CompIf, ConcatenatedString, Dict, DictComp, DictElement, Element, Ellipsis, Float, FormattedString, FormattedStringExpression, FormattedStringText, From, GeneratorExp, IfExp, Imaginary, Index, Integer, Lambda, LeftCurlyBrace, LeftParen, LeftSquareBracket, List, ListComp, Name, NamedExpr, Param, Parameters, RightCurlyBrace, RightParen, RightSquareBracket, Set, SetComp, Slice, StarredDictElement, StarredElement, Subscript, SubscriptElement, Tuple, UnaryOperation, Yield, ) from libcst._nodes.op import ( Add, And, AssignEqual, BaseBinaryOp, BaseBooleanOp, BaseCompOp, BitAnd, BitInvert, BitOr, BitXor, Colon, Comma, Divide, Dot, Equal, FloorDivide, GreaterThan, GreaterThanEqual, In, Is, IsNot, LeftShift, LessThan, LessThanEqual, MatrixMultiply, Minus, Modulo, Multiply, Not, NotEqual, NotIn, Or, Plus, Power, RightShift, Subtract, ) from libcst._nodes.whitespace import SimpleWhitespace from libcst._parser.custom_itertools import grouper from libcst._parser.production_decorator import with_production from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import ( ArglistPartial, AttributePartial, CallPartial, FormattedStringConversionPartial, FormattedStringFormatSpecPartial, SlicePartial, SubscriptPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace class LeftParen(CSTNode): """ Used by various nodes to denote a parenthesized section. This doesn't own the whitespace to the left of it since this is owned by the parent node. """ #: Any space that appears directly after this left parenthesis. whitespace_after: BaseParenthesizableWhitespace = SimpleWhitespace.field("") def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "LeftParen": return LeftParen( whitespace_after=visit_required( self, "whitespace_after", self.whitespace_after, visitor ) ) def _codegen_impl(self, state: CodegenState) -> None: state.add_token("(") self.whitespace_after._codegen(state) class RightParen(CSTNode): """ Used by various nodes to denote a parenthesized section. This doesn't own the whitespace to the right of it since this is owned by the parent node. """ #: Any space that appears directly after this left parenthesis. whitespace_before: BaseParenthesizableWhitespace = SimpleWhitespace.field("") def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "RightParen": return RightParen( whitespace_before=visit_required( self, "whitespace_before", self.whitespace_before, visitor ) ) def _codegen_impl(self, state: CodegenState) -> None: self.whitespace_before._codegen(state) state.add_token(")") ParserConfig = config_mod.ParserConfig class WithLeadingWhitespace(Generic[_T]): value: _T whitespace_before: WhitespaceState class CallPartial: lpar: WithLeadingWhitespace[LeftParen] args: Sequence[Arg] rpar: RightParen parse_parenthesizable_whitespace = mod.parse_parenthesizable_whitespace def convert_trailer_arglist( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: lpar, *arglist, rpar = children return CallPartial( lpar=WithLeadingWhitespace( LeftParen( whitespace_after=parse_parenthesizable_whitespace( config, lpar.whitespace_after ) ), lpar.whitespace_before, ), args=() if not arglist else arglist[0].args, rpar=RightParen( whitespace_before=parse_parenthesizable_whitespace( config, rpar.whitespace_before ) ), )
null
4,889
import re import typing from tokenize import ( Floatnumber as FLOATNUMBER_RE, Imagnumber as IMAGNUMBER_RE, Intnumber as INTNUMBER_RE, ) from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Arg, Asynchronous, Attribute, Await, BinaryOperation, BooleanOperation, Call, Comparison, ComparisonTarget, CompFor, CompIf, ConcatenatedString, Dict, DictComp, DictElement, Element, Ellipsis, Float, FormattedString, FormattedStringExpression, FormattedStringText, From, GeneratorExp, IfExp, Imaginary, Index, Integer, Lambda, LeftCurlyBrace, LeftParen, LeftSquareBracket, List, ListComp, Name, NamedExpr, Param, Parameters, RightCurlyBrace, RightParen, RightSquareBracket, Set, SetComp, Slice, StarredDictElement, StarredElement, Subscript, SubscriptElement, Tuple, UnaryOperation, Yield, ) from libcst._nodes.op import ( Add, And, AssignEqual, BaseBinaryOp, BaseBooleanOp, BaseCompOp, BitAnd, BitInvert, BitOr, BitXor, Colon, Comma, Divide, Dot, Equal, FloorDivide, GreaterThan, GreaterThanEqual, In, Is, IsNot, LeftShift, LessThan, LessThanEqual, MatrixMultiply, Minus, Modulo, Multiply, Not, NotEqual, NotIn, Or, Plus, Power, RightShift, Subtract, ) from libcst._nodes.whitespace import SimpleWhitespace from libcst._parser.custom_itertools import grouper from libcst._parser.production_decorator import with_production from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import ( ArglistPartial, AttributePartial, CallPartial, FormattedStringConversionPartial, FormattedStringFormatSpecPartial, SlicePartial, SubscriptPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace class LeftSquareBracket(CSTNode): """ Used by various nodes to denote a subscript or list section. This doesn't own the whitespace to the left of it since this is owned by the parent node. """ #: Any space that appears directly after this left square bracket. whitespace_after: BaseParenthesizableWhitespace = SimpleWhitespace.field("") def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "LeftSquareBracket": return LeftSquareBracket( whitespace_after=visit_required( self, "whitespace_after", self.whitespace_after, visitor ) ) def _codegen_impl(self, state: CodegenState) -> None: state.add_token("[") self.whitespace_after._codegen(state) class RightSquareBracket(CSTNode): """ Used by various nodes to denote a subscript or list section. This doesn't own the whitespace to the right of it since this is owned by the parent node. """ #: Any space that appears directly before this right square bracket. whitespace_before: BaseParenthesizableWhitespace = SimpleWhitespace.field("") def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "RightSquareBracket": return RightSquareBracket( whitespace_before=visit_required( self, "whitespace_before", self.whitespace_before, visitor ) ) def _codegen_impl(self, state: CodegenState) -> None: self.whitespace_before._codegen(state) state.add_token("]") ParserConfig = config_mod.ParserConfig class SubscriptPartial: slice: Union[Index, Slice, Sequence[SubscriptElement]] lbracket: LeftSquareBracket rbracket: RightSquareBracket whitespace_before: WhitespaceState parse_parenthesizable_whitespace = mod.parse_parenthesizable_whitespace def convert_trailer_subscriptlist( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: (lbracket, subscriptlist, rbracket) = children return SubscriptPartial( lbracket=LeftSquareBracket( whitespace_after=parse_parenthesizable_whitespace( config, lbracket.whitespace_after ) ), slice=subscriptlist.value, rbracket=RightSquareBracket( whitespace_before=parse_parenthesizable_whitespace( config, rbracket.whitespace_before ) ), whitespace_before=lbracket.whitespace_before, )
null
4,890
import re import typing from tokenize import ( Floatnumber as FLOATNUMBER_RE, Imagnumber as IMAGNUMBER_RE, Intnumber as INTNUMBER_RE, ) from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Arg, Asynchronous, Attribute, Await, BinaryOperation, BooleanOperation, Call, Comparison, ComparisonTarget, CompFor, CompIf, ConcatenatedString, Dict, DictComp, DictElement, Element, Ellipsis, Float, FormattedString, FormattedStringExpression, FormattedStringText, From, GeneratorExp, IfExp, Imaginary, Index, Integer, Lambda, LeftCurlyBrace, LeftParen, LeftSquareBracket, List, ListComp, Name, NamedExpr, Param, Parameters, RightCurlyBrace, RightParen, RightSquareBracket, Set, SetComp, Slice, StarredDictElement, StarredElement, Subscript, SubscriptElement, Tuple, UnaryOperation, Yield, ) from libcst._nodes.op import ( Add, And, AssignEqual, BaseBinaryOp, BaseBooleanOp, BaseCompOp, BitAnd, BitInvert, BitOr, BitXor, Colon, Comma, Divide, Dot, Equal, FloorDivide, GreaterThan, GreaterThanEqual, In, Is, IsNot, LeftShift, LessThan, LessThanEqual, MatrixMultiply, Minus, Modulo, Multiply, Not, NotEqual, NotIn, Or, Plus, Power, RightShift, Subtract, ) from libcst._nodes.whitespace import SimpleWhitespace from libcst._parser.custom_itertools import grouper from libcst._parser.production_decorator import with_production from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import ( ArglistPartial, AttributePartial, CallPartial, FormattedStringConversionPartial, FormattedStringFormatSpecPartial, SlicePartial, SubscriptPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace class SubscriptElement(CSTNode): """ Part of a sequence of slices in a :class:`Subscript`, such as ``1:2, 3``. This is not used in Python's standard library, but it is used in some third-party libraries. For example, `NumPy uses it to select values and ranges from multi-dimensional arrays <https://docs.scipy.org/doc/numpy-1.10.1/user/basics.indexing.html>`_. """ #: A slice or index that is part of a subscript. slice: BaseSlice #: A separating comma, with any whitespace it owns. comma: Union[Comma, MaybeSentinel] = MaybeSentinel.DEFAULT def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "SubscriptElement": return SubscriptElement( slice=visit_required(self, "slice", self.slice, visitor), comma=visit_sentinel(self, "comma", self.comma, visitor), ) def _codegen_impl(self, state: CodegenState, default_comma: bool = False) -> None: with state.record_syntactic_position(self): self.slice._codegen(state) comma = self.comma if comma is MaybeSentinel.DEFAULT and default_comma: state.add_token(", ") elif isinstance(comma, Comma): comma._codegen(state) class Comma(_BaseOneTokenOp): """ Syntactic trivia used as a separator between subsequent items in various parts of the grammar. Some use-cases are: * :class:`Import` or :class:`ImportFrom`. * :class:`FunctionDef` arguments. * :class:`Tuple`/:class:`List`/:class:`Set`/:class:`Dict` elements. """ #: Any space that appears directly before this comma. whitespace_before: BaseParenthesizableWhitespace = SimpleWhitespace.field("") #: Any space that appears directly after this comma. whitespace_after: BaseParenthesizableWhitespace = SimpleWhitespace.field("") def _get_token(self) -> str: return "," def grouper(iterable: Iterable[_T], n: int, fillvalue: _T = None) -> Iterator[_T]: "Collect data into fixed-length chunks or blocks" # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx" args = [iter(iterable)] * n return zip_longest(*args, fillvalue=fillvalue) ParserConfig = config_mod.ParserConfig class WithLeadingWhitespace(Generic[_T]): value: _T whitespace_before: WhitespaceState parse_parenthesizable_whitespace = mod.parse_parenthesizable_whitespace def convert_subscriptlist( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: # This is a list of SubscriptElement, so construct as such by grouping every # subscript with an optional comma and adding to a list. elements = [] for slice, comma in grouper(children, 2): if comma is None: elements.append(SubscriptElement(slice=slice.value)) else: elements.append( SubscriptElement( slice=slice.value, comma=Comma( whitespace_before=parse_parenthesizable_whitespace( config, comma.whitespace_before ), whitespace_after=parse_parenthesizable_whitespace( config, comma.whitespace_after ), ), ) ) return WithLeadingWhitespace(elements, children[0].whitespace_before)
null
4,891
import re import typing from tokenize import ( Floatnumber as FLOATNUMBER_RE, Imagnumber as IMAGNUMBER_RE, Intnumber as INTNUMBER_RE, ) from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Arg, Asynchronous, Attribute, Await, BinaryOperation, BooleanOperation, Call, Comparison, ComparisonTarget, CompFor, CompIf, ConcatenatedString, Dict, DictComp, DictElement, Element, Ellipsis, Float, FormattedString, FormattedStringExpression, FormattedStringText, From, GeneratorExp, IfExp, Imaginary, Index, Integer, Lambda, LeftCurlyBrace, LeftParen, LeftSquareBracket, List, ListComp, Name, NamedExpr, Param, Parameters, RightCurlyBrace, RightParen, RightSquareBracket, Set, SetComp, Slice, StarredDictElement, StarredElement, Subscript, SubscriptElement, Tuple, UnaryOperation, Yield, ) from libcst._nodes.op import ( Add, And, AssignEqual, BaseBinaryOp, BaseBooleanOp, BaseCompOp, BitAnd, BitInvert, BitOr, BitXor, Colon, Comma, Divide, Dot, Equal, FloorDivide, GreaterThan, GreaterThanEqual, In, Is, IsNot, LeftShift, LessThan, LessThanEqual, MatrixMultiply, Minus, Modulo, Multiply, Not, NotEqual, NotIn, Or, Plus, Power, RightShift, Subtract, ) from libcst._nodes.whitespace import SimpleWhitespace from libcst._parser.custom_itertools import grouper from libcst._parser.production_decorator import with_production from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import ( ArglistPartial, AttributePartial, CallPartial, FormattedStringConversionPartial, FormattedStringFormatSpecPartial, SlicePartial, SubscriptPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace class MaybeSentinel(Enum): """ A :class:`MaybeSentinel` value is used as the default value for some attributes to denote that when generating code (when :attr:`Module.code` is evaluated) we should optionally include this element in order to generate valid code. :class:`MaybeSentinel` is only used for "syntactic trivia" that most users shouldn't care much about anyways, like commas, semicolons, and whitespace. For example, a function call's :attr:`Arg.comma` value defaults to :attr:`MaybeSentinel.DEFAULT`. A comma is required after every argument, except for the last one. If a comma is required and :attr:`Arg.comma` is a :class:`MaybeSentinel`, one is inserted. This makes manual node construction easier, but it also means that we safely add arguments to a preexisting function call without manually fixing the commas: >>> import libcst as cst >>> fn_call = cst.parse_expression("fn(1, 2)") >>> new_fn_call = fn_call.with_changes( ... args=[*fn_call.args, cst.Arg(cst.Integer("3"))] ... ) >>> dummy_module = cst.parse_module("") # we need to use Module.code_for_node >>> dummy_module.code_for_node(fn_call) 'fn(1, 2)' >>> dummy_module.code_for_node(new_fn_call) 'fn(1, 2, 3)' Notice that a comma was automatically inserted after the second argument. Since the original second argument had no comma, it was initialized to :attr:`MaybeSentinel.DEFAULT`. During the code generation of the second argument, a comma was inserted to ensure that the resulting code is valid. .. warning:: While this sentinel is used in place of nodes, it is not a :class:`CSTNode`, and will not be visited by a :class:`CSTVisitor`. Some other libraries, like `RedBaron`_, take other approaches to this problem. RedBaron's tree is mutable (LibCST's tree is immutable), and so they're able to solve this problem with `"proxy lists" <http://redbaron.pycqa.org/en/latest/proxy_list.html>`_. Both approaches come with different sets of tradeoffs. .. _RedBaron: http://redbaron.pycqa.org/en/latest/index.html """ DEFAULT = auto() def __repr__(self) -> str: return str(self) class Index(BaseSlice): """ Any index as passed to a :class:`Subscript`. In ``x[2]``, this would be the ``2`` value. """ #: The index value itself. value: BaseExpression #: An optional string with an asterisk appearing before the name. This is #: expanded into variable number of positional arguments. See PEP-646 star: Optional[Literal["*"]] = None #: Whitespace after the ``star`` (if it exists), but before the ``value``. whitespace_after_star: Optional[BaseParenthesizableWhitespace] = None def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Index": return Index( star=self.star, whitespace_after_star=visit_optional( self, "whitespace_after_star", self.whitespace_after_star, visitor ), value=visit_required(self, "value", self.value, visitor), ) def _codegen_impl(self, state: CodegenState) -> None: star = self.star if star is not None: state.add_token(star) ws = self.whitespace_after_star if ws is not None: ws._codegen(state) self.value._codegen(state) class Slice(BaseSlice): """ Any slice operation in a :class:`Subscript`, such as ``1:``, ``2:3:4``, etc. Note that the grammar does NOT allow parenthesis around a slice so they are not supported here. """ #: The lower bound in the slice, if present lower: Optional[BaseExpression] #: The upper bound in the slice, if present upper: Optional[BaseExpression] #: The step in the slice, if present step: Optional[BaseExpression] = None #: The first slice operator first_colon: Colon = Colon.field() #: The second slice operator, usually omitted second_colon: Union[Colon, MaybeSentinel] = MaybeSentinel.DEFAULT def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Slice": return Slice( lower=visit_optional(self, "lower", self.lower, visitor), first_colon=visit_required(self, "first_colon", self.first_colon, visitor), upper=visit_optional(self, "upper", self.upper, visitor), second_colon=visit_sentinel( self, "second_colon", self.second_colon, visitor ), step=visit_optional(self, "step", self.step, visitor), ) def _codegen_impl(self, state: CodegenState) -> None: lower = self.lower if lower is not None: lower._codegen(state) self.first_colon._codegen(state) upper = self.upper if upper is not None: upper._codegen(state) second_colon = self.second_colon if second_colon is MaybeSentinel.DEFAULT and self.step is not None: state.add_token(":") elif isinstance(second_colon, Colon): second_colon._codegen(state) step = self.step if step is not None: step._codegen(state) class Colon(_BaseOneTokenOp): """ Used by :class:`Slice` as a separator between subsequent expressions, and in :class:`Lambda` to separate arguments and body. """ #: Any space that appears directly before this colon. whitespace_before: BaseParenthesizableWhitespace = SimpleWhitespace.field("") #: Any space that appears directly after this colon. whitespace_after: BaseParenthesizableWhitespace = SimpleWhitespace.field("") def _get_token(self) -> str: return ":" ParserConfig = config_mod.ParserConfig class WithLeadingWhitespace(Generic[_T]): value: _T whitespace_before: WhitespaceState class SlicePartial: second_colon: Colon step: Optional[BaseExpression] parse_parenthesizable_whitespace = mod.parse_parenthesizable_whitespace def convert_subscript( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: if len(children) == 1 and not isinstance(children[0], Token): # This is just an index node (test,) = children return WithLeadingWhitespace(Index(test.value), test.whitespace_before) if isinstance(children[-1], SlicePartial): # We got a partial slice as the final param. Extract the final # bits of the full subscript. *others, sliceop = children whitespace_before = others[0].whitespace_before second_colon = sliceop.second_colon step = sliceop.step else: # We can just parse this below, without taking extras from the # partial child. others = children whitespace_before = others[0].whitespace_before second_colon = MaybeSentinel.DEFAULT step = None # We need to create a partial slice to pass up. So, align so we have # a list that's always [Optional[Test], Colon, Optional[Test]]. if isinstance(others[0], Token): # First token is a colon, so insert an empty test on the LHS. We # know the RHS is a test since it's not a sliceop. slicechildren = [None, *others] else: # First token is non-colon, so its a test. slicechildren = [*others] if len(slicechildren) < 3: # Now, we have to fill in the RHS. We know its two long # at this point if its not already 3. slicechildren = [*slicechildren, None] lower, first_colon, upper = slicechildren return WithLeadingWhitespace( Slice( lower=lower.value if lower is not None else None, first_colon=Colon( whitespace_before=parse_parenthesizable_whitespace( config, first_colon.whitespace_before, ), whitespace_after=parse_parenthesizable_whitespace( config, first_colon.whitespace_after, ), ), upper=upper.value if upper is not None else None, second_colon=second_colon, step=step, ), whitespace_before=whitespace_before, )
null
4,892
import re import typing from tokenize import ( Floatnumber as FLOATNUMBER_RE, Imagnumber as IMAGNUMBER_RE, Intnumber as INTNUMBER_RE, ) from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Arg, Asynchronous, Attribute, Await, BinaryOperation, BooleanOperation, Call, Comparison, ComparisonTarget, CompFor, CompIf, ConcatenatedString, Dict, DictComp, DictElement, Element, Ellipsis, Float, FormattedString, FormattedStringExpression, FormattedStringText, From, GeneratorExp, IfExp, Imaginary, Index, Integer, Lambda, LeftCurlyBrace, LeftParen, LeftSquareBracket, List, ListComp, Name, NamedExpr, Param, Parameters, RightCurlyBrace, RightParen, RightSquareBracket, Set, SetComp, Slice, StarredDictElement, StarredElement, Subscript, SubscriptElement, Tuple, UnaryOperation, Yield, ) from libcst._nodes.op import ( Add, And, AssignEqual, BaseBinaryOp, BaseBooleanOp, BaseCompOp, BitAnd, BitInvert, BitOr, BitXor, Colon, Comma, Divide, Dot, Equal, FloorDivide, GreaterThan, GreaterThanEqual, In, Is, IsNot, LeftShift, LessThan, LessThanEqual, MatrixMultiply, Minus, Modulo, Multiply, Not, NotEqual, NotIn, Or, Plus, Power, RightShift, Subtract, ) from libcst._nodes.whitespace import SimpleWhitespace from libcst._parser.custom_itertools import grouper from libcst._parser.production_decorator import with_production from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import ( ArglistPartial, AttributePartial, CallPartial, FormattedStringConversionPartial, FormattedStringFormatSpecPartial, SlicePartial, SubscriptPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace class Colon(_BaseOneTokenOp): def _get_token(self) -> str: ParserConfig = config_mod.ParserConfig class SlicePartial: parse_parenthesizable_whitespace = mod.parse_parenthesizable_whitespace def convert_sliceop( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: if len(children) == 2: colon, test = children step = test.value else: (colon,) = children step = None return SlicePartial( second_colon=Colon( whitespace_before=parse_parenthesizable_whitespace( config, colon.whitespace_before ), whitespace_after=parse_parenthesizable_whitespace( config, colon.whitespace_after ), ), step=step, )
null
4,893
import re import typing from tokenize import ( Floatnumber as FLOATNUMBER_RE, Imagnumber as IMAGNUMBER_RE, Intnumber as INTNUMBER_RE, ) from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Arg, Asynchronous, Attribute, Await, BinaryOperation, BooleanOperation, Call, Comparison, ComparisonTarget, CompFor, CompIf, ConcatenatedString, Dict, DictComp, DictElement, Element, Ellipsis, Float, FormattedString, FormattedStringExpression, FormattedStringText, From, GeneratorExp, IfExp, Imaginary, Index, Integer, Lambda, LeftCurlyBrace, LeftParen, LeftSquareBracket, List, ListComp, Name, NamedExpr, Param, Parameters, RightCurlyBrace, RightParen, RightSquareBracket, Set, SetComp, Slice, StarredDictElement, StarredElement, Subscript, SubscriptElement, Tuple, UnaryOperation, Yield, ) from libcst._nodes.op import ( Add, And, AssignEqual, BaseBinaryOp, BaseBooleanOp, BaseCompOp, BitAnd, BitInvert, BitOr, BitXor, Colon, Comma, Divide, Dot, Equal, FloorDivide, GreaterThan, GreaterThanEqual, In, Is, IsNot, LeftShift, LessThan, LessThanEqual, MatrixMultiply, Minus, Modulo, Multiply, Not, NotEqual, NotIn, Or, Plus, Power, RightShift, Subtract, ) from libcst._nodes.whitespace import SimpleWhitespace from libcst._parser.custom_itertools import grouper from libcst._parser.production_decorator import with_production from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import ( ArglistPartial, AttributePartial, CallPartial, FormattedStringConversionPartial, FormattedStringFormatSpecPartial, SlicePartial, SubscriptPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace class Name(BaseAssignTargetExpression, BaseDelTargetExpression): """ A simple variable name. Names are typically used in the context of a variable access, an assignment, or a deletion. Dotted variable names (``a.b.c``) are represented with :class:`Attribute` nodes, and subscripted variable names (``a[b]``) are represented with :class:`Subscript` nodes. """ #: The variable's name (or "identifier") as a string. value: str lpar: Sequence[LeftParen] = () #: Sequence of parenthesis for precedence dictation. rpar: Sequence[RightParen] = () def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Name": return Name( lpar=visit_sequence(self, "lpar", self.lpar, visitor), value=self.value, rpar=visit_sequence(self, "rpar", self.rpar, visitor), ) def _validate(self) -> None: super(Name, self)._validate() if len(self.value) == 0: raise CSTValidationError("Cannot have empty name identifier.") if not self.value.isidentifier(): raise CSTValidationError(f"Name {self.value!r} is not a valid identifier.") def _codegen_impl(self, state: CodegenState) -> None: with self._parenthesize(state): state.add_token(self.value) class Dot(_BaseOneTokenOp): """ Used by :class:`Attribute` as a separator between subsequent :class:`Name` nodes. """ #: Any space that appears directly before this dot. whitespace_before: BaseParenthesizableWhitespace = SimpleWhitespace.field("") #: Any space that appears directly after this dot. whitespace_after: BaseParenthesizableWhitespace = SimpleWhitespace.field("") def _get_token(self) -> str: return "." ParserConfig = config_mod.ParserConfig class AttributePartial: dot: Dot attr: Name parse_parenthesizable_whitespace = mod.parse_parenthesizable_whitespace def convert_trailer_attribute( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: dot, name = children return AttributePartial( dot=Dot( whitespace_before=parse_parenthesizable_whitespace( config, dot.whitespace_before ), whitespace_after=parse_parenthesizable_whitespace( config, dot.whitespace_after ), ), attr=Name(name.string), )
null
4,894
import re import typing from tokenize import ( Floatnumber as FLOATNUMBER_RE, Imagnumber as IMAGNUMBER_RE, Intnumber as INTNUMBER_RE, ) from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Arg, Asynchronous, Attribute, Await, BinaryOperation, BooleanOperation, Call, Comparison, ComparisonTarget, CompFor, CompIf, ConcatenatedString, Dict, DictComp, DictElement, Element, Ellipsis, Float, FormattedString, FormattedStringExpression, FormattedStringText, From, GeneratorExp, IfExp, Imaginary, Index, Integer, Lambda, LeftCurlyBrace, LeftParen, LeftSquareBracket, List, ListComp, Name, NamedExpr, Param, Parameters, RightCurlyBrace, RightParen, RightSquareBracket, Set, SetComp, Slice, StarredDictElement, StarredElement, Subscript, SubscriptElement, Tuple, UnaryOperation, Yield, ) from libcst._nodes.op import ( Add, And, AssignEqual, BaseBinaryOp, BaseBooleanOp, BaseCompOp, BitAnd, BitInvert, BitOr, BitXor, Colon, Comma, Divide, Dot, Equal, FloorDivide, GreaterThan, GreaterThanEqual, In, Is, IsNot, LeftShift, LessThan, LessThanEqual, MatrixMultiply, Minus, Modulo, Multiply, Not, NotEqual, NotIn, Or, Plus, Power, RightShift, Subtract, ) from libcst._nodes.whitespace import SimpleWhitespace from libcst._parser.custom_itertools import grouper from libcst._parser.production_decorator import with_production from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import ( ArglistPartial, AttributePartial, CallPartial, FormattedStringConversionPartial, FormattedStringFormatSpecPartial, SlicePartial, SubscriptPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace ParserConfig = config_mod.ParserConfig def convert_atom( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: (child,) = children return child
null
4,895
import re import typing from tokenize import ( Floatnumber as FLOATNUMBER_RE, Imagnumber as IMAGNUMBER_RE, Intnumber as INTNUMBER_RE, ) from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Arg, Asynchronous, Attribute, Await, BinaryOperation, BooleanOperation, Call, Comparison, ComparisonTarget, CompFor, CompIf, ConcatenatedString, Dict, DictComp, DictElement, Element, Ellipsis, Float, FormattedString, FormattedStringExpression, FormattedStringText, From, GeneratorExp, IfExp, Imaginary, Index, Integer, Lambda, LeftCurlyBrace, LeftParen, LeftSquareBracket, List, ListComp, Name, NamedExpr, Param, Parameters, RightCurlyBrace, RightParen, RightSquareBracket, Set, SetComp, Slice, StarredDictElement, StarredElement, Subscript, SubscriptElement, Tuple, UnaryOperation, Yield, ) from libcst._nodes.op import ( Add, And, AssignEqual, BaseBinaryOp, BaseBooleanOp, BaseCompOp, BitAnd, BitInvert, BitOr, BitXor, Colon, Comma, Divide, Dot, Equal, FloorDivide, GreaterThan, GreaterThanEqual, In, Is, IsNot, LeftShift, LessThan, LessThanEqual, MatrixMultiply, Minus, Modulo, Multiply, Not, NotEqual, NotIn, Or, Plus, Power, RightShift, Subtract, ) from libcst._nodes.whitespace import SimpleWhitespace from libcst._parser.custom_itertools import grouper from libcst._parser.production_decorator import with_production from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import ( ArglistPartial, AttributePartial, CallPartial, FormattedStringConversionPartial, FormattedStringFormatSpecPartial, SlicePartial, SubscriptPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace class Name(BaseAssignTargetExpression, BaseDelTargetExpression): """ A simple variable name. Names are typically used in the context of a variable access, an assignment, or a deletion. Dotted variable names (``a.b.c``) are represented with :class:`Attribute` nodes, and subscripted variable names (``a[b]``) are represented with :class:`Subscript` nodes. """ #: The variable's name (or "identifier") as a string. value: str lpar: Sequence[LeftParen] = () #: Sequence of parenthesis for precedence dictation. rpar: Sequence[RightParen] = () def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Name": return Name( lpar=visit_sequence(self, "lpar", self.lpar, visitor), value=self.value, rpar=visit_sequence(self, "rpar", self.rpar, visitor), ) def _validate(self) -> None: super(Name, self)._validate() if len(self.value) == 0: raise CSTValidationError("Cannot have empty name identifier.") if not self.value.isidentifier(): raise CSTValidationError(f"Name {self.value!r} is not a valid identifier.") def _codegen_impl(self, state: CodegenState) -> None: with self._parenthesize(state): state.add_token(self.value) class Integer(BaseNumber): #: A string representation of the integer, such as ``"100000"`` or ``100_000``. #: #: To convert this string representation to an ``int``, use the calculated #: property :attr:`~Integer.evaluated_value`. value: str lpar: Sequence[LeftParen] = () #: Sequence of parenthesis for precedence dictation. rpar: Sequence[RightParen] = () def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Integer": return Integer( lpar=visit_sequence(self, "lpar", self.lpar, visitor), value=self.value, rpar=visit_sequence(self, "rpar", self.rpar, visitor), ) def _validate(self) -> None: super(Integer, self)._validate() if not re.fullmatch(INTNUMBER_RE, self.value): raise CSTValidationError("Number is not a valid integer.") def _codegen_impl(self, state: CodegenState) -> None: with self._parenthesize(state): state.add_token(self.value) def evaluated_value(self) -> int: """ Return an :func:`ast.literal_eval` evaluated int of :py:attr:`value`. """ return literal_eval(self.value) class Float(BaseNumber): #: A string representation of the floating point number, such as ``"0.05"``, #: ``".050"``, or ``"5e-2"``. #: #: To convert this string representation to an ``float``, use the calculated #: property :attr:`~Float.evaluated_value`. value: str lpar: Sequence[LeftParen] = () #: Sequence of parenthesis for precedence dictation. rpar: Sequence[RightParen] = () def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Float": return Float( lpar=visit_sequence(self, "lpar", self.lpar, visitor), value=self.value, rpar=visit_sequence(self, "rpar", self.rpar, visitor), ) def _validate(self) -> None: super(Float, self)._validate() if not re.fullmatch(FLOATNUMBER_RE, self.value): raise CSTValidationError("Number is not a valid float.") def _codegen_impl(self, state: CodegenState) -> None: with self._parenthesize(state): state.add_token(self.value) def evaluated_value(self) -> float: """ Return an :func:`ast.literal_eval` evaluated float of :py:attr:`value`. """ return literal_eval(self.value) class Imaginary(BaseNumber): #: A string representation of the imaginary (complex) number, such as ``"2j"``. #: #: To convert this string representation to an ``complex``, use the calculated #: property :attr:`~Imaginary.evaluated_value`. value: str lpar: Sequence[LeftParen] = () #: Sequence of parenthesis for precedence dictation. rpar: Sequence[RightParen] = () def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Imaginary": return Imaginary( lpar=visit_sequence(self, "lpar", self.lpar, visitor), value=self.value, rpar=visit_sequence(self, "rpar", self.rpar, visitor), ) def _validate(self) -> None: super(Imaginary, self)._validate() if not re.fullmatch(IMAGNUMBER_RE, self.value): raise CSTValidationError("Number is not a valid imaginary.") def _codegen_impl(self, state: CodegenState) -> None: with self._parenthesize(state): state.add_token(self.value) def evaluated_value(self) -> complex: """ Return an :func:`ast.literal_eval` evaluated complex of :py:attr:`value`. """ return literal_eval(self.value) ParserConfig = config_mod.ParserConfig class WithLeadingWhitespace(Generic[_T]): value: _T whitespace_before: WhitespaceState def convert_atom_basic( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: (child,) = children if child.type.name == "NAME": # This also handles 'None', 'True', and 'False' directly, but we # keep it in the grammar to be more correct. return WithLeadingWhitespace(Name(child.string), child.whitespace_before) elif child.type.name == "NUMBER": # We must determine what type of number it is since we split node # types up this way. if re.fullmatch(INTNUMBER_RE, child.string): return WithLeadingWhitespace(Integer(child.string), child.whitespace_before) elif re.fullmatch(FLOATNUMBER_RE, child.string): return WithLeadingWhitespace(Float(child.string), child.whitespace_before) elif re.fullmatch(IMAGNUMBER_RE, child.string): return WithLeadingWhitespace( Imaginary(child.string), child.whitespace_before ) else: raise Exception(f"Unparseable number {child.string}") else: raise Exception(f"Logic error, unexpected token {child.type.name}")
null
4,896
import re import typing from tokenize import ( Floatnumber as FLOATNUMBER_RE, Imagnumber as IMAGNUMBER_RE, Intnumber as INTNUMBER_RE, ) from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Arg, Asynchronous, Attribute, Await, BinaryOperation, BooleanOperation, Call, Comparison, ComparisonTarget, CompFor, CompIf, ConcatenatedString, Dict, DictComp, DictElement, Element, Ellipsis, Float, FormattedString, FormattedStringExpression, FormattedStringText, From, GeneratorExp, IfExp, Imaginary, Index, Integer, Lambda, LeftCurlyBrace, LeftParen, LeftSquareBracket, List, ListComp, Name, NamedExpr, Param, Parameters, RightCurlyBrace, RightParen, RightSquareBracket, Set, SetComp, Slice, StarredDictElement, StarredElement, Subscript, SubscriptElement, Tuple, UnaryOperation, Yield, ) from libcst._nodes.op import ( Add, And, AssignEqual, BaseBinaryOp, BaseBooleanOp, BaseCompOp, BitAnd, BitInvert, BitOr, BitXor, Colon, Comma, Divide, Dot, Equal, FloorDivide, GreaterThan, GreaterThanEqual, In, Is, IsNot, LeftShift, LessThan, LessThanEqual, MatrixMultiply, Minus, Modulo, Multiply, Not, NotEqual, NotIn, Or, Plus, Power, RightShift, Subtract, ) from libcst._nodes.whitespace import SimpleWhitespace from libcst._parser.custom_itertools import grouper from libcst._parser.production_decorator import with_production from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import ( ArglistPartial, AttributePartial, CallPartial, FormattedStringConversionPartial, FormattedStringFormatSpecPartial, SlicePartial, SubscriptPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace class LeftSquareBracket(CSTNode): """ Used by various nodes to denote a subscript or list section. This doesn't own the whitespace to the left of it since this is owned by the parent node. """ #: Any space that appears directly after this left square bracket. whitespace_after: BaseParenthesizableWhitespace = SimpleWhitespace.field("") def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "LeftSquareBracket": return LeftSquareBracket( whitespace_after=visit_required( self, "whitespace_after", self.whitespace_after, visitor ) ) def _codegen_impl(self, state: CodegenState) -> None: state.add_token("[") self.whitespace_after._codegen(state) class RightSquareBracket(CSTNode): """ Used by various nodes to denote a subscript or list section. This doesn't own the whitespace to the right of it since this is owned by the parent node. """ #: Any space that appears directly before this right square bracket. whitespace_before: BaseParenthesizableWhitespace = SimpleWhitespace.field("") def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "RightSquareBracket": return RightSquareBracket( whitespace_before=visit_required( self, "whitespace_before", self.whitespace_before, visitor ) ) def _codegen_impl(self, state: CodegenState) -> None: self.whitespace_before._codegen(state) state.add_token("]") class List(BaseList, BaseAssignTargetExpression, BaseDelTargetExpression): """ A mutable literal list. :: List([ Element(Integer("1")), Element(Integer("2")), StarredElement(Name("others")), ]) generates the following code:: [1, 2, *others] List comprehensions are represented with a :class:`ListComp` node. """ #: A sequence containing all the :class:`Element` and :class:`StarredElement` nodes #: in the list. elements: Sequence[BaseElement] lbracket: LeftSquareBracket = LeftSquareBracket.field() #: Brackets surrounding the list. rbracket: RightSquareBracket = RightSquareBracket.field() lpar: Sequence[LeftParen] = () #: Sequence of parenthesis for precedence dictation. rpar: Sequence[RightParen] = () def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "List": return List( lpar=visit_sequence(self, "lpar", self.lpar, visitor), lbracket=visit_required(self, "lbracket", self.lbracket, visitor), elements=visit_sequence(self, "elements", self.elements, visitor), rbracket=visit_required(self, "rbracket", self.rbracket, visitor), rpar=visit_sequence(self, "rpar", self.rpar, visitor), ) def _codegen_impl(self, state: CodegenState) -> None: with self._parenthesize(state), self._bracketize(state): elements = self.elements for idx, el in enumerate(elements): el._codegen( state, default_comma=(idx < len(elements) - 1), default_comma_whitespace=True, ) ParserConfig = config_mod.ParserConfig class WithLeadingWhitespace(Generic[_T]): value: _T whitespace_before: WhitespaceState parse_parenthesizable_whitespace = mod.parse_parenthesizable_whitespace def convert_atom_squarebrackets( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: lbracket_tok, *body, rbracket_tok = children lbracket = LeftSquareBracket( whitespace_after=parse_parenthesizable_whitespace( config, lbracket_tok.whitespace_after ) ) rbracket = RightSquareBracket( whitespace_before=parse_parenthesizable_whitespace( config, rbracket_tok.whitespace_before ) ) if len(body) == 0: list_node = List((), lbracket=lbracket, rbracket=rbracket) else: # len(body) == 1 # body[0] is a List or ListComp list_node = body[0].value.with_changes(lbracket=lbracket, rbracket=rbracket) return WithLeadingWhitespace(list_node, lbracket_tok.whitespace_before)
null
4,897
import re import typing from tokenize import ( Floatnumber as FLOATNUMBER_RE, Imagnumber as IMAGNUMBER_RE, Intnumber as INTNUMBER_RE, ) from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Arg, Asynchronous, Attribute, Await, BinaryOperation, BooleanOperation, Call, Comparison, ComparisonTarget, CompFor, CompIf, ConcatenatedString, Dict, DictComp, DictElement, Element, Ellipsis, Float, FormattedString, FormattedStringExpression, FormattedStringText, From, GeneratorExp, IfExp, Imaginary, Index, Integer, Lambda, LeftCurlyBrace, LeftParen, LeftSquareBracket, List, ListComp, Name, NamedExpr, Param, Parameters, RightCurlyBrace, RightParen, RightSquareBracket, Set, SetComp, Slice, StarredDictElement, StarredElement, Subscript, SubscriptElement, Tuple, UnaryOperation, Yield, ) from libcst._nodes.op import ( Add, And, AssignEqual, BaseBinaryOp, BaseBooleanOp, BaseCompOp, BitAnd, BitInvert, BitOr, BitXor, Colon, Comma, Divide, Dot, Equal, FloorDivide, GreaterThan, GreaterThanEqual, In, Is, IsNot, LeftShift, LessThan, LessThanEqual, MatrixMultiply, Minus, Modulo, Multiply, Not, NotEqual, NotIn, Or, Plus, Power, RightShift, Subtract, ) from libcst._nodes.whitespace import SimpleWhitespace from libcst._parser.custom_itertools import grouper from libcst._parser.production_decorator import with_production from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import ( ArglistPartial, AttributePartial, CallPartial, FormattedStringConversionPartial, FormattedStringFormatSpecPartial, SlicePartial, SubscriptPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace class LeftCurlyBrace(CSTNode): """ Used by various nodes to denote a dict or set. This doesn't own the whitespace to the left of it since this is owned by the parent node. """ #: Any space that appears directly after this left curly brace. whitespace_after: BaseParenthesizableWhitespace = SimpleWhitespace.field("") def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "LeftCurlyBrace": return LeftCurlyBrace( whitespace_after=visit_required( self, "whitespace_after", self.whitespace_after, visitor ) ) def _codegen_impl(self, state: CodegenState) -> None: state.add_token("{") self.whitespace_after._codegen(state) class RightCurlyBrace(CSTNode): """ Used by various nodes to denote a dict or set. This doesn't own the whitespace to the right of it since this is owned by the parent node. """ #: Any space that appears directly before this right curly brace. whitespace_before: BaseParenthesizableWhitespace = SimpleWhitespace.field("") def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "RightCurlyBrace": return RightCurlyBrace( whitespace_before=visit_required( self, "whitespace_before", self.whitespace_before, visitor ) ) def _codegen_impl(self, state: CodegenState) -> None: self.whitespace_before._codegen(state) state.add_token("}") class Dict(BaseDict): """ A literal dictionary. Key-value pairs are stored in ``elements`` using :class:`DictElement` nodes. It's possible to expand one dictionary into another, as in ``{k: v, **expanded}``. Expanded elements are stored as :class:`StarredDictElement` nodes. :: Dict([ DictElement(Name("k1"), Name("v1")), DictElement(Name("k2"), Name("v2")), StarredDictElement(Name("expanded")), ]) generates the following code:: {k1: v1, k2: v2, **expanded} """ elements: Sequence[BaseDictElement] lbrace: LeftCurlyBrace = LeftCurlyBrace.field() rbrace: RightCurlyBrace = RightCurlyBrace.field() lpar: Sequence[LeftParen] = () rpar: Sequence[RightParen] = () def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Dict": return Dict( lpar=visit_sequence(self, "lpar", self.lpar, visitor), lbrace=visit_required(self, "lbrace", self.lbrace, visitor), elements=visit_sequence(self, "elements", self.elements, visitor), rbrace=visit_required(self, "rbrace", self.rbrace, visitor), rpar=visit_sequence(self, "rpar", self.rpar, visitor), ) def _codegen_impl(self, state: CodegenState) -> None: with self._parenthesize(state), self._braceize(state): elements = self.elements for idx, el in enumerate(elements): el._codegen( state, default_comma=(idx < len(elements) - 1), default_comma_whitespace=True, ) ParserConfig = config_mod.ParserConfig class WithLeadingWhitespace(Generic[_T]): value: _T whitespace_before: WhitespaceState parse_parenthesizable_whitespace = mod.parse_parenthesizable_whitespace def convert_atom_curlybraces( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: lbrace_tok, *body, rbrace_tok = children lbrace = LeftCurlyBrace( whitespace_after=parse_parenthesizable_whitespace( config, lbrace_tok.whitespace_after ) ) rbrace = RightCurlyBrace( whitespace_before=parse_parenthesizable_whitespace( config, rbrace_tok.whitespace_before ) ) if len(body) == 0: dict_or_set_node = Dict((), lbrace=lbrace, rbrace=rbrace) else: # len(body) == 1 dict_or_set_node = body[0].value.with_changes(lbrace=lbrace, rbrace=rbrace) return WithLeadingWhitespace(dict_or_set_node, lbrace_tok.whitespace_before)
null
4,898
import re import typing from tokenize import ( Floatnumber as FLOATNUMBER_RE, Imagnumber as IMAGNUMBER_RE, Intnumber as INTNUMBER_RE, ) from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Arg, Asynchronous, Attribute, Await, BinaryOperation, BooleanOperation, Call, Comparison, ComparisonTarget, CompFor, CompIf, ConcatenatedString, Dict, DictComp, DictElement, Element, Ellipsis, Float, FormattedString, FormattedStringExpression, FormattedStringText, From, GeneratorExp, IfExp, Imaginary, Index, Integer, Lambda, LeftCurlyBrace, LeftParen, LeftSquareBracket, List, ListComp, Name, NamedExpr, Param, Parameters, RightCurlyBrace, RightParen, RightSquareBracket, Set, SetComp, Slice, StarredDictElement, StarredElement, Subscript, SubscriptElement, Tuple, UnaryOperation, Yield, ) from libcst._nodes.op import ( Add, And, AssignEqual, BaseBinaryOp, BaseBooleanOp, BaseCompOp, BitAnd, BitInvert, BitOr, BitXor, Colon, Comma, Divide, Dot, Equal, FloorDivide, GreaterThan, GreaterThanEqual, In, Is, IsNot, LeftShift, LessThan, LessThanEqual, MatrixMultiply, Minus, Modulo, Multiply, Not, NotEqual, NotIn, Or, Plus, Power, RightShift, Subtract, ) from libcst._nodes.whitespace import SimpleWhitespace from libcst._parser.custom_itertools import grouper from libcst._parser.production_decorator import with_production from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import ( ArglistPartial, AttributePartial, CallPartial, FormattedStringConversionPartial, FormattedStringFormatSpecPartial, SlicePartial, SubscriptPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace class LeftParen(CSTNode): """ Used by various nodes to denote a parenthesized section. This doesn't own the whitespace to the left of it since this is owned by the parent node. """ #: Any space that appears directly after this left parenthesis. whitespace_after: BaseParenthesizableWhitespace = SimpleWhitespace.field("") def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "LeftParen": return LeftParen( whitespace_after=visit_required( self, "whitespace_after", self.whitespace_after, visitor ) ) def _codegen_impl(self, state: CodegenState) -> None: state.add_token("(") self.whitespace_after._codegen(state) class RightParen(CSTNode): """ Used by various nodes to denote a parenthesized section. This doesn't own the whitespace to the right of it since this is owned by the parent node. """ #: Any space that appears directly after this left parenthesis. whitespace_before: BaseParenthesizableWhitespace = SimpleWhitespace.field("") def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "RightParen": return RightParen( whitespace_before=visit_required( self, "whitespace_before", self.whitespace_before, visitor ) ) def _codegen_impl(self, state: CodegenState) -> None: self.whitespace_before._codegen(state) state.add_token(")") class Tuple(BaseAssignTargetExpression, BaseDelTargetExpression): """ An immutable literal tuple. Tuples are often (but not always) parenthesized. :: Tuple([ Element(Integer("1")), Element(Integer("2")), StarredElement(Name("others")), ]) generates the following code:: (1, 2, *others) """ #: A sequence containing all the :class:`Element` and :class:`StarredElement` nodes #: in the tuple. elements: Sequence[BaseElement] lpar: Sequence[LeftParen] = field(default_factory=lambda: (LeftParen(),)) #: Sequence of parenthesis for precedence dictation. rpar: Sequence[RightParen] = field(default_factory=lambda: (RightParen(),)) def _safe_to_use_with_word_operator(self, position: ExpressionPosition) -> bool: if super(Tuple, self)._safe_to_use_with_word_operator(position): # if we have parenthesis, we're safe. return True # elements[-1] and elements[0] must exist past this point, because # we're not parenthesized, meaning we must have at least one element. elements = self.elements if position == ExpressionPosition.LEFT: last_element = elements[-1] return ( isinstance(last_element.comma, Comma) or ( isinstance(last_element, StarredElement) and len(last_element.rpar) > 0 ) or last_element.value._safe_to_use_with_word_operator(position) ) else: # ExpressionPosition.RIGHT first_element = elements[0] # starred elements are always safe because they begin with ( or * return isinstance( first_element, StarredElement ) or first_element.value._safe_to_use_with_word_operator(position) def _validate(self) -> None: # Paren validation and such super(Tuple, self)._validate() if len(self.elements) == 0: if len(self.lpar) == 0: # assumes len(lpar) == len(rpar), via superclass raise CSTValidationError( "A zero-length tuple must be wrapped in parentheses." ) # Invalid commas aren't possible, because MaybeSentinel will ensure that there # is a comma where required. def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Tuple": return Tuple( lpar=visit_sequence(self, "lpar", self.lpar, visitor), elements=visit_sequence(self, "elements", self.elements, visitor), rpar=visit_sequence(self, "rpar", self.rpar, visitor), ) def _codegen_impl(self, state: CodegenState) -> None: with self._parenthesize(state): elements = self.elements if len(elements) == 1: elements[0]._codegen( state, default_comma=True, default_comma_whitespace=False ) else: for idx, el in enumerate(elements): el._codegen( state, default_comma=(idx < len(elements) - 1), default_comma_whitespace=True, ) ParserConfig = config_mod.ParserConfig class WithLeadingWhitespace(Generic[_T]): value: _T whitespace_before: WhitespaceState parse_parenthesizable_whitespace = mod.parse_parenthesizable_whitespace def convert_atom_parens( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: lpar_tok, *atoms, rpar_tok = children lpar = LeftParen( whitespace_after=parse_parenthesizable_whitespace( config, lpar_tok.whitespace_after ) ) rpar = RightParen( whitespace_before=parse_parenthesizable_whitespace( config, rpar_tok.whitespace_before ) ) if len(atoms) == 1: # inner_atom is a _BaseParenthesizedNode inner_atom = atoms[0].value return WithLeadingWhitespace( inner_atom.with_changes( # pyre-fixme[60]: Expected to unpack an iterable, but got `unknown`. lpar=(lpar, *inner_atom.lpar), # pyre-fixme[60]: Expected to unpack an iterable, but got `unknown`. rpar=(*inner_atom.rpar, rpar), ), lpar_tok.whitespace_before, ) else: return WithLeadingWhitespace( Tuple((), lpar=(lpar,), rpar=(rpar,)), lpar_tok.whitespace_before )
null
4,899
import re import typing from tokenize import ( Floatnumber as FLOATNUMBER_RE, Imagnumber as IMAGNUMBER_RE, Intnumber as INTNUMBER_RE, ) from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Arg, Asynchronous, Attribute, Await, BinaryOperation, BooleanOperation, Call, Comparison, ComparisonTarget, CompFor, CompIf, ConcatenatedString, Dict, DictComp, DictElement, Element, Ellipsis, Float, FormattedString, FormattedStringExpression, FormattedStringText, From, GeneratorExp, IfExp, Imaginary, Index, Integer, Lambda, LeftCurlyBrace, LeftParen, LeftSquareBracket, List, ListComp, Name, NamedExpr, Param, Parameters, RightCurlyBrace, RightParen, RightSquareBracket, Set, SetComp, Slice, StarredDictElement, StarredElement, Subscript, SubscriptElement, Tuple, UnaryOperation, Yield, ) from libcst._nodes.op import ( Add, And, AssignEqual, BaseBinaryOp, BaseBooleanOp, BaseCompOp, BitAnd, BitInvert, BitOr, BitXor, Colon, Comma, Divide, Dot, Equal, FloorDivide, GreaterThan, GreaterThanEqual, In, Is, IsNot, LeftShift, LessThan, LessThanEqual, MatrixMultiply, Minus, Modulo, Multiply, Not, NotEqual, NotIn, Or, Plus, Power, RightShift, Subtract, ) from libcst._nodes.whitespace import SimpleWhitespace from libcst._parser.custom_itertools import grouper from libcst._parser.production_decorator import with_production from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import ( ArglistPartial, AttributePartial, CallPartial, FormattedStringConversionPartial, FormattedStringFormatSpecPartial, SlicePartial, SubscriptPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace class Ellipsis(BaseExpression): """ An ellipsis ``...``. When used as an expression, it evaluates to the `Ellipsis constant`_. Ellipsis are often used as placeholders in code or in conjunction with :class:`SubscriptElement`. .. _Ellipsis constant: https://docs.python.org/3/library/constants.html#Ellipsis """ lpar: Sequence[LeftParen] = () #: Sequence of parenthesis for precedence dictation. rpar: Sequence[RightParen] = () def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Ellipsis": return Ellipsis( lpar=visit_sequence(self, "lpar", self.lpar, visitor), rpar=visit_sequence(self, "rpar", self.rpar, visitor), ) def _safe_to_use_with_word_operator(self, position: ExpressionPosition) -> bool: return True def _codegen_impl(self, state: CodegenState) -> None: with self._parenthesize(state): state.add_token("...") ParserConfig = config_mod.ParserConfig class WithLeadingWhitespace(Generic[_T]): value: _T whitespace_before: WhitespaceState def convert_atom_ellipses( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: (token,) = children return WithLeadingWhitespace(Ellipsis(), token.whitespace_before)
null
4,900
import re import typing from tokenize import ( Floatnumber as FLOATNUMBER_RE, Imagnumber as IMAGNUMBER_RE, Intnumber as INTNUMBER_RE, ) from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Arg, Asynchronous, Attribute, Await, BinaryOperation, BooleanOperation, Call, Comparison, ComparisonTarget, CompFor, CompIf, ConcatenatedString, Dict, DictComp, DictElement, Element, Ellipsis, Float, FormattedString, FormattedStringExpression, FormattedStringText, From, GeneratorExp, IfExp, Imaginary, Index, Integer, Lambda, LeftCurlyBrace, LeftParen, LeftSquareBracket, List, ListComp, Name, NamedExpr, Param, Parameters, RightCurlyBrace, RightParen, RightSquareBracket, Set, SetComp, Slice, StarredDictElement, StarredElement, Subscript, SubscriptElement, Tuple, UnaryOperation, Yield, ) from libcst._nodes.op import ( Add, And, AssignEqual, BaseBinaryOp, BaseBooleanOp, BaseCompOp, BitAnd, BitInvert, BitOr, BitXor, Colon, Comma, Divide, Dot, Equal, FloorDivide, GreaterThan, GreaterThanEqual, In, Is, IsNot, LeftShift, LessThan, LessThanEqual, MatrixMultiply, Minus, Modulo, Multiply, Not, NotEqual, NotIn, Or, Plus, Power, RightShift, Subtract, ) from libcst._nodes.whitespace import SimpleWhitespace from libcst._parser.custom_itertools import grouper from libcst._parser.production_decorator import with_production from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import ( ArglistPartial, AttributePartial, CallPartial, FormattedStringConversionPartial, FormattedStringFormatSpecPartial, SlicePartial, SubscriptPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace class ConcatenatedString(BaseString): def _safe_to_use_with_word_operator(self, position: ExpressionPosition) -> bool: def _validate(self) -> None: def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "ConcatenatedString": def _codegen_impl(self, state: CodegenState) -> None: def evaluated_value(self) -> Union[str, bytes, None]: ParserConfig = config_mod.ParserConfig class WithLeadingWhitespace(Generic[_T]): parse_parenthesizable_whitespace = mod.parse_parenthesizable_whitespace def convert_atom_string( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: if len(children) == 1: return children[0] else: left, right = children return WithLeadingWhitespace( ConcatenatedString( left=left.value, whitespace_between=parse_parenthesizable_whitespace( config, right.whitespace_before ), right=right.value, ), left.whitespace_before, )
null
4,901
import re import typing from tokenize import ( Floatnumber as FLOATNUMBER_RE, Imagnumber as IMAGNUMBER_RE, Intnumber as INTNUMBER_RE, ) from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Arg, Asynchronous, Attribute, Await, BinaryOperation, BooleanOperation, Call, Comparison, ComparisonTarget, CompFor, CompIf, ConcatenatedString, Dict, DictComp, DictElement, Element, Ellipsis, Float, FormattedString, FormattedStringExpression, FormattedStringText, From, GeneratorExp, IfExp, Imaginary, Index, Integer, Lambda, LeftCurlyBrace, LeftParen, LeftSquareBracket, List, ListComp, Name, NamedExpr, Param, Parameters, RightCurlyBrace, RightParen, RightSquareBracket, Set, SetComp, Slice, StarredDictElement, StarredElement, Subscript, SubscriptElement, Tuple, UnaryOperation, Yield, ) from libcst._nodes.op import ( Add, And, AssignEqual, BaseBinaryOp, BaseBooleanOp, BaseCompOp, BitAnd, BitInvert, BitOr, BitXor, Colon, Comma, Divide, Dot, Equal, FloorDivide, GreaterThan, GreaterThanEqual, In, Is, IsNot, LeftShift, LessThan, LessThanEqual, MatrixMultiply, Minus, Modulo, Multiply, Not, NotEqual, NotIn, Or, Plus, Power, RightShift, Subtract, ) from libcst._nodes.whitespace import SimpleWhitespace from libcst._parser.custom_itertools import grouper from libcst._parser.production_decorator import with_production from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import ( ArglistPartial, AttributePartial, CallPartial, FormattedStringConversionPartial, FormattedStringFormatSpecPartial, SlicePartial, SubscriptPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace class FormattedString(_BasePrefixedString): """ An "f-string". These formatted strings are string literals prefixed by the letter "f". An f-string may contain interpolated expressions inside curly braces (``{`` and ``}``). F-strings are defined in `PEP 498`_ and documented in `Python's language reference <https://docs.python.org/3/reference/lexical_analysis.html#formatted-string-literals>`__. >>> import libcst as cst >>> cst.parse_expression('f"ab{cd}ef"') FormattedString( parts=[ FormattedStringText( value='ab', ), FormattedStringExpression( expression=Name( value='cd', lpar=[], rpar=[], ), conversion=None, format_spec=None, whitespace_before_expression=SimpleWhitespace( value='', ), whitespace_after_expression=SimpleWhitespace( value='', ), ), FormattedStringText( value='ef', ), ], start='f"', end='"', lpar=[], rpar=[], ) .. _PEP 498: https://www.python.org/dev/peps/pep-0498/#specification """ #: A formatted string is composed as a series of :class:`FormattedStringText` and #: :class:`FormattedStringExpression` parts. parts: Sequence[BaseFormattedStringContent] #: The string prefix and the leading quote, such as ``f"``, ``F'``, ``fr"``, or #: ``f"""``. start: str = 'f"' #: The trailing quote. This must match the type of quote used in ``start``. end: Literal['"', "'", '"""', "'''"] = '"' lpar: Sequence[LeftParen] = () #: Sequence of parenthesis for precidence dictation. rpar: Sequence[RightParen] = () def _validate(self) -> None: super(FormattedString, self)._validate() # Validate any prefix prefix = self.prefix if prefix not in ("f", "fr", "rf"): raise CSTValidationError("Invalid f-string prefix.") # Validate wrapping quotes starttoken = self.start[len(prefix) :] if starttoken != self.end: raise CSTValidationError("f-string must have matching enclosing quotes.") # Validate valid wrapping quote usage if starttoken not in ('"', "'", '"""', "'''"): raise CSTValidationError("Invalid f-string enclosing quotes.") def prefix(self) -> str: """ Returns the string's prefix, if any exists. The prefix can be ``f``, ``fr``, or ``rf``. """ prefix = "" for c in self.start: if c in ['"', "'"]: break prefix += c return prefix.lower() def quote(self) -> StringQuoteLiteral: """ Returns the quotation used to denote the string. Can be either ``'``, ``"``, ``'''`` or ``\"\"\"``. """ return self.end def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "FormattedString": return FormattedString( lpar=visit_sequence(self, "lpar", self.lpar, visitor), start=self.start, parts=visit_sequence(self, "parts", self.parts, visitor), end=self.end, rpar=visit_sequence(self, "rpar", self.rpar, visitor), ) def _codegen_impl(self, state: CodegenState) -> None: with self._parenthesize(state): state.add_token(self.start) for part in self.parts: part._codegen(state) state.add_token(self.end) ParserConfig = config_mod.ParserConfig class WithLeadingWhitespace(Generic[_T]): value: _T whitespace_before: WhitespaceState def convert_fstring( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: start, *content, end = children return WithLeadingWhitespace( FormattedString(start=start.string, parts=tuple(content), end=end.string), start.whitespace_before, )
null
4,902
import re import typing from tokenize import ( Floatnumber as FLOATNUMBER_RE, Imagnumber as IMAGNUMBER_RE, Intnumber as INTNUMBER_RE, ) from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Arg, Asynchronous, Attribute, Await, BinaryOperation, BooleanOperation, Call, Comparison, ComparisonTarget, CompFor, CompIf, ConcatenatedString, Dict, DictComp, DictElement, Element, Ellipsis, Float, FormattedString, FormattedStringExpression, FormattedStringText, From, GeneratorExp, IfExp, Imaginary, Index, Integer, Lambda, LeftCurlyBrace, LeftParen, LeftSquareBracket, List, ListComp, Name, NamedExpr, Param, Parameters, RightCurlyBrace, RightParen, RightSquareBracket, Set, SetComp, Slice, StarredDictElement, StarredElement, Subscript, SubscriptElement, Tuple, UnaryOperation, Yield, ) from libcst._nodes.op import ( Add, And, AssignEqual, BaseBinaryOp, BaseBooleanOp, BaseCompOp, BitAnd, BitInvert, BitOr, BitXor, Colon, Comma, Divide, Dot, Equal, FloorDivide, GreaterThan, GreaterThanEqual, In, Is, IsNot, LeftShift, LessThan, LessThanEqual, MatrixMultiply, Minus, Modulo, Multiply, Not, NotEqual, NotIn, Or, Plus, Power, RightShift, Subtract, ) from libcst._nodes.whitespace import SimpleWhitespace from libcst._parser.custom_itertools import grouper from libcst._parser.production_decorator import with_production from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import ( ArglistPartial, AttributePartial, CallPartial, FormattedStringConversionPartial, FormattedStringFormatSpecPartial, SlicePartial, SubscriptPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace class FormattedStringText(BaseFormattedStringContent): """ Part of a :class:`FormattedString` that is not inside curly braces (``{`` or ``}``). For example, in:: f"ab{cd}ef" ``ab`` and ``ef`` are :class:`FormattedStringText` nodes, but ``{cd}`` is a :class:`FormattedStringExpression`. """ #: The raw string value, including any escape characters present in the source #: code, not including any enclosing quotes. value: str def _visit_and_replace_children( self, visitor: CSTVisitorT ) -> "FormattedStringText": return FormattedStringText(value=self.value) def _codegen_impl(self, state: CodegenState) -> None: state.add_token(self.value) ParserConfig = config_mod.ParserConfig def convert_fstring_content( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: (child,) = children if isinstance(child, Token): # Construct and return a raw string portion. return FormattedStringText(child.string) else: # Pass the expression up one production. return child
null
4,903
import re import typing from tokenize import ( Floatnumber as FLOATNUMBER_RE, Imagnumber as IMAGNUMBER_RE, Intnumber as INTNUMBER_RE, ) from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Arg, Asynchronous, Attribute, Await, BinaryOperation, BooleanOperation, Call, Comparison, ComparisonTarget, CompFor, CompIf, ConcatenatedString, Dict, DictComp, DictElement, Element, Ellipsis, Float, FormattedString, FormattedStringExpression, FormattedStringText, From, GeneratorExp, IfExp, Imaginary, Index, Integer, Lambda, LeftCurlyBrace, LeftParen, LeftSquareBracket, List, ListComp, Name, NamedExpr, Param, Parameters, RightCurlyBrace, RightParen, RightSquareBracket, Set, SetComp, Slice, StarredDictElement, StarredElement, Subscript, SubscriptElement, Tuple, UnaryOperation, Yield, ) from libcst._nodes.op import ( Add, And, AssignEqual, BaseBinaryOp, BaseBooleanOp, BaseCompOp, BitAnd, BitInvert, BitOr, BitXor, Colon, Comma, Divide, Dot, Equal, FloorDivide, GreaterThan, GreaterThanEqual, In, Is, IsNot, LeftShift, LessThan, LessThanEqual, MatrixMultiply, Minus, Modulo, Multiply, Not, NotEqual, NotIn, Or, Plus, Power, RightShift, Subtract, ) from libcst._nodes.whitespace import SimpleWhitespace from libcst._parser.custom_itertools import grouper from libcst._parser.production_decorator import with_production from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import ( ArglistPartial, AttributePartial, CallPartial, FormattedStringConversionPartial, FormattedStringFormatSpecPartial, SlicePartial, SubscriptPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace ParserConfig = config_mod.ParserConfig class FormattedStringConversionPartial: value: str whitespace_before: WhitespaceState def convert_fstring_conversion( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: exclaim, name = children # There cannot be a space between the two tokens, so no need to preserve this. return FormattedStringConversionPartial(name.string, exclaim.whitespace_before)
null
4,904
import re import typing from tokenize import ( Floatnumber as FLOATNUMBER_RE, Imagnumber as IMAGNUMBER_RE, Intnumber as INTNUMBER_RE, ) from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Arg, Asynchronous, Attribute, Await, BinaryOperation, BooleanOperation, Call, Comparison, ComparisonTarget, CompFor, CompIf, ConcatenatedString, Dict, DictComp, DictElement, Element, Ellipsis, Float, FormattedString, FormattedStringExpression, FormattedStringText, From, GeneratorExp, IfExp, Imaginary, Index, Integer, Lambda, LeftCurlyBrace, LeftParen, LeftSquareBracket, List, ListComp, Name, NamedExpr, Param, Parameters, RightCurlyBrace, RightParen, RightSquareBracket, Set, SetComp, Slice, StarredDictElement, StarredElement, Subscript, SubscriptElement, Tuple, UnaryOperation, Yield, ) from libcst._nodes.op import ( Add, And, AssignEqual, BaseBinaryOp, BaseBooleanOp, BaseCompOp, BitAnd, BitInvert, BitOr, BitXor, Colon, Comma, Divide, Dot, Equal, FloorDivide, GreaterThan, GreaterThanEqual, In, Is, IsNot, LeftShift, LessThan, LessThanEqual, MatrixMultiply, Minus, Modulo, Multiply, Not, NotEqual, NotIn, Or, Plus, Power, RightShift, Subtract, ) from libcst._nodes.whitespace import SimpleWhitespace from libcst._parser.custom_itertools import grouper from libcst._parser.production_decorator import with_production from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import ( ArglistPartial, AttributePartial, CallPartial, FormattedStringConversionPartial, FormattedStringFormatSpecPartial, SlicePartial, SubscriptPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace class AssignEqual(_BaseOneTokenOp): """ Used by :class:`AnnAssign` to denote a single equal character when doing an assignment on top of a type annotation. Also used by :class:`Param` and :class:`Arg` to denote assignment of a default value, and by :class:`FormattedStringExpression` to denote usage of self-documenting expressions. """ #: Any space that appears directly before this equal sign. whitespace_before: BaseParenthesizableWhitespace = SimpleWhitespace.field(" ") #: Any space that appears directly after this equal sign. whitespace_after: BaseParenthesizableWhitespace = SimpleWhitespace.field(" ") def _get_token(self) -> str: return "=" ParserConfig = config_mod.ParserConfig parse_parenthesizable_whitespace = mod.parse_parenthesizable_whitespace def convert_fstring_equality( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: (equal,) = children return AssignEqual( whitespace_before=parse_parenthesizable_whitespace( config, equal.whitespace_before ), whitespace_after=parse_parenthesizable_whitespace( config, equal.whitespace_after ), )
null
4,905
import re import typing from tokenize import ( Floatnumber as FLOATNUMBER_RE, Imagnumber as IMAGNUMBER_RE, Intnumber as INTNUMBER_RE, ) from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Arg, Asynchronous, Attribute, Await, BinaryOperation, BooleanOperation, Call, Comparison, ComparisonTarget, CompFor, CompIf, ConcatenatedString, Dict, DictComp, DictElement, Element, Ellipsis, Float, FormattedString, FormattedStringExpression, FormattedStringText, From, GeneratorExp, IfExp, Imaginary, Index, Integer, Lambda, LeftCurlyBrace, LeftParen, LeftSquareBracket, List, ListComp, Name, NamedExpr, Param, Parameters, RightCurlyBrace, RightParen, RightSquareBracket, Set, SetComp, Slice, StarredDictElement, StarredElement, Subscript, SubscriptElement, Tuple, UnaryOperation, Yield, ) from libcst._nodes.op import ( Add, And, AssignEqual, BaseBinaryOp, BaseBooleanOp, BaseCompOp, BitAnd, BitInvert, BitOr, BitXor, Colon, Comma, Divide, Dot, Equal, FloorDivide, GreaterThan, GreaterThanEqual, In, Is, IsNot, LeftShift, LessThan, LessThanEqual, MatrixMultiply, Minus, Modulo, Multiply, Not, NotEqual, NotIn, Or, Plus, Power, RightShift, Subtract, ) from libcst._nodes.whitespace import SimpleWhitespace from libcst._parser.custom_itertools import grouper from libcst._parser.production_decorator import with_production from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import ( ArglistPartial, AttributePartial, CallPartial, FormattedStringConversionPartial, FormattedStringFormatSpecPartial, SlicePartial, SubscriptPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace class FormattedStringExpression(BaseFormattedStringContent): def _validate(self) -> None: def _visit_and_replace_children( self, visitor: CSTVisitorT ) -> "FormattedStringExpression": def _codegen_impl(self, state: CodegenState) -> None: class AssignEqual(_BaseOneTokenOp): def _get_token(self) -> str: class SimpleWhitespace(BaseParenthesizableWhitespace, BaseValueToken): def _validate(self) -> None: def empty(self) -> bool: ParserConfig = config_mod.ParserConfig class FormattedStringConversionPartial: parse_parenthesizable_whitespace = mod.parse_parenthesizable_whitespace def convert_fstring_expr( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: openbrkt, testlist, *conversions, closebrkt = children # Extract any optional equality (self-debugging expressions) if len(conversions) > 0 and isinstance(conversions[0], AssignEqual): equal = conversions[0] conversions = conversions[1:] else: equal = None # Extract any optional conversion if len(conversions) > 0 and isinstance( conversions[0], FormattedStringConversionPartial ): conversion = conversions[0].value conversions = conversions[1:] else: conversion = None # Extract any optional format spec if len(conversions) > 0: format_spec = conversions[0].values else: format_spec = None # Fix up any spacing issue we find due to the fact that the equal can # have whitespace and is also at the end of the expression. if equal is not None: whitespace_after_expression = SimpleWhitespace("") else: whitespace_after_expression = parse_parenthesizable_whitespace( config, children[2].whitespace_before ) return FormattedStringExpression( whitespace_before_expression=parse_parenthesizable_whitespace( config, testlist.whitespace_before ), expression=testlist.value, equal=equal, whitespace_after_expression=whitespace_after_expression, conversion=conversion, format_spec=format_spec, )
null
4,906
import re import typing from tokenize import ( Floatnumber as FLOATNUMBER_RE, Imagnumber as IMAGNUMBER_RE, Intnumber as INTNUMBER_RE, ) from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Arg, Asynchronous, Attribute, Await, BinaryOperation, BooleanOperation, Call, Comparison, ComparisonTarget, CompFor, CompIf, ConcatenatedString, Dict, DictComp, DictElement, Element, Ellipsis, Float, FormattedString, FormattedStringExpression, FormattedStringText, From, GeneratorExp, IfExp, Imaginary, Index, Integer, Lambda, LeftCurlyBrace, LeftParen, LeftSquareBracket, List, ListComp, Name, NamedExpr, Param, Parameters, RightCurlyBrace, RightParen, RightSquareBracket, Set, SetComp, Slice, StarredDictElement, StarredElement, Subscript, SubscriptElement, Tuple, UnaryOperation, Yield, ) from libcst._nodes.op import ( Add, And, AssignEqual, BaseBinaryOp, BaseBooleanOp, BaseCompOp, BitAnd, BitInvert, BitOr, BitXor, Colon, Comma, Divide, Dot, Equal, FloorDivide, GreaterThan, GreaterThanEqual, In, Is, IsNot, LeftShift, LessThan, LessThanEqual, MatrixMultiply, Minus, Modulo, Multiply, Not, NotEqual, NotIn, Or, Plus, Power, RightShift, Subtract, ) from libcst._nodes.whitespace import SimpleWhitespace from libcst._parser.custom_itertools import grouper from libcst._parser.production_decorator import with_production from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import ( ArglistPartial, AttributePartial, CallPartial, FormattedStringConversionPartial, FormattedStringFormatSpecPartial, SlicePartial, SubscriptPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace ParserConfig = config_mod.ParserConfig class FormattedStringFormatSpecPartial: values: Sequence[BaseFormattedStringContent] whitespace_before: WhitespaceState def convert_fstring_format_spec( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: colon, *content = children return FormattedStringFormatSpecPartial(tuple(content), colon.whitespace_before)
null
4,907
import re import typing from tokenize import ( Floatnumber as FLOATNUMBER_RE, Imagnumber as IMAGNUMBER_RE, Intnumber as INTNUMBER_RE, ) from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Arg, Asynchronous, Attribute, Await, BinaryOperation, BooleanOperation, Call, Comparison, ComparisonTarget, CompFor, CompIf, ConcatenatedString, Dict, DictComp, DictElement, Element, Ellipsis, Float, FormattedString, FormattedStringExpression, FormattedStringText, From, GeneratorExp, IfExp, Imaginary, Index, Integer, Lambda, LeftCurlyBrace, LeftParen, LeftSquareBracket, List, ListComp, Name, NamedExpr, Param, Parameters, RightCurlyBrace, RightParen, RightSquareBracket, Set, SetComp, Slice, StarredDictElement, StarredElement, Subscript, SubscriptElement, Tuple, UnaryOperation, Yield, ) from libcst._nodes.op import ( Add, And, AssignEqual, BaseBinaryOp, BaseBooleanOp, BaseCompOp, BitAnd, BitInvert, BitOr, BitXor, Colon, Comma, Divide, Dot, Equal, FloorDivide, GreaterThan, GreaterThanEqual, In, Is, IsNot, LeftShift, LessThan, LessThanEqual, MatrixMultiply, Minus, Modulo, Multiply, Not, NotEqual, NotIn, Or, Plus, Power, RightShift, Subtract, ) from libcst._nodes.whitespace import SimpleWhitespace from libcst._parser.custom_itertools import grouper from libcst._parser.production_decorator import with_production from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import ( ArglistPartial, AttributePartial, CallPartial, FormattedStringConversionPartial, FormattedStringFormatSpecPartial, SlicePartial, SubscriptPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace def _convert_testlist_comp( config: ParserConfig, children: typing.Sequence[typing.Any], single_child_is_sequence: bool, sequence_type: typing.Union[ typing.Type[Tuple], typing.Type[List], typing.Type[Set] ], comprehension_type: typing.Union[ typing.Type[GeneratorExp], typing.Type[ListComp], typing.Type[SetComp] ], ) -> typing.Any: # This is either a single-element list, or the second token is a comma, so we're not # in a generator. if len(children) == 1 or isinstance(children[1], Token): return _convert_sequencelike( config, children, single_child_is_sequence, sequence_type ) else: # N.B. The parent node (e.g. atom) is responsible for computing and attaching # whitespace information on any parenthesis, square brackets, or curly braces elt, for_in = children return WithLeadingWhitespace( comprehension_type(elt=elt.value, for_in=for_in, lpar=(), rpar=()), elt.whitespace_before, ) class Tuple(BaseAssignTargetExpression, BaseDelTargetExpression): """ An immutable literal tuple. Tuples are often (but not always) parenthesized. :: Tuple([ Element(Integer("1")), Element(Integer("2")), StarredElement(Name("others")), ]) generates the following code:: (1, 2, *others) """ #: A sequence containing all the :class:`Element` and :class:`StarredElement` nodes #: in the tuple. elements: Sequence[BaseElement] lpar: Sequence[LeftParen] = field(default_factory=lambda: (LeftParen(),)) #: Sequence of parenthesis for precedence dictation. rpar: Sequence[RightParen] = field(default_factory=lambda: (RightParen(),)) def _safe_to_use_with_word_operator(self, position: ExpressionPosition) -> bool: if super(Tuple, self)._safe_to_use_with_word_operator(position): # if we have parenthesis, we're safe. return True # elements[-1] and elements[0] must exist past this point, because # we're not parenthesized, meaning we must have at least one element. elements = self.elements if position == ExpressionPosition.LEFT: last_element = elements[-1] return ( isinstance(last_element.comma, Comma) or ( isinstance(last_element, StarredElement) and len(last_element.rpar) > 0 ) or last_element.value._safe_to_use_with_word_operator(position) ) else: # ExpressionPosition.RIGHT first_element = elements[0] # starred elements are always safe because they begin with ( or * return isinstance( first_element, StarredElement ) or first_element.value._safe_to_use_with_word_operator(position) def _validate(self) -> None: # Paren validation and such super(Tuple, self)._validate() if len(self.elements) == 0: if len(self.lpar) == 0: # assumes len(lpar) == len(rpar), via superclass raise CSTValidationError( "A zero-length tuple must be wrapped in parentheses." ) # Invalid commas aren't possible, because MaybeSentinel will ensure that there # is a comma where required. def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Tuple": return Tuple( lpar=visit_sequence(self, "lpar", self.lpar, visitor), elements=visit_sequence(self, "elements", self.elements, visitor), rpar=visit_sequence(self, "rpar", self.rpar, visitor), ) def _codegen_impl(self, state: CodegenState) -> None: with self._parenthesize(state): elements = self.elements if len(elements) == 1: elements[0]._codegen( state, default_comma=True, default_comma_whitespace=False ) else: for idx, el in enumerate(elements): el._codegen( state, default_comma=(idx < len(elements) - 1), default_comma_whitespace=True, ) class GeneratorExp(BaseSimpleComp): """ A generator expression. ``elt`` represents the value yielded for each item in :attr:`CompFor.iter`. All ``for ... in ...`` and ``if ...`` clauses are stored as a recursive :class:`CompFor` data structure inside ``for_in``. """ #: The expression evaluated and yielded during each iteration of the generator. elt: BaseExpression #: The ``for ... in ... if ...`` clause that comes after ``elt``. This may be a #: nested structure for nested comprehensions. See :class:`CompFor` for details. for_in: CompFor lpar: Sequence[LeftParen] = field(default_factory=lambda: (LeftParen(),)) #: Sequence of parentheses for precedence dictation. Generator expressions must #: always be parenthesized. However, if a generator expression is the only argument #: inside a function call, the enclosing :class:`Call` node may own the parentheses #: instead. rpar: Sequence[RightParen] = field(default_factory=lambda: (RightParen(),)) def _safe_to_use_with_word_operator(self, position: ExpressionPosition) -> bool: # Generators are always parenthesized return True # A note about validation: Generators must always be parenthesized, but it's # possible that this Generator node doesn't own those parenthesis (in the case of a # function call with a single generator argument). # # Therefore, there's no useful validation we can do here. In theory, our parent # could do the validation, but there's a ton of potential parents to a Generator, so # it's not worth the effort. def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "GeneratorExp": return GeneratorExp( lpar=visit_sequence(self, "lpar", self.lpar, visitor), elt=visit_required(self, "elt", self.elt, visitor), for_in=visit_required(self, "for_in", self.for_in, visitor), rpar=visit_sequence(self, "rpar", self.rpar, visitor), ) def _codegen_impl(self, state: CodegenState) -> None: with self._parenthesize(state): self.elt._codegen(state) self.for_in._codegen(state) ParserConfig = config_mod.ParserConfig def convert_testlist_comp_tuple( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: return _convert_testlist_comp( config, children, single_child_is_sequence=False, sequence_type=Tuple, comprehension_type=GeneratorExp, )
null
4,908
import re import typing from tokenize import ( Floatnumber as FLOATNUMBER_RE, Imagnumber as IMAGNUMBER_RE, Intnumber as INTNUMBER_RE, ) from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Arg, Asynchronous, Attribute, Await, BinaryOperation, BooleanOperation, Call, Comparison, ComparisonTarget, CompFor, CompIf, ConcatenatedString, Dict, DictComp, DictElement, Element, Ellipsis, Float, FormattedString, FormattedStringExpression, FormattedStringText, From, GeneratorExp, IfExp, Imaginary, Index, Integer, Lambda, LeftCurlyBrace, LeftParen, LeftSquareBracket, List, ListComp, Name, NamedExpr, Param, Parameters, RightCurlyBrace, RightParen, RightSquareBracket, Set, SetComp, Slice, StarredDictElement, StarredElement, Subscript, SubscriptElement, Tuple, UnaryOperation, Yield, ) from libcst._nodes.op import ( Add, And, AssignEqual, BaseBinaryOp, BaseBooleanOp, BaseCompOp, BitAnd, BitInvert, BitOr, BitXor, Colon, Comma, Divide, Dot, Equal, FloorDivide, GreaterThan, GreaterThanEqual, In, Is, IsNot, LeftShift, LessThan, LessThanEqual, MatrixMultiply, Minus, Modulo, Multiply, Not, NotEqual, NotIn, Or, Plus, Power, RightShift, Subtract, ) from libcst._nodes.whitespace import SimpleWhitespace from libcst._parser.custom_itertools import grouper from libcst._parser.production_decorator import with_production from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import ( ArglistPartial, AttributePartial, CallPartial, FormattedStringConversionPartial, FormattedStringFormatSpecPartial, SlicePartial, SubscriptPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace def _convert_testlist_comp( config: ParserConfig, children: typing.Sequence[typing.Any], single_child_is_sequence: bool, sequence_type: typing.Union[ typing.Type[Tuple], typing.Type[List], typing.Type[Set] ], comprehension_type: typing.Union[ typing.Type[GeneratorExp], typing.Type[ListComp], typing.Type[SetComp] ], ) -> typing.Any: # This is either a single-element list, or the second token is a comma, so we're not # in a generator. if len(children) == 1 or isinstance(children[1], Token): return _convert_sequencelike( config, children, single_child_is_sequence, sequence_type ) else: # N.B. The parent node (e.g. atom) is responsible for computing and attaching # whitespace information on any parenthesis, square brackets, or curly braces elt, for_in = children return WithLeadingWhitespace( comprehension_type(elt=elt.value, for_in=for_in, lpar=(), rpar=()), elt.whitespace_before, ) class List(BaseList, BaseAssignTargetExpression, BaseDelTargetExpression): """ A mutable literal list. :: List([ Element(Integer("1")), Element(Integer("2")), StarredElement(Name("others")), ]) generates the following code:: [1, 2, *others] List comprehensions are represented with a :class:`ListComp` node. """ #: A sequence containing all the :class:`Element` and :class:`StarredElement` nodes #: in the list. elements: Sequence[BaseElement] lbracket: LeftSquareBracket = LeftSquareBracket.field() #: Brackets surrounding the list. rbracket: RightSquareBracket = RightSquareBracket.field() lpar: Sequence[LeftParen] = () #: Sequence of parenthesis for precedence dictation. rpar: Sequence[RightParen] = () def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "List": return List( lpar=visit_sequence(self, "lpar", self.lpar, visitor), lbracket=visit_required(self, "lbracket", self.lbracket, visitor), elements=visit_sequence(self, "elements", self.elements, visitor), rbracket=visit_required(self, "rbracket", self.rbracket, visitor), rpar=visit_sequence(self, "rpar", self.rpar, visitor), ) def _codegen_impl(self, state: CodegenState) -> None: with self._parenthesize(state), self._bracketize(state): elements = self.elements for idx, el in enumerate(elements): el._codegen( state, default_comma=(idx < len(elements) - 1), default_comma_whitespace=True, ) class ListComp(BaseList, BaseSimpleComp): """ A list comprehension. ``elt`` represents the value stored for each item in :attr:`CompFor.iter`. All ``for ... in ...`` and ``if ...`` clauses are stored as a recursive :class:`CompFor` data structure inside ``for_in``. """ #: The expression evaluated and stored during each iteration of the comprehension. elt: BaseExpression #: The ``for ... in ... if ...`` clause that comes after ``elt``. This may be a #: nested structure for nested comprehensions. See :class:`CompFor` for details. for_in: CompFor lbracket: LeftSquareBracket = LeftSquareBracket.field() #: Brackets surrounding the list comprehension. rbracket: RightSquareBracket = RightSquareBracket.field() lpar: Sequence[LeftParen] = () #: Sequence of parenthesis for precedence dictation. rpar: Sequence[RightParen] = () def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "ListComp": return ListComp( lpar=visit_sequence(self, "lpar", self.lpar, visitor), lbracket=visit_required(self, "lbracket", self.lbracket, visitor), elt=visit_required(self, "elt", self.elt, visitor), for_in=visit_required(self, "for_in", self.for_in, visitor), rbracket=visit_required(self, "rbracket", self.rbracket, visitor), rpar=visit_sequence(self, "rpar", self.rpar, visitor), ) def _codegen_impl(self, state: CodegenState) -> None: with self._parenthesize(state), self._bracketize(state): self.elt._codegen(state) self.for_in._codegen(state) ParserConfig = config_mod.ParserConfig def convert_testlist_comp_list( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: return _convert_testlist_comp( config, children, single_child_is_sequence=True, sequence_type=List, comprehension_type=ListComp, )
null
4,909
import re import typing from tokenize import ( Floatnumber as FLOATNUMBER_RE, Imagnumber as IMAGNUMBER_RE, Intnumber as INTNUMBER_RE, ) from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Arg, Asynchronous, Attribute, Await, BinaryOperation, BooleanOperation, Call, Comparison, ComparisonTarget, CompFor, CompIf, ConcatenatedString, Dict, DictComp, DictElement, Element, Ellipsis, Float, FormattedString, FormattedStringExpression, FormattedStringText, From, GeneratorExp, IfExp, Imaginary, Index, Integer, Lambda, LeftCurlyBrace, LeftParen, LeftSquareBracket, List, ListComp, Name, NamedExpr, Param, Parameters, RightCurlyBrace, RightParen, RightSquareBracket, Set, SetComp, Slice, StarredDictElement, StarredElement, Subscript, SubscriptElement, Tuple, UnaryOperation, Yield, ) from libcst._nodes.op import ( Add, And, AssignEqual, BaseBinaryOp, BaseBooleanOp, BaseCompOp, BitAnd, BitInvert, BitOr, BitXor, Colon, Comma, Divide, Dot, Equal, FloorDivide, GreaterThan, GreaterThanEqual, In, Is, IsNot, LeftShift, LessThan, LessThanEqual, MatrixMultiply, Minus, Modulo, Multiply, Not, NotEqual, NotIn, Or, Plus, Power, RightShift, Subtract, ) from libcst._nodes.whitespace import SimpleWhitespace from libcst._parser.custom_itertools import grouper from libcst._parser.production_decorator import with_production from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import ( ArglistPartial, AttributePartial, CallPartial, FormattedStringConversionPartial, FormattedStringFormatSpecPartial, SlicePartial, SubscriptPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace def _convert_sequencelike( config: ParserConfig, children: typing.Sequence[typing.Any], single_child_is_sequence: bool, sequence_type: typing.Union[ typing.Type[Tuple], typing.Type[List], typing.Type[Set] ], ) -> typing.Any: if not single_child_is_sequence and len(children) == 1: return children[0] # N.B. The parent node (e.g. atom) is responsible for computing and attaching # whitespace information on any parenthesis, square brackets, or curly braces elements = [] for wrapped_expr_or_starred_element, comma_token in grouper(children, 2): expr_or_starred_element = wrapped_expr_or_starred_element.value if comma_token is None: comma = MaybeSentinel.DEFAULT else: comma = Comma( whitespace_before=parse_parenthesizable_whitespace( config, comma_token.whitespace_before ), # Only compute whitespace_after if we're not a trailing comma. # If we're a trailing comma, that whitespace should be consumed by the # TrailingWhitespace, parenthesis, etc. whitespace_after=( parse_parenthesizable_whitespace( config, comma_token.whitespace_after ) if comma_token is not children[-1] else SimpleWhitespace("") ), ) if isinstance(expr_or_starred_element, StarredElement): starred_element = expr_or_starred_element elements.append(starred_element.with_changes(comma=comma)) else: expr = expr_or_starred_element elements.append(Element(value=expr, comma=comma)) # lpar/rpar are the responsibility of our parent return WithLeadingWhitespace( sequence_type(elements, lpar=(), rpar=()), children[0].whitespace_before, ) "dictorsetmaker", ( "( ((test ':' test | '**' expr)" + " (comp_for | (',' (test ':' test | '**' expr))* [','])) |" + "((test | star_expr) " + " (comp_for | (',' (test | star_expr))* [','])) )" ), version=">=3.5", class Tuple(BaseAssignTargetExpression, BaseDelTargetExpression): """ An immutable literal tuple. Tuples are often (but not always) parenthesized. :: Tuple([ Element(Integer("1")), Element(Integer("2")), StarredElement(Name("others")), ]) generates the following code:: (1, 2, *others) """ #: A sequence containing all the :class:`Element` and :class:`StarredElement` nodes #: in the tuple. elements: Sequence[BaseElement] lpar: Sequence[LeftParen] = field(default_factory=lambda: (LeftParen(),)) #: Sequence of parenthesis for precedence dictation. rpar: Sequence[RightParen] = field(default_factory=lambda: (RightParen(),)) def _safe_to_use_with_word_operator(self, position: ExpressionPosition) -> bool: if super(Tuple, self)._safe_to_use_with_word_operator(position): # if we have parenthesis, we're safe. return True # elements[-1] and elements[0] must exist past this point, because # we're not parenthesized, meaning we must have at least one element. elements = self.elements if position == ExpressionPosition.LEFT: last_element = elements[-1] return ( isinstance(last_element.comma, Comma) or ( isinstance(last_element, StarredElement) and len(last_element.rpar) > 0 ) or last_element.value._safe_to_use_with_word_operator(position) ) else: # ExpressionPosition.RIGHT first_element = elements[0] # starred elements are always safe because they begin with ( or * return isinstance( first_element, StarredElement ) or first_element.value._safe_to_use_with_word_operator(position) def _validate(self) -> None: # Paren validation and such super(Tuple, self)._validate() if len(self.elements) == 0: if len(self.lpar) == 0: # assumes len(lpar) == len(rpar), via superclass raise CSTValidationError( "A zero-length tuple must be wrapped in parentheses." ) # Invalid commas aren't possible, because MaybeSentinel will ensure that there # is a comma where required. def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Tuple": return Tuple( lpar=visit_sequence(self, "lpar", self.lpar, visitor), elements=visit_sequence(self, "elements", self.elements, visitor), rpar=visit_sequence(self, "rpar", self.rpar, visitor), ) def _codegen_impl(self, state: CodegenState) -> None: with self._parenthesize(state): elements = self.elements if len(elements) == 1: elements[0]._codegen( state, default_comma=True, default_comma_whitespace=False ) else: for idx, el in enumerate(elements): el._codegen( state, default_comma=(idx < len(elements) - 1), default_comma_whitespace=True, ) ParserConfig = config_mod.ParserConfig def convert_test_or_expr_list( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: # Used by expression statements and assignments. Neither of these cases want to # treat a single child as a sequence. return _convert_sequencelike( config, children, single_child_is_sequence=False, sequence_type=Tuple )
null
4,910
import re import typing from tokenize import ( Floatnumber as FLOATNUMBER_RE, Imagnumber as IMAGNUMBER_RE, Intnumber as INTNUMBER_RE, ) from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Arg, Asynchronous, Attribute, Await, BinaryOperation, BooleanOperation, Call, Comparison, ComparisonTarget, CompFor, CompIf, ConcatenatedString, Dict, DictComp, DictElement, Element, Ellipsis, Float, FormattedString, FormattedStringExpression, FormattedStringText, From, GeneratorExp, IfExp, Imaginary, Index, Integer, Lambda, LeftCurlyBrace, LeftParen, LeftSquareBracket, List, ListComp, Name, NamedExpr, Param, Parameters, RightCurlyBrace, RightParen, RightSquareBracket, Set, SetComp, Slice, StarredDictElement, StarredElement, Subscript, SubscriptElement, Tuple, UnaryOperation, Yield, ) from libcst._nodes.op import ( Add, And, AssignEqual, BaseBinaryOp, BaseBooleanOp, BaseCompOp, BitAnd, BitInvert, BitOr, BitXor, Colon, Comma, Divide, Dot, Equal, FloorDivide, GreaterThan, GreaterThanEqual, In, Is, IsNot, LeftShift, LessThan, LessThanEqual, MatrixMultiply, Minus, Modulo, Multiply, Not, NotEqual, NotIn, Or, Plus, Power, RightShift, Subtract, ) from libcst._nodes.whitespace import SimpleWhitespace from libcst._parser.custom_itertools import grouper from libcst._parser.production_decorator import with_production from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import ( ArglistPartial, AttributePartial, CallPartial, FormattedStringConversionPartial, FormattedStringFormatSpecPartial, SlicePartial, SubscriptPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace def _convert_dict( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: def _convert_set( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: ParserConfig = config_mod.ParserConfig def convert_dictorsetmaker( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: # We'll always have at least one child. `atom_curlybraces` handles empty # dicts. if len(children) > 1 and ( (isinstance(children[1], Token) and children[1].string == ":") or (isinstance(children[0], Token) and children[0].string == "**") ): return _convert_dict(config, children) else: return _convert_set(config, children)
null
4,911
import re import typing from tokenize import ( Floatnumber as FLOATNUMBER_RE, Imagnumber as IMAGNUMBER_RE, Intnumber as INTNUMBER_RE, ) from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Arg, Asynchronous, Attribute, Await, BinaryOperation, BooleanOperation, Call, Comparison, ComparisonTarget, CompFor, CompIf, ConcatenatedString, Dict, DictComp, DictElement, Element, Ellipsis, Float, FormattedString, FormattedStringExpression, FormattedStringText, From, GeneratorExp, IfExp, Imaginary, Index, Integer, Lambda, LeftCurlyBrace, LeftParen, LeftSquareBracket, List, ListComp, Name, NamedExpr, Param, Parameters, RightCurlyBrace, RightParen, RightSquareBracket, Set, SetComp, Slice, StarredDictElement, StarredElement, Subscript, SubscriptElement, Tuple, UnaryOperation, Yield, ) from libcst._nodes.op import ( Add, And, AssignEqual, BaseBinaryOp, BaseBooleanOp, BaseCompOp, BitAnd, BitInvert, BitOr, BitXor, Colon, Comma, Divide, Dot, Equal, FloorDivide, GreaterThan, GreaterThanEqual, In, Is, IsNot, LeftShift, LessThan, LessThanEqual, MatrixMultiply, Minus, Modulo, Multiply, Not, NotEqual, NotIn, Or, Plus, Power, RightShift, Subtract, ) from libcst._nodes.whitespace import SimpleWhitespace from libcst._parser.custom_itertools import grouper from libcst._parser.production_decorator import with_production from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import ( ArglistPartial, AttributePartial, CallPartial, FormattedStringConversionPartial, FormattedStringFormatSpecPartial, SlicePartial, SubscriptPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace class Comma(_BaseOneTokenOp): """ Syntactic trivia used as a separator between subsequent items in various parts of the grammar. Some use-cases are: * :class:`Import` or :class:`ImportFrom`. * :class:`FunctionDef` arguments. * :class:`Tuple`/:class:`List`/:class:`Set`/:class:`Dict` elements. """ #: Any space that appears directly before this comma. whitespace_before: BaseParenthesizableWhitespace = SimpleWhitespace.field("") #: Any space that appears directly after this comma. whitespace_after: BaseParenthesizableWhitespace = SimpleWhitespace.field("") def _get_token(self) -> str: return "," def grouper(iterable: Iterable[_T], n: int, fillvalue: _T = None) -> Iterator[_T]: "Collect data into fixed-length chunks or blocks" # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx" args = [iter(iterable)] * n return zip_longest(*args, fillvalue=fillvalue) ParserConfig = config_mod.ParserConfig class ArglistPartial: args: Sequence[Arg] parse_parenthesizable_whitespace = mod.parse_parenthesizable_whitespace def convert_arglist( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: args = [] for argument, comma in grouper(children, 2): if comma is None: args.append(argument) else: args.append( argument.with_changes( comma=Comma( whitespace_before=parse_parenthesizable_whitespace( config, comma.whitespace_before ), whitespace_after=parse_parenthesizable_whitespace( config, comma.whitespace_after ), ) ) ) return ArglistPartial(args)
null
4,912
import re import typing from tokenize import ( Floatnumber as FLOATNUMBER_RE, Imagnumber as IMAGNUMBER_RE, Intnumber as INTNUMBER_RE, ) from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Arg, Asynchronous, Attribute, Await, BinaryOperation, BooleanOperation, Call, Comparison, ComparisonTarget, CompFor, CompIf, ConcatenatedString, Dict, DictComp, DictElement, Element, Ellipsis, Float, FormattedString, FormattedStringExpression, FormattedStringText, From, GeneratorExp, IfExp, Imaginary, Index, Integer, Lambda, LeftCurlyBrace, LeftParen, LeftSquareBracket, List, ListComp, Name, NamedExpr, Param, Parameters, RightCurlyBrace, RightParen, RightSquareBracket, Set, SetComp, Slice, StarredDictElement, StarredElement, Subscript, SubscriptElement, Tuple, UnaryOperation, Yield, ) from libcst._nodes.op import ( Add, And, AssignEqual, BaseBinaryOp, BaseBooleanOp, BaseCompOp, BitAnd, BitInvert, BitOr, BitXor, Colon, Comma, Divide, Dot, Equal, FloorDivide, GreaterThan, GreaterThanEqual, In, Is, IsNot, LeftShift, LessThan, LessThanEqual, MatrixMultiply, Minus, Modulo, Multiply, Not, NotEqual, NotIn, Or, Plus, Power, RightShift, Subtract, ) from libcst._nodes.whitespace import SimpleWhitespace from libcst._parser.custom_itertools import grouper from libcst._parser.production_decorator import with_production from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import ( ArglistPartial, AttributePartial, CallPartial, FormattedStringConversionPartial, FormattedStringFormatSpecPartial, SlicePartial, SubscriptPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace ParserConfig = config_mod.ParserConfig def convert_argument( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: (child,) = children return child
null
4,913
import re import typing from tokenize import ( Floatnumber as FLOATNUMBER_RE, Imagnumber as IMAGNUMBER_RE, Intnumber as INTNUMBER_RE, ) from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Arg, Asynchronous, Attribute, Await, BinaryOperation, BooleanOperation, Call, Comparison, ComparisonTarget, CompFor, CompIf, ConcatenatedString, Dict, DictComp, DictElement, Element, Ellipsis, Float, FormattedString, FormattedStringExpression, FormattedStringText, From, GeneratorExp, IfExp, Imaginary, Index, Integer, Lambda, LeftCurlyBrace, LeftParen, LeftSquareBracket, List, ListComp, Name, NamedExpr, Param, Parameters, RightCurlyBrace, RightParen, RightSquareBracket, Set, SetComp, Slice, StarredDictElement, StarredElement, Subscript, SubscriptElement, Tuple, UnaryOperation, Yield, ) from libcst._nodes.op import ( Add, And, AssignEqual, BaseBinaryOp, BaseBooleanOp, BaseCompOp, BitAnd, BitInvert, BitOr, BitXor, Colon, Comma, Divide, Dot, Equal, FloorDivide, GreaterThan, GreaterThanEqual, In, Is, IsNot, LeftShift, LessThan, LessThanEqual, MatrixMultiply, Minus, Modulo, Multiply, Not, NotEqual, NotIn, Or, Plus, Power, RightShift, Subtract, ) from libcst._nodes.whitespace import SimpleWhitespace from libcst._parser.custom_itertools import grouper from libcst._parser.production_decorator import with_production from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import ( ArglistPartial, AttributePartial, CallPartial, FormattedStringConversionPartial, FormattedStringFormatSpecPartial, SlicePartial, SubscriptPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace def convert_namedexpr_test( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: test, *assignment = children if len(assignment) == 0: return test # Convert all of the operations that have no precedence in a loop (walrus, value) = assignment return WithLeadingWhitespace( NamedExpr( target=test.value, whitespace_before_walrus=parse_parenthesizable_whitespace( config, walrus.whitespace_before ), whitespace_after_walrus=parse_parenthesizable_whitespace( config, walrus.whitespace_after ), value=value.value, ), test.whitespace_before, ) class Arg(CSTNode): """ A single argument to a :class:`Call`. This supports named keyword arguments in the form of ``keyword=value`` and variable argument expansion using ``*args`` or ``**kwargs`` syntax. """ #: The argument expression itself, not including a preceding keyword, or any of #: the surrounding the value, like a comma or asterisks. value: BaseExpression #: Optional keyword for the argument. keyword: Optional[Name] = None #: The equal sign used to denote assignment if there is a keyword. equal: Union[AssignEqual, MaybeSentinel] = MaybeSentinel.DEFAULT #: Any trailing comma. comma: Union[Comma, MaybeSentinel] = MaybeSentinel.DEFAULT #: A string with zero, one, or two asterisks appearing before the name. These are #: expanded into variable number of positional or keyword arguments. star: Literal["", "*", "**"] = "" #: Whitespace after the ``star`` (if it exists), but before the ``keyword`` or #: ``value`` (if no keyword is provided). whitespace_after_star: BaseParenthesizableWhitespace = SimpleWhitespace.field("") #: Whitespace after this entire node. The :class:`Comma` node (if it exists) may #: also store some trailing whitespace. whitespace_after_arg: BaseParenthesizableWhitespace = SimpleWhitespace.field("") def _validate(self) -> None: if self.keyword is None and isinstance(self.equal, AssignEqual): raise CSTValidationError( "Must have a keyword when specifying an AssignEqual." ) if self.star not in ("", "*", "**"): raise CSTValidationError("Must specify either '', '*' or '**' for star.") if self.star in ("*", "**") and self.keyword is not None: raise CSTValidationError("Cannot specify a star and a keyword together.") def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Arg": return Arg( star=self.star, whitespace_after_star=visit_required( self, "whitespace_after_star", self.whitespace_after_star, visitor ), keyword=visit_optional(self, "keyword", self.keyword, visitor), equal=visit_sentinel(self, "equal", self.equal, visitor), value=visit_required(self, "value", self.value, visitor), comma=visit_sentinel(self, "comma", self.comma, visitor), whitespace_after_arg=visit_required( self, "whitespace_after_arg", self.whitespace_after_arg, visitor ), ) def _codegen_impl(self, state: CodegenState, default_comma: bool = False) -> None: with state.record_syntactic_position(self): state.add_token(self.star) self.whitespace_after_star._codegen(state) keyword = self.keyword if keyword is not None: keyword._codegen(state) equal = self.equal if equal is MaybeSentinel.DEFAULT and self.keyword is not None: state.add_token(" = ") elif isinstance(equal, AssignEqual): equal._codegen(state) self.value._codegen(state) comma = self.comma if comma is MaybeSentinel.DEFAULT and default_comma: state.add_token(", ") elif isinstance(comma, Comma): comma._codegen(state) self.whitespace_after_arg._codegen(state) class GeneratorExp(BaseSimpleComp): """ A generator expression. ``elt`` represents the value yielded for each item in :attr:`CompFor.iter`. All ``for ... in ...`` and ``if ...`` clauses are stored as a recursive :class:`CompFor` data structure inside ``for_in``. """ #: The expression evaluated and yielded during each iteration of the generator. elt: BaseExpression #: The ``for ... in ... if ...`` clause that comes after ``elt``. This may be a #: nested structure for nested comprehensions. See :class:`CompFor` for details. for_in: CompFor lpar: Sequence[LeftParen] = field(default_factory=lambda: (LeftParen(),)) #: Sequence of parentheses for precedence dictation. Generator expressions must #: always be parenthesized. However, if a generator expression is the only argument #: inside a function call, the enclosing :class:`Call` node may own the parentheses #: instead. rpar: Sequence[RightParen] = field(default_factory=lambda: (RightParen(),)) def _safe_to_use_with_word_operator(self, position: ExpressionPosition) -> bool: # Generators are always parenthesized return True # A note about validation: Generators must always be parenthesized, but it's # possible that this Generator node doesn't own those parenthesis (in the case of a # function call with a single generator argument). # # Therefore, there's no useful validation we can do here. In theory, our parent # could do the validation, but there's a ton of potential parents to a Generator, so # it's not worth the effort. def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "GeneratorExp": return GeneratorExp( lpar=visit_sequence(self, "lpar", self.lpar, visitor), elt=visit_required(self, "elt", self.elt, visitor), for_in=visit_required(self, "for_in", self.for_in, visitor), rpar=visit_sequence(self, "rpar", self.rpar, visitor), ) def _codegen_impl(self, state: CodegenState) -> None: with self._parenthesize(state): self.elt._codegen(state) self.for_in._codegen(state) class AssignEqual(_BaseOneTokenOp): """ Used by :class:`AnnAssign` to denote a single equal character when doing an assignment on top of a type annotation. Also used by :class:`Param` and :class:`Arg` to denote assignment of a default value, and by :class:`FormattedStringExpression` to denote usage of self-documenting expressions. """ #: Any space that appears directly before this equal sign. whitespace_before: BaseParenthesizableWhitespace = SimpleWhitespace.field(" ") #: Any space that appears directly after this equal sign. whitespace_after: BaseParenthesizableWhitespace = SimpleWhitespace.field(" ") def _get_token(self) -> str: return "=" ParserConfig = config_mod.ParserConfig class WithLeadingWhitespace(Generic[_T]): value: _T whitespace_before: WhitespaceState parse_parenthesizable_whitespace = mod.parse_parenthesizable_whitespace def convert_arg_assign_comp_for( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: if len(children) == 1: # Simple test (child,) = children return Arg(value=child.value) elif len(children) == 2: elt, for_in = children return Arg(value=GeneratorExp(elt.value, for_in, lpar=(), rpar=())) else: lhs, equal, rhs = children # "key := value" assignment; positional if equal.string == ":=": val = convert_namedexpr_test(config, children) if not isinstance(val, WithLeadingWhitespace): raise Exception( f"convert_namedexpr_test returned {val!r}, not WithLeadingWhitespace" ) return Arg(value=val.value) # "key = value" assignment; keyword argument return Arg( keyword=lhs.value, equal=AssignEqual( whitespace_before=parse_parenthesizable_whitespace( config, equal.whitespace_before ), whitespace_after=parse_parenthesizable_whitespace( config, equal.whitespace_after ), ), value=rhs.value, )
null
4,914
import re import typing from tokenize import ( Floatnumber as FLOATNUMBER_RE, Imagnumber as IMAGNUMBER_RE, Intnumber as INTNUMBER_RE, ) from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Arg, Asynchronous, Attribute, Await, BinaryOperation, BooleanOperation, Call, Comparison, ComparisonTarget, CompFor, CompIf, ConcatenatedString, Dict, DictComp, DictElement, Element, Ellipsis, Float, FormattedString, FormattedStringExpression, FormattedStringText, From, GeneratorExp, IfExp, Imaginary, Index, Integer, Lambda, LeftCurlyBrace, LeftParen, LeftSquareBracket, List, ListComp, Name, NamedExpr, Param, Parameters, RightCurlyBrace, RightParen, RightSquareBracket, Set, SetComp, Slice, StarredDictElement, StarredElement, Subscript, SubscriptElement, Tuple, UnaryOperation, Yield, ) from libcst._nodes.op import ( Add, And, AssignEqual, BaseBinaryOp, BaseBooleanOp, BaseCompOp, BitAnd, BitInvert, BitOr, BitXor, Colon, Comma, Divide, Dot, Equal, FloorDivide, GreaterThan, GreaterThanEqual, In, Is, IsNot, LeftShift, LessThan, LessThanEqual, MatrixMultiply, Minus, Modulo, Multiply, Not, NotEqual, NotIn, Or, Plus, Power, RightShift, Subtract, ) from libcst._nodes.whitespace import SimpleWhitespace from libcst._parser.custom_itertools import grouper from libcst._parser.production_decorator import with_production from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import ( ArglistPartial, AttributePartial, CallPartial, FormattedStringConversionPartial, FormattedStringFormatSpecPartial, SlicePartial, SubscriptPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace class Arg(CSTNode): """ A single argument to a :class:`Call`. This supports named keyword arguments in the form of ``keyword=value`` and variable argument expansion using ``*args`` or ``**kwargs`` syntax. """ #: The argument expression itself, not including a preceding keyword, or any of #: the surrounding the value, like a comma or asterisks. value: BaseExpression #: Optional keyword for the argument. keyword: Optional[Name] = None #: The equal sign used to denote assignment if there is a keyword. equal: Union[AssignEqual, MaybeSentinel] = MaybeSentinel.DEFAULT #: Any trailing comma. comma: Union[Comma, MaybeSentinel] = MaybeSentinel.DEFAULT #: A string with zero, one, or two asterisks appearing before the name. These are #: expanded into variable number of positional or keyword arguments. star: Literal["", "*", "**"] = "" #: Whitespace after the ``star`` (if it exists), but before the ``keyword`` or #: ``value`` (if no keyword is provided). whitespace_after_star: BaseParenthesizableWhitespace = SimpleWhitespace.field("") #: Whitespace after this entire node. The :class:`Comma` node (if it exists) may #: also store some trailing whitespace. whitespace_after_arg: BaseParenthesizableWhitespace = SimpleWhitespace.field("") def _validate(self) -> None: if self.keyword is None and isinstance(self.equal, AssignEqual): raise CSTValidationError( "Must have a keyword when specifying an AssignEqual." ) if self.star not in ("", "*", "**"): raise CSTValidationError("Must specify either '', '*' or '**' for star.") if self.star in ("*", "**") and self.keyword is not None: raise CSTValidationError("Cannot specify a star and a keyword together.") def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Arg": return Arg( star=self.star, whitespace_after_star=visit_required( self, "whitespace_after_star", self.whitespace_after_star, visitor ), keyword=visit_optional(self, "keyword", self.keyword, visitor), equal=visit_sentinel(self, "equal", self.equal, visitor), value=visit_required(self, "value", self.value, visitor), comma=visit_sentinel(self, "comma", self.comma, visitor), whitespace_after_arg=visit_required( self, "whitespace_after_arg", self.whitespace_after_arg, visitor ), ) def _codegen_impl(self, state: CodegenState, default_comma: bool = False) -> None: with state.record_syntactic_position(self): state.add_token(self.star) self.whitespace_after_star._codegen(state) keyword = self.keyword if keyword is not None: keyword._codegen(state) equal = self.equal if equal is MaybeSentinel.DEFAULT and self.keyword is not None: state.add_token(" = ") elif isinstance(equal, AssignEqual): equal._codegen(state) self.value._codegen(state) comma = self.comma if comma is MaybeSentinel.DEFAULT and default_comma: state.add_token(", ") elif isinstance(comma, Comma): comma._codegen(state) self.whitespace_after_arg._codegen(state) ParserConfig = config_mod.ParserConfig parse_parenthesizable_whitespace = mod.parse_parenthesizable_whitespace def convert_star_arg( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: star, test = children return Arg( star=star.string, whitespace_after_star=parse_parenthesizable_whitespace( config, star.whitespace_after ), value=test.value, )
null
4,915
import re import typing from tokenize import ( Floatnumber as FLOATNUMBER_RE, Imagnumber as IMAGNUMBER_RE, Intnumber as INTNUMBER_RE, ) from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Arg, Asynchronous, Attribute, Await, BinaryOperation, BooleanOperation, Call, Comparison, ComparisonTarget, CompFor, CompIf, ConcatenatedString, Dict, DictComp, DictElement, Element, Ellipsis, Float, FormattedString, FormattedStringExpression, FormattedStringText, From, GeneratorExp, IfExp, Imaginary, Index, Integer, Lambda, LeftCurlyBrace, LeftParen, LeftSquareBracket, List, ListComp, Name, NamedExpr, Param, Parameters, RightCurlyBrace, RightParen, RightSquareBracket, Set, SetComp, Slice, StarredDictElement, StarredElement, Subscript, SubscriptElement, Tuple, UnaryOperation, Yield, ) from libcst._nodes.op import ( Add, And, AssignEqual, BaseBinaryOp, BaseBooleanOp, BaseCompOp, BitAnd, BitInvert, BitOr, BitXor, Colon, Comma, Divide, Dot, Equal, FloorDivide, GreaterThan, GreaterThanEqual, In, Is, IsNot, LeftShift, LessThan, LessThanEqual, MatrixMultiply, Minus, Modulo, Multiply, Not, NotEqual, NotIn, Or, Plus, Power, RightShift, Subtract, ) from libcst._nodes.whitespace import SimpleWhitespace from libcst._parser.custom_itertools import grouper from libcst._parser.production_decorator import with_production from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import ( ArglistPartial, AttributePartial, CallPartial, FormattedStringConversionPartial, FormattedStringFormatSpecPartial, SlicePartial, SubscriptPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace class CompFor(CSTNode): """ One ``for`` clause in a :class:`BaseComp`, or a nested hierarchy of ``for`` clauses. Nested loops in comprehensions are difficult to get right, but they can be thought of as a flat representation of nested clauses. ``elt for a in b for c in d if e`` can be thought of as:: for a in b: for c in d: if e: yield elt And that would form the following CST:: ListComp( elt=Name("elt"), for_in=CompFor( target=Name("a"), iter=Name("b"), ifs=[], inner_comp_for=CompFor( target=Name("c"), iter=Name("d"), ifs=[ CompIf( test=Name("e"), ), ], ), ), ) Normal ``for`` statements are provided by :class:`For`. """ #: The target to assign a value to in each iteration of the loop. This is different #: from :attr:`GeneratorExp.elt`, :attr:`ListComp.elt`, :attr:`SetComp.elt`, and #: ``key`` and ``value`` in :class:`DictComp`, because it doesn't directly effect #: the value of resulting generator, list, set, or dict. target: BaseAssignTargetExpression #: The value to iterate over. Every value in ``iter`` is stored in ``target``. iter: BaseExpression #: Zero or more conditional clauses that control this loop. If any of these tests #: fail, the ``target`` item is skipped. #: #: :: #: #: if a if b if c #: #: has similar semantics to:: #: #: if a and b and c ifs: Sequence["CompIf"] = () #: Another :class:`CompFor` node used to form nested loops. Nested comprehensions #: can be useful, but they tend to be difficult to read and write. As a result they #: are uncommon. inner_for_in: Optional["CompFor"] = None #: An optional async modifier that appears before the ``for`` keyword. asynchronous: Optional[Asynchronous] = None #: Whitespace that appears at the beginning of this node, before the ``for`` and #: ``async`` keywords. whitespace_before: BaseParenthesizableWhitespace = SimpleWhitespace.field(" ") #: Whitespace appearing after the ``for`` keyword, but before the ``target``. whitespace_after_for: BaseParenthesizableWhitespace = SimpleWhitespace.field(" ") #: Whitespace appearing after the ``target``, but before the ``in`` keyword. whitespace_before_in: BaseParenthesizableWhitespace = SimpleWhitespace.field(" ") #: Whitespace appearing after the ``in`` keyword, but before the ``iter``. whitespace_after_in: BaseParenthesizableWhitespace = SimpleWhitespace.field(" ") def _validate(self) -> None: if ( self.whitespace_after_for.empty and not self.target._safe_to_use_with_word_operator( ExpressionPosition.RIGHT ) ): raise CSTValidationError( "Must have at least one space after 'for' keyword." ) if ( self.whitespace_before_in.empty and not self.target._safe_to_use_with_word_operator(ExpressionPosition.LEFT) ): raise CSTValidationError( "Must have at least one space before 'in' keyword." ) if ( self.whitespace_after_in.empty and not self.iter._safe_to_use_with_word_operator(ExpressionPosition.RIGHT) ): raise CSTValidationError("Must have at least one space after 'in' keyword.") prev_expr = self.iter for if_clause in self.ifs: if ( if_clause.whitespace_before.empty and not prev_expr._safe_to_use_with_word_operator( ExpressionPosition.LEFT ) ): raise CSTValidationError( "Must have at least one space before 'if' keyword." ) prev_expr = if_clause.test inner_for_in = self.inner_for_in if ( inner_for_in is not None and inner_for_in.whitespace_before.empty and not prev_expr._safe_to_use_with_word_operator(ExpressionPosition.LEFT) ): keyword = "async" if inner_for_in.asynchronous else "for" raise CSTValidationError( f"Must have at least one space before '{keyword}' keyword." ) def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "CompFor": return CompFor( whitespace_before=visit_required( self, "whitespace_before", self.whitespace_before, visitor ), asynchronous=visit_optional( self, "asynchronous", self.asynchronous, visitor ), whitespace_after_for=visit_required( self, "whitespace_after_for", self.whitespace_after_for, visitor ), target=visit_required(self, "target", self.target, visitor), whitespace_before_in=visit_required( self, "whitespace_before_in", self.whitespace_before_in, visitor ), whitespace_after_in=visit_required( self, "whitespace_after_in", self.whitespace_after_in, visitor ), iter=visit_required(self, "iter", self.iter, visitor), ifs=visit_sequence(self, "ifs", self.ifs, visitor), inner_for_in=visit_optional( self, "inner_for_in", self.inner_for_in, visitor ), ) def _codegen_impl(self, state: CodegenState) -> None: self.whitespace_before._codegen(state) asynchronous = self.asynchronous if asynchronous is not None: asynchronous._codegen(state) state.add_token("for") self.whitespace_after_for._codegen(state) self.target._codegen(state) self.whitespace_before_in._codegen(state) state.add_token("in") self.whitespace_after_in._codegen(state) self.iter._codegen(state) ifs = self.ifs for if_clause in ifs: if_clause._codegen(state) inner_for_in = self.inner_for_in if inner_for_in is not None: inner_for_in._codegen(state) ParserConfig = config_mod.ParserConfig parse_parenthesizable_whitespace = mod.parse_parenthesizable_whitespace def convert_sync_comp_for( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: # unpack for_tok, target, in_tok, iter, *trailing = children if len(trailing) and isinstance(trailing[-1], CompFor): *ifs, inner_for_in = trailing else: ifs, inner_for_in = trailing, None return CompFor( target=target.value, iter=iter.value, ifs=ifs, inner_for_in=inner_for_in, whitespace_before=parse_parenthesizable_whitespace( config, for_tok.whitespace_before ), whitespace_after_for=parse_parenthesizable_whitespace( config, for_tok.whitespace_after ), whitespace_before_in=parse_parenthesizable_whitespace( config, in_tok.whitespace_before ), whitespace_after_in=parse_parenthesizable_whitespace( config, in_tok.whitespace_after ), )
null
4,916
import re import typing from tokenize import ( Floatnumber as FLOATNUMBER_RE, Imagnumber as IMAGNUMBER_RE, Intnumber as INTNUMBER_RE, ) from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Arg, Asynchronous, Attribute, Await, BinaryOperation, BooleanOperation, Call, Comparison, ComparisonTarget, CompFor, CompIf, ConcatenatedString, Dict, DictComp, DictElement, Element, Ellipsis, Float, FormattedString, FormattedStringExpression, FormattedStringText, From, GeneratorExp, IfExp, Imaginary, Index, Integer, Lambda, LeftCurlyBrace, LeftParen, LeftSquareBracket, List, ListComp, Name, NamedExpr, Param, Parameters, RightCurlyBrace, RightParen, RightSquareBracket, Set, SetComp, Slice, StarredDictElement, StarredElement, Subscript, SubscriptElement, Tuple, UnaryOperation, Yield, ) from libcst._nodes.op import ( Add, And, AssignEqual, BaseBinaryOp, BaseBooleanOp, BaseCompOp, BitAnd, BitInvert, BitOr, BitXor, Colon, Comma, Divide, Dot, Equal, FloorDivide, GreaterThan, GreaterThanEqual, In, Is, IsNot, LeftShift, LessThan, LessThanEqual, MatrixMultiply, Minus, Modulo, Multiply, Not, NotEqual, NotIn, Or, Plus, Power, RightShift, Subtract, ) from libcst._nodes.whitespace import SimpleWhitespace from libcst._parser.custom_itertools import grouper from libcst._parser.production_decorator import with_production from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import ( ArglistPartial, AttributePartial, CallPartial, FormattedStringConversionPartial, FormattedStringFormatSpecPartial, SlicePartial, SubscriptPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace class Asynchronous(CSTNode): """ Used by asynchronous function definitions, as well as ``async for`` and ``async with``. """ #: Any space that appears directly after this async keyword. whitespace_after: SimpleWhitespace = SimpleWhitespace.field(" ") def _validate(self) -> None: if len(self.whitespace_after.value) < 1: raise CSTValidationError("Must have at least one space after Asynchronous.") def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Asynchronous": return Asynchronous( whitespace_after=visit_required( self, "whitespace_after", self.whitespace_after, visitor ) ) def _codegen_impl(self, state: CodegenState) -> None: with state.record_syntactic_position(self): state.add_token("async") self.whitespace_after._codegen(state) ParserConfig = config_mod.ParserConfig parse_parenthesizable_whitespace = mod.parse_parenthesizable_whitespace def convert_comp_for( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: if len(children) == 1: (sync_comp_for,) = children return sync_comp_for else: (async_tok, sync_comp_for) = children return sync_comp_for.with_changes( # asynchronous steals the `CompFor`'s `whitespace_before`. asynchronous=Asynchronous(whitespace_after=sync_comp_for.whitespace_before), # But, in exchange, `CompFor` gets to keep `async_tok`'s leading # whitespace, because that's now the beginning of the `CompFor`. whitespace_before=parse_parenthesizable_whitespace( config, async_tok.whitespace_before ), )
null
4,917
import re import typing from tokenize import ( Floatnumber as FLOATNUMBER_RE, Imagnumber as IMAGNUMBER_RE, Intnumber as INTNUMBER_RE, ) from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Arg, Asynchronous, Attribute, Await, BinaryOperation, BooleanOperation, Call, Comparison, ComparisonTarget, CompFor, CompIf, ConcatenatedString, Dict, DictComp, DictElement, Element, Ellipsis, Float, FormattedString, FormattedStringExpression, FormattedStringText, From, GeneratorExp, IfExp, Imaginary, Index, Integer, Lambda, LeftCurlyBrace, LeftParen, LeftSquareBracket, List, ListComp, Name, NamedExpr, Param, Parameters, RightCurlyBrace, RightParen, RightSquareBracket, Set, SetComp, Slice, StarredDictElement, StarredElement, Subscript, SubscriptElement, Tuple, UnaryOperation, Yield, ) from libcst._nodes.op import ( Add, And, AssignEqual, BaseBinaryOp, BaseBooleanOp, BaseCompOp, BitAnd, BitInvert, BitOr, BitXor, Colon, Comma, Divide, Dot, Equal, FloorDivide, GreaterThan, GreaterThanEqual, In, Is, IsNot, LeftShift, LessThan, LessThanEqual, MatrixMultiply, Minus, Modulo, Multiply, Not, NotEqual, NotIn, Or, Plus, Power, RightShift, Subtract, ) from libcst._nodes.whitespace import SimpleWhitespace from libcst._parser.custom_itertools import grouper from libcst._parser.production_decorator import with_production from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import ( ArglistPartial, AttributePartial, CallPartial, FormattedStringConversionPartial, FormattedStringFormatSpecPartial, SlicePartial, SubscriptPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace class CompIf(CSTNode): """ A conditional clause in a :class:`CompFor`, used as part of a generator or comprehension expression. If the ``test`` fails, the current element in the :class:`CompFor` will be skipped. """ #: An expression to evaluate. When interpreted, Python will coerce it to a boolean. test: BaseExpression #: Whitespace before the ``if`` keyword. whitespace_before: BaseParenthesizableWhitespace = SimpleWhitespace.field(" ") #: Whitespace after the ``if`` keyword, but before the ``test`` expression. whitespace_before_test: BaseParenthesizableWhitespace = SimpleWhitespace.field(" ") def _validate(self) -> None: if ( self.whitespace_before_test.empty and not self.test._safe_to_use_with_word_operator(ExpressionPosition.RIGHT) ): raise CSTValidationError("Must have at least one space after 'if' keyword.") def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "CompIf": return CompIf( whitespace_before=visit_required( self, "whitespace_before", self.whitespace_before, visitor ), whitespace_before_test=visit_required( self, "whitespace_before_test", self.whitespace_before_test, visitor ), test=visit_required(self, "test", self.test, visitor), ) def _codegen_impl(self, state: CodegenState) -> None: self.whitespace_before._codegen(state) state.add_token("if") self.whitespace_before_test._codegen(state) self.test._codegen(state) ParserConfig = config_mod.ParserConfig parse_parenthesizable_whitespace = mod.parse_parenthesizable_whitespace def convert_comp_if( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: if_tok, test = children return CompIf( test.value, whitespace_before=parse_parenthesizable_whitespace( config, if_tok.whitespace_before ), whitespace_before_test=parse_parenthesizable_whitespace( config, test.whitespace_before ), )
null
4,918
import re import typing from tokenize import ( Floatnumber as FLOATNUMBER_RE, Imagnumber as IMAGNUMBER_RE, Intnumber as INTNUMBER_RE, ) from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Arg, Asynchronous, Attribute, Await, BinaryOperation, BooleanOperation, Call, Comparison, ComparisonTarget, CompFor, CompIf, ConcatenatedString, Dict, DictComp, DictElement, Element, Ellipsis, Float, FormattedString, FormattedStringExpression, FormattedStringText, From, GeneratorExp, IfExp, Imaginary, Index, Integer, Lambda, LeftCurlyBrace, LeftParen, LeftSquareBracket, List, ListComp, Name, NamedExpr, Param, Parameters, RightCurlyBrace, RightParen, RightSquareBracket, Set, SetComp, Slice, StarredDictElement, StarredElement, Subscript, SubscriptElement, Tuple, UnaryOperation, Yield, ) from libcst._nodes.op import ( Add, And, AssignEqual, BaseBinaryOp, BaseBooleanOp, BaseCompOp, BitAnd, BitInvert, BitOr, BitXor, Colon, Comma, Divide, Dot, Equal, FloorDivide, GreaterThan, GreaterThanEqual, In, Is, IsNot, LeftShift, LessThan, LessThanEqual, MatrixMultiply, Minus, Modulo, Multiply, Not, NotEqual, NotIn, Or, Plus, Power, RightShift, Subtract, ) from libcst._nodes.whitespace import SimpleWhitespace from libcst._parser.custom_itertools import grouper from libcst._parser.production_decorator import with_production from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import ( ArglistPartial, AttributePartial, CallPartial, FormattedStringConversionPartial, FormattedStringFormatSpecPartial, SlicePartial, SubscriptPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace class Yield(BaseExpression): """ A yield expression similar to ``yield x`` or ``yield from fun()``. To learn more about the ways that yield can be used in generators, refer to `Python's language reference <https://docs.python.org/3/reference/expressions.html#yieldexpr>`__. """ #: The value yielded from the generator, in the case of a :class:`From` clause, a #: sub-generator to iterate over. value: Optional[Union[BaseExpression, From]] = None lpar: Sequence[LeftParen] = () #: Sequence of parenthesis for precedence dictation. rpar: Sequence[RightParen] = () #: Whitespace after the ``yield`` keyword, but before the ``value``. whitespace_after_yield: Union[ BaseParenthesizableWhitespace, MaybeSentinel ] = MaybeSentinel.DEFAULT def _validate(self) -> None: # Paren rules and such super(Yield, self)._validate() # Our own rules whitespace_after_yield = self.whitespace_after_yield if ( isinstance(whitespace_after_yield, BaseParenthesizableWhitespace) and whitespace_after_yield.empty ): value = self.value if isinstance(value, From): raise CSTValidationError( "Must have at least one space after 'yield' keyword." ) if isinstance( value, BaseExpression ) and not value._safe_to_use_with_word_operator(ExpressionPosition.RIGHT): raise CSTValidationError( "Must have at least one space after 'yield' keyword." ) def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Yield": return Yield( lpar=visit_sequence(self, "lpar", self.lpar, visitor), whitespace_after_yield=visit_sentinel( self, "whitespace_after_yield", self.whitespace_after_yield, visitor ), value=visit_optional(self, "value", self.value, visitor), rpar=visit_sequence(self, "rpar", self.rpar, visitor), ) def _codegen_impl(self, state: CodegenState) -> None: with self._parenthesize(state): state.add_token("yield") whitespace_after_yield = self.whitespace_after_yield if isinstance(whitespace_after_yield, BaseParenthesizableWhitespace): whitespace_after_yield._codegen(state) else: # Only need a space after yield if there is a value to yield. if self.value is not None: state.add_token(" ") value = self.value if isinstance(value, From): value._codegen(state, default_space="") elif value is not None: value._codegen(state) ParserConfig = config_mod.ParserConfig class WithLeadingWhitespace(Generic[_T]): value: _T whitespace_before: WhitespaceState parse_parenthesizable_whitespace = mod.parse_parenthesizable_whitespace def convert_yield_expr( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: if len(children) == 1: # Yielding implicit none (yield_token,) = children yield_node = Yield(value=None) else: # Yielding explicit value (yield_token, yield_arg) = children yield_node = Yield( value=yield_arg.value, whitespace_after_yield=parse_parenthesizable_whitespace( config, yield_arg.whitespace_before ), ) return WithLeadingWhitespace(yield_node, yield_token.whitespace_before)
null
4,919
import re import typing from tokenize import ( Floatnumber as FLOATNUMBER_RE, Imagnumber as IMAGNUMBER_RE, Intnumber as INTNUMBER_RE, ) from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Arg, Asynchronous, Attribute, Await, BinaryOperation, BooleanOperation, Call, Comparison, ComparisonTarget, CompFor, CompIf, ConcatenatedString, Dict, DictComp, DictElement, Element, Ellipsis, Float, FormattedString, FormattedStringExpression, FormattedStringText, From, GeneratorExp, IfExp, Imaginary, Index, Integer, Lambda, LeftCurlyBrace, LeftParen, LeftSquareBracket, List, ListComp, Name, NamedExpr, Param, Parameters, RightCurlyBrace, RightParen, RightSquareBracket, Set, SetComp, Slice, StarredDictElement, StarredElement, Subscript, SubscriptElement, Tuple, UnaryOperation, Yield, ) from libcst._nodes.op import ( Add, And, AssignEqual, BaseBinaryOp, BaseBooleanOp, BaseCompOp, BitAnd, BitInvert, BitOr, BitXor, Colon, Comma, Divide, Dot, Equal, FloorDivide, GreaterThan, GreaterThanEqual, In, Is, IsNot, LeftShift, LessThan, LessThanEqual, MatrixMultiply, Minus, Modulo, Multiply, Not, NotEqual, NotIn, Or, Plus, Power, RightShift, Subtract, ) from libcst._nodes.whitespace import SimpleWhitespace from libcst._parser.custom_itertools import grouper from libcst._parser.production_decorator import with_production from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import ( ArglistPartial, AttributePartial, CallPartial, FormattedStringConversionPartial, FormattedStringFormatSpecPartial, SlicePartial, SubscriptPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace class From(CSTNode): """ A ``from x`` stanza in a :class:`Yield` or :class:`Raise`. """ #: The expression that we are yielding/raising from. item: BaseExpression #: The whitespace at the very start of this node. whitespace_before_from: Union[ BaseParenthesizableWhitespace, MaybeSentinel ] = MaybeSentinel.DEFAULT #: The whitespace after the ``from`` keyword, but before the ``item``. whitespace_after_from: BaseParenthesizableWhitespace = SimpleWhitespace.field(" ") def _validate(self) -> None: if ( isinstance(self.whitespace_after_from, BaseParenthesizableWhitespace) and self.whitespace_after_from.empty and not self.item._safe_to_use_with_word_operator(ExpressionPosition.RIGHT) ): raise CSTValidationError( "Must have at least one space after 'from' keyword." ) def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "From": return From( whitespace_before_from=visit_sentinel( self, "whitespace_before_from", self.whitespace_before_from, visitor ), whitespace_after_from=visit_required( self, "whitespace_after_from", self.whitespace_after_from, visitor ), item=visit_required(self, "item", self.item, visitor), ) def _codegen_impl(self, state: CodegenState, default_space: str = "") -> None: whitespace_before_from = self.whitespace_before_from if isinstance(whitespace_before_from, BaseParenthesizableWhitespace): whitespace_before_from._codegen(state) else: state.add_token(default_space) with state.record_syntactic_position(self): state.add_token("from") self.whitespace_after_from._codegen(state) self.item._codegen(state) ParserConfig = config_mod.ParserConfig class WithLeadingWhitespace(Generic[_T]): value: _T whitespace_before: WhitespaceState parse_parenthesizable_whitespace = mod.parse_parenthesizable_whitespace def convert_yield_arg( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: if len(children) == 1: # Just a regular testlist, pass it up (child,) = children return child else: # Its a yield from (from_token, test) = children return WithLeadingWhitespace( From( item=test.value, whitespace_after_from=parse_parenthesizable_whitespace( config, test.whitespace_before ), ), from_token.whitespace_before, )
null
4,920
from typing import Any, Sequence from libcst._nodes.module import Module from libcst._nodes.whitespace import NEWLINE_RE from libcst._parser.production_decorator import with_production from libcst._parser.types.config import ParserConfig class Module(CSTNode): """ Contains some top-level information inferred from the file letting us set correct defaults when printing the tree about global formatting rules. All code parsed with :func:`parse_module` will be encapsulated in a module. """ #: A list of zero or more statements that make up this module. body: Sequence[Union[SimpleStatementLine, BaseCompoundStatement]] #: Normally any whitespace/comments are assigned to the next node visited, but #: :class:`Module` is a special case, and comments at the top of the file tend #: to refer to the module itself, so we assign them to the :class:`Module` #: instead of the first statement in the body. header: Sequence[EmptyLine] = () #: Any trailing whitespace/comments found after the last statement. footer: Sequence[EmptyLine] = () #: The file's encoding format. When parsing a ``bytes`` object, this value may be #: inferred from the contents of the parsed source code. When parsing a ``str``, #: this value defaults to ``"utf-8"``. #: #: This value affects how :attr:`bytes` encodes the source code. encoding: str = "utf-8" #: The indentation of the file, expressed as a series of tabs and/or spaces. This #: value is inferred from the contents of the parsed source code by default. default_indent: str = " " * 4 #: The newline of the file, expressed as ``\n``, ``\r\n``, or ``\r``. This value is #: inferred from the contents of the parsed source code by default. default_newline: str = "\n" #: Whether the module has a trailing newline or not. has_trailing_newline: bool = True def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Module": return Module( header=visit_sequence(self, "header", self.header, visitor), body=visit_body_sequence(self, "body", self.body, visitor), footer=visit_sequence(self, "footer", self.footer, visitor), encoding=self.encoding, default_indent=self.default_indent, default_newline=self.default_newline, has_trailing_newline=self.has_trailing_newline, ) def visit(self: _ModuleSelfT, visitor: CSTVisitorT) -> _ModuleSelfT: """ Returns the result of running a visitor over this module. :class:`Module` overrides the default visitor entry point to resolve metadata dependencies declared by 'visitor'. """ result = super(Module, self).visit(visitor) if isinstance(result, RemovalSentinel): return self.with_changes(body=(), header=(), footer=()) else: # is a Module return cast(_ModuleSelfT, result) def _codegen_impl(self, state: CodegenState) -> None: for h in self.header: h._codegen(state) for stmt in self.body: stmt._codegen(state) for f in self.footer: f._codegen(state) if self.has_trailing_newline: if len(state.tokens) == 0: # There was nothing in the header, footer, or body. Just add a newline # to preserve the trailing newline. state.add_token(state.default_newline) else: # has_trailing_newline is false state.pop_trailing_newline() def code(self) -> str: """ The string representation of this module, respecting the inferred indentation and newline type. """ return self.code_for_node(self) def bytes(self) -> builtin_bytes: """ The bytes representation of this module, respecting the inferred indentation and newline type, using the current encoding. """ return self.code.encode(self.encoding) def code_for_node(self, node: CSTNode) -> str: """ Generates the code for the given node in the context of this module. This is a method of Module, not CSTNode, because we need to know the module's default indentation and newline formats. """ state = CodegenState( default_indent=self.default_indent, default_newline=self.default_newline ) node._codegen(state) return "".join(state.tokens) def config_for_parsing(self) -> "PartialParserConfig": """ Generates a parser config appropriate for passing to a :func:`parse_expression` or :func:`parse_statement` call. This is useful when using either parser function to generate code from a string template. By using a generated parser config instead of the default, you can guarantee that trees generated from both statement and expression strings have the same inferred defaults for things like newlines, indents and similar:: module = cst.parse_module("pass\\n") expression = cst.parse_expression("1 + 2", config=module.config_for_parsing) """ from libcst._parser.types.config import PartialParserConfig return PartialParserConfig( encoding=self.encoding, default_indent=self.default_indent, default_newline=self.default_newline, ) def get_docstring(self, clean: bool = True) -> Optional[str]: """ Returns a :func:`inspect.cleandoc` cleaned docstring if the docstring is available, ``None`` otherwise. """ return get_docstring_impl(self.body, clean) NEWLINE_RE: Pattern[str] = re.compile(r"\r\n?|\n", re.UNICODE) ParserConfig = config_mod.ParserConfig def convert_file_input(config: ParserConfig, children: Sequence[Any]) -> Any: *body, footer = children if len(body) == 0: # If there's no body, the header and footer are ambiguous. The header is more # important, and should own the EmptyLine nodes instead of the footer. header = footer footer = () if ( len(config.lines) == 2 and NEWLINE_RE.fullmatch(config.lines[0]) and config.lines[1] == "" ): # This is an empty file (not even a comment), so special-case this to an # empty list instead of a single dummy EmptyLine (which is what we'd # normally parse). header = () else: # Steal the leading lines from the first statement, and move them into the # header. first_stmt = body[0] header = first_stmt.leading_lines body[0] = first_stmt.with_changes(leading_lines=()) return Module( header=header, body=body, footer=footer, encoding=config.encoding, default_indent=config.default_indent, default_newline=config.default_newline, has_trailing_newline=config.has_trailing_newline, )
null
4,921
import abc from dataclasses import asdict, dataclass from typing import Any, FrozenSet, Mapping, Sequence from libcst._parser.parso.utils import PythonVersionInfo class ParserConfig(BaseWhitespaceParserConfig): """ An internal configuration object that the python parser passes around. These values are global to the parsed code and should not change during the lifetime of the parser object. """ lines: Sequence[str] encoding: str default_indent: str default_newline: str has_trailing_newline: bool version: PythonVersionInfo future_imports: FrozenSet[str] The provided code snippet includes necessary dependencies for implementing the `parser_config_asdict` function. Write a Python function `def parser_config_asdict(config: ParserConfig) -> Mapping[str, Any]` to solve the following problem: An internal helper function used by unit tests to compare configs. Here is the function: def parser_config_asdict(config: ParserConfig) -> Mapping[str, Any]: """ An internal helper function used by unit tests to compare configs. """ return asdict(config)
An internal helper function used by unit tests to compare configs.
4,922
import codecs import re import sys from dataclasses import dataclass, field, fields from enum import Enum from typing import Any, Callable, FrozenSet, List, Mapping, Optional, Pattern, Union from libcst._add_slots import add_slots from libcst._nodes.whitespace import NEWLINE_RE from libcst._parser.parso.utils import parse_version_string, PythonVersionInfo KNOWN_PYTHON_VERSION_STRINGS = ["3.0", "3.1", "3.3", "3.5", "3.6", "3.7", "3.8"] class PythonVersionInfo: major: int minor: int def __gt__(self, other: Union["PythonVersionInfo", Tuple[int, int]]) -> bool: if isinstance(other, tuple): if len(other) != 2: raise ValueError("Can only compare to tuples of length 2.") return (self.major, self.minor) > other return (self.major, self.minor) > (other.major, other.minor) def __ge__(self, other: Union["PythonVersionInfo", Tuple[int, int]]) -> bool: return self.__gt__(other) or self.__eq__(other) def __lt__(self, other: Union["PythonVersionInfo", Tuple[int, int]]) -> bool: if isinstance(other, tuple): if len(other) != 2: raise ValueError("Can only compare to tuples of length 2.") return (self.major, self.minor) < other return (self.major, self.minor) < (other.major, other.minor) def __le__(self, other: Union["PythonVersionInfo", Tuple[int, int]]) -> bool: return self.__lt__(other) or self.__eq__(other) def __eq__(self, other: Union["PythonVersionInfo", Tuple[int, int]]) -> bool: if isinstance(other, tuple): if len(other) != 2: raise ValueError("Can only compare to tuples of length 2.") return (self.major, self.minor) == other return (self.major, self.minor) == (other.major, other.minor) def __ne__(self, other: Union["PythonVersionInfo", Tuple[int, int]]) -> bool: return not self.__eq__(other) def __hash__(self) -> int: return hash((self.major, self.minor)) def parse_version_string(version: Optional[str] = None) -> PythonVersionInfo: """ Checks for a valid version number (e.g. `3.2` or `2.7.1` or `3`) and returns a corresponding version info that is always two characters long in decimal. """ if version is None: version = "%s.%s" % sys.version_info[:2] return _parse_version(version) def _pick_compatible_python_version(version: Optional[str] = None) -> PythonVersionInfo: max_version = parse_version_string(version) for v in KNOWN_PYTHON_VERSION_STRINGS[::-1]: tmp = parse_version_string(v) if tmp <= max_version: return tmp raise ValueError( f"No version found older than {version} ({max_version}) while " + f"running on {sys.version_info}" )
null
4,923
import collections.abc import inspect import re from abc import ABCMeta from dataclasses import dataclass, fields from enum import auto, Enum from typing import ( Callable, cast, Dict, Generic, Iterator, List, Mapping, NoReturn, Optional, Pattern, Sequence, Tuple, Type, TypeVar, Union, ) import libcst import libcst.metadata as meta from libcst import FlattenSentinel, MaybeSentinel, RemovalSentinel from libcst._metadata_dependent import LazyValue class DoNotCareSentinel(Enum): """ A sentinel that is used in matcher classes to indicate that a caller does not care what this value is. We recommend that you do not use this directly, and instead use the :func:`DoNotCare` helper. You do not need to use this for concrete matcher attributes since :func:`DoNotCare` is already the default. """ DEFAULT = auto() def __repr__(self) -> str: return "DoNotCare()" The provided code snippet includes necessary dependencies for implementing the `DoNotCare` function. Write a Python function `def DoNotCare() -> DoNotCareSentinel` to solve the following problem: Used when you want to match exactly one node, but you do not care what node it is. Useful inside sequences such as a :class:`libcst.matchers.Call`'s args attribte. You do not need to use this for concrete matcher attributes since :func:`DoNotCare` is already the default. For example, the following matcher would match against any function calls with three arguments, regardless of the arguments themselves and regardless of the function name that we were calling:: m.Call(args=[m.DoNotCare(), m.DoNotCare(), m.DoNotCare()]) Here is the function: def DoNotCare() -> DoNotCareSentinel: """ Used when you want to match exactly one node, but you do not care what node it is. Useful inside sequences such as a :class:`libcst.matchers.Call`'s args attribte. You do not need to use this for concrete matcher attributes since :func:`DoNotCare` is already the default. For example, the following matcher would match against any function calls with three arguments, regardless of the arguments themselves and regardless of the function name that we were calling:: m.Call(args=[m.DoNotCare(), m.DoNotCare(), m.DoNotCare()]) """ return DoNotCareSentinel.DEFAULT
Used when you want to match exactly one node, but you do not care what node it is. Useful inside sequences such as a :class:`libcst.matchers.Call`'s args attribte. You do not need to use this for concrete matcher attributes since :func:`DoNotCare` is already the default. For example, the following matcher would match against any function calls with three arguments, regardless of the arguments themselves and regardless of the function name that we were calling:: m.Call(args=[m.DoNotCare(), m.DoNotCare(), m.DoNotCare()])
4,924
import collections.abc import inspect import re from abc import ABCMeta from dataclasses import dataclass, fields from enum import auto, Enum from typing import ( Callable, cast, Dict, Generic, Iterator, List, Mapping, NoReturn, Optional, Pattern, Sequence, Tuple, Type, TypeVar, Union, ) import libcst import libcst.metadata as meta from libcst import FlattenSentinel, MaybeSentinel, RemovalSentinel from libcst._metadata_dependent import LazyValue class MatchIfTrue(Generic[_MatchIfTrueT]): """ Matcher that matches if its child callable returns ``True``. The child callable should take one argument which is the attribute on the LibCST node we are trying to match against. This is useful if you want to do complex logic to determine if an attribute should match or not. One example of this is the :func:`MatchRegex` matcher build on top of :class:`MatchIfTrue` which takes a regular expression and matches any string attribute where a regex match is found. For example, to match on any identifier spelled with the letter ``e``:: m.Name(value=m.MatchIfTrue(lambda value: "e" in value)) This can be used in place of any concrete matcher as long as it is not the root matcher. Calling :func:`matches` directly on a :class:`MatchIfTrue` is redundant since you can just call the child callable directly with the node you are passing to :func:`matches`. """ _func: Callable[[_MatchIfTrueT], bool] def __init__(self, func: Callable[[_MatchIfTrueT], bool]) -> None: self._func = func def func(self) -> Callable[[_MatchIfTrueT], bool]: """ The function that we will call with a LibCST node in order to determine if we match. If the function returns ``True`` then we consider ourselves to be a match. """ return self._func # pyre-fixme[15]: `__or__` overrides method defined in `type` inconsistently. def __or__( self, other: _OtherNodeT ) -> "OneOf[Union[MatchIfTrue[_MatchIfTrueT], _OtherNodeT]]": return OneOf(self, other) def __and__( self, other: _OtherNodeT ) -> "AllOf[Union[MatchIfTrue[_MatchIfTrueT], _OtherNodeT]]": return AllOf(self, other) def __invert__(self) -> "MatchIfTrue[_MatchIfTrueT]": # Construct a wrapped version of MatchIfTrue for typing simplicity. # Without the cast, pyre doesn't seem to think the lambda is valid. return MatchIfTrue(lambda val: not self._func(val)) def __repr__(self) -> str: return f"MatchIfTrue({repr(self._func)})" The provided code snippet includes necessary dependencies for implementing the `MatchRegex` function. Write a Python function `def MatchRegex(regex: Union[str, Pattern[str]]) -> MatchIfTrue[str]` to solve the following problem: Used as a convenience wrapper to :class:`MatchIfTrue` which allows for matching a string attribute against a regex. ``regex`` can be any regular expression string or a compiled ``Pattern``. This uses Python's re module under the hood and is compatible with syntax documented on `docs.python.org <https://docs.python.org/3/library/re.html>`_. For example, to match against any identifier that is at least one character long and only contains alphabetical characters:: m.Name(value=m.MatchRegex(r'[A-Za-z]+')) This can be used in place of any string literal when constructing a concrete matcher. Here is the function: def MatchRegex(regex: Union[str, Pattern[str]]) -> MatchIfTrue[str]: """ Used as a convenience wrapper to :class:`MatchIfTrue` which allows for matching a string attribute against a regex. ``regex`` can be any regular expression string or a compiled ``Pattern``. This uses Python's re module under the hood and is compatible with syntax documented on `docs.python.org <https://docs.python.org/3/library/re.html>`_. For example, to match against any identifier that is at least one character long and only contains alphabetical characters:: m.Name(value=m.MatchRegex(r'[A-Za-z]+')) This can be used in place of any string literal when constructing a concrete matcher. """ def _match_func(value: object) -> bool: if isinstance(value, str): return bool(re.fullmatch(regex, value)) else: return False return MatchIfTrue(_match_func)
Used as a convenience wrapper to :class:`MatchIfTrue` which allows for matching a string attribute against a regex. ``regex`` can be any regular expression string or a compiled ``Pattern``. This uses Python's re module under the hood and is compatible with syntax documented on `docs.python.org <https://docs.python.org/3/library/re.html>`_. For example, to match against any identifier that is at least one character long and only contains alphabetical characters:: m.Name(value=m.MatchRegex(r'[A-Za-z]+')) This can be used in place of any string literal when constructing a concrete matcher.
4,925
import collections.abc import inspect import re from abc import ABCMeta from dataclasses import dataclass, fields from enum import auto, Enum from typing import ( Callable, cast, Dict, Generic, Iterator, List, Mapping, NoReturn, Optional, Pattern, Sequence, Tuple, Type, TypeVar, Union, ) import libcst import libcst.metadata as meta from libcst import FlattenSentinel, MaybeSentinel, RemovalSentinel from libcst._metadata_dependent import LazyValue class DoNotCareSentinel(Enum): """ A sentinel that is used in matcher classes to indicate that a caller does not care what this value is. We recommend that you do not use this directly, and instead use the :func:`DoNotCare` helper. You do not need to use this for concrete matcher attributes since :func:`DoNotCare` is already the default. """ DEFAULT = auto() def __repr__(self) -> str: return "DoNotCare()" _MatcherT = TypeVar("_MatcherT", covariant=True) class AtLeastN(Generic[_MatcherT], _BaseWildcardNode): """ Matcher that matches ``n`` or more LibCST nodes in a row in a sequence. :class:`AtLeastN` defaults to matching against the :func:`DoNotCare` matcher, so if you do not specify a matcher as a child, :class:`AtLeastN` will match only by count. If you do specify a matcher as a child, :class:`AtLeastN` will instead make sure that each LibCST node matches the matcher supplied. For example, this will match all function calls with at least 3 arguments:: m.Call(args=[m.AtLeastN(n=3)]) This will match all function calls with 3 or more integer arguments:: m.Call(args=[m.AtLeastN(n=3, matcher=m.Arg(m.Integer()))]) You can combine sequence matchers with concrete matchers and special matchers and it will behave as you expect. For example, this will match all function calls that have 2 or more integer arguments in a row, followed by any arbitrary argument:: m.Call(args=[m.AtLeastN(n=2, matcher=m.Arg(m.Integer())), m.DoNotCare()]) And finally, this will match all function calls that have at least 5 arguments, the final one being an integer:: m.Call(args=[m.AtLeastN(n=4), m.Arg(m.Integer())]) """ def __init__( self, matcher: Union[_MatcherT, DoNotCareSentinel] = DoNotCareSentinel.DEFAULT, *, n: int, ) -> None: if n < 0: raise Exception(f"{self.__class__.__name__} n attribute must be positive") self._n: int = n self._matcher: Union[_MatcherT, DoNotCareSentinel] = matcher def n(self) -> int: """ The number of nodes in a row that must match :attr:`AtLeastN.matcher` for this matcher to be considered a match. If there are less than ``n`` matches, this matcher will not be considered a match. If there are equal to or more than ``n`` matches, this matcher will be considered a match. """ return self._n def matcher(self) -> Union[_MatcherT, DoNotCareSentinel]: """ The matcher which each node in a sequence needs to match. """ return self._matcher # pyre-fixme[15]: `__or__` overrides method defined in `type` inconsistently. def __or__(self, other: object) -> NoReturn: raise Exception("AtLeastN cannot be used in a OneOf matcher") def __and__(self, other: object) -> NoReturn: raise Exception("AtLeastN cannot be used in an AllOf matcher") def __invert__(self) -> NoReturn: raise Exception("Cannot invert an AtLeastN matcher!") def __repr__(self) -> str: if self._n == 0: return f"ZeroOrMore({repr(self._matcher)})" else: return f"AtLeastN({repr(self._matcher)}, n={self._n})" The provided code snippet includes necessary dependencies for implementing the `ZeroOrMore` function. Write a Python function `def ZeroOrMore( matcher: Union[_MatcherT, DoNotCareSentinel] = DoNotCareSentinel.DEFAULT ) -> AtLeastN[Union[_MatcherT, DoNotCareSentinel]]` to solve the following problem: Used as a convenience wrapper to :class:`AtLeastN` when ``n`` is equal to ``0``. Use this when you want to match against any number of nodes in a sequence. For example, this will match any function call with zero or more arguments, as long as all of the arguments are integers:: m.Call(args=[m.ZeroOrMore(m.Arg(m.Integer()))]) This will match any function call where the first argument is an integer and it doesn't matter what the rest of the arguments are:: m.Call(args=[m.Arg(m.Integer()), m.ZeroOrMore()]) You will often want to use :class:`ZeroOrMore` on both sides of a concrete matcher in order to match against sequences that contain a particular node in an arbitrary location. For example, the following will match any function call that takes in at least one string argument anywhere:: m.Call(args=[m.ZeroOrMore(), m.Arg(m.SimpleString()), m.ZeroOrMore()]) Here is the function: def ZeroOrMore( matcher: Union[_MatcherT, DoNotCareSentinel] = DoNotCareSentinel.DEFAULT ) -> AtLeastN[Union[_MatcherT, DoNotCareSentinel]]: """ Used as a convenience wrapper to :class:`AtLeastN` when ``n`` is equal to ``0``. Use this when you want to match against any number of nodes in a sequence. For example, this will match any function call with zero or more arguments, as long as all of the arguments are integers:: m.Call(args=[m.ZeroOrMore(m.Arg(m.Integer()))]) This will match any function call where the first argument is an integer and it doesn't matter what the rest of the arguments are:: m.Call(args=[m.Arg(m.Integer()), m.ZeroOrMore()]) You will often want to use :class:`ZeroOrMore` on both sides of a concrete matcher in order to match against sequences that contain a particular node in an arbitrary location. For example, the following will match any function call that takes in at least one string argument anywhere:: m.Call(args=[m.ZeroOrMore(), m.Arg(m.SimpleString()), m.ZeroOrMore()]) """ return cast(AtLeastN[Union[_MatcherT, DoNotCareSentinel]], AtLeastN(matcher, n=0))
Used as a convenience wrapper to :class:`AtLeastN` when ``n`` is equal to ``0``. Use this when you want to match against any number of nodes in a sequence. For example, this will match any function call with zero or more arguments, as long as all of the arguments are integers:: m.Call(args=[m.ZeroOrMore(m.Arg(m.Integer()))]) This will match any function call where the first argument is an integer and it doesn't matter what the rest of the arguments are:: m.Call(args=[m.Arg(m.Integer()), m.ZeroOrMore()]) You will often want to use :class:`ZeroOrMore` on both sides of a concrete matcher in order to match against sequences that contain a particular node in an arbitrary location. For example, the following will match any function call that takes in at least one string argument anywhere:: m.Call(args=[m.ZeroOrMore(), m.Arg(m.SimpleString()), m.ZeroOrMore()])
4,926
import collections.abc import inspect import re from abc import ABCMeta from dataclasses import dataclass, fields from enum import auto, Enum from typing import ( Callable, cast, Dict, Generic, Iterator, List, Mapping, NoReturn, Optional, Pattern, Sequence, Tuple, Type, TypeVar, Union, ) import libcst import libcst.metadata as meta from libcst import FlattenSentinel, MaybeSentinel, RemovalSentinel from libcst._metadata_dependent import LazyValue class DoNotCareSentinel(Enum): """ A sentinel that is used in matcher classes to indicate that a caller does not care what this value is. We recommend that you do not use this directly, and instead use the :func:`DoNotCare` helper. You do not need to use this for concrete matcher attributes since :func:`DoNotCare` is already the default. """ DEFAULT = auto() def __repr__(self) -> str: return "DoNotCare()" _MatcherT = TypeVar("_MatcherT", covariant=True) class AtMostN(Generic[_MatcherT], _BaseWildcardNode): """ Matcher that matches ``n`` or fewer LibCST nodes in a row in a sequence. :class:`AtMostN` defaults to matching against the :func:`DoNotCare` matcher, so if you do not specify a matcher as a child, :class:`AtMostN` will match only by count. If you do specify a matcher as a child, :class:`AtMostN` will instead make sure that each LibCST node matches the matcher supplied. For example, this will match all function calls with 3 or fewer arguments:: m.Call(args=[m.AtMostN(n=3)]) This will match all function calls with 0, 1 or 2 string arguments:: m.Call(args=[m.AtMostN(n=2, matcher=m.Arg(m.SimpleString()))]) You can combine sequence matchers with concrete matchers and special matchers and it will behave as you expect. For example, this will match all function calls that have 0, 1 or 2 string arguments in a row, followed by an arbitrary argument:: m.Call(args=[m.AtMostN(n=2, matcher=m.Arg(m.SimpleString())), m.DoNotCare()]) And finally, this will match all function calls that have at least 2 arguments, the final one being a string:: m.Call(args=[m.AtMostN(n=2), m.Arg(m.SimpleString())]) """ def __init__( self, matcher: Union[_MatcherT, DoNotCareSentinel] = DoNotCareSentinel.DEFAULT, *, n: int, ) -> None: if n < 0: raise Exception(f"{self.__class__.__name__} n attribute must be positive") self._n: int = n self._matcher: Union[_MatcherT, DoNotCareSentinel] = matcher def n(self) -> int: """ The number of nodes in a row that must match :attr:`AtLeastN.matcher` for this matcher to be considered a match. If there are less than or equal to ``n`` matches, then this matcher will be considered a match. Any more than ``n`` matches in a row and this matcher will stop matching and be considered not a match. """ return self._n def matcher(self) -> Union[_MatcherT, DoNotCareSentinel]: """ The matcher which each node in a sequence needs to match. """ return self._matcher # pyre-fixme[15]: `__or__` overrides method defined in `type` inconsistently. def __or__(self, other: object) -> NoReturn: raise Exception("AtMostN cannot be used in a OneOf matcher") def __and__(self, other: object) -> NoReturn: raise Exception("AtMostN cannot be used in an AllOf matcher") def __invert__(self) -> NoReturn: raise Exception("Cannot invert an AtMostN matcher!") def __repr__(self) -> str: if self._n == 1: return f"ZeroOrOne({repr(self._matcher)})" else: return f"AtMostN({repr(self._matcher)}, n={self._n})" The provided code snippet includes necessary dependencies for implementing the `ZeroOrOne` function. Write a Python function `def ZeroOrOne( matcher: Union[_MatcherT, DoNotCareSentinel] = DoNotCareSentinel.DEFAULT ) -> AtMostN[Union[_MatcherT, DoNotCareSentinel]]` to solve the following problem: Used as a convenience wrapper to :class:`AtMostN` when ``n`` is equal to ``1``. This is effectively a maybe clause. For example, this will match any function call with zero or one integer argument:: m.Call(args=[m.ZeroOrOne(m.Arg(m.Integer()))]) This will match any function call that has two or three arguments, and the first and last arguments are strings:: m.Call(args=[m.Arg(m.SimpleString()), m.ZeroOrOne(), m.Arg(m.SimpleString())]) Here is the function: def ZeroOrOne( matcher: Union[_MatcherT, DoNotCareSentinel] = DoNotCareSentinel.DEFAULT ) -> AtMostN[Union[_MatcherT, DoNotCareSentinel]]: """ Used as a convenience wrapper to :class:`AtMostN` when ``n`` is equal to ``1``. This is effectively a maybe clause. For example, this will match any function call with zero or one integer argument:: m.Call(args=[m.ZeroOrOne(m.Arg(m.Integer()))]) This will match any function call that has two or three arguments, and the first and last arguments are strings:: m.Call(args=[m.Arg(m.SimpleString()), m.ZeroOrOne(), m.Arg(m.SimpleString())]) """ return cast(AtMostN[Union[_MatcherT, DoNotCareSentinel]], AtMostN(matcher, n=1))
Used as a convenience wrapper to :class:`AtMostN` when ``n`` is equal to ``1``. This is effectively a maybe clause. For example, this will match any function call with zero or one integer argument:: m.Call(args=[m.ZeroOrOne(m.Arg(m.Integer()))]) This will match any function call that has two or three arguments, and the first and last arguments are strings:: m.Call(args=[m.Arg(m.SimpleString()), m.ZeroOrOne(), m.Arg(m.SimpleString())])
4,927
import collections.abc import inspect import re from abc import ABCMeta from dataclasses import dataclass, fields from enum import auto, Enum from typing import ( Callable, cast, Dict, Generic, Iterator, List, Mapping, NoReturn, Optional, Pattern, Sequence, Tuple, Type, TypeVar, Union, ) import libcst import libcst.metadata as meta from libcst import FlattenSentinel, MaybeSentinel, RemovalSentinel from libcst._metadata_dependent import LazyValue _OtherNodeT = TypeVar("_OtherNodeT") class BaseMatcherNode: """ Base class that all concrete matchers subclass from. :class:`OneOf` and :class:`AllOf` also subclass from this in order to allow them to be used in any place that a concrete matcher is allowed. This means that, for example, you can call :func:`matches` with a concrete matcher, or a :class:`OneOf` with several concrete matchers as options. """ # pyre-fixme[15]: `__or__` overrides method defined in `type` inconsistently. def __or__( self: _BaseMatcherNodeSelfT, other: _OtherNodeT ) -> "OneOf[Union[_BaseMatcherNodeSelfT, _OtherNodeT]]": return OneOf(self, other) def __and__( self: _BaseMatcherNodeSelfT, other: _OtherNodeT ) -> "AllOf[Union[_BaseMatcherNodeSelfT, _OtherNodeT]]": return AllOf(self, other) def __invert__(self: _BaseMatcherNodeSelfT) -> "_BaseMatcherNodeSelfT": return cast(_BaseMatcherNodeSelfT, _InverseOf(self)) class _InverseOf(Generic[_MatcherT]): """ Matcher that inverts the match result of its child. You can also construct a :class:`_InverseOf` matcher by using Python's bitwise invert operator with concrete matcher classes or any special matcher. Note that you should refrain from constructing a :class:`_InverseOf` directly, and should instead use the :func:`DoesNotMatch` helper function. For example, the following matches against any identifier that isn't ``True``/``False``:: m.DoesNotMatch(m.OneOf(m.Name("True"), m.Name("False"))) Or you could use the shorthand, like: ~(m.Name("True") | m.Name("False")) """ def __init__(self, matcher: _MatcherT) -> None: self._matcher: _MatcherT = matcher def matcher(self) -> _MatcherT: """ The matcher that we will evaluate and invert. If this matcher is true, then :class:`_InverseOf` will be considered not a match, and vice-versa. """ return self._matcher # pyre-fixme[15]: `__or__` overrides method defined in `type` inconsistently. def __or__(self, other: _OtherNodeT) -> "OneOf[Union[_MatcherT, _OtherNodeT]]": # Without a cast, pyre thinks that the below OneOf is type OneOf[object] # even though it has the types passed into it. return cast(OneOf[Union[_MatcherT, _OtherNodeT]], OneOf(self, other)) def __and__(self, other: _OtherNodeT) -> "AllOf[Union[_MatcherT, _OtherNodeT]]": # Without a cast, pyre thinks that the below AllOf is type AllOf[object] # even though it has the types passed into it. return cast(AllOf[Union[_MatcherT, _OtherNodeT]], AllOf(self, other)) def __getattr__(self, key: str) -> object: # We lie about types to make _InverseOf appear transparent. So, its conceivable # that somebody might try to dereference an attribute on the _MatcherT wrapped # node and become surprised that it doesn't work. return getattr(self._matcher, key) def __invert__(self) -> _MatcherT: return self._matcher def __repr__(self) -> str: return f"DoesNotMatch({repr(self._matcher)})" class _ExtractMatchingNode(Generic[_MatcherT]): """ Transparent pass-through matcher that captures the node which matches its children, making it available to the caller of :func:`extract` or :func:`extractall`. Note that you should refrain from constructing a :class:`_ExtractMatchingNode` directly, and should instead use the :func:`SaveMatchedNode` helper function. For example, the following will match against any binary operation whose left and right operands are not integers, saving those expressions for later inspection. If used inside :func:`extract` or :func:`extractall`, the resulting dictionary will contain the keys ``left_operand`` and ``right_operand``. m.BinaryOperation( left=m.SaveMatchedNode( m.DoesNotMatch(m.Integer()), "left_operand", ), right=m.SaveMatchedNode( m.DoesNotMatch(m.Integer()), "right_operand", ), ) """ def __init__(self, matcher: _MatcherT, name: str) -> None: self._matcher: _MatcherT = matcher self._name: str = name def matcher(self) -> _MatcherT: """ The matcher that we will evaluate and capture matching LibCST nodes for. If this matcher is true, then :class:`_ExtractMatchingNode` will be considered a match and will save the node which matched. """ return self._matcher def name(self) -> str: """ The name we will call our captured LibCST node inside the resulting dictionary returned by :func:`extract` or :func:`extractall`. """ return self._name # pyre-fixme[15]: `__or__` overrides method defined in `type` inconsistently. def __or__(self, other: _OtherNodeT) -> "OneOf[Union[_MatcherT, _OtherNodeT]]": # Without a cast, pyre thinks that the below OneOf is type OneOf[object] # even though it has the types passed into it. return cast(OneOf[Union[_MatcherT, _OtherNodeT]], OneOf(self, other)) def __and__(self, other: _OtherNodeT) -> "AllOf[Union[_MatcherT, _OtherNodeT]]": # This doesn't make sense. If we have multiple SaveMatchedNode captures # that are captured with an and, either all of them will be assigned the # same node, or none of them. It makes more sense to move the SaveMatchedNode # up to wrap the AllOf. raise Exception( ( "Cannot use AllOf with SavedMatchedNode children! Instead, you should " + "use SaveMatchedNode(AllOf(options...))." ) ) def __getattr__(self, key: str) -> object: # We lie about types to make _ExtractMatchingNode appear transparent. So, # its conceivable that somebody might try to dereference an attribute on # the _MatcherT wrapped node and become surprised that it doesn't work. return getattr(self._matcher, key) def __invert__(self) -> "_MatcherT": # This doesn't make sense. We don't want to capture a node only if it # doesn't match, since this will never capture anything. raise Exception( ( "Cannot invert a SaveMatchedNode. Instead you should wrap SaveMatchedNode " + "around your inversion itself" ) ) def __repr__(self) -> str: return ( f"SaveMatchedNode(matcher={repr(self._matcher)}, name={repr(self._name)})" ) class MatchIfTrue(Generic[_MatchIfTrueT]): """ Matcher that matches if its child callable returns ``True``. The child callable should take one argument which is the attribute on the LibCST node we are trying to match against. This is useful if you want to do complex logic to determine if an attribute should match or not. One example of this is the :func:`MatchRegex` matcher build on top of :class:`MatchIfTrue` which takes a regular expression and matches any string attribute where a regex match is found. For example, to match on any identifier spelled with the letter ``e``:: m.Name(value=m.MatchIfTrue(lambda value: "e" in value)) This can be used in place of any concrete matcher as long as it is not the root matcher. Calling :func:`matches` directly on a :class:`MatchIfTrue` is redundant since you can just call the child callable directly with the node you are passing to :func:`matches`. """ _func: Callable[[_MatchIfTrueT], bool] def __init__(self, func: Callable[[_MatchIfTrueT], bool]) -> None: self._func = func def func(self) -> Callable[[_MatchIfTrueT], bool]: """ The function that we will call with a LibCST node in order to determine if we match. If the function returns ``True`` then we consider ourselves to be a match. """ return self._func # pyre-fixme[15]: `__or__` overrides method defined in `type` inconsistently. def __or__( self, other: _OtherNodeT ) -> "OneOf[Union[MatchIfTrue[_MatchIfTrueT], _OtherNodeT]]": return OneOf(self, other) def __and__( self, other: _OtherNodeT ) -> "AllOf[Union[MatchIfTrue[_MatchIfTrueT], _OtherNodeT]]": return AllOf(self, other) def __invert__(self) -> "MatchIfTrue[_MatchIfTrueT]": # Construct a wrapped version of MatchIfTrue for typing simplicity. # Without the cast, pyre doesn't seem to think the lambda is valid. return MatchIfTrue(lambda val: not self._func(val)) def __repr__(self) -> str: return f"MatchIfTrue({repr(self._func)})" class _BaseMetadataMatcher: """ Class that's only around for typing purposes. """ pass The provided code snippet includes necessary dependencies for implementing the `DoesNotMatch` function. Write a Python function `def DoesNotMatch(obj: _OtherNodeT) -> _OtherNodeT` to solve the following problem: Matcher helper that inverts the match result of its child. You can also invert a matcher by using Python's bitwise invert operator on concrete matchers or any special matcher. For example, the following matches against any identifier that isn't ``True``/``False``:: m.DoesNotMatch(m.OneOf(m.Name("True"), m.Name("False"))) Or you could use the shorthand, like:: ~(m.Name("True") | m.Name("False")) This can be used in place of any concrete matcher as long as it is not the root matcher. Calling :func:`matches` directly on a :func:`DoesNotMatch` is redundant since you can invert the return of :func:`matches` using a bitwise not. Here is the function: def DoesNotMatch(obj: _OtherNodeT) -> _OtherNodeT: """ Matcher helper that inverts the match result of its child. You can also invert a matcher by using Python's bitwise invert operator on concrete matchers or any special matcher. For example, the following matches against any identifier that isn't ``True``/``False``:: m.DoesNotMatch(m.OneOf(m.Name("True"), m.Name("False"))) Or you could use the shorthand, like:: ~(m.Name("True") | m.Name("False")) This can be used in place of any concrete matcher as long as it is not the root matcher. Calling :func:`matches` directly on a :func:`DoesNotMatch` is redundant since you can invert the return of :func:`matches` using a bitwise not. """ # This type is a complete, dirty lie, but there's no way to recursively apply # a parameter to each type inside a Union that may be in a _OtherNodeT. # However, given the way _InverseOf works (it will unwrap itself if # inverted again), and the way we apply De Morgan's law for OneOf and AllOf, # this lie ends up getting us correct typing. Anywhere a node is valid, using # DoesNotMatch(node) is also valid. # # ~MatchIfTrue is still MatchIfTrue # ~MatchMetadataIfTrue is still MatchMetadataIfTrue # ~OneOf[x] is AllOf[~x] # ~AllOf[x] is OneOf[~x] # ~~x is x # # So, under all circumstances, since OneOf/AllOf are both allowed in every # instance, and given that inverting MatchIfTrue is still MatchIfTrue, # and inverting an inverted value returns us the original, its clear that # there are no operations we can possibly do that bring us outside of the # types specified in the concrete matchers as long as we lie that DoesNotMatch # returns the value passed in. if isinstance( obj, ( BaseMatcherNode, MatchIfTrue, _BaseMetadataMatcher, _InverseOf, _ExtractMatchingNode, ), ): # We can use the overridden __invert__ in this case. Pyre doesn't think # we can though, and casting doesn't fix the issue. inverse = ~obj else: # We must wrap in a _InverseOf. inverse = _InverseOf(obj) return cast(_OtherNodeT, inverse)
Matcher helper that inverts the match result of its child. You can also invert a matcher by using Python's bitwise invert operator on concrete matchers or any special matcher. For example, the following matches against any identifier that isn't ``True``/``False``:: m.DoesNotMatch(m.OneOf(m.Name("True"), m.Name("False"))) Or you could use the shorthand, like:: ~(m.Name("True") | m.Name("False")) This can be used in place of any concrete matcher as long as it is not the root matcher. Calling :func:`matches` directly on a :func:`DoesNotMatch` is redundant since you can invert the return of :func:`matches` using a bitwise not.
4,928
import collections.abc import inspect import re from abc import ABCMeta from dataclasses import dataclass, fields from enum import auto, Enum from typing import ( Callable, cast, Dict, Generic, Iterator, List, Mapping, NoReturn, Optional, Pattern, Sequence, Tuple, Type, TypeVar, Union, ) import libcst import libcst.metadata as meta from libcst import FlattenSentinel, MaybeSentinel, RemovalSentinel from libcst._metadata_dependent import LazyValue _OtherNodeT = TypeVar("_OtherNodeT") class _ExtractMatchingNode(Generic[_MatcherT]): """ Transparent pass-through matcher that captures the node which matches its children, making it available to the caller of :func:`extract` or :func:`extractall`. Note that you should refrain from constructing a :class:`_ExtractMatchingNode` directly, and should instead use the :func:`SaveMatchedNode` helper function. For example, the following will match against any binary operation whose left and right operands are not integers, saving those expressions for later inspection. If used inside :func:`extract` or :func:`extractall`, the resulting dictionary will contain the keys ``left_operand`` and ``right_operand``. m.BinaryOperation( left=m.SaveMatchedNode( m.DoesNotMatch(m.Integer()), "left_operand", ), right=m.SaveMatchedNode( m.DoesNotMatch(m.Integer()), "right_operand", ), ) """ def __init__(self, matcher: _MatcherT, name: str) -> None: self._matcher: _MatcherT = matcher self._name: str = name def matcher(self) -> _MatcherT: """ The matcher that we will evaluate and capture matching LibCST nodes for. If this matcher is true, then :class:`_ExtractMatchingNode` will be considered a match and will save the node which matched. """ return self._matcher def name(self) -> str: """ The name we will call our captured LibCST node inside the resulting dictionary returned by :func:`extract` or :func:`extractall`. """ return self._name # pyre-fixme[15]: `__or__` overrides method defined in `type` inconsistently. def __or__(self, other: _OtherNodeT) -> "OneOf[Union[_MatcherT, _OtherNodeT]]": # Without a cast, pyre thinks that the below OneOf is type OneOf[object] # even though it has the types passed into it. return cast(OneOf[Union[_MatcherT, _OtherNodeT]], OneOf(self, other)) def __and__(self, other: _OtherNodeT) -> "AllOf[Union[_MatcherT, _OtherNodeT]]": # This doesn't make sense. If we have multiple SaveMatchedNode captures # that are captured with an and, either all of them will be assigned the # same node, or none of them. It makes more sense to move the SaveMatchedNode # up to wrap the AllOf. raise Exception( ( "Cannot use AllOf with SavedMatchedNode children! Instead, you should " + "use SaveMatchedNode(AllOf(options...))." ) ) def __getattr__(self, key: str) -> object: # We lie about types to make _ExtractMatchingNode appear transparent. So, # its conceivable that somebody might try to dereference an attribute on # the _MatcherT wrapped node and become surprised that it doesn't work. return getattr(self._matcher, key) def __invert__(self) -> "_MatcherT": # This doesn't make sense. We don't want to capture a node only if it # doesn't match, since this will never capture anything. raise Exception( ( "Cannot invert a SaveMatchedNode. Instead you should wrap SaveMatchedNode " + "around your inversion itself" ) ) def __repr__(self) -> str: return ( f"SaveMatchedNode(matcher={repr(self._matcher)}, name={repr(self._name)})" ) The provided code snippet includes necessary dependencies for implementing the `SaveMatchedNode` function. Write a Python function `def SaveMatchedNode(matcher: _OtherNodeT, name: str) -> _OtherNodeT` to solve the following problem: Matcher helper that captures the matched node that matched against a matcher class, making it available in the dictionary returned by :func:`extract` or :func:`extractall`. For example, the following will match against any binary operation whose left and right operands are not integers, saving those expressions for later inspection. If used inside :func:`extract` or :func:`extractall`, the resulting dictionary will contain the keys ``left_operand`` and ``right_operand``:: m.BinaryOperation( left=m.SaveMatchedNode( m.DoesNotMatch(m.Integer()), "left_operand", ), right=m.SaveMatchedNode( m.DoesNotMatch(m.Integer()), "right_operand", ), ) This can be used in place of any concrete matcher as long as it is not the root matcher. Calling :func:`extract` directly on a :func:`SaveMatchedNode` is redundant since you already have the reference to the node itself. Here is the function: def SaveMatchedNode(matcher: _OtherNodeT, name: str) -> _OtherNodeT: """ Matcher helper that captures the matched node that matched against a matcher class, making it available in the dictionary returned by :func:`extract` or :func:`extractall`. For example, the following will match against any binary operation whose left and right operands are not integers, saving those expressions for later inspection. If used inside :func:`extract` or :func:`extractall`, the resulting dictionary will contain the keys ``left_operand`` and ``right_operand``:: m.BinaryOperation( left=m.SaveMatchedNode( m.DoesNotMatch(m.Integer()), "left_operand", ), right=m.SaveMatchedNode( m.DoesNotMatch(m.Integer()), "right_operand", ), ) This can be used in place of any concrete matcher as long as it is not the root matcher. Calling :func:`extract` directly on a :func:`SaveMatchedNode` is redundant since you already have the reference to the node itself. """ return cast(_OtherNodeT, _ExtractMatchingNode(matcher, name))
Matcher helper that captures the matched node that matched against a matcher class, making it available in the dictionary returned by :func:`extract` or :func:`extractall`. For example, the following will match against any binary operation whose left and right operands are not integers, saving those expressions for later inspection. If used inside :func:`extract` or :func:`extractall`, the resulting dictionary will contain the keys ``left_operand`` and ``right_operand``:: m.BinaryOperation( left=m.SaveMatchedNode( m.DoesNotMatch(m.Integer()), "left_operand", ), right=m.SaveMatchedNode( m.DoesNotMatch(m.Integer()), "right_operand", ), ) This can be used in place of any concrete matcher as long as it is not the root matcher. Calling :func:`extract` directly on a :func:`SaveMatchedNode` is redundant since you already have the reference to the node itself.
4,929
import collections.abc import inspect import re from abc import ABCMeta from dataclasses import dataclass, fields from enum import auto, Enum from typing import ( Callable, cast, Dict, Generic, Iterator, List, Mapping, NoReturn, Optional, Pattern, Sequence, Tuple, Type, TypeVar, Union, ) import libcst import libcst.metadata as meta from libcst import FlattenSentinel, MaybeSentinel, RemovalSentinel from libcst._metadata_dependent import LazyValue class BaseMatcherNode: """ Base class that all concrete matchers subclass from. :class:`OneOf` and :class:`AllOf` also subclass from this in order to allow them to be used in any place that a concrete matcher is allowed. This means that, for example, you can call :func:`matches` with a concrete matcher, or a :class:`OneOf` with several concrete matchers as options. """ # pyre-fixme[15]: `__or__` overrides method defined in `type` inconsistently. def __or__( self: _BaseMatcherNodeSelfT, other: _OtherNodeT ) -> "OneOf[Union[_BaseMatcherNodeSelfT, _OtherNodeT]]": return OneOf(self, other) def __and__( self: _BaseMatcherNodeSelfT, other: _OtherNodeT ) -> "AllOf[Union[_BaseMatcherNodeSelfT, _OtherNodeT]]": return AllOf(self, other) def __invert__(self: _BaseMatcherNodeSelfT) -> "_BaseMatcherNodeSelfT": return cast(_BaseMatcherNodeSelfT, _InverseOf(self)) class MatchIfTrue(Generic[_MatchIfTrueT]): """ Matcher that matches if its child callable returns ``True``. The child callable should take one argument which is the attribute on the LibCST node we are trying to match against. This is useful if you want to do complex logic to determine if an attribute should match or not. One example of this is the :func:`MatchRegex` matcher build on top of :class:`MatchIfTrue` which takes a regular expression and matches any string attribute where a regex match is found. For example, to match on any identifier spelled with the letter ``e``:: m.Name(value=m.MatchIfTrue(lambda value: "e" in value)) This can be used in place of any concrete matcher as long as it is not the root matcher. Calling :func:`matches` directly on a :class:`MatchIfTrue` is redundant since you can just call the child callable directly with the node you are passing to :func:`matches`. """ _func: Callable[[_MatchIfTrueT], bool] def __init__(self, func: Callable[[_MatchIfTrueT], bool]) -> None: self._func = func def func(self) -> Callable[[_MatchIfTrueT], bool]: """ The function that we will call with a LibCST node in order to determine if we match. If the function returns ``True`` then we consider ourselves to be a match. """ return self._func # pyre-fixme[15]: `__or__` overrides method defined in `type` inconsistently. def __or__( self, other: _OtherNodeT ) -> "OneOf[Union[MatchIfTrue[_MatchIfTrueT], _OtherNodeT]]": return OneOf(self, other) def __and__( self, other: _OtherNodeT ) -> "AllOf[Union[MatchIfTrue[_MatchIfTrueT], _OtherNodeT]]": return AllOf(self, other) def __invert__(self) -> "MatchIfTrue[_MatchIfTrueT]": # Construct a wrapped version of MatchIfTrue for typing simplicity. # Without the cast, pyre doesn't seem to think the lambda is valid. return MatchIfTrue(lambda val: not self._func(val)) def __repr__(self) -> str: return f"MatchIfTrue({repr(self._func)})" class _BaseMetadataMatcher: """ Class that's only around for typing purposes. """ pass def _find_or_extract_all( tree: Union[MaybeSentinel, RemovalSentinel, libcst.CSTNode, meta.MetadataWrapper], matcher: Union[ BaseMatcherNode, MatchIfTrue[libcst.CSTNode], _BaseMetadataMatcher, # The inverse clause is left off of the public functions `findall` and # `extractall` because we play a dirty trick. We lie to the typechecker # that `DoesNotMatch` returns identity, so the public functions don't # need to be aware of inverses. If we could represent predicate logic # in python types we could get away with this, but that's not the state # of things right now. _InverseOf[ Union[ BaseMatcherNode, MatchIfTrue[libcst.CSTNode], _BaseMetadataMatcher, ] ], ], *, metadata_resolver: Optional[ Union[libcst.MetadataDependent, libcst.MetadataWrapper] ] = None, ) -> Tuple[ Sequence[libcst.CSTNode], Sequence[Dict[str, Union[libcst.CSTNode, Sequence[libcst.CSTNode]]]], ]: if isinstance(tree, (RemovalSentinel, MaybeSentinel)): # We can't possibly match on a removal sentinel, so it doesn't match. return [], [] if isinstance(matcher, (AtLeastN, AtMostN)): # We can't match this, since these matchers are forbidden at top level. # These are not subclasses of BaseMatcherNode, but in the case that the # user is not using type checking, this should still behave correctly. return [], [] if isinstance(tree, meta.MetadataWrapper) and metadata_resolver is None: # Provide a convenience for calling findall directly on a MetadataWrapper. metadata_resolver = tree if metadata_resolver is None: fetcher = _construct_metadata_fetcher_null() elif isinstance(metadata_resolver, libcst.MetadataWrapper): fetcher = _construct_metadata_fetcher_wrapper(metadata_resolver) else: fetcher = _construct_metadata_fetcher_dependent(metadata_resolver) finder = _FindAllVisitor(matcher, fetcher) tree.visit(finder) return finder.found_nodes, finder.extracted_nodes The provided code snippet includes necessary dependencies for implementing the `findall` function. Write a Python function `def findall( tree: Union[MaybeSentinel, RemovalSentinel, libcst.CSTNode, meta.MetadataWrapper], matcher: Union[BaseMatcherNode, MatchIfTrue[libcst.CSTNode], _BaseMetadataMatcher], *, metadata_resolver: Optional[ Union[libcst.MetadataDependent, libcst.MetadataWrapper] ] = None, ) -> Sequence[libcst.CSTNode]` to solve the following problem: Given an arbitrary node from a LibCST tree and an arbitrary matcher, iterates over that node and all children returning a sequence of all child nodes that match the given matcher. Note that the tree can also be a :class:`~libcst.RemovalSentinel` or a :class:`~libcst.MaybeSentinel` in order to use findall directly on transform results and node attributes. In these cases, :func:`findall` will always return an empty sequence. Note also that instead of a LibCST tree, you can instead pass in a :class:`~libcst.metadata.MetadataWrapper`. This mirrors the fact that you can call ``visit`` on a :class:`~libcst.metadata.MetadataWrapper` in order to iterate over it with a transform. If you provide a wrapper for the tree and do not set the ``metadata_resolver`` parameter specifically, it will automatically be set to the wrapper for you. The matcher can be any concrete matcher that subclasses from :class:`BaseMatcherNode`, or a :class:`OneOf`/:class:`AllOf` special matcher. Unlike :func:`matches`, it can also be a :class:`MatchIfTrue` or :func:`DoesNotMatch` matcher, since we are traversing the tree looking for matches. It cannot be a :class:`AtLeastN` or :class:`AtMostN` matcher because these types are wildcards which can only be used inside sequences. Here is the function: def findall( tree: Union[MaybeSentinel, RemovalSentinel, libcst.CSTNode, meta.MetadataWrapper], matcher: Union[BaseMatcherNode, MatchIfTrue[libcst.CSTNode], _BaseMetadataMatcher], *, metadata_resolver: Optional[ Union[libcst.MetadataDependent, libcst.MetadataWrapper] ] = None, ) -> Sequence[libcst.CSTNode]: """ Given an arbitrary node from a LibCST tree and an arbitrary matcher, iterates over that node and all children returning a sequence of all child nodes that match the given matcher. Note that the tree can also be a :class:`~libcst.RemovalSentinel` or a :class:`~libcst.MaybeSentinel` in order to use findall directly on transform results and node attributes. In these cases, :func:`findall` will always return an empty sequence. Note also that instead of a LibCST tree, you can instead pass in a :class:`~libcst.metadata.MetadataWrapper`. This mirrors the fact that you can call ``visit`` on a :class:`~libcst.metadata.MetadataWrapper` in order to iterate over it with a transform. If you provide a wrapper for the tree and do not set the ``metadata_resolver`` parameter specifically, it will automatically be set to the wrapper for you. The matcher can be any concrete matcher that subclasses from :class:`BaseMatcherNode`, or a :class:`OneOf`/:class:`AllOf` special matcher. Unlike :func:`matches`, it can also be a :class:`MatchIfTrue` or :func:`DoesNotMatch` matcher, since we are traversing the tree looking for matches. It cannot be a :class:`AtLeastN` or :class:`AtMostN` matcher because these types are wildcards which can only be used inside sequences. """ nodes, _ = _find_or_extract_all(tree, matcher, metadata_resolver=metadata_resolver) return nodes
Given an arbitrary node from a LibCST tree and an arbitrary matcher, iterates over that node and all children returning a sequence of all child nodes that match the given matcher. Note that the tree can also be a :class:`~libcst.RemovalSentinel` or a :class:`~libcst.MaybeSentinel` in order to use findall directly on transform results and node attributes. In these cases, :func:`findall` will always return an empty sequence. Note also that instead of a LibCST tree, you can instead pass in a :class:`~libcst.metadata.MetadataWrapper`. This mirrors the fact that you can call ``visit`` on a :class:`~libcst.metadata.MetadataWrapper` in order to iterate over it with a transform. If you provide a wrapper for the tree and do not set the ``metadata_resolver`` parameter specifically, it will automatically be set to the wrapper for you. The matcher can be any concrete matcher that subclasses from :class:`BaseMatcherNode`, or a :class:`OneOf`/:class:`AllOf` special matcher. Unlike :func:`matches`, it can also be a :class:`MatchIfTrue` or :func:`DoesNotMatch` matcher, since we are traversing the tree looking for matches. It cannot be a :class:`AtLeastN` or :class:`AtMostN` matcher because these types are wildcards which can only be used inside sequences.
4,930
import collections.abc import inspect import re from abc import ABCMeta from dataclasses import dataclass, fields from enum import auto, Enum from typing import ( Callable, cast, Dict, Generic, Iterator, List, Mapping, NoReturn, Optional, Pattern, Sequence, Tuple, Type, TypeVar, Union, ) import libcst import libcst.metadata as meta from libcst import FlattenSentinel, MaybeSentinel, RemovalSentinel from libcst._metadata_dependent import LazyValue class BaseMatcherNode: """ Base class that all concrete matchers subclass from. :class:`OneOf` and :class:`AllOf` also subclass from this in order to allow them to be used in any place that a concrete matcher is allowed. This means that, for example, you can call :func:`matches` with a concrete matcher, or a :class:`OneOf` with several concrete matchers as options. """ # pyre-fixme[15]: `__or__` overrides method defined in `type` inconsistently. def __or__( self: _BaseMatcherNodeSelfT, other: _OtherNodeT ) -> "OneOf[Union[_BaseMatcherNodeSelfT, _OtherNodeT]]": return OneOf(self, other) def __and__( self: _BaseMatcherNodeSelfT, other: _OtherNodeT ) -> "AllOf[Union[_BaseMatcherNodeSelfT, _OtherNodeT]]": return AllOf(self, other) def __invert__(self: _BaseMatcherNodeSelfT) -> "_BaseMatcherNodeSelfT": return cast(_BaseMatcherNodeSelfT, _InverseOf(self)) class MatchIfTrue(Generic[_MatchIfTrueT]): """ Matcher that matches if its child callable returns ``True``. The child callable should take one argument which is the attribute on the LibCST node we are trying to match against. This is useful if you want to do complex logic to determine if an attribute should match or not. One example of this is the :func:`MatchRegex` matcher build on top of :class:`MatchIfTrue` which takes a regular expression and matches any string attribute where a regex match is found. For example, to match on any identifier spelled with the letter ``e``:: m.Name(value=m.MatchIfTrue(lambda value: "e" in value)) This can be used in place of any concrete matcher as long as it is not the root matcher. Calling :func:`matches` directly on a :class:`MatchIfTrue` is redundant since you can just call the child callable directly with the node you are passing to :func:`matches`. """ _func: Callable[[_MatchIfTrueT], bool] def __init__(self, func: Callable[[_MatchIfTrueT], bool]) -> None: self._func = func def func(self) -> Callable[[_MatchIfTrueT], bool]: """ The function that we will call with a LibCST node in order to determine if we match. If the function returns ``True`` then we consider ourselves to be a match. """ return self._func # pyre-fixme[15]: `__or__` overrides method defined in `type` inconsistently. def __or__( self, other: _OtherNodeT ) -> "OneOf[Union[MatchIfTrue[_MatchIfTrueT], _OtherNodeT]]": return OneOf(self, other) def __and__( self, other: _OtherNodeT ) -> "AllOf[Union[MatchIfTrue[_MatchIfTrueT], _OtherNodeT]]": return AllOf(self, other) def __invert__(self) -> "MatchIfTrue[_MatchIfTrueT]": # Construct a wrapped version of MatchIfTrue for typing simplicity. # Without the cast, pyre doesn't seem to think the lambda is valid. return MatchIfTrue(lambda val: not self._func(val)) def __repr__(self) -> str: return f"MatchIfTrue({repr(self._func)})" class _BaseMetadataMatcher: """ Class that's only around for typing purposes. """ pass def _find_or_extract_all( tree: Union[MaybeSentinel, RemovalSentinel, libcst.CSTNode, meta.MetadataWrapper], matcher: Union[ BaseMatcherNode, MatchIfTrue[libcst.CSTNode], _BaseMetadataMatcher, # The inverse clause is left off of the public functions `findall` and # `extractall` because we play a dirty trick. We lie to the typechecker # that `DoesNotMatch` returns identity, so the public functions don't # need to be aware of inverses. If we could represent predicate logic # in python types we could get away with this, but that's not the state # of things right now. _InverseOf[ Union[ BaseMatcherNode, MatchIfTrue[libcst.CSTNode], _BaseMetadataMatcher, ] ], ], *, metadata_resolver: Optional[ Union[libcst.MetadataDependent, libcst.MetadataWrapper] ] = None, ) -> Tuple[ Sequence[libcst.CSTNode], Sequence[Dict[str, Union[libcst.CSTNode, Sequence[libcst.CSTNode]]]], ]: if isinstance(tree, (RemovalSentinel, MaybeSentinel)): # We can't possibly match on a removal sentinel, so it doesn't match. return [], [] if isinstance(matcher, (AtLeastN, AtMostN)): # We can't match this, since these matchers are forbidden at top level. # These are not subclasses of BaseMatcherNode, but in the case that the # user is not using type checking, this should still behave correctly. return [], [] if isinstance(tree, meta.MetadataWrapper) and metadata_resolver is None: # Provide a convenience for calling findall directly on a MetadataWrapper. metadata_resolver = tree if metadata_resolver is None: fetcher = _construct_metadata_fetcher_null() elif isinstance(metadata_resolver, libcst.MetadataWrapper): fetcher = _construct_metadata_fetcher_wrapper(metadata_resolver) else: fetcher = _construct_metadata_fetcher_dependent(metadata_resolver) finder = _FindAllVisitor(matcher, fetcher) tree.visit(finder) return finder.found_nodes, finder.extracted_nodes The provided code snippet includes necessary dependencies for implementing the `extractall` function. Write a Python function `def extractall( tree: Union[MaybeSentinel, RemovalSentinel, libcst.CSTNode, meta.MetadataWrapper], matcher: Union[BaseMatcherNode, MatchIfTrue[libcst.CSTNode], _BaseMetadataMatcher], *, metadata_resolver: Optional[ Union[libcst.MetadataDependent, libcst.MetadataWrapper] ] = None, ) -> Sequence[Dict[str, Union[libcst.CSTNode, Sequence[libcst.CSTNode]]]]` to solve the following problem: Given an arbitrary node from a LibCST tree and an arbitrary matcher, iterates over that node and all children returning a sequence of dictionaries representing the saved and extracted children specified by :func:`SaveMatchedNode` for each match found in the tree. This is analogous to running a :func:`findall` over a tree, then running :func:`extract` with the same matcher over each of the returned nodes. Note that the tree can also be a :class:`~libcst.RemovalSentinel` or a :class:`~libcst.MaybeSentinel` in order to use extractall directly on transform results and node attributes. In these cases, :func:`extractall` will always return an empty sequence. Note also that instead of a LibCST tree, you can instead pass in a :class:`~libcst.metadata.MetadataWrapper`. This mirrors the fact that you can call ``visit`` on a :class:`~libcst.metadata.MetadataWrapper` in order to iterate over it with a transform. If you provide a wrapper for the tree and do not set the ``metadata_resolver`` parameter specifically, it will automatically be set to the wrapper for you. The matcher can be any concrete matcher that subclasses from :class:`BaseMatcherNode`, or a :class:`OneOf`/:class:`AllOf` special matcher. Unlike :func:`matches`, it can also be a :class:`MatchIfTrue` or :func:`DoesNotMatch` matcher, since we are traversing the tree looking for matches. It cannot be a :class:`AtLeastN` or :class:`AtMostN` matcher because these types are wildcards which can only be usedi inside sequences. Here is the function: def extractall( tree: Union[MaybeSentinel, RemovalSentinel, libcst.CSTNode, meta.MetadataWrapper], matcher: Union[BaseMatcherNode, MatchIfTrue[libcst.CSTNode], _BaseMetadataMatcher], *, metadata_resolver: Optional[ Union[libcst.MetadataDependent, libcst.MetadataWrapper] ] = None, ) -> Sequence[Dict[str, Union[libcst.CSTNode, Sequence[libcst.CSTNode]]]]: """ Given an arbitrary node from a LibCST tree and an arbitrary matcher, iterates over that node and all children returning a sequence of dictionaries representing the saved and extracted children specified by :func:`SaveMatchedNode` for each match found in the tree. This is analogous to running a :func:`findall` over a tree, then running :func:`extract` with the same matcher over each of the returned nodes. Note that the tree can also be a :class:`~libcst.RemovalSentinel` or a :class:`~libcst.MaybeSentinel` in order to use extractall directly on transform results and node attributes. In these cases, :func:`extractall` will always return an empty sequence. Note also that instead of a LibCST tree, you can instead pass in a :class:`~libcst.metadata.MetadataWrapper`. This mirrors the fact that you can call ``visit`` on a :class:`~libcst.metadata.MetadataWrapper` in order to iterate over it with a transform. If you provide a wrapper for the tree and do not set the ``metadata_resolver`` parameter specifically, it will automatically be set to the wrapper for you. The matcher can be any concrete matcher that subclasses from :class:`BaseMatcherNode`, or a :class:`OneOf`/:class:`AllOf` special matcher. Unlike :func:`matches`, it can also be a :class:`MatchIfTrue` or :func:`DoesNotMatch` matcher, since we are traversing the tree looking for matches. It cannot be a :class:`AtLeastN` or :class:`AtMostN` matcher because these types are wildcards which can only be usedi inside sequences. """ _, extractions = _find_or_extract_all( tree, matcher, metadata_resolver=metadata_resolver ) return extractions
Given an arbitrary node from a LibCST tree and an arbitrary matcher, iterates over that node and all children returning a sequence of dictionaries representing the saved and extracted children specified by :func:`SaveMatchedNode` for each match found in the tree. This is analogous to running a :func:`findall` over a tree, then running :func:`extract` with the same matcher over each of the returned nodes. Note that the tree can also be a :class:`~libcst.RemovalSentinel` or a :class:`~libcst.MaybeSentinel` in order to use extractall directly on transform results and node attributes. In these cases, :func:`extractall` will always return an empty sequence. Note also that instead of a LibCST tree, you can instead pass in a :class:`~libcst.metadata.MetadataWrapper`. This mirrors the fact that you can call ``visit`` on a :class:`~libcst.metadata.MetadataWrapper` in order to iterate over it with a transform. If you provide a wrapper for the tree and do not set the ``metadata_resolver`` parameter specifically, it will automatically be set to the wrapper for you. The matcher can be any concrete matcher that subclasses from :class:`BaseMatcherNode`, or a :class:`OneOf`/:class:`AllOf` special matcher. Unlike :func:`matches`, it can also be a :class:`MatchIfTrue` or :func:`DoesNotMatch` matcher, since we are traversing the tree looking for matches. It cannot be a :class:`AtLeastN` or :class:`AtMostN` matcher because these types are wildcards which can only be usedi inside sequences.
4,931
import collections.abc import inspect import re from abc import ABCMeta from dataclasses import dataclass, fields from enum import auto, Enum from typing import ( Callable, cast, Dict, Generic, Iterator, List, Mapping, NoReturn, Optional, Pattern, Sequence, Tuple, Type, TypeVar, Union, ) import libcst import libcst.metadata as meta from libcst import FlattenSentinel, MaybeSentinel, RemovalSentinel from libcst._metadata_dependent import LazyValue class BaseMatcherNode: """ Base class that all concrete matchers subclass from. :class:`OneOf` and :class:`AllOf` also subclass from this in order to allow them to be used in any place that a concrete matcher is allowed. This means that, for example, you can call :func:`matches` with a concrete matcher, or a :class:`OneOf` with several concrete matchers as options. """ # pyre-fixme[15]: `__or__` overrides method defined in `type` inconsistently. def __or__( self: _BaseMatcherNodeSelfT, other: _OtherNodeT ) -> "OneOf[Union[_BaseMatcherNodeSelfT, _OtherNodeT]]": return OneOf(self, other) def __and__( self: _BaseMatcherNodeSelfT, other: _OtherNodeT ) -> "AllOf[Union[_BaseMatcherNodeSelfT, _OtherNodeT]]": return AllOf(self, other) def __invert__(self: _BaseMatcherNodeSelfT) -> "_BaseMatcherNodeSelfT": return cast(_BaseMatcherNodeSelfT, _InverseOf(self)) class MatchIfTrue(Generic[_MatchIfTrueT]): """ Matcher that matches if its child callable returns ``True``. The child callable should take one argument which is the attribute on the LibCST node we are trying to match against. This is useful if you want to do complex logic to determine if an attribute should match or not. One example of this is the :func:`MatchRegex` matcher build on top of :class:`MatchIfTrue` which takes a regular expression and matches any string attribute where a regex match is found. For example, to match on any identifier spelled with the letter ``e``:: m.Name(value=m.MatchIfTrue(lambda value: "e" in value)) This can be used in place of any concrete matcher as long as it is not the root matcher. Calling :func:`matches` directly on a :class:`MatchIfTrue` is redundant since you can just call the child callable directly with the node you are passing to :func:`matches`. """ _func: Callable[[_MatchIfTrueT], bool] def __init__(self, func: Callable[[_MatchIfTrueT], bool]) -> None: self._func = func def func(self) -> Callable[[_MatchIfTrueT], bool]: """ The function that we will call with a LibCST node in order to determine if we match. If the function returns ``True`` then we consider ourselves to be a match. """ return self._func # pyre-fixme[15]: `__or__` overrides method defined in `type` inconsistently. def __or__( self, other: _OtherNodeT ) -> "OneOf[Union[MatchIfTrue[_MatchIfTrueT], _OtherNodeT]]": return OneOf(self, other) def __and__( self, other: _OtherNodeT ) -> "AllOf[Union[MatchIfTrue[_MatchIfTrueT], _OtherNodeT]]": return AllOf(self, other) def __invert__(self) -> "MatchIfTrue[_MatchIfTrueT]": # Construct a wrapped version of MatchIfTrue for typing simplicity. # Without the cast, pyre doesn't seem to think the lambda is valid. return MatchIfTrue(lambda val: not self._func(val)) def __repr__(self) -> str: return f"MatchIfTrue({repr(self._func)})" class _BaseMetadataMatcher: """ Class that's only around for typing purposes. """ pass class AtLeastN(Generic[_MatcherT], _BaseWildcardNode): """ Matcher that matches ``n`` or more LibCST nodes in a row in a sequence. :class:`AtLeastN` defaults to matching against the :func:`DoNotCare` matcher, so if you do not specify a matcher as a child, :class:`AtLeastN` will match only by count. If you do specify a matcher as a child, :class:`AtLeastN` will instead make sure that each LibCST node matches the matcher supplied. For example, this will match all function calls with at least 3 arguments:: m.Call(args=[m.AtLeastN(n=3)]) This will match all function calls with 3 or more integer arguments:: m.Call(args=[m.AtLeastN(n=3, matcher=m.Arg(m.Integer()))]) You can combine sequence matchers with concrete matchers and special matchers and it will behave as you expect. For example, this will match all function calls that have 2 or more integer arguments in a row, followed by any arbitrary argument:: m.Call(args=[m.AtLeastN(n=2, matcher=m.Arg(m.Integer())), m.DoNotCare()]) And finally, this will match all function calls that have at least 5 arguments, the final one being an integer:: m.Call(args=[m.AtLeastN(n=4), m.Arg(m.Integer())]) """ def __init__( self, matcher: Union[_MatcherT, DoNotCareSentinel] = DoNotCareSentinel.DEFAULT, *, n: int, ) -> None: if n < 0: raise Exception(f"{self.__class__.__name__} n attribute must be positive") self._n: int = n self._matcher: Union[_MatcherT, DoNotCareSentinel] = matcher def n(self) -> int: """ The number of nodes in a row that must match :attr:`AtLeastN.matcher` for this matcher to be considered a match. If there are less than ``n`` matches, this matcher will not be considered a match. If there are equal to or more than ``n`` matches, this matcher will be considered a match. """ return self._n def matcher(self) -> Union[_MatcherT, DoNotCareSentinel]: """ The matcher which each node in a sequence needs to match. """ return self._matcher # pyre-fixme[15]: `__or__` overrides method defined in `type` inconsistently. def __or__(self, other: object) -> NoReturn: raise Exception("AtLeastN cannot be used in a OneOf matcher") def __and__(self, other: object) -> NoReturn: raise Exception("AtLeastN cannot be used in an AllOf matcher") def __invert__(self) -> NoReturn: raise Exception("Cannot invert an AtLeastN matcher!") def __repr__(self) -> str: if self._n == 0: return f"ZeroOrMore({repr(self._matcher)})" else: return f"AtLeastN({repr(self._matcher)}, n={self._n})" class AtMostN(Generic[_MatcherT], _BaseWildcardNode): """ Matcher that matches ``n`` or fewer LibCST nodes in a row in a sequence. :class:`AtMostN` defaults to matching against the :func:`DoNotCare` matcher, so if you do not specify a matcher as a child, :class:`AtMostN` will match only by count. If you do specify a matcher as a child, :class:`AtMostN` will instead make sure that each LibCST node matches the matcher supplied. For example, this will match all function calls with 3 or fewer arguments:: m.Call(args=[m.AtMostN(n=3)]) This will match all function calls with 0, 1 or 2 string arguments:: m.Call(args=[m.AtMostN(n=2, matcher=m.Arg(m.SimpleString()))]) You can combine sequence matchers with concrete matchers and special matchers and it will behave as you expect. For example, this will match all function calls that have 0, 1 or 2 string arguments in a row, followed by an arbitrary argument:: m.Call(args=[m.AtMostN(n=2, matcher=m.Arg(m.SimpleString())), m.DoNotCare()]) And finally, this will match all function calls that have at least 2 arguments, the final one being a string:: m.Call(args=[m.AtMostN(n=2), m.Arg(m.SimpleString())]) """ def __init__( self, matcher: Union[_MatcherT, DoNotCareSentinel] = DoNotCareSentinel.DEFAULT, *, n: int, ) -> None: if n < 0: raise Exception(f"{self.__class__.__name__} n attribute must be positive") self._n: int = n self._matcher: Union[_MatcherT, DoNotCareSentinel] = matcher def n(self) -> int: """ The number of nodes in a row that must match :attr:`AtLeastN.matcher` for this matcher to be considered a match. If there are less than or equal to ``n`` matches, then this matcher will be considered a match. Any more than ``n`` matches in a row and this matcher will stop matching and be considered not a match. """ return self._n def matcher(self) -> Union[_MatcherT, DoNotCareSentinel]: """ The matcher which each node in a sequence needs to match. """ return self._matcher # pyre-fixme[15]: `__or__` overrides method defined in `type` inconsistently. def __or__(self, other: object) -> NoReturn: raise Exception("AtMostN cannot be used in a OneOf matcher") def __and__(self, other: object) -> NoReturn: raise Exception("AtMostN cannot be used in an AllOf matcher") def __invert__(self) -> NoReturn: raise Exception("Cannot invert an AtMostN matcher!") def __repr__(self) -> str: if self._n == 1: return f"ZeroOrOne({repr(self._matcher)})" else: return f"AtMostN({repr(self._matcher)}, n={self._n})" def _construct_metadata_fetcher_null() -> ( Callable[[meta.ProviderT, libcst.CSTNode], object] ): def _fetch(provider: meta.ProviderT, node: libcst.CSTNode) -> NoReturn: raise LookupError( f"{provider.__name__} is not resolved; did you forget a MetadataWrapper?" ) return _fetch def _construct_metadata_fetcher_dependent( dependent_class: libcst.MetadataDependent, ) -> Callable[[meta.ProviderT, libcst.CSTNode], object]: def _fetch(provider: meta.ProviderT, node: libcst.CSTNode) -> object: return dependent_class.get_metadata(provider, node, _METADATA_MISSING_SENTINEL) return _fetch def _construct_metadata_fetcher_wrapper( wrapper: libcst.MetadataWrapper, ) -> Callable[[meta.ProviderT, libcst.CSTNode], object]: metadata: Dict[meta.ProviderT, Mapping[libcst.CSTNode, object]] = {} def _fetch(provider: meta.ProviderT, node: libcst.CSTNode) -> object: if provider not in metadata: metadata[provider] = wrapper.resolve(provider) node_metadata = metadata[provider].get(node, _METADATA_MISSING_SENTINEL) if isinstance(node_metadata, LazyValue): node_metadata = node_metadata() return node_metadata return _fetch class _ReplaceTransformer(libcst.CSTTransformer): def __init__( self, matcher: Union[ BaseMatcherNode, MatchIfTrue[libcst.CSTNode], _BaseMetadataMatcher, _InverseOf[ Union[ BaseMatcherNode, MatchIfTrue[libcst.CSTNode], _BaseMetadataMatcher, ] ], ], metadata_lookup: Callable[[meta.ProviderT, libcst.CSTNode], object], replacement: Union[ MaybeSentinel, RemovalSentinel, libcst.CSTNode, Callable[ [ libcst.CSTNode, Dict[str, Union[libcst.CSTNode, Sequence[libcst.CSTNode]]], ], Union[MaybeSentinel, RemovalSentinel, libcst.CSTNode], ], ], ) -> None: self.matcher = matcher self.metadata_lookup = metadata_lookup self.replacement: Callable[ [ libcst.CSTNode, Dict[str, Union[libcst.CSTNode, Sequence[libcst.CSTNode]]], ], Union[MaybeSentinel, RemovalSentinel, libcst.CSTNode], ] if inspect.isfunction(replacement): self.replacement = replacement elif isinstance(replacement, (MaybeSentinel, RemovalSentinel)): self.replacement = lambda node, matches: replacement else: # pyre-ignore We know this is a CSTNode. self.replacement = lambda node, matches: replacement.deep_clone() # We run into a really weird problem here, where we need to run the match # and extract step on the original node in order for metadata to work. # However, if we do that, then using things like `deep_replace` will fail # since any extracted nodes are the originals, not the updates and LibCST # does replacement by identity for safety reasons. If we try to run the # match and extract step on the updated node (or twice, once for the match # and once for the extract), it will fail to extract if any metadata-based # matchers are used. So, we try to compromise with the best of both worlds. # We track all node updates, and when we send the extracted nodes to the # replacement callable, we look up the original nodes and replace them with # updated nodes. In the case that an update made the node no-longer exist, # we act as if there was not a match (because in reality, there would not # have been if we had run the matcher on the update). self.node_lut: Dict[libcst.CSTNode, libcst.CSTNode] = {} def _node_translate( self, node_or_sequence: Union[libcst.CSTNode, Sequence[libcst.CSTNode]] ) -> Union[libcst.CSTNode, Sequence[libcst.CSTNode]]: if isinstance(node_or_sequence, Sequence): return tuple(self.node_lut[node] for node in node_or_sequence) else: return self.node_lut[node_or_sequence] def _extraction_translate( self, extracted: Dict[str, Union[libcst.CSTNode, Sequence[libcst.CSTNode]]] ) -> Dict[str, Union[libcst.CSTNode, Sequence[libcst.CSTNode]]]: return {key: self._node_translate(val) for key, val in extracted.items()} def on_leave( self, original_node: libcst.CSTNode, updated_node: libcst.CSTNode ) -> Union[libcst.CSTNode, MaybeSentinel, RemovalSentinel]: # Track original to updated node mapping for this node. self.node_lut[original_node] = updated_node # This gets complicated. We need to do the match on the original node, # but we want to do the extraction on the updated node. This is so # metadata works properly in matchers. So, if we get a match, we fix # up the nodes in the match and return that to the replacement lambda. extracted = _matches(original_node, self.matcher, self.metadata_lookup) if extracted is not None: try: # Attempt to do a translation from original to updated node. extracted = self._extraction_translate(extracted) except KeyError: # One of the nodes we looked up doesn't exist anymore, this # is no longer a match. This can happen if a child node was # modified, making this original match not applicable anymore. extracted = None if extracted is not None: # We're replacing this node entirely, so don't save the original # updated node. We don't want this to be part of a parent match # since we can't guarantee that the update matches anymore. del self.node_lut[original_node] return self.replacement(updated_node, extracted) return updated_node The provided code snippet includes necessary dependencies for implementing the `replace` function. Write a Python function `def replace( tree: Union[MaybeSentinel, RemovalSentinel, libcst.CSTNode, meta.MetadataWrapper], matcher: Union[BaseMatcherNode, MatchIfTrue[libcst.CSTNode], _BaseMetadataMatcher], replacement: Union[ MaybeSentinel, RemovalSentinel, libcst.CSTNode, Callable[ [ libcst.CSTNode, Dict[str, Union[libcst.CSTNode, Sequence[libcst.CSTNode]]], ], Union[MaybeSentinel, RemovalSentinel, libcst.CSTNode], ], ], *, metadata_resolver: Optional[ Union[libcst.MetadataDependent, libcst.MetadataWrapper] ] = None, ) -> Union[MaybeSentinel, RemovalSentinel, libcst.CSTNode]` to solve the following problem: Given an arbitrary node from a LibCST tree and an arbitrary matcher, iterates over that node and all children and replaces each node that matches the supplied matcher with a supplied replacement. Note that the replacement can either be a valid node type, or a callable which takes the matched node and a dictionary of any extracted child values and returns a valid node type. If you provide a valid LibCST node type, :func:`replace` will replace every node that matches the supplied matcher with the replacement node. If you provide a callable, :func:`replace` will run :func:`extract` over all matched nodes and call the callable with both the node that should be replaced and the dictionary returned by :func:`extract`. Under all circumstances a new tree is returned. :func:`extract` should be viewed as a short-cut to writing a transform which also returns a new tree even when no changes are applied. Note that the tree can also be a :class:`~libcst.RemovalSentinel` or a :class:`~libcst.MaybeSentinel` in order to use replace directly on transform results and node attributes. In these cases, :func:`replace` will return the same :class:`~libcst.RemovalSentinel` or :class:`~libcst.MaybeSentinel`. Note also that instead of a LibCST tree, you can instead pass in a :class:`~libcst.metadata.MetadataWrapper`. This mirrors the fact that you can call ``visit`` on a :class:`~libcst.metadata.MetadataWrapper` in order to iterate over it with a transform. If you provide a wrapper for the tree and do not set the ``metadata_resolver`` parameter specifically, it will automatically be set to the wrapper for you. The matcher can be any concrete matcher that subclasses from :class:`BaseMatcherNode`, or a :class:`OneOf`/:class:`AllOf` special matcher. Unlike :func:`matches`, it can also be a :class:`MatchIfTrue` or :func:`DoesNotMatch` matcher, since we are traversing the tree looking for matches. It cannot be a :class:`AtLeastN` or :class:`AtMostN` matcher because these types are wildcards which can only be usedi inside sequences. Here is the function: def replace( tree: Union[MaybeSentinel, RemovalSentinel, libcst.CSTNode, meta.MetadataWrapper], matcher: Union[BaseMatcherNode, MatchIfTrue[libcst.CSTNode], _BaseMetadataMatcher], replacement: Union[ MaybeSentinel, RemovalSentinel, libcst.CSTNode, Callable[ [ libcst.CSTNode, Dict[str, Union[libcst.CSTNode, Sequence[libcst.CSTNode]]], ], Union[MaybeSentinel, RemovalSentinel, libcst.CSTNode], ], ], *, metadata_resolver: Optional[ Union[libcst.MetadataDependent, libcst.MetadataWrapper] ] = None, ) -> Union[MaybeSentinel, RemovalSentinel, libcst.CSTNode]: """ Given an arbitrary node from a LibCST tree and an arbitrary matcher, iterates over that node and all children and replaces each node that matches the supplied matcher with a supplied replacement. Note that the replacement can either be a valid node type, or a callable which takes the matched node and a dictionary of any extracted child values and returns a valid node type. If you provide a valid LibCST node type, :func:`replace` will replace every node that matches the supplied matcher with the replacement node. If you provide a callable, :func:`replace` will run :func:`extract` over all matched nodes and call the callable with both the node that should be replaced and the dictionary returned by :func:`extract`. Under all circumstances a new tree is returned. :func:`extract` should be viewed as a short-cut to writing a transform which also returns a new tree even when no changes are applied. Note that the tree can also be a :class:`~libcst.RemovalSentinel` or a :class:`~libcst.MaybeSentinel` in order to use replace directly on transform results and node attributes. In these cases, :func:`replace` will return the same :class:`~libcst.RemovalSentinel` or :class:`~libcst.MaybeSentinel`. Note also that instead of a LibCST tree, you can instead pass in a :class:`~libcst.metadata.MetadataWrapper`. This mirrors the fact that you can call ``visit`` on a :class:`~libcst.metadata.MetadataWrapper` in order to iterate over it with a transform. If you provide a wrapper for the tree and do not set the ``metadata_resolver`` parameter specifically, it will automatically be set to the wrapper for you. The matcher can be any concrete matcher that subclasses from :class:`BaseMatcherNode`, or a :class:`OneOf`/:class:`AllOf` special matcher. Unlike :func:`matches`, it can also be a :class:`MatchIfTrue` or :func:`DoesNotMatch` matcher, since we are traversing the tree looking for matches. It cannot be a :class:`AtLeastN` or :class:`AtMostN` matcher because these types are wildcards which can only be usedi inside sequences. """ if isinstance(tree, (RemovalSentinel, MaybeSentinel)): # We can't do any replacements on this, so return the tree exactly. return tree if isinstance(matcher, (AtLeastN, AtMostN)): # We can't match this, since these matchers are forbidden at top level. # These are not subclasses of BaseMatcherNode, but in the case that the # user is not using type checking, this should still behave correctly. if isinstance(tree, libcst.CSTNode): return tree.deep_clone() elif isinstance(tree, meta.MetadataWrapper): return tree.module.deep_clone() else: raise Exception("Logic error!") if isinstance(tree, meta.MetadataWrapper) and metadata_resolver is None: # Provide a convenience for calling replace directly on a MetadataWrapper. metadata_resolver = tree if metadata_resolver is None: fetcher = _construct_metadata_fetcher_null() elif isinstance(metadata_resolver, libcst.MetadataWrapper): fetcher = _construct_metadata_fetcher_wrapper(metadata_resolver) else: fetcher = _construct_metadata_fetcher_dependent(metadata_resolver) replacer = _ReplaceTransformer(matcher, fetcher, replacement) new_tree = tree.visit(replacer) if isinstance(new_tree, FlattenSentinel): # The above transform never returns FlattenSentinel, so this isn't possible raise Exception("Logic error, cannot get a FlattenSentinel here!") return new_tree
Given an arbitrary node from a LibCST tree and an arbitrary matcher, iterates over that node and all children and replaces each node that matches the supplied matcher with a supplied replacement. Note that the replacement can either be a valid node type, or a callable which takes the matched node and a dictionary of any extracted child values and returns a valid node type. If you provide a valid LibCST node type, :func:`replace` will replace every node that matches the supplied matcher with the replacement node. If you provide a callable, :func:`replace` will run :func:`extract` over all matched nodes and call the callable with both the node that should be replaced and the dictionary returned by :func:`extract`. Under all circumstances a new tree is returned. :func:`extract` should be viewed as a short-cut to writing a transform which also returns a new tree even when no changes are applied. Note that the tree can also be a :class:`~libcst.RemovalSentinel` or a :class:`~libcst.MaybeSentinel` in order to use replace directly on transform results and node attributes. In these cases, :func:`replace` will return the same :class:`~libcst.RemovalSentinel` or :class:`~libcst.MaybeSentinel`. Note also that instead of a LibCST tree, you can instead pass in a :class:`~libcst.metadata.MetadataWrapper`. This mirrors the fact that you can call ``visit`` on a :class:`~libcst.metadata.MetadataWrapper` in order to iterate over it with a transform. If you provide a wrapper for the tree and do not set the ``metadata_resolver`` parameter specifically, it will automatically be set to the wrapper for you. The matcher can be any concrete matcher that subclasses from :class:`BaseMatcherNode`, or a :class:`OneOf`/:class:`AllOf` special matcher. Unlike :func:`matches`, it can also be a :class:`MatchIfTrue` or :func:`DoesNotMatch` matcher, since we are traversing the tree looking for matches. It cannot be a :class:`AtLeastN` or :class:`AtMostN` matcher because these types are wildcards which can only be usedi inside sequences.
4,932
from typing import Callable, TypeVar from libcst.matchers._matcher_base import BaseMatcherNode _CSTVisitFuncT = TypeVar("_CSTVisitFuncT") VISIT_POSITIVE_MATCHER_ATTR: str = "_call_if_inside_matcher" class BaseMatcherNode: """ Base class that all concrete matchers subclass from. :class:`OneOf` and :class:`AllOf` also subclass from this in order to allow them to be used in any place that a concrete matcher is allowed. This means that, for example, you can call :func:`matches` with a concrete matcher, or a :class:`OneOf` with several concrete matchers as options. """ # pyre-fixme[15]: `__or__` overrides method defined in `type` inconsistently. def __or__( self: _BaseMatcherNodeSelfT, other: _OtherNodeT ) -> "OneOf[Union[_BaseMatcherNodeSelfT, _OtherNodeT]]": return OneOf(self, other) def __and__( self: _BaseMatcherNodeSelfT, other: _OtherNodeT ) -> "AllOf[Union[_BaseMatcherNodeSelfT, _OtherNodeT]]": return AllOf(self, other) def __invert__(self: _BaseMatcherNodeSelfT) -> "_BaseMatcherNodeSelfT": return cast(_BaseMatcherNodeSelfT, _InverseOf(self)) The provided code snippet includes necessary dependencies for implementing the `call_if_inside` function. Write a Python function `def call_if_inside( matcher: BaseMatcherNode, # pyre-fixme[34]: `Variable[_CSTVisitFuncT]` isn't present in the function's parameters. ) -> Callable[[_CSTVisitFuncT], _CSTVisitFuncT]` to solve the following problem: A decorator for visit and leave methods inside a :class:`MatcherDecoratableTransformer` or a :class:`MatcherDecoratableVisitor`. A method that is decorated with this decorator will only be called if it or one of its parents matches the supplied matcher. Use this to selectively gate visit and leave methods to be called only when inside of another relevant node. Note that this works for both node and attribute methods, so you can decorate a ``visit_<Node>`` or a ``visit_<Node>_<Attr>`` method. Here is the function: def call_if_inside( matcher: BaseMatcherNode, # pyre-fixme[34]: `Variable[_CSTVisitFuncT]` isn't present in the function's parameters. ) -> Callable[[_CSTVisitFuncT], _CSTVisitFuncT]: """ A decorator for visit and leave methods inside a :class:`MatcherDecoratableTransformer` or a :class:`MatcherDecoratableVisitor`. A method that is decorated with this decorator will only be called if it or one of its parents matches the supplied matcher. Use this to selectively gate visit and leave methods to be called only when inside of another relevant node. Note that this works for both node and attribute methods, so you can decorate a ``visit_<Node>`` or a ``visit_<Node>_<Attr>`` method. """ def inner(original: _CSTVisitFuncT) -> _CSTVisitFuncT: setattr( original, VISIT_POSITIVE_MATCHER_ATTR, [*getattr(original, VISIT_POSITIVE_MATCHER_ATTR, []), matcher], ) return original return inner
A decorator for visit and leave methods inside a :class:`MatcherDecoratableTransformer` or a :class:`MatcherDecoratableVisitor`. A method that is decorated with this decorator will only be called if it or one of its parents matches the supplied matcher. Use this to selectively gate visit and leave methods to be called only when inside of another relevant node. Note that this works for both node and attribute methods, so you can decorate a ``visit_<Node>`` or a ``visit_<Node>_<Attr>`` method.
4,933
from typing import Callable, TypeVar from libcst.matchers._matcher_base import BaseMatcherNode _CSTVisitFuncT = TypeVar("_CSTVisitFuncT") VISIT_NEGATIVE_MATCHER_ATTR: str = "_call_if_not_inside_matcher" class BaseMatcherNode: """ Base class that all concrete matchers subclass from. :class:`OneOf` and :class:`AllOf` also subclass from this in order to allow them to be used in any place that a concrete matcher is allowed. This means that, for example, you can call :func:`matches` with a concrete matcher, or a :class:`OneOf` with several concrete matchers as options. """ # pyre-fixme[15]: `__or__` overrides method defined in `type` inconsistently. def __or__( self: _BaseMatcherNodeSelfT, other: _OtherNodeT ) -> "OneOf[Union[_BaseMatcherNodeSelfT, _OtherNodeT]]": return OneOf(self, other) def __and__( self: _BaseMatcherNodeSelfT, other: _OtherNodeT ) -> "AllOf[Union[_BaseMatcherNodeSelfT, _OtherNodeT]]": return AllOf(self, other) def __invert__(self: _BaseMatcherNodeSelfT) -> "_BaseMatcherNodeSelfT": return cast(_BaseMatcherNodeSelfT, _InverseOf(self)) The provided code snippet includes necessary dependencies for implementing the `call_if_not_inside` function. Write a Python function `def call_if_not_inside( matcher: BaseMatcherNode, # pyre-fixme[34]: `Variable[_CSTVisitFuncT]` isn't present in the function's parameters. ) -> Callable[[_CSTVisitFuncT], _CSTVisitFuncT]` to solve the following problem: A decorator for visit and leave methods inside a :class:`MatcherDecoratableTransformer` or a :class:`MatcherDecoratableVisitor`. A method that is decorated with this decorator will only be called if it or one of its parents does not match the supplied matcher. Use this to selectively gate visit and leave methods to be called only when outside of another relevant node. Note that this works for both node and attribute methods, so you can decorate a ``visit_<Node>`` or a ``visit_<Node>_<Attr>`` method. Here is the function: def call_if_not_inside( matcher: BaseMatcherNode, # pyre-fixme[34]: `Variable[_CSTVisitFuncT]` isn't present in the function's parameters. ) -> Callable[[_CSTVisitFuncT], _CSTVisitFuncT]: """ A decorator for visit and leave methods inside a :class:`MatcherDecoratableTransformer` or a :class:`MatcherDecoratableVisitor`. A method that is decorated with this decorator will only be called if it or one of its parents does not match the supplied matcher. Use this to selectively gate visit and leave methods to be called only when outside of another relevant node. Note that this works for both node and attribute methods, so you can decorate a ``visit_<Node>`` or a ``visit_<Node>_<Attr>`` method. """ def inner(original: _CSTVisitFuncT) -> _CSTVisitFuncT: setattr( original, VISIT_NEGATIVE_MATCHER_ATTR, [*getattr(original, VISIT_NEGATIVE_MATCHER_ATTR, []), matcher], ) return original return inner
A decorator for visit and leave methods inside a :class:`MatcherDecoratableTransformer` or a :class:`MatcherDecoratableVisitor`. A method that is decorated with this decorator will only be called if it or one of its parents does not match the supplied matcher. Use this to selectively gate visit and leave methods to be called only when outside of another relevant node. Note that this works for both node and attribute methods, so you can decorate a ``visit_<Node>`` or a ``visit_<Node>_<Attr>`` method.
4,934
from typing import Callable, TypeVar from libcst.matchers._matcher_base import BaseMatcherNode _CSTVisitFuncT = TypeVar("_CSTVisitFuncT") CONSTRUCTED_VISIT_MATCHER_ATTR: str = "_visit_matcher" class BaseMatcherNode: """ Base class that all concrete matchers subclass from. :class:`OneOf` and :class:`AllOf` also subclass from this in order to allow them to be used in any place that a concrete matcher is allowed. This means that, for example, you can call :func:`matches` with a concrete matcher, or a :class:`OneOf` with several concrete matchers as options. """ # pyre-fixme[15]: `__or__` overrides method defined in `type` inconsistently. def __or__( self: _BaseMatcherNodeSelfT, other: _OtherNodeT ) -> "OneOf[Union[_BaseMatcherNodeSelfT, _OtherNodeT]]": return OneOf(self, other) def __and__( self: _BaseMatcherNodeSelfT, other: _OtherNodeT ) -> "AllOf[Union[_BaseMatcherNodeSelfT, _OtherNodeT]]": return AllOf(self, other) def __invert__(self: _BaseMatcherNodeSelfT) -> "_BaseMatcherNodeSelfT": return cast(_BaseMatcherNodeSelfT, _InverseOf(self)) The provided code snippet includes necessary dependencies for implementing the `visit` function. Write a Python function `def visit(matcher: BaseMatcherNode) -> Callable[[_CSTVisitFuncT], _CSTVisitFuncT]` to solve the following problem: A decorator that allows a method inside a :class:`MatcherDecoratableTransformer` or a :class:`MatcherDecoratableVisitor` visitor to be called when visiting a node that matches the provided matcher. Note that you can use this in combination with :func:`call_if_inside` and :func:`call_if_not_inside` decorators. Unlike explicit ``visit_<Node>`` and ``leave_<Node>`` methods, functions decorated with this decorator cannot stop child traversal by returning ``False``. Decorated visit functions should always have a return annotation of ``None``. There is no restriction on the number of visit decorators allowed on a method. There is also no restriction on the number of methods that may be decorated with the same matcher. When multiple visit decorators are found on the same method, they act as a simple or, and the method will be called when any one of the contained matches is ``True``. Here is the function: def visit(matcher: BaseMatcherNode) -> Callable[[_CSTVisitFuncT], _CSTVisitFuncT]: """ A decorator that allows a method inside a :class:`MatcherDecoratableTransformer` or a :class:`MatcherDecoratableVisitor` visitor to be called when visiting a node that matches the provided matcher. Note that you can use this in combination with :func:`call_if_inside` and :func:`call_if_not_inside` decorators. Unlike explicit ``visit_<Node>`` and ``leave_<Node>`` methods, functions decorated with this decorator cannot stop child traversal by returning ``False``. Decorated visit functions should always have a return annotation of ``None``. There is no restriction on the number of visit decorators allowed on a method. There is also no restriction on the number of methods that may be decorated with the same matcher. When multiple visit decorators are found on the same method, they act as a simple or, and the method will be called when any one of the contained matches is ``True``. """ def inner(original: _CSTVisitFuncT) -> _CSTVisitFuncT: setattr( original, CONSTRUCTED_VISIT_MATCHER_ATTR, [*getattr(original, CONSTRUCTED_VISIT_MATCHER_ATTR, []), matcher], ) return original return inner
A decorator that allows a method inside a :class:`MatcherDecoratableTransformer` or a :class:`MatcherDecoratableVisitor` visitor to be called when visiting a node that matches the provided matcher. Note that you can use this in combination with :func:`call_if_inside` and :func:`call_if_not_inside` decorators. Unlike explicit ``visit_<Node>`` and ``leave_<Node>`` methods, functions decorated with this decorator cannot stop child traversal by returning ``False``. Decorated visit functions should always have a return annotation of ``None``. There is no restriction on the number of visit decorators allowed on a method. There is also no restriction on the number of methods that may be decorated with the same matcher. When multiple visit decorators are found on the same method, they act as a simple or, and the method will be called when any one of the contained matches is ``True``.
4,935
from typing import Callable, TypeVar from libcst.matchers._matcher_base import BaseMatcherNode _CSTVisitFuncT = TypeVar("_CSTVisitFuncT") CONSTRUCTED_LEAVE_MATCHER_ATTR: str = "_leave_matcher" class BaseMatcherNode: """ Base class that all concrete matchers subclass from. :class:`OneOf` and :class:`AllOf` also subclass from this in order to allow them to be used in any place that a concrete matcher is allowed. This means that, for example, you can call :func:`matches` with a concrete matcher, or a :class:`OneOf` with several concrete matchers as options. """ # pyre-fixme[15]: `__or__` overrides method defined in `type` inconsistently. def __or__( self: _BaseMatcherNodeSelfT, other: _OtherNodeT ) -> "OneOf[Union[_BaseMatcherNodeSelfT, _OtherNodeT]]": return OneOf(self, other) def __and__( self: _BaseMatcherNodeSelfT, other: _OtherNodeT ) -> "AllOf[Union[_BaseMatcherNodeSelfT, _OtherNodeT]]": return AllOf(self, other) def __invert__(self: _BaseMatcherNodeSelfT) -> "_BaseMatcherNodeSelfT": return cast(_BaseMatcherNodeSelfT, _InverseOf(self)) The provided code snippet includes necessary dependencies for implementing the `leave` function. Write a Python function `def leave(matcher: BaseMatcherNode) -> Callable[[_CSTVisitFuncT], _CSTVisitFuncT]` to solve the following problem: A decorator that allows a method inside a :class:`MatcherDecoratableTransformer` or a :class:`MatcherDecoratableVisitor` visitor to be called when leaving a node that matches the provided matcher. Note that you can use this in combination with :func:`call_if_inside` and :func:`call_if_not_inside` decorators. There is no restriction on the number of leave decorators allowed on a method. There is also no restriction on the number of methods that may be decorated with the same matcher. When multiple leave decorators are found on the same method, they act as a simple or, and the method will be called when any one of the contained matches is ``True``. Here is the function: def leave(matcher: BaseMatcherNode) -> Callable[[_CSTVisitFuncT], _CSTVisitFuncT]: """ A decorator that allows a method inside a :class:`MatcherDecoratableTransformer` or a :class:`MatcherDecoratableVisitor` visitor to be called when leaving a node that matches the provided matcher. Note that you can use this in combination with :func:`call_if_inside` and :func:`call_if_not_inside` decorators. There is no restriction on the number of leave decorators allowed on a method. There is also no restriction on the number of methods that may be decorated with the same matcher. When multiple leave decorators are found on the same method, they act as a simple or, and the method will be called when any one of the contained matches is ``True``. """ def inner(original: _CSTVisitFuncT) -> _CSTVisitFuncT: setattr( original, CONSTRUCTED_LEAVE_MATCHER_ATTR, [*getattr(original, CONSTRUCTED_LEAVE_MATCHER_ATTR, []), matcher], ) return original return inner
A decorator that allows a method inside a :class:`MatcherDecoratableTransformer` or a :class:`MatcherDecoratableVisitor` visitor to be called when leaving a node that matches the provided matcher. Note that you can use this in combination with :func:`call_if_inside` and :func:`call_if_not_inside` decorators. There is no restriction on the number of leave decorators allowed on a method. There is also no restriction on the number of methods that may be decorated with the same matcher. When multiple leave decorators are found on the same method, they act as a simple or, and the method will be called when any one of the contained matches is ``True``.
4,936
from inspect import ismethod, signature from typing import ( Any, Callable, cast, Dict, get_type_hints, List, Optional, Sequence, Set, Tuple, Type, Union, ) import libcst as cst from libcst import CSTTransformer, CSTVisitor from libcst._types import CSTNodeT from libcst.matchers._decorators import ( CONSTRUCTED_LEAVE_MATCHER_ATTR, CONSTRUCTED_VISIT_MATCHER_ATTR, VISIT_NEGATIVE_MATCHER_ATTR, VISIT_POSITIVE_MATCHER_ATTR, ) from libcst.matchers._matcher_base import ( AllOf, AtLeastN, AtMostN, BaseMatcherNode, extract, extractall, findall, matches, MatchIfTrue, MatchMetadata, MatchMetadataIfTrue, OneOf, replace, ) from libcst.matchers._return_types import TYPED_FUNCTION_RETURN_MAPPING class MatchDecoratorMismatch(Exception): def __init__(self, func: str, message: str) -> None: def __reduce__( self, ) -> Tuple[Callable[..., "MatchDecoratorMismatch"], Tuple[object, ...]]: def _match_decorator_unpickler(kwargs: Any) -> "MatchDecoratorMismatch": return MatchDecoratorMismatch(**kwargs)
null
4,937
from inspect import ismethod, signature from typing import ( Any, Callable, cast, Dict, get_type_hints, List, Optional, Sequence, Set, Tuple, Type, Union, ) import libcst as cst from libcst import CSTTransformer, CSTVisitor from libcst._types import CSTNodeT from libcst.matchers._decorators import ( CONSTRUCTED_LEAVE_MATCHER_ATTR, CONSTRUCTED_VISIT_MATCHER_ATTR, VISIT_NEGATIVE_MATCHER_ATTR, VISIT_POSITIVE_MATCHER_ATTR, ) from libcst.matchers._matcher_base import ( AllOf, AtLeastN, AtMostN, BaseMatcherNode, extract, extractall, findall, matches, MatchIfTrue, MatchMetadata, MatchMetadataIfTrue, OneOf, replace, ) from libcst.matchers._return_types import TYPED_FUNCTION_RETURN_MAPPING class MatchDecoratorMismatch(Exception): def __init__(self, func: str, message: str) -> None: def __reduce__( self, ) -> Tuple[Callable[..., "MatchDecoratorMismatch"], Tuple[object, ...]]: def _get_possible_match_classes(matcher: BaseMatcherNode) -> List[Type[cst.CSTNode]]: def _verify_return_annotation( possible_match_classes: Sequence[Type[cst.CSTNode]], # pyre-ignore We only care that meth is callable. meth: Callable[..., Any], decorator_name: str, *, expected_none: bool, ) -> None: def _verify_parameter_annotations( possible_match_classes: Sequence[Type[cst.CSTNode]], # pyre-ignore We only care that meth is callable. meth: Callable[..., Any], decorator_name: str, *, expected_param_count: int, ) -> None: class BaseMatcherNode: def __or__( self: _BaseMatcherNodeSelfT, other: _OtherNodeT ) -> "OneOf[Union[_BaseMatcherNodeSelfT, _OtherNodeT]]": def __and__( self: _BaseMatcherNodeSelfT, other: _OtherNodeT ) -> "AllOf[Union[_BaseMatcherNodeSelfT, _OtherNodeT]]": def __invert__(self: _BaseMatcherNodeSelfT) -> "_BaseMatcherNodeSelfT": class MatchIfTrue(Generic[_MatchIfTrueT]): def __init__(self, func: Callable[[_MatchIfTrueT], bool]) -> None: def func(self) -> Callable[[_MatchIfTrueT], bool]: def __or__( self, other: _OtherNodeT ) -> "OneOf[Union[MatchIfTrue[_MatchIfTrueT], _OtherNodeT]]": def __and__( self, other: _OtherNodeT ) -> "AllOf[Union[MatchIfTrue[_MatchIfTrueT], _OtherNodeT]]": def __invert__(self) -> "MatchIfTrue[_MatchIfTrueT]": def __repr__(self) -> str: class AtLeastN(Generic[_MatcherT], _BaseWildcardNode): def __init__( self, matcher: Union[_MatcherT, DoNotCareSentinel] = DoNotCareSentinel.DEFAULT, *, n: int, ) -> None: def n(self) -> int: def matcher(self) -> Union[_MatcherT, DoNotCareSentinel]: def __or__(self, other: object) -> NoReturn: def __and__(self, other: object) -> NoReturn: def __invert__(self) -> NoReturn: def __repr__(self) -> str: class AtMostN(Generic[_MatcherT], _BaseWildcardNode): def __init__( self, matcher: Union[_MatcherT, DoNotCareSentinel] = DoNotCareSentinel.DEFAULT, *, n: int, ) -> None: def n(self) -> int: def matcher(self) -> Union[_MatcherT, DoNotCareSentinel]: def __or__(self, other: object) -> NoReturn: def __and__(self, other: object) -> NoReturn: def __invert__(self) -> NoReturn: def __repr__(self) -> str: def _check_types( # pyre-ignore We don't care about the type of sequence, just that its callable. decoratormap: Dict[BaseMatcherNode, Sequence[Callable[..., Any]]], decorator_name: str, *, expected_param_count: int, expected_none_return: bool, ) -> None: for matcher, methods in decoratormap.items(): # Given the matcher class we have, get the list of possible cst nodes that # could be passed to the functionis we wrap. possible_match_classes = _get_possible_match_classes(matcher) has_invalid_top_level = any( isinstance(m, (AtLeastN, AtMostN, MatchIfTrue)) for m in possible_match_classes ) # Now, loop through each function we wrap and verify that the type signature # is valid. for meth in methods: # First thing first, make sure this isn't wrapping an inner class. if not ismethod(meth): raise MatchDecoratorMismatch( meth.__qualname__, "Matcher decorators should only be used on methods of " + "MatcherDecoratableTransformer or " + "MatcherDecoratableVisitor", ) if has_invalid_top_level: raise MatchDecoratorMismatch( meth.__qualname__, "The root matcher in a matcher decorator cannot be an " + "AtLeastN, AtMostN or MatchIfTrue matcher", ) # Now, check that the return annotation is valid. _verify_return_annotation( possible_match_classes, meth, decorator_name, expected_none=expected_none_return, ) # Finally, check that the parameter annotations are valid. _verify_parameter_annotations( possible_match_classes, meth, decorator_name, expected_param_count=expected_param_count, )
null
4,938
from inspect import ismethod, signature from typing import ( Any, Callable, cast, Dict, get_type_hints, List, Optional, Sequence, Set, Tuple, Type, Union, ) import libcst as cst from libcst import CSTTransformer, CSTVisitor from libcst._types import CSTNodeT from libcst.matchers._decorators import ( CONSTRUCTED_LEAVE_MATCHER_ATTR, CONSTRUCTED_VISIT_MATCHER_ATTR, VISIT_NEGATIVE_MATCHER_ATTR, VISIT_POSITIVE_MATCHER_ATTR, ) from libcst.matchers._matcher_base import ( AllOf, AtLeastN, AtMostN, BaseMatcherNode, extract, extractall, findall, matches, MatchIfTrue, MatchMetadata, MatchMetadataIfTrue, OneOf, replace, ) from libcst.matchers._return_types import TYPED_FUNCTION_RETURN_MAPPING VISIT_POSITIVE_MATCHER_ATTR: str = "_call_if_inside_matcher" VISIT_NEGATIVE_MATCHER_ATTR: str = "_call_if_not_inside_matcher" class BaseMatcherNode: """ Base class that all concrete matchers subclass from. :class:`OneOf` and :class:`AllOf` also subclass from this in order to allow them to be used in any place that a concrete matcher is allowed. This means that, for example, you can call :func:`matches` with a concrete matcher, or a :class:`OneOf` with several concrete matchers as options. """ # pyre-fixme[15]: `__or__` overrides method defined in `type` inconsistently. def __or__( self: _BaseMatcherNodeSelfT, other: _OtherNodeT ) -> "OneOf[Union[_BaseMatcherNodeSelfT, _OtherNodeT]]": return OneOf(self, other) def __and__( self: _BaseMatcherNodeSelfT, other: _OtherNodeT ) -> "AllOf[Union[_BaseMatcherNodeSelfT, _OtherNodeT]]": return AllOf(self, other) def __invert__(self: _BaseMatcherNodeSelfT) -> "_BaseMatcherNodeSelfT": return cast(_BaseMatcherNodeSelfT, _InverseOf(self)) def _gather_matchers(obj: object) -> Set[BaseMatcherNode]: visit_matchers: Set[BaseMatcherNode] = set() for func in dir(obj): try: for matcher in getattr(getattr(obj, func), VISIT_POSITIVE_MATCHER_ATTR, []): visit_matchers.add(cast(BaseMatcherNode, matcher)) for matcher in getattr(getattr(obj, func), VISIT_NEGATIVE_MATCHER_ATTR, []): visit_matchers.add(cast(BaseMatcherNode, matcher)) except Exception: # This could be a caculated property, and calling getattr() evaluates it. # We have no control over the implementation detail, so if it raises, we # should not crash. pass return visit_matchers
null
4,939
from inspect import ismethod, signature from typing import ( Any, Callable, cast, Dict, get_type_hints, List, Optional, Sequence, Set, Tuple, Type, Union, ) import libcst as cst from libcst import CSTTransformer, CSTVisitor from libcst._types import CSTNodeT from libcst.matchers._decorators import ( CONSTRUCTED_LEAVE_MATCHER_ATTR, CONSTRUCTED_VISIT_MATCHER_ATTR, VISIT_NEGATIVE_MATCHER_ATTR, VISIT_POSITIVE_MATCHER_ATTR, ) from libcst.matchers._matcher_base import ( AllOf, AtLeastN, AtMostN, BaseMatcherNode, extract, extractall, findall, matches, MatchIfTrue, MatchMetadata, MatchMetadataIfTrue, OneOf, replace, ) from libcst.matchers._return_types import TYPED_FUNCTION_RETURN_MAPPING def _assert_not_concrete( decorator_name: str, func: Callable[[cst.CSTNode], None] ) -> None: if func.__name__ in CONCRETE_METHODS: raise MatchDecoratorMismatch( func.__qualname__, f"@{decorator_name} should not decorate functions that are concrete " + "visit or leave methods.", ) CONSTRUCTED_VISIT_MATCHER_ATTR: str = "_visit_matcher" class BaseMatcherNode: """ Base class that all concrete matchers subclass from. :class:`OneOf` and :class:`AllOf` also subclass from this in order to allow them to be used in any place that a concrete matcher is allowed. This means that, for example, you can call :func:`matches` with a concrete matcher, or a :class:`OneOf` with several concrete matchers as options. """ # pyre-fixme[15]: `__or__` overrides method defined in `type` inconsistently. def __or__( self: _BaseMatcherNodeSelfT, other: _OtherNodeT ) -> "OneOf[Union[_BaseMatcherNodeSelfT, _OtherNodeT]]": return OneOf(self, other) def __and__( self: _BaseMatcherNodeSelfT, other: _OtherNodeT ) -> "AllOf[Union[_BaseMatcherNodeSelfT, _OtherNodeT]]": return AllOf(self, other) def __invert__(self: _BaseMatcherNodeSelfT) -> "_BaseMatcherNodeSelfT": return cast(_BaseMatcherNodeSelfT, _InverseOf(self)) def _gather_constructed_visit_funcs( obj: object, ) -> Dict[BaseMatcherNode, Sequence[Callable[[cst.CSTNode], None]]]: constructed_visitors: Dict[ BaseMatcherNode, Sequence[Callable[[cst.CSTNode], None]] ] = {} for funcname in dir(obj): try: possible_func = getattr(obj, funcname) if not ismethod(possible_func): continue func = cast(Callable[[cst.CSTNode], None], possible_func) except Exception: # This could be a caculated property, and calling getattr() evaluates it. # We have no control over the implementation detail, so if it raises, we # should not crash. continue matchers = getattr(func, CONSTRUCTED_VISIT_MATCHER_ATTR, []) if matchers: # Make sure that we aren't accidentally putting a @visit on a visit_Node. _assert_not_concrete("visit", func) for matcher in matchers: casted_matcher = cast(BaseMatcherNode, matcher) constructed_visitors[casted_matcher] = ( *constructed_visitors.get(casted_matcher, ()), func, ) return constructed_visitors
null
4,940
from inspect import ismethod, signature from typing import ( Any, Callable, cast, Dict, get_type_hints, List, Optional, Sequence, Set, Tuple, Type, Union, ) import libcst as cst from libcst import CSTTransformer, CSTVisitor from libcst._types import CSTNodeT from libcst.matchers._decorators import ( CONSTRUCTED_LEAVE_MATCHER_ATTR, CONSTRUCTED_VISIT_MATCHER_ATTR, VISIT_NEGATIVE_MATCHER_ATTR, VISIT_POSITIVE_MATCHER_ATTR, ) from libcst.matchers._matcher_base import ( AllOf, AtLeastN, AtMostN, BaseMatcherNode, extract, extractall, findall, matches, MatchIfTrue, MatchMetadata, MatchMetadataIfTrue, OneOf, replace, ) from libcst.matchers._return_types import TYPED_FUNCTION_RETURN_MAPPING def _assert_not_concrete( decorator_name: str, func: Callable[[cst.CSTNode], None] ) -> None: CONSTRUCTED_LEAVE_MATCHER_ATTR: str = "_leave_matcher" class BaseMatcherNode: def __or__( self: _BaseMatcherNodeSelfT, other: _OtherNodeT ) -> "OneOf[Union[_BaseMatcherNodeSelfT, _OtherNodeT]]": def __and__( self: _BaseMatcherNodeSelfT, other: _OtherNodeT ) -> "AllOf[Union[_BaseMatcherNodeSelfT, _OtherNodeT]]": def __invert__(self: _BaseMatcherNodeSelfT) -> "_BaseMatcherNodeSelfT": def _gather_constructed_leave_funcs( obj: object, ) -> Dict[BaseMatcherNode, Sequence[Callable[..., Any]]]: constructed_visitors: Dict[ BaseMatcherNode, Sequence[Callable[[cst.CSTNode], None]] ] = {} for funcname in dir(obj): try: possible_func = getattr(obj, funcname) if not ismethod(possible_func): continue func = cast(Callable[[cst.CSTNode], None], possible_func) except Exception: # This could be a caculated property, and calling getattr() evaluates it. # We have no control over the implementation detail, so if it raises, we # should not crash. continue matchers = getattr(func, CONSTRUCTED_LEAVE_MATCHER_ATTR, []) if matchers: # Make sure that we aren't accidentally putting a @leave on a leave_Node. _assert_not_concrete("leave", func) for matcher in matchers: casted_matcher = cast(BaseMatcherNode, matcher) constructed_visitors[casted_matcher] = ( *constructed_visitors.get(casted_matcher, ()), func, ) return constructed_visitors
null
4,941
from inspect import ismethod, signature from typing import ( Any, Callable, cast, Dict, get_type_hints, List, Optional, Sequence, Set, Tuple, Type, Union, ) import libcst as cst from libcst import CSTTransformer, CSTVisitor from libcst._types import CSTNodeT from libcst.matchers._decorators import ( CONSTRUCTED_LEAVE_MATCHER_ATTR, CONSTRUCTED_VISIT_MATCHER_ATTR, VISIT_NEGATIVE_MATCHER_ATTR, VISIT_POSITIVE_MATCHER_ATTR, ) from libcst.matchers._matcher_base import ( AllOf, AtLeastN, AtMostN, BaseMatcherNode, extract, extractall, findall, matches, MatchIfTrue, MatchMetadata, MatchMetadataIfTrue, OneOf, replace, ) from libcst.matchers._return_types import TYPED_FUNCTION_RETURN_MAPPING class BaseMatcherNode: """ Base class that all concrete matchers subclass from. :class:`OneOf` and :class:`AllOf` also subclass from this in order to allow them to be used in any place that a concrete matcher is allowed. This means that, for example, you can call :func:`matches` with a concrete matcher, or a :class:`OneOf` with several concrete matchers as options. """ # pyre-fixme[15]: `__or__` overrides method defined in `type` inconsistently. def __or__( self: _BaseMatcherNodeSelfT, other: _OtherNodeT ) -> "OneOf[Union[_BaseMatcherNodeSelfT, _OtherNodeT]]": return OneOf(self, other) def __and__( self: _BaseMatcherNodeSelfT, other: _OtherNodeT ) -> "AllOf[Union[_BaseMatcherNodeSelfT, _OtherNodeT]]": return AllOf(self, other) def __invert__(self: _BaseMatcherNodeSelfT) -> "_BaseMatcherNodeSelfT": return cast(_BaseMatcherNodeSelfT, _InverseOf(self)) def matches( node: Union[MaybeSentinel, RemovalSentinel, libcst.CSTNode], matcher: BaseMatcherNode, *, metadata_resolver: Optional[ Union[libcst.MetadataDependent, libcst.MetadataWrapper] ] = None, ) -> bool: """ Given an arbitrary node from a LibCST tree, and an arbitrary matcher, returns ``True`` if the node matches the shape defined by the matcher. Note that the node can also be a :class:`~libcst.RemovalSentinel` or a :class:`~libcst.MaybeSentinel` in order to use matches directly on transform results and node attributes. In these cases, :func:`matches` will always return ``False``. The matcher can be any concrete matcher that subclasses from :class:`BaseMatcherNode`, or a :class:`OneOf`/:class:`AllOf` special matcher. It cannot be a :class:`MatchIfTrue` or a :func:`DoesNotMatch` matcher since these are redundant. It cannot be a :class:`AtLeastN` or :class:`AtMostN` matcher because these types are wildcards which can only be used inside sequences. """ return extract(node, matcher, metadata_resolver=metadata_resolver) is not None def _visit_matchers( matchers: Dict[BaseMatcherNode, Optional[cst.CSTNode]], node: cst.CSTNode, metadata_resolver: cst.MetadataDependent, ) -> Dict[BaseMatcherNode, Optional[cst.CSTNode]]: new_matchers: Dict[BaseMatcherNode, Optional[cst.CSTNode]] = {} for matcher, existing_node in matchers.items(): # We don't care about visiting matchers that are already true. if existing_node is None and matches( node, matcher, metadata_resolver=metadata_resolver ): # This node matches! Remember which node it was so we can # cancel it later. new_matchers[matcher] = node else: new_matchers[matcher] = existing_node return new_matchers
null
4,942
from inspect import ismethod, signature from typing import ( Any, Callable, cast, Dict, get_type_hints, List, Optional, Sequence, Set, Tuple, Type, Union, ) import libcst as cst from libcst import CSTTransformer, CSTVisitor from libcst._types import CSTNodeT from libcst.matchers._decorators import ( CONSTRUCTED_LEAVE_MATCHER_ATTR, CONSTRUCTED_VISIT_MATCHER_ATTR, VISIT_NEGATIVE_MATCHER_ATTR, VISIT_POSITIVE_MATCHER_ATTR, ) from libcst.matchers._matcher_base import ( AllOf, AtLeastN, AtMostN, BaseMatcherNode, extract, extractall, findall, matches, MatchIfTrue, MatchMetadata, MatchMetadataIfTrue, OneOf, replace, ) from libcst.matchers._return_types import TYPED_FUNCTION_RETURN_MAPPING class BaseMatcherNode: """ Base class that all concrete matchers subclass from. :class:`OneOf` and :class:`AllOf` also subclass from this in order to allow them to be used in any place that a concrete matcher is allowed. This means that, for example, you can call :func:`matches` with a concrete matcher, or a :class:`OneOf` with several concrete matchers as options. """ # pyre-fixme[15]: `__or__` overrides method defined in `type` inconsistently. def __or__( self: _BaseMatcherNodeSelfT, other: _OtherNodeT ) -> "OneOf[Union[_BaseMatcherNodeSelfT, _OtherNodeT]]": return OneOf(self, other) def __and__( self: _BaseMatcherNodeSelfT, other: _OtherNodeT ) -> "AllOf[Union[_BaseMatcherNodeSelfT, _OtherNodeT]]": return AllOf(self, other) def __invert__(self: _BaseMatcherNodeSelfT) -> "_BaseMatcherNodeSelfT": return cast(_BaseMatcherNodeSelfT, _InverseOf(self)) def _leave_matchers( matchers: Dict[BaseMatcherNode, Optional[cst.CSTNode]], node: cst.CSTNode ) -> Dict[BaseMatcherNode, Optional[cst.CSTNode]]: new_matchers: Dict[BaseMatcherNode, Optional[cst.CSTNode]] = {} for matcher, existing_node in matchers.items(): if node is existing_node: # This node matches, so we are no longer inside it. new_matchers[matcher] = None else: # We aren't leaving this node. new_matchers[matcher] = existing_node return new_matchers
null
4,943
from inspect import ismethod, signature from typing import ( Any, Callable, cast, Dict, get_type_hints, List, Optional, Sequence, Set, Tuple, Type, Union, ) import libcst as cst from libcst import CSTTransformer, CSTVisitor from libcst._types import CSTNodeT from libcst.matchers._decorators import ( CONSTRUCTED_LEAVE_MATCHER_ATTR, CONSTRUCTED_VISIT_MATCHER_ATTR, VISIT_NEGATIVE_MATCHER_ATTR, VISIT_POSITIVE_MATCHER_ATTR, ) from libcst.matchers._matcher_base import ( AllOf, AtLeastN, AtMostN, BaseMatcherNode, extract, extractall, findall, matches, MatchIfTrue, MatchMetadata, MatchMetadataIfTrue, OneOf, replace, ) from libcst.matchers._return_types import TYPED_FUNCTION_RETURN_MAPPING def _should_allow_visit( all_matchers: Dict[BaseMatcherNode, Optional[cst.CSTNode]], obj: object ) -> bool: return _all_positive_matchers_true( all_matchers, obj ) and _all_negative_matchers_false(all_matchers, obj) class BaseMatcherNode: """ Base class that all concrete matchers subclass from. :class:`OneOf` and :class:`AllOf` also subclass from this in order to allow them to be used in any place that a concrete matcher is allowed. This means that, for example, you can call :func:`matches` with a concrete matcher, or a :class:`OneOf` with several concrete matchers as options. """ # pyre-fixme[15]: `__or__` overrides method defined in `type` inconsistently. def __or__( self: _BaseMatcherNodeSelfT, other: _OtherNodeT ) -> "OneOf[Union[_BaseMatcherNodeSelfT, _OtherNodeT]]": return OneOf(self, other) def __and__( self: _BaseMatcherNodeSelfT, other: _OtherNodeT ) -> "AllOf[Union[_BaseMatcherNodeSelfT, _OtherNodeT]]": return AllOf(self, other) def __invert__(self: _BaseMatcherNodeSelfT) -> "_BaseMatcherNodeSelfT": return cast(_BaseMatcherNodeSelfT, _InverseOf(self)) def matches( node: Union[MaybeSentinel, RemovalSentinel, libcst.CSTNode], matcher: BaseMatcherNode, *, metadata_resolver: Optional[ Union[libcst.MetadataDependent, libcst.MetadataWrapper] ] = None, ) -> bool: """ Given an arbitrary node from a LibCST tree, and an arbitrary matcher, returns ``True`` if the node matches the shape defined by the matcher. Note that the node can also be a :class:`~libcst.RemovalSentinel` or a :class:`~libcst.MaybeSentinel` in order to use matches directly on transform results and node attributes. In these cases, :func:`matches` will always return ``False``. The matcher can be any concrete matcher that subclasses from :class:`BaseMatcherNode`, or a :class:`OneOf`/:class:`AllOf` special matcher. It cannot be a :class:`MatchIfTrue` or a :func:`DoesNotMatch` matcher since these are redundant. It cannot be a :class:`AtLeastN` or :class:`AtMostN` matcher because these types are wildcards which can only be used inside sequences. """ return extract(node, matcher, metadata_resolver=metadata_resolver) is not None def _visit_constructed_funcs( visit_funcs: Dict[BaseMatcherNode, Sequence[Callable[[cst.CSTNode], None]]], all_matchers: Dict[BaseMatcherNode, Optional[cst.CSTNode]], node: cst.CSTNode, metadata_resolver: cst.MetadataDependent, ) -> None: for matcher, visit_funcs in visit_funcs.items(): if matches(node, matcher, metadata_resolver=metadata_resolver): for visit_func in visit_funcs: if _should_allow_visit(all_matchers, visit_func): visit_func(node)
null
4,944
import argparse import ast import builtins import dataclasses import functools import sys from typing import cast, Dict, List, Optional, Sequence, Set, Tuple, Union from typing_extensions import TypeAlias import libcst as cst import libcst.matchers as m from libcst.codemod import CodemodContext, VisitorBasedCodemodCommand def _ast_for_statement(node: cst.CSTNode) -> ast.stmt: """ Get the type-comment-enriched python AST for a node. If there are illegal type comments, this can return a SyntaxError. In that case, return the same node with no type comments (which will cause this codemod to ignore it). """ code = _code_for_node(node) try: return ast.parse(code, type_comments=True).body[-1] except SyntaxError: return ast.parse(code, type_comments=False).body[-1] def _parse_type_comment( type_comment: Optional[str], ) -> Optional[ast.expr]: """ Attempt to parse a type comment. If it is None or if it fails to parse, return None. """ if type_comment is None: return None try: return ast.parse(type_comment, "<type_comment>", "eval").body except SyntaxError: return None def _annotation_for_statement( node: cst.CSTNode, ) -> Optional[ast.expr]: return _parse_type_comment(_ast_for_statement(node).type_comment)
null
4,945
import argparse import ast import builtins import dataclasses import functools import sys from typing import cast, Dict, List, Optional, Sequence, Set, Tuple, Union from typing_extensions import TypeAlias import libcst as cst import libcst.matchers as m from libcst.codemod import CodemodContext, VisitorBasedCodemodCommand def _parse_func_type_comment( func_type_comment: Optional[str], ) -> Optional["ast.FunctionType"]: if func_type_comment is None: return None return ast.parse(func_type_comment, "<func_type_comment>", "func_type")
null
4,946
import argparse import ast import builtins import dataclasses import functools import sys from typing import cast, Dict, List, Optional, Sequence, Set, Tuple, Union from typing_extensions import TypeAlias import libcst as cst import libcst.matchers as m from libcst.codemod import CodemodContext, VisitorBasedCodemodCommand def _is_type_comment(comment: Optional[cst.Comment]) -> bool: """ Determine whether a comment is a type comment. Unfortunately, to strip type comments in a location-invariant way requires finding them from pure libcst data. We only use this in function defs, where the precise cst location of the type comment cna be hard to predict. """ if comment is None: return False value = comment.value[1:].strip() if not value.startswith("type:"): return False suffix = value.removeprefix("type:").strip().split() if len(suffix) > 0 and suffix[0] == "ignore": return False return True The provided code snippet includes necessary dependencies for implementing the `_strip_type_comment` function. Write a Python function `def _strip_type_comment(comment: Optional[cst.Comment]) -> Optional[cst.Comment]` to solve the following problem: Remove the type comment while keeping any following comments. Here is the function: def _strip_type_comment(comment: Optional[cst.Comment]) -> Optional[cst.Comment]: """ Remove the type comment while keeping any following comments. """ if not _is_type_comment(comment): return comment assert comment is not None idx = comment.value.find("#", 1) if idx < 0: return None return comment.with_changes(value=comment.value[idx:])
Remove the type comment while keeping any following comments.
4,947
import argparse import ast import builtins import dataclasses import functools import sys from typing import cast, Dict, List, Optional, Sequence, Set, Tuple, Union from typing_extensions import TypeAlias import libcst as cst import libcst.matchers as m from libcst.codemod import CodemodContext, VisitorBasedCodemodCommand def _convert_annotation( raw: str, quote_annotations: bool, ) -> cst.Annotation: """ Convert a raw annotation - which is a string coming from a type comment - into a suitable libcst Annotation node. If `quote_annotations`, we'll always quote annotations unless they are builtin types. The reason for this is to make the codemod safer to apply on legacy code where type comments may well include invalid types that would crash at runtime. """ if _is_builtin(raw): return cst.Annotation(annotation=cst.Name(value=raw)) if not quote_annotations: try: return cst.Annotation(annotation=cst.parse_expression(raw)) except cst.ParserSyntaxError: pass return cst.Annotation(annotation=cst.SimpleString(f'"{raw}"')) class _FailedToApplyAnnotation: pass class _ArityError(Exception): pass class AnnotationSpreader: """ Utilities to help with lining up tuples of types from type comments with the tuples of values with which they should be associated. """ def unpack_annotation( expression: ast.expr, ) -> UnpackedAnnotations: if isinstance(expression, ast.Tuple): return [ AnnotationSpreader.unpack_annotation(elt) for elt in expression.elts ] else: return ast.unparse(expression) def unpack_target( target: cst.BaseExpression, ) -> UnpackedBindings: """ Take a (non-function-type) type comment and split it into components. A type comment body should always be either a single type or a tuple of types. We work with strings for annotations because without detailed scope analysis that is the safest option for codemods. """ if isinstance(target, cst.Tuple): return [ AnnotationSpreader.unpack_target(element.value) for element in target.elements ] else: return target def annotated_bindings( bindings: UnpackedBindings, annotations: UnpackedAnnotations, ) -> List[Tuple[cst.BaseAssignTargetExpression, str]]: if isinstance(annotations, list): if isinstance(bindings, list) and len(bindings) == len(annotations): # The arities match, so we return the flattened result of # mapping annotated_bindings over each pair. out: List[Tuple[cst.BaseAssignTargetExpression, str]] = [] for binding, annotation in zip(bindings, annotations): out.extend( AnnotationSpreader.annotated_bindings(binding, annotation) ) return out else: # Either mismatched lengths, or multi-type and one-target raise _ArityError() elif isinstance(bindings, list): # multi-target and one-type raise _ArityError() else: assert isinstance(bindings, cst.BaseAssignTargetExpression) return [(bindings, annotations)] def type_declaration( binding: cst.BaseAssignTargetExpression, raw_annotation: str, quote_annotations: bool, ) -> cst.AnnAssign: return cst.AnnAssign( target=binding, annotation=_convert_annotation( raw=raw_annotation, quote_annotations=quote_annotations, ), value=None, ) def type_declaration_statements( bindings: UnpackedBindings, annotations: UnpackedAnnotations, leading_lines: Sequence[cst.EmptyLine], quote_annotations: bool, ) -> List[cst.SimpleStatementLine]: return [ cst.SimpleStatementLine( body=[ AnnotationSpreader.type_declaration( binding=binding, raw_annotation=raw_annotation, quote_annotations=quote_annotations, ) ], leading_lines=leading_lines if i == 0 else [], ) for i, (binding, raw_annotation) in enumerate( AnnotationSpreader.annotated_bindings( bindings=bindings, annotations=annotations, ) ) ] def convert_Assign( node: cst.Assign, annotation: ast.expr, quote_annotations: bool, ) -> Union[ _FailedToApplyAnnotation, cst.AnnAssign, List[Union[cst.AnnAssign, cst.Assign]], ]: # zip the type and target information tother. If there are mismatched # arities, this is a PEP 484 violation (technically we could use # logic beyond the PEP to recover some cases as typing.Tuple, but this # should be rare) so we give up. try: annotations = AnnotationSpreader.unpack_annotation(annotation) annotated_targets = [ AnnotationSpreader.annotated_bindings( bindings=AnnotationSpreader.unpack_target(target.target), annotations=annotations, ) for target in node.targets ] except _ArityError: return _FailedToApplyAnnotation() if len(annotated_targets) == 1 and len(annotated_targets[0]) == 1: # We can convert simple one-target assignments into a single AnnAssign binding, raw_annotation = annotated_targets[0][0] return cst.AnnAssign( target=binding, annotation=_convert_annotation( raw=raw_annotation, quote_annotations=quote_annotations, ), value=node.value, semicolon=node.semicolon, ) else: # For multi-target assigns (regardless of whether they are using tuples # on the LHS or multiple `=` tokens or both), we need to add a type # declaration per individual LHS target. type_declarations = [ AnnotationSpreader.type_declaration( binding, raw_annotation, quote_annotations=quote_annotations, ) for annotated_bindings in annotated_targets for binding, raw_annotation in annotated_bindings ] return [ *type_declarations, node, ]
null
4,948
import argparse from typing import Callable, Optional, Sequence, Set, Tuple, Union import libcst as cst from libcst.codemod import CodemodContext, VisitorBasedCodemodCommand from libcst.codemod.visitors import AddImportsVisitor, RemoveImportsVisitor from libcst.helpers import get_full_name_for_node from libcst.metadata import QualifiedNameProvider def leave_import_decorator( method: Callable[..., Union[cst.Import, cst.ImportFrom]] ) -> Callable[..., Union[cst.Import, cst.ImportFrom]]: # We want to record any 'as name' that is relevant but only after we leave the corresponding Import/ImportFrom node since # we don't want the 'as name' to interfere with children 'Name' and 'Attribute' nodes. def wrapper( self: "RenameCommand", original_node: Union[cst.Import, cst.ImportFrom], updated_node: Union[cst.Import, cst.ImportFrom], ) -> Union[cst.Import, cst.ImportFrom]: updated_node = method(self, original_node, updated_node) if original_node != updated_node: self.record_asname(original_node) return updated_node return wrapper
null
4,949
import argparse import ast from typing import Generator, List, Optional, Sequence, Set, Tuple import libcst as cst import libcst.matchers as m from libcst.codemod import ( CodemodContext, ContextAwareTransformer, ContextAwareVisitor, VisitorBasedCodemodCommand, ) def _get_lhs(field: cst.BaseExpression) -> cst.BaseExpression: if isinstance(field, (cst.Name, cst.Integer)): return field elif isinstance(field, (cst.Attribute, cst.Subscript)): return _get_lhs(field.value) else: raise Exception("Unsupported node type!") def _find_expr_from_field_name( fieldname: str, args: Sequence[cst.Arg] ) -> Optional[cst.BaseExpression]: # Things like "0.name" are invalid expressions in python since # we can't tell if name is supposed to be the fraction or a name. # So we do a trick to parse here where we wrap the LHS in parens # and assume LibCST will handle it. if "." in fieldname: ind, exp = fieldname.split(".", 1) fieldname = f"({ind}).{exp}" field_expr = cst.parse_expression(fieldname) lhs = _get_lhs(field_expr) # Verify we don't have any *args or **kwargs attributes. if any(arg.star != "" for arg in args): return None # Get the index into the arg index: Optional[int] = None if isinstance(lhs, cst.Integer): index = int(lhs.value) if index < 0 or index >= len(args): raise Exception(f"Logic error, arg sequence {index} out of bounds!") elif isinstance(lhs, cst.Name): for i, arg in enumerate(args): kw = arg.keyword if kw is None: continue if kw.value == lhs.value: index = i break if index is None: raise Exception(f"Logic error, arg name {lhs.value} out of bounds!") if index is None: raise Exception(f"Logic error, unsupported fieldname expression {fieldname}!") # Format it! return field_expr.deep_replace(lhs, args[index].value)
null
4,950
import argparse import ast from typing import Generator, List, Optional, Sequence, Set, Tuple import libcst as cst import libcst.matchers as m from libcst.codemod import ( CodemodContext, ContextAwareTransformer, ContextAwareVisitor, VisitorBasedCodemodCommand, ) def _get_field(formatstr: str) -> Tuple[str, Optional[str], Optional[str]]: def _get_tokens( # noqa: C901 string: str, ) -> Generator[Tuple[str, Optional[str], Optional[str], Optional[str]], None, None]: length = len(string) prefix: str = "" format_accum: str = "" in_brackets: int = 0 seen_escape: bool = False for pos, char in enumerate(string): if seen_escape: # The last character was an escape character, so consume # this one as well, and then pop out of the escape. if in_brackets == 0: prefix += char else: format_accum += char seen_escape = False continue # We can't escape inside a f-string/format specifier. if in_brackets == 0: # Grab the next character to see if we are an escape sequence. next_char: Optional[str] = None if pos < length - 1: next_char = string[pos + 1] # If this current character is an escape, we want to # not react to it, append it to the current accumulator and # then do the same for the next character. if char == "{" and next_char == "{": seen_escape = True if char == "}" and next_char == "}": seen_escape = True # Only if we are not an escape sequence do we consider these # brackets. if not seen_escape: if char == "{": in_brackets += 1 # We want to add brackets to the format accumulator as # long as they aren't the outermost, because format # specs allow {} expansion. if in_brackets == 1: continue if char == "}": in_brackets -= 1 if in_brackets < 0: raise Exception("Stray } in format string!") if in_brackets == 0: field_name, format_spec, conversion = _get_field(format_accum) yield (prefix, field_name, format_spec, conversion) prefix = "" format_accum = "" continue # Place in the correct accumulator if in_brackets == 0: prefix += char else: format_accum += char if in_brackets > 0: raise Exception("Stray { in format string!") if format_accum: raise Exception("Logic error!") # Yield the last bit of information yield (prefix, None, None, None)
null
4,951
import itertools import re from typing import Callable, cast, List, Sequence import libcst as cst import libcst.matchers as m from libcst.codemod import VisitorBasedCodemodCommand def _match_simple_string(node: cst.CSTNode) -> bool: if isinstance(node, cst.SimpleString) and not node.prefix.lower().startswith("b"): # SimpleString can be a bytes and fstring don't support bytes return re.fullmatch("[^%]*(%s[^%]*)+", node.raw_value) is not None return False
null
4,952
import itertools import re from typing import Callable, cast, List, Sequence import libcst as cst import libcst.matchers as m from libcst.codemod import VisitorBasedCodemodCommand USE_FSTRING_SIMPLE_EXPRESSION_MAX_LENGTH = 30 def _gen_match_simple_expression(module: cst.Module) -> Callable[[cst.CSTNode], bool]: def _match_simple_expression(node: cst.CSTNode) -> bool: # either each element in Tuple is simple expression or the entire expression is simple. if ( isinstance(node, cst.Tuple) and all( len(module.code_for_node(elm.value)) < USE_FSTRING_SIMPLE_EXPRESSION_MAX_LENGTH for elm in node.elements ) ) or len(module.code_for_node(node)) < USE_FSTRING_SIMPLE_EXPRESSION_MAX_LENGTH: return True return False return _match_simple_expression
null
4,953
import difflib import os.path import re import subprocess import sys import time import traceback from dataclasses import dataclass, replace from multiprocessing import cpu_count, Pool from pathlib import Path from typing import Any, AnyStr, cast, Dict, List, Optional, Sequence, Union from libcst import parse_module, PartialParserConfig from libcst.codemod._codemod import Codemod from libcst.codemod._dummy_pool import DummyPool from libcst.codemod._runner import ( SkipFile, SkipReason, transform_module, TransformExit, TransformFailure, TransformResult, TransformSkip, TransformSuccess, ) from libcst.helpers import calculate_module_and_package from libcst.metadata import FullRepoManager The provided code snippet includes necessary dependencies for implementing the `gather_files` function. Write a Python function `def gather_files( files_or_dirs: Sequence[str], *, include_stubs: bool = False ) -> List[str]` to solve the following problem: Given a list of files or directories (can be intermingled), return a list of all python files that exist at those locations. If ``include_stubs`` is ``True``, this will include ``.py`` and ``.pyi`` stub files. If it is ``False``, only ``.py`` files will be included in the returned list. Here is the function: def gather_files( files_or_dirs: Sequence[str], *, include_stubs: bool = False ) -> List[str]: """ Given a list of files or directories (can be intermingled), return a list of all python files that exist at those locations. If ``include_stubs`` is ``True``, this will include ``.py`` and ``.pyi`` stub files. If it is ``False``, only ``.py`` files will be included in the returned list. """ ret: List[str] = [] for fd in files_or_dirs: if os.path.isfile(fd): ret.append(fd) elif os.path.isdir(fd): ret.extend( str(p) for p in Path(fd).rglob("*.py*") if Path.is_file(p) and ( str(p).endswith("py") or (include_stubs and str(p).endswith("pyi")) ) ) return sorted(ret)
Given a list of files or directories (can be intermingled), return a list of all python files that exist at those locations. If ``include_stubs`` is ``True``, this will include ``.py`` and ``.pyi`` stub files. If it is ``False``, only ``.py`` files will be included in the returned list.
4,954
import difflib import os.path import re import subprocess import sys import time import traceback from dataclasses import dataclass, replace from multiprocessing import cpu_count, Pool from pathlib import Path from typing import Any, AnyStr, cast, Dict, List, Optional, Sequence, Union from libcst import parse_module, PartialParserConfig from libcst.codemod._codemod import Codemod from libcst.codemod._dummy_pool import DummyPool from libcst.codemod._runner import ( SkipFile, SkipReason, transform_module, TransformExit, TransformFailure, TransformResult, TransformSkip, TransformSuccess, ) from libcst.helpers import calculate_module_and_package from libcst.metadata import FullRepoManager _DEFAULT_GENERATED_CODE_MARKER: str = f"@gen{''}erated" def invoke_formatter(formatter_args: Sequence[str], code: AnyStr) -> AnyStr: """ Given a code string, run an external formatter on the code and return new formatted code. """ # Make sure there is something to run if len(formatter_args) == 0: raise Exception("No formatter configured but code formatting requested.") # Invoke the formatter, giving it the code as stdin and assuming the formatted # code comes from stdout. work_with_bytes = isinstance(code, bytes) return cast( AnyStr, subprocess.check_output( formatter_args, input=code, universal_newlines=not work_with_bytes, encoding=None if work_with_bytes else "utf-8", ), ) def print_execution_result(result: TransformResult) -> None: for warning in result.warning_messages: print(f"WARNING: {warning}", file=sys.stderr) if isinstance(result, TransformFailure): error = result.error if isinstance(error, subprocess.CalledProcessError): print(error.output.decode("utf-8"), file=sys.stderr) print(result.traceback_str, file=sys.stderr) class Codemod(MetadataDependent, ABC): """ Abstract base class that all codemods must subclass from. Classes wishing to perform arbitrary, non-visitor-based mutations on a tree should subclass from this class directly. Classes wishing to perform visitor-based mutation should instead subclass from :class:`~libcst.codemod.ContextAwareTransformer`. Note that a :class:`~libcst.codemod.Codemod` is a subclass of :class:`~libcst.MetadataDependent`, meaning that you can declare metadata dependencies with the :attr:`~libcst.MetadataDependent.METADATA_DEPENDENCIES` class property and while you are executing a transform you can call :meth:`~libcst.MetadataDependent.get_metadata` to retrieve the resolved metadata. """ def __init__(self, context: CodemodContext) -> None: MetadataDependent.__init__(self) self.context: CodemodContext = context def should_allow_multiple_passes(self) -> bool: """ Override this and return ``True`` to allow your transform to be called repeatedly until the tree doesn't change between passes. By default, this is off, and should suffice for most transforms. """ return False def warn(self, warning: str) -> None: """ Emit a warning that is displayed to the user who has invoked this codemod. """ self.context.warnings.append(warning) def module(self) -> Module: """ Reference to the currently-traversed module. Note that this is only available during the execution of a codemod. The module reference is particularly handy if you want to use :meth:`libcst.Module.code_for_node` or :attr:`libcst.Module.config_for_parsing` and don't wish to track a reference to the top-level module manually. """ module = self.context.module if module is None: raise Exception( f"Attempted access of {self.__class__.__name__}.module outside of " + "transform_module()." ) return module def transform_module_impl(self, tree: Module) -> Module: """ Override this with your transform. You should take in the tree, optionally mutate it and then return the mutated version. The module reference and all calculated metadata are available for the lifetime of this function. """ ... def _handle_metadata_reference( self, module: Module ) -> Generator[Module, None, None]: oldwrapper = self.context.wrapper metadata_manager = self.context.metadata_manager filename = self.context.filename if metadata_manager is not None and filename: # We can look up full-repo metadata for this codemod! cache = metadata_manager.get_cache_for_path(filename) wrapper = MetadataWrapper(module, cache=cache) else: # We are missing either the repo manager or the current path, # which can happen when we are codemodding from stdin or when # an upstream dependency manually instantiates us. wrapper = MetadataWrapper(module) with self.resolve(wrapper): self.context = replace(self.context, wrapper=wrapper) try: yield wrapper.module finally: self.context = replace(self.context, wrapper=oldwrapper) def transform_module(self, tree: Module) -> Module: """ Transform entrypoint which handles multi-pass logic and metadata calculation for you. This is the method that you should call if you wish to invoke a codemod directly. This is the method that is called by :func:`~libcst.codemod.transform_module`. """ if not self.should_allow_multiple_passes(): with self._handle_metadata_reference(tree) as tree_with_metadata: return self.transform_module_impl(tree_with_metadata) # We allow multiple passes, so we execute 1+ passes until there are # no more changes. previous: Module = tree while True: with self._handle_metadata_reference(tree) as tree_with_metadata: tree = self.transform_module_impl(tree_with_metadata) if tree.deep_equals(previous): break previous = tree return tree class TransformFailure: """ A :class:`~libcst.codemod.TransformResult` used when the codemod failed. Stores all the information we might need to display to the user upon a failure. """ #: All warning messages that were generated before the codemod crashed. warning_messages: Sequence[str] #: The exception that was raised during the codemod. error: Exception #: The traceback string that was recorded at the time of exception. traceback_str: str class TransformExit: """ A :class:`~libcst.codemod.TransformResult` used when the codemod was interrupted by the user (e.g. KeyboardInterrupt). """ #: An empty list of warnings, included so that all #: :class:`~libcst.codemod.TransformResult` have a ``warning_messages`` attribute. warning_messages: Sequence[str] = () class TransformSkip: """ A :class:`~libcst.codemod.TransformResult` used when the codemod requested to be skipped. This could be because it's a generated file, or due to filename blacklist, or because the transform raised :class:`~libcst.codemod.SkipFile`. """ #: The reason that we skipped codemodding this module. skip_reason: SkipReason #: The description populated from the :class:`~libcst.codemod.SkipFile` exception. skip_description: str #: All warning messages that were generated before the codemod decided to skip. warning_messages: Sequence[str] = () def transform_module( transformer: Codemod, code: str, *, python_version: Optional[str] = None ) -> TransformResult: """ Given a module as represented by a string and a :class:`~libcst.codemod.Codemod` that we wish to run, execute the codemod on the code and return a :class:`~libcst.codemod.TransformResult`. This should never raise an exception. On success, this returns a :class:`~libcst.codemod.TransformSuccess` containing any generated warnings as well as the transformed code. If the codemod is interrupted with a Ctrl+C, this returns a :class:`~libcst.codemod.TransformExit`. If the codemod elected to skip by throwing a :class:`~libcst.codemod.SkipFile` exception, this will return a :class:`~libcst.codemod.TransformSkip` containing the reason for skipping as well as any warnings that were generated before the codemod decided to skip. If the codemod throws an unexpected exception, this will return a :class:`~libcst.codemod.TransformFailure` containing the exception that occured as well as any warnings that were generated before the codemod crashed. """ try: input_tree = parse_module( code, config=( PartialParserConfig(python_version=python_version) if python_version is not None else PartialParserConfig() ), ) output_tree = transformer.transform_module(input_tree) return TransformSuccess( code=output_tree.code, warning_messages=transformer.context.warnings ) except KeyboardInterrupt: return TransformExit() except SkipFile as ex: return TransformSkip( skip_description=str(ex), skip_reason=SkipReason.OTHER, warning_messages=transformer.context.warnings, ) except Exception as ex: return TransformFailure( error=ex, traceback_str=traceback.format_exc(), warning_messages=transformer.context.warnings, ) The provided code snippet includes necessary dependencies for implementing the `exec_transform_with_prettyprint` function. Write a Python function `def exec_transform_with_prettyprint( transform: Codemod, code: str, *, include_generated: bool = False, generated_code_marker: str = _DEFAULT_GENERATED_CODE_MARKER, format_code: bool = False, formatter_args: Sequence[str] = (), python_version: Optional[str] = None, ) -> Optional[str]` to solve the following problem: Given an instantiated codemod and a string representing a module, transform that code by executing the transform, optionally invoking the formatter and finally printing any generated warnings to stderr. If the code includes the generated marker at any spot and ``include_generated`` is not set to ``True``, the code will not be modified. If ``format_code`` is set to ``False`` or the instantiated codemod does not modify the code, the code will not be formatted. If a ``python_version`` is provided, then we will parse the module using this version. Otherwise, we will use the version of the currently executing python binary. In all cases a module will be returned. Whether it is changed depends on the input parameters as well as the codemod itself. Here is the function: def exec_transform_with_prettyprint( transform: Codemod, code: str, *, include_generated: bool = False, generated_code_marker: str = _DEFAULT_GENERATED_CODE_MARKER, format_code: bool = False, formatter_args: Sequence[str] = (), python_version: Optional[str] = None, ) -> Optional[str]: """ Given an instantiated codemod and a string representing a module, transform that code by executing the transform, optionally invoking the formatter and finally printing any generated warnings to stderr. If the code includes the generated marker at any spot and ``include_generated`` is not set to ``True``, the code will not be modified. If ``format_code`` is set to ``False`` or the instantiated codemod does not modify the code, the code will not be formatted. If a ``python_version`` is provided, then we will parse the module using this version. Otherwise, we will use the version of the currently executing python binary. In all cases a module will be returned. Whether it is changed depends on the input parameters as well as the codemod itself. """ if not include_generated and generated_code_marker in code: print( "WARNING: Code is generated and we are set to ignore generated code, " + "skipping!", file=sys.stderr, ) return code result = transform_module(transform, code, python_version=python_version) maybe_code: Optional[str] = ( None if isinstance(result, (TransformFailure, TransformExit, TransformSkip)) else result.code ) if maybe_code is not None and format_code: try: maybe_code = invoke_formatter(formatter_args, maybe_code) except Exception as ex: # Failed to format code, treat as a failure and make sure that # we print the exception for debugging. maybe_code = None result = TransformFailure( error=ex, traceback_str=traceback.format_exc(), warning_messages=result.warning_messages, ) # Finally, print the output, regardless of what happened print_execution_result(result) return maybe_code
Given an instantiated codemod and a string representing a module, transform that code by executing the transform, optionally invoking the formatter and finally printing any generated warnings to stderr. If the code includes the generated marker at any spot and ``include_generated`` is not set to ``True``, the code will not be modified. If ``format_code`` is set to ``False`` or the instantiated codemod does not modify the code, the code will not be formatted. If a ``python_version`` is provided, then we will parse the module using this version. Otherwise, we will use the version of the currently executing python binary. In all cases a module will be returned. Whether it is changed depends on the input parameters as well as the codemod itself.
4,955
import difflib import os.path import re import subprocess import sys import time import traceback from dataclasses import dataclass, replace from multiprocessing import cpu_count, Pool from pathlib import Path from typing import Any, AnyStr, cast, Dict, List, Optional, Sequence, Union from libcst import parse_module, PartialParserConfig from libcst.codemod._codemod import Codemod from libcst.codemod._dummy_pool import DummyPool from libcst.codemod._runner import ( SkipFile, SkipReason, transform_module, TransformExit, TransformFailure, TransformResult, TransformSkip, TransformSuccess, ) from libcst.helpers import calculate_module_and_package from libcst.metadata import FullRepoManager _DEFAULT_GENERATED_CODE_MARKER: str = f"@gen{''}erated" class ExecutionConfig: blacklist_patterns: Sequence[str] = () format_code: bool = False formatter_args: Sequence[str] = () generated_code_marker: str = _DEFAULT_GENERATED_CODE_MARKER include_generated: bool = False python_version: Optional[str] = None repo_root: Optional[str] = None unified_diff: Optional[int] = None class Progress: ERASE_CURRENT_LINE: str = "\r\033[2K" def __init__(self, *, enabled: bool, total: int) -> None: self.enabled = enabled self.total = total # 1/100 = 0, len("0") = 1, precision = 0, more digits for more files self.pretty_precision: int = len(str(self.total // 100)) - 1 # Pretend we start processing immediately. This is not true, but it's # close enough to true. self.started_at: float = time.time() def print(self, finished: int) -> None: if not self.enabled: return left = self.total - finished percent = 100.0 * (float(finished) / float(self.total)) elapsed_time = max(time.time() - self.started_at, 0) print( f"{self.ERASE_CURRENT_LINE}{self._human_seconds(elapsed_time)} {percent:.{self.pretty_precision}f}% complete, {self.estimate_completion(elapsed_time, finished, left)} estimated for {left} files to go...", end="", file=sys.stderr, ) def _human_seconds(self, seconds: Union[int, float]) -> str: """ This returns a string which is a human-ish readable elapsed time such as 30.42s or 10m 31s """ minutes, seconds = divmod(seconds, 60) hours, minutes = divmod(minutes, 60) if hours > 0: return f"{hours:.0f}h {minutes:02.0f}m {seconds:02.0f}s" elif minutes > 0: return f"{minutes:02.0f}m {seconds:02.0f}s" else: return f"{seconds:02.2f}s" def estimate_completion( self, elapsed_seconds: float, files_finished: int, files_left: int ) -> str: """ Computes a really basic estimated completion given a number of operations still to do. """ if files_finished <= 0: # Technically infinite but calculating sounds better. return "[calculating]" fps = files_finished / elapsed_seconds estimated_seconds_left = files_left / fps return self._human_seconds(estimated_seconds_left) def clear(self) -> None: if not self.enabled: return print(self.ERASE_CURRENT_LINE, end="", file=sys.stderr) def _print_parallel_result( exec_result: ExecutionResult, progress: Progress, *, unified_diff: bool, show_successes: bool, hide_generated: bool, hide_blacklisted: bool, ) -> None: filename = exec_result.filename result = exec_result.transform_result if isinstance(result, TransformSkip): # Skipped file, print message and don't write back since not changed. if not ( (result.skip_reason is SkipReason.BLACKLISTED and hide_blacklisted) or (result.skip_reason is SkipReason.GENERATED and hide_generated) ): progress.clear() print(f"Codemodding {filename}", file=sys.stderr) print_execution_result(result) print( f"Skipped codemodding {filename}: {result.skip_description}\n", file=sys.stderr, ) elif isinstance(result, TransformFailure): # Print any exception, don't write the file back. progress.clear() print(f"Codemodding {filename}", file=sys.stderr) print_execution_result(result) print(f"Failed to codemod {filename}\n", file=sys.stderr) elif isinstance(result, TransformSuccess): if show_successes or result.warning_messages: # Print any warnings, save the changes if there were any. progress.clear() print(f"Codemodding {filename}", file=sys.stderr) print_execution_result(result) print( f"Successfully codemodded {filename}" + (" with warnings\n" if result.warning_messages else "\n"), file=sys.stderr, ) # In unified diff mode, the code is a diff we must print. if unified_diff and result.code: print(result.code) class ParallelTransformResult: """ The result of running :func:`~libcst.codemod.parallel_exec_transform_with_prettyprint` against a series of files. This is a simple summary, with counts for number of successfully codemodded files, number of files that we failed to codemod, number of warnings generated when running the codemod across the files, and the number of files that we skipped when running the codemod. """ #: Number of files that we successfully transformed. successes: int #: Number of files that we failed to transform. failures: int #: Number of warnings generated when running transform across files. warnings: int #: Number of files skipped because they were blacklisted, generated #: or the codemod requested to skip. skips: int def _execute_transform_wrap( job: Dict[str, Any], ) -> ExecutionResult: return _execute_transform(**job) class Codemod(MetadataDependent, ABC): """ Abstract base class that all codemods must subclass from. Classes wishing to perform arbitrary, non-visitor-based mutations on a tree should subclass from this class directly. Classes wishing to perform visitor-based mutation should instead subclass from :class:`~libcst.codemod.ContextAwareTransformer`. Note that a :class:`~libcst.codemod.Codemod` is a subclass of :class:`~libcst.MetadataDependent`, meaning that you can declare metadata dependencies with the :attr:`~libcst.MetadataDependent.METADATA_DEPENDENCIES` class property and while you are executing a transform you can call :meth:`~libcst.MetadataDependent.get_metadata` to retrieve the resolved metadata. """ def __init__(self, context: CodemodContext) -> None: MetadataDependent.__init__(self) self.context: CodemodContext = context def should_allow_multiple_passes(self) -> bool: """ Override this and return ``True`` to allow your transform to be called repeatedly until the tree doesn't change between passes. By default, this is off, and should suffice for most transforms. """ return False def warn(self, warning: str) -> None: """ Emit a warning that is displayed to the user who has invoked this codemod. """ self.context.warnings.append(warning) def module(self) -> Module: """ Reference to the currently-traversed module. Note that this is only available during the execution of a codemod. The module reference is particularly handy if you want to use :meth:`libcst.Module.code_for_node` or :attr:`libcst.Module.config_for_parsing` and don't wish to track a reference to the top-level module manually. """ module = self.context.module if module is None: raise Exception( f"Attempted access of {self.__class__.__name__}.module outside of " + "transform_module()." ) return module def transform_module_impl(self, tree: Module) -> Module: """ Override this with your transform. You should take in the tree, optionally mutate it and then return the mutated version. The module reference and all calculated metadata are available for the lifetime of this function. """ ... def _handle_metadata_reference( self, module: Module ) -> Generator[Module, None, None]: oldwrapper = self.context.wrapper metadata_manager = self.context.metadata_manager filename = self.context.filename if metadata_manager is not None and filename: # We can look up full-repo metadata for this codemod! cache = metadata_manager.get_cache_for_path(filename) wrapper = MetadataWrapper(module, cache=cache) else: # We are missing either the repo manager or the current path, # which can happen when we are codemodding from stdin or when # an upstream dependency manually instantiates us. wrapper = MetadataWrapper(module) with self.resolve(wrapper): self.context = replace(self.context, wrapper=wrapper) try: yield wrapper.module finally: self.context = replace(self.context, wrapper=oldwrapper) def transform_module(self, tree: Module) -> Module: """ Transform entrypoint which handles multi-pass logic and metadata calculation for you. This is the method that you should call if you wish to invoke a codemod directly. This is the method that is called by :func:`~libcst.codemod.transform_module`. """ if not self.should_allow_multiple_passes(): with self._handle_metadata_reference(tree) as tree_with_metadata: return self.transform_module_impl(tree_with_metadata) # We allow multiple passes, so we execute 1+ passes until there are # no more changes. previous: Module = tree while True: with self._handle_metadata_reference(tree) as tree_with_metadata: tree = self.transform_module_impl(tree_with_metadata) if tree.deep_equals(previous): break previous = tree return tree class DummyPool: """ Synchronous dummy `multiprocessing.Pool` analogue. """ def __init__(self, processes: Optional[int] = None) -> None: pass def imap_unordered( self, func: Callable[[ArgT], RetT], iterable: Iterable[ArgT], chunksize: Optional[int] = None, ) -> Generator[RetT, None, None]: for args in iterable: yield func(args) def __enter__(self) -> "DummyPool": return self def __exit__( self, exc_type: Optional[Type[Exception]], exc: Optional[Exception], tb: Optional[TracebackType], ) -> None: pass class TransformSuccess: """ A :class:`~libcst.codemod.TransformResult` used when the codemod was successful. Stores all the information we might need to display to the user upon success, as well as the transformed file contents. """ #: All warning messages that were generated during the codemod. warning_messages: Sequence[str] #: The updated code, post-codemod. code: str class TransformFailure: """ A :class:`~libcst.codemod.TransformResult` used when the codemod failed. Stores all the information we might need to display to the user upon a failure. """ #: All warning messages that were generated before the codemod crashed. warning_messages: Sequence[str] #: The exception that was raised during the codemod. error: Exception #: The traceback string that was recorded at the time of exception. traceback_str: str class TransformExit: """ A :class:`~libcst.codemod.TransformResult` used when the codemod was interrupted by the user (e.g. KeyboardInterrupt). """ #: An empty list of warnings, included so that all #: :class:`~libcst.codemod.TransformResult` have a ``warning_messages`` attribute. warning_messages: Sequence[str] = () class TransformSkip: """ A :class:`~libcst.codemod.TransformResult` used when the codemod requested to be skipped. This could be because it's a generated file, or due to filename blacklist, or because the transform raised :class:`~libcst.codemod.SkipFile`. """ #: The reason that we skipped codemodding this module. skip_reason: SkipReason #: The description populated from the :class:`~libcst.codemod.SkipFile` exception. skip_description: str #: All warning messages that were generated before the codemod decided to skip. warning_messages: Sequence[str] = () The provided code snippet includes necessary dependencies for implementing the `parallel_exec_transform_with_prettyprint` function. Write a Python function `def parallel_exec_transform_with_prettyprint( # noqa: C901 transform: Codemod, files: Sequence[str], *, jobs: Optional[int] = None, unified_diff: Optional[int] = None, include_generated: bool = False, generated_code_marker: str = _DEFAULT_GENERATED_CODE_MARKER, format_code: bool = False, formatter_args: Sequence[str] = (), show_successes: bool = False, hide_generated: bool = False, hide_blacklisted: bool = False, hide_progress: bool = False, blacklist_patterns: Sequence[str] = (), python_version: Optional[str] = None, repo_root: Optional[str] = None, ) -> ParallelTransformResult` to solve the following problem: Given a list of files and an instantiated codemod we should apply to them, fork and apply the codemod in parallel to all of the files, including any configured formatter. The ``jobs`` parameter controls the maximum number of in-flight transforms, and needs to be at least 1. If not included, the number of jobs will automatically be set to the number of CPU cores. If ``unified_diff`` is set to a number, changes to files will be printed to stdout with ``unified_diff`` lines of context. If it is set to ``None`` or left out, files themselves will be updated with changes and formatting. If a ``python_version`` is provided, then we will parse each source file using this version. Otherwise, we will use the version of the currently executing python binary. A progress indicator as well as any generated warnings will be printed to stderr. To supress the interactive progress indicator, set ``hide_progress`` to ``True``. Files that include the generated code marker will be skipped unless the ``include_generated`` parameter is set to ``True``. Similarly, files that match a supplied blacklist of regex patterns will be skipped. Warnings for skipping both blacklisted and generated files will be printed to stderr along with warnings generated by the codemod unless ``hide_blacklisted`` and ``hide_generated`` are set to ``True``. Files that were successfully codemodded will not be printed to stderr unless ``show_successes`` is set to ``True``. To make this API possible, we take an instantiated transform. This is due to the fact that lambdas are not pickleable and pickling functions is undefined. This means we're implicitly relying on fork behavior on UNIX-like systems, and this function will not work on Windows systems. To create a command-line utility that runs on Windows, please instead see :func:`~libcst.codemod.exec_transform_with_prettyprint`. Here is the function: def parallel_exec_transform_with_prettyprint( # noqa: C901 transform: Codemod, files: Sequence[str], *, jobs: Optional[int] = None, unified_diff: Optional[int] = None, include_generated: bool = False, generated_code_marker: str = _DEFAULT_GENERATED_CODE_MARKER, format_code: bool = False, formatter_args: Sequence[str] = (), show_successes: bool = False, hide_generated: bool = False, hide_blacklisted: bool = False, hide_progress: bool = False, blacklist_patterns: Sequence[str] = (), python_version: Optional[str] = None, repo_root: Optional[str] = None, ) -> ParallelTransformResult: """ Given a list of files and an instantiated codemod we should apply to them, fork and apply the codemod in parallel to all of the files, including any configured formatter. The ``jobs`` parameter controls the maximum number of in-flight transforms, and needs to be at least 1. If not included, the number of jobs will automatically be set to the number of CPU cores. If ``unified_diff`` is set to a number, changes to files will be printed to stdout with ``unified_diff`` lines of context. If it is set to ``None`` or left out, files themselves will be updated with changes and formatting. If a ``python_version`` is provided, then we will parse each source file using this version. Otherwise, we will use the version of the currently executing python binary. A progress indicator as well as any generated warnings will be printed to stderr. To supress the interactive progress indicator, set ``hide_progress`` to ``True``. Files that include the generated code marker will be skipped unless the ``include_generated`` parameter is set to ``True``. Similarly, files that match a supplied blacklist of regex patterns will be skipped. Warnings for skipping both blacklisted and generated files will be printed to stderr along with warnings generated by the codemod unless ``hide_blacklisted`` and ``hide_generated`` are set to ``True``. Files that were successfully codemodded will not be printed to stderr unless ``show_successes`` is set to ``True``. To make this API possible, we take an instantiated transform. This is due to the fact that lambdas are not pickleable and pickling functions is undefined. This means we're implicitly relying on fork behavior on UNIX-like systems, and this function will not work on Windows systems. To create a command-line utility that runs on Windows, please instead see :func:`~libcst.codemod.exec_transform_with_prettyprint`. """ # Ensure that we have no duplicates, otherwise we might get race conditions # on write. files = sorted({os.path.abspath(f) for f in files}) total = len(files) progress = Progress(enabled=not hide_progress, total=total) chunksize = 4 # Grab number of cores if we need to jobs = min( jobs if jobs is not None else cpu_count(), (len(files) + chunksize - 1) // chunksize, ) if jobs < 1: raise Exception("Must have at least one job to process!") if total == 0: return ParallelTransformResult(successes=0, failures=0, skips=0, warnings=0) if repo_root is not None: # Make sure if there is a root that we have the absolute path to it. repo_root = os.path.abspath(repo_root) # Spin up a full repo metadata manager so that we can provide metadata # like type inference to individual forked processes. print("Calculating full-repo metadata...", file=sys.stderr) metadata_manager = FullRepoManager( repo_root, files, transform.get_inherited_dependencies(), ) metadata_manager.resolve_cache() transform.context = replace( transform.context, metadata_manager=metadata_manager, ) print("Executing codemod...", file=sys.stderr) config = ExecutionConfig( repo_root=repo_root, unified_diff=unified_diff, include_generated=include_generated, generated_code_marker=generated_code_marker, format_code=format_code, formatter_args=formatter_args, blacklist_patterns=blacklist_patterns, python_version=python_version, ) if total == 1 or jobs == 1: # Simple case, we should not pay for process overhead. # Let's just use a dummy synchronous pool. jobs = 1 pool_impl = DummyPool else: pool_impl = Pool # Warm the parser, pre-fork. parse_module( "", config=( PartialParserConfig(python_version=python_version) if python_version is not None else PartialParserConfig() ), ) successes: int = 0 failures: int = 0 warnings: int = 0 skips: int = 0 with pool_impl(processes=jobs) as p: # type: ignore args = [ { "transformer": transform, "filename": filename, "config": config, } for filename in files ] try: for result in p.imap_unordered( _execute_transform_wrap, args, chunksize=chunksize ): # Print an execution result, keep track of failures _print_parallel_result( result, progress, unified_diff=bool(unified_diff), show_successes=show_successes, hide_generated=hide_generated, hide_blacklisted=hide_blacklisted, ) progress.print(successes + failures + skips) if isinstance(result.transform_result, TransformFailure): failures += 1 elif isinstance(result.transform_result, TransformSuccess): successes += 1 elif isinstance( result.transform_result, (TransformExit, TransformSkip) ): skips += 1 warnings += len(result.transform_result.warning_messages) finally: progress.clear() # Return whether there was one or more failure. return ParallelTransformResult( successes=successes, failures=failures, skips=skips, warnings=warnings )
Given a list of files and an instantiated codemod we should apply to them, fork and apply the codemod in parallel to all of the files, including any configured formatter. The ``jobs`` parameter controls the maximum number of in-flight transforms, and needs to be at least 1. If not included, the number of jobs will automatically be set to the number of CPU cores. If ``unified_diff`` is set to a number, changes to files will be printed to stdout with ``unified_diff`` lines of context. If it is set to ``None`` or left out, files themselves will be updated with changes and formatting. If a ``python_version`` is provided, then we will parse each source file using this version. Otherwise, we will use the version of the currently executing python binary. A progress indicator as well as any generated warnings will be printed to stderr. To supress the interactive progress indicator, set ``hide_progress`` to ``True``. Files that include the generated code marker will be skipped unless the ``include_generated`` parameter is set to ``True``. Similarly, files that match a supplied blacklist of regex patterns will be skipped. Warnings for skipping both blacklisted and generated files will be printed to stderr along with warnings generated by the codemod unless ``hide_blacklisted`` and ``hide_generated`` are set to ``True``. Files that were successfully codemodded will not be printed to stderr unless ``show_successes`` is set to ``True``. To make this API possible, we take an instantiated transform. This is due to the fact that lambdas are not pickleable and pickling functions is undefined. This means we're implicitly relying on fork behavior on UNIX-like systems, and this function will not work on Windows systems. To create a command-line utility that runs on Windows, please instead see :func:`~libcst.codemod.exec_transform_with_prettyprint`.
4,956
from collections import defaultdict from typing import Dict, List, Optional, Sequence, Set, Tuple, Union import libcst from libcst import matchers as m, parse_statement from libcst._nodes.statement import Import, ImportFrom, SimpleStatementLine from libcst.codemod._context import CodemodContext from libcst.codemod._visitor import ContextAwareTransformer from libcst.codemod.visitors._gather_imports import _GatherImportsMixin from libcst.codemod.visitors._imports import ImportItem from libcst.helpers import get_absolute_module_from_package_for_import from libcst.helpers.common import ensure_type class SimpleStatementLine(_BaseSimpleStatement, BaseStatement): """ A simple statement that's part of an IndentedBlock or Module. A simple statement is a series of small statements joined together by semicolons. This isn't differentiated from a :class:`SimpleStatementSuite` in the grammar, but because a :class:`SimpleStatementLine` can own additional whitespace that a :class:`SimpleStatementSuite` doesn't have, we're differentiating it in the CST. """ #: Sequence of small statements. All but the last statement are required to have #: a semicolon. body: Sequence[BaseSmallStatement] #: Sequence of empty lines appearing before this simple statement line. leading_lines: Sequence[EmptyLine] = () #: Any optional trailing comment and the final ``NEWLINE`` at the end of the line. trailing_whitespace: TrailingWhitespace = TrailingWhitespace.field() def _visit_and_replace_children( self, visitor: CSTVisitorT ) -> "SimpleStatementLine": return SimpleStatementLine( leading_lines=visit_sequence( self, "leading_lines", self.leading_lines, visitor ), body=visit_sequence(self, "body", self.body, visitor), trailing_whitespace=visit_required( self, "trailing_whitespace", self.trailing_whitespace, visitor ), ) def _is_removable(self) -> bool: # If we have an empty body, we are removable since we don't represent # anything concrete. return not self.body def _codegen_impl(self, state: CodegenState) -> None: for ll in self.leading_lines: ll._codegen(state) state.add_indent_tokens() _BaseSimpleStatement._codegen_impl(self, state) # pyre-fixme[13]: Attribute `body` is never initialized. def _skip_first(orig_module: libcst.Module) -> bool: # Is there a __strict__ flag or docstring at the top? if m.matches( orig_module, m.Module( body=[ m.SimpleStatementLine( body=[ m.Assign(targets=[m.AssignTarget(target=m.Name("__strict__"))]) ] ), m.ZeroOrMore(), ] ) | m.Module( body=[ m.SimpleStatementLine(body=[m.Expr(value=m.SimpleString())]), m.ZeroOrMore(), ] ), ): return True return False
null
4,957
from collections import defaultdict from dataclasses import dataclass from typing import Dict, List, Optional, Sequence, Set, Tuple, Union import libcst as cst import libcst.matchers as m from libcst.codemod._context import CodemodContext from libcst.codemod._visitor import ContextAwareTransformer from libcst.codemod.visitors._add_imports import AddImportsVisitor from libcst.codemod.visitors._gather_global_names import GatherGlobalNamesVisitor from libcst.codemod.visitors._gather_imports import GatherImportsVisitor from libcst.codemod.visitors._imports import ImportItem from libcst.helpers import get_full_name_for_node from libcst.metadata import PositionProvider, QualifiedNameProvider def _module_and_target(qualified_name: str) -> Tuple[str, str]: relative_prefix = "" while qualified_name.startswith("."): relative_prefix += "." qualified_name = qualified_name[1:] split = qualified_name.rsplit(".", 1) if len(split) == 1: qualifier, target = "", split[0] else: qualifier, target = split return (relative_prefix + qualifier, target)
null
4,958
from collections import defaultdict from dataclasses import dataclass from typing import Dict, List, Optional, Sequence, Set, Tuple, Union import libcst as cst import libcst.matchers as m from libcst.codemod._context import CodemodContext from libcst.codemod._visitor import ContextAwareTransformer from libcst.codemod.visitors._add_imports import AddImportsVisitor from libcst.codemod.visitors._gather_global_names import GatherGlobalNamesVisitor from libcst.codemod.visitors._gather_imports import GatherImportsVisitor from libcst.codemod.visitors._imports import ImportItem from libcst.helpers import get_full_name_for_node from libcst.metadata import PositionProvider, QualifiedNameProvider def _get_unique_qualified_name( visitor: m.MatcherDecoratableVisitor, node: cst.CSTNode ) -> str: name = None names = [q.name for q in visitor.get_metadata(QualifiedNameProvider, node)] if len(names) == 0: # we hit this branch if the stub is directly using a fully # qualified name, which is not technically valid python but is # convenient to allow. name = get_full_name_for_node(node) elif len(names) == 1 and isinstance(names[0], str): name = names[0] if name is None: start = visitor.get_metadata(PositionProvider, node).start raise ValueError( "Could not resolve a unique qualified name for type " + f"{get_full_name_for_node(node)} at {start.line}:{start.column}. " + f"Candidate names were: {names!r}" ) return name
null
4,959
from collections import defaultdict from dataclasses import dataclass from typing import Dict, List, Optional, Sequence, Set, Tuple, Union import libcst as cst import libcst.matchers as m from libcst.codemod._context import CodemodContext from libcst.codemod._visitor import ContextAwareTransformer from libcst.codemod.visitors._add_imports import AddImportsVisitor from libcst.codemod.visitors._gather_global_names import GatherGlobalNamesVisitor from libcst.codemod.visitors._gather_imports import GatherImportsVisitor from libcst.codemod.visitors._imports import ImportItem from libcst.helpers import get_full_name_for_node from libcst.metadata import PositionProvider, QualifiedNameProvider def _get_import_alias_names( import_aliases: Sequence[cst.ImportAlias], ) -> Set[str]: import_names = set() for imported_name in import_aliases: asname = imported_name.asname if asname is not None: import_names.add(get_full_name_for_node(asname.name)) else: import_names.add(get_full_name_for_node(imported_name.name)) return import_names The provided code snippet includes necessary dependencies for implementing the `_get_imported_names` function. Write a Python function `def _get_imported_names( imports: Sequence[Union[cst.Import, cst.ImportFrom]], ) -> Set[str]` to solve the following problem: Given a series of import statements (both Import and ImportFrom), determine all of the names that have been imported into the current scope. For example: - ``import foo.bar as bar, foo.baz`` produces ``{'bar', 'foo.baz'}`` - ``from foo import (Bar, Baz as B)`` produces ``{'Bar', 'B'}`` - ``from foo import *`` produces ``set()` because we cannot resolve names Here is the function: def _get_imported_names( imports: Sequence[Union[cst.Import, cst.ImportFrom]], ) -> Set[str]: """ Given a series of import statements (both Import and ImportFrom), determine all of the names that have been imported into the current scope. For example: - ``import foo.bar as bar, foo.baz`` produces ``{'bar', 'foo.baz'}`` - ``from foo import (Bar, Baz as B)`` produces ``{'Bar', 'B'}`` - ``from foo import *`` produces ``set()` because we cannot resolve names """ import_names = set() for _import in imports: if isinstance(_import, cst.Import): import_names.update(_get_import_alias_names(_import.names)) else: names = _import.names if not isinstance(names, cst.ImportStar): import_names.update(_get_import_alias_names(names)) return import_names
Given a series of import statements (both Import and ImportFrom), determine all of the names that have been imported into the current scope. For example: - ``import foo.bar as bar, foo.baz`` produces ``{'bar', 'foo.baz'}`` - ``from foo import (Bar, Baz as B)`` produces ``{'Bar', 'B'}`` - ``from foo import *`` produces ``set()` because we cannot resolve names
4,960
from collections import defaultdict from dataclasses import dataclass from typing import Dict, List, Optional, Sequence, Set, Tuple, Union import libcst as cst import libcst.matchers as m from libcst.codemod._context import CodemodContext from libcst.codemod._visitor import ContextAwareTransformer from libcst.codemod.visitors._add_imports import AddImportsVisitor from libcst.codemod.visitors._gather_global_names import GatherGlobalNamesVisitor from libcst.codemod.visitors._gather_imports import GatherImportsVisitor from libcst.codemod.visitors._imports import ImportItem from libcst.helpers import get_full_name_for_node from libcst.metadata import PositionProvider, QualifiedNameProvider def _is_non_sentinel( x: Union[None, cst.CSTNode, cst.MaybeSentinel], ) -> bool: return x is not None and x != cst.MaybeSentinel.DEFAULT
null
4,961
from collections import defaultdict from dataclasses import dataclass from typing import Dict, List, Optional, Sequence, Set, Tuple, Union import libcst as cst import libcst.matchers as m from libcst.codemod._context import CodemodContext from libcst.codemod._visitor import ContextAwareTransformer from libcst.codemod.visitors._add_imports import AddImportsVisitor from libcst.codemod.visitors._gather_global_names import GatherGlobalNamesVisitor from libcst.codemod.visitors._gather_imports import GatherImportsVisitor from libcst.codemod.visitors._imports import ImportItem from libcst.helpers import get_full_name_for_node from libcst.metadata import PositionProvider, QualifiedNameProvider def _get_string_value( node: cst.SimpleString, ) -> str: s = node.value c = s[-1] return s[s.index(c) : -1]
null
4,962
from collections import defaultdict from dataclasses import dataclass from typing import Dict, List, Optional, Sequence, Set, Tuple, Union import libcst as cst import libcst.matchers as m from libcst.codemod._context import CodemodContext from libcst.codemod._visitor import ContextAwareTransformer from libcst.codemod.visitors._add_imports import AddImportsVisitor from libcst.codemod.visitors._gather_global_names import GatherGlobalNamesVisitor from libcst.codemod.visitors._gather_imports import GatherImportsVisitor from libcst.codemod.visitors._imports import ImportItem from libcst.helpers import get_full_name_for_node from libcst.metadata import PositionProvider, QualifiedNameProvider def _find_generic_base( node: cst.ClassDef, ) -> Optional[cst.Arg]: for b in node.bases: if m.matches(b.value, m.Subscript(value=m.Name("Generic"))): return b
null
4,963
from typing import Any, Dict, Iterable, List, Optional, Sequence, Set, Tuple, Union import libcst as cst from libcst.codemod._context import CodemodContext from libcst.codemod._visitor import ContextAwareTransformer, ContextAwareVisitor from libcst.codemod.visitors._gather_unused_imports import GatherUnusedImportsVisitor from libcst.helpers import ( get_absolute_module_from_package_for_import, get_full_name_for_node, ) from libcst.metadata import Assignment, ProviderT, ScopeProvider def _merge_whitespace_after( left: cst.BaseParenthesizableWhitespace, right: cst.BaseParenthesizableWhitespace ) -> cst.BaseParenthesizableWhitespace: if not isinstance(right, cst.ParenthesizedWhitespace): return left if not isinstance(left, cst.ParenthesizedWhitespace): return right return left.with_changes( empty_lines=tuple( line for line in right.empty_lines if line.comment is not None ), )
null
4,964
import re from dataclasses import dataclass, fields from typing import Generator, List, Optional, Sequence, Set, Tuple, Type, Union import libcst as cst from libcst import ensure_type, parse_expression from libcst.codegen.gather import all_libcst_nodes, typeclasses class RemoveTypesFromGeneric(cst.CSTTransformer): def __init__(self, values: Sequence[str]) -> None: self.values: Set[str] = set(values) def leave_SubscriptElement( self, original_node: cst.SubscriptElement, updated_node: cst.SubscriptElement ) -> Union[cst.SubscriptElement, cst.RemovalSentinel]: slc = updated_node.slice if isinstance(slc, cst.Index): val = slc.value if isinstance(val, cst.Name): if val.value in self.values: # This type matches, so out it goes return cst.RemoveFromParent() return updated_node The provided code snippet includes necessary dependencies for implementing the `_remove_types` function. Write a Python function `def _remove_types( oldtype: cst.BaseExpression, values: Sequence[str] ) -> cst.BaseExpression` to solve the following problem: Given a BaseExpression from a type, return a new BaseExpression that does not refer to any types listed in values. Here is the function: def _remove_types( oldtype: cst.BaseExpression, values: Sequence[str] ) -> cst.BaseExpression: """ Given a BaseExpression from a type, return a new BaseExpression that does not refer to any types listed in values. """ return ensure_type( oldtype.visit(RemoveTypesFromGeneric(values)), cst.BaseExpression )
Given a BaseExpression from a type, return a new BaseExpression that does not refer to any types listed in values.
4,965
import re from dataclasses import dataclass, fields from typing import Generator, List, Optional, Sequence, Set, Tuple, Type, Union import libcst as cst from libcst import ensure_type, parse_expression from libcst.codegen.gather import all_libcst_nodes, typeclasses def _add_generic(name: str, oldtype: cst.BaseExpression) -> cst.BaseExpression: return cst.Subscript(cst.Name(name), (cst.SubscriptElement(cst.Index(oldtype)),))
null
4,966
import re from dataclasses import dataclass, fields from typing import Generator, List, Optional, Sequence, Set, Tuple, Type, Union import libcst as cst from libcst import ensure_type, parse_expression from libcst.codegen.gather import all_libcst_nodes, typeclasses _global_aliases: Set[str] = set() class Field: name: str type: str aliases: List[Alias] def _get_clean_type_and_aliases( typeobj: object, ) -> Tuple[str, List[Alias]]: # noqa: C901 """ Given a type object as returned by dataclasses, sanitize it and convert it to a type string that is appropriate for our codegen below. """ # First, get the type as a parseable expression. typestr = repr(typeobj) typestr = re.sub(CLASS_RE, r"\1", typestr) typestr = re.sub(OPTIONAL_RE, r"typing.Optional[\1]", typestr) # Now, parse the expression with LibCST. cleanser = CleanseFullTypeNames() typecst = parse_expression(typestr) typecst = typecst.visit(cleanser) aliases: List[Alias] = [] # Now, convert the type to allow for MetadataMatchType and MatchIfTrue values. if isinstance(typecst, cst.Subscript): clean_type = _get_clean_type_from_subscript(aliases, typecst) elif isinstance(typecst, (cst.Name, cst.SimpleString)): clean_type = _get_clean_type_from_expression(aliases, typecst) else: raise Exception("Logic error, unexpected top level type!") # Now, insert OneOf/AllOf and MatchIfTrue into unions so we can typecheck their usage. # This allows us to put OneOf[SomeType] or MatchIfTrue[cst.SomeType] into any # spot that we would have originally allowed a SomeType. clean_type = ensure_type(clean_type.visit(AddLogicMatchersToUnions()), cst.CSTNode) # Now, insert AtMostN and AtLeastN into sequence unions, so we can typecheck # them. This relies on the previous OneOf/AllOf insertion to ensure that all # sequences we care about are Sequence[Union[<x>]]. clean_type = ensure_type( clean_type.visit(AddWildcardsToSequenceUnions()), cst.CSTNode ) # Finally, generate the code given a default Module so we can spit it out. return cst.Module(body=()).code_for_node(clean_type), aliases The provided code snippet includes necessary dependencies for implementing the `_get_fields` function. Write a Python function `def _get_fields(node: Type[cst.CSTNode]) -> Generator[Field, None, None]` to solve the following problem: Given a CSTNode, generate a field name and type string for each. Here is the function: def _get_fields(node: Type[cst.CSTNode]) -> Generator[Field, None, None]: """ Given a CSTNode, generate a field name and type string for each. """ for field in fields(node) or []: if field.name == "_metadata": continue fieldtype, aliases = _get_clean_type_and_aliases(field.type) yield Field( name=field.name, type=fieldtype, aliases=[a for a in aliases if a.name not in _global_aliases], ) _global_aliases.update(a.name for a in aliases)
Given a CSTNode, generate a field name and type string for each.
4,967
import inspect from collections import defaultdict from collections.abc import Sequence as ABCSequence from dataclasses import dataclass, fields, replace from typing import Dict, Iterator, List, Mapping, Sequence, Set, Type, Union import libcst as cst The provided code snippet includes necessary dependencies for implementing the `_get_bases` function. Write a Python function `def _get_bases() -> Iterator[Type[cst.CSTNode]]` to solve the following problem: Get all base classes that are subclasses of CSTNode but not an actual node itself. This allows us to keep our types sane by refering to the base classes themselves. Here is the function: def _get_bases() -> Iterator[Type[cst.CSTNode]]: """ Get all base classes that are subclasses of CSTNode but not an actual node itself. This allows us to keep our types sane by refering to the base classes themselves. """ for name in dir(cst): if not name.startswith("Base"): continue yield getattr(cst, name)
Get all base classes that are subclasses of CSTNode but not an actual node itself. This allows us to keep our types sane by refering to the base classes themselves.
4,968
import inspect from collections import defaultdict from collections.abc import Sequence as ABCSequence from dataclasses import dataclass, fields, replace from typing import Dict, Iterator, List, Mapping, Sequence, Set, Type, Union import libcst as cst for node in all_libcst_nodes: # Map the base classes for this node node_to_bases[node] = list( reversed([b for b in inspect.getmro(node) if issubclass(b, cst.CSTNode)]) ) for node in all_libcst_nodes: # Find the most generic version of this node that isn't CSTNode. nodebases[node] = _get_most_generic_base_for_node(node) for node in all_libcst_nodes: for field in fields(node) or []: if field.name == "_metadata": continue _calc_node_usage(field.type) for node, base in nodebases.items(): if node.__name__.startswith("Base"): continue for x in (node, base): imports[x.__module__].add(x.__name__) The provided code snippet includes necessary dependencies for implementing the `_get_nodes` function. Write a Python function `def _get_nodes() -> Iterator[Type[cst.CSTNode]]` to solve the following problem: Grab all CSTNodes that are not a superclass. Basically, anything that a person might use to generate a tree. Here is the function: def _get_nodes() -> Iterator[Type[cst.CSTNode]]: """ Grab all CSTNodes that are not a superclass. Basically, anything that a person might use to generate a tree. """ for name in dir(cst): if name.startswith("__") and name.endswith("__"): continue if name == "CSTNode": continue node = getattr(cst, name) try: if issubclass(node, cst.CSTNode): yield node except TypeError: # This isn't a class, so we don't care about it. pass
Grab all CSTNodes that are not a superclass. Basically, anything that a person might use to generate a tree.
4,969
import inspect from collections import defaultdict from collections.abc import Sequence as ABCSequence from dataclasses import dataclass, fields, replace from typing import Dict, Iterator, List, Mapping, Sequence, Set, Type, Union import libcst as cst node_to_bases: Dict[Type[cst.CSTNode], List[Type[cst.CSTNode]]] = {} def _get_most_generic_base_for_node(node: Type[cst.CSTNode]) -> Type[cst.CSTNode]: # Ignore non-exported bases, a user couldn't specify these types # in type hints. exportable_bases = [b for b in node_to_bases[node] if b in node_to_bases] return exportable_bases[0]
null
4,970
import inspect from collections import defaultdict from collections.abc import Sequence as ABCSequence from dataclasses import dataclass, fields, replace from typing import Dict, Iterator, List, Mapping, Sequence, Set, Type, Union import libcst as cst all_libcst_nodes: Sequence[Type[cst.CSTNode]] = sorted( _get_nodes(), key=lambda node: node.__name__ ) for node in all_libcst_nodes: # Map the base classes for this node node_to_bases[node] = list( reversed([b for b in inspect.getmro(node) if issubclass(b, cst.CSTNode)]) ) for node in all_libcst_nodes: # Find the most generic version of this node that isn't CSTNode. nodebases[node] = _get_most_generic_base_for_node(node) nodeuses: Dict[Type[cst.CSTNode], Usage] = {node: Usage() for node in all_libcst_nodes} def _is_maybe(typeobj: object) -> bool: try: # pyre-ignore We wrap this in a TypeError check so this is safe return issubclass(typeobj, cst.MaybeSentinel) except TypeError: return False def _get_args(typeobj: object) -> List[object]: try: # pyre-ignore We wrap this in a AttributeError check so this is safe return typeobj.__args__ except AttributeError: # Don't care, not a union or sequence return [] def _is_sequence(typeobj: object) -> bool: origin = _get_origin(typeobj) return origin is Sequence or origin is ABCSequence def _is_union(typeobj: object) -> bool: return _get_origin(typeobj) is Union for node in all_libcst_nodes: for field in fields(node) or []: if field.name == "_metadata": continue _calc_node_usage(field.type) for node, base in nodebases.items(): if node.__name__.startswith("Base"): continue for x in (node, base): imports[x.__module__].add(x.__name__) def _calc_node_usage(typeobj: object) -> None: if _is_union(typeobj): has_maybe = any(_is_maybe(n) for n in _get_args(typeobj)) has_none = any(isinstance(n, type(None)) for n in _get_args(typeobj)) for node in _get_args(typeobj): if node in all_libcst_nodes: nodeuses[node] = replace( nodeuses[node], maybe=nodeuses[node].maybe or has_maybe, optional=nodeuses[node].optional or has_none, ) else: _calc_node_usage(node) if _is_sequence(typeobj): for node in _get_args(typeobj): if node in all_libcst_nodes: nodeuses[node] = replace(nodeuses[node], sequence=True) else: _calc_node_usage(node)
null
4,971
import argparse import os import os.path import shutil import subprocess import sys from typing import List import libcst as cst from libcst import ensure_type, parse_module from libcst.codegen.transforms import ( DoubleQuoteForwardRefsTransformer, SimplifyUnionsTransformer, ) def format_file(fname: str) -> None: def clean_generated_code(code: str) -> str: def codegen_visitors() -> None: # First, back up the original file, since we have a nasty bootstrap problem. # We're in a situation where we want to import libcst in order to get the # valid nodes for visitors, but doing so means that we depend on ourselves. # So, this attempts to keep the repo in a working state for as many operations # as possible. base = os.path.abspath( os.path.join(os.path.dirname(os.path.abspath(__file__)), "../") ) visitors_file = os.path.join(base, "_typed_visitor.py") shutil.copyfile(visitors_file, f"{visitors_file}.bak") try: # Now that we backed up the file, lets codegen a new version. # We import now, because this script does work on import. import libcst.codegen.gen_visitor_functions as visitor_codegen new_code = clean_generated_code("\n".join(visitor_codegen.generated_code)) with open(visitors_file, "w") as fp: fp.write(new_code) fp.close() # Now, see if the file we generated causes any import errors # by attempting to run codegen again in a new process. subprocess.check_call( [sys.executable, "-m", "libcst.codegen.gen_visitor_functions"], cwd=base, stdout=subprocess.DEVNULL, ) # If it worked, lets format the file format_file(visitors_file) # Since we were successful with importing, we can remove the backup. os.remove(f"{visitors_file}.bak") # Inform the user print(f"Successfully generated a new {visitors_file} file.") except Exception: # On failure, we put the original file back, and keep the failed version # for developers to look at. print( f"Failed to generated a new {visitors_file} file, failure " + f"is saved in {visitors_file}.failed_generate.", file=sys.stderr, ) os.rename(visitors_file, f"{visitors_file}.failed_generate") os.rename(f"{visitors_file}.bak", visitors_file) # Reraise so we can debug raise
null
4,972
import argparse import os import os.path import shutil import subprocess import sys from typing import List import libcst as cst from libcst import ensure_type, parse_module from libcst.codegen.transforms import ( DoubleQuoteForwardRefsTransformer, SimplifyUnionsTransformer, ) def format_file(fname: str) -> None: subprocess.check_call( ["ufmt", "format", fname], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) def clean_generated_code(code: str) -> str: """ Generalized sanity clean-up for all codegen so we can fix issues such as Union[SingleType]. The transforms found here are strictly for form and do not affect functionality. """ module = parse_module(code) module = ensure_type(module.visit(SimplifyUnionsTransformer()), cst.Module) module = ensure_type(module.visit(DoubleQuoteForwardRefsTransformer()), cst.Module) return module.code def codegen_matchers() -> None: # Given that matchers isn't in the default import chain, we don't have to # worry about generating invalid code that then prevents us from generating # again. import libcst.codegen.gen_matcher_classes as matcher_codegen base = os.path.abspath( os.path.join(os.path.dirname(os.path.abspath(__file__)), "../") ) matchers_file = os.path.join(base, "matchers/__init__.py") new_code = clean_generated_code("\n".join(matcher_codegen.generated_code)) with open(matchers_file, "w") as fp: fp.write(new_code) fp.close() # If it worked, lets format the file format_file(matchers_file) # Inform the user print(f"Successfully generated a new {matchers_file} file.")
null
4,973
import argparse import os import os.path import shutil import subprocess import sys from typing import List import libcst as cst from libcst import ensure_type, parse_module from libcst.codegen.transforms import ( DoubleQuoteForwardRefsTransformer, SimplifyUnionsTransformer, ) def format_file(fname: str) -> None: subprocess.check_call( ["ufmt", "format", fname], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) def clean_generated_code(code: str) -> str: """ Generalized sanity clean-up for all codegen so we can fix issues such as Union[SingleType]. The transforms found here are strictly for form and do not affect functionality. """ module = parse_module(code) module = ensure_type(module.visit(SimplifyUnionsTransformer()), cst.Module) module = ensure_type(module.visit(DoubleQuoteForwardRefsTransformer()), cst.Module) return module.code def codegen_return_types() -> None: # Given that matchers isn't in the default import chain, we don't have to # worry about generating invalid code that then prevents us from generating # again. import libcst.codegen.gen_type_mapping as type_codegen base = os.path.abspath( os.path.join(os.path.dirname(os.path.abspath(__file__)), "../") ) type_mapping_file = os.path.join(base, "matchers/_return_types.py") new_code = clean_generated_code("\n".join(type_codegen.generated_code)) with open(type_mapping_file, "w") as fp: fp.write(new_code) fp.close() # If it worked, lets format the file format_file(type_mapping_file) # Inform the user print(f"Successfully generated a new {type_mapping_file} file.")
null
4,974
import inspect import re from abc import ABC, abstractmethod from dataclasses import dataclass, field from typing import Optional, Pattern, Sequence, Union from libcst._add_slots import add_slots from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.base import CSTNode, CSTValidationError from libcst._nodes.expression import ( _BaseParenthesizedNode, Annotation, Arg, Asynchronous, Attribute, BaseAssignTargetExpression, BaseDelTargetExpression, BaseExpression, ConcatenatedString, ExpressionPosition, From, LeftCurlyBrace, LeftParen, LeftSquareBracket, List, Name, Parameters, RightCurlyBrace, RightParen, RightSquareBracket, SimpleString, Tuple, ) from libcst._nodes.internal import ( CodegenState, visit_body_sequence, visit_optional, visit_required, visit_sentinel, visit_sequence, ) from libcst._nodes.op import ( AssignEqual, BaseAugOp, BitOr, Colon, Comma, Dot, ImportStar, Semicolon, ) from libcst._nodes.whitespace import ( BaseParenthesizableWhitespace, EmptyLine, ParenthesizedWhitespace, SimpleWhitespace, TrailingWhitespace, ) from libcst._visitors import CSTVisitorT class BaseSuite(CSTNode, ABC): """ A dummy base-class for both :class:`SimpleStatementSuite` and :class:`IndentedBlock`. This exists to simplify type definitions and isinstance checks. A suite is a group of statements controlled by a clause. A suite can be one or more semicolon-separated simple statements on the same line as the header, following the header’s colon, or it can be one or more indented statements on subsequent lines. -- https://docs.python.org/3/reference/compound_stmts.html """ __slots__ = () body: Union[Sequence["BaseStatement"], Sequence["BaseSmallStatement"]] class Expr(BaseSmallStatement): """ An expression used as a statement, where the result is unused and unassigned. The most common place you will find this is in function calls where the return value is unneeded. """ #: The expression itself. Python will evaluate the expression but not assign #: the result anywhere. value: BaseExpression #: Optional semicolon when this is used in a statement line. This semicolon #: owns the whitespace on both sides of it when it is used. semicolon: Union[Semicolon, MaybeSentinel] = MaybeSentinel.DEFAULT def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Expr": return Expr( value=visit_required(self, "value", self.value, visitor), semicolon=visit_sentinel(self, "semicolon", self.semicolon, visitor), ) def _codegen_impl( self, state: CodegenState, default_semicolon: bool = False ) -> None: with state.record_syntactic_position(self): self.value._codegen(state) semicolon = self.semicolon if isinstance(semicolon, MaybeSentinel): if default_semicolon: state.add_token("; ") elif isinstance(semicolon, Semicolon): semicolon._codegen(state) class SimpleStatementLine(_BaseSimpleStatement, BaseStatement): """ A simple statement that's part of an IndentedBlock or Module. A simple statement is a series of small statements joined together by semicolons. This isn't differentiated from a :class:`SimpleStatementSuite` in the grammar, but because a :class:`SimpleStatementLine` can own additional whitespace that a :class:`SimpleStatementSuite` doesn't have, we're differentiating it in the CST. """ #: Sequence of small statements. All but the last statement are required to have #: a semicolon. body: Sequence[BaseSmallStatement] #: Sequence of empty lines appearing before this simple statement line. leading_lines: Sequence[EmptyLine] = () #: Any optional trailing comment and the final ``NEWLINE`` at the end of the line. trailing_whitespace: TrailingWhitespace = TrailingWhitespace.field() def _visit_and_replace_children( self, visitor: CSTVisitorT ) -> "SimpleStatementLine": return SimpleStatementLine( leading_lines=visit_sequence( self, "leading_lines", self.leading_lines, visitor ), body=visit_sequence(self, "body", self.body, visitor), trailing_whitespace=visit_required( self, "trailing_whitespace", self.trailing_whitespace, visitor ), ) def _is_removable(self) -> bool: # If we have an empty body, we are removable since we don't represent # anything concrete. return not self.body def _codegen_impl(self, state: CodegenState) -> None: for ll in self.leading_lines: ll._codegen(state) state.add_indent_tokens() _BaseSimpleStatement._codegen_impl(self, state) class BaseCompoundStatement(BaseStatement, ABC): """ Encapsulates a compound statement, like ``if True: pass`` or ``while True: pass``. This exists to simplify type definitions and isinstance checks. Compound statements contain (groups of) other statements; they affect or control the execution of those other statements in some way. In general, compound statements span multiple lines, although in simple incarnations a whole compound statement may be contained in one line. -- https://docs.python.org/3/reference/compound_stmts.html """ __slots__ = () #: The body of this compound statement. body: BaseSuite #: Any empty lines or comments appearing before this statement. leading_lines: Sequence[EmptyLine] class SimpleString(_BasePrefixedString): """ Any sort of literal string expression that is not a :class:`FormattedString` (f-string), including triple-quoted multi-line strings. """ #: The texual representation of the string, including quotes, prefix characters, and #: any escape characters present in the original source code , such as #: ``r"my string\n"``. To remove the quotes and interpret any escape characters, #: use the calculated property :attr:`~SimpleString.evaluated_value`. value: str lpar: Sequence[LeftParen] = () #: Sequence of parenthesis for precidence dictation. rpar: Sequence[RightParen] = () def _validate(self) -> None: super(SimpleString, self)._validate() # Validate any prefix prefix = self.prefix if prefix not in ("", "r", "u", "b", "br", "rb"): raise CSTValidationError("Invalid string prefix.") prefixlen = len(prefix) # Validate wrapping quotes if len(self.value) < (prefixlen + 2): raise CSTValidationError("String must have enclosing quotes.") if ( self.value[prefixlen] not in ['"', "'"] or self.value[prefixlen] != self.value[-1] ): raise CSTValidationError("String must have matching enclosing quotes.") # Check validity of triple-quoted strings if len(self.value) >= (prefixlen + 6): if self.value[prefixlen] == self.value[prefixlen + 1]: # We know this isn't an empty string, so there needs to be a third # identical enclosing token. if ( self.value[prefixlen] != self.value[prefixlen + 2] or self.value[prefixlen] != self.value[-2] or self.value[prefixlen] != self.value[-3] ): raise CSTValidationError( "String must have matching enclosing quotes." ) # We should check the contents as well, but this is pretty complicated, # partially due to triple-quoted strings. def prefix(self) -> str: """ Returns the string's prefix, if any exists. The prefix can be ``r``, ``u``, ``b``, ``br`` or ``rb``. """ prefix: str = "" for c in self.value: if c in ['"', "'"]: break prefix += c return prefix.lower() def quote(self) -> StringQuoteLiteral: """ Returns the quotation used to denote the string. Can be either ``'``, ``"``, ``'''`` or ``\"\"\"``. """ quote: str = "" for char in self.value[len(self.prefix) :]: if char not in {"'", '"'}: break if quote and char != quote[0]: # This is no longer the same string quote break quote += char if len(quote) == 2: # Let's assume this is an empty string. quote = quote[:1] elif 3 < len(quote) <= 6: # Let's assume this can be one of the following: # >>> """"foo""" # '"foo' # >>> """""bar""" # '""bar' # >>> """""" # '' quote = quote[:3] if len(quote) not in {1, 3}: # We shouldn't get here due to construction validation logic, # but handle the case anyway. raise Exception(f"Invalid string {self.value}") # pyre-ignore We know via the above validation that we will only # ever return one of the four string literals. return quote def raw_value(self) -> str: """ Returns the raw value of the string as it appears in source, without the beginning or end quotes and without the prefix. This is often useful when constructing transforms which need to manipulate strings in source code. """ prefix_len = len(self.prefix) quote_len = len(self.quote) return self.value[(prefix_len + quote_len) : (-quote_len)] def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "SimpleString": return SimpleString( lpar=visit_sequence(self, "lpar", self.lpar, visitor), value=self.value, rpar=visit_sequence(self, "rpar", self.rpar, visitor), ) def _codegen_impl(self, state: CodegenState) -> None: with self._parenthesize(state): state.add_token(self.value) def evaluated_value(self) -> Union[str, bytes]: """ Return an :func:`ast.literal_eval` evaluated str of :py:attr:`value`. """ return literal_eval(self.value) class ConcatenatedString(BaseString): """ Represents an implicitly concatenated string, such as:: "abc" "def" == "abcdef" .. warning:: This is different from two strings joined in a :class:`BinaryOperation` with an :class:`Add` operator, and is `sometimes viewed as an antifeature of Python <https://lwn.net/Articles/551426/>`_. """ #: String on the left of the concatenation. left: Union[SimpleString, FormattedString] #: String on the right of the concatenation. right: Union[SimpleString, FormattedString, "ConcatenatedString"] lpar: Sequence[LeftParen] = () #: Sequence of parenthesis for precidence dictation. rpar: Sequence[RightParen] = () #: Whitespace between the ``left`` and ``right`` substrings. whitespace_between: BaseParenthesizableWhitespace = SimpleWhitespace.field("") def _safe_to_use_with_word_operator(self, position: ExpressionPosition) -> bool: if super(ConcatenatedString, self)._safe_to_use_with_word_operator(position): # if we have parenthesis, we're safe. return True return self._check_left_right_word_concatenation_safety( position, self.left, self.right ) def _validate(self) -> None: super(ConcatenatedString, self)._validate() # Strings that are concatenated cannot have parens. if bool(self.left.lpar) or bool(self.left.rpar): raise CSTValidationError("Cannot concatenate parenthesized strings.") if bool(self.right.lpar) or bool(self.right.rpar): raise CSTValidationError("Cannot concatenate parenthesized strings.") # Cannot concatenate str and bytes leftbytes = "b" in self.left.prefix right = self.right if isinstance(right, ConcatenatedString): rightbytes = "b" in right.left.prefix elif isinstance(right, SimpleString): rightbytes = "b" in right.prefix elif isinstance(right, FormattedString): rightbytes = "b" in right.prefix else: raise Exception("Logic error!") if leftbytes != rightbytes: raise CSTValidationError("Cannot concatenate string and bytes.") def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "ConcatenatedString": return ConcatenatedString( lpar=visit_sequence(self, "lpar", self.lpar, visitor), left=visit_required(self, "left", self.left, visitor), whitespace_between=visit_required( self, "whitespace_between", self.whitespace_between, visitor ), right=visit_required(self, "right", self.right, visitor), rpar=visit_sequence(self, "rpar", self.rpar, visitor), ) def _codegen_impl(self, state: CodegenState) -> None: with self._parenthesize(state): self.left._codegen(state) self.whitespace_between._codegen(state) self.right._codegen(state) def evaluated_value(self) -> Union[str, bytes, None]: """ Return an :func:`ast.literal_eval` evaluated str of recursively concatenated :py:attr:`left` and :py:attr:`right` if and only if both :py:attr:`left` and :py:attr:`right` are composed by :class:`SimpleString` or :class:`ConcatenatedString` (:class:`FormattedString` cannot be evaluated). """ left = self.left right = self.right if isinstance(left, FormattedString) or isinstance(right, FormattedString): return None left_val = left.evaluated_value right_val = right.evaluated_value if right_val is None: return None if isinstance(left_val, bytes) and isinstance(right_val, bytes): return left_val + right_val if isinstance(left_val, str) and isinstance(right_val, str): return left_val + right_val return None The provided code snippet includes necessary dependencies for implementing the `get_docstring_impl` function. Write a Python function `def get_docstring_impl( body: Union[BaseSuite, Sequence[Union[SimpleStatementLine, BaseCompoundStatement]]], clean: bool, ) -> Optional[str]` to solve the following problem: Implementation Reference: - :func:`ast.get_docstring` https://docs.python.org/3/library/ast.html#ast.get_docstring and https://github.com/python/cpython/blob/89aa4694fc8c6d190325ef8ed6ce6a6b8efb3e50/Lib/ast.py#L254 - PEP 257 https://www.python.org/dev/peps/pep-0257/ Here is the function: def get_docstring_impl( body: Union[BaseSuite, Sequence[Union[SimpleStatementLine, BaseCompoundStatement]]], clean: bool, ) -> Optional[str]: """ Implementation Reference: - :func:`ast.get_docstring` https://docs.python.org/3/library/ast.html#ast.get_docstring and https://github.com/python/cpython/blob/89aa4694fc8c6d190325ef8ed6ce6a6b8efb3e50/Lib/ast.py#L254 - PEP 257 https://www.python.org/dev/peps/pep-0257/ """ if isinstance(body, Sequence): if body: expr = body[0] else: return None else: expr = body while isinstance(expr, (BaseSuite, SimpleStatementLine)): if len(expr.body) == 0: return None expr = expr.body[0] if not isinstance(expr, Expr): return None val = expr.value if isinstance(val, (SimpleString, ConcatenatedString)): evaluated_value = val.evaluated_value else: return None if isinstance(evaluated_value, bytes): return None if evaluated_value is not None and clean: return inspect.cleandoc(evaluated_value) return evaluated_value
Implementation Reference: - :func:`ast.get_docstring` https://docs.python.org/3/library/ast.html#ast.get_docstring and https://github.com/python/cpython/blob/89aa4694fc8c6d190325ef8ed6ce6a6b8efb3e50/Lib/ast.py#L254 - PEP 257 https://www.python.org/dev/peps/pep-0257/
4,975
from abc import ABC, abstractmethod from copy import deepcopy from dataclasses import dataclass, field, fields, replace from typing import Any, cast, ClassVar, Dict, List, Mapping, Sequence, TypeVar, Union from libcst._flatten_sentinel import FlattenSentinel from libcst._nodes.internal import CodegenState from libcst._removal_sentinel import RemovalSentinel from libcst._type_enforce import is_value_of_type from libcst._types import CSTNodeT from libcst._visitors import CSTTransformer, CSTVisitor, CSTVisitorT def _pretty_repr_sequence(seq: Sequence[object]) -> str: if len(seq) == 0: return "[]" else: return "\n".join(["[", *[f"{_indent(repr(el))}," for el in seq], "]"]) def _pretty_repr(value: object) -> str: if not isinstance(value, str) and isinstance(value, Sequence): return _pretty_repr_sequence(value) else: return repr(value)
null
4,976
from abc import ABC, abstractmethod from copy import deepcopy from dataclasses import dataclass, field, fields, replace from typing import Any, cast, ClassVar, Dict, List, Mapping, Sequence, TypeVar, Union from libcst._flatten_sentinel import FlattenSentinel from libcst._nodes.internal import CodegenState from libcst._removal_sentinel import RemovalSentinel from libcst._type_enforce import is_value_of_type from libcst._types import CSTNodeT from libcst._visitors import CSTTransformer, CSTVisitor, CSTVisitorT def _clone(val: object) -> object: # We can't use isinstance(val, CSTNode) here due to poor performance # of isinstance checks against ABC direct subclasses. What we're trying # to do here is recursively call this functionality on subclasses, but # if the attribute isn't a CSTNode, fall back to copy.deepcopy. try: # pyre-ignore We know this might not exist, that's the point of the # attribute error and try block. return val.deep_clone() except AttributeError: return deepcopy(val)
null
4,977
from contextlib import contextmanager from dataclasses import dataclass, field from typing import Iterable, Iterator, List, Optional, Sequence, TYPE_CHECKING, Union from libcst._add_slots import add_slots from libcst._flatten_sentinel import FlattenSentinel from libcst._maybe_sentinel import MaybeSentinel from libcst._removal_sentinel import RemovalSentinel from libcst._types import CSTNodeT class FlattenSentinel(Sequence[CSTNodeT_co]): """ A :class:`FlattenSentinel` may be returned by a :meth:`CSTTransformer.on_leave` method when one wants to replace a node with multiple nodes. The replaced node must be contained in a `Sequence` attribute such as :attr:`~libcst.Module.body`. This is generally the case for :class:`~libcst.BaseStatement` and :class:`~libcst.BaseSmallStatement`. For example to insert a print before every return:: def leave_Return( self, original_node: cst.Return, updated_node: cst.Return ) -> Union[cst.Return, cst.RemovalSentinel, cst.FlattenSentinel[cst.BaseSmallStatement]]: log_stmt = cst.Expr(cst.parse_expression("print('returning')")) return cst.FlattenSentinel([log_stmt, updated_node]) Returning an empty :class:`FlattenSentinel` is equivalent to returning :attr:`cst.RemovalSentinel.REMOVE` and is subject to its requirements. """ nodes: Sequence[CSTNodeT_co] def __init__(self, nodes: Iterable[CSTNodeT_co]) -> None: self.nodes = tuple(nodes) def __getitem__(self, idx: int) -> CSTNodeT_co: return self.nodes[idx] def __len__(self) -> int: return len(self.nodes) class RemovalSentinel(Enum): """ A :attr:`RemovalSentinel.REMOVE` value should be returned by a :meth:`CSTTransformer.on_leave` method when we want to remove that child from its parent. As a convenience, this can be constructed by calling :func:`libcst.RemoveFromParent`. The parent node should make a best-effort to remove the child, but may raise an exception when removing the child doesn't make sense, or could change the semantics in an unexpected way. For example, a function definition with no name doesn't make sense, but removing one of the arguments is valid. In we can't automatically remove the child, the developer should instead remove the child by constructing a new parent in the parent's :meth:`~CSTTransformer.on_leave` call. We use this instead of ``None`` to force developers to be explicit about deletions. Because ``None`` is the default return value for a function with no return statement, it would be too easy to accidentally delete nodes from the tree by forgetting to return a value. """ REMOVE = auto() CSTNodeT = TypeVar("CSTNodeT", bound="CSTNode") The provided code snippet includes necessary dependencies for implementing the `visit_required` function. Write a Python function `def visit_required( parent: "CSTNode", fieldname: str, node: CSTNodeT, visitor: "CSTVisitorT" ) -> CSTNodeT` to solve the following problem: Given a node, visits the node using `visitor`. If removal is attempted by the visitor, an exception is raised. Here is the function: def visit_required( parent: "CSTNode", fieldname: str, node: CSTNodeT, visitor: "CSTVisitorT" ) -> CSTNodeT: """ Given a node, visits the node using `visitor`. If removal is attempted by the visitor, an exception is raised. """ visitor.on_visit_attribute(parent, fieldname) result = node.visit(visitor) if isinstance(result, RemovalSentinel): raise TypeError( f"We got a RemovalSentinel while visiting a {type(node).__name__}. This " + "node's parent does not allow it to be removed." ) elif isinstance(result, FlattenSentinel): raise TypeError( f"We got a FlattenSentinel while visiting a {type(node).__name__}. This " + "node's parent does not allow for it to be it to be replaced with a " + "sequence." ) visitor.on_leave_attribute(parent, fieldname) return result
Given a node, visits the node using `visitor`. If removal is attempted by the visitor, an exception is raised.
4,978
from contextlib import contextmanager from dataclasses import dataclass, field from typing import Iterable, Iterator, List, Optional, Sequence, TYPE_CHECKING, Union from libcst._add_slots import add_slots from libcst._flatten_sentinel import FlattenSentinel from libcst._maybe_sentinel import MaybeSentinel from libcst._removal_sentinel import RemovalSentinel from libcst._types import CSTNodeT class FlattenSentinel(Sequence[CSTNodeT_co]): """ A :class:`FlattenSentinel` may be returned by a :meth:`CSTTransformer.on_leave` method when one wants to replace a node with multiple nodes. The replaced node must be contained in a `Sequence` attribute such as :attr:`~libcst.Module.body`. This is generally the case for :class:`~libcst.BaseStatement` and :class:`~libcst.BaseSmallStatement`. For example to insert a print before every return:: def leave_Return( self, original_node: cst.Return, updated_node: cst.Return ) -> Union[cst.Return, cst.RemovalSentinel, cst.FlattenSentinel[cst.BaseSmallStatement]]: log_stmt = cst.Expr(cst.parse_expression("print('returning')")) return cst.FlattenSentinel([log_stmt, updated_node]) Returning an empty :class:`FlattenSentinel` is equivalent to returning :attr:`cst.RemovalSentinel.REMOVE` and is subject to its requirements. """ nodes: Sequence[CSTNodeT_co] def __init__(self, nodes: Iterable[CSTNodeT_co]) -> None: self.nodes = tuple(nodes) def __getitem__(self, idx: int) -> CSTNodeT_co: return self.nodes[idx] def __len__(self) -> int: return len(self.nodes) class RemovalSentinel(Enum): """ A :attr:`RemovalSentinel.REMOVE` value should be returned by a :meth:`CSTTransformer.on_leave` method when we want to remove that child from its parent. As a convenience, this can be constructed by calling :func:`libcst.RemoveFromParent`. The parent node should make a best-effort to remove the child, but may raise an exception when removing the child doesn't make sense, or could change the semantics in an unexpected way. For example, a function definition with no name doesn't make sense, but removing one of the arguments is valid. In we can't automatically remove the child, the developer should instead remove the child by constructing a new parent in the parent's :meth:`~CSTTransformer.on_leave` call. We use this instead of ``None`` to force developers to be explicit about deletions. Because ``None`` is the default return value for a function with no return statement, it would be too easy to accidentally delete nodes from the tree by forgetting to return a value. """ REMOVE = auto() CSTNodeT = TypeVar("CSTNodeT", bound="CSTNode") The provided code snippet includes necessary dependencies for implementing the `visit_optional` function. Write a Python function `def visit_optional( parent: "CSTNode", fieldname: str, node: Optional[CSTNodeT], visitor: "CSTVisitorT" ) -> Optional[CSTNodeT]` to solve the following problem: Given an optional node, visits the node if it exists with `visitor`. If the node is removed, returns None. Here is the function: def visit_optional( parent: "CSTNode", fieldname: str, node: Optional[CSTNodeT], visitor: "CSTVisitorT" ) -> Optional[CSTNodeT]: """ Given an optional node, visits the node if it exists with `visitor`. If the node is removed, returns None. """ if node is None: visitor.on_visit_attribute(parent, fieldname) visitor.on_leave_attribute(parent, fieldname) return None visitor.on_visit_attribute(parent, fieldname) result = node.visit(visitor) if isinstance(result, FlattenSentinel): raise TypeError( f"We got a FlattenSentinel while visiting a {type(node).__name__}. This " + "node's parent does not allow for it to be it to be replaced with a " + "sequence." ) visitor.on_leave_attribute(parent, fieldname) return None if isinstance(result, RemovalSentinel) else result
Given an optional node, visits the node if it exists with `visitor`. If the node is removed, returns None.
4,979
from contextlib import contextmanager from dataclasses import dataclass, field from typing import Iterable, Iterator, List, Optional, Sequence, TYPE_CHECKING, Union from libcst._add_slots import add_slots from libcst._flatten_sentinel import FlattenSentinel from libcst._maybe_sentinel import MaybeSentinel from libcst._removal_sentinel import RemovalSentinel from libcst._types import CSTNodeT class FlattenSentinel(Sequence[CSTNodeT_co]): """ A :class:`FlattenSentinel` may be returned by a :meth:`CSTTransformer.on_leave` method when one wants to replace a node with multiple nodes. The replaced node must be contained in a `Sequence` attribute such as :attr:`~libcst.Module.body`. This is generally the case for :class:`~libcst.BaseStatement` and :class:`~libcst.BaseSmallStatement`. For example to insert a print before every return:: def leave_Return( self, original_node: cst.Return, updated_node: cst.Return ) -> Union[cst.Return, cst.RemovalSentinel, cst.FlattenSentinel[cst.BaseSmallStatement]]: log_stmt = cst.Expr(cst.parse_expression("print('returning')")) return cst.FlattenSentinel([log_stmt, updated_node]) Returning an empty :class:`FlattenSentinel` is equivalent to returning :attr:`cst.RemovalSentinel.REMOVE` and is subject to its requirements. """ nodes: Sequence[CSTNodeT_co] def __init__(self, nodes: Iterable[CSTNodeT_co]) -> None: self.nodes = tuple(nodes) def __getitem__(self, idx: int) -> CSTNodeT_co: return self.nodes[idx] def __len__(self) -> int: return len(self.nodes) class MaybeSentinel(Enum): """ A :class:`MaybeSentinel` value is used as the default value for some attributes to denote that when generating code (when :attr:`Module.code` is evaluated) we should optionally include this element in order to generate valid code. :class:`MaybeSentinel` is only used for "syntactic trivia" that most users shouldn't care much about anyways, like commas, semicolons, and whitespace. For example, a function call's :attr:`Arg.comma` value defaults to :attr:`MaybeSentinel.DEFAULT`. A comma is required after every argument, except for the last one. If a comma is required and :attr:`Arg.comma` is a :class:`MaybeSentinel`, one is inserted. This makes manual node construction easier, but it also means that we safely add arguments to a preexisting function call without manually fixing the commas: >>> import libcst as cst >>> fn_call = cst.parse_expression("fn(1, 2)") >>> new_fn_call = fn_call.with_changes( ... args=[*fn_call.args, cst.Arg(cst.Integer("3"))] ... ) >>> dummy_module = cst.parse_module("") # we need to use Module.code_for_node >>> dummy_module.code_for_node(fn_call) 'fn(1, 2)' >>> dummy_module.code_for_node(new_fn_call) 'fn(1, 2, 3)' Notice that a comma was automatically inserted after the second argument. Since the original second argument had no comma, it was initialized to :attr:`MaybeSentinel.DEFAULT`. During the code generation of the second argument, a comma was inserted to ensure that the resulting code is valid. .. warning:: While this sentinel is used in place of nodes, it is not a :class:`CSTNode`, and will not be visited by a :class:`CSTVisitor`. Some other libraries, like `RedBaron`_, take other approaches to this problem. RedBaron's tree is mutable (LibCST's tree is immutable), and so they're able to solve this problem with `"proxy lists" <http://redbaron.pycqa.org/en/latest/proxy_list.html>`_. Both approaches come with different sets of tradeoffs. .. _RedBaron: http://redbaron.pycqa.org/en/latest/index.html """ DEFAULT = auto() def __repr__(self) -> str: return str(self) class RemovalSentinel(Enum): """ A :attr:`RemovalSentinel.REMOVE` value should be returned by a :meth:`CSTTransformer.on_leave` method when we want to remove that child from its parent. As a convenience, this can be constructed by calling :func:`libcst.RemoveFromParent`. The parent node should make a best-effort to remove the child, but may raise an exception when removing the child doesn't make sense, or could change the semantics in an unexpected way. For example, a function definition with no name doesn't make sense, but removing one of the arguments is valid. In we can't automatically remove the child, the developer should instead remove the child by constructing a new parent in the parent's :meth:`~CSTTransformer.on_leave` call. We use this instead of ``None`` to force developers to be explicit about deletions. Because ``None`` is the default return value for a function with no return statement, it would be too easy to accidentally delete nodes from the tree by forgetting to return a value. """ REMOVE = auto() CSTNodeT = TypeVar("CSTNodeT", bound="CSTNode") The provided code snippet includes necessary dependencies for implementing the `visit_sentinel` function. Write a Python function `def visit_sentinel( parent: "CSTNode", fieldname: str, node: Union[CSTNodeT, MaybeSentinel], visitor: "CSTVisitorT", ) -> Union[CSTNodeT, MaybeSentinel]` to solve the following problem: Given a node that can be a real value or a sentinel value, visits the node if it is real with `visitor`. If the node is removed, returns MaybeSentinel. Here is the function: def visit_sentinel( parent: "CSTNode", fieldname: str, node: Union[CSTNodeT, MaybeSentinel], visitor: "CSTVisitorT", ) -> Union[CSTNodeT, MaybeSentinel]: """ Given a node that can be a real value or a sentinel value, visits the node if it is real with `visitor`. If the node is removed, returns MaybeSentinel. """ if isinstance(node, MaybeSentinel): visitor.on_visit_attribute(parent, fieldname) visitor.on_leave_attribute(parent, fieldname) return MaybeSentinel.DEFAULT visitor.on_visit_attribute(parent, fieldname) result = node.visit(visitor) if isinstance(result, FlattenSentinel): raise TypeError( f"We got a FlattenSentinel while visiting a {type(node).__name__}. This " + "node's parent does not allow for it to be it to be replaced with a " + "sequence." ) visitor.on_leave_attribute(parent, fieldname) return MaybeSentinel.DEFAULT if isinstance(result, RemovalSentinel) else result
Given a node that can be a real value or a sentinel value, visits the node if it is real with `visitor`. If the node is removed, returns MaybeSentinel.