How to use libcst - 10 common examples

To help you get started, we’ve selected a few libcst examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Instagram / LibCST / libcst / codegen / generate.py View on Github external
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
github Instagram / LibCST / libcst / codegen / gen_matcher_classes.py View on Github external
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[]].
    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
github Instagram / LibCST / libcst / codegen / gen_matcher_classes.py View on Github external
# 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[]].
    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
github Instagram / LibCST / libcst / _nodes / expression.py View on Github external
def _codegen_impl(self, state: CodegenState) -> None:
        with self._parenthesize(state):
            self.func._codegen(state)
            self.whitespace_after_func._codegen(state)
            state.add_token("(")
            self.whitespace_before_args._codegen(state)
            lastarg = len(self.args) - 1
            for i, arg in enumerate(self.args):
                arg._codegen(state, default_comma=(i != lastarg))
            state.add_token(")")


@add_slots
@dataclass(frozen=True)
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(" ")
github Instagram / LibCST / libcst / _typed_visitor.py View on Github external
    @mark_no_op
    def visit_ComparisonTarget(self, node: "ComparisonTarget") -> Optional[bool]:
        pass
github Instagram / LibCST / libcst / _typed_visitor.py View on Github external
    @mark_no_op
    def visit_FloorDivide(self, node: "FloorDivide") -> Optional[bool]:
        pass
github Instagram / LibCST / libcst / _typed_visitor.py View on Github external
    @mark_no_op
    def leave_And(self, original_node: "And") -> None:
        pass
github Instagram / LibCST / libcst / _typed_visitor.py View on Github external
    @mark_no_op
    def visit_SubtractAssign(self, node: "SubtractAssign") -> Optional[bool]:
        pass
github Instagram / LibCST / libcst / _typed_visitor.py View on Github external
    @mark_no_op
    def leave_GeneratorExp(
        self, original_node: "GeneratorExp", updated_node: "GeneratorExp"
    ) -> Union["BaseExpression"]:
        return updated_node
github Instagram / LibCST / libcst / _typed_visitor.py View on Github external
    @mark_no_op
    def visit_LessThanEqual(self, node: "LessThanEqual") -> Optional[bool]:
        pass