id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
4,780
import asyncio import base64 import functools import hashlib import itertools import json import logging import os import re import shutil import tempfile import time from abc import ABC, abstractmethod from dataclasses import dataclass from typing import Any, Callable, Optional import aiofiles import aiohttp import m3u8 from Cryptodome.Cipher import AES, Blowfish from Cryptodome.Util import Counter from .. import converter from ..exceptions import NonStreamableError The provided code snippet includes necessary dependencies for implementing the `concat_audio_files` function. Write a Python function `async def concat_audio_files(paths: list[str], out: str, ext: str, max_files_open=128)` to solve the following problem: Concatenate audio files using FFmpeg. Batched by max files open. Recurses log_{max_file_open}(len(paths)) times. Here is the function: async def concat_audio_files(paths: list[str], out: str, ext: str, max_files_open=128): """Concatenate audio files using FFmpeg. Batched by max files open. Recurses log_{max_file_open}(len(paths)) times. """ if shutil.which("ffmpeg") is None: raise Exception("FFmpeg must be installed.") # Base case if len(paths) == 1: shutil.move(paths[0], out) return it = iter(paths) num_batches = len(paths) // max_files_open + ( 1 if len(paths) % max_files_open != 0 else 0 ) tempdir = tempfile.gettempdir() outpaths = [ os.path.join( tempdir, f"__streamrip_ffmpeg_{hash(paths[i*max_files_open])}.{ext}", ) for i in range(num_batches) ] for p in outpaths: try: os.remove(p) # in case of failure except FileNotFoundError: pass proc_futures = [] for i in range(num_batches): command = ( "ffmpeg", "-i", f"concat:{'|'.join(itertools.islice(it, max_files_open))}", "-acodec", "copy", "-loglevel", "warning", outpaths[i], ) fut = asyncio.create_subprocess_exec(*command, stderr=asyncio.subprocess.PIPE) proc_futures.append(fut) # Create all processes concurrently processes = await asyncio.gather(*proc_futures) # wait for all of them to finish await asyncio.gather(*[p.communicate() for p in processes]) for proc in processes: if proc.returncode != 0: raise Exception( f"FFMPEG returned with status code {proc.returncode} error: {proc.stderr} output: {proc.stdout}", ) # Recurse on remaining batches await concat_audio_files(outpaths, out, ext)
Concatenate audio files using FFmpeg. Batched by max files open. Recurses log_{max_file_open}(len(paths)) times.
4,781
import asyncio import itertools import logging import random import re from ..config import Config from ..exceptions import NonStreamableError from .client import Client from .downloadable import SoundcloudDownloadable def batched(iterable, n, fillvalue=None): args = [iter(iterable)] * n return list(itertools.zip_longest(*args, fillvalue=fillvalue))
null
4,782
import asyncio import itertools import logging import random import re from ..config import Config from ..exceptions import NonStreamableError from .client import Client from .downloadable import SoundcloudDownloadable def filter_none(iterable): return (x for x in iterable if x is not None)
null
4,783
from os import environ import setuptools from setuptools_rust import Binding, RustExtension def no_local_scheme(version: str) -> str: return ""
null
4,784
def strip_class_signature(app, what, name, obj, options, signature, return_annotation): if what == "class": return (None, return_annotation) return (signature, return_annotation) def strip_class_signature_docstring(app, what, name, obj, options, lines): if what == "class": cls_name = name.split(".")[-1] if lines and lines[0].startswith(cls_name): while lines: del lines[0] def setup(app): app.connect("autodoc-process-signature", strip_class_signature) app.connect("autodoc-process-docstring", strip_class_signature_docstring) app.add_css_file("custom.css")
null
4,785
import json import subprocess from pathlib import Path from typing import Dict, List, Mapping, Optional, Sequence, Tuple from mypy_extensions import TypedDict import libcst as cst from libcst._position import CodePosition, CodeRange from libcst.metadata.base_provider import BatchableMetadataProvider from libcst.metadata.position_provider import PositionProvider def run_command( cmd_args: List[str], timeout: Optional[int] = None ) -> Tuple[str, str, int]: process = subprocess.run(cmd_args, capture_output=True, timeout=timeout) return process.stdout.decode(), process.stderr.decode(), process.returncode
null
4,786
import json import subprocess from pathlib import Path from typing import Dict, List, Mapping, Optional, Sequence, Tuple from mypy_extensions import TypedDict import libcst as cst from libcst._position import CodePosition, CodeRange from libcst.metadata.base_provider import BatchableMetadataProvider from libcst.metadata.position_provider import PositionProvider class PyreData(TypedDict, total=False): types: Sequence[InferredType] class RawPyreData(TypedDict): path: str types: Sequence[InferredType] def _sort_by_position(data: InferredType) -> Tuple[int, int, int, int]: start = data["location"]["start"] stop = data["location"]["stop"] return start["line"], start["column"], stop["line"], stop["column"] def _process_pyre_data(data: RawPyreData) -> PyreData: return {"types": sorted(data["types"], key=_sort_by_position)}
null
4,787
from contextlib import contextmanager from dataclasses import dataclass, field from typing import Callable, Iterator, List, Optional from libcst import CSTNode, Module from libcst._nodes.internal import CodegenState from libcst.metadata.base_provider import BaseMetadataProvider def byte_length_in_utf8(value: str) -> int: return len(value.encode("utf8"))
null
4,788
import textwrap from contextlib import ExitStack from types import MappingProxyType from typing import ( Any, cast, Collection, Iterable, Mapping, MutableMapping, MutableSet, Optional, Type, TYPE_CHECKING, TypeVar, ) from libcst._batched_visitor import BatchableCSTVisitor, visit_batched, VisitorMethod from libcst._exceptions import MetadataException from libcst.metadata.base_provider import BatchableMetadataProvider def _gen_batchable( wrapper: "MetadataWrapper", # pyre-fixme[2]: Parameter `providers` must have a type that does not contain `Any` providers: Iterable[BatchableMetadataProvider[Any]], ) -> Mapping["ProviderT", Mapping["CSTNode", object]]: """ Returns map of metadata mappings from resolving ``providers`` on ``wrapper``. """ wrapper.visit_batched(providers) # Make immutable metadata mapping # pyre-ignore[7] return {type(p): MappingProxyType(dict(p._computed)) for p in providers} def _gather_providers( providers: Collection["ProviderT"], gathered: MutableSet["ProviderT"] ) -> MutableSet["ProviderT"]: """ Recursively gathers all the given providers and their dependencies. """ for P in providers: if P not in gathered: gathered.add(P) _gather_providers(P.METADATA_DEPENDENCIES, gathered) return gathered class MetadataException(Exception): pass class BatchableMetadataProvider( BatchableCSTVisitor, BaseMetadataProvider[_ProvidedMetadataT] ): """ The low-level base class for all batchable visitor-based metadata providers. Batchable providers should be preferred when possible as they are more efficient to run compared to non-batchable visitor-based providers. Inherits from :class:`~libcst.BatchableCSTVisitor`. This class is generic. A subclass of ``BatchableMetadataProvider[T]`` will provider metadata of type ``T``. """ def _gen_impl(self, module: "Module") -> None: """ Batchables providers are resolved through _gen_batchable] so no implementation should be provided in _gen_impl. """ pass The provided code snippet includes necessary dependencies for implementing the `_resolve_impl` function. Write a Python function `def _resolve_impl( wrapper: "MetadataWrapper", providers: Collection["ProviderT"] ) -> None` to solve the following problem: Updates the _metadata map on wrapper with metadata from the given providers as well as their dependencies. Here is the function: def _resolve_impl( wrapper: "MetadataWrapper", providers: Collection["ProviderT"] ) -> None: """ Updates the _metadata map on wrapper with metadata from the given providers as well as their dependencies. """ completed = set(wrapper._metadata.keys()) remaining = _gather_providers(set(providers), set()) - completed while len(remaining) > 0: batchable = set() for P in remaining: if set(P.METADATA_DEPENDENCIES).issubset(completed): if issubclass(P, BatchableMetadataProvider): batchable.add(P) else: wrapper._metadata[P] = ( P(wrapper._cache.get(P))._gen(wrapper) if P.gen_cache else P()._gen(wrapper) ) completed.add(P) initialized_batchable = [ p(wrapper._cache.get(p)) if p.gen_cache else p() for p in batchable ] metadata_batch = _gen_batchable(wrapper, initialized_batchable) wrapper._metadata.update(metadata_batch) completed |= batchable if len(completed) == 0 and len(batchable) == 0: # remaining must be non-empty at this point names = ", ".join([P.__name__ for P in remaining]) raise MetadataException(f"Detected circular dependencies in {names}") remaining -= completed
Updates the _metadata map on wrapper with metadata from the given providers as well as their dependencies.
4,789
import abc import builtins from collections import defaultdict from contextlib import contextmanager, ExitStack from dataclasses import dataclass from enum import auto, Enum from typing import ( Collection, Dict, Iterator, List, Mapping, MutableMapping, Optional, Set, Tuple, Type, Union, ) import libcst as cst from libcst import ensure_type from libcst._add_slots import add_slots from libcst.helpers import get_full_name_for_node from libcst.metadata.base_provider import BatchableMetadataProvider from libcst.metadata.expression_context_provider import ( ExpressionContext, ExpressionContextProvider, ) def _gen_dotted_names( node: Union[cst.Attribute, cst.Name] ) -> Iterator[Tuple[str, Union[cst.Attribute, cst.Name]]]: if isinstance(node, cst.Name): yield node.value, node else: value = node.value if isinstance(value, cst.Call): value = value.func if isinstance(value, (cst.Attribute, cst.Name)): name_values = _gen_dotted_names(value) try: next_name, next_node = next(name_values) except StopIteration: return else: yield next_name, next_node yield from name_values elif isinstance(value, (cst.Attribute, cst.Name)): name_values = _gen_dotted_names(value) try: next_name, next_node = next(name_values) except StopIteration: return else: yield f"{next_name}.{node.attr.value}", node yield next_name, next_node yield from name_values
null
4,790
import abc import builtins from collections import defaultdict from contextlib import contextmanager, ExitStack from dataclasses import dataclass from enum import auto, Enum from typing import ( Collection, Dict, Iterator, List, Mapping, MutableMapping, Optional, Set, Tuple, Type, Union, ) import libcst as cst from libcst import ensure_type from libcst._add_slots import add_slots from libcst.helpers import get_full_name_for_node from libcst.metadata.base_provider import BatchableMetadataProvider from libcst.metadata.expression_context_provider import ( ExpressionContext, ExpressionContextProvider, ) The provided code snippet includes necessary dependencies for implementing the `_is_assignment` function. Write a Python function `def _is_assignment(node: cst.CSTNode, assignment_node: cst.CSTNode) -> bool` to solve the following problem: Returns true if ``node`` is part of the assignment at ``assignment_node``. Normally this is just a simple identity check, except for imports where the assignment is attached to the entire import statement but we are interested in ``Name`` nodes inside the statement. Here is the function: def _is_assignment(node: cst.CSTNode, assignment_node: cst.CSTNode) -> bool: """ Returns true if ``node`` is part of the assignment at ``assignment_node``. Normally this is just a simple identity check, except for imports where the assignment is attached to the entire import statement but we are interested in ``Name`` nodes inside the statement. """ if node is assignment_node: return True if isinstance(assignment_node, (cst.Import, cst.ImportFrom)): aliases = assignment_node.names if isinstance(aliases, cst.ImportStar): return False for alias in aliases: if alias.name is node: return True asname = alias.asname if asname is not None: if asname.name is node: return True return False
Returns true if ``node`` is part of the assignment at ``assignment_node``. Normally this is just a simple identity check, except for imports where the assignment is attached to the entire import statement but we are interested in ``Name`` nodes inside the statement.
4,791
The provided code snippet includes necessary dependencies for implementing the `expand_tabs` function. Write a Python function `def expand_tabs(line: str) -> str` to solve the following problem: Tabs are treated as 1-8 spaces according to https://docs.python.org/3/reference/lexical_analysis.html#indentation Given a string with tabs, this removes all tab characters and replaces them with the appropriate number of spaces. Here is the function: def expand_tabs(line: str) -> str: """ Tabs are treated as 1-8 spaces according to https://docs.python.org/3/reference/lexical_analysis.html#indentation Given a string with tabs, this removes all tab characters and replaces them with the appropriate number of spaces. """ result_list = [] total = 0 for ch in line: if ch == "\t": prev_total = total total = ((total + 8) // 8) * 8 result_list.append(" " * (total - prev_total)) else: total += 1 result_list.append(ch) return "".join(result_list)
Tabs are treated as 1-8 spaces according to https://docs.python.org/3/reference/lexical_analysis.html#indentation Given a string with tabs, this removes all tab characters and replaces them with the appropriate number of spaces.
4,792
import dataclasses from itertools import chain, filterfalse from typing import Any, Mapping, Type, TypeVar _T = TypeVar("_T") def add_slots(cls: Type[_T]) -> Type[_T]: # Need to create a new class, since we can't set __slots__ # after a class has been created. # Make sure __slots__ isn't already set. if "__slots__" in cls.__dict__: raise TypeError(f"{cls.__name__} already specifies __slots__") # Create a new dict for our new class. cls_dict = dict(cls.__dict__) field_names = tuple(f.name for f in dataclasses.fields(cls)) inherited_slots = set( chain.from_iterable( superclass.__dict__.get("__slots__", ()) for superclass in cls.mro() ) ) cls_dict["__slots__"] = tuple( filterfalse(inherited_slots.__contains__, field_names) ) for field_name in field_names: # Remove our attributes, if present. They'll still be # available in _MARKER. cls_dict.pop(field_name, None) # Remove __dict__ itself. cls_dict.pop("__dict__", None) # Create the class. qualname = getattr(cls, "__qualname__", None) # pyre-fixme[9]: cls has type `Type[Variable[_T]]`; used as `_T`. # pyre-fixme[19]: Expected 0 positional arguments. cls = type(cls)(cls.__name__, cls.__bases__, cls_dict) if qualname is not None: cls.__qualname__ = qualname # Set __getstate__ and __setstate__ to workaround a bug with pickling frozen # dataclasses with slots. See https://bugs.python.org/issue36424 def __getstate__(self: object) -> Mapping[str, Any]: return { field.name: getattr(self, field.name) for field in dataclasses.fields(self) if hasattr(self, field.name) } def __setstate__(self: object, state: Mapping[str, Any]) -> None: for fieldname, value in state.items(): object.__setattr__(self, fieldname, value) cls.__getstate__ = __getstate__ cls.__setstate__ = __setstate__ return cls
null
4,793
import argparse import dataclasses import importlib import inspect import os import os.path import shutil import sys import textwrap from abc import ABC, abstractmethod from typing import Any, Callable, Dict, List, Sequence, Tuple, Type import yaml from libcst import ( CSTNode, IndentedBlock, LIBCST_VERSION, Module, parse_module, PartialParserConfig, ) from libcst._nodes.deep_equals import deep_equals from libcst._parser.parso.utils import parse_version_string from libcst.codemod import ( CodemodCommand, CodemodContext, diff_code, exec_transform_with_prettyprint, gather_files, parallel_exec_transform_with_prettyprint, ) _DEFAULT_INDENT: str = " " def dump( node: CSTNode, *, indent: str = _DEFAULT_INDENT, show_defaults: bool = False, show_syntax: bool = False, show_whitespace: bool = False, ) -> str: """ Returns a string representation of the node that contains minimal differences from the default contruction of the node while also hiding whitespace and syntax fields. Setting ``show_default`` to ``True`` will add fields regardless if their value is different from the default value. Setting ``show_whitespace`` will add whitespace fields and setting ``show_syntax`` will add syntax fields while respecting the value of ``show_default``. When all keyword args are set to true, the output of this function is indentical to the __repr__ method of the node. """ return "".join( _node_repr_recursive( node, indent=indent, show_defaults=show_defaults, show_syntax=show_syntax, show_whitespace=show_whitespace, ) ) def _print_tree_impl(proc_name: str, command_args: List[str]) -> int: parser = argparse.ArgumentParser( description="Print the LibCST tree representation of a file.", prog=f"{proc_name} print", fromfile_prefix_chars="@", ) parser.add_argument( "infile", metavar="INFILE", help='File to print tree for. Use "-" for stdin', type=str, ) parser.add_argument( "--show-whitespace", action="store_true", help="Show whitespace nodes in printed tree", ) parser.add_argument( "--show-defaults", action="store_true", help="Show values that are unchanged from the default", ) parser.add_argument( "--show-syntax", action="store_true", help="Show values that exist only for syntax, like commas or semicolons", ) parser.add_argument( "--indent-string", default=_DEFAULT_INDENT, help=f"String to use for indenting levels, defaults to {_DEFAULT_INDENT!r}", ) parser.add_argument( "-p", "--python-version", metavar="VERSION", help=( "Override the version string used for parsing Python source files. Defaults " + "to the version of python used to run this tool." ), type=str, default=None, ) args = parser.parse_args(command_args) infile = args.infile # Grab input file if infile == "-": code = sys.stdin.read() else: with open(infile, "rb") as fp: code = fp.read() tree = parse_module( code, config=( PartialParserConfig(python_version=args.python_version) if args.python_version is not None else PartialParserConfig() ), ) print( dump( tree, indent=args.indent_string, show_defaults=args.show_defaults, show_syntax=args.show_syntax, show_whitespace=args.show_whitespace, ) ) return 0
null
4,794
import argparse import dataclasses import importlib import inspect import os import os.path import shutil import sys import textwrap from abc import ABC, abstractmethod from typing import Any, Callable, Dict, List, Sequence, Tuple, Type import yaml from libcst import ( CSTNode, IndentedBlock, LIBCST_VERSION, Module, parse_module, PartialParserConfig, ) from libcst._nodes.deep_equals import deep_equals from libcst._parser.parso.utils import parse_version_string from libcst.codemod import ( CodemodCommand, CodemodContext, diff_code, exec_transform_with_prettyprint, gather_files, parallel_exec_transform_with_prettyprint, ) def _find_and_load_config(proc_name: str) -> Dict[str, Any]: # Initialize with some sane defaults. config = _default_config() # Walk up the filesystem looking for a config file. current_dir = os.path.abspath(os.getcwd()) previous_dir = None found_config = False while current_dir != previous_dir: # See if the config file exists config_file = os.path.join(current_dir, CONFIG_FILE_NAME) if os.path.isfile(config_file): # Load it, override defaults with what is in the config. with open(config_file, "r") as fp: possible_config = yaml.safe_load(fp.read()) # Lets be careful with all user input so we don't crash. if isinstance(possible_config, dict): # Grab the generated code marker. for str_setting in ["generated_code_marker"]: if str_setting in possible_config and isinstance( possible_config[str_setting], str ): config[str_setting] = possible_config[str_setting] # Grab the formatter, blacklisted patterns and module directories. for list_setting in ["formatter", "blacklist_patterns", "modules"]: if ( list_setting in possible_config and isinstance(possible_config[list_setting], list) and all( isinstance(s, str) for s in possible_config[list_setting] ) ): config[list_setting] = possible_config[list_setting] # Grab the repo root config. for path_setting in ["repo_root"]: if path_setting in possible_config and isinstance( possible_config[path_setting], str ): config[path_setting] = os.path.abspath( os.path.join(current_dir, possible_config[path_setting]), ) # We successfully located a file, stop traversing. found_config = True break # Try the parent directory. previous_dir = current_dir current_dir = os.path.abspath(os.path.join(current_dir, os.pardir)) requires_config = bool(os.environ.get("LIBCST_TOOL_REQUIRE_CONFIG", "")) if requires_config and not found_config: raise Exception( f"Did not find a {CONFIG_FILE_NAME} in current directory or any " + "parent directory! Perhaps you meant to run this command from a " + "configured subdirectory, or you need to initialize a new project " + f'using "{proc_name} initialize"?' ) # Make sure that the formatter is findable. if config["formatter"]: exe = shutil.which(config["formatter"][0]) or config["formatter"][0] config["formatter"] = [os.path.abspath(exe), *config["formatter"][1:]] return config 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 _codemod_impl(proc_name: str, command_args: List[str]) -> int: # noqa: C901 # Grab the configuration for running this, if it exsts. config = _find_and_load_config(proc_name) # First, try to grab the command with a first pass. We aren't going to react # to user input here, so refuse to add help. Help will be parsed in the # full parser below once we know the command and have added its arguments. parser = argparse.ArgumentParser(add_help=False, fromfile_prefix_chars="@") parser.add_argument("command", metavar="COMMAND", type=str, nargs="?", default=None) ext_action = parser.add_argument( "-x", "--external", action="store_true", default=False, help="Interpret `command` as just a module/class specifier", ) args, _ = parser.parse_known_args(command_args) # Now, try to load the class and get its arguments for help purposes. if args.command is not None: command_module_name, _, command_class_name = args.command.rpartition(".") if not (command_module_name and command_class_name): print(f"{args.command} is not a valid codemod command", file=sys.stderr) return 1 if args.external: # There's no error handling here on purpose; if the user opted in for `-x`, # they'll probably want to see the exact import error too. command_class = getattr( importlib.import_module(command_module_name), command_class_name, ) else: command_class = None for module in config["modules"]: try: command_class = getattr( importlib.import_module(f"{module}.{command_module_name}"), command_class_name, ) break # Only swallow known import errors, show the rest of the exceptions # to the user who is trying to run the codemod. except AttributeError: continue except ModuleNotFoundError: continue if command_class is None: print( f"Could not find {command_module_name} in any configured modules", file=sys.stderr, ) return 1 else: # Dummy, specifically to allow for running --help with no arguments. command_class = CodemodCommand # Now, construct the full parser, parse the args and run the class. parser = argparse.ArgumentParser( description=( "Execute a codemod against a series of files." if command_class is CodemodCommand else command_class.DESCRIPTION ), prog=f"{proc_name} codemod", fromfile_prefix_chars="@", ) parser._add_action(ext_action) parser.add_argument( "command", metavar="COMMAND", type=str, help=( "The name of the file (minus the path and extension) and class joined with " + "a '.' that defines your command (e.g. strip_strings_from_types.StripStringsCommand)" ), ) parser.add_argument( "path", metavar="PATH", nargs="+", help=( "Path to codemod. Can be a directory, file, or multiple of either. To " + 'instead read from stdin and write to stdout, use "-"' ), ) parser.add_argument( "-j", "--jobs", metavar="JOBS", help="Number of jobs to use when processing files. Defaults to number of cores", type=int, default=None, ) parser.add_argument( "-p", "--python-version", metavar="VERSION", help=( "Override the version string used for parsing Python source files. Defaults " + "to the version of python used to run this tool." ), type=str, default=None, ) parser.add_argument( "-u", "--unified-diff", metavar="CONTEXT", help="Output unified diff instead of contents. Implies outputting to stdout", type=int, nargs="?", default=None, const=5, ) parser.add_argument( "--include-generated", action="store_true", help="Codemod generated files." ) parser.add_argument( "--include-stubs", action="store_true", help="Codemod typing stub files." ) parser.add_argument( "--no-format", action="store_true", help="Don't format resulting codemod with configured formatter.", ) parser.add_argument( "--show-successes", action="store_true", help="Print files successfully codemodded with no warnings.", ) parser.add_argument( "--hide-generated-warnings", action="store_true", help="Do not print files that are skipped for being autogenerated.", ) parser.add_argument( "--hide-blacklisted-warnings", action="store_true", help="Do not print files that are skipped for being blacklisted.", ) parser.add_argument( "--hide-progress", action="store_true", help="Do not print progress indicator. Useful if calling from a script.", ) command_class.add_args(parser) args = parser.parse_args(command_args) codemod_args = { k: v for k, v in vars(args).items() if k not in { "command", "external", "hide_blacklisted_warnings", "hide_generated_warnings", "hide_progress", "include_generated", "include_stubs", "jobs", "no_format", "path", "python_version", "show_successes", "unified_diff", } } command_instance = command_class(CodemodContext(), **codemod_args) # Sepcify target version for black formatter if os.path.basename(config["formatter"][0]) in ("black", "black.exe"): parsed_version = parse_version_string(args.python_version) config["formatter"] = [ config["formatter"][0], "--target-version", f"py{parsed_version.major}{parsed_version.minor}", ] + config["formatter"][1:] # Special case for allowing stdin/stdout. Note that this does not allow for # full-repo metadata since there is no path. if any(p == "-" for p in args.path): if len(args.path) > 1: raise Exception("Cannot specify multiple paths when reading from stdin!") print("Codemodding from stdin", file=sys.stderr) oldcode = sys.stdin.read() newcode = exec_transform_with_prettyprint( command_instance, oldcode, include_generated=args.include_generated, generated_code_marker=config["generated_code_marker"], format_code=not args.no_format, formatter_args=config["formatter"], python_version=args.python_version, ) if not newcode: print("Failed to codemod from stdin", file=sys.stderr) return 1 # Now, either print or diff the code if args.unified_diff: print(diff_code(oldcode, newcode, args.unified_diff, filename="stdin")) else: print(newcode) return 0 # Let's run it! files = gather_files(args.path, include_stubs=args.include_stubs) try: result = parallel_exec_transform_with_prettyprint( command_instance, files, jobs=args.jobs, unified_diff=args.unified_diff, include_generated=args.include_generated, generated_code_marker=config["generated_code_marker"], format_code=not args.no_format, formatter_args=config["formatter"], show_successes=args.show_successes, hide_generated=args.hide_generated_warnings, hide_blacklisted=args.hide_blacklisted_warnings, hide_progress=args.hide_progress, blacklist_patterns=config["blacklist_patterns"], python_version=args.python_version, repo_root=config["repo_root"], ) except KeyboardInterrupt: print("Interrupted!", file=sys.stderr) return 2 # Print a fancy summary at the end. print( f"Finished codemodding {result.successes + result.skips + result.failures} files!", file=sys.stderr, ) print(f" - Transformed {result.successes} files successfully.", file=sys.stderr) print(f" - Skipped {result.skips} files.", file=sys.stderr) print(f" - Failed to codemod {result.failures} files.", file=sys.stderr) print(f" - {result.warnings} warnings were generated.", file=sys.stderr) return 1 if result.failures > 0 else 0
null
4,795
import argparse import dataclasses import importlib import inspect import os import os.path import shutil import sys import textwrap from abc import ABC, abstractmethod from typing import Any, Callable, Dict, List, Sequence, Tuple, Type import yaml from libcst import ( CSTNode, IndentedBlock, LIBCST_VERSION, Module, parse_module, PartialParserConfig, ) from libcst._nodes.deep_equals import deep_equals from libcst._parser.parso.utils import parse_version_string from libcst.codemod import ( CodemodCommand, CodemodContext, diff_code, exec_transform_with_prettyprint, gather_files, parallel_exec_transform_with_prettyprint, ) def _default_config() -> Dict[str, Any]: CONFIG_FILE_NAME = ".libcst.codemod.yaml" class _SerializerBase(ABC): def __init__(self, comment: str) -> None: def serialize(self, key: str, value: object) -> str: def _serialize_impl(self, key: str, value: object) -> str: class _StrSerializer(_SerializerBase): def _serialize_impl(self, key: str, value: object) -> str: class _ListSerializer(_SerializerBase): def __init__(self, comment: str, *, newlines: bool = False) -> None: def _serialize_impl(self, key: str, value: object) -> str: def _initialize_impl(proc_name: str, command_args: List[str]) -> int: # Now, construct the full parser, parse the args and run the class. parser = argparse.ArgumentParser( description="Initialize a directory by writing a default LibCST config to it.", prog=f"{proc_name} initialize", fromfile_prefix_chars="@", ) parser.add_argument( "path", metavar="PATH", type=str, help="Path to initialize with a default LibCST codemod configuration", ) args = parser.parse_args(command_args) # Get default configuration file, write it to the YAML file we # recognize as our config. default_config = _default_config() # We serialize for ourselves here, since PyYAML doesn't allow # us to control comments in the default file. serializers: Dict[str, _SerializerBase] = { "generated_code_marker": _StrSerializer( "String that LibCST should look for in code which indicates " + "that the module is generated code." ), "formatter": _ListSerializer( "Command line and arguments for invoking a code formatter. " + "Anything specified here must be capable of taking code via " + "stdin and returning formatted code via stdout." ), "blacklist_patterns": _ListSerializer( "List of regex patterns which LibCST will evaluate against " + "filenames to determine if the module should be touched." ), "modules": _ListSerializer( "List of modules that contain codemods inside of them.", newlines=True ), "repo_root": _StrSerializer( "Absolute or relative path of the repository root, used for " + "providing full-repo metadata. Relative paths should be " + "specified with this file location as the base." ), } config_str = "".join( serializers[key].serialize(key, val) for key, val in default_config.items() ) # For safety, verify that it parses to the identical file. actual_config = yaml.safe_load(config_str) if actual_config != default_config: raise Exception("Logic error, serialization is invalid!") config_file = os.path.abspath(os.path.join(args.path, CONFIG_FILE_NAME)) with open(config_file, "w") as fp: fp.write(config_str) print(f"Successfully wrote default config file to {config_file}") return 0
null
4,796
import argparse import dataclasses import importlib import inspect import os import os.path import shutil import sys import textwrap from abc import ABC, abstractmethod from typing import Any, Callable, Dict, List, Sequence, Tuple, Type import yaml from libcst import ( CSTNode, IndentedBlock, LIBCST_VERSION, Module, parse_module, PartialParserConfig, ) from libcst._nodes.deep_equals import deep_equals from libcst._parser.parso.utils import parse_version_string from libcst.codemod import ( CodemodCommand, CodemodContext, diff_code, exec_transform_with_prettyprint, gather_files, parallel_exec_transform_with_prettyprint, ) def _find_and_load_config(proc_name: str) -> Dict[str, Any]: # Initialize with some sane defaults. config = _default_config() # Walk up the filesystem looking for a config file. current_dir = os.path.abspath(os.getcwd()) previous_dir = None found_config = False while current_dir != previous_dir: # See if the config file exists config_file = os.path.join(current_dir, CONFIG_FILE_NAME) if os.path.isfile(config_file): # Load it, override defaults with what is in the config. with open(config_file, "r") as fp: possible_config = yaml.safe_load(fp.read()) # Lets be careful with all user input so we don't crash. if isinstance(possible_config, dict): # Grab the generated code marker. for str_setting in ["generated_code_marker"]: if str_setting in possible_config and isinstance( possible_config[str_setting], str ): config[str_setting] = possible_config[str_setting] # Grab the formatter, blacklisted patterns and module directories. for list_setting in ["formatter", "blacklist_patterns", "modules"]: if ( list_setting in possible_config and isinstance(possible_config[list_setting], list) and all( isinstance(s, str) for s in possible_config[list_setting] ) ): config[list_setting] = possible_config[list_setting] # Grab the repo root config. for path_setting in ["repo_root"]: if path_setting in possible_config and isinstance( possible_config[path_setting], str ): config[path_setting] = os.path.abspath( os.path.join(current_dir, possible_config[path_setting]), ) # We successfully located a file, stop traversing. found_config = True break # Try the parent directory. previous_dir = current_dir current_dir = os.path.abspath(os.path.join(current_dir, os.pardir)) requires_config = bool(os.environ.get("LIBCST_TOOL_REQUIRE_CONFIG", "")) if requires_config and not found_config: raise Exception( f"Did not find a {CONFIG_FILE_NAME} in current directory or any " + "parent directory! Perhaps you meant to run this command from a " + "configured subdirectory, or you need to initialize a new project " + f'using "{proc_name} initialize"?' ) # Make sure that the formatter is findable. if config["formatter"]: exe = shutil.which(config["formatter"][0]) or config["formatter"][0] config["formatter"] = [os.path.abspath(exe), *config["formatter"][1:]] return config def _recursive_find(base_dir: str, base_module: str) -> List[Tuple[str, object]]: """ Given a base directory and a base module, recursively walk the directory looking for importable python modules, returning them and their relative module name based off of the base_module. """ modules: List[Tuple[str, object]] = [] for path in os.listdir(base_dir): full_path = os.path.join(base_dir, path) if os.path.isdir(full_path): # Recursively add files in subdirectories. additions = _recursive_find(full_path, f"{base_module}.{path}") for module_name, module_object in additions: modules.append((f"{path}.{module_name}", module_object)) continue if not os.path.isfile(full_path) or not path.endswith(".py"): continue try: module_name = path[:-3] potential_codemod = importlib.import_module(f"{base_module}.{module_name}") modules.append((module_name, potential_codemod)) except Exception: # Unlike running a codemod, listing shouldn't crash with exceptions. continue return modules def _list_impl(proc_name: str, command_args: List[str]) -> int: # noqa: C901 # Grab the configuration so we can determine which modules to list from config = _find_and_load_config(proc_name) parser = argparse.ArgumentParser( description="List all codemods available to run.", prog=f"{proc_name} list", fromfile_prefix_chars="@", ) _ = parser.parse_args(command_args) # Now, import each of the modules to determine their paths. codemods: Dict[Type[CodemodCommand], str] = {} for module in config["modules"]: try: imported_module = importlib.import_module(module) except Exception: # Unlike running a codemod, listing shouldn't crash with exceptions. imported_module = None if not imported_module: print( f"Could not import {module}, cannot list codemods inside it", file=sys.stderr, ) continue # Grab the path, try to import all of the files inside of it. # pyre-fixme[6]: For 1st argument expected `PathLike[Variable[AnyStr <: # [str, bytes]]]` but got `Optional[str]`. path = os.path.dirname(os.path.abspath(imported_module.__file__)) for name, imported_module in _recursive_find(path, module): for objname in dir(imported_module): try: obj = getattr(imported_module, objname) if not issubclass(obj, CodemodCommand): continue if inspect.isabstract(obj): continue # isabstract is broken for direct subclasses of ABC which # don't themselves define any abstract methods, so lets # check for that here. if any(cls[0] is ABC for cls in inspect.getclasstree([obj])): continue # Deduplicate any codemods that were referenced in other # codemods. Always take the shortest name. fullname = f"{name}.{obj.__name__}" if obj in codemods: if len(fullname) < len(codemods[obj]): codemods[obj] = fullname else: codemods[obj] = fullname except TypeError: continue printable_codemods: List[str] = [ f"{name} - {obj.DESCRIPTION}" for obj, name in codemods.items() ] print("\n".join(sorted(printable_codemods))) return 0
null
4,797
from dataclasses import dataclass, field from typing import Generic, Iterable, List, Sequence, TypeVar, Union from libcst._exceptions import ( EOFSentinel, get_expected_str, ParserSyntaxError, PartialParserSyntaxError, ) from libcst._parser.parso.pgen2.generator import DFAState, Grammar, ReservedString from libcst._parser.parso.python.token import TokenType from libcst._parser.types.token import Token _TokenTypeT = TypeVar("_TokenTypeT", bound=TokenType) class ReservedString: """ Most grammars will have certain keywords and operators that are mentioned in the grammar as strings (e.g. "if") and not token types (e.g. NUMBER). This class basically is the former. """ def __init__(self, value: str) -> None: self.value = value def __repr__(self) -> str: return "%s(%s)" % (self.__class__.__name__, self.value) def _token_to_transition( grammar: "Grammar[_TokenTypeT]", type_: _TokenTypeT, value: str ) -> Union[ReservedString, _TokenTypeT]: # Map from token to label if type_.contains_syntax: # Check for reserved words (keywords) try: return grammar.reserved_syntax_strings[value] except KeyError: pass return type_
null
4,798
import re from functools import lru_cache from typing import FrozenSet, Iterator, Mapping, Optional, Tuple, Union from libcst._parser.conversions.expression import ( convert_arg_assign_comp_for, convert_arglist, convert_argument, convert_atom, convert_atom_basic, convert_atom_curlybraces, convert_atom_ellipses, convert_atom_expr, convert_atom_expr_await, convert_atom_expr_trailer, convert_atom_parens, convert_atom_squarebrackets, convert_atom_string, convert_binop, convert_boolop, convert_comp_for, convert_comp_if, convert_comp_op, convert_comparison, convert_dictorsetmaker, convert_expression_input, convert_factor, convert_fstring, convert_fstring_content, convert_fstring_conversion, convert_fstring_equality, convert_fstring_expr, convert_fstring_format_spec, convert_lambda, convert_namedexpr_test, convert_not_test, convert_power, convert_sliceop, convert_star_arg, convert_star_expr, convert_subscript, convert_subscriptlist, convert_sync_comp_for, convert_test, convert_test_nocond, convert_test_or_expr_list, convert_testlist_comp_list, convert_testlist_comp_tuple, convert_trailer, convert_trailer_arglist, convert_trailer_attribute, convert_trailer_subscriptlist, convert_yield_arg, convert_yield_expr, ) from libcst._parser.conversions.module import convert_file_input from libcst._parser.conversions.params import ( convert_argslist, convert_fpdef, convert_fpdef_assign, convert_fpdef_slash, convert_fpdef_star, convert_fpdef_starstar, ) from libcst._parser.conversions.statement import ( convert_annassign, convert_assert_stmt, convert_assign, convert_asyncable_funcdef, convert_asyncable_stmt, convert_augassign, convert_break_stmt, convert_classdef, convert_compound_stmt, convert_continue_stmt, convert_decorated, convert_decorator, convert_decorators, convert_del_stmt, convert_dotted_as_name, convert_dotted_as_names, convert_dotted_name, convert_except_clause, convert_expr_stmt, convert_for_stmt, convert_funcdef, convert_funcdef_annotation, convert_global_stmt, convert_if_stmt, convert_if_stmt_elif, convert_if_stmt_else, convert_import_as_name, convert_import_as_names, convert_import_from, convert_import_name, convert_import_relative, convert_import_stmt, convert_indented_suite, convert_nonlocal_stmt, convert_parameters, convert_pass_stmt, convert_raise_stmt, convert_return_stmt, convert_simple_stmt_line, convert_simple_stmt_partial, convert_simple_stmt_suite, convert_small_stmt, convert_stmt, convert_stmt_input, convert_suite, convert_try_stmt, convert_while_stmt, convert_with_item, convert_with_stmt, ) from libcst._parser.conversions.terminals import ( convert_ASYNC, convert_AWAIT, convert_DEDENT, convert_ENDMARKER, convert_FSTRING_END, convert_FSTRING_START, convert_FSTRING_STRING, convert_INDENT, convert_NAME, convert_NEWLINE, convert_NUMBER, convert_OP, convert_STRING, ) from libcst._parser.parso.pgen2.generator import generate_grammar, Grammar from libcst._parser.parso.python.token import PythonTokenTypes, TokenType from libcst._parser.parso.utils import parse_version_string, PythonVersionInfo from libcst._parser.production_decorator import get_productions from libcst._parser.types.config import AutoConfig from libcst._parser.types.conversions import NonterminalConversion, TerminalConversion from libcst._parser.types.production import Production _TERMINAL_CONVERSIONS_SEQUENCE: Tuple[TerminalConversion, ...] = ( convert_DEDENT, convert_ENDMARKER, convert_INDENT, convert_NAME, convert_NEWLINE, convert_NUMBER, convert_OP, convert_STRING, convert_FSTRING_START, convert_FSTRING_END, convert_FSTRING_STRING, convert_ASYNC, convert_AWAIT, ) TerminalConversion = Callable[[ParserConfig, Token], Any] The provided code snippet includes necessary dependencies for implementing the `get_terminal_conversions` function. Write a Python function `def get_terminal_conversions() -> Mapping[str, TerminalConversion]` to solve the following problem: Returns a mapping from terminal type name to the conversion function that should be called by the parser. Here is the function: def get_terminal_conversions() -> Mapping[str, TerminalConversion]: """ Returns a mapping from terminal type name to the conversion function that should be called by the parser. """ return { # pyre-fixme[16]: Optional type has no attribute `group`. re.match("convert_(.*)", fn.__name__).group(1): fn for fn in _TERMINAL_CONVERSIONS_SEQUENCE }
Returns a mapping from terminal type name to the conversion function that should be called by the parser.
4,799
import re from functools import lru_cache from typing import FrozenSet, Iterator, Mapping, Optional, Tuple, Union from libcst._parser.conversions.expression import ( convert_arg_assign_comp_for, convert_arglist, convert_argument, convert_atom, convert_atom_basic, convert_atom_curlybraces, convert_atom_ellipses, convert_atom_expr, convert_atom_expr_await, convert_atom_expr_trailer, convert_atom_parens, convert_atom_squarebrackets, convert_atom_string, convert_binop, convert_boolop, convert_comp_for, convert_comp_if, convert_comp_op, convert_comparison, convert_dictorsetmaker, convert_expression_input, convert_factor, convert_fstring, convert_fstring_content, convert_fstring_conversion, convert_fstring_equality, convert_fstring_expr, convert_fstring_format_spec, convert_lambda, convert_namedexpr_test, convert_not_test, convert_power, convert_sliceop, convert_star_arg, convert_star_expr, convert_subscript, convert_subscriptlist, convert_sync_comp_for, convert_test, convert_test_nocond, convert_test_or_expr_list, convert_testlist_comp_list, convert_testlist_comp_tuple, convert_trailer, convert_trailer_arglist, convert_trailer_attribute, convert_trailer_subscriptlist, convert_yield_arg, convert_yield_expr, ) from libcst._parser.conversions.module import convert_file_input from libcst._parser.conversions.params import ( convert_argslist, convert_fpdef, convert_fpdef_assign, convert_fpdef_slash, convert_fpdef_star, convert_fpdef_starstar, ) from libcst._parser.conversions.statement import ( convert_annassign, convert_assert_stmt, convert_assign, convert_asyncable_funcdef, convert_asyncable_stmt, convert_augassign, convert_break_stmt, convert_classdef, convert_compound_stmt, convert_continue_stmt, convert_decorated, convert_decorator, convert_decorators, convert_del_stmt, convert_dotted_as_name, convert_dotted_as_names, convert_dotted_name, convert_except_clause, convert_expr_stmt, convert_for_stmt, convert_funcdef, convert_funcdef_annotation, convert_global_stmt, convert_if_stmt, convert_if_stmt_elif, convert_if_stmt_else, convert_import_as_name, convert_import_as_names, convert_import_from, convert_import_name, convert_import_relative, convert_import_stmt, convert_indented_suite, convert_nonlocal_stmt, convert_parameters, convert_pass_stmt, convert_raise_stmt, convert_return_stmt, convert_simple_stmt_line, convert_simple_stmt_partial, convert_simple_stmt_suite, convert_small_stmt, convert_stmt, convert_stmt_input, convert_suite, convert_try_stmt, convert_while_stmt, convert_with_item, convert_with_stmt, ) from libcst._parser.conversions.terminals import ( convert_ASYNC, convert_AWAIT, convert_DEDENT, convert_ENDMARKER, convert_FSTRING_END, convert_FSTRING_START, convert_FSTRING_STRING, convert_INDENT, convert_NAME, convert_NEWLINE, convert_NUMBER, convert_OP, convert_STRING, ) from libcst._parser.parso.pgen2.generator import generate_grammar, Grammar from libcst._parser.parso.python.token import PythonTokenTypes, TokenType from libcst._parser.parso.utils import parse_version_string, PythonVersionInfo from libcst._parser.production_decorator import get_productions from libcst._parser.types.config import AutoConfig from libcst._parser.types.conversions import NonterminalConversion, TerminalConversion from libcst._parser.types.production import Production _NONTERMINAL_CONVERSIONS_SEQUENCE: Tuple[NonterminalConversion, ...] = ( convert_file_input, convert_stmt_input, # roughly equivalent to single_input convert_expression_input, # roughly equivalent to eval_input convert_stmt, convert_simple_stmt_partial, convert_simple_stmt_line, convert_simple_stmt_suite, convert_small_stmt, convert_expr_stmt, convert_annassign, convert_augassign, convert_assign, convert_pass_stmt, convert_continue_stmt, convert_break_stmt, convert_del_stmt, convert_import_stmt, convert_import_name, convert_import_relative, convert_import_from, convert_import_as_name, convert_dotted_as_name, convert_import_as_names, convert_dotted_as_names, convert_dotted_name, convert_return_stmt, convert_raise_stmt, convert_global_stmt, convert_nonlocal_stmt, convert_assert_stmt, convert_compound_stmt, convert_if_stmt, convert_if_stmt_elif, convert_if_stmt_else, convert_while_stmt, convert_for_stmt, convert_try_stmt, convert_except_clause, convert_with_stmt, convert_with_item, convert_asyncable_funcdef, convert_funcdef, convert_classdef, convert_decorator, convert_decorators, convert_decorated, convert_asyncable_stmt, convert_parameters, convert_argslist, convert_fpdef_slash, convert_fpdef_star, convert_fpdef_starstar, convert_fpdef_assign, convert_fpdef, convert_funcdef_annotation, convert_suite, convert_indented_suite, convert_namedexpr_test, convert_test, convert_test_nocond, convert_lambda, convert_boolop, convert_not_test, convert_comparison, convert_comp_op, convert_star_expr, convert_binop, convert_factor, convert_power, convert_atom_expr, convert_atom_expr_await, convert_atom_expr_trailer, convert_trailer, convert_trailer_attribute, convert_trailer_subscriptlist, convert_subscriptlist, convert_subscript, convert_sliceop, convert_trailer_arglist, convert_atom, convert_atom_basic, convert_atom_parens, convert_atom_squarebrackets, convert_atom_curlybraces, convert_atom_string, convert_fstring, convert_fstring_content, convert_fstring_conversion, convert_fstring_equality, convert_fstring_expr, convert_fstring_format_spec, convert_atom_ellipses, convert_testlist_comp_tuple, convert_testlist_comp_list, convert_test_or_expr_list, convert_dictorsetmaker, convert_arglist, convert_argument, convert_arg_assign_comp_for, convert_star_arg, convert_sync_comp_for, convert_comp_for, convert_comp_if, convert_yield_expr, convert_yield_arg, ) def _should_include( requested_version: Optional[str], actual_version: PythonVersionInfo ) -> bool: if requested_version is None: return True for version in requested_version.split(","): comparison, parsed_version = _get_version_comparison(version.strip()) if not _compare_versions(parsed_version, actual_version, comparison): return False return True def _should_include_future( future: Optional[str], future_imports: FrozenSet[str], ) -> bool: if future is None: return True if future[:1] == "!": return future[1:] not in future_imports return future in future_imports 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 get_productions(fn: NonterminalConversion) -> Sequence[Production]: # pyre-ignore Pyre doesn't know about this magic field we added return fn.productions NonterminalConversion = Callable[[ParserConfig, Sequence[Any]], Any] The provided code snippet includes necessary dependencies for implementing the `get_nonterminal_conversions` function. Write a Python function `def get_nonterminal_conversions( version: PythonVersionInfo, future_imports: FrozenSet[str], ) -> Mapping[str, NonterminalConversion]` to solve the following problem: Returns a mapping from nonterminal production name to the conversion function that should be called by the parser. Here is the function: def get_nonterminal_conversions( version: PythonVersionInfo, future_imports: FrozenSet[str], ) -> Mapping[str, NonterminalConversion]: """ Returns a mapping from nonterminal production name to the conversion function that should be called by the parser. """ conversions = {} for fn in _NONTERMINAL_CONVERSIONS_SEQUENCE: for fn_production in get_productions(fn): if not _should_include(fn_production.version, version): continue if not _should_include_future(fn_production.future, future_imports): continue if fn_production.name in conversions: raise Exception( f"Found duplicate '{fn_production.name}' production in grammar" ) conversions[fn_production.name] = fn return conversions
Returns a mapping from nonterminal production name to the conversion function that should be called by the parser.
4,800
import re import sys from ast import literal_eval from dataclasses import dataclass from typing import Optional, Sequence, Tuple, Union The provided code snippet includes necessary dependencies for implementing the `python_bytes_to_unicode` function. Write a Python function `def python_bytes_to_unicode( source: Union[str, bytes], encoding: str = "utf-8", errors: str = "strict" ) -> str` to solve the following problem: Checks for unicode BOMs and PEP 263 encoding declarations. Then returns a unicode object like in :py:meth:`bytes.decode`. :param encoding: See :py:meth:`bytes.decode` documentation. :param errors: See :py:meth:`bytes.decode` documentation. ``errors`` can be ``'strict'``, ``'replace'`` or ``'ignore'``. Here is the function: def python_bytes_to_unicode( source: Union[str, bytes], encoding: str = "utf-8", errors: str = "strict" ) -> str: """ Checks for unicode BOMs and PEP 263 encoding declarations. Then returns a unicode object like in :py:meth:`bytes.decode`. :param encoding: See :py:meth:`bytes.decode` documentation. :param errors: See :py:meth:`bytes.decode` documentation. ``errors`` can be ``'strict'``, ``'replace'`` or ``'ignore'``. """ def detect_encoding() -> Union[str, bytes]: """ For the implementation of encoding definitions in Python, look at: - http://www.python.org/dev/peps/pep-0263/ - http://docs.python.org/2/reference/lexical_analysis.html#encoding-declarations """ byte_mark = literal_eval(r"b'\xef\xbb\xbf'") if source.startswith(byte_mark): # UTF-8 byte-order mark return b"utf-8" # pyre-ignore Pyre can't see that Union[str, bytes] conforms to AnyStr. first_two_match = re.match(rb"(?:[^\n]*\n){0,2}", source) if first_two_match is None: return encoding first_two_lines = first_two_match.group(0) possible_encoding = re.search(rb"coding[=:]\s*([-\w.]+)", first_two_lines) if possible_encoding: return possible_encoding.group(1) else: # the default if nothing else has been set -> PEP 263 return encoding if isinstance(source, str): # only cast bytes return source actual_encoding = detect_encoding() if not isinstance(actual_encoding, str): actual_encoding = actual_encoding.decode("utf-8", "replace") # Cast to str return source.decode(actual_encoding, errors)
Checks for unicode BOMs and PEP 263 encoding declarations. Then returns a unicode object like in :py:meth:`bytes.decode`. :param encoding: See :py:meth:`bytes.decode` documentation. :param errors: See :py:meth:`bytes.decode` documentation. ``errors`` can be ``'strict'``, ``'replace'`` or ``'ignore'``.
4,801
from typing import Callable, Optional, Sequence, TypeVar from libcst._parser.types.conversions import NonterminalConversion from libcst._parser.types.production import Production _NonterminalConversionT = TypeVar( "_NonterminalConversionT", bound=NonterminalConversion ) class Production: name: str children: str version: Optional[str] future: Optional[str] def __str__(self) -> str: return f"{self.name}: {self.children}" The provided code snippet includes necessary dependencies for implementing the `with_production` function. Write a Python function `def with_production( production_name: str, children: str, *, version: Optional[str] = None, future: Optional[str] = None, # pyre-fixme[34]: `Variable[_NonterminalConversionT (bound to # typing.Callable[[libcst_native.parser_config.ParserConfig, # typing.Sequence[typing.Any]], typing.Any])]` isn't present in the function's # parameters. ) -> Callable[[_NonterminalConversionT], _NonterminalConversionT]` to solve the following problem: Attaches a bit of grammar to a conversion function. The parser extracts all of these production strings, and uses it to form the language's full grammar. If you need to attach multiple productions to the same conversion function Here is the function: def with_production( production_name: str, children: str, *, version: Optional[str] = None, future: Optional[str] = None, # pyre-fixme[34]: `Variable[_NonterminalConversionT (bound to # typing.Callable[[libcst_native.parser_config.ParserConfig, # typing.Sequence[typing.Any]], typing.Any])]` isn't present in the function's # parameters. ) -> Callable[[_NonterminalConversionT], _NonterminalConversionT]: """ Attaches a bit of grammar to a conversion function. The parser extracts all of these production strings, and uses it to form the language's full grammar. If you need to attach multiple productions to the same conversion function """ def inner(fn: _NonterminalConversionT) -> _NonterminalConversionT: if not hasattr(fn, "productions"): fn.productions = [] # pyre-ignore: Pyre doesn't think that fn has a __name__ attribute fn_name = fn.__name__ if not fn_name.startswith("convert_"): raise Exception( "A function with a production must be named 'convert_X', not " + f"'{fn_name}'." ) # pyre-ignore: Pyre doesn't know about this magic field we added fn.productions.append(Production(production_name, children, version, future)) return fn return inner
Attaches a bit of grammar to a conversion function. The parser extracts all of these production strings, and uses it to form the language's full grammar. If you need to attach multiple productions to the same conversion function
4,802
from typing import List, Optional, Sequence, Tuple, Union from libcst._nodes.whitespace import ( Comment, COMMENT_RE, EmptyLine, Newline, NEWLINE_RE, ParenthesizedWhitespace, SIMPLE_WHITESPACE_RE, SimpleWhitespace, TrailingWhitespace, ) from libcst._parser.types.config import BaseWhitespaceParserConfig from libcst._parser.types.whitespace_state import WhitespaceState as State def _parse_empty_line( config: BaseWhitespaceParserConfig, state: State, *, override_absolute_indent: Optional[str] = None, ) -> Optional[EmptyLine]: class EmptyLine(CSTNode): def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "EmptyLine": def _codegen_impl(self, state: CodegenState) -> None: BaseWhitespaceParserConfig = config_mod.BaseWhitespaceParserConfig def parse_empty_lines( config: BaseWhitespaceParserConfig, state: State, *, override_absolute_indent: Optional[str] = None, ) -> Sequence[EmptyLine]: # If override_absolute_indent is true, then we need to parse all lines up # to and including the last line that is indented at our level. These all # belong to the footer and not to the next line's leading_lines. All lines # that have indent=False and come after the last line where indent=True # do not belong to this node. state_for_line = State( state.line, state.column, state.absolute_indent, state.is_parenthesized ) lines: List[Tuple[State, EmptyLine]] = [] while True: el = _parse_empty_line( config, state_for_line, override_absolute_indent=override_absolute_indent ) if el is None: break # Store the updated state with the element we parsed. Then make a new state # clone for the next element. lines.append((state_for_line, el)) state_for_line = State( state_for_line.line, state_for_line.column, state.absolute_indent, state.is_parenthesized, ) if override_absolute_indent is not None: # We need to find the last element that is indented, and then split the list # at that point. for i in range(len(lines) - 1, -1, -1): if lines[i][1].indent: lines = lines[: (i + 1)] break else: # We didn't find any lines, throw them all away lines = [] if lines: # Update the state line and column to match the last line actually parsed. final_state: State = lines[-1][0] state.line = final_state.line state.column = final_state.column return [r[1] for r in lines]
null
4,803
from typing import List, Optional, Sequence, Tuple, Union from libcst._nodes.whitespace import ( Comment, COMMENT_RE, EmptyLine, Newline, NEWLINE_RE, ParenthesizedWhitespace, SIMPLE_WHITESPACE_RE, SimpleWhitespace, TrailingWhitespace, ) from libcst._parser.types.config import BaseWhitespaceParserConfig from libcst._parser.types.whitespace_state import WhitespaceState as State def _parse_trailing_whitespace( config: BaseWhitespaceParserConfig, state: State ) -> Optional[TrailingWhitespace]: # Begin speculative parsing speculative_state = State( state.line, state.column, state.absolute_indent, state.is_parenthesized ) whitespace = parse_simple_whitespace(config, speculative_state) comment = _parse_comment(config, speculative_state) newline = _parse_newline(config, speculative_state) if newline is None: # Speculative parsing failed return None # Speculative parsing succeeded state.line = speculative_state.line state.column = speculative_state.column # don't need to copy absolute_indent/is_parenthesized because they don't change. return TrailingWhitespace(whitespace, comment, newline) class TrailingWhitespace(CSTNode): """ The whitespace at the end of a line after a statement. If a line contains only whitespace, :class:`EmptyLine` should be used instead. """ #: Any simple whitespace before any comment or newline. whitespace: SimpleWhitespace = SimpleWhitespace.field("") #: An optional comment appearing after any simple whitespace. comment: Optional[Comment] = None #: The newline character that terminates this trailing whitespace. newline: Newline = Newline.field() def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "TrailingWhitespace": return TrailingWhitespace( whitespace=visit_required(self, "whitespace", self.whitespace, visitor), comment=visit_optional(self, "comment", self.comment, visitor), newline=visit_required(self, "newline", self.newline, visitor), ) def _codegen_impl(self, state: CodegenState) -> None: self.whitespace._codegen(state) comment = self.comment if comment is not None: comment._codegen(state) self.newline._codegen(state) BaseWhitespaceParserConfig = config_mod.BaseWhitespaceParserConfig def parse_trailing_whitespace( config: BaseWhitespaceParserConfig, state: State ) -> TrailingWhitespace: trailing_whitespace = _parse_trailing_whitespace(config, state) if trailing_whitespace is None: raise Exception( "Internal Error: Failed to parse TrailingWhitespace. This should never " + "happen because a TrailingWhitespace is never optional in the grammar, " + "so this error should've been caught by parso first." ) return trailing_whitespace
null
4,804
from typing import List, Optional, Sequence, Tuple, Union from libcst._nodes.whitespace import ( Comment, COMMENT_RE, EmptyLine, Newline, NEWLINE_RE, ParenthesizedWhitespace, SIMPLE_WHITESPACE_RE, SimpleWhitespace, TrailingWhitespace, ) from libcst._parser.types.config import BaseWhitespaceParserConfig from libcst._parser.types.whitespace_state import WhitespaceState as State def parse_simple_whitespace( config: BaseWhitespaceParserConfig, state: State ) -> SimpleWhitespace: def _parse_parenthesized_whitespace( config: BaseWhitespaceParserConfig, state: State ) -> Optional[ParenthesizedWhitespace]: class SimpleWhitespace(BaseParenthesizableWhitespace, BaseValueToken): def _validate(self) -> None: def empty(self) -> bool: class ParenthesizedWhitespace(BaseParenthesizableWhitespace): def _visit_and_replace_children( self, visitor: CSTVisitorT ) -> "ParenthesizedWhitespace": def _codegen_impl(self, state: CodegenState) -> None: def empty(self) -> bool: BaseWhitespaceParserConfig = config_mod.BaseWhitespaceParserConfig def parse_parenthesizable_whitespace( config: BaseWhitespaceParserConfig, state: State ) -> Union[SimpleWhitespace, ParenthesizedWhitespace]: if state.is_parenthesized: # First, try parenthesized (don't need speculation because it either # parses or doesn't modify state). parenthesized_whitespace = _parse_parenthesized_whitespace(config, state) if parenthesized_whitespace is not None: return parenthesized_whitespace # Now, just parse and return a simple whitespace return parse_simple_whitespace(config, state)
null
4,805
from typing import Any, List, Optional, Sequence, Union from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Name, Param, Parameters, ParamSlash, ParamStar, ) from libcst._nodes.op import AssignEqual, Comma 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 ParamStarPartial from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace class PartialParserSyntaxError(Exception): """ An internal exception that represents a partially-constructed :class:`ParserSyntaxError`. It's raised by our internal parser conversion functions, which don't always know the current line and column information. This partial object only contains a message, with the expectation that the line and column information will be filled in by :class:`libcst._base_parser.BaseParser`. This should never be visible to the end-user. """ message: str def __init__(self, message: str) -> None: self.message = message 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 ParamStar(CSTNode): """ A sentinel indicator on a :class:`Parameters` list to denote that the subsequent params are keyword-only args. This syntax is described in `PEP 3102`_. .. _PEP 3102: https://www.python.org/dev/peps/pep-3102/#specification """ # Comma that comes after the star. comma: Comma = Comma.field(whitespace_after=SimpleWhitespace(" ")) def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "ParamStar": return ParamStar(comma=visit_required(self, "comma", self.comma, visitor)) def _codegen_impl(self, state: CodegenState) -> None: state.add_token("*") self.comma._codegen(state) class ParamSlash(CSTNode): """ A sentinel indicator on a :class:`Parameters` list to denote that the previous params are positional-only args. This syntax is described in `PEP 570`_. .. _PEP 570: https://www.python.org/dev/peps/pep-0570/#specification """ #: Optional comma that comes after the slash. This comma doesn't own the whitespace #: between ``/`` and ``,``. comma: Union[Comma, MaybeSentinel] = MaybeSentinel.DEFAULT #: Whitespace after the ``/`` character. This is captured here in case there is a #: comma. whitespace_after: BaseParenthesizableWhitespace = SimpleWhitespace.field("") def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "ParamSlash": return ParamSlash( comma=visit_sentinel(self, "comma", self.comma, visitor), whitespace_after=visit_required( self, "whitespace_after", self.whitespace_after, visitor ), ) def _codegen_impl(self, state: CodegenState, default_comma: bool = False) -> None: state.add_token("/") self.whitespace_after._codegen(state) comma = self.comma if comma is MaybeSentinel.DEFAULT and default_comma: state.add_token(", ") elif isinstance(comma, Comma): comma._codegen(state) class Param(CSTNode): """ A positional or keyword argument in a :class:`Parameters` list. May contain an :class:`Annotation` and, in some cases, a ``default``. """ #: The parameter name itself. name: Name #: Any optional :class:`Annotation`. These annotations are usually used as type #: hints. annotation: Optional[Annotation] = None #: The equal sign used to denote assignment if there is a default. equal: Union[AssignEqual, MaybeSentinel] = MaybeSentinel.DEFAULT #: Any optional default value, used when the argument is not supplied. default: Optional[BaseExpression] = None #: A trailing comma. If one is not provided, :class:`MaybeSentinel` will be #: replaced with a comma only if a comma is required. comma: Union[Comma, MaybeSentinel] = MaybeSentinel.DEFAULT #: Zero, one, or two asterisks appearing before name for :class:`Param`'s #: ``star_arg`` and ``star_kwarg``. star: Union[str, MaybeSentinel] = MaybeSentinel.DEFAULT #: The whitespace before ``name``. It will appear after ``star`` when a star #: exists. whitespace_after_star: BaseParenthesizableWhitespace = SimpleWhitespace.field("") #: The whitespace after this entire node. whitespace_after_param: BaseParenthesizableWhitespace = SimpleWhitespace.field("") def _validate(self) -> None: if self.default is None and isinstance(self.equal, AssignEqual): raise CSTValidationError( "Must have a default when specifying an AssignEqual." ) if isinstance(self.star, str) and self.star not in ("", "*", "**"): raise CSTValidationError("Must specify either '', '*' or '**' for star.") def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Param": return Param( star=self.star, whitespace_after_star=visit_required( self, "whitespace_after_star", self.whitespace_after_star, visitor ), name=visit_required(self, "name", self.name, visitor), annotation=visit_optional(self, "annotation", self.annotation, visitor), equal=visit_sentinel(self, "equal", self.equal, visitor), default=visit_optional(self, "default", self.default, visitor), comma=visit_sentinel(self, "comma", self.comma, visitor), whitespace_after_param=visit_required( self, "whitespace_after_param", self.whitespace_after_param, visitor ), ) def _codegen_impl( self, state: CodegenState, default_star: Optional[str] = None, default_comma: bool = False, ) -> None: with state.record_syntactic_position(self): star = self.star if isinstance(star, MaybeSentinel): if default_star is None: raise CSTCodegenError( "Must specify a concrete default_star if default used on star." ) star = default_star if isinstance(star, str): state.add_token(star) self.whitespace_after_star._codegen(state) self.name._codegen(state) annotation = self.annotation if annotation is not None: annotation._codegen(state, default_indicator=":") equal = self.equal if equal is MaybeSentinel.DEFAULT and self.default is not None: state.add_token(" = ") elif isinstance(equal, AssignEqual): equal._codegen(state) default = self.default if default is not None: default._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_param._codegen(state) class Parameters(CSTNode): """ A function or lambda parameter list. """ #: Positional parameters, with or without defaults. Positional parameters #: with defaults must all be after those without defaults. params: Sequence[Param] = () # Optional parameter that captures unspecified positional arguments or a sentinel # star that dictates parameters following are kwonly args. star_arg: Union[Param, ParamStar, MaybeSentinel] = MaybeSentinel.DEFAULT #: Keyword-only params that may or may not have defaults. kwonly_params: Sequence[Param] = () #: Optional parameter that captures unspecified kwargs. star_kwarg: Optional[Param] = None #: Positional-only parameters, with or without defaults. Positional-only #: parameters with defaults must all be after those without defaults. posonly_params: Sequence[Param] = () #: Optional sentinel that dictates parameters preceeding are positional-only #: args. posonly_ind: Union[ParamSlash, MaybeSentinel] = MaybeSentinel.DEFAULT def _validate_stars_sequence(self, vals: Sequence[Param], *, section: str) -> None: if len(vals) == 0: return for val in vals: if isinstance(val.star, str) and val.star != "": raise CSTValidationError( f"Expecting a star prefix of '' for {section} Param." ) def _validate_posonly_ind(self) -> None: if isinstance(self.posonly_ind, ParamSlash) and len(self.posonly_params) == 0: raise CSTValidationError( "Must have at least one posonly param if ParamSlash is used." ) def _validate_kwonly_star(self) -> None: if isinstance(self.star_arg, ParamStar) and len(self.kwonly_params) == 0: raise CSTValidationError( "Must have at least one kwonly param if ParamStar is used." ) def _validate_defaults(self) -> None: seen_default = False # pyre-fixme[60]: Concatenation not yet support for multiple variadic # tuples: `*self.posonly_params, *self.params`. for param in (*self.posonly_params, *self.params): if param.default: # Mark that we've moved onto defaults if not seen_default: seen_default = True else: if seen_default: # We accidentally included a non-default after a default arg! raise CSTValidationError( "Cannot have param without defaults following a param with defaults." ) star_arg = self.star_arg if isinstance(star_arg, Param) and star_arg.default is not None: raise CSTValidationError("Cannot have default for star_arg.") star_kwarg = self.star_kwarg if star_kwarg is not None and star_kwarg.default is not None: raise CSTValidationError("Cannot have default for star_kwarg.") def _validate_stars(self) -> None: if len(self.params) > 0: self._validate_stars_sequence(self.params, section="params") if len(self.posonly_params) > 0: self._validate_stars_sequence(self.posonly_params, section="posonly_params") star_arg = self.star_arg if ( isinstance(star_arg, Param) and isinstance(star_arg.star, str) and star_arg.star != "*" ): raise CSTValidationError( "Expecting a star prefix of '*' for star_arg Param." ) if len(self.kwonly_params) > 0: self._validate_stars_sequence(self.kwonly_params, section="kwonly_params") star_kwarg = self.star_kwarg if ( star_kwarg is not None and isinstance(star_kwarg.star, str) and star_kwarg.star != "**" ): raise CSTValidationError( "Expecting a star prefix of '**' for star_kwarg Param." ) def _validate(self) -> None: # Validate posonly_params slash placement semantics. self._validate_posonly_ind() # Validate kwonly_param star placement semantics. self._validate_kwonly_star() # Validate defaults semantics for params and star_arg/star_kwarg. self._validate_defaults() # Validate that we don't have random stars on non star_kwarg. self._validate_stars() def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Parameters": return Parameters( posonly_params=visit_sequence( self, "posonly_params", self.posonly_params, visitor ), posonly_ind=visit_sentinel(self, "posonly_ind", self.posonly_ind, visitor), params=visit_sequence(self, "params", self.params, visitor), star_arg=visit_sentinel(self, "star_arg", self.star_arg, visitor), kwonly_params=visit_sequence( self, "kwonly_params", self.kwonly_params, visitor ), star_kwarg=visit_optional(self, "star_kwarg", self.star_kwarg, visitor), ) def _safe_to_join_with_lambda(self) -> bool: """ Determine if Parameters need a space after the `lambda` keyword. Returns True iff it's safe to omit the space between `lambda` and these Parameters. See also `BaseExpression._safe_to_use_with_word_operator`. For example: `lambda*_: pass` """ if len(self.posonly_params) != 0: return False # posonly_ind can't appear if above condition is false if len(self.params) > 0 and self.params[0].star not in {"*", "**"}: return False return True def _codegen_impl(self, state: CodegenState) -> None: # noqa: C901 # Compute the star existence first so we can ask about whether # each element is the last in the list or not. star_arg = self.star_arg if isinstance(star_arg, MaybeSentinel): starincluded = len(self.kwonly_params) > 0 elif isinstance(star_arg, (Param, ParamStar)): starincluded = True else: starincluded = False # Render out the positional-only params first. They will always have trailing # commas because in order to have positional-only params, there must be a # slash afterwards. for i, param in enumerate(self.posonly_params): param._codegen(state, default_star="", default_comma=True) # Render out the positional-only indicator if necessary. more_values = ( starincluded or len(self.params) > 0 or len(self.kwonly_params) > 0 or self.star_kwarg is not None ) posonly_ind = self.posonly_ind if isinstance(posonly_ind, ParamSlash): # Its explicitly included, so render the version we have here which # might have spacing applied to its comma. posonly_ind._codegen(state, default_comma=more_values) elif len(self.posonly_params) > 0: if more_values: state.add_token("/, ") else: state.add_token("/") # Render out the params next, computing necessary trailing commas. lastparam = len(self.params) - 1 more_values = ( starincluded or len(self.kwonly_params) > 0 or self.star_kwarg is not None ) for i, param in enumerate(self.params): param._codegen( state, default_star="", default_comma=(i < lastparam or more_values) ) # Render out optional star sentinel if its explicitly included or # if we are inferring it from kwonly_params. Otherwise, render out the # optional star_arg. if isinstance(star_arg, MaybeSentinel): if starincluded: state.add_token("*, ") elif isinstance(star_arg, Param): more_values = len(self.kwonly_params) > 0 or self.star_kwarg is not None star_arg._codegen(state, default_star="*", default_comma=more_values) elif isinstance(star_arg, ParamStar): star_arg._codegen(state) # Render out the kwonly_args next, computing necessary trailing commas. lastparam = len(self.kwonly_params) - 1 more_values = self.star_kwarg is not None for i, param in enumerate(self.kwonly_params): param._codegen( state, default_star="", default_comma=(i < lastparam or more_values) ) # Finally, render out any optional star_kwarg star_kwarg = self.star_kwarg if star_kwarg is not None: star_kwarg._codegen(state, default_star="**", default_comma=False) 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 ParamStarPartial: pass parse_parenthesizable_whitespace = mod.parse_parenthesizable_whitespace def convert_argslist( # noqa: C901 config: ParserConfig, children: Sequence[Any] ) -> Any: posonly_params: List[Param] = [] posonly_ind: Union[ParamSlash, MaybeSentinel] = MaybeSentinel.DEFAULT params: List[Param] = [] seen_default: bool = False star_arg: Union[Param, ParamStar, MaybeSentinel] = MaybeSentinel.DEFAULT kwonly_params: List[Param] = [] star_kwarg: Optional[Param] = None def add_param( current_param: Optional[List[Param]], param: Union[Param, ParamStar] ) -> Optional[List[Param]]: nonlocal star_arg nonlocal star_kwarg nonlocal seen_default nonlocal posonly_params nonlocal posonly_ind nonlocal params if isinstance(param, ParamStar): # Only can add this if we don't already have a "*" or a "*param". if current_param is params: star_arg = param current_param = kwonly_params else: # Example code: # def fn(*abc, *): ... # This should be unreachable, the grammar already disallows it. raise Exception( "Cannot have multiple star ('*') markers in a single argument " + "list." ) elif isinstance(param, ParamSlash): # Only can add this if we don't already have a "/" or a "*" or a "*param". if current_param is params and len(posonly_params) == 0: posonly_ind = param posonly_params = params params = [] current_param = params else: # Example code: # def fn(foo, /, *, /, bar): ... # This should be unreachable, the grammar already disallows it. raise Exception( "Cannot have multiple slash ('/') markers in a single argument " + "list." ) elif isinstance(param.star, str) and param.star == "" and param.default is None: # Can only add this if we're in the params or kwonly_params section if current_param is params and not seen_default: params.append(param) elif current_param is kwonly_params: kwonly_params.append(param) else: # Example code: # def fn(first=None, second): ... # This code is reachable, so we should use a PartialParserSyntaxError. raise PartialParserSyntaxError( "Cannot have a non-default argument following a default argument." ) elif ( isinstance(param.star, str) and param.star == "" and param.default is not None ): # Can only add this if we're not yet at star args. if current_param is params: seen_default = True params.append(param) elif current_param is kwonly_params: kwonly_params.append(param) else: # Example code: # def fn(**kwargs, trailing=None) # This should be unreachable, the grammar already disallows it. raise Exception("Cannot have any arguments after a kwargs expansion.") elif ( isinstance(param.star, str) and param.star == "*" and param.default is None ): # Can only add this if we're in params, since we only allow one of # "*" or "*param". if current_param is params: star_arg = param current_param = kwonly_params else: # Example code: # def fn(*first, *second): ... # This should be unreachable, the grammar already disallows it. raise Exception( "Expected a keyword argument but found a starred positional " + "argument expansion." ) elif ( isinstance(param.star, str) and param.star == "**" and param.default is None ): # Can add this in all cases where we don't have a star_kwarg # yet. if current_param is not None: star_kwarg = param current_param = None else: # Example code: # def fn(**first, **second) # This should be unreachable, the grammar already disallows it. raise Exception( "Multiple starred keyword argument expansions are not allowed in a " + "single argument list" ) else: # The state machine should never end up here. raise Exception("Logic error!") return current_param # The parameter list we are adding to current: Optional[List[Param]] = params # We should have every other item in the group as a param or a comma by now, # so split them up, add commas and then put them in the appropriate group. for parameter, comma in grouper(children, 2): if comma is None: if isinstance(parameter, ParamStarPartial): # Example: # def fn(abc, *): ... # # There's also the case where we have bare * with a trailing comma. # That's handled later. # # It's not valid to construct a ParamStar object without a comma, so we # need to catch the non-comma case separately. raise PartialParserSyntaxError( "Named (keyword) arguments must follow a bare *." ) else: current = add_param(current, parameter) else: comma = Comma( whitespace_before=parse_parenthesizable_whitespace( config, comma.whitespace_before ), whitespace_after=parse_parenthesizable_whitespace( config, comma.whitespace_after ), ) if isinstance(parameter, ParamStarPartial): current = add_param(current, ParamStar(comma=comma)) else: current = add_param(current, parameter.with_changes(comma=comma)) if isinstance(star_arg, ParamStar) and len(kwonly_params) == 0: # Example: # def fn(abc, *,): ... # # This will raise a validation error, but we want to make sure to raise a syntax # error instead. # # The case where there's no trailing comma is already handled by this point, so # this conditional is only for the case where we have a trailing comma. raise PartialParserSyntaxError( "Named (keyword) arguments must follow a bare *." ) return Parameters( posonly_params=tuple(posonly_params), posonly_ind=posonly_ind, params=tuple(params), star_arg=star_arg, kwonly_params=tuple(kwonly_params), star_kwarg=star_kwarg, )
null
4,806
from typing import Any, List, Optional, Sequence, Union from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Name, Param, Parameters, ParamSlash, ParamStar, ) from libcst._nodes.op import AssignEqual, Comma 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 ParamStarPartial from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace ParserConfig = config_mod.ParserConfig class ParamStarPartial: pass parse_parenthesizable_whitespace = mod.parse_parenthesizable_whitespace def convert_fpdef_star(config: ParserConfig, children: Sequence[Any]) -> Any: if len(children) == 1: (star,) = children return ParamStarPartial() else: star, param = children return param.with_changes( star=star.string, whitespace_after_star=parse_parenthesizable_whitespace( config, star.whitespace_after ), )
null
4,807
from typing import Any, List, Optional, Sequence, Union from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Name, Param, Parameters, ParamSlash, ParamStar, ) from libcst._nodes.op import AssignEqual, Comma 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 ParamStarPartial from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace ParserConfig = config_mod.ParserConfig parse_parenthesizable_whitespace = mod.parse_parenthesizable_whitespace def convert_fpdef_starstar(config: ParserConfig, children: Sequence[Any]) -> Any: starstar, param = children return param.with_changes( star=starstar.string, whitespace_after_star=parse_parenthesizable_whitespace( config, starstar.whitespace_after ), )
null
4,808
from typing import Any, List, Optional, Sequence, Union from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Name, Param, Parameters, ParamSlash, ParamStar, ) from libcst._nodes.op import AssignEqual, Comma 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 ParamStarPartial 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_fpdef_assign(config: ParserConfig, children: Sequence[Any]) -> Any: if len(children) == 1: (child,) = children return child param, equal, default = children return param.with_changes( equal=AssignEqual( whitespace_before=parse_parenthesizable_whitespace( config, equal.whitespace_before ), whitespace_after=parse_parenthesizable_whitespace( config, equal.whitespace_after ), ), default=default.value, )
null
4,809
from typing import Any, List, Optional, Sequence, Union from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Name, Param, Parameters, ParamSlash, ParamStar, ) from libcst._nodes.op import AssignEqual, Comma 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 ParamStarPartial 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 Annotation(CSTNode): """ An annotation for a function (`PEP 3107`_) or on a variable (`PEP 526`_). Typically these are used in the context of type hints (`PEP 484`_), such as:: # a variable with a type good_ideas: List[str] = [] # a function with type annotations def concat(substrings: Sequence[str]) -> str: ... .. _PEP 3107: https://www.python.org/dev/peps/pep-3107/ .. _PEP 526: https://www.python.org/dev/peps/pep-0526/ .. _PEP 484: https://www.python.org/dev/peps/pep-0484/ """ #: The annotation's value itself. This is the part of the annotation after the #: colon or arrow. annotation: BaseExpression whitespace_before_indicator: Union[ BaseParenthesizableWhitespace, MaybeSentinel ] = MaybeSentinel.DEFAULT whitespace_after_indicator: BaseParenthesizableWhitespace = SimpleWhitespace.field( " " ) def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Annotation": return Annotation( whitespace_before_indicator=visit_sentinel( self, "whitespace_before_indicator", self.whitespace_before_indicator, visitor, ), whitespace_after_indicator=visit_required( self, "whitespace_after_indicator", self.whitespace_after_indicator, visitor, ), annotation=visit_required(self, "annotation", self.annotation, visitor), ) def _codegen_impl( self, state: CodegenState, default_indicator: Optional[str] = None ) -> None: # First, figure out the indicator which tells us default whitespace. if default_indicator is None: raise CSTCodegenError( "Must specify a concrete default_indicator if default used on indicator." ) # Now, output the whitespace whitespace_before_indicator = self.whitespace_before_indicator if isinstance(whitespace_before_indicator, BaseParenthesizableWhitespace): whitespace_before_indicator._codegen(state) elif isinstance(whitespace_before_indicator, MaybeSentinel): if default_indicator == "->": state.add_token(" ") else: raise Exception("Logic error!") # Now, output the indicator and the rest of the annotation state.add_token(default_indicator) self.whitespace_after_indicator._codegen(state) with state.record_syntactic_position(self): self.annotation._codegen(state) class Param(CSTNode): """ A positional or keyword argument in a :class:`Parameters` list. May contain an :class:`Annotation` and, in some cases, a ``default``. """ #: The parameter name itself. name: Name #: Any optional :class:`Annotation`. These annotations are usually used as type #: hints. annotation: Optional[Annotation] = None #: The equal sign used to denote assignment if there is a default. equal: Union[AssignEqual, MaybeSentinel] = MaybeSentinel.DEFAULT #: Any optional default value, used when the argument is not supplied. default: Optional[BaseExpression] = None #: A trailing comma. If one is not provided, :class:`MaybeSentinel` will be #: replaced with a comma only if a comma is required. comma: Union[Comma, MaybeSentinel] = MaybeSentinel.DEFAULT #: Zero, one, or two asterisks appearing before name for :class:`Param`'s #: ``star_arg`` and ``star_kwarg``. star: Union[str, MaybeSentinel] = MaybeSentinel.DEFAULT #: The whitespace before ``name``. It will appear after ``star`` when a star #: exists. whitespace_after_star: BaseParenthesizableWhitespace = SimpleWhitespace.field("") #: The whitespace after this entire node. whitespace_after_param: BaseParenthesizableWhitespace = SimpleWhitespace.field("") def _validate(self) -> None: if self.default is None and isinstance(self.equal, AssignEqual): raise CSTValidationError( "Must have a default when specifying an AssignEqual." ) if isinstance(self.star, str) and self.star not in ("", "*", "**"): raise CSTValidationError("Must specify either '', '*' or '**' for star.") def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Param": return Param( star=self.star, whitespace_after_star=visit_required( self, "whitespace_after_star", self.whitespace_after_star, visitor ), name=visit_required(self, "name", self.name, visitor), annotation=visit_optional(self, "annotation", self.annotation, visitor), equal=visit_sentinel(self, "equal", self.equal, visitor), default=visit_optional(self, "default", self.default, visitor), comma=visit_sentinel(self, "comma", self.comma, visitor), whitespace_after_param=visit_required( self, "whitespace_after_param", self.whitespace_after_param, visitor ), ) def _codegen_impl( self, state: CodegenState, default_star: Optional[str] = None, default_comma: bool = False, ) -> None: with state.record_syntactic_position(self): star = self.star if isinstance(star, MaybeSentinel): if default_star is None: raise CSTCodegenError( "Must specify a concrete default_star if default used on star." ) star = default_star if isinstance(star, str): state.add_token(star) self.whitespace_after_star._codegen(state) self.name._codegen(state) annotation = self.annotation if annotation is not None: annotation._codegen(state, default_indicator=":") equal = self.equal if equal is MaybeSentinel.DEFAULT and self.default is not None: state.add_token(" = ") elif isinstance(equal, AssignEqual): equal._codegen(state) default = self.default if default is not None: default._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_param._codegen(state) ParserConfig = config_mod.ParserConfig parse_parenthesizable_whitespace = mod.parse_parenthesizable_whitespace def convert_fpdef(config: ParserConfig, children: Sequence[Any]) -> Any: if len(children) == 1: # This is just a parameter (child,) = children namenode = Name(child.string) annotation = None else: # This is a parameter with a type hint name, colon, typehint = children namenode = Name(name.string) annotation = Annotation( whitespace_before_indicator=parse_parenthesizable_whitespace( config, colon.whitespace_before ), whitespace_after_indicator=parse_parenthesizable_whitespace( config, colon.whitespace_after ), annotation=typehint.value, ) return Param(star="", name=namenode, annotation=annotation, default=None)
null
4,810
from typing import Any, List, Optional, Sequence, Union from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Name, Param, Parameters, ParamSlash, ParamStar, ) from libcst._nodes.op import AssignEqual, Comma 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 ParamStarPartial from libcst._parser.whitespace_parser import parse_parenthesizable_whitespace class ParamSlash(CSTNode): """ A sentinel indicator on a :class:`Parameters` list to denote that the previous params are positional-only args. This syntax is described in `PEP 570`_. .. _PEP 570: https://www.python.org/dev/peps/pep-0570/#specification """ #: Optional comma that comes after the slash. This comma doesn't own the whitespace #: between ``/`` and ``,``. comma: Union[Comma, MaybeSentinel] = MaybeSentinel.DEFAULT #: Whitespace after the ``/`` character. This is captured here in case there is a #: comma. whitespace_after: BaseParenthesizableWhitespace = SimpleWhitespace.field("") def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "ParamSlash": return ParamSlash( comma=visit_sentinel(self, "comma", self.comma, visitor), whitespace_after=visit_required( self, "whitespace_after", self.whitespace_after, visitor ), ) def _codegen_impl(self, state: CodegenState, default_comma: bool = False) -> None: state.add_token("/") self.whitespace_after._codegen(state) comma = self.comma if comma is MaybeSentinel.DEFAULT and default_comma: state.add_token(", ") elif isinstance(comma, Comma): comma._codegen(state) ParserConfig = config_mod.ParserConfig def convert_fpdef_slash(config: ParserConfig, children: Sequence[Any]) -> Any: return ParamSlash()
null
4,811
from typing import Any from libcst._nodes.expression import SimpleString from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import WithLeadingWhitespace from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_trailing_whitespace, ) ParserConfig = config_mod.ParserConfig def convert_NAME(config: ParserConfig, token: Token) -> Any: return token
null
4,812
from typing import Any from libcst._nodes.expression import SimpleString from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import WithLeadingWhitespace from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_trailing_whitespace, ) ParserConfig = config_mod.ParserConfig def convert_NUMBER(config: ParserConfig, token: Token) -> Any: return token
null
4,813
from typing import Any from libcst._nodes.expression import SimpleString from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import WithLeadingWhitespace from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_trailing_whitespace, ) 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) ParserConfig = config_mod.ParserConfig class WithLeadingWhitespace(Generic[_T]): value: _T whitespace_before: WhitespaceState def convert_STRING(config: ParserConfig, token: Token) -> Any: return WithLeadingWhitespace(SimpleString(token.string), token.whitespace_before)
null
4,814
from typing import Any from libcst._nodes.expression import SimpleString from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import WithLeadingWhitespace from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_trailing_whitespace, ) ParserConfig = config_mod.ParserConfig def convert_OP(config: ParserConfig, token: Token) -> Any: return token
null
4,815
from typing import Any from libcst._nodes.expression import SimpleString from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import WithLeadingWhitespace from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_trailing_whitespace, ) ParserConfig = config_mod.ParserConfig parse_trailing_whitespace = mod.parse_trailing_whitespace def convert_NEWLINE(config: ParserConfig, token: Token) -> Any: # A NEWLINE token is only emitted for semantic newlines, which means that this # corresponds to a TrailingWhitespace, since that's the only semantic # newline-containing node. # N.B. Because this token is whitespace, and because the whitespace parser doesn't # try to prevent overflows, `token.whitespace_before` will end up overflowing into # the value of this newline token, so `parse_trailing_whitespace` will include # token.string's value. This is expected and desired behavior. return parse_trailing_whitespace(config, token.whitespace_before)
null
4,816
from typing import Any from libcst._nodes.expression import SimpleString from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import WithLeadingWhitespace from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_trailing_whitespace, ) ParserConfig = config_mod.ParserConfig def convert_INDENT(config: ParserConfig, token: Token) -> Any: return token
null
4,817
from typing import Any from libcst._nodes.expression import SimpleString from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import WithLeadingWhitespace from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_trailing_whitespace, ) ParserConfig = config_mod.ParserConfig def convert_DEDENT(config: ParserConfig, token: Token) -> Any: return token
null
4,818
from typing import Any from libcst._nodes.expression import SimpleString from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import WithLeadingWhitespace from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_trailing_whitespace, ) ParserConfig = config_mod.ParserConfig parse_empty_lines = mod.parse_empty_lines def convert_ENDMARKER(config: ParserConfig, token: Token) -> Any: # Parse any and all empty lines with an indent similar to the header. That is, # indent of nothing and including all indents. In some cases, like when the # footer parser follows an indented suite, the state's indent can be wrong # due to the fact that it is shared with the _DEDENT node. We know that if # we're parsing the end of a file, we will have no indent. return parse_empty_lines( config, token.whitespace_before, override_absolute_indent="" )
null
4,819
from typing import Any from libcst._nodes.expression import SimpleString from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import WithLeadingWhitespace from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_trailing_whitespace, ) ParserConfig = config_mod.ParserConfig def convert_FSTRING_START(config: ParserConfig, token: Token) -> Any: return token
null
4,820
from typing import Any from libcst._nodes.expression import SimpleString from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import WithLeadingWhitespace from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_trailing_whitespace, ) ParserConfig = config_mod.ParserConfig def convert_FSTRING_END(config: ParserConfig, token: Token) -> Any: return token
null
4,821
from typing import Any from libcst._nodes.expression import SimpleString from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import WithLeadingWhitespace from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_trailing_whitespace, ) ParserConfig = config_mod.ParserConfig def convert_FSTRING_STRING(config: ParserConfig, token: Token) -> Any: return token
null
4,822
from typing import Any from libcst._nodes.expression import SimpleString from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import WithLeadingWhitespace from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_trailing_whitespace, ) ParserConfig = config_mod.ParserConfig def convert_ASYNC(config: ParserConfig, token: Token) -> Any: return token
null
4,823
from typing import Any from libcst._nodes.expression import SimpleString from libcst._parser.types.config import ParserConfig from libcst._parser.types.partials import WithLeadingWhitespace from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_trailing_whitespace, ) ParserConfig = config_mod.ParserConfig def convert_AWAIT(config: ParserConfig, token: Token) -> Any: return token
null
4,824
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_whitespace, ) ParserConfig = config_mod.ParserConfig def convert_stmt_input(config: ParserConfig, children: Sequence[Any]) -> Any: (child, endmarker) = children return child
null
4,825
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_whitespace, ) ParserConfig = config_mod.ParserConfig def convert_stmt(config: ParserConfig, children: Sequence[Any]) -> Any: (child,) = children return child
null
4,826
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_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 Semicolon(_BaseOneTokenOp): """ Used by any small statement (any subclass of :class:`BaseSmallStatement` such as :class:`Pass`) as a separator between subsequent nodes contained within a :class:`SimpleStatementLine` or :class:`SimpleStatementSuite`. """ #: Any space that appears directly before this semicolon. whitespace_before: BaseParenthesizableWhitespace = SimpleWhitespace.field("") #: Any space that appears directly after this semicolon. whitespace_after: BaseParenthesizableWhitespace = SimpleWhitespace.field("") def _get_token(self) -> str: return ";" class SimpleWhitespace(BaseParenthesizableWhitespace, BaseValueToken): """ This is the kind of whitespace you might see inside the body of a statement or expression between two tokens. This is the most common type of whitespace. A simple whitespace cannot contain a newline character unless it is directly preceeded by a line continuation character (``\\``). It can contain zero or more spaces or tabs. If you need a newline character without a line continuation character, use :class:`ParenthesizedWhitespace` instead. Simple whitespace is often non-semantic (optional), but in cases where whitespace solves a grammar ambiguity between tokens (e.g. ``if test``, versus ``iftest``), it has some semantic value. An example :class:`SimpleWhitespace` containing a space, a line continuation, a newline and another space is as follows:: SimpleWhitespace(r" \\\\n ") """ #: Actual string value of the simple whitespace. A legal value contains only #: space, ``\f`` and ``\t`` characters, and optionally a continuation #: (``\``) followed by a newline (``\n`` or ``\r\n``). value: str def _validate(self) -> None: if SIMPLE_WHITESPACE_RE.fullmatch(self.value) is None: raise CSTValidationError( f"Got non-whitespace value for whitespace node: {repr(self.value)}" ) def empty(self) -> bool: """ Indicates that this node is empty (zero whitespace characters). """ return len(self.value) == 0 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 SimpleStatementPartial: body: Sequence[BaseSmallStatement] whitespace_before: WhitespaceState trailing_whitespace: TrailingWhitespace parse_simple_whitespace = mod.parse_simple_whitespace def convert_simple_stmt_partial(config: ParserConfig, children: Sequence[Any]) -> Any: *statements, trailing_whitespace = children last_stmt = len(statements) / 2 body = [] for i, (stmt_body, semi) in enumerate(grouper(statements, 2)): if semi is not None: if i == (last_stmt - 1): # Trailing semicolons only own the whitespace before. semi = Semicolon( whitespace_before=parse_simple_whitespace( config, semi.whitespace_before ), whitespace_after=SimpleWhitespace(""), ) else: # Middle semicolons own the whitespace before and after. semi = Semicolon( whitespace_before=parse_simple_whitespace( config, semi.whitespace_before ), whitespace_after=parse_simple_whitespace( config, semi.whitespace_after ), ) else: semi = MaybeSentinel.DEFAULT body.append(stmt_body.value.with_changes(semicolon=semi)) return SimpleStatementPartial( body, whitespace_before=statements[0].whitespace_before, trailing_whitespace=trailing_whitespace, )
null
4,827
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_whitespace, ) 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. ParserConfig = config_mod.ParserConfig parse_empty_lines = mod.parse_empty_lines The provided code snippet includes necessary dependencies for implementing the `convert_simple_stmt_line` function. Write a Python function `def convert_simple_stmt_line(config: ParserConfig, children: Sequence[Any]) -> Any` to solve the following problem: This function is similar to convert_simple_stmt_suite, but yields a different type Here is the function: def convert_simple_stmt_line(config: ParserConfig, children: Sequence[Any]) -> Any: """ This function is similar to convert_simple_stmt_suite, but yields a different type """ (partial,) = children return SimpleStatementLine( partial.body, leading_lines=parse_empty_lines(config, partial.whitespace_before), trailing_whitespace=partial.trailing_whitespace, )
This function is similar to convert_simple_stmt_suite, but yields a different type
4,828
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_whitespace, ) class SimpleStatementSuite(_BaseSimpleStatement, BaseSuite): """ A simple statement that's used as a suite. A simple statement is a series of small statements joined together by semicolons. A suite is the thing that follows the colon in a compound statement. .. code-block:: if test:<leading_whitespace><body><trailing_whitespace> This isn't differentiated from a :class:`SimpleStatementLine` in the grammar, but because the two classes need to track different whitespace, 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] #: The whitespace between the colon in the parent statement and the body. leading_whitespace: SimpleWhitespace = SimpleWhitespace.field(" ") #: 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 ) -> "SimpleStatementSuite": return SimpleStatementSuite( leading_whitespace=visit_required( self, "leading_whitespace", self.leading_whitespace, visitor ), body=visit_sequence(self, "body", self.body, visitor), trailing_whitespace=visit_required( self, "trailing_whitespace", self.trailing_whitespace, visitor ), ) def _codegen_impl(self, state: CodegenState) -> None: self.leading_whitespace._codegen(state) _BaseSimpleStatement._codegen_impl(self, state) # pyre-fixme[13]: Attribute `body` is never initialized. ParserConfig = config_mod.ParserConfig parse_simple_whitespace = mod.parse_simple_whitespace The provided code snippet includes necessary dependencies for implementing the `convert_simple_stmt_suite` function. Write a Python function `def convert_simple_stmt_suite(config: ParserConfig, children: Sequence[Any]) -> Any` to solve the following problem: This function is similar to convert_simple_stmt_line, but yields a different type Here is the function: def convert_simple_stmt_suite(config: ParserConfig, children: Sequence[Any]) -> Any: """ This function is similar to convert_simple_stmt_line, but yields a different type """ (partial,) = children return SimpleStatementSuite( partial.body, leading_whitespace=parse_simple_whitespace(config, partial.whitespace_before), trailing_whitespace=partial.trailing_whitespace, )
This function is similar to convert_simple_stmt_line, but yields a different type
4,829
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_whitespace, ) ParserConfig = config_mod.ParserConfig def convert_small_stmt(config: ParserConfig, children: Sequence[Any]) -> Any: # Doesn't construct SmallStatement, because we don't know about semicolons yet. # convert_simple_stmt will construct the SmallStatement nodes. (small_stmt_body,) = children return small_stmt_body
null
4,830
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_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 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 AssignTarget(CSTNode): """ A target for an :class:`Assign`. Owns the equals sign and the whitespace around it. """ #: The target expression being assigned to. target: BaseAssignTargetExpression #: The whitespace appearing before the equals sign. whitespace_before_equal: SimpleWhitespace = SimpleWhitespace.field(" ") #: The whitespace appearing after the equals sign. whitespace_after_equal: SimpleWhitespace = SimpleWhitespace.field(" ") def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "AssignTarget": return AssignTarget( target=visit_required(self, "target", self.target, visitor), whitespace_before_equal=visit_required( self, "whitespace_before_equal", self.whitespace_before_equal, visitor ), whitespace_after_equal=visit_required( self, "whitespace_after_equal", self.whitespace_after_equal, visitor ), ) def _codegen_impl(self, state: CodegenState) -> None: with state.record_syntactic_position(self): self.target._codegen(state) self.whitespace_before_equal._codegen(state) state.add_token("=") self.whitespace_after_equal._codegen(state) class Assign(BaseSmallStatement): """ An assignment statement such as ``x = y`` or ``x = y = z``. Unlike :class:`AnnAssign`, this does not allow type annotations but does allow for multiple targets. """ #: One or more targets that are being assigned to. targets: Sequence[AssignTarget] #: The expression being assigned to the targets. 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 _validate(self) -> None: if len(self.targets) == 0: raise CSTValidationError( "An Assign statement must have at least one AssignTarget" ) def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Assign": return Assign( targets=visit_sequence(self, "targets", self.targets, visitor), 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): for target in self.targets: target._codegen(state) 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 AnnAssign(BaseSmallStatement): """ An assignment statement such as ``x: int = 5`` or ``x: int``. This only allows for one assignment target unlike :class:`Assign` but it includes a variable annotation. Also unlike :class:`Assign`, the assignment target is optional, as it is possible to annotate an expression without assigning to it. """ #: The target that is being annotated and possibly assigned to. target: BaseAssignTargetExpression #: The annotation for the target. annotation: Annotation #: The optional expression being assigned to the target. value: Optional[BaseExpression] = None #: The equals sign used to denote assignment if there is a value. equal: Union[AssignEqual, MaybeSentinel] = MaybeSentinel.DEFAULT #: 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 _validate(self) -> None: if self.value is None and isinstance(self.equal, AssignEqual): raise CSTValidationError( "Must have a value when specifying an AssignEqual." ) def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "AnnAssign": return AnnAssign( target=visit_required(self, "target", self.target, visitor), annotation=visit_required(self, "annotation", self.annotation, visitor), equal=visit_sentinel(self, "equal", self.equal, visitor), value=visit_optional(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.target._codegen(state) self.annotation._codegen(state, default_indicator=":") equal = self.equal if equal is MaybeSentinel.DEFAULT and self.value is not None: state.add_token(" = ") elif isinstance(equal, AssignEqual): equal._codegen(state) value = self.value if value is not None: value._codegen(state) semicolon = self.semicolon if isinstance(semicolon, MaybeSentinel): if default_semicolon: state.add_token("; ") elif isinstance(semicolon, Semicolon): semicolon._codegen(state) class AugAssign(BaseSmallStatement): """ An augmented assignment statement, such as ``x += 5``. """ #: Target that is being operated on and assigned to. target: BaseAssignTargetExpression #: The augmented assignment operation being performed. operator: BaseAugOp #: The value used with the above operator to calculate the new assignment. 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) -> "AugAssign": return AugAssign( target=visit_required(self, "target", self.target, visitor), operator=visit_required(self, "operator", self.operator, visitor), 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.target._codegen(state) self.operator._codegen(state) self.value._codegen(state) semicolon = self.semicolon if isinstance(semicolon, MaybeSentinel): if default_semicolon: state.add_token("; ") elif isinstance(semicolon, Semicolon): semicolon._codegen(state) # pyre-fixme[13]: Attribute `body` is never initialized. ParserConfig = config_mod.ParserConfig class WithLeadingWhitespace(Generic[_T]): value: _T whitespace_before: WhitespaceState class AnnAssignPartial: annotation: Annotation equal: Optional[AssignEqual] value: Optional[BaseExpression] class AugAssignPartial: operator: BaseAugOp value: BaseExpression def convert_expr_stmt(config: ParserConfig, children: Sequence[Any]) -> Any: if len(children) == 1: # This is an unassigned expr statement (like a function call) (test_node,) = children return WithLeadingWhitespace( Expr(value=test_node.value), test_node.whitespace_before ) elif len(children) == 2: lhs, rhs = children if isinstance(rhs, AnnAssignPartial): return WithLeadingWhitespace( AnnAssign( target=lhs.value, annotation=rhs.annotation, equal=MaybeSentinel.DEFAULT if rhs.equal is None else rhs.equal, value=rhs.value, ), lhs.whitespace_before, ) elif isinstance(rhs, AugAssignPartial): return WithLeadingWhitespace( AugAssign(target=lhs.value, operator=rhs.operator, value=rhs.value), lhs.whitespace_before, ) # The only thing it could be at this point is an assign with one or more targets. # So, walk the children moving the equals ownership back one and constructing a # list of AssignTargets. targets = [] for i in range(len(children) - 1): target = children[i].value equal = children[i + 1].equal targets.append( AssignTarget( target=target, whitespace_before_equal=equal.whitespace_before, whitespace_after_equal=equal.whitespace_after, ) ) return WithLeadingWhitespace( Assign(targets=tuple(targets), value=children[-1].value), children[0].whitespace_before, )
null
4,831
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_whitespace, ) class Annotation(CSTNode): """ An annotation for a function (`PEP 3107`_) or on a variable (`PEP 526`_). Typically these are used in the context of type hints (`PEP 484`_), such as:: # a variable with a type good_ideas: List[str] = [] # a function with type annotations def concat(substrings: Sequence[str]) -> str: ... .. _PEP 3107: https://www.python.org/dev/peps/pep-3107/ .. _PEP 526: https://www.python.org/dev/peps/pep-0526/ .. _PEP 484: https://www.python.org/dev/peps/pep-0484/ """ #: The annotation's value itself. This is the part of the annotation after the #: colon or arrow. annotation: BaseExpression whitespace_before_indicator: Union[ BaseParenthesizableWhitespace, MaybeSentinel ] = MaybeSentinel.DEFAULT whitespace_after_indicator: BaseParenthesizableWhitespace = SimpleWhitespace.field( " " ) def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Annotation": return Annotation( whitespace_before_indicator=visit_sentinel( self, "whitespace_before_indicator", self.whitespace_before_indicator, visitor, ), whitespace_after_indicator=visit_required( self, "whitespace_after_indicator", self.whitespace_after_indicator, visitor, ), annotation=visit_required(self, "annotation", self.annotation, visitor), ) def _codegen_impl( self, state: CodegenState, default_indicator: Optional[str] = None ) -> None: # First, figure out the indicator which tells us default whitespace. if default_indicator is None: raise CSTCodegenError( "Must specify a concrete default_indicator if default used on indicator." ) # Now, output the whitespace whitespace_before_indicator = self.whitespace_before_indicator if isinstance(whitespace_before_indicator, BaseParenthesizableWhitespace): whitespace_before_indicator._codegen(state) elif isinstance(whitespace_before_indicator, MaybeSentinel): if default_indicator == "->": state.add_token(" ") else: raise Exception("Logic error!") # Now, output the indicator and the rest of the annotation state.add_token(default_indicator) self.whitespace_after_indicator._codegen(state) with state.record_syntactic_position(self): self.annotation._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 AnnAssignPartial: annotation: Annotation equal: Optional[AssignEqual] value: Optional[BaseExpression] parse_simple_whitespace = mod.parse_simple_whitespace def convert_annassign(config: ParserConfig, children: Sequence[Any]) -> Any: if len(children) == 2: # Variable annotation only colon, annotation = children annotation = annotation.value equal = None value = None elif len(children) == 4: # Variable annotation and assignment colon, annotation, equal, value = children annotation = annotation.value value = value.value equal = AssignEqual( whitespace_before=parse_simple_whitespace(config, equal.whitespace_before), whitespace_after=parse_simple_whitespace(config, equal.whitespace_after), ) else: raise Exception("Invalid parser state!") return AnnAssignPartial( annotation=Annotation( whitespace_before_indicator=parse_simple_whitespace( config, colon.whitespace_before ), whitespace_after_indicator=parse_simple_whitespace( config, colon.whitespace_after ), annotation=annotation, ), equal=equal, value=value, )
null
4,832
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_whitespace, ) AUGOP_TOKEN_LUT: Dict[str, Type[BaseAugOp]] = { "+=": AddAssign, "-=": SubtractAssign, "*=": MultiplyAssign, "@=": MatrixMultiplyAssign, "/=": DivideAssign, "%=": ModuloAssign, "&=": BitAndAssign, "|=": BitOrAssign, "^=": BitXorAssign, "<<=": LeftShiftAssign, ">>=": RightShiftAssign, "**=": PowerAssign, "//=": FloorDivideAssign, } ParserConfig = config_mod.ParserConfig class AugAssignPartial: operator: BaseAugOp value: BaseExpression parse_simple_whitespace = mod.parse_simple_whitespace def convert_augassign(config: ParserConfig, children: Sequence[Any]) -> Any: op, expr = children if op.string not in AUGOP_TOKEN_LUT: raise Exception(f"Unexpected token '{op.string}'!") return AugAssignPartial( # pyre-ignore Pyre seems to think that the value of this LUT is CSTNode operator=AUGOP_TOKEN_LUT[op.string]( whitespace_before=parse_simple_whitespace(config, op.whitespace_before), whitespace_after=parse_simple_whitespace(config, op.whitespace_after), ), value=expr.value, )
null
4,833
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_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 class AssignPartial: equal: AssignEqual value: BaseExpression parse_simple_whitespace = mod.parse_simple_whitespace def convert_assign(config: ParserConfig, children: Sequence[Any]) -> Any: equal, expr = children return AssignPartial( equal=AssignEqual( whitespace_before=parse_simple_whitespace(config, equal.whitespace_before), whitespace_after=parse_simple_whitespace(config, equal.whitespace_after), ), value=expr.value, )
null
4,834
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_whitespace, ) class Pass(BaseSmallStatement): """ Represents a ``pass`` statement. """ #: 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) -> "Pass": return Pass( 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): state.add_token("pass") semicolon = self.semicolon if isinstance(semicolon, MaybeSentinel): if default_semicolon: state.add_token("; ") elif isinstance(semicolon, Semicolon): semicolon._codegen(state) # pyre-fixme[13]: Attribute `body` is never initialized. ParserConfig = config_mod.ParserConfig class WithLeadingWhitespace(Generic[_T]): value: _T whitespace_before: WhitespaceState def convert_pass_stmt(config: ParserConfig, children: Sequence[Any]) -> Any: (name,) = children return WithLeadingWhitespace(Pass(), name.whitespace_before)
null
4,835
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_whitespace, ) class Del(BaseSmallStatement): def _validate(self) -> None: def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Del": def _codegen_impl( self, state: CodegenState, default_semicolon: bool = False ) -> None: # pyre-fixme[13]: Attribute `body` is never initialized. ParserConfig = config_mod.ParserConfig class WithLeadingWhitespace(Generic[_T]): parse_simple_whitespace = mod.parse_simple_whitespace def convert_del_stmt(config: ParserConfig, children: Sequence[Any]) -> Any: (del_name, exprlist) = children return WithLeadingWhitespace( Del( target=exprlist.value, whitespace_after_del=parse_simple_whitespace( config, del_name.whitespace_after ), ), del_name.whitespace_before, )
null
4,836
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_whitespace, ) class Continue(BaseSmallStatement): def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Continue": def _codegen_impl( self, state: CodegenState, default_semicolon: bool = False ) -> None: # pyre-fixme[13]: Attribute `body` is never initialized. ParserConfig = config_mod.ParserConfig class WithLeadingWhitespace(Generic[_T]): def convert_continue_stmt(config: ParserConfig, children: Sequence[Any]) -> Any: (name,) = children return WithLeadingWhitespace(Continue(), name.whitespace_before)
null
4,837
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_whitespace, ) class Break(BaseSmallStatement): """ Represents a ``break`` statement, which is used to break out of a :class:`For` or :class:`While` loop early. """ #: 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) -> "Break": return Break( 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): state.add_token("break") semicolon = self.semicolon if isinstance(semicolon, MaybeSentinel): if default_semicolon: state.add_token("; ") elif isinstance(semicolon, Semicolon): semicolon._codegen(state) # pyre-fixme[13]: Attribute `body` is never initialized. ParserConfig = config_mod.ParserConfig class WithLeadingWhitespace(Generic[_T]): value: _T whitespace_before: WhitespaceState def convert_break_stmt(config: ParserConfig, children: Sequence[Any]) -> Any: (name,) = children return WithLeadingWhitespace(Break(), name.whitespace_before)
null
4,838
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_whitespace, ) class Return(BaseSmallStatement): """ Represents a ``return`` or a ``return x`` statement. """ #: The optional expression that will be evaluated and returned. value: Optional[BaseExpression] = None #: Optional whitespace after the ``return`` keyword before the optional #: value expression. whitespace_after_return: Union[ SimpleWhitespace, MaybeSentinel ] = MaybeSentinel.DEFAULT #: 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 _validate(self) -> None: value = self.value if value is not None: whitespace_after_return = self.whitespace_after_return has_no_gap = ( not isinstance(whitespace_after_return, MaybeSentinel) and whitespace_after_return.empty ) if has_no_gap and not value._safe_to_use_with_word_operator( ExpressionPosition.RIGHT ): raise CSTValidationError("Must have at least one space after 'return'.") def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Return": return Return( whitespace_after_return=visit_sentinel( self, "whitespace_after_return", self.whitespace_after_return, visitor ), value=visit_optional(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): state.add_token("return") whitespace_after_return = self.whitespace_after_return value = self.value if isinstance(whitespace_after_return, MaybeSentinel): if value is not None: state.add_token(" ") else: whitespace_after_return._codegen(state) if value is not None: value._codegen(state) semicolon = self.semicolon if isinstance(semicolon, MaybeSentinel): if default_semicolon: state.add_token("; ") elif isinstance(semicolon, Semicolon): semicolon._codegen(state) # pyre-fixme[13]: Attribute `body` is never initialized. class SimpleWhitespace(BaseParenthesizableWhitespace, BaseValueToken): """ This is the kind of whitespace you might see inside the body of a statement or expression between two tokens. This is the most common type of whitespace. A simple whitespace cannot contain a newline character unless it is directly preceeded by a line continuation character (``\\``). It can contain zero or more spaces or tabs. If you need a newline character without a line continuation character, use :class:`ParenthesizedWhitespace` instead. Simple whitespace is often non-semantic (optional), but in cases where whitespace solves a grammar ambiguity between tokens (e.g. ``if test``, versus ``iftest``), it has some semantic value. An example :class:`SimpleWhitespace` containing a space, a line continuation, a newline and another space is as follows:: SimpleWhitespace(r" \\\\n ") """ #: Actual string value of the simple whitespace. A legal value contains only #: space, ``\f`` and ``\t`` characters, and optionally a continuation #: (``\``) followed by a newline (``\n`` or ``\r\n``). value: str def _validate(self) -> None: if SIMPLE_WHITESPACE_RE.fullmatch(self.value) is None: raise CSTValidationError( f"Got non-whitespace value for whitespace node: {repr(self.value)}" ) def empty(self) -> bool: """ Indicates that this node is empty (zero whitespace characters). """ return len(self.value) == 0 ParserConfig = config_mod.ParserConfig class WithLeadingWhitespace(Generic[_T]): value: _T whitespace_before: WhitespaceState parse_simple_whitespace = mod.parse_simple_whitespace def convert_return_stmt(config: ParserConfig, children: Sequence[Any]) -> Any: if len(children) == 1: (keyword,) = children return WithLeadingWhitespace( Return(whitespace_after_return=SimpleWhitespace("")), keyword.whitespace_before, ) else: (keyword, testlist) = children return WithLeadingWhitespace( Return( value=testlist.value, whitespace_after_return=parse_simple_whitespace( config, keyword.whitespace_after ), ), keyword.whitespace_before, )
null
4,839
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_whitespace, ) ParserConfig = config_mod.ParserConfig def convert_import_stmt(config: ParserConfig, children: Sequence[Any]) -> Any: (child,) = children return child
null
4,840
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_whitespace, ) class Import(BaseSmallStatement): """ An ``import`` statement. """ #: One or more names that are being imported, with optional local aliases. names: Sequence[ImportAlias] #: 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 #: The whitespace that appears after the ``import`` keyword but before #: the first import alias. whitespace_after_import: SimpleWhitespace = SimpleWhitespace.field(" ") def _validate(self) -> None: if len(self.names) == 0: raise CSTValidationError( "An ImportStatement must have at least one ImportAlias" ) if isinstance(self.names[-1].comma, Comma): raise CSTValidationError( "An ImportStatement does not allow a trailing comma" ) if self.whitespace_after_import.empty: raise CSTValidationError("Must have at least one space after import.") def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Import": return Import( whitespace_after_import=visit_required( self, "whitespace_after_import", self.whitespace_after_import, visitor ), names=visit_sequence(self, "names", self.names, 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): state.add_token("import") self.whitespace_after_import._codegen(state) lastname = len(self.names) - 1 for i, name in enumerate(self.names): name._codegen(state, default_comma=(i != lastname)) semicolon = self.semicolon if isinstance(semicolon, MaybeSentinel): if default_semicolon: state.add_token("; ") elif isinstance(semicolon, Semicolon): semicolon._codegen(state) # pyre-fixme[13]: Attribute `body` is never initialized. ParserConfig = config_mod.ParserConfig class WithLeadingWhitespace(Generic[_T]): value: _T whitespace_before: WhitespaceState parse_simple_whitespace = mod.parse_simple_whitespace def convert_import_name(config: ParserConfig, children: Sequence[Any]) -> Any: importtoken, names = children return WithLeadingWhitespace( Import( names=names.names, whitespace_after_import=parse_simple_whitespace( config, importtoken.whitespace_after ), ), importtoken.whitespace_before, )
null
4,841
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_whitespace, ) 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 ImportRelativePartial: relative: Sequence[Dot] module: Optional[Union[Attribute, Name]] parse_simple_whitespace = mod.parse_simple_whitespace def convert_import_relative(config: ParserConfig, children: Sequence[Any]) -> Any: dots = [] dotted_name = None for child in children: if isinstance(child, Token): # Special case for "...", which is part of the grammar if child.string == "...": dots.extend( [ Dot(), Dot(), Dot( whitespace_after=parse_simple_whitespace( config, child.whitespace_after ) ), ] ) else: dots.append( Dot( whitespace_after=parse_simple_whitespace( config, child.whitespace_after ) ) ) else: # This should be the dotted name, and we can't get more than # one, but lets be sure anyway if dotted_name is not None: raise Exception("Logic error!") dotted_name = child return ImportRelativePartial(relative=tuple(dots), module=dotted_name)
null
4,842
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_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 ImportStar(BaseLeaf): """ Used by :class:`ImportFrom` to denote a star import instead of a list of importable objects. """ def _codegen_impl(self, state: CodegenState) -> None: state.add_token("*") class ImportFrom(BaseSmallStatement): """ A ``from x import y`` statement. """ #: Name or Attribute node representing the module we're importing from. #: This is optional as :class:`ImportFrom` allows purely relative imports. module: Optional[Union[Attribute, Name]] #: One or more names that are being imported from the specified module, #: with optional local aliases. names: Union[Sequence[ImportAlias], ImportStar] #: Sequence of :class:`Dot` nodes indicating relative import level. relative: Sequence[Dot] = () #: Optional open parenthesis for multi-line import continuation. lpar: Optional[LeftParen] = None #: Optional close parenthesis for multi-line import continuation. rpar: Optional[RightParen] = None #: 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 #: The whitespace that appears after the ``from`` keyword but before #: the module and any relative import dots. whitespace_after_from: SimpleWhitespace = SimpleWhitespace.field(" ") #: The whitespace that appears after the module but before the #: ``import`` keyword. whitespace_before_import: SimpleWhitespace = SimpleWhitespace.field(" ") #: The whitespace that appears after the ``import`` keyword but #: before the first import name or optional left paren. whitespace_after_import: SimpleWhitespace = SimpleWhitespace.field(" ") def _validate_module(self) -> None: if self.module is None and len(self.relative) == 0: raise CSTValidationError( "Must have a module specified if there is no relative import." ) def _validate_names(self) -> None: names = self.names if isinstance(names, Sequence): if len(names) == 0: raise CSTValidationError( "An ImportFrom must have at least one ImportAlias" ) for name in names[:-1]: if name.comma is None: raise CSTValidationError("Non-final ImportAliases require a comma") if self.lpar is not None and self.rpar is None: raise CSTValidationError("Cannot have left paren without right paren.") if self.lpar is None and self.rpar is not None: raise CSTValidationError("Cannot have right paren without left paren.") if isinstance(names, ImportStar): if self.lpar is not None or self.rpar is not None: raise CSTValidationError( "An ImportFrom using ImportStar cannot have parens" ) def _validate_whitespace(self) -> None: if self.whitespace_after_from.empty and not self.relative: raise CSTValidationError("Must have at least one space after from.") if self.whitespace_before_import.empty and not ( self.relative and self.module is None ): raise CSTValidationError("Must have at least one space before import.") if ( self.whitespace_after_import.empty and self.lpar is None and not isinstance(self.names, ImportStar) ): raise CSTValidationError("Must have at least one space after import.") def _validate(self) -> None: self._validate_module() self._validate_names() self._validate_whitespace() def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "ImportFrom": names = self.names return ImportFrom( whitespace_after_from=visit_required( self, "whitespace_after_from", self.whitespace_after_from, visitor ), relative=visit_sequence(self, "relative", self.relative, visitor), module=visit_optional(self, "module", self.module, visitor), whitespace_before_import=visit_required( self, "whitespace_before_import", self.whitespace_before_import, visitor ), whitespace_after_import=visit_required( self, "whitespace_after_import", self.whitespace_after_import, visitor ), lpar=visit_optional(self, "lpar", self.lpar, visitor), names=( visit_required(self, "names", names, visitor) if isinstance(names, ImportStar) else visit_sequence(self, "names", names, visitor) ), rpar=visit_optional(self, "rpar", self.rpar, visitor), semicolon=visit_sentinel(self, "semicolon", self.semicolon, visitor), ) def _codegen_impl( self, state: CodegenState, default_semicolon: bool = False ) -> None: names = self.names end_node = names[-1] if isinstance(names, Sequence) else names end_node = end_node if self.rpar is None else self.rpar with state.record_syntactic_position(self, end_node=end_node): state.add_token("from") self.whitespace_after_from._codegen(state) for dot in self.relative: dot._codegen(state) module = self.module if module is not None: module._codegen(state) self.whitespace_before_import._codegen(state) state.add_token("import") self.whitespace_after_import._codegen(state) lpar = self.lpar if lpar is not None: lpar._codegen(state) if isinstance(names, Sequence): lastname = len(names) - 1 for i, name in enumerate(names): name._codegen(state, default_comma=(i != lastname)) if isinstance(names, ImportStar): names._codegen(state) rpar = self.rpar if rpar is not None: rpar._codegen(state) semicolon = self.semicolon if isinstance(semicolon, MaybeSentinel): if default_semicolon: state.add_token("; ") elif isinstance(semicolon, Semicolon): semicolon._codegen(state) # pyre-fixme[13]: Attribute `body` is never initialized. class SimpleWhitespace(BaseParenthesizableWhitespace, BaseValueToken): """ This is the kind of whitespace you might see inside the body of a statement or expression between two tokens. This is the most common type of whitespace. A simple whitespace cannot contain a newline character unless it is directly preceeded by a line continuation character (``\\``). It can contain zero or more spaces or tabs. If you need a newline character without a line continuation character, use :class:`ParenthesizedWhitespace` instead. Simple whitespace is often non-semantic (optional), but in cases where whitespace solves a grammar ambiguity between tokens (e.g. ``if test``, versus ``iftest``), it has some semantic value. An example :class:`SimpleWhitespace` containing a space, a line continuation, a newline and another space is as follows:: SimpleWhitespace(r" \\\\n ") """ #: Actual string value of the simple whitespace. A legal value contains only #: space, ``\f`` and ``\t`` characters, and optionally a continuation #: (``\``) followed by a newline (``\n`` or ``\r\n``). value: str def _validate(self) -> None: if SIMPLE_WHITESPACE_RE.fullmatch(self.value) is None: raise CSTValidationError( f"Got non-whitespace value for whitespace node: {repr(self.value)}" ) def empty(self) -> bool: """ Indicates that this node is empty (zero whitespace characters). """ return len(self.value) == 0 ParserConfig = config_mod.ParserConfig class WithLeadingWhitespace(Generic[_T]): value: _T whitespace_before: WhitespaceState parse_simple_whitespace = mod.parse_simple_whitespace parse_parenthesizable_whitespace = mod.parse_parenthesizable_whitespace def convert_import_from(config: ParserConfig, children: Sequence[Any]) -> Any: fromtoken, import_relative, importtoken, *importlist = children if len(importlist) == 1: (possible_star,) = importlist if isinstance(possible_star, Token): # Its a "*" import, so we must construct this node. names = ImportStar() else: # Its an import as names partial, grab the names from that. names = possible_star.names lpar = None rpar = None else: # Its an import as names partial with parens lpartoken, namespartial, rpartoken = importlist lpar = LeftParen( whitespace_after=parse_parenthesizable_whitespace( config, lpartoken.whitespace_after ) ) names = namespartial.names rpar = RightParen( whitespace_before=parse_parenthesizable_whitespace( config, rpartoken.whitespace_before ) ) # If we have a relative-only import, then we need to relocate the space # after the final dot to be owned by the import token. if len(import_relative.relative) > 0 and import_relative.module is None: whitespace_before_import = import_relative.relative[-1].whitespace_after relative = ( *import_relative.relative[:-1], import_relative.relative[-1].with_changes( whitespace_after=SimpleWhitespace("") ), ) else: whitespace_before_import = parse_simple_whitespace( config, importtoken.whitespace_before ) relative = import_relative.relative return WithLeadingWhitespace( ImportFrom( whitespace_after_from=parse_simple_whitespace( config, fromtoken.whitespace_after ), relative=relative, module=import_relative.module, whitespace_before_import=whitespace_before_import, whitespace_after_import=parse_simple_whitespace( config, importtoken.whitespace_after ), lpar=lpar, names=names, rpar=rpar, ), fromtoken.whitespace_before, )
null
4,843
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_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 AsName(CSTNode): """ An ``as name`` clause inside an :class:`ExceptHandler`, :class:`ImportAlias` or :class:`WithItem` node. """ #: Identifier that the parent node will be aliased to. name: Union[Name, Tuple, List] #: Whitespace between the parent node and the ``as`` keyword. whitespace_before_as: BaseParenthesizableWhitespace = SimpleWhitespace.field(" ") #: Whitespace between the ``as`` keyword and the name. whitespace_after_as: BaseParenthesizableWhitespace = SimpleWhitespace.field(" ") def _validate(self) -> None: if ( self.whitespace_after_as.empty and not self.name._safe_to_use_with_word_operator(ExpressionPosition.RIGHT) ): raise CSTValidationError( "There must be at least one space between 'as' and name." ) def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "AsName": return AsName( whitespace_before_as=visit_required( self, "whitespace_before_as", self.whitespace_before_as, visitor ), name=visit_required(self, "name", self.name, visitor), whitespace_after_as=visit_required( self, "whitespace_after_as", self.whitespace_after_as, visitor ), ) def _codegen_impl(self, state: CodegenState) -> None: self.whitespace_before_as._codegen(state) state.add_token("as") self.whitespace_after_as._codegen(state) self.name._codegen(state) class ImportAlias(CSTNode): """ An import, with an optional :class:`AsName`. Used in both :class:`Import` and :class:`ImportFrom` to specify a single import out of another module. """ #: Name or Attribute node representing the object we are importing. name: Union[Attribute, Name] #: Local alias we will import the above object as. asname: Optional[AsName] = None #: Any trailing comma that appears after this import. This is optional for the #: last :class:`ImportAlias` in a :class:`Import` or :class:`ImportFrom`, but all #: other import aliases inside an import must contain a comma to disambiguate #: multiple imports. comma: Union[Comma, MaybeSentinel] = MaybeSentinel.DEFAULT def _validate(self) -> None: asname = self.asname if asname is not None: if not isinstance(asname.name, Name): raise CSTValidationError( "Must use a Name node for AsName name inside ImportAlias." ) if asname.whitespace_before_as.empty: raise CSTValidationError( "Must have at least one space before as keyword in an ImportAlias." ) try: self.evaluated_name except Exception as e: if str(e) == "Logic error!": raise CSTValidationError( "The imported name must be a valid qualified name." ) raise e def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "ImportAlias": return ImportAlias( name=visit_required(self, "name", self.name, visitor), asname=visit_optional(self, "asname", self.asname, 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.name._codegen(state) asname = self.asname if asname is not None: asname._codegen(state) comma = self.comma if comma is MaybeSentinel.DEFAULT and default_comma: state.add_token(", ") elif isinstance(comma, Comma): comma._codegen(state) def _name(self, node: CSTNode) -> str: # Unrolled version of get_full_name_for_node to avoid circular imports. if isinstance(node, Name): return node.value elif isinstance(node, Attribute): return f"{self._name(node.value)}.{node.attr.value}" else: raise Exception("Logic error!") def evaluated_name(self) -> str: """ Returns the string name this :class:`ImportAlias` represents. """ return self._name(self.name) def evaluated_alias(self) -> Optional[str]: """ Returns the string name for any alias that this :class:`ImportAlias` has. If there is no ``asname`` attribute, this returns ``None``. """ asname = self.asname if asname is not None: return self._name(asname.name) return None # pyre-fixme[13]: Attribute `body` is never initialized. ParserConfig = config_mod.ParserConfig parse_simple_whitespace = mod.parse_simple_whitespace def convert_import_as_name(config: ParserConfig, children: Sequence[Any]) -> Any: if len(children) == 1: (dotted_name,) = children return ImportAlias(name=Name(dotted_name.string), asname=None) else: dotted_name, astoken, name = children return ImportAlias( name=Name(dotted_name.string), asname=AsName( whitespace_before_as=parse_simple_whitespace( config, astoken.whitespace_before ), whitespace_after_as=parse_simple_whitespace( config, astoken.whitespace_after ), name=Name(name.string), ), )
null
4,844
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_whitespace, ) class Name(BaseAssignTargetExpression, BaseDelTargetExpression): def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Name": def _validate(self) -> None: def _codegen_impl(self, state: CodegenState) -> None: class AsName(CSTNode): def _validate(self) -> None: def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "AsName": def _codegen_impl(self, state: CodegenState) -> None: class ImportAlias(CSTNode): def _validate(self) -> None: def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "ImportAlias": def _codegen_impl(self, state: CodegenState, default_comma: bool = False) -> None: def _name(self, node: CSTNode) -> str: def evaluated_name(self) -> str: def evaluated_alias(self) -> Optional[str]: # pyre-fixme[13]: Attribute `body` is never initialized. ParserConfig = config_mod.ParserConfig parse_parenthesizable_whitespace = mod.parse_parenthesizable_whitespace def convert_dotted_as_name(config: ParserConfig, children: Sequence[Any]) -> Any: if len(children) == 1: (dotted_name,) = children return ImportAlias(name=dotted_name, asname=None) else: dotted_name, astoken, name = children return ImportAlias( name=dotted_name, asname=AsName( whitespace_before_as=parse_parenthesizable_whitespace( config, astoken.whitespace_before ), whitespace_after_as=parse_parenthesizable_whitespace( config, astoken.whitespace_after ), name=Name(name.string), ), )
null
4,845
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_whitespace, ) def _gather_import_names( config: ParserConfig, children: Sequence[Any] ) -> ImportPartial: names = [] for name, comma in grouper(children, 2): if comma is None: names.append(name) else: names.append( name.with_changes( comma=Comma( whitespace_before=parse_parenthesizable_whitespace( config, comma.whitespace_before ), whitespace_after=parse_parenthesizable_whitespace( config, comma.whitespace_after ), ) ) ) return ImportPartial(names=names) ParserConfig = config_mod.ParserConfig def convert_import_as_names(config: ParserConfig, children: Sequence[Any]) -> Any: return _gather_import_names(config, children)
null
4,846
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_whitespace, ) def _gather_import_names( config: ParserConfig, children: Sequence[Any] ) -> ImportPartial: ParserConfig = config_mod.ParserConfig def convert_dotted_as_names(config: ParserConfig, children: Sequence[Any]) -> Any: return _gather_import_names(config, children)
null
4,847
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_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 Attribute(BaseAssignTargetExpression, BaseDelTargetExpression): """ An attribute reference, such as ``x.y``. Note that in the case of ``x.y.z``, the outer attribute will have an attr of ``z`` and the value will be another :class:`Attribute` referencing the ``y`` attribute on ``x``:: Attribute( value=Attribute( value=Name("x") attr=Name("y") ), attr=Name("z"), ) """ #: An expression which, when evaluated, will produce an object with ``attr`` as an #: attribute. value: BaseExpression #: The name of the attribute being accessed on the ``value`` object. attr: Name #: A separating dot. If there's whitespace between the ``value`` and ``attr``, this #: dot owns it. dot: Dot = Dot() lpar: Sequence[LeftParen] = () #: Sequence of parenthesis for precedence dictation. rpar: Sequence[RightParen] = () def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Attribute": return Attribute( lpar=visit_sequence(self, "lpar", self.lpar, visitor), value=visit_required(self, "value", self.value, visitor), dot=visit_required(self, "dot", self.dot, visitor), attr=visit_required(self, "attr", self.attr, visitor), rpar=visit_sequence(self, "rpar", self.rpar, visitor), ) def _safe_to_use_with_word_operator(self, position: ExpressionPosition) -> bool: if super(Attribute, self)._safe_to_use_with_word_operator(position): return True return self._check_left_right_word_concatenation_safety( position, self.value, self.attr ) def _codegen_impl(self, state: CodegenState) -> None: with self._parenthesize(state): self.value._codegen(state) self.dot._codegen(state) self.attr._codegen(state) 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 "." 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 parse_parenthesizable_whitespace = mod.parse_parenthesizable_whitespace def convert_dotted_name(config: ParserConfig, children: Sequence[Any]) -> Any: left, *rest = children node = Name(left.string) for dot, right in grouper(rest, 2): node = Attribute( value=node, dot=Dot( whitespace_before=parse_parenthesizable_whitespace( config, dot.whitespace_before ), whitespace_after=parse_parenthesizable_whitespace( config, dot.whitespace_after ), ), attr=Name(right.string), ) return node
null
4,848
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_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 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) class Raise(BaseSmallStatement): """ A ``raise exc`` or ``raise exc from cause`` statement. """ #: The exception that we should raise. exc: Optional[BaseExpression] = None #: Optionally, a ``from cause`` clause to allow us to raise an exception #: out of another exception's context. cause: Optional[From] = None #: Any whitespace appearing between the ``raise`` keyword and the exception. whitespace_after_raise: Union[ SimpleWhitespace, MaybeSentinel ] = MaybeSentinel.DEFAULT #: 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 _validate(self) -> None: # Validate correct construction if self.exc is None and self.cause is not None: raise CSTValidationError( "Must have an 'exc' when specifying 'clause'. on Raise." ) # Validate spacing between "raise" and "exc" exc = self.exc if exc is not None: whitespace_after_raise = self.whitespace_after_raise has_no_gap = ( not isinstance(whitespace_after_raise, MaybeSentinel) and whitespace_after_raise.empty ) if has_no_gap and not exc._safe_to_use_with_word_operator( ExpressionPosition.RIGHT ): raise CSTValidationError("Must have at least one space after 'raise'.") # Validate spacing between "exc" and "from" cause = self.cause if exc is not None and cause is not None: whitespace_before_from = cause.whitespace_before_from has_no_gap = ( not isinstance(whitespace_before_from, MaybeSentinel) and whitespace_before_from.empty ) if has_no_gap and not exc._safe_to_use_with_word_operator( ExpressionPosition.LEFT ): raise CSTValidationError("Must have at least one space before 'from'.") def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Raise": return Raise( whitespace_after_raise=visit_sentinel( self, "whitespace_after_raise", self.whitespace_after_raise, visitor ), exc=visit_optional(self, "exc", self.exc, visitor), cause=visit_optional(self, "cause", self.cause, 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): exc = self.exc cause = self.cause state.add_token("raise") whitespace_after_raise = self.whitespace_after_raise if isinstance(whitespace_after_raise, MaybeSentinel): if exc is not None: state.add_token(" ") else: whitespace_after_raise._codegen(state) if exc is not None: exc._codegen(state) if cause is not None: cause._codegen(state, default_space=" ") semicolon = self.semicolon if isinstance(semicolon, MaybeSentinel): if default_semicolon: state.add_token("; ") elif isinstance(semicolon, Semicolon): semicolon._codegen(state) # pyre-fixme[13]: Attribute `body` is never initialized. ParserConfig = config_mod.ParserConfig class WithLeadingWhitespace(Generic[_T]): value: _T whitespace_before: WhitespaceState parse_simple_whitespace = mod.parse_simple_whitespace def convert_raise_stmt(config: ParserConfig, children: Sequence[Any]) -> Any: if len(children) == 1: (raise_token,) = children whitespace_after_raise = MaybeSentinel.DEFAULT exc = None cause = None elif len(children) == 2: (raise_token, test) = children whitespace_after_raise = parse_simple_whitespace(config, test.whitespace_before) exc = test.value cause = None elif len(children) == 4: (raise_token, test, from_token, source) = children whitespace_after_raise = parse_simple_whitespace(config, test.whitespace_before) exc = test.value cause = From( whitespace_before_from=parse_simple_whitespace( config, from_token.whitespace_before ), whitespace_after_from=parse_simple_whitespace( config, source.whitespace_before ), item=source.value, ) else: raise Exception("Logic error!") return WithLeadingWhitespace( Raise(whitespace_after_raise=whitespace_after_raise, exc=exc, cause=cause), raise_token.whitespace_before, )
null
4,849
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_whitespace, ) def _construct_nameitems(config: ParserConfig, names: Sequence[Any]) -> List[NameItem]: nameitems: List[NameItem] = [] for name, maybe_comma in grouper(names, 2): if maybe_comma is None: nameitems.append(NameItem(Name(name.string))) else: nameitems.append( NameItem( Name(name.string), comma=Comma( whitespace_before=parse_simple_whitespace( config, maybe_comma.whitespace_before ), whitespace_after=parse_simple_whitespace( config, maybe_comma.whitespace_after ), ), ) ) return nameitems class Global(BaseSmallStatement): """ A ``global`` statement. """ #: A list of one or more names. names: Sequence[NameItem] #: Whitespace appearing after the ``global`` keyword and before the first name. whitespace_after_global: SimpleWhitespace = SimpleWhitespace.field(" ") #: 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 _validate(self) -> None: if len(self.names) == 0: raise CSTValidationError( "A Global statement must have at least one NameItem." ) if self.names[-1].comma != MaybeSentinel.DEFAULT: raise CSTValidationError( "The last NameItem in a Global cannot have a trailing comma." ) if self.whitespace_after_global.empty: raise CSTValidationError( "Must have at least one space after 'global' keyword." ) def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Global": return Global( whitespace_after_global=visit_required( self, "whitespace_after_global", self.whitespace_after_global, visitor ), names=visit_sequence(self, "names", self.names, 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): state.add_token("global") self.whitespace_after_global._codegen(state) last_name = len(self.names) - 1 for i, name in enumerate(self.names): name._codegen(state, default_comma=(i != last_name)) semicolon = self.semicolon if isinstance(semicolon, MaybeSentinel): if default_semicolon: state.add_token("; ") elif isinstance(semicolon, Semicolon): semicolon._codegen(state) # pyre-fixme[13]: Attribute `body` is never initialized. ParserConfig = config_mod.ParserConfig class WithLeadingWhitespace(Generic[_T]): value: _T whitespace_before: WhitespaceState parse_simple_whitespace = mod.parse_simple_whitespace def convert_global_stmt(config: ParserConfig, children: Sequence[Any]) -> Any: (global_token, *names) = children return WithLeadingWhitespace( Global( names=tuple(_construct_nameitems(config, names)), whitespace_after_global=parse_simple_whitespace( config, names[0].whitespace_before ), ), global_token.whitespace_before, )
null
4,850
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_whitespace, ) def _construct_nameitems(config: ParserConfig, names: Sequence[Any]) -> List[NameItem]: nameitems: List[NameItem] = [] for name, maybe_comma in grouper(names, 2): if maybe_comma is None: nameitems.append(NameItem(Name(name.string))) else: nameitems.append( NameItem( Name(name.string), comma=Comma( whitespace_before=parse_simple_whitespace( config, maybe_comma.whitespace_before ), whitespace_after=parse_simple_whitespace( config, maybe_comma.whitespace_after ), ), ) ) return nameitems class Nonlocal(BaseSmallStatement): """ A ``nonlocal`` statement. """ #: A list of one or more names. names: Sequence[NameItem] #: Whitespace appearing after the ``global`` keyword and before the first name. whitespace_after_nonlocal: SimpleWhitespace = SimpleWhitespace.field(" ") #: 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 _validate(self) -> None: if len(self.names) == 0: raise CSTValidationError( "A Nonlocal statement must have at least one NameItem." ) if self.names[-1].comma != MaybeSentinel.DEFAULT: raise CSTValidationError( "The last NameItem in a Nonlocal cannot have a trailing comma." ) if self.whitespace_after_nonlocal.empty: raise CSTValidationError( "Must have at least one space after 'nonlocal' keyword." ) def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Nonlocal": return Nonlocal( whitespace_after_nonlocal=visit_required( self, "whitespace_after_nonlocal", self.whitespace_after_nonlocal, visitor, ), names=visit_sequence(self, "names", self.names, 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): state.add_token("nonlocal") self.whitespace_after_nonlocal._codegen(state) last_name = len(self.names) - 1 for i, name in enumerate(self.names): name._codegen(state, default_comma=(i != last_name)) semicolon = self.semicolon if isinstance(semicolon, MaybeSentinel): if default_semicolon: state.add_token("; ") elif isinstance(semicolon, Semicolon): semicolon._codegen(state) # pyre-fixme[13]: Attribute `body` is never initialized. ParserConfig = config_mod.ParserConfig class WithLeadingWhitespace(Generic[_T]): value: _T whitespace_before: WhitespaceState parse_simple_whitespace = mod.parse_simple_whitespace def convert_nonlocal_stmt(config: ParserConfig, children: Sequence[Any]) -> Any: (nonlocal_token, *names) = children return WithLeadingWhitespace( Nonlocal( names=tuple(_construct_nameitems(config, names)), whitespace_after_nonlocal=parse_simple_whitespace( config, names[0].whitespace_before ), ), nonlocal_token.whitespace_before, )
null
4,851
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_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 "," class Assert(BaseSmallStatement): """ An assert statement such as ``assert x > 5`` or ``assert x > 5, 'Uh oh!'`` """ #: The test we are going to assert on. test: BaseExpression #: The optional message to display if the test evaluates to a falsey value. msg: Optional[BaseExpression] = None #: A comma separating test and message, if there is a message. comma: Union[Comma, MaybeSentinel] = MaybeSentinel.DEFAULT #: Whitespace appearing after the ``assert`` keyword and before the test. whitespace_after_assert: SimpleWhitespace = SimpleWhitespace.field(" ") #: 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 _validate(self) -> None: # Validate whitespace if ( self.whitespace_after_assert.empty and not self.test._safe_to_use_with_word_operator(ExpressionPosition.RIGHT) ): raise CSTValidationError("Must have at least one space after 'assert'.") # Validate comma rules if self.msg is None and isinstance(self.comma, Comma): raise CSTValidationError("Cannot have trailing comma after 'test'.") def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Assert": return Assert( whitespace_after_assert=visit_required( self, "whitespace_after_assert", self.whitespace_after_assert, visitor ), test=visit_required(self, "test", self.test, visitor), comma=visit_sentinel(self, "comma", self.comma, visitor), msg=visit_optional(self, "msg", self.msg, 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): state.add_token("assert") self.whitespace_after_assert._codegen(state) self.test._codegen(state) comma = self.comma msg = self.msg if isinstance(comma, MaybeSentinel): if msg is not None: state.add_token(", ") else: comma._codegen(state) if msg is not None: msg._codegen(state) semicolon = self.semicolon if isinstance(semicolon, MaybeSentinel): if default_semicolon: state.add_token("; ") elif isinstance(semicolon, Semicolon): semicolon._codegen(state) # pyre-fixme[13]: Attribute `body` is never initialized. ParserConfig = config_mod.ParserConfig class WithLeadingWhitespace(Generic[_T]): value: _T whitespace_before: WhitespaceState parse_simple_whitespace = mod.parse_simple_whitespace def convert_assert_stmt(config: ParserConfig, children: Sequence[Any]) -> Any: if len(children) == 2: (assert_token, test) = children assert_node = Assert( whitespace_after_assert=parse_simple_whitespace( config, test.whitespace_before ), test=test.value, msg=None, ) else: (assert_token, test, comma_token, msg) = children assert_node = Assert( whitespace_after_assert=parse_simple_whitespace( config, test.whitespace_before ), test=test.value, comma=Comma( whitespace_before=parse_simple_whitespace( config, comma_token.whitespace_before ), whitespace_after=parse_simple_whitespace(config, msg.whitespace_before), ), msg=msg.value, ) return WithLeadingWhitespace(assert_node, assert_token.whitespace_before)
null
4,852
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_whitespace, ) ParserConfig = config_mod.ParserConfig def convert_compound_stmt(config: ParserConfig, children: Sequence[Any]) -> Any: (stmt,) = children return stmt
null
4,853
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_whitespace, ) def convert_if_stmt(config: ParserConfig, children: Sequence[Any]) -> Any: if_tok, test, colon_tok, suite, *tail = children if len(tail) > 0: (orelse,) = tail else: orelse = None return If( leading_lines=parse_empty_lines(config, if_tok.whitespace_before), whitespace_before_test=parse_simple_whitespace(config, if_tok.whitespace_after), test=test.value, whitespace_after_test=parse_simple_whitespace( config, colon_tok.whitespace_before ), body=suite, orelse=orelse, ) "if_stmt_elif", "'elif' test ':' suite [if_stmt_elif|if_stmt_else]", version="<=3.7" ParserConfig = config_mod.ParserConfig def convert_if_stmt_elif(config: ParserConfig, children: Sequence[Any]) -> Any: # this behaves exactly the same as `convert_if_stmt`, except that the leading token # has a different string value. return convert_if_stmt(config, children)
null
4,854
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_whitespace, ) class Else(CSTNode): def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Else": def _codegen_impl(self, state: CodegenState) -> None: # pyre-fixme[13]: Attribute `body` is never initialized. ParserConfig = config_mod.ParserConfig parse_simple_whitespace = mod.parse_simple_whitespace parse_empty_lines = mod.parse_empty_lines def convert_if_stmt_else(config: ParserConfig, children: Sequence[Any]) -> Any: else_tok, colon_tok, suite = children return Else( leading_lines=parse_empty_lines(config, else_tok.whitespace_before), whitespace_before_colon=parse_simple_whitespace( config, colon_tok.whitespace_before ), body=suite, )
null
4,855
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_whitespace, ) class Else(CSTNode): """ An ``else`` clause that appears optionally after an :class:`If`, :class:`While`, :class:`Try`, or :class:`For` statement. This node does not match ``elif`` clauses in :class:`If` statements. It also does not match the required ``else`` clause in an :class:`IfExp` expression (``a = if b else c``). """ #: The body of else clause. body: BaseSuite #: Sequence of empty lines appearing before this compound statement line. leading_lines: Sequence[EmptyLine] = () #: The whitespace appearing after the ``else`` keyword but before the colon. whitespace_before_colon: SimpleWhitespace = SimpleWhitespace.field("") def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Else": return Else( leading_lines=visit_sequence( self, "leading_lines", self.leading_lines, visitor ), whitespace_before_colon=visit_required( self, "whitespace_before_colon", self.whitespace_before_colon, visitor ), body=visit_required(self, "body", self.body, visitor), ) def _codegen_impl(self, state: CodegenState) -> None: for ll in self.leading_lines: ll._codegen(state) state.add_indent_tokens() with state.record_syntactic_position(self, end_node=self.body): state.add_token("else") self.whitespace_before_colon._codegen(state) state.add_token(":") self.body._codegen(state) class While(BaseCompoundStatement): """ A ``while`` statement. """ #: The test we will loop against. test: BaseExpression #: The suite that is wrapped with this statement. body: BaseSuite #: An optional else case which will be executed if there is no #: :class:`Break` statement encountered while looping. orelse: Optional[Else] = None #: Sequence of empty lines appearing before this while statement. leading_lines: Sequence[EmptyLine] = () #: Whitespace after the ``while`` keyword and before the test. whitespace_after_while: SimpleWhitespace = SimpleWhitespace.field(" ") #: Whitespace after the test and before the colon. whitespace_before_colon: SimpleWhitespace = SimpleWhitespace.field("") def _validate(self) -> None: if ( self.whitespace_after_while.empty and not self.test._safe_to_use_with_word_operator(ExpressionPosition.RIGHT) ): raise CSTValidationError( "Must have at least one space after 'while' keyword." ) def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "While": return While( leading_lines=visit_sequence( self, "leading_lines", self.leading_lines, visitor ), whitespace_after_while=visit_required( self, "whitespace_after_while", self.whitespace_after_while, visitor ), test=visit_required(self, "test", self.test, visitor), whitespace_before_colon=visit_required( self, "whitespace_before_colon", self.whitespace_before_colon, visitor ), body=visit_required(self, "body", self.body, visitor), orelse=visit_optional(self, "orelse", self.orelse, visitor), ) def _codegen_impl(self, state: CodegenState) -> None: for ll in self.leading_lines: ll._codegen(state) state.add_indent_tokens() end_node = self.body if self.orelse is None else self.orelse with state.record_syntactic_position(self, end_node=end_node): state.add_token("while") self.whitespace_after_while._codegen(state) self.test._codegen(state) self.whitespace_before_colon._codegen(state) state.add_token(":") self.body._codegen(state) orelse = self.orelse if orelse is not None: orelse._codegen(state) # pyre-fixme[13]: Attribute `body` is never initialized. ParserConfig = config_mod.ParserConfig parse_simple_whitespace = mod.parse_simple_whitespace parse_empty_lines = mod.parse_empty_lines def convert_while_stmt(config: ParserConfig, children: Sequence[Any]) -> Any: while_token, test, while_colon_token, while_suite, *else_block = children if len(else_block) > 0: (else_token, else_colon_token, else_suite) = else_block orelse = Else( leading_lines=parse_empty_lines(config, else_token.whitespace_before), whitespace_before_colon=parse_simple_whitespace( config, else_colon_token.whitespace_before ), body=else_suite, ) else: orelse = None return While( leading_lines=parse_empty_lines(config, while_token.whitespace_before), whitespace_after_while=parse_simple_whitespace( config, while_token.whitespace_after ), test=test.value, whitespace_before_colon=parse_simple_whitespace( config, while_colon_token.whitespace_before ), body=while_suite, orelse=orelse, )
null
4,856
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_whitespace, ) class Else(CSTNode): def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Else": def _codegen_impl(self, state: CodegenState) -> None: class For(BaseCompoundStatement): def _validate(self) -> None: def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "For": def _codegen_impl(self, state: CodegenState) -> None: # pyre-fixme[13]: Attribute `body` is never initialized. ParserConfig = config_mod.ParserConfig class WithLeadingWhitespace(Generic[_T]): parse_simple_whitespace = mod.parse_simple_whitespace parse_empty_lines = mod.parse_empty_lines def convert_for_stmt(config: ParserConfig, children: Sequence[Any]) -> Any: ( for_token, expr, in_token, test, for_colon_token, for_suite, *else_block, ) = children if len(else_block) > 0: (else_token, else_colon_token, else_suite) = else_block orelse = Else( leading_lines=parse_empty_lines(config, else_token.whitespace_before), whitespace_before_colon=parse_simple_whitespace( config, else_colon_token.whitespace_before ), body=else_suite, ) else: orelse = None return WithLeadingWhitespace( For( whitespace_after_for=parse_simple_whitespace( config, for_token.whitespace_after ), target=expr.value, whitespace_before_in=parse_simple_whitespace( config, in_token.whitespace_before ), whitespace_after_in=parse_simple_whitespace( config, in_token.whitespace_after ), iter=test.value, whitespace_before_colon=parse_simple_whitespace( config, for_colon_token.whitespace_before ), body=for_suite, orelse=orelse, ), for_token.whitespace_before, )
null
4,857
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_whitespace, ) class Else(CSTNode): """ An ``else`` clause that appears optionally after an :class:`If`, :class:`While`, :class:`Try`, or :class:`For` statement. This node does not match ``elif`` clauses in :class:`If` statements. It also does not match the required ``else`` clause in an :class:`IfExp` expression (``a = if b else c``). """ #: The body of else clause. body: BaseSuite #: Sequence of empty lines appearing before this compound statement line. leading_lines: Sequence[EmptyLine] = () #: The whitespace appearing after the ``else`` keyword but before the colon. whitespace_before_colon: SimpleWhitespace = SimpleWhitespace.field("") def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Else": return Else( leading_lines=visit_sequence( self, "leading_lines", self.leading_lines, visitor ), whitespace_before_colon=visit_required( self, "whitespace_before_colon", self.whitespace_before_colon, visitor ), body=visit_required(self, "body", self.body, visitor), ) def _codegen_impl(self, state: CodegenState) -> None: for ll in self.leading_lines: ll._codegen(state) state.add_indent_tokens() with state.record_syntactic_position(self, end_node=self.body): state.add_token("else") self.whitespace_before_colon._codegen(state) state.add_token(":") self.body._codegen(state) class ExceptHandler(CSTNode): """ An ``except`` clause that appears optionally after a :class:`Try` statement. """ #: The body of the except. body: BaseSuite #: The type of exception this catches. Can be a tuple in some cases, #: or ``None`` if the code is catching all exceptions. type: Optional[BaseExpression] = None #: The optional name that a caught exception is assigned to. name: Optional[AsName] = None #: Sequence of empty lines appearing before this compound statement line. leading_lines: Sequence[EmptyLine] = () #: The whitespace between the ``except`` keyword and the type attribute. whitespace_after_except: SimpleWhitespace = SimpleWhitespace.field(" ") #: The whitespace after any type or name node (whichever comes last) and #: the colon. whitespace_before_colon: SimpleWhitespace = SimpleWhitespace.field("") def _validate(self) -> None: name = self.name if self.type is None and name is not None: raise CSTValidationError("Cannot have a name for an empty type.") if name is not None and not isinstance(name.name, Name): raise CSTValidationError( "Must use a Name node for AsName name inside ExceptHandler." ) type_ = self.type if type_ is not None and self.whitespace_after_except.empty: # Space is only required when the first char in `type` could start # an identifier. In the most common cases, we want to allow # grouping or tuple parens. if isinstance(type_, Name) and not type_.lpar: raise CSTValidationError( "Must have at least one space after except when ExceptHandler has a type." ) name = self.name if ( type_ is not None and name is not None and name.whitespace_before_as.empty and not type_._safe_to_use_with_word_operator(ExpressionPosition.LEFT) ): raise CSTValidationError( "Must have at least one space before as keyword in an except handler." ) def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "ExceptHandler": return ExceptHandler( leading_lines=visit_sequence( self, "leading_lines", self.leading_lines, visitor ), whitespace_after_except=visit_required( self, "whitespace_after_except", self.whitespace_after_except, visitor ), type=visit_optional(self, "type", self.type, visitor), name=visit_optional(self, "name", self.name, visitor), whitespace_before_colon=visit_required( self, "whitespace_before_colon", self.whitespace_before_colon, visitor ), body=visit_required(self, "body", self.body, visitor), ) def _codegen_impl(self, state: CodegenState) -> None: for ll in self.leading_lines: ll._codegen(state) state.add_indent_tokens() with state.record_syntactic_position(self, end_node=self.body): state.add_token("except") self.whitespace_after_except._codegen(state) typenode = self.type if typenode is not None: typenode._codegen(state) namenode = self.name if namenode is not None: namenode._codegen(state) self.whitespace_before_colon._codegen(state) state.add_token(":") self.body._codegen(state) class Finally(CSTNode): """ A ``finally`` clause that appears optionally after a :class:`Try` statement. """ #: The body of the except. body: BaseSuite #: Sequence of empty lines appearing before this compound statement line. leading_lines: Sequence[EmptyLine] = () #: The whitespace that appears after the ``finally`` keyword but before #: the colon. whitespace_before_colon: SimpleWhitespace = SimpleWhitespace.field("") def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Finally": return Finally( leading_lines=visit_sequence( self, "leading_lines", self.leading_lines, visitor ), whitespace_before_colon=visit_required( self, "whitespace_before_colon", self.whitespace_before_colon, visitor ), body=visit_required(self, "body", self.body, visitor), ) def _codegen_impl(self, state: CodegenState) -> None: for ll in self.leading_lines: ll._codegen(state) state.add_indent_tokens() with state.record_syntactic_position(self, end_node=self.body): state.add_token("finally") self.whitespace_before_colon._codegen(state) state.add_token(":") self.body._codegen(state) class Try(BaseCompoundStatement): """ A regular ``try`` statement that cannot contain :class:`ExceptStar` blocks. For ``try`` statements that can contain :class:`ExceptStar` blocks, see :class:`TryStar`. """ #: The suite that is wrapped with a try statement. body: BaseSuite #: A list of zero or more exception handlers. handlers: Sequence[ExceptHandler] = () #: An optional else case. orelse: Optional[Else] = None #: An optional finally case. finalbody: Optional[Finally] = None #: Sequence of empty lines appearing before this compound statement line. leading_lines: Sequence[EmptyLine] = () #: The whitespace that appears after the ``try`` keyword but before #: the colon. whitespace_before_colon: SimpleWhitespace = SimpleWhitespace.field("") def _validate(self) -> None: if len(self.handlers) == 0 and self.finalbody is None: raise CSTValidationError( "A Try statement must have at least one ExceptHandler or Finally" ) if len(self.handlers) == 0 and self.orelse is not None: raise CSTValidationError( "A Try statement must have at least one ExceptHandler in order " + "to have an Else." ) # Check bare excepts are always at the last position if any(handler.type is None for handler in self.handlers[:-1]): raise CSTValidationError("The bare except: handler must be the last one.") def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Try": return Try( leading_lines=visit_sequence( self, "leading_lines", self.leading_lines, visitor ), whitespace_before_colon=visit_required( self, "whitespace_before_colon", self.whitespace_before_colon, visitor ), body=visit_required(self, "body", self.body, visitor), handlers=visit_sequence(self, "handlers", self.handlers, visitor), orelse=visit_optional(self, "orelse", self.orelse, visitor), finalbody=visit_optional(self, "finalbody", self.finalbody, visitor), ) def _codegen_impl(self, state: CodegenState) -> None: for ll in self.leading_lines: ll._codegen(state) state.add_indent_tokens() end_node = self.body if len(self.handlers) > 0: end_node = self.handlers[-1] orelse = self.orelse end_node = end_node if orelse is None else orelse finalbody = self.finalbody end_node = end_node if finalbody is None else finalbody with state.record_syntactic_position(self, end_node=end_node): state.add_token("try") self.whitespace_before_colon._codegen(state) state.add_token(":") self.body._codegen(state) for handler in self.handlers: handler._codegen(state) if orelse is not None: orelse._codegen(state) if finalbody is not None: finalbody._codegen(state) # pyre-fixme[13]: Attribute `body` is never initialized. 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 ExceptClausePartial: leading_lines: Sequence[EmptyLine] whitespace_after_except: SimpleWhitespace type: Optional[BaseExpression] = None name: Optional[AsName] = None parse_simple_whitespace = mod.parse_simple_whitespace parse_empty_lines = mod.parse_empty_lines def convert_try_stmt(config: ParserConfig, children: Sequence[Any]) -> Any: trytoken, try_colon_token, try_suite, *rest = children handlers: List[ExceptHandler] = [] orelse: Optional[Else] = None finalbody: Optional[Finally] = None for clause, colon_token, suite in grouper(rest, 3): if isinstance(clause, Token): if clause.string == "else": if orelse is not None: raise Exception("Logic error!") orelse = Else( leading_lines=parse_empty_lines(config, clause.whitespace_before), whitespace_before_colon=parse_simple_whitespace( config, colon_token.whitespace_before ), body=suite, ) elif clause.string == "finally": if finalbody is not None: raise Exception("Logic error!") finalbody = Finally( leading_lines=parse_empty_lines(config, clause.whitespace_before), whitespace_before_colon=parse_simple_whitespace( config, colon_token.whitespace_before ), body=suite, ) else: raise Exception("Logic error!") elif isinstance(clause, ExceptClausePartial): handlers.append( ExceptHandler( body=suite, type=clause.type, name=clause.name, leading_lines=clause.leading_lines, whitespace_after_except=clause.whitespace_after_except, whitespace_before_colon=parse_simple_whitespace( config, colon_token.whitespace_before ), ) ) else: raise Exception("Logic error!") return Try( leading_lines=parse_empty_lines(config, trytoken.whitespace_before), whitespace_before_colon=parse_simple_whitespace( config, try_colon_token.whitespace_before ), body=try_suite, handlers=tuple(handlers), orelse=orelse, finalbody=finalbody, )
null
4,858
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_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 AsName(CSTNode): """ An ``as name`` clause inside an :class:`ExceptHandler`, :class:`ImportAlias` or :class:`WithItem` node. """ #: Identifier that the parent node will be aliased to. name: Union[Name, Tuple, List] #: Whitespace between the parent node and the ``as`` keyword. whitespace_before_as: BaseParenthesizableWhitespace = SimpleWhitespace.field(" ") #: Whitespace between the ``as`` keyword and the name. whitespace_after_as: BaseParenthesizableWhitespace = SimpleWhitespace.field(" ") def _validate(self) -> None: if ( self.whitespace_after_as.empty and not self.name._safe_to_use_with_word_operator(ExpressionPosition.RIGHT) ): raise CSTValidationError( "There must be at least one space between 'as' and name." ) def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "AsName": return AsName( whitespace_before_as=visit_required( self, "whitespace_before_as", self.whitespace_before_as, visitor ), name=visit_required(self, "name", self.name, visitor), whitespace_after_as=visit_required( self, "whitespace_after_as", self.whitespace_after_as, visitor ), ) def _codegen_impl(self, state: CodegenState) -> None: self.whitespace_before_as._codegen(state) state.add_token("as") self.whitespace_after_as._codegen(state) self.name._codegen(state) # pyre-fixme[13]: Attribute `body` is never initialized. class SimpleWhitespace(BaseParenthesizableWhitespace, BaseValueToken): """ This is the kind of whitespace you might see inside the body of a statement or expression between two tokens. This is the most common type of whitespace. A simple whitespace cannot contain a newline character unless it is directly preceeded by a line continuation character (``\\``). It can contain zero or more spaces or tabs. If you need a newline character without a line continuation character, use :class:`ParenthesizedWhitespace` instead. Simple whitespace is often non-semantic (optional), but in cases where whitespace solves a grammar ambiguity between tokens (e.g. ``if test``, versus ``iftest``), it has some semantic value. An example :class:`SimpleWhitespace` containing a space, a line continuation, a newline and another space is as follows:: SimpleWhitespace(r" \\\\n ") """ #: Actual string value of the simple whitespace. A legal value contains only #: space, ``\f`` and ``\t`` characters, and optionally a continuation #: (``\``) followed by a newline (``\n`` or ``\r\n``). value: str def _validate(self) -> None: if SIMPLE_WHITESPACE_RE.fullmatch(self.value) is None: raise CSTValidationError( f"Got non-whitespace value for whitespace node: {repr(self.value)}" ) def empty(self) -> bool: """ Indicates that this node is empty (zero whitespace characters). """ return len(self.value) == 0 ParserConfig = config_mod.ParserConfig class ExceptClausePartial: leading_lines: Sequence[EmptyLine] whitespace_after_except: SimpleWhitespace type: Optional[BaseExpression] = None name: Optional[AsName] = None parse_simple_whitespace = mod.parse_simple_whitespace parse_empty_lines = mod.parse_empty_lines def convert_except_clause(config: ParserConfig, children: Sequence[Any]) -> Any: if len(children) == 1: (except_token,) = children whitespace_after_except = SimpleWhitespace("") test = None name = None elif len(children) == 2: (except_token, test_node) = children whitespace_after_except = parse_simple_whitespace( config, except_token.whitespace_after ) test = test_node.value name = None else: (except_token, test_node, as_token, name_token) = children whitespace_after_except = parse_simple_whitespace( config, except_token.whitespace_after ) test = test_node.value name = AsName( whitespace_before_as=parse_simple_whitespace( config, as_token.whitespace_before ), whitespace_after_as=parse_simple_whitespace( config, as_token.whitespace_after ), name=Name(name_token.string), ) return ExceptClausePartial( leading_lines=parse_empty_lines(config, except_token.whitespace_before), whitespace_after_except=whitespace_after_except, type=test, name=name, )
null
4,859
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_whitespace, ) class Comma(_BaseOneTokenOp): def _get_token(self) -> str: class WithItem(CSTNode): def _validate(self) -> None: def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "WithItem": def _codegen_impl(self, state: CodegenState, default_comma: bool = False) -> None: class With(BaseCompoundStatement): def _validate_parens(self) -> None: def _validate(self) -> None: def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "With": def _codegen_impl(self, state: CodegenState) -> None: # pyre-fixme[13]: Attribute `body` is never initialized. def grouper(iterable: Iterable[_T], n: int, fillvalue: _T = None) -> Iterator[_T]: ParserConfig = config_mod.ParserConfig class WithLeadingWhitespace(Generic[_T]): parse_simple_whitespace = mod.parse_simple_whitespace parse_parenthesizable_whitespace = mod.parse_parenthesizable_whitespace def convert_with_stmt(config: ParserConfig, children: Sequence[Any]) -> Any: (with_token, *items, colon_token, suite) = children item_nodes: List[WithItem] = [] for with_item, maybe_comma in grouper(items, 2): if maybe_comma is not None: item_nodes.append( with_item.with_changes( comma=Comma( whitespace_before=parse_parenthesizable_whitespace( config, maybe_comma.whitespace_before ), whitespace_after=parse_parenthesizable_whitespace( config, maybe_comma.whitespace_after ), ) ) ) else: item_nodes.append(with_item) return WithLeadingWhitespace( With( whitespace_after_with=parse_simple_whitespace( config, with_token.whitespace_after ), items=tuple(item_nodes), whitespace_before_colon=parse_simple_whitespace( config, colon_token.whitespace_before ), body=suite, ), with_token.whitespace_before, )
null
4,860
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_whitespace, ) class AsName(CSTNode): """ An ``as name`` clause inside an :class:`ExceptHandler`, :class:`ImportAlias` or :class:`WithItem` node. """ #: Identifier that the parent node will be aliased to. name: Union[Name, Tuple, List] #: Whitespace between the parent node and the ``as`` keyword. whitespace_before_as: BaseParenthesizableWhitespace = SimpleWhitespace.field(" ") #: Whitespace between the ``as`` keyword and the name. whitespace_after_as: BaseParenthesizableWhitespace = SimpleWhitespace.field(" ") def _validate(self) -> None: if ( self.whitespace_after_as.empty and not self.name._safe_to_use_with_word_operator(ExpressionPosition.RIGHT) ): raise CSTValidationError( "There must be at least one space between 'as' and name." ) def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "AsName": return AsName( whitespace_before_as=visit_required( self, "whitespace_before_as", self.whitespace_before_as, visitor ), name=visit_required(self, "name", self.name, visitor), whitespace_after_as=visit_required( self, "whitespace_after_as", self.whitespace_after_as, visitor ), ) def _codegen_impl(self, state: CodegenState) -> None: self.whitespace_before_as._codegen(state) state.add_token("as") self.whitespace_after_as._codegen(state) self.name._codegen(state) class WithItem(CSTNode): """ A single context manager in a :class:`With` block, with an optional variable name. """ #: Expression that evaluates to a context manager. item: BaseExpression #: Variable to assign the context manager to, if it is needed in the #: :class:`With` body. asname: Optional[AsName] = None #: This is forbidden for the last :class:`WithItem` in a :class:`With`, but all #: other items inside a with block must contain a comma to separate them. comma: Union[Comma, MaybeSentinel] = MaybeSentinel.DEFAULT def _validate(self) -> None: asname = self.asname if ( asname is not None and asname.whitespace_before_as.empty and not self.item._safe_to_use_with_word_operator(ExpressionPosition.LEFT) ): raise CSTValidationError("Must have at least one space before as keyword.") def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "WithItem": return WithItem( item=visit_required(self, "item", self.item, visitor), asname=visit_optional(self, "asname", self.asname, 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.item._codegen(state) asname = self.asname if asname is not None: asname._codegen(state) comma = self.comma if comma is MaybeSentinel.DEFAULT and default_comma: state.add_token(", ") elif isinstance(comma, Comma): comma._codegen(state) # pyre-fixme[13]: Attribute `body` is never initialized. ParserConfig = config_mod.ParserConfig parse_simple_whitespace = mod.parse_simple_whitespace def convert_with_item(config: ParserConfig, children: Sequence[Any]) -> Any: if len(children) == 3: (test, as_token, expr_node) = children test_node = test.value asname = AsName( whitespace_before_as=parse_simple_whitespace( config, as_token.whitespace_before ), whitespace_after_as=parse_simple_whitespace( config, as_token.whitespace_after ), name=expr_node.value, ) else: (test,) = children test_node = test.value asname = None return WithItem(item=test_node, asname=asname)
null
4,861
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_whitespace, ) def _extract_async( config: ParserConfig, children: Sequence[Any] ) -> Tuple[List[EmptyLine], Optional[Asynchronous], Any]: if len(children) == 1: (stmt,) = children whitespace_before = stmt.whitespace_before asyncnode = None else: asynctoken, stmt = children whitespace_before = asynctoken.whitespace_before asyncnode = Asynchronous( whitespace_after=parse_simple_whitespace( config, asynctoken.whitespace_after ) ) return (parse_empty_lines(config, whitespace_before), asyncnode, stmt.value) ParserConfig = config_mod.ParserConfig def convert_asyncable_funcdef(config: ParserConfig, children: Sequence[Any]) -> Any: leading_lines, asyncnode, funcdef = _extract_async(config, children) return funcdef.with_changes( asynchronous=asyncnode, leading_lines=leading_lines, lines_after_decorators=() )
null
4,862
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_whitespace, ) class MaybeSentinel(Enum): def __repr__(self) -> str: class Name(BaseAssignTargetExpression, BaseDelTargetExpression): def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Name": def _validate(self) -> None: def _codegen_impl(self, state: CodegenState) -> None: class Param(CSTNode): def _validate(self) -> None: def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Param": def _codegen_impl( self, state: CodegenState, default_star: Optional[str] = None, default_comma: bool = False, ) -> None: class FunctionDef(BaseCompoundStatement): def _validate(self) -> None: def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "FunctionDef": def _codegen_impl(self, state: CodegenState) -> None: def get_docstring(self, clean: bool = True) -> Optional[str]: # pyre-fixme[13]: Attribute `body` is never initialized. ParserConfig = config_mod.ParserConfig class WithLeadingWhitespace(Generic[_T]): parse_simple_whitespace = mod.parse_simple_whitespace def convert_funcdef(config: ParserConfig, children: Sequence[Any]) -> Any: defnode, namenode, param_partial, *annotation, colon, suite = children # If the trailing paremeter doesn't have a comma, then it owns the trailing # whitespace before the rpar. Otherwise, the comma owns it (and will have # already parsed it). We don't check/update ParamStar because if it exists # then we are guaranteed have at least one kwonly_param. parameters = param_partial.params if parameters.star_kwarg is not None: if parameters.star_kwarg.comma == MaybeSentinel.DEFAULT: parameters = parameters.with_changes( star_kwarg=parameters.star_kwarg.with_changes( whitespace_after_param=param_partial.rpar.whitespace_before ) ) elif parameters.kwonly_params: if parameters.kwonly_params[-1].comma == MaybeSentinel.DEFAULT: parameters = parameters.with_changes( kwonly_params=( *parameters.kwonly_params[:-1], parameters.kwonly_params[-1].with_changes( whitespace_after_param=param_partial.rpar.whitespace_before ), ) ) elif isinstance(parameters.star_arg, Param): if parameters.star_arg.comma == MaybeSentinel.DEFAULT: parameters = parameters.with_changes( star_arg=parameters.star_arg.with_changes( whitespace_after_param=param_partial.rpar.whitespace_before ) ) elif parameters.params: if parameters.params[-1].comma == MaybeSentinel.DEFAULT: parameters = parameters.with_changes( params=( *parameters.params[:-1], parameters.params[-1].with_changes( whitespace_after_param=param_partial.rpar.whitespace_before ), ) ) return WithLeadingWhitespace( FunctionDef( whitespace_after_def=parse_simple_whitespace( config, defnode.whitespace_after ), name=Name(namenode.string), whitespace_after_name=parse_simple_whitespace( config, namenode.whitespace_after ), whitespace_before_params=param_partial.lpar.whitespace_after, params=parameters, returns=None if not annotation else annotation[0], whitespace_before_colon=parse_simple_whitespace( config, colon.whitespace_before ), body=suite, ), defnode.whitespace_before, )
null
4,863
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_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 Parameters(CSTNode): """ A function or lambda parameter list. """ #: Positional parameters, with or without defaults. Positional parameters #: with defaults must all be after those without defaults. params: Sequence[Param] = () # Optional parameter that captures unspecified positional arguments or a sentinel # star that dictates parameters following are kwonly args. star_arg: Union[Param, ParamStar, MaybeSentinel] = MaybeSentinel.DEFAULT #: Keyword-only params that may or may not have defaults. kwonly_params: Sequence[Param] = () #: Optional parameter that captures unspecified kwargs. star_kwarg: Optional[Param] = None #: Positional-only parameters, with or without defaults. Positional-only #: parameters with defaults must all be after those without defaults. posonly_params: Sequence[Param] = () #: Optional sentinel that dictates parameters preceeding are positional-only #: args. posonly_ind: Union[ParamSlash, MaybeSentinel] = MaybeSentinel.DEFAULT def _validate_stars_sequence(self, vals: Sequence[Param], *, section: str) -> None: if len(vals) == 0: return for val in vals: if isinstance(val.star, str) and val.star != "": raise CSTValidationError( f"Expecting a star prefix of '' for {section} Param." ) def _validate_posonly_ind(self) -> None: if isinstance(self.posonly_ind, ParamSlash) and len(self.posonly_params) == 0: raise CSTValidationError( "Must have at least one posonly param if ParamSlash is used." ) def _validate_kwonly_star(self) -> None: if isinstance(self.star_arg, ParamStar) and len(self.kwonly_params) == 0: raise CSTValidationError( "Must have at least one kwonly param if ParamStar is used." ) def _validate_defaults(self) -> None: seen_default = False # pyre-fixme[60]: Concatenation not yet support for multiple variadic # tuples: `*self.posonly_params, *self.params`. for param in (*self.posonly_params, *self.params): if param.default: # Mark that we've moved onto defaults if not seen_default: seen_default = True else: if seen_default: # We accidentally included a non-default after a default arg! raise CSTValidationError( "Cannot have param without defaults following a param with defaults." ) star_arg = self.star_arg if isinstance(star_arg, Param) and star_arg.default is not None: raise CSTValidationError("Cannot have default for star_arg.") star_kwarg = self.star_kwarg if star_kwarg is not None and star_kwarg.default is not None: raise CSTValidationError("Cannot have default for star_kwarg.") def _validate_stars(self) -> None: if len(self.params) > 0: self._validate_stars_sequence(self.params, section="params") if len(self.posonly_params) > 0: self._validate_stars_sequence(self.posonly_params, section="posonly_params") star_arg = self.star_arg if ( isinstance(star_arg, Param) and isinstance(star_arg.star, str) and star_arg.star != "*" ): raise CSTValidationError( "Expecting a star prefix of '*' for star_arg Param." ) if len(self.kwonly_params) > 0: self._validate_stars_sequence(self.kwonly_params, section="kwonly_params") star_kwarg = self.star_kwarg if ( star_kwarg is not None and isinstance(star_kwarg.star, str) and star_kwarg.star != "**" ): raise CSTValidationError( "Expecting a star prefix of '**' for star_kwarg Param." ) def _validate(self) -> None: # Validate posonly_params slash placement semantics. self._validate_posonly_ind() # Validate kwonly_param star placement semantics. self._validate_kwonly_star() # Validate defaults semantics for params and star_arg/star_kwarg. self._validate_defaults() # Validate that we don't have random stars on non star_kwarg. self._validate_stars() def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Parameters": return Parameters( posonly_params=visit_sequence( self, "posonly_params", self.posonly_params, visitor ), posonly_ind=visit_sentinel(self, "posonly_ind", self.posonly_ind, visitor), params=visit_sequence(self, "params", self.params, visitor), star_arg=visit_sentinel(self, "star_arg", self.star_arg, visitor), kwonly_params=visit_sequence( self, "kwonly_params", self.kwonly_params, visitor ), star_kwarg=visit_optional(self, "star_kwarg", self.star_kwarg, visitor), ) def _safe_to_join_with_lambda(self) -> bool: """ Determine if Parameters need a space after the `lambda` keyword. Returns True iff it's safe to omit the space between `lambda` and these Parameters. See also `BaseExpression._safe_to_use_with_word_operator`. For example: `lambda*_: pass` """ if len(self.posonly_params) != 0: return False # posonly_ind can't appear if above condition is false if len(self.params) > 0 and self.params[0].star not in {"*", "**"}: return False return True def _codegen_impl(self, state: CodegenState) -> None: # noqa: C901 # Compute the star existence first so we can ask about whether # each element is the last in the list or not. star_arg = self.star_arg if isinstance(star_arg, MaybeSentinel): starincluded = len(self.kwonly_params) > 0 elif isinstance(star_arg, (Param, ParamStar)): starincluded = True else: starincluded = False # Render out the positional-only params first. They will always have trailing # commas because in order to have positional-only params, there must be a # slash afterwards. for i, param in enumerate(self.posonly_params): param._codegen(state, default_star="", default_comma=True) # Render out the positional-only indicator if necessary. more_values = ( starincluded or len(self.params) > 0 or len(self.kwonly_params) > 0 or self.star_kwarg is not None ) posonly_ind = self.posonly_ind if isinstance(posonly_ind, ParamSlash): # Its explicitly included, so render the version we have here which # might have spacing applied to its comma. posonly_ind._codegen(state, default_comma=more_values) elif len(self.posonly_params) > 0: if more_values: state.add_token("/, ") else: state.add_token("/") # Render out the params next, computing necessary trailing commas. lastparam = len(self.params) - 1 more_values = ( starincluded or len(self.kwonly_params) > 0 or self.star_kwarg is not None ) for i, param in enumerate(self.params): param._codegen( state, default_star="", default_comma=(i < lastparam or more_values) ) # Render out optional star sentinel if its explicitly included or # if we are inferring it from kwonly_params. Otherwise, render out the # optional star_arg. if isinstance(star_arg, MaybeSentinel): if starincluded: state.add_token("*, ") elif isinstance(star_arg, Param): more_values = len(self.kwonly_params) > 0 or self.star_kwarg is not None star_arg._codegen(state, default_star="*", default_comma=more_values) elif isinstance(star_arg, ParamStar): star_arg._codegen(state) # Render out the kwonly_args next, computing necessary trailing commas. lastparam = len(self.kwonly_params) - 1 more_values = self.star_kwarg is not None for i, param in enumerate(self.kwonly_params): param._codegen( state, default_star="", default_comma=(i < lastparam or more_values) ) # Finally, render out any optional star_kwarg star_kwarg = self.star_kwarg if star_kwarg is not None: star_kwarg._codegen(state, default_star="**", default_comma=False) ParserConfig = config_mod.ParserConfig class FuncdefPartial: lpar: LeftParen params: Parameters rpar: RightParen parse_parenthesizable_whitespace = mod.parse_parenthesizable_whitespace def convert_parameters(config: ParserConfig, children: Sequence[Any]) -> Any: lpar, *paramlist, rpar = children return FuncdefPartial( lpar=LeftParen( whitespace_after=parse_parenthesizable_whitespace( config, lpar.whitespace_after ) ), params=Parameters() if not paramlist else paramlist[0], rpar=RightParen( whitespace_before=parse_parenthesizable_whitespace( config, rpar.whitespace_before ) ), )
null
4,864
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_whitespace, ) class Annotation(CSTNode): def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Annotation": def _codegen_impl( self, state: CodegenState, default_indicator: Optional[str] = None ) -> None: ParserConfig = config_mod.ParserConfig parse_parenthesizable_whitespace = mod.parse_parenthesizable_whitespace def convert_funcdef_annotation(config: ParserConfig, children: Sequence[Any]) -> Any: arrow, typehint = children return Annotation( whitespace_before_indicator=parse_parenthesizable_whitespace( config, arrow.whitespace_before ), whitespace_after_indicator=parse_parenthesizable_whitespace( config, arrow.whitespace_after ), annotation=typehint.value, )
null
4,865
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_whitespace, ) class PartialParserSyntaxError(Exception): """ An internal exception that represents a partially-constructed :class:`ParserSyntaxError`. It's raised by our internal parser conversion functions, which don't always know the current line and column information. This partial object only contains a message, with the expectation that the line and column information will be filled in by :class:`libcst._base_parser.BaseParser`. This should never be visible to the end-user. """ message: str def __init__(self, message: str) -> None: self.message = message 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 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 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 ClassDef(BaseCompoundStatement): """ A class definition. """ #: The class name. name: Name #: The class body. body: BaseSuite #: Sequence of base classes this class inherits from. bases: Sequence[Arg] = () #: Sequence of keywords, such as "metaclass". keywords: Sequence[Arg] = () #: Sequence of decorators applied to this class. decorators: Sequence[Decorator] = () #: Optional open parenthesis used when there are bases or keywords. lpar: Union[LeftParen, MaybeSentinel] = MaybeSentinel.DEFAULT #: Optional close parenthesis used when there are bases or keywords. rpar: Union[RightParen, MaybeSentinel] = MaybeSentinel.DEFAULT #: Leading empty lines and comments before the first decorator. We #: assume any comments before the first decorator are owned by the #: class definition itself. If there are no decorators, this will #: still contain all of the empty lines and comments before the #: class definition. leading_lines: Sequence[EmptyLine] = () #: Empty lines and comments between the final decorator and the #: :class:`ClassDef` node. In the case of no decorators, this will be empty. lines_after_decorators: Sequence[EmptyLine] = () #: Whitespace after the ``class`` keyword and before the class name. whitespace_after_class: SimpleWhitespace = SimpleWhitespace.field(" ") #: Whitespace after the class name and before the type parameters or the opening #: parenthesis for the bases and keywords. whitespace_after_name: SimpleWhitespace = SimpleWhitespace.field("") #: Whitespace after the closing parenthesis or class name and before #: the colon. whitespace_before_colon: SimpleWhitespace = SimpleWhitespace.field("") #: An optional declaration of type parameters. type_parameters: Optional["TypeParameters"] = None #: Whitespace between type parameters and opening parenthesis for the bases and #: keywords. whitespace_after_type_parameters: SimpleWhitespace = SimpleWhitespace.field("") def _validate_whitespace(self) -> None: if self.whitespace_after_class.empty: raise CSTValidationError( "There must be at least one space between 'class' and name." ) if ( self.type_parameters is None and not self.whitespace_after_type_parameters.empty ): raise CSTValidationError( "whitespace_after_type_parameters must be empty if there are no type" "parameters in a ClassDef" ) def _validate_parens(self) -> None: if len(self.name.lpar) > 0 or len(self.name.rpar) > 0: raise CSTValidationError("Cannot have parens around Name in a ClassDef.") if isinstance(self.lpar, MaybeSentinel) and isinstance(self.rpar, RightParen): raise CSTValidationError( "Do not mix concrete LeftParen/RightParen with MaybeSentinel." ) if isinstance(self.lpar, LeftParen) and isinstance(self.rpar, MaybeSentinel): raise CSTValidationError( "Do not mix concrete LeftParen/RightParen with MaybeSentinel." ) def _validate_args(self) -> None: if any((arg.keyword is not None) for arg in self.bases): raise CSTValidationError("Bases must be arguments without keywords.") if any((arg.keyword is None and arg.star != "**") for arg in self.keywords): raise CSTValidationError( "Keywords must be arguments with keywords or dictionary expansions." ) def _validate(self) -> None: self._validate_whitespace() self._validate_parens() self._validate_args() def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "ClassDef": return ClassDef( leading_lines=visit_sequence( self, "leading_lines", self.leading_lines, visitor ), decorators=visit_sequence(self, "decorators", self.decorators, visitor), lines_after_decorators=visit_sequence( self, "lines_after_decorators", self.lines_after_decorators, visitor ), whitespace_after_class=visit_required( self, "whitespace_after_class", self.whitespace_after_class, visitor ), name=visit_required(self, "name", self.name, visitor), whitespace_after_name=visit_required( self, "whitespace_after_name", self.whitespace_after_name, visitor ), type_parameters=visit_optional( self, "type_parameters", self.type_parameters, visitor ), whitespace_after_type_parameters=visit_required( self, "whitespace_after_type_parameters", self.whitespace_after_type_parameters, visitor, ), lpar=visit_sentinel(self, "lpar", self.lpar, visitor), bases=visit_sequence(self, "bases", self.bases, visitor), keywords=visit_sequence(self, "keywords", self.keywords, visitor), rpar=visit_sentinel(self, "rpar", self.rpar, visitor), whitespace_before_colon=visit_required( self, "whitespace_before_colon", self.whitespace_before_colon, visitor ), body=visit_required(self, "body", self.body, visitor), ) def _codegen_impl(self, state: CodegenState) -> None: # noqa: C901 for ll in self.leading_lines: ll._codegen(state) for decorator in self.decorators: decorator._codegen(state) for lad in self.lines_after_decorators: lad._codegen(state) state.add_indent_tokens() with state.record_syntactic_position(self, end_node=self.body): state.add_token("class") self.whitespace_after_class._codegen(state) self.name._codegen(state) self.whitespace_after_name._codegen(state) type_params = self.type_parameters if type_params is not None: type_params._codegen(state) self.whitespace_after_type_parameters._codegen(state) lpar = self.lpar if isinstance(lpar, MaybeSentinel): if self.bases or self.keywords: state.add_token("(") elif isinstance(lpar, LeftParen): lpar._codegen(state) args = [*self.bases, *self.keywords] last_arg = len(args) - 1 for i, arg in enumerate(args): arg._codegen(state, default_comma=(i != last_arg)) rpar = self.rpar if isinstance(rpar, MaybeSentinel): if self.bases or self.keywords: state.add_token(")") elif isinstance(rpar, RightParen): rpar._codegen(state) self.whitespace_before_colon._codegen(state) state.add_token(":") self.body._codegen(state) 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) # pyre-fixme[13]: Attribute `body` is never initialized. ParserConfig = config_mod.ParserConfig parse_simple_whitespace = mod.parse_simple_whitespace parse_empty_lines = mod.parse_empty_lines parse_parenthesizable_whitespace = mod.parse_parenthesizable_whitespace def convert_classdef(config: ParserConfig, children: Sequence[Any]) -> Any: classdef, name, *arglist, colon, suite = children # First, parse out the comments and empty lines before the statement. leading_lines = parse_empty_lines(config, classdef.whitespace_before) # Compute common whitespace and nodes whitespace_after_class = parse_simple_whitespace(config, classdef.whitespace_after) namenode = Name(name.string) whitespace_after_name = parse_simple_whitespace(config, name.whitespace_after) # Now, construct the classdef node itself if not arglist: # No arglist, so no arguments to this class return ClassDef( leading_lines=leading_lines, lines_after_decorators=(), whitespace_after_class=whitespace_after_class, name=namenode, whitespace_after_name=whitespace_after_name, body=suite, ) else: # Unwrap arglist partial, because its valid to not have any lpar, *args, rpar = arglist args = args[0].args if args else [] bases: List[Arg] = [] keywords: List[Arg] = [] current_arg = bases for arg in args: if arg.star == "**" or arg.keyword is not None: current_arg = keywords # Some quick validation if current_arg is keywords and ( arg.star == "*" or (arg.star == "" and arg.keyword is None) ): raise PartialParserSyntaxError( "Positional argument follows keyword argument." ) current_arg.append(arg) return ClassDef( leading_lines=leading_lines, lines_after_decorators=(), whitespace_after_class=whitespace_after_class, name=namenode, whitespace_after_name=whitespace_after_name, lpar=LeftParen( whitespace_after=parse_parenthesizable_whitespace( config, lpar.whitespace_after ) ), bases=bases, keywords=keywords, rpar=RightParen( whitespace_before=parse_parenthesizable_whitespace( config, rpar.whitespace_before ) ), whitespace_before_colon=parse_simple_whitespace( config, colon.whitespace_before ), body=suite, )
null
4,866
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_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 Call(_BaseExpressionWithArgs): """ An expression representing a function call, such as ``do_math(1, 2)`` or ``picture.post_on_instagram()``. Function calls consist of a function name and a sequence of arguments wrapped in :class:`Arg` nodes. """ #: The expression resulting in a callable that we are to call. Often a :class:`Name` #: or :class:`Attribute`. func: BaseExpression #: The arguments to pass to the resulting callable. These may be a mix of #: positional arguments, keyword arguments, or "starred" arguments. args: Sequence[Arg] = () lpar: Sequence[LeftParen] = () #: Sequence of parenthesis for precedence dictation. These are not the parenthesis #: before and after the list of ``args``, but rather arguments around the entire #: call expression, such as ``(( do_math(1, 2) ))``. rpar: Sequence[RightParen] = () #: Whitespace after the ``func`` name, but before the opening parenthesis. whitespace_after_func: BaseParenthesizableWhitespace = SimpleWhitespace.field("") #: Whitespace after the opening parenthesis but before the first argument (if there #: are any). Whitespace after the last argument but before the closing parenthesis #: is owned by the last :class:`Arg` if it exists. whitespace_before_args: BaseParenthesizableWhitespace = SimpleWhitespace.field("") def _safe_to_use_with_word_operator(self, position: ExpressionPosition) -> bool: """ Calls have a close paren on the right side regardless of whether they're parenthesized as a whole. As a result, they are safe to use directly against an adjacent node to the right. """ if position == ExpressionPosition.LEFT: return True if super(Call, self)._safe_to_use_with_word_operator(position): return True if position == ExpressionPosition.RIGHT: return self.func._safe_to_use_with_word_operator(ExpressionPosition.RIGHT) return False def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Call": return Call( lpar=visit_sequence(self, "lpar", self.lpar, visitor), func=visit_required(self, "func", self.func, visitor), whitespace_after_func=visit_required( self, "whitespace_after_func", self.whitespace_after_func, visitor ), whitespace_before_args=visit_required( self, "whitespace_before_args", self.whitespace_before_args, visitor ), args=visit_sequence(self, "args", self.args, visitor), rpar=visit_sequence(self, "rpar", self.rpar, visitor), ) 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(")") class Decorator(CSTNode): """ A single decorator that decorates a :class:`FunctionDef` or a :class:`ClassDef`. """ #: The decorator that will return a new function wrapping the parent #: of this decorator. decorator: BaseExpression #: Line comments and empty lines before this decorator. The parent #: :class:`FunctionDef` or :class:`ClassDef` node owns leading lines before #: the first decorator so that if the first decorator is removed, spacing is preserved. leading_lines: Sequence[EmptyLine] = () #: Whitespace after the ``@`` and before the decorator expression itself. whitespace_after_at: SimpleWhitespace = SimpleWhitespace.field("") #: Optional trailing comment and newline following the decorator before the next line. trailing_whitespace: TrailingWhitespace = TrailingWhitespace.field() def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Decorator": return Decorator( leading_lines=visit_sequence( self, "leading_lines", self.leading_lines, visitor ), whitespace_after_at=visit_required( self, "whitespace_after_at", self.whitespace_after_at, visitor ), decorator=visit_required(self, "decorator", self.decorator, visitor), trailing_whitespace=visit_required( self, "trailing_whitespace", self.trailing_whitespace, visitor ), ) def _codegen_impl(self, state: CodegenState) -> None: for ll in self.leading_lines: ll._codegen(state) state.add_indent_tokens() with state.record_syntactic_position(self): state.add_token("@") self.whitespace_after_at._codegen(state) self.decorator._codegen(state) self.trailing_whitespace._codegen(state) # pyre-fixme[13]: Attribute `body` is never initialized. ParserConfig = config_mod.ParserConfig parse_simple_whitespace = mod.parse_simple_whitespace parse_empty_lines = mod.parse_empty_lines parse_parenthesizable_whitespace = mod.parse_parenthesizable_whitespace def convert_decorator(config: ParserConfig, children: Sequence[Any]) -> Any: atsign, name, *arglist, newline = children if not arglist: # This is either a name or an attribute node, so just extract it. decoratornode = name else: # This needs to be converted into a call node, and we have the # arglist partial. lpar, *args, rpar = arglist args = args[0].args if args else [] # 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(args) > 0 and args[-1].comma == MaybeSentinel.DEFAULT: args[-1] = args[-1].with_changes( whitespace_after_arg=parse_parenthesizable_whitespace( config, rpar.whitespace_before ) ) decoratornode = Call( func=name, whitespace_after_func=parse_simple_whitespace( config, lpar.whitespace_before ), whitespace_before_args=parse_parenthesizable_whitespace( config, lpar.whitespace_after ), args=tuple(args), ) return Decorator( leading_lines=parse_empty_lines(config, atsign.whitespace_before), whitespace_after_at=parse_simple_whitespace(config, atsign.whitespace_after), decorator=decoratornode, trailing_whitespace=newline, )
null
4,867
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_whitespace, ) ParserConfig = config_mod.ParserConfig class DecoratorPartial: decorators: Sequence[Decorator] def convert_decorators(config: ParserConfig, children: Sequence[Any]) -> Any: return DecoratorPartial(decorators=children)
null
4,868
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_whitespace, ) ParserConfig = config_mod.ParserConfig def convert_decorated(config: ParserConfig, children: Sequence[Any]) -> Any: partial, class_or_func = children # First, split up the spacing on the first decorator leading_lines = partial.decorators[0].leading_lines # Now, redistribute ownership of the whitespace decorators = ( partial.decorators[0].with_changes(leading_lines=()), *partial.decorators[1:], ) # Now, modify the original function or class to add the decorators. return class_or_func.with_changes( leading_lines=leading_lines, # pyre-fixme[60]: Concatenation not yet support for multiple variadic # tuples: `*class_or_func.leading_lines, # *class_or_func.lines_after_decorators`. # pyre-fixme[60]: Expected to unpack an iterable, but got `unknown`. lines_after_decorators=( *class_or_func.leading_lines, *class_or_func.lines_after_decorators, ), decorators=decorators, )
null
4,869
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_whitespace, ) def _extract_async( config: ParserConfig, children: Sequence[Any] ) -> Tuple[List[EmptyLine], Optional[Asynchronous], Any]: if len(children) == 1: (stmt,) = children whitespace_before = stmt.whitespace_before asyncnode = None else: asynctoken, stmt = children whitespace_before = asynctoken.whitespace_before asyncnode = Asynchronous( whitespace_after=parse_simple_whitespace( config, asynctoken.whitespace_after ) ) return (parse_empty_lines(config, whitespace_before), asyncnode, stmt.value) class FunctionDef(BaseCompoundStatement): """ A function definition. """ #: The function name. name: Name #: The function parameters. Present even if there are no params. params: Parameters #: The function body. body: BaseSuite #: Sequence of decorators applied to this function. Decorators are listed in #: order that they appear in source (top to bottom) as apposed to the order #: that they are applied to the function at runtime. decorators: Sequence[Decorator] = () #: An optional return annotation, if the function is annotated. returns: Optional[Annotation] = None #: Optional async modifier, if this is an async function. asynchronous: Optional[Asynchronous] = None #: Leading empty lines and comments before the first decorator. We #: assume any comments before the first decorator are owned by the #: function definition itself. If there are no decorators, this will #: still contain all of the empty lines and comments before the #: function definition. leading_lines: Sequence[EmptyLine] = () #: Empty lines and comments between the final decorator and the #: :class:`FunctionDef` node. In the case of no decorators, this will be empty. lines_after_decorators: Sequence[EmptyLine] = () #: Whitespace after the ``def`` keyword and before the function name. whitespace_after_def: SimpleWhitespace = SimpleWhitespace.field(" ") #: Whitespace after the function name and before the type parameters or the opening #: parenthesis for the parameters. whitespace_after_name: SimpleWhitespace = SimpleWhitespace.field("") #: Whitespace after the opening parenthesis for the parameters but before #: the first param itself. whitespace_before_params: BaseParenthesizableWhitespace = SimpleWhitespace.field("") #: Whitespace after the closing parenthesis or return annotation and before #: the colon. whitespace_before_colon: SimpleWhitespace = SimpleWhitespace.field("") #: An optional declaration of type parameters. type_parameters: Optional["TypeParameters"] = None #: Whitespace between the type parameters and the opening parenthesis for the #: (non-type) parameters. whitespace_after_type_parameters: SimpleWhitespace = SimpleWhitespace.field("") def _validate(self) -> None: if len(self.name.lpar) > 0 or len(self.name.rpar) > 0: raise CSTValidationError("Cannot have parens around Name in a FunctionDef.") if self.whitespace_after_def.empty: raise CSTValidationError( "There must be at least one space between 'def' and name." ) if ( self.type_parameters is None and not self.whitespace_after_type_parameters.empty ): raise CSTValidationError( "whitespace_after_type_parameters must be empty if there are no type " "parameters in FunctionDef" ) def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "FunctionDef": return FunctionDef( leading_lines=visit_sequence( self, "leading_lines", self.leading_lines, visitor ), decorators=visit_sequence(self, "decorators", self.decorators, visitor), lines_after_decorators=visit_sequence( self, "lines_after_decorators", self.lines_after_decorators, visitor ), asynchronous=visit_optional( self, "asynchronous", self.asynchronous, visitor ), whitespace_after_def=visit_required( self, "whitespace_after_def", self.whitespace_after_def, visitor ), name=visit_required(self, "name", self.name, visitor), whitespace_after_name=visit_required( self, "whitespace_after_name", self.whitespace_after_name, visitor ), type_parameters=visit_optional( self, "type_parameters", self.type_parameters, visitor ), whitespace_after_type_parameters=visit_required( self, "whitespace_after_type_parameters", self.whitespace_after_type_parameters, visitor, ), whitespace_before_params=visit_required( self, "whitespace_before_params", self.whitespace_before_params, visitor ), params=visit_required(self, "params", self.params, visitor), returns=visit_optional(self, "returns", self.returns, visitor), whitespace_before_colon=visit_required( self, "whitespace_before_colon", self.whitespace_before_colon, visitor ), body=visit_required(self, "body", self.body, visitor), ) def _codegen_impl(self, state: CodegenState) -> None: for ll in self.leading_lines: ll._codegen(state) for decorator in self.decorators: decorator._codegen(state) for lad in self.lines_after_decorators: lad._codegen(state) state.add_indent_tokens() with state.record_syntactic_position(self, end_node=self.body): asynchronous = self.asynchronous if asynchronous is not None: asynchronous._codegen(state) state.add_token("def") self.whitespace_after_def._codegen(state) self.name._codegen(state) self.whitespace_after_name._codegen(state) type_params = self.type_parameters if type_params is not None: type_params._codegen(state) self.whitespace_after_type_parameters._codegen(state) state.add_token("(") self.whitespace_before_params._codegen(state) self.params._codegen(state) state.add_token(")") returns = self.returns if returns is not None: returns._codegen(state, default_indicator="->") self.whitespace_before_colon._codegen(state) state.add_token(":") self.body._codegen(state) def get_docstring(self, clean: bool = True) -> Optional[str]: """ When docstring is available, returns a :func:`inspect.cleandoc` cleaned docstring. Otherwise, returns ``None``. """ return get_docstring_impl(self.body, clean) class With(BaseCompoundStatement): """ A ``with`` statement. """ #: A sequence of one or more items that evaluate to context managers. items: Sequence[WithItem] #: The suite that is wrapped with this statement. body: BaseSuite #: Optional async modifier if this is an ``async with`` statement. asynchronous: Optional[Asynchronous] = None #: Sequence of empty lines appearing before this with statement. leading_lines: Sequence[EmptyLine] = () #: Optional open parenthesis for multi-line with bindings lpar: Union[LeftParen, MaybeSentinel] = MaybeSentinel.DEFAULT #: Optional close parenthesis for multi-line with bindings rpar: Union[RightParen, MaybeSentinel] = MaybeSentinel.DEFAULT #: Whitespace after the ``with`` keyword and before the first item. whitespace_after_with: SimpleWhitespace = SimpleWhitespace.field(" ") #: Whitespace after the last item and before the colon. whitespace_before_colon: SimpleWhitespace = SimpleWhitespace.field("") def _validate_parens(self) -> None: if isinstance(self.lpar, MaybeSentinel) and isinstance(self.rpar, RightParen): raise CSTValidationError( "Do not mix concrete LeftParen/RightParen with MaybeSentinel." ) if isinstance(self.lpar, LeftParen) and isinstance(self.rpar, MaybeSentinel): raise CSTValidationError( "Do not mix concrete LeftParen/RightParen with MaybeSentinel." ) def _validate(self) -> None: self._validate_parens() if len(self.items) == 0: raise CSTValidationError( "A With statement must have at least one WithItem." ) if ( isinstance(self.rpar, MaybeSentinel) and self.items[-1].comma != MaybeSentinel.DEFAULT ): raise CSTValidationError( "The last WithItem in an unparenthesized With cannot have a trailing comma." ) if self.whitespace_after_with.empty and not ( isinstance(self.lpar, LeftParen) or self.items[0].item._safe_to_use_with_word_operator( ExpressionPosition.RIGHT ) ): raise CSTValidationError("Must have at least one space after with keyword.") def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "With": return With( leading_lines=visit_sequence( self, "leading_lines", self.leading_lines, visitor ), asynchronous=visit_optional( self, "asynchronous", self.asynchronous, visitor ), whitespace_after_with=visit_required( self, "whitespace_after_with", self.whitespace_after_with, visitor ), lpar=visit_sentinel(self, "lpar", self.lpar, visitor), items=visit_sequence(self, "items", self.items, visitor), rpar=visit_sentinel(self, "rpar", self.rpar, visitor), whitespace_before_colon=visit_required( self, "whitespace_before_colon", self.whitespace_before_colon, visitor ), body=visit_required(self, "body", self.body, visitor), ) def _codegen_impl(self, state: CodegenState) -> None: for ll in self.leading_lines: ll._codegen(state) state.add_indent_tokens() needs_paren = False for item in self.items: comma = item.comma if isinstance(comma, Comma): if isinstance( comma.whitespace_after, (EmptyLine, TrailingWhitespace, ParenthesizedWhitespace), ): needs_paren = True break with state.record_syntactic_position(self, end_node=self.body): asynchronous = self.asynchronous if asynchronous is not None: asynchronous._codegen(state) state.add_token("with") self.whitespace_after_with._codegen(state) lpar = self.lpar if isinstance(lpar, LeftParen): lpar._codegen(state) elif needs_paren: state.add_token("(") last_item = len(self.items) - 1 for i, item in enumerate(self.items): item._codegen(state, default_comma=(i != last_item)) rpar = self.rpar if isinstance(rpar, RightParen): rpar._codegen(state) elif needs_paren: state.add_token(")") self.whitespace_before_colon._codegen(state) state.add_token(":") self.body._codegen(state) class For(BaseCompoundStatement): """ A ``for target in iter`` statement. """ #: The target of the iterator in the for statement. target: BaseAssignTargetExpression #: The iterable expression we will loop over. iter: BaseExpression #: The suite that is wrapped with this statement. body: BaseSuite #: An optional else case which will be executed if there is no #: :class:`Break` statement encountered while looping. orelse: Optional[Else] = None #: Optional async modifier, if this is an `async for` statement. asynchronous: Optional[Asynchronous] = None #: Sequence of empty lines appearing before this for statement. leading_lines: Sequence[EmptyLine] = () #: Whitespace after the ``for`` keyword and before the target. whitespace_after_for: SimpleWhitespace = SimpleWhitespace.field(" ") #: Whitespace after the target and before the ``in`` keyword. whitespace_before_in: SimpleWhitespace = SimpleWhitespace.field(" ") #: Whitespace after the ``in`` keyword and before the iter. whitespace_after_in: SimpleWhitespace = SimpleWhitespace.field(" ") #: Whitespace after the iter and before the colon. whitespace_before_colon: SimpleWhitespace = 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.") def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "For": return For( leading_lines=visit_sequence( self, "leading_lines", self.leading_lines, 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), whitespace_before_colon=visit_required( self, "whitespace_before_colon", self.whitespace_before_colon, visitor ), body=visit_required(self, "body", self.body, visitor), orelse=visit_optional(self, "orelse", self.orelse, visitor), ) def _codegen_impl(self, state: CodegenState) -> None: for ll in self.leading_lines: ll._codegen(state) state.add_indent_tokens() end_node = self.body if self.orelse is None else self.orelse with state.record_syntactic_position(self, end_node=end_node): 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) self.whitespace_before_colon._codegen(state) state.add_token(":") self.body._codegen(state) orelse = self.orelse if orelse is not None: orelse._codegen(state) # pyre-fixme[13]: Attribute `body` is never initialized. ParserConfig = config_mod.ParserConfig def convert_asyncable_stmt(config: ParserConfig, children: Sequence[Any]) -> Any: leading_lines, asyncnode, stmtnode = _extract_async(config, children) if isinstance(stmtnode, FunctionDef): return stmtnode.with_changes( asynchronous=asyncnode, leading_lines=leading_lines, lines_after_decorators=(), ) elif isinstance(stmtnode, With): return stmtnode.with_changes( asynchronous=asyncnode, leading_lines=leading_lines ) elif isinstance(stmtnode, For): return stmtnode.with_changes( asynchronous=asyncnode, leading_lines=leading_lines ) else: raise Exception("Logic error!")
null
4,870
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_whitespace, ) ParserConfig = config_mod.ParserConfig def convert_suite(config: ParserConfig, children: Sequence[Any]) -> Any: (suite,) = children return suite
null
4,871
from typing import Any, Dict, List, Optional, Sequence, Tuple, Type from libcst._exceptions import PartialParserSyntaxError from libcst._maybe_sentinel import MaybeSentinel from libcst._nodes.expression import ( Annotation, Arg, Asynchronous, Attribute, Call, From, LeftParen, Name, Param, Parameters, RightParen, ) from libcst._nodes.op import ( AddAssign, AssignEqual, BaseAugOp, BitAndAssign, BitOrAssign, BitXorAssign, Comma, DivideAssign, Dot, FloorDivideAssign, ImportStar, LeftShiftAssign, MatrixMultiplyAssign, ModuloAssign, MultiplyAssign, PowerAssign, RightShiftAssign, Semicolon, SubtractAssign, ) from libcst._nodes.statement import ( AnnAssign, AsName, Assert, Assign, AssignTarget, AugAssign, Break, ClassDef, Continue, Decorator, Del, Else, ExceptHandler, Expr, Finally, For, FunctionDef, Global, If, Import, ImportAlias, ImportFrom, IndentedBlock, NameItem, Nonlocal, Pass, Raise, Return, SimpleStatementLine, SimpleStatementSuite, Try, While, With, WithItem, ) from libcst._nodes.whitespace import EmptyLine, 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 ( AnnAssignPartial, AssignPartial, AugAssignPartial, DecoratorPartial, ExceptClausePartial, FuncdefPartial, ImportPartial, ImportRelativePartial, SimpleStatementPartial, WithLeadingWhitespace, ) from libcst._parser.types.token import Token from libcst._parser.whitespace_parser import ( parse_empty_lines, parse_parenthesizable_whitespace, parse_simple_whitespace, ) class IndentedBlock(BaseSuite): """ Represents a block of statements beginning with an ``INDENT`` token and ending in a ``DEDENT`` token. Used as the body of compound statements, such as an if statement's body. A common alternative to an :class:`IndentedBlock` is a :class:`SimpleStatementSuite`, which can also be used as a :class:`BaseSuite`, meaning that it can be used as the body of many compound statements. An :class:`IndentedBlock` always occurs after a colon in a :class:`BaseCompoundStatement`, so it owns the trailing whitespace for the compound statement's clause. .. code-block:: if test: # IndentedBlock's header body """ #: Sequence of statements belonging to this indented block. body: Sequence[BaseStatement] #: Any optional trailing comment and the final ``NEWLINE`` at the end of the line. header: TrailingWhitespace = TrailingWhitespace.field() #: A string represents a specific indentation. A ``None`` value uses the modules's #: default indentation. This is included because indentation is allowed to be #: inconsistent across a file, just not ambiguously. indent: Optional[str] = None #: Any trailing comments or lines after the dedent that are owned by this indented #: block. Statements own preceeding and same-line trailing comments, but not #: trailing lines, so it falls on :class:`IndentedBlock` to own it. In the case #: that a statement follows an :class:`IndentedBlock`, that statement will own the #: comments and lines that are at the same indent as the statement, and this #: :class:`IndentedBlock` will own the comments and lines that are indented further. footer: Sequence[EmptyLine] = () def _validate(self) -> None: indent = self.indent if indent is not None: if len(indent) == 0: raise CSTValidationError( "An indented block must have a non-zero width indent." ) if _INDENT_WHITESPACE_RE.fullmatch(indent) is None: raise CSTValidationError( "An indent must be composed of only whitespace characters." ) def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "IndentedBlock": return IndentedBlock( header=visit_required(self, "header", self.header, visitor), indent=self.indent, body=visit_body_sequence(self, "body", self.body, visitor), footer=visit_sequence(self, "footer", self.footer, visitor), ) def _codegen_impl(self, state: CodegenState) -> None: self.header._codegen(state) indent = self.indent state.increase_indent(state.default_indent if indent is None else indent) if self.body: with state.record_syntactic_position( self, start_node=self.body[0], end_node=self.body[-1] ): for stmt in self.body: # IndentedBlock is responsible for adjusting the current indentation level, # but its children are responsible for actually adding that indentation to # the token list. stmt._codegen(state) else: # Empty indented blocks are not syntactically valid in Python unless # they contain a 'pass' statement, so add one here. state.add_indent_tokens() with state.record_syntactic_position(self): state.add_token("pass") state.add_token(state.default_newline) for f in self.footer: f._codegen(state) state.decrease_indent() # pyre-fixme[13]: Attribute `body` is never initialized. ParserConfig = config_mod.ParserConfig parse_empty_lines = mod.parse_empty_lines def convert_indented_suite(config: ParserConfig, children: Sequence[Any]) -> Any: newline, indent, *stmts, dedent = children return IndentedBlock( header=newline, indent=( None if indent.relative_indent == config.default_indent else indent.relative_indent ), body=stmts, # We want to be able to only keep comments in the footer that are actually for # this IndentedBlock. We do so by assuming that lines which are indented to the # same level as the block itself are comments that go at the footer of the # block. Comments that are indented to less than this indent are assumed to # belong to the next line of code. We override the indent here because the # dedent node's absolute indent is the resulting indentation after the dedent # is performed. Its this way because the whitespace state for both the dedent's # whitespace_after and the next BaseCompoundStatement's whitespace_before is # shared. This allows us to partially parse here and parse the rest of the # whitespace and comments on the next line, effectively making sure that # comments are attached to the correct node. footer=parse_empty_lines( config, dedent.whitespace_after, override_absolute_indent=indent.whitespace_before.absolute_indent, ), )
null
4,872
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 WithLeadingWhitespace(Generic[_T]): def convert_expression_input( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: (child, endmarker) = children # HACK: UGLY! REMOVE THIS SOON! # Unwrap WithLeadingWhitespace if it exists. It shouldn't exist by this point, but # testlist isn't fully implemented, and we currently leak these partial objects. if isinstance(child, WithLeadingWhitespace): child = child.value return child
null
4,873
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 IfExp(BaseExpression): def _safe_to_use_with_word_operator(self, position: ExpressionPosition) -> bool: def _validate(self) -> None: def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "IfExp": def _codegen_impl(self, state: CodegenState) -> None: ParserConfig = config_mod.ParserConfig class WithLeadingWhitespace(Generic[_T]): parse_parenthesizable_whitespace = mod.parse_parenthesizable_whitespace def convert_test( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: if len(children) == 1: (child,) = children return child else: (body, if_token, test, else_token, orelse) = children return WithLeadingWhitespace( IfExp( body=body.value, test=test.value, orelse=orelse.value, whitespace_before_if=parse_parenthesizable_whitespace( config, if_token.whitespace_before ), whitespace_after_if=parse_parenthesizable_whitespace( config, if_token.whitespace_after ), whitespace_before_else=parse_parenthesizable_whitespace( config, else_token.whitespace_before ), whitespace_after_else=parse_parenthesizable_whitespace( config, else_token.whitespace_after ), ), body.whitespace_before, )
null
4,874
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_test_nocond( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: (child,) = children return child
null
4,875
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 Param(CSTNode): def _validate(self) -> None: def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Param": def _codegen_impl( self, state: CodegenState, default_star: Optional[str] = None, default_comma: bool = False, ) -> None: class Parameters(CSTNode): def _validate_stars_sequence(self, vals: Sequence[Param], *, section: str) -> None: def _validate_posonly_ind(self) -> None: def _validate_kwonly_star(self) -> None: def _validate_defaults(self) -> None: def _validate_stars(self) -> None: def _validate(self) -> None: def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Parameters": def _safe_to_join_with_lambda(self) -> bool: def _codegen_impl(self, state: CodegenState) -> None: class Lambda(BaseExpression): def _safe_to_use_with_word_operator(self, position: ExpressionPosition) -> bool: def _validate(self) -> None: def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Lambda": def _codegen_impl(self, state: CodegenState) -> None: class Colon(_BaseOneTokenOp): def _get_token(self) -> str: class SimpleWhitespace(BaseParenthesizableWhitespace, BaseValueToken): def _validate(self) -> None: def empty(self) -> bool: ParserConfig = config_mod.ParserConfig class WithLeadingWhitespace(Generic[_T]): parse_parenthesizable_whitespace = mod.parse_parenthesizable_whitespace def convert_lambda( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: lambdatoken, *params, colontoken, test = children # Grab the whitespace around the colon. If there are no params, then # the colon owns the whitespace before and after it. If there are # any params, then the last param owns the whitespace before the colon. # We handle the parameter movement below. colon = Colon( whitespace_before=parse_parenthesizable_whitespace( config, colontoken.whitespace_before ), whitespace_after=parse_parenthesizable_whitespace( config, colontoken.whitespace_after ), ) # Unpack optional parameters if len(params) == 0: parameters = Parameters() whitespace_after_lambda = MaybeSentinel.DEFAULT else: (parameters,) = params whitespace_after_lambda = parse_parenthesizable_whitespace( config, lambdatoken.whitespace_after ) # Handle pre-colon whitespace if parameters.star_kwarg is not None: if parameters.star_kwarg.comma == MaybeSentinel.DEFAULT: parameters = parameters.with_changes( star_kwarg=parameters.star_kwarg.with_changes( whitespace_after_param=colon.whitespace_before ) ) elif parameters.kwonly_params: if parameters.kwonly_params[-1].comma == MaybeSentinel.DEFAULT: parameters = parameters.with_changes( kwonly_params=( *parameters.kwonly_params[:-1], parameters.kwonly_params[-1].with_changes( whitespace_after_param=colon.whitespace_before ), ) ) elif isinstance(parameters.star_arg, Param): if parameters.star_arg.comma == MaybeSentinel.DEFAULT: parameters = parameters.with_changes( star_arg=parameters.star_arg.with_changes( whitespace_after_param=colon.whitespace_before ) ) elif parameters.params: if parameters.params[-1].comma == MaybeSentinel.DEFAULT: parameters = parameters.with_changes( params=( *parameters.params[:-1], parameters.params[-1].with_changes( whitespace_after_param=colon.whitespace_before ), ) ) # Colon doesn't own its own pre-whitespace now. colon = colon.with_changes(whitespace_before=SimpleWhitespace("")) # Return a lambda return WithLeadingWhitespace( Lambda( whitespace_after_lambda=whitespace_after_lambda, params=parameters, body=test.value, colon=colon, ), lambdatoken.whitespace_before, )
null
4,876
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 BOOLOP_TOKEN_LUT: typing.Dict[str, typing.Type[BaseBooleanOp]] = {"and": And, "or": Or} class BooleanOperation(BaseExpression): """ An operation that combines two booleans such as ``x or y`` or ``z and w`` :class:`BooleanOperation` nodes apply a :class:`BaseBooleanOp` to an expression. Boolean operations do not include operations performed with :class:`BaseBinaryOp` nodes, such as ``+`` or ``<<``. Instead, those operations are provided by :class:`BinaryOperation`. 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 ``and`` or ``or`` that combines the ``left`` and #: ``right`` expressions. operator: BaseBooleanOp #: The right hand side of the operation. right: BaseExpression lpar: Sequence[LeftParen] = () #: Sequence of parenthesis for precedence dictation. rpar: Sequence[RightParen] = () def _validate(self) -> None: # Paren validation and such super(BooleanOperation, self)._validate() # Validate spacing rules if ( self.operator.whitespace_before.empty and not self.left._safe_to_use_with_word_operator(ExpressionPosition.LEFT) ): raise CSTValidationError( "Must have at least one space around boolean operator." ) if ( self.operator.whitespace_after.empty and not self.right._safe_to_use_with_word_operator(ExpressionPosition.RIGHT) ): raise CSTValidationError( "Must have at least one space around boolean operator." ) def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "BooleanOperation": return BooleanOperation( 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(BooleanOperation, 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) 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_boolop( 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 BOOLOP_TOKEN_LUT: raise Exception(f"Unexpected token '{op.string}'!") leftexpr = BooleanOperation( left=leftexpr, # pyre-ignore Pyre thinks that the type of the LUT is CSTNode. operator=BOOLOP_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,877
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 Not(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 "not" ParserConfig = config_mod.ParserConfig class WithLeadingWhitespace(Generic[_T]): value: _T whitespace_before: WhitespaceState parse_parenthesizable_whitespace = mod.parse_parenthesizable_whitespace def convert_not_test( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: if len(children) == 1: (child,) = children return child else: nottoken, nottest = children return WithLeadingWhitespace( UnaryOperation( operator=Not( whitespace_after=parse_parenthesizable_whitespace( config, nottoken.whitespace_after ) ), expression=nottest.value, ), nottoken.whitespace_before, )
null
4,878
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 ComparisonTarget(CSTNode): """ A target for a :class:`Comparison`. Owns the comparison operator and the value to the right of the operator. """ #: A comparison operator such as ``<``, ``>=``, ``==``, ``is``, or ``in``. operator: BaseCompOp #: The right hand side of the comparison operation. comparator: BaseExpression def _validate(self) -> None: # Validate operator spacing rules operator = self.operator if ( isinstance(operator, (In, NotIn, Is, IsNot)) and operator.whitespace_after.empty and not self.comparator._safe_to_use_with_word_operator( ExpressionPosition.RIGHT ) ): raise CSTValidationError( "Must have at least one space around comparison operator." ) def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "ComparisonTarget": return ComparisonTarget( operator=visit_required(self, "operator", self.operator, visitor), comparator=visit_required(self, "comparator", self.comparator, visitor), ) def _codegen_impl(self, state: CodegenState) -> None: self.operator._codegen(state) self.comparator._codegen(state) class Comparison(BaseExpression): """ A comparison between multiple values such as ``x < y``, ``x < y < z``, or ``x in [y, z]``. These comparisions typically result in boolean values. Unlike :class:`BinaryOperation` and :class:`BooleanOperation`, comparisons are not restricted to a left and right child. Instead they can contain an arbitrary number of :class:`ComparisonTarget` children. ``x < y < z`` is not equivalent to ``(x < y) < z`` or ``x < (y < z)``. Instead, it's roughly equivalent to ``x < y and y < z``. For more details, see `Python's documentation on comparisons <https://docs.python.org/3/reference/expressions.html#comparisons>`_. :: # x < y < z Comparison( Name("x"), [ ComparisonTarget(LessThan(), Name("y")), ComparisonTarget(LessThan(), Name("z")), ], ) """ #: The first value in the full sequence of values to compare. This value will be #: compared against the first value in ``comparisions``. left: BaseExpression #: Pairs of :class:`BaseCompOp` operators and expression values to compare. These #: come after ``left``. Each value is compared against the value before and after #: itself in the sequence. comparisons: Sequence[ComparisonTarget] lpar: Sequence[LeftParen] = () #: Sequence of parenthesis for precedence dictation. rpar: Sequence[RightParen] = () def _safe_to_use_with_word_operator(self, position: ExpressionPosition) -> bool: if super(Comparison, self)._safe_to_use_with_word_operator(position): # we have parenthesis return True return self._check_left_right_word_concatenation_safety( position, self.left, self.comparisons[-1].comparator ) def _validate(self) -> None: # Perform any validation on base type super(Comparison, self)._validate() if len(self.comparisons) == 0: raise CSTValidationError("Must have at least one ComparisonTarget.") # Validate operator spacing rules previous_comparator = self.left for target in self.comparisons: operator = target.operator if ( isinstance(operator, (In, NotIn, Is, IsNot)) and operator.whitespace_before.empty and not previous_comparator._safe_to_use_with_word_operator( ExpressionPosition.LEFT ) ): raise CSTValidationError( "Must have at least one space around comparison operator." ) previous_comparator = target.comparator def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "Comparison": return Comparison( lpar=visit_sequence(self, "lpar", self.lpar, visitor), left=visit_required(self, "left", self.left, visitor), comparisons=visit_sequence(self, "comparisons", self.comparisons, visitor), rpar=visit_sequence(self, "rpar", self.rpar, visitor), ) def _codegen_impl(self, state: CodegenState) -> None: with self._parenthesize(state): self.left._codegen(state) for comp in self.comparisons: comp._codegen(state) 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, ) 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 def convert_comparison( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: if len(children) == 1: (child,) = children return child lhs, *rest = children comparisons: typing.List[ComparisonTarget] = [] for operator, comparator in grouper(rest, 2): comparisons.append( ComparisonTarget(operator=operator, comparator=comparator.value) ) return WithLeadingWhitespace( Comparison(left=lhs.value, comparisons=tuple(comparisons)), lhs.whitespace_before, )
null
4,879
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 COMPOP_TOKEN_LUT: typing.Dict[str, typing.Type[BaseCompOp]] = { "<": LessThan, ">": GreaterThan, "==": Equal, "<=": LessThanEqual, ">=": GreaterThanEqual, "in": In, "is": Is, } class NotEqual(BaseCompOp, _BaseOneTokenOp): """ A comparison operator that can be used in a :class:`Comparison` expression. This node defines a static value for convenience, but in reality due to PEP 401 it can be one of two values, both of which should be a :class:`NotEqual` :class:`Comparison` operator. """ #: The actual text value of this operator. Can be either ``!=`` or ``<>``. value: str = "!=" #: 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 _validate(self) -> None: if self.value not in ["!=", "<>"]: raise CSTValidationError("Invalid value for NotEqual node.") def _visit_and_replace_children(self, visitor: CSTVisitorT) -> "NotEqual": return self.__class__( whitespace_before=visit_required( self, "whitespace_before", self.whitespace_before, visitor ), value=self.value, whitespace_after=visit_required( self, "whitespace_after", self.whitespace_after, visitor ), ) def _get_token(self) -> str: return self.value class NotIn(BaseCompOp, _BaseTwoTokenOp): """ A comparision operator that can be used in a :class:`Comparison` expression. This operator spans two tokens that must be separated by at least one space, so there is a third whitespace attribute to represent this. """ #: Any space that appears directly before this operator. whitespace_before: BaseParenthesizableWhitespace = SimpleWhitespace.field(" ") #: Any space that appears between the ``not`` and ``in`` tokens. whitespace_between: BaseParenthesizableWhitespace = SimpleWhitespace.field(" ") #: Any space that appears directly after this operator. whitespace_after: BaseParenthesizableWhitespace = SimpleWhitespace.field(" ") def _get_tokens(self) -> Tuple[str, str]: return ("not", "in") class IsNot(BaseCompOp, _BaseTwoTokenOp): """ A comparision operator that can be used in a :class:`Comparison` expression. This operator spans two tokens that must be separated by at least one space, so there is a third whitespace attribute to represent this. """ #: Any space that appears directly before this operator. whitespace_before: BaseParenthesizableWhitespace = SimpleWhitespace.field(" ") #: Any space that appears between the ``is`` and ``not`` tokens. whitespace_between: BaseParenthesizableWhitespace = SimpleWhitespace.field(" ") #: Any space that appears directly after this operator. whitespace_after: BaseParenthesizableWhitespace = SimpleWhitespace.field(" ") def _get_tokens(self) -> Tuple[str, str]: return ("is", "not") ParserConfig = config_mod.ParserConfig parse_parenthesizable_whitespace = mod.parse_parenthesizable_whitespace def convert_comp_op( config: ParserConfig, children: typing.Sequence[typing.Any] ) -> typing.Any: if len(children) == 1: (op,) = children if op.string in COMPOP_TOKEN_LUT: # A regular comparison containing one token # pyre-ignore Pyre thinks that the type of the LUT is CSTNode. return COMPOP_TOKEN_LUT[op.string]( whitespace_before=parse_parenthesizable_whitespace( config, op.whitespace_before ), whitespace_after=parse_parenthesizable_whitespace( config, op.whitespace_after ), ) elif op.string in ["!=", "<>"]: # Not equal, which can take two forms in some cases return NotEqual( whitespace_before=parse_parenthesizable_whitespace( config, op.whitespace_before ), value=op.string, whitespace_after=parse_parenthesizable_whitespace( config, op.whitespace_after ), ) else: # this should be unreachable raise Exception(f"Unexpected token '{op.string}'!") else: # A two-token comparison leftcomp, rightcomp = children if leftcomp.string == "not" and rightcomp.string == "in": return NotIn( whitespace_before=parse_parenthesizable_whitespace( config, leftcomp.whitespace_before ), whitespace_between=parse_parenthesizable_whitespace( config, leftcomp.whitespace_after ), whitespace_after=parse_parenthesizable_whitespace( config, rightcomp.whitespace_after ), ) elif leftcomp.string == "is" and rightcomp.string == "not": return IsNot( whitespace_before=parse_parenthesizable_whitespace( config, leftcomp.whitespace_before ), whitespace_between=parse_parenthesizable_whitespace( config, leftcomp.whitespace_after ), whitespace_after=parse_parenthesizable_whitespace( config, rightcomp.whitespace_after ), ) else: # this should be unreachable raise Exception(f"Unexpected token '{leftcomp.string} {rightcomp.string}'!")
null