All patches and comments are welcome. Please squash your changes to logical
commits before using git-format-patch and git-send-email to
patches@git.madduck.net.
If you'd read over the Git project's submission guidelines and adhered to them,
I'd be especially grateful.
   2 from asyncio.base_events import BaseEventLoop
 
   3 from concurrent.futures import Executor, ProcessPoolExecutor
 
   4 from datetime import datetime
 
   5 from enum import Enum, Flag
 
   6 from functools import lru_cache, partial, wraps
 
  11 from multiprocessing import Manager, freeze_support
 
  13 from pathlib import Path
 
  39 from appdirs import user_cache_dir
 
  40 from attr import dataclass, Factory
 
  45 from blib2to3.pytree import Node, Leaf, type_repr
 
  46 from blib2to3 import pygram, pytree
 
  47 from blib2to3.pgen2 import driver, token
 
  48 from blib2to3.pgen2.parse import ParseError
 
  51 __version__ = "18.9b0"
 
  52 DEFAULT_LINE_LENGTH = 88
 
  54     r"/(\.eggs|\.git|\.hg|\.mypy_cache|\.nox|\.tox|\.venv|_build|buck-out|build|dist)/"
 
  56 DEFAULT_INCLUDES = r"\.pyi?$"
 
  57 CACHE_DIR = Path(user_cache_dir("black", version=__version__))
 
  69 LN = Union[Leaf, Node]
 
  70 SplitFunc = Callable[["Line", bool], Iterator["Line"]]
 
  73 CacheInfo = Tuple[Timestamp, FileSize]
 
  74 Cache = Dict[Path, CacheInfo]
 
  75 out = partial(click.secho, bold=True, err=True)
 
  76 err = partial(click.secho, fg="red", err=True)
 
  78 pygram.initialize(CACHE_DIR)
 
  79 syms = pygram.python_symbols
 
  82 class NothingChanged(UserWarning):
 
  83     """Raised when reformatted code is the same as source."""
 
  86 class CannotSplit(Exception):
 
  87     """A readable split that fits the allotted line length is impossible."""
 
  90 class InvalidInput(ValueError):
 
  91     """Raised when input source code fails all parse attempts."""
 
  94 class WriteBack(Enum):
 
 101     def from_configuration(cls, *, check: bool, diff: bool) -> "WriteBack":
 
 102         if check and not diff:
 
 105         return cls.DIFF if diff else cls.YES
 
 114 class FileMode(Flag):
 
 118     NO_STRING_NORMALIZATION = 4
 
 119     NO_NUMERIC_UNDERSCORE_NORMALIZATION = 8
 
 122     def from_configuration(
 
 127         skip_string_normalization: bool,
 
 128         skip_numeric_underscore_normalization: bool,
 
 130         mode = cls.AUTO_DETECT
 
 135         if skip_string_normalization:
 
 136             mode |= cls.NO_STRING_NORMALIZATION
 
 137         if skip_numeric_underscore_normalization:
 
 138             mode |= cls.NO_NUMERIC_UNDERSCORE_NORMALIZATION
 
 142 def read_pyproject_toml(
 
 143     ctx: click.Context, param: click.Parameter, value: Union[str, int, bool, None]
 
 145     """Inject Black configuration from "pyproject.toml" into defaults in `ctx`.
 
 147     Returns the path to a successfully found and read configuration file, None
 
 150     assert not isinstance(value, (int, bool)), "Invalid parameter type passed"
 
 152         root = find_project_root(ctx.params.get("src", ()))
 
 153         path = root / "pyproject.toml"
 
 160         pyproject_toml = toml.load(value)
 
 161         config = pyproject_toml.get("tool", {}).get("black", {})
 
 162     except (toml.TomlDecodeError, OSError) as e:
 
 163         raise click.BadOptionUsage(f"Error reading configuration file: {e}", ctx)
 
 168     if ctx.default_map is None:
 
 170     ctx.default_map.update(  # type: ignore  # bad types in .pyi
 
 171         {k.replace("--", "").replace("-", "_"): v for k, v in config.items()}
 
 176 @click.command(context_settings=dict(help_option_names=["-h", "--help"]))
 
 181     default=DEFAULT_LINE_LENGTH,
 
 182     help="How many characters per line to allow.",
 
 189         "Allow using Python 3.6-only syntax on all input files.  This will put "
 
 190         "trailing commas in function signatures and calls also after *args and "
 
 191         "**kwargs.  [default: per-file auto-detection]"
 
 198         "Format all input files like typing stubs regardless of file extension "
 
 199         "(useful when piping source on standard input)."
 
 204     "--skip-string-normalization",
 
 206     help="Don't normalize string quotes or prefixes.",
 
 210     "--skip-numeric-underscore-normalization",
 
 212     help="Don't normalize underscores in numeric literals.",
 
 218         "Don't write the files back, just return the status.  Return code 0 "
 
 219         "means nothing would change.  Return code 1 means some files would be "
 
 220         "reformatted.  Return code 123 means there was an internal error."
 
 226     help="Don't write the files back, just output a diff for each file on stdout.",
 
 231     help="If --fast given, skip temporary sanity checks. [default: --safe]",
 
 236     default=DEFAULT_INCLUDES,
 
 238         "A regular expression that matches files and directories that should be "
 
 239         "included on recursive searches.  An empty value means all files are "
 
 240         "included regardless of the name.  Use forward slashes for directories on "
 
 241         "all platforms (Windows, too).  Exclusions are calculated first, inclusions "
 
 249     default=DEFAULT_EXCLUDES,
 
 251         "A regular expression that matches files and directories that should be "
 
 252         "excluded on recursive searches.  An empty value means no paths are excluded. "
 
 253         "Use forward slashes for directories on all platforms (Windows, too).  "
 
 254         "Exclusions are calculated first, inclusions later."
 
 263         "Don't emit non-error messages to stderr. Errors are still emitted, "
 
 264         "silence those with 2>/dev/null."
 
 272         "Also emit messages to stderr about files that were not changed or were "
 
 273         "ignored due to --exclude=."
 
 276 @click.version_option(version=__version__)
 
 281         exists=True, file_okay=True, dir_okay=True, readable=True, allow_dash=True
 
 288         exists=False, file_okay=True, dir_okay=False, readable=True, allow_dash=False
 
 291     callback=read_pyproject_toml,
 
 292     help="Read configuration from PATH.",
 
 303     skip_string_normalization: bool,
 
 304     skip_numeric_underscore_normalization: bool,
 
 310     config: Optional[str],
 
 312     """The uncompromising code formatter."""
 
 313     write_back = WriteBack.from_configuration(check=check, diff=diff)
 
 314     mode = FileMode.from_configuration(
 
 317         skip_string_normalization=skip_string_normalization,
 
 318         skip_numeric_underscore_normalization=skip_numeric_underscore_normalization,
 
 320     if config and verbose:
 
 321         out(f"Using configuration from {config}.", bold=False, fg="blue")
 
 323         include_regex = re_compile_maybe_verbose(include)
 
 325         err(f"Invalid regular expression for include given: {include!r}")
 
 328         exclude_regex = re_compile_maybe_verbose(exclude)
 
 330         err(f"Invalid regular expression for exclude given: {exclude!r}")
 
 332     report = Report(check=check, quiet=quiet, verbose=verbose)
 
 333     root = find_project_root(src)
 
 334     sources: Set[Path] = set()
 
 339                 gen_python_files_in_dir(p, root, include_regex, exclude_regex, report)
 
 341         elif p.is_file() or s == "-":
 
 342             # if a file was explicitly given, we don't care about its extension
 
 345             err(f"invalid path: {s}")
 
 346     if len(sources) == 0:
 
 347         if verbose or not quiet:
 
 348             out("No paths given. Nothing to do 😴")
 
 351     if len(sources) == 1:
 
 354             line_length=line_length,
 
 356             write_back=write_back,
 
 361         loop = asyncio.get_event_loop()
 
 362         executor = ProcessPoolExecutor(max_workers=os.cpu_count())
 
 364             loop.run_until_complete(
 
 367                     line_length=line_length,
 
 369                     write_back=write_back,
 
 378     if verbose or not quiet:
 
 379         bang = "💥 💔 💥" if report.return_code else "✨ 🍰 ✨"
 
 380         out(f"All done! {bang}")
 
 381         click.secho(str(report), err=True)
 
 382     ctx.exit(report.return_code)
 
 389     write_back: WriteBack,
 
 393     """Reformat a single file under `src` without spawning child processes.
 
 395     If `quiet` is True, non-error messages are not output. `line_length`,
 
 396     `write_back`, `fast` and `pyi` options are passed to
 
 397     :func:`format_file_in_place` or :func:`format_stdin_to_stdout`.
 
 401         if not src.is_file() and str(src) == "-":
 
 402             if format_stdin_to_stdout(
 
 403                 line_length=line_length, fast=fast, write_back=write_back, mode=mode
 
 405                 changed = Changed.YES
 
 408             if write_back != WriteBack.DIFF:
 
 409                 cache = read_cache(line_length, mode)
 
 410                 res_src = src.resolve()
 
 411                 if res_src in cache and cache[res_src] == get_cache_info(res_src):
 
 412                     changed = Changed.CACHED
 
 413             if changed is not Changed.CACHED and format_file_in_place(
 
 415                 line_length=line_length,
 
 417                 write_back=write_back,
 
 420                 changed = Changed.YES
 
 421             if (write_back is WriteBack.YES and changed is not Changed.CACHED) or (
 
 422                 write_back is WriteBack.CHECK and changed is Changed.NO
 
 424                 write_cache(cache, [src], line_length, mode)
 
 425         report.done(src, changed)
 
 426     except Exception as exc:
 
 427         report.failed(src, str(exc))
 
 430 async def schedule_formatting(
 
 434     write_back: WriteBack,
 
 440     """Run formatting of `sources` in parallel using the provided `executor`.
 
 442     (Use ProcessPoolExecutors for actual parallelism.)
 
 444     `line_length`, `write_back`, `fast`, and `pyi` options are passed to
 
 445     :func:`format_file_in_place`.
 
 448     if write_back != WriteBack.DIFF:
 
 449         cache = read_cache(line_length, mode)
 
 450         sources, cached = filter_cached(cache, sources)
 
 451         for src in sorted(cached):
 
 452             report.done(src, Changed.CACHED)
 
 457     sources_to_cache = []
 
 459     if write_back == WriteBack.DIFF:
 
 460         # For diff output, we need locks to ensure we don't interleave output
 
 461         # from different processes.
 
 463         lock = manager.Lock()
 
 465         loop.run_in_executor(
 
 467             format_file_in_place,
 
 475         for src in sorted(sources)
 
 477     pending: Iterable[asyncio.Task] = tasks.keys()
 
 479         loop.add_signal_handler(signal.SIGINT, cancel, pending)
 
 480         loop.add_signal_handler(signal.SIGTERM, cancel, pending)
 
 481     except NotImplementedError:
 
 482         # There are no good alternatives for these on Windows.
 
 485         done, _ = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
 
 487             src = tasks.pop(task)
 
 489                 cancelled.append(task)
 
 490             elif task.exception():
 
 491                 report.failed(src, str(task.exception()))
 
 493                 changed = Changed.YES if task.result() else Changed.NO
 
 494                 # If the file was written back or was successfully checked as
 
 495                 # well-formatted, store this information in the cache.
 
 496                 if write_back is WriteBack.YES or (
 
 497                     write_back is WriteBack.CHECK and changed is Changed.NO
 
 499                     sources_to_cache.append(src)
 
 500                 report.done(src, changed)
 
 502         await asyncio.gather(*cancelled, loop=loop, return_exceptions=True)
 
 504         write_cache(cache, sources_to_cache, line_length, mode)
 
 507 def format_file_in_place(
 
 511     write_back: WriteBack = WriteBack.NO,
 
 512     mode: FileMode = FileMode.AUTO_DETECT,
 
 513     lock: Any = None,  # multiprocessing.Manager().Lock() is some crazy proxy
 
 515     """Format file under `src` path. Return True if changed.
 
 517     If `write_back` is DIFF, write a diff to stdout. If it is YES, write reformatted
 
 519     `line_length` and `fast` options are passed to :func:`format_file_contents`.
 
 521     if src.suffix == ".pyi":
 
 524     then = datetime.utcfromtimestamp(src.stat().st_mtime)
 
 525     with open(src, "rb") as buf:
 
 526         src_contents, encoding, newline = decode_bytes(buf.read())
 
 528         dst_contents = format_file_contents(
 
 529             src_contents, line_length=line_length, fast=fast, mode=mode
 
 531     except NothingChanged:
 
 534     if write_back == write_back.YES:
 
 535         with open(src, "w", encoding=encoding, newline=newline) as f:
 
 536             f.write(dst_contents)
 
 537     elif write_back == write_back.DIFF:
 
 538         now = datetime.utcnow()
 
 539         src_name = f"{src}\t{then} +0000"
 
 540         dst_name = f"{src}\t{now} +0000"
 
 541         diff_contents = diff(src_contents, dst_contents, src_name, dst_name)
 
 545             f = io.TextIOWrapper(
 
 551             f.write(diff_contents)
 
 559 def format_stdin_to_stdout(
 
 562     write_back: WriteBack = WriteBack.NO,
 
 563     mode: FileMode = FileMode.AUTO_DETECT,
 
 565     """Format file on stdin. Return True if changed.
 
 567     If `write_back` is YES, write reformatted code back to stdout. If it is DIFF,
 
 568     write a diff to stdout.
 
 569     `line_length`, `fast`, `is_pyi`, and `force_py36` arguments are passed to
 
 570     :func:`format_file_contents`.
 
 572     then = datetime.utcnow()
 
 573     src, encoding, newline = decode_bytes(sys.stdin.buffer.read())
 
 576         dst = format_file_contents(src, line_length=line_length, fast=fast, mode=mode)
 
 579     except NothingChanged:
 
 583         f = io.TextIOWrapper(
 
 584             sys.stdout.buffer, encoding=encoding, newline=newline, write_through=True
 
 586         if write_back == WriteBack.YES:
 
 588         elif write_back == WriteBack.DIFF:
 
 589             now = datetime.utcnow()
 
 590             src_name = f"STDIN\t{then} +0000"
 
 591             dst_name = f"STDOUT\t{now} +0000"
 
 592             f.write(diff(src, dst, src_name, dst_name))
 
 596 def format_file_contents(
 
 601     mode: FileMode = FileMode.AUTO_DETECT,
 
 603     """Reformat contents a file and return new contents.
 
 605     If `fast` is False, additionally confirm that the reformatted code is
 
 606     valid by calling :func:`assert_equivalent` and :func:`assert_stable` on it.
 
 607     `line_length` is passed to :func:`format_str`.
 
 609     if src_contents.strip() == "":
 
 612     dst_contents = format_str(src_contents, line_length=line_length, mode=mode)
 
 613     if src_contents == dst_contents:
 
 617         assert_equivalent(src_contents, dst_contents)
 
 618         assert_stable(src_contents, dst_contents, line_length=line_length, mode=mode)
 
 623     src_contents: str, line_length: int, *, mode: FileMode = FileMode.AUTO_DETECT
 
 625     """Reformat a string and return new contents.
 
 627     `line_length` determines how many characters per line are allowed.
 
 629     src_node = lib2to3_parse(src_contents.lstrip())
 
 631     future_imports = get_future_imports(src_node)
 
 632     is_pyi = bool(mode & FileMode.PYI)
 
 633     py36 = bool(mode & FileMode.PYTHON36) or is_python36(src_node)
 
 634     normalize_strings = not bool(mode & FileMode.NO_STRING_NORMALIZATION)
 
 635     normalize_fmt_off(src_node)
 
 636     lines = LineGenerator(
 
 637         remove_u_prefix=py36 or "unicode_literals" in future_imports,
 
 639         normalize_strings=normalize_strings,
 
 640         allow_underscores=py36
 
 641         and not bool(mode & FileMode.NO_NUMERIC_UNDERSCORE_NORMALIZATION),
 
 643     elt = EmptyLineTracker(is_pyi=is_pyi)
 
 646     for current_line in lines.visit(src_node):
 
 647         for _ in range(after):
 
 648             dst_contents += str(empty_line)
 
 649         before, after = elt.maybe_empty_lines(current_line)
 
 650         for _ in range(before):
 
 651             dst_contents += str(empty_line)
 
 652         for line in split_line(current_line, line_length=line_length, py36=py36):
 
 653             dst_contents += str(line)
 
 657 def decode_bytes(src: bytes) -> Tuple[FileContent, Encoding, NewLine]:
 
 658     """Return a tuple of (decoded_contents, encoding, newline).
 
 660     `newline` is either CRLF or LF but `decoded_contents` is decoded with
 
 661     universal newlines (i.e. only contains LF).
 
 663     srcbuf = io.BytesIO(src)
 
 664     encoding, lines = tokenize.detect_encoding(srcbuf.readline)
 
 666         return "", encoding, "\n"
 
 668     newline = "\r\n" if b"\r\n" == lines[0][-2:] else "\n"
 
 670     with io.TextIOWrapper(srcbuf, encoding) as tiow:
 
 671         return tiow.read(), encoding, newline
 
 675     pygram.python_grammar_no_print_statement_no_exec_statement,
 
 676     pygram.python_grammar_no_print_statement,
 
 677     pygram.python_grammar,
 
 681 def lib2to3_parse(src_txt: str) -> Node:
 
 682     """Given a string with source, return the lib2to3 Node."""
 
 683     if src_txt[-1:] != "\n":
 
 685     for grammar in GRAMMARS:
 
 686         drv = driver.Driver(grammar, pytree.convert)
 
 688             result = drv.parse_string(src_txt, True)
 
 691         except ParseError as pe:
 
 692             lineno, column = pe.context[1]
 
 693             lines = src_txt.splitlines()
 
 695                 faulty_line = lines[lineno - 1]
 
 697                 faulty_line = "<line number missing in source>"
 
 698             exc = InvalidInput(f"Cannot parse: {lineno}:{column}: {faulty_line}")
 
 702     if isinstance(result, Leaf):
 
 703         result = Node(syms.file_input, [result])
 
 707 def lib2to3_unparse(node: Node) -> str:
 
 708     """Given a lib2to3 node, return its string representation."""
 
 716 class Visitor(Generic[T]):
 
 717     """Basic lib2to3 visitor that yields things of type `T` on `visit()`."""
 
 719     def visit(self, node: LN) -> Iterator[T]:
 
 720         """Main method to visit `node` and its children.
 
 722         It tries to find a `visit_*()` method for the given `node.type`, like
 
 723         `visit_simple_stmt` for Node objects or `visit_INDENT` for Leaf objects.
 
 724         If no dedicated `visit_*()` method is found, chooses `visit_default()`
 
 727         Then yields objects of type `T` from the selected visitor.
 
 730             name = token.tok_name[node.type]
 
 732             name = type_repr(node.type)
 
 733         yield from getattr(self, f"visit_{name}", self.visit_default)(node)
 
 735     def visit_default(self, node: LN) -> Iterator[T]:
 
 736         """Default `visit_*()` implementation. Recurses to children of `node`."""
 
 737         if isinstance(node, Node):
 
 738             for child in node.children:
 
 739                 yield from self.visit(child)
 
 743 class DebugVisitor(Visitor[T]):
 
 746     def visit_default(self, node: LN) -> Iterator[T]:
 
 747         indent = " " * (2 * self.tree_depth)
 
 748         if isinstance(node, Node):
 
 749             _type = type_repr(node.type)
 
 750             out(f"{indent}{_type}", fg="yellow")
 
 752             for child in node.children:
 
 753                 yield from self.visit(child)
 
 756             out(f"{indent}/{_type}", fg="yellow", bold=False)
 
 758             _type = token.tok_name.get(node.type, str(node.type))
 
 759             out(f"{indent}{_type}", fg="blue", nl=False)
 
 761                 # We don't have to handle prefixes for `Node` objects since
 
 762                 # that delegates to the first child anyway.
 
 763                 out(f" {node.prefix!r}", fg="green", bold=False, nl=False)
 
 764             out(f" {node.value!r}", fg="blue", bold=False)
 
 767     def show(cls, code: Union[str, Leaf, Node]) -> None:
 
 768         """Pretty-print the lib2to3 AST of a given string of `code`.
 
 770         Convenience method for debugging.
 
 772         v: DebugVisitor[None] = DebugVisitor()
 
 773         if isinstance(code, str):
 
 774             code = lib2to3_parse(code)
 
 778 KEYWORDS = set(keyword.kwlist)
 
 779 WHITESPACE = {token.DEDENT, token.INDENT, token.NEWLINE}
 
 780 FLOW_CONTROL = {"return", "raise", "break", "continue"}
 
 791 STANDALONE_COMMENT = 153
 
 792 token.tok_name[STANDALONE_COMMENT] = "STANDALONE_COMMENT"
 
 793 LOGIC_OPERATORS = {"and", "or"}
 
 818 STARS = {token.STAR, token.DOUBLESTAR}
 
 821     syms.argument,  # double star in arglist
 
 822     syms.trailer,  # single argument to call
 
 824     syms.varargslist,  # lambdas
 
 826 UNPACKING_PARENTS = {
 
 827     syms.atom,  # single element of a list or set literal
 
 831     syms.testlist_star_expr,
 
 866 COMPREHENSION_PRIORITY = 20
 
 868 TERNARY_PRIORITY = 16
 
 871 COMPARATOR_PRIORITY = 10
 
 882     token.DOUBLESLASH: 4,
 
 892 class BracketTracker:
 
 893     """Keeps track of brackets on a line."""
 
 896     bracket_match: Dict[Tuple[Depth, NodeType], Leaf] = Factory(dict)
 
 897     delimiters: Dict[LeafID, Priority] = Factory(dict)
 
 898     previous: Optional[Leaf] = None
 
 899     _for_loop_depths: List[int] = Factory(list)
 
 900     _lambda_argument_depths: List[int] = Factory(list)
 
 902     def mark(self, leaf: Leaf) -> None:
 
 903         """Mark `leaf` with bracket-related metadata. Keep track of delimiters.
 
 905         All leaves receive an int `bracket_depth` field that stores how deep
 
 906         within brackets a given leaf is. 0 means there are no enclosing brackets
 
 907         that started on this line.
 
 909         If a leaf is itself a closing bracket, it receives an `opening_bracket`
 
 910         field that it forms a pair with. This is a one-directional link to
 
 911         avoid reference cycles.
 
 913         If a leaf is a delimiter (a token on which Black can split the line if
 
 914         needed) and it's on depth 0, its `id()` is stored in the tracker's
 
 917         if leaf.type == token.COMMENT:
 
 920         self.maybe_decrement_after_for_loop_variable(leaf)
 
 921         self.maybe_decrement_after_lambda_arguments(leaf)
 
 922         if leaf.type in CLOSING_BRACKETS:
 
 924             opening_bracket = self.bracket_match.pop((self.depth, leaf.type))
 
 925             leaf.opening_bracket = opening_bracket
 
 926         leaf.bracket_depth = self.depth
 
 928             delim = is_split_before_delimiter(leaf, self.previous)
 
 929             if delim and self.previous is not None:
 
 930                 self.delimiters[id(self.previous)] = delim
 
 932                 delim = is_split_after_delimiter(leaf, self.previous)
 
 934                     self.delimiters[id(leaf)] = delim
 
 935         if leaf.type in OPENING_BRACKETS:
 
 936             self.bracket_match[self.depth, BRACKET[leaf.type]] = leaf
 
 939         self.maybe_increment_lambda_arguments(leaf)
 
 940         self.maybe_increment_for_loop_variable(leaf)
 
 942     def any_open_brackets(self) -> bool:
 
 943         """Return True if there is an yet unmatched open bracket on the line."""
 
 944         return bool(self.bracket_match)
 
 946     def max_delimiter_priority(self, exclude: Iterable[LeafID] = ()) -> int:
 
 947         """Return the highest priority of a delimiter found on the line.
 
 949         Values are consistent with what `is_split_*_delimiter()` return.
 
 950         Raises ValueError on no delimiters.
 
 952         return max(v for k, v in self.delimiters.items() if k not in exclude)
 
 954     def delimiter_count_with_priority(self, priority: int = 0) -> int:
 
 955         """Return the number of delimiters with the given `priority`.
 
 957         If no `priority` is passed, defaults to max priority on the line.
 
 959         if not self.delimiters:
 
 962         priority = priority or self.max_delimiter_priority()
 
 963         return sum(1 for p in self.delimiters.values() if p == priority)
 
 965     def maybe_increment_for_loop_variable(self, leaf: Leaf) -> bool:
 
 966         """In a for loop, or comprehension, the variables are often unpacks.
 
 968         To avoid splitting on the comma in this situation, increase the depth of
 
 969         tokens between `for` and `in`.
 
 971         if leaf.type == token.NAME and leaf.value == "for":
 
 973             self._for_loop_depths.append(self.depth)
 
 978     def maybe_decrement_after_for_loop_variable(self, leaf: Leaf) -> bool:
 
 979         """See `maybe_increment_for_loop_variable` above for explanation."""
 
 981             self._for_loop_depths
 
 982             and self._for_loop_depths[-1] == self.depth
 
 983             and leaf.type == token.NAME
 
 984             and leaf.value == "in"
 
 987             self._for_loop_depths.pop()
 
 992     def maybe_increment_lambda_arguments(self, leaf: Leaf) -> bool:
 
 993         """In a lambda expression, there might be more than one argument.
 
 995         To avoid splitting on the comma in this situation, increase the depth of
 
 996         tokens between `lambda` and `:`.
 
 998         if leaf.type == token.NAME and leaf.value == "lambda":
 
1000             self._lambda_argument_depths.append(self.depth)
 
1005     def maybe_decrement_after_lambda_arguments(self, leaf: Leaf) -> bool:
 
1006         """See `maybe_increment_lambda_arguments` above for explanation."""
 
1008             self._lambda_argument_depths
 
1009             and self._lambda_argument_depths[-1] == self.depth
 
1010             and leaf.type == token.COLON
 
1013             self._lambda_argument_depths.pop()
 
1018     def get_open_lsqb(self) -> Optional[Leaf]:
 
1019         """Return the most recent opening square bracket (if any)."""
 
1020         return self.bracket_match.get((self.depth - 1, token.RSQB))
 
1025     """Holds leaves and comments. Can be printed with `str(line)`."""
 
1028     leaves: List[Leaf] = Factory(list)
 
1029     # The LeafID keys of comments must remain ordered by the corresponding leaf's index
 
1031     comments: Dict[LeafID, List[Leaf]] = Factory(dict)
 
1032     bracket_tracker: BracketTracker = Factory(BracketTracker)
 
1033     inside_brackets: bool = False
 
1034     should_explode: bool = False
 
1036     def append(self, leaf: Leaf, preformatted: bool = False) -> None:
 
1037         """Add a new `leaf` to the end of the line.
 
1039         Unless `preformatted` is True, the `leaf` will receive a new consistent
 
1040         whitespace prefix and metadata applied by :class:`BracketTracker`.
 
1041         Trailing commas are maybe removed, unpacked for loop variables are
 
1042         demoted from being delimiters.
 
1044         Inline comments are put aside.
 
1046         has_value = leaf.type in BRACKETS or bool(leaf.value.strip())
 
1050         if token.COLON == leaf.type and self.is_class_paren_empty:
 
1051             del self.leaves[-2:]
 
1052         if self.leaves and not preformatted:
 
1053             # Note: at this point leaf.prefix should be empty except for
 
1054             # imports, for which we only preserve newlines.
 
1055             leaf.prefix += whitespace(
 
1056                 leaf, complex_subscript=self.is_complex_subscript(leaf)
 
1058         if self.inside_brackets or not preformatted:
 
1059             self.bracket_tracker.mark(leaf)
 
1060             self.maybe_remove_trailing_comma(leaf)
 
1061         if not self.append_comment(leaf):
 
1062             self.leaves.append(leaf)
 
1064     def append_safe(self, leaf: Leaf, preformatted: bool = False) -> None:
 
1065         """Like :func:`append()` but disallow invalid standalone comment structure.
 
1067         Raises ValueError when any `leaf` is appended after a standalone comment
 
1068         or when a standalone comment is not the first leaf on the line.
 
1070         if self.bracket_tracker.depth == 0:
 
1072                 raise ValueError("cannot append to standalone comments")
 
1074             if self.leaves and leaf.type == STANDALONE_COMMENT:
 
1076                     "cannot append standalone comments to a populated line"
 
1079         self.append(leaf, preformatted=preformatted)
 
1082     def is_comment(self) -> bool:
 
1083         """Is this line a standalone comment?"""
 
1084         return len(self.leaves) == 1 and self.leaves[0].type == STANDALONE_COMMENT
 
1087     def is_decorator(self) -> bool:
 
1088         """Is this line a decorator?"""
 
1089         return bool(self) and self.leaves[0].type == token.AT
 
1092     def is_import(self) -> bool:
 
1093         """Is this an import line?"""
 
1094         return bool(self) and is_import(self.leaves[0])
 
1097     def is_class(self) -> bool:
 
1098         """Is this line a class definition?"""
 
1101             and self.leaves[0].type == token.NAME
 
1102             and self.leaves[0].value == "class"
 
1106     def is_stub_class(self) -> bool:
 
1107         """Is this line a class definition with a body consisting only of "..."?"""
 
1108         return self.is_class and self.leaves[-3:] == [
 
1109             Leaf(token.DOT, ".") for _ in range(3)
 
1113     def is_def(self) -> bool:
 
1114         """Is this a function definition? (Also returns True for async defs.)"""
 
1116             first_leaf = self.leaves[0]
 
1121             second_leaf: Optional[Leaf] = self.leaves[1]
 
1124         return (first_leaf.type == token.NAME and first_leaf.value == "def") or (
 
1125             first_leaf.type == token.ASYNC
 
1126             and second_leaf is not None
 
1127             and second_leaf.type == token.NAME
 
1128             and second_leaf.value == "def"
 
1132     def is_class_paren_empty(self) -> bool:
 
1133         """Is this a class with no base classes but using parentheses?
 
1135         Those are unnecessary and should be removed.
 
1139             and len(self.leaves) == 4
 
1141             and self.leaves[2].type == token.LPAR
 
1142             and self.leaves[2].value == "("
 
1143             and self.leaves[3].type == token.RPAR
 
1144             and self.leaves[3].value == ")"
 
1148     def is_triple_quoted_string(self) -> bool:
 
1149         """Is the line a triple quoted string?"""
 
1152             and self.leaves[0].type == token.STRING
 
1153             and self.leaves[0].value.startswith(('"""', "'''"))
 
1156     def contains_standalone_comments(self, depth_limit: int = sys.maxsize) -> bool:
 
1157         """If so, needs to be split before emitting."""
 
1158         for leaf in self.leaves:
 
1159             if leaf.type == STANDALONE_COMMENT:
 
1160                 if leaf.bracket_depth <= depth_limit:
 
1165     def contains_multiline_strings(self) -> bool:
 
1166         for leaf in self.leaves:
 
1167             if is_multiline_string(leaf):
 
1172     def maybe_remove_trailing_comma(self, closing: Leaf) -> bool:
 
1173         """Remove trailing comma if there is one and it's safe."""
 
1176             and self.leaves[-1].type == token.COMMA
 
1177             and closing.type in CLOSING_BRACKETS
 
1181         if closing.type == token.RBRACE:
 
1182             self.remove_trailing_comma()
 
1185         if closing.type == token.RSQB:
 
1186             comma = self.leaves[-1]
 
1187             if comma.parent and comma.parent.type == syms.listmaker:
 
1188                 self.remove_trailing_comma()
 
1191         # For parens let's check if it's safe to remove the comma.
 
1192         # Imports are always safe.
 
1194             self.remove_trailing_comma()
 
1197         # Otherwise, if the trailing one is the only one, we might mistakenly
 
1198         # change a tuple into a different type by removing the comma.
 
1199         depth = closing.bracket_depth + 1
 
1201         opening = closing.opening_bracket
 
1202         for _opening_index, leaf in enumerate(self.leaves):
 
1209         for leaf in self.leaves[_opening_index + 1 :]:
 
1213             bracket_depth = leaf.bracket_depth
 
1214             if bracket_depth == depth and leaf.type == token.COMMA:
 
1216                 if leaf.parent and leaf.parent.type == syms.arglist:
 
1221             self.remove_trailing_comma()
 
1226     def append_comment(self, comment: Leaf) -> bool:
 
1227         """Add an inline or standalone comment to the line."""
 
1229             comment.type == STANDALONE_COMMENT
 
1230             and self.bracket_tracker.any_open_brackets()
 
1235         if comment.type != token.COMMENT:
 
1239             comment.type = STANDALONE_COMMENT
 
1244             leaf_id = id(self.leaves[-1])
 
1245             if leaf_id not in self.comments:
 
1246                 self.comments[leaf_id] = [comment]
 
1248                 self.comments[leaf_id].append(comment)
 
1251     def comments_after(self, leaf: Leaf) -> List[Leaf]:
 
1252         """Generate comments that should appear directly after `leaf`."""
 
1253         return self.comments.get(id(leaf), [])
 
1255     def remove_trailing_comma(self) -> None:
 
1256         """Remove the trailing comma and moves the comments attached to it."""
 
1257         # Remember, the LeafID keys of self.comments are ordered by the
 
1258         # corresponding leaf's index in self.leaves
 
1259         # If id(self.leaves[-2]) is in self.comments, the order doesn't change.
 
1260         # Otherwise, we insert it into self.comments, and it becomes the last entry.
 
1261         # However, since we delete id(self.leaves[-1]) from self.comments, the invariant
 
1263         self.comments.setdefault(id(self.leaves[-2]), []).extend(
 
1264             self.comments.get(id(self.leaves[-1]), [])
 
1266         self.comments.pop(id(self.leaves[-1]), None)
 
1269     def is_complex_subscript(self, leaf: Leaf) -> bool:
 
1270         """Return True iff `leaf` is part of a slice with non-trivial exprs."""
 
1271         open_lsqb = self.bracket_tracker.get_open_lsqb()
 
1272         if open_lsqb is None:
 
1275         subscript_start = open_lsqb.next_sibling
 
1277         if isinstance(subscript_start, Node):
 
1278             if subscript_start.type == syms.listmaker:
 
1281             if subscript_start.type == syms.subscriptlist:
 
1282                 subscript_start = child_towards(subscript_start, leaf)
 
1283         return subscript_start is not None and any(
 
1284             n.type in TEST_DESCENDANTS for n in subscript_start.pre_order()
 
1287     def __str__(self) -> str:
 
1288         """Render the line."""
 
1292         indent = "    " * self.depth
 
1293         leaves = iter(self.leaves)
 
1294         first = next(leaves)
 
1295         res = f"{first.prefix}{indent}{first.value}"
 
1298         for comment in itertools.chain.from_iterable(self.comments.values()):
 
1302     def __bool__(self) -> bool:
 
1303         """Return True if the line has leaves or comments."""
 
1304         return bool(self.leaves or self.comments)
 
1308 class EmptyLineTracker:
 
1309     """Provides a stateful method that returns the number of potential extra
 
1310     empty lines needed before and after the currently processed line.
 
1312     Note: this tracker works on lines that haven't been split yet.  It assumes
 
1313     the prefix of the first leaf consists of optional newlines.  Those newlines
 
1314     are consumed by `maybe_empty_lines()` and included in the computation.
 
1317     is_pyi: bool = False
 
1318     previous_line: Optional[Line] = None
 
1319     previous_after: int = 0
 
1320     previous_defs: List[int] = Factory(list)
 
1322     def maybe_empty_lines(self, current_line: Line) -> Tuple[int, int]:
 
1323         """Return the number of extra empty lines before and after the `current_line`.
 
1325         This is for separating `def`, `async def` and `class` with extra empty
 
1326         lines (two on module-level).
 
1328         before, after = self._maybe_empty_lines(current_line)
 
1329         before -= self.previous_after
 
1330         self.previous_after = after
 
1331         self.previous_line = current_line
 
1332         return before, after
 
1334     def _maybe_empty_lines(self, current_line: Line) -> Tuple[int, int]:
 
1336         if current_line.depth == 0:
 
1337             max_allowed = 1 if self.is_pyi else 2
 
1338         if current_line.leaves:
 
1339             # Consume the first leaf's extra newlines.
 
1340             first_leaf = current_line.leaves[0]
 
1341             before = first_leaf.prefix.count("\n")
 
1342             before = min(before, max_allowed)
 
1343             first_leaf.prefix = ""
 
1346         depth = current_line.depth
 
1347         while self.previous_defs and self.previous_defs[-1] >= depth:
 
1348             self.previous_defs.pop()
 
1350                 before = 0 if depth else 1
 
1352                 before = 1 if depth else 2
 
1353         if current_line.is_decorator or current_line.is_def or current_line.is_class:
 
1354             return self._maybe_empty_lines_for_class_or_def(current_line, before)
 
1358             and self.previous_line.is_import
 
1359             and not current_line.is_import
 
1360             and depth == self.previous_line.depth
 
1362             return (before or 1), 0
 
1366             and self.previous_line.is_class
 
1367             and current_line.is_triple_quoted_string
 
1373     def _maybe_empty_lines_for_class_or_def(
 
1374         self, current_line: Line, before: int
 
1375     ) -> Tuple[int, int]:
 
1376         if not current_line.is_decorator:
 
1377             self.previous_defs.append(current_line.depth)
 
1378         if self.previous_line is None:
 
1379             # Don't insert empty lines before the first line in the file.
 
1382         if self.previous_line.is_decorator:
 
1385         if self.previous_line.depth < current_line.depth and (
 
1386             self.previous_line.is_class or self.previous_line.is_def
 
1391             self.previous_line.is_comment
 
1392             and self.previous_line.depth == current_line.depth
 
1398             if self.previous_line.depth > current_line.depth:
 
1400             elif current_line.is_class or self.previous_line.is_class:
 
1401                 if current_line.is_stub_class and self.previous_line.is_stub_class:
 
1402                     # No blank line between classes with an empty body
 
1406             elif current_line.is_def and not self.previous_line.is_def:
 
1407                 # Blank line between a block of functions and a block of non-functions
 
1413         if current_line.depth and newlines:
 
1419 class LineGenerator(Visitor[Line]):
 
1420     """Generates reformatted Line objects.  Empty lines are not emitted.
 
1422     Note: destroys the tree it's visiting by mutating prefixes of its leaves
 
1423     in ways that will no longer stringify to valid Python code on the tree.
 
1426     is_pyi: bool = False
 
1427     normalize_strings: bool = True
 
1428     current_line: Line = Factory(Line)
 
1429     remove_u_prefix: bool = False
 
1430     allow_underscores: bool = False
 
1432     def line(self, indent: int = 0) -> Iterator[Line]:
 
1435         If the line is empty, only emit if it makes sense.
 
1436         If the line is too long, split it first and then generate.
 
1438         If any lines were generated, set up a new current_line.
 
1440         if not self.current_line:
 
1441             self.current_line.depth += indent
 
1442             return  # Line is empty, don't emit. Creating a new one unnecessary.
 
1444         complete_line = self.current_line
 
1445         self.current_line = Line(depth=complete_line.depth + indent)
 
1448     def visit_default(self, node: LN) -> Iterator[Line]:
 
1449         """Default `visit_*()` implementation. Recurses to children of `node`."""
 
1450         if isinstance(node, Leaf):
 
1451             any_open_brackets = self.current_line.bracket_tracker.any_open_brackets()
 
1452             for comment in generate_comments(node):
 
1453                 if any_open_brackets:
 
1454                     # any comment within brackets is subject to splitting
 
1455                     self.current_line.append(comment)
 
1456                 elif comment.type == token.COMMENT:
 
1457                     # regular trailing comment
 
1458                     self.current_line.append(comment)
 
1459                     yield from self.line()
 
1462                     # regular standalone comment
 
1463                     yield from self.line()
 
1465                     self.current_line.append(comment)
 
1466                     yield from self.line()
 
1468             normalize_prefix(node, inside_brackets=any_open_brackets)
 
1469             if self.normalize_strings and node.type == token.STRING:
 
1470                 normalize_string_prefix(node, remove_u_prefix=self.remove_u_prefix)
 
1471                 normalize_string_quotes(node)
 
1472             if node.type == token.NUMBER:
 
1473                 normalize_numeric_literal(node, self.allow_underscores)
 
1474             if node.type not in WHITESPACE:
 
1475                 self.current_line.append(node)
 
1476         yield from super().visit_default(node)
 
1478     def visit_INDENT(self, node: Node) -> Iterator[Line]:
 
1479         """Increase indentation level, maybe yield a line."""
 
1480         # In blib2to3 INDENT never holds comments.
 
1481         yield from self.line(+1)
 
1482         yield from self.visit_default(node)
 
1484     def visit_DEDENT(self, node: Node) -> Iterator[Line]:
 
1485         """Decrease indentation level, maybe yield a line."""
 
1486         # The current line might still wait for trailing comments.  At DEDENT time
 
1487         # there won't be any (they would be prefixes on the preceding NEWLINE).
 
1488         # Emit the line then.
 
1489         yield from self.line()
 
1491         # While DEDENT has no value, its prefix may contain standalone comments
 
1492         # that belong to the current indentation level.  Get 'em.
 
1493         yield from self.visit_default(node)
 
1495         # Finally, emit the dedent.
 
1496         yield from self.line(-1)
 
1499         self, node: Node, keywords: Set[str], parens: Set[str]
 
1500     ) -> Iterator[Line]:
 
1501         """Visit a statement.
 
1503         This implementation is shared for `if`, `while`, `for`, `try`, `except`,
 
1504         `def`, `with`, `class`, `assert` and assignments.
 
1506         The relevant Python language `keywords` for a given statement will be
 
1507         NAME leaves within it. This methods puts those on a separate line.
 
1509         `parens` holds a set of string leaf values immediately after which
 
1510         invisible parens should be put.
 
1512         normalize_invisible_parens(node, parens_after=parens)
 
1513         for child in node.children:
 
1514             if child.type == token.NAME and child.value in keywords:  # type: ignore
 
1515                 yield from self.line()
 
1517             yield from self.visit(child)
 
1519     def visit_suite(self, node: Node) -> Iterator[Line]:
 
1520         """Visit a suite."""
 
1521         if self.is_pyi and is_stub_suite(node):
 
1522             yield from self.visit(node.children[2])
 
1524             yield from self.visit_default(node)
 
1526     def visit_simple_stmt(self, node: Node) -> Iterator[Line]:
 
1527         """Visit a statement without nested statements."""
 
1528         is_suite_like = node.parent and node.parent.type in STATEMENT
 
1530             if self.is_pyi and is_stub_body(node):
 
1531                 yield from self.visit_default(node)
 
1533                 yield from self.line(+1)
 
1534                 yield from self.visit_default(node)
 
1535                 yield from self.line(-1)
 
1538             if not self.is_pyi or not node.parent or not is_stub_suite(node.parent):
 
1539                 yield from self.line()
 
1540             yield from self.visit_default(node)
 
1542     def visit_async_stmt(self, node: Node) -> Iterator[Line]:
 
1543         """Visit `async def`, `async for`, `async with`."""
 
1544         yield from self.line()
 
1546         children = iter(node.children)
 
1547         for child in children:
 
1548             yield from self.visit(child)
 
1550             if child.type == token.ASYNC:
 
1553         internal_stmt = next(children)
 
1554         for child in internal_stmt.children:
 
1555             yield from self.visit(child)
 
1557     def visit_decorators(self, node: Node) -> Iterator[Line]:
 
1558         """Visit decorators."""
 
1559         for child in node.children:
 
1560             yield from self.line()
 
1561             yield from self.visit(child)
 
1563     def visit_SEMI(self, leaf: Leaf) -> Iterator[Line]:
 
1564         """Remove a semicolon and put the other statement on a separate line."""
 
1565         yield from self.line()
 
1567     def visit_ENDMARKER(self, leaf: Leaf) -> Iterator[Line]:
 
1568         """End of file. Process outstanding comments and end with a newline."""
 
1569         yield from self.visit_default(leaf)
 
1570         yield from self.line()
 
1572     def visit_STANDALONE_COMMENT(self, leaf: Leaf) -> Iterator[Line]:
 
1573         if not self.current_line.bracket_tracker.any_open_brackets():
 
1574             yield from self.line()
 
1575         yield from self.visit_default(leaf)
 
1577     def __attrs_post_init__(self) -> None:
 
1578         """You are in a twisty little maze of passages."""
 
1581         self.visit_assert_stmt = partial(v, keywords={"assert"}, parens={"assert", ","})
 
1582         self.visit_if_stmt = partial(
 
1583             v, keywords={"if", "else", "elif"}, parens={"if", "elif"}
 
1585         self.visit_while_stmt = partial(v, keywords={"while", "else"}, parens={"while"})
 
1586         self.visit_for_stmt = partial(v, keywords={"for", "else"}, parens={"for", "in"})
 
1587         self.visit_try_stmt = partial(
 
1588             v, keywords={"try", "except", "else", "finally"}, parens=Ø
 
1590         self.visit_except_clause = partial(v, keywords={"except"}, parens=Ø)
 
1591         self.visit_with_stmt = partial(v, keywords={"with"}, parens=Ø)
 
1592         self.visit_funcdef = partial(v, keywords={"def"}, parens=Ø)
 
1593         self.visit_classdef = partial(v, keywords={"class"}, parens=Ø)
 
1594         self.visit_expr_stmt = partial(v, keywords=Ø, parens=ASSIGNMENTS)
 
1595         self.visit_return_stmt = partial(v, keywords={"return"}, parens={"return"})
 
1596         self.visit_import_from = partial(v, keywords=Ø, parens={"import"})
 
1597         self.visit_async_funcdef = self.visit_async_stmt
 
1598         self.visit_decorated = self.visit_decorators
 
1601 IMPLICIT_TUPLE = {syms.testlist, syms.testlist_star_expr, syms.exprlist}
 
1602 BRACKET = {token.LPAR: token.RPAR, token.LSQB: token.RSQB, token.LBRACE: token.RBRACE}
 
1603 OPENING_BRACKETS = set(BRACKET.keys())
 
1604 CLOSING_BRACKETS = set(BRACKET.values())
 
1605 BRACKETS = OPENING_BRACKETS | CLOSING_BRACKETS
 
1606 ALWAYS_NO_SPACE = CLOSING_BRACKETS | {token.COMMA, STANDALONE_COMMENT}
 
1609 def whitespace(leaf: Leaf, *, complex_subscript: bool) -> str:  # noqa C901
 
1610     """Return whitespace prefix if needed for the given `leaf`.
 
1612     `complex_subscript` signals whether the given leaf is part of a subscription
 
1613     which has non-trivial arguments, like arithmetic expressions or function calls.
 
1621     if t in ALWAYS_NO_SPACE:
 
1624     if t == token.COMMENT:
 
1627     assert p is not None, f"INTERNAL ERROR: hand-made leaf without parent: {leaf!r}"
 
1628     if t == token.COLON and p.type not in {
 
1635     prev = leaf.prev_sibling
 
1637         prevp = preceding_leaf(p)
 
1638         if not prevp or prevp.type in OPENING_BRACKETS:
 
1641         if t == token.COLON:
 
1642             if prevp.type == token.COLON:
 
1645             elif prevp.type != token.COMMA and not complex_subscript:
 
1650         if prevp.type == token.EQUAL:
 
1652                 if prevp.parent.type in {
 
1660                 elif prevp.parent.type == syms.typedargslist:
 
1661                     # A bit hacky: if the equal sign has whitespace, it means we
 
1662                     # previously found it's a typed argument.  So, we're using
 
1666         elif prevp.type in STARS:
 
1667             if is_vararg(prevp, within=VARARGS_PARENTS | UNPACKING_PARENTS):
 
1670         elif prevp.type == token.COLON:
 
1671             if prevp.parent and prevp.parent.type in {syms.subscript, syms.sliceop}:
 
1672                 return SPACE if complex_subscript else NO
 
1676             and prevp.parent.type == syms.factor
 
1677             and prevp.type in MATH_OPERATORS
 
1682             prevp.type == token.RIGHTSHIFT
 
1684             and prevp.parent.type == syms.shift_expr
 
1685             and prevp.prev_sibling
 
1686             and prevp.prev_sibling.type == token.NAME
 
1687             and prevp.prev_sibling.value == "print"  # type: ignore
 
1689             # Python 2 print chevron
 
1692     elif prev.type in OPENING_BRACKETS:
 
1695     if p.type in {syms.parameters, syms.arglist}:
 
1696         # untyped function signatures or calls
 
1697         if not prev or prev.type != token.COMMA:
 
1700     elif p.type == syms.varargslist:
 
1702         if prev and prev.type != token.COMMA:
 
1705     elif p.type == syms.typedargslist:
 
1706         # typed function signatures
 
1710         if t == token.EQUAL:
 
1711             if prev.type != syms.tname:
 
1714         elif prev.type == token.EQUAL:
 
1715             # A bit hacky: if the equal sign has whitespace, it means we
 
1716             # previously found it's a typed argument.  So, we're using that, too.
 
1719         elif prev.type != token.COMMA:
 
1722     elif p.type == syms.tname:
 
1725             prevp = preceding_leaf(p)
 
1726             if not prevp or prevp.type != token.COMMA:
 
1729     elif p.type == syms.trailer:
 
1730         # attributes and calls
 
1731         if t == token.LPAR or t == token.RPAR:
 
1736                 prevp = preceding_leaf(p)
 
1737                 if not prevp or prevp.type != token.NUMBER:
 
1740             elif t == token.LSQB:
 
1743         elif prev.type != token.COMMA:
 
1746     elif p.type == syms.argument:
 
1748         if t == token.EQUAL:
 
1752             prevp = preceding_leaf(p)
 
1753             if not prevp or prevp.type == token.LPAR:
 
1756         elif prev.type in {token.EQUAL} | STARS:
 
1759     elif p.type == syms.decorator:
 
1763     elif p.type == syms.dotted_name:
 
1767         prevp = preceding_leaf(p)
 
1768         if not prevp or prevp.type == token.AT or prevp.type == token.DOT:
 
1771     elif p.type == syms.classdef:
 
1775         if prev and prev.type == token.LPAR:
 
1778     elif p.type in {syms.subscript, syms.sliceop}:
 
1781             assert p.parent is not None, "subscripts are always parented"
 
1782             if p.parent.type == syms.subscriptlist:
 
1787         elif not complex_subscript:
 
1790     elif p.type == syms.atom:
 
1791         if prev and t == token.DOT:
 
1792             # dots, but not the first one.
 
1795     elif p.type == syms.dictsetmaker:
 
1797         if prev and prev.type == token.DOUBLESTAR:
 
1800     elif p.type in {syms.factor, syms.star_expr}:
 
1803             prevp = preceding_leaf(p)
 
1804             if not prevp or prevp.type in OPENING_BRACKETS:
 
1807             prevp_parent = prevp.parent
 
1808             assert prevp_parent is not None
 
1809             if prevp.type == token.COLON and prevp_parent.type in {
 
1815             elif prevp.type == token.EQUAL and prevp_parent.type == syms.argument:
 
1818         elif t in {token.NAME, token.NUMBER, token.STRING}:
 
1821     elif p.type == syms.import_from:
 
1823             if prev and prev.type == token.DOT:
 
1826         elif t == token.NAME:
 
1830             if prev and prev.type == token.DOT:
 
1833     elif p.type == syms.sliceop:
 
1839 def preceding_leaf(node: Optional[LN]) -> Optional[Leaf]:
 
1840     """Return the first leaf that precedes `node`, if any."""
 
1842         res = node.prev_sibling
 
1844             if isinstance(res, Leaf):
 
1848                 return list(res.leaves())[-1]
 
1857 def child_towards(ancestor: Node, descendant: LN) -> Optional[LN]:
 
1858     """Return the child of `ancestor` that contains `descendant`."""
 
1859     node: Optional[LN] = descendant
 
1860     while node and node.parent != ancestor:
 
1865 def container_of(leaf: Leaf) -> LN:
 
1866     """Return `leaf` or one of its ancestors that is the topmost container of it.
 
1868     By "container" we mean a node where `leaf` is the very first child.
 
1870     same_prefix = leaf.prefix
 
1871     container: LN = leaf
 
1873         parent = container.parent
 
1877         if parent.children[0].prefix != same_prefix:
 
1880         if parent.type == syms.file_input:
 
1883         if parent.prev_sibling is not None and parent.prev_sibling.type in BRACKETS:
 
1890 def is_split_after_delimiter(leaf: Leaf, previous: Optional[Leaf] = None) -> int:
 
1891     """Return the priority of the `leaf` delimiter, given a line break after it.
 
1893     The delimiter priorities returned here are from those delimiters that would
 
1894     cause a line break after themselves.
 
1896     Higher numbers are higher priority.
 
1898     if leaf.type == token.COMMA:
 
1899         return COMMA_PRIORITY
 
1904 def is_split_before_delimiter(leaf: Leaf, previous: Optional[Leaf] = None) -> int:
 
1905     """Return the priority of the `leaf` delimiter, given a line break before it.
 
1907     The delimiter priorities returned here are from those delimiters that would
 
1908     cause a line break before themselves.
 
1910     Higher numbers are higher priority.
 
1912     if is_vararg(leaf, within=VARARGS_PARENTS | UNPACKING_PARENTS):
 
1913         # * and ** might also be MATH_OPERATORS but in this case they are not.
 
1914         # Don't treat them as a delimiter.
 
1918         leaf.type == token.DOT
 
1920         and leaf.parent.type not in {syms.import_from, syms.dotted_name}
 
1921         and (previous is None or previous.type in CLOSING_BRACKETS)
 
1926         leaf.type in MATH_OPERATORS
 
1928         and leaf.parent.type not in {syms.factor, syms.star_expr}
 
1930         return MATH_PRIORITIES[leaf.type]
 
1932     if leaf.type in COMPARATORS:
 
1933         return COMPARATOR_PRIORITY
 
1936         leaf.type == token.STRING
 
1937         and previous is not None
 
1938         and previous.type == token.STRING
 
1940         return STRING_PRIORITY
 
1942     if leaf.type not in {token.NAME, token.ASYNC}:
 
1948         and leaf.parent.type in {syms.comp_for, syms.old_comp_for}
 
1949         or leaf.type == token.ASYNC
 
1952             not isinstance(leaf.prev_sibling, Leaf)
 
1953             or leaf.prev_sibling.value != "async"
 
1955             return COMPREHENSION_PRIORITY
 
1960         and leaf.parent.type in {syms.comp_if, syms.old_comp_if}
 
1962         return COMPREHENSION_PRIORITY
 
1964     if leaf.value in {"if", "else"} and leaf.parent and leaf.parent.type == syms.test:
 
1965         return TERNARY_PRIORITY
 
1967     if leaf.value == "is":
 
1968         return COMPARATOR_PRIORITY
 
1973         and leaf.parent.type in {syms.comp_op, syms.comparison}
 
1975             previous is not None
 
1976             and previous.type == token.NAME
 
1977             and previous.value == "not"
 
1980         return COMPARATOR_PRIORITY
 
1985         and leaf.parent.type == syms.comp_op
 
1987             previous is not None
 
1988             and previous.type == token.NAME
 
1989             and previous.value == "is"
 
1992         return COMPARATOR_PRIORITY
 
1994     if leaf.value in LOGIC_OPERATORS and leaf.parent:
 
1995         return LOGIC_PRIORITY
 
2000 FMT_OFF = {"# fmt: off", "# fmt:off", "# yapf: disable"}
 
2001 FMT_ON = {"# fmt: on", "# fmt:on", "# yapf: enable"}
 
2004 def generate_comments(leaf: LN) -> Iterator[Leaf]:
 
2005     """Clean the prefix of the `leaf` and generate comments from it, if any.
 
2007     Comments in lib2to3 are shoved into the whitespace prefix.  This happens
 
2008     in `pgen2/driver.py:Driver.parse_tokens()`.  This was a brilliant implementation
 
2009     move because it does away with modifying the grammar to include all the
 
2010     possible places in which comments can be placed.
 
2012     The sad consequence for us though is that comments don't "belong" anywhere.
 
2013     This is why this function generates simple parentless Leaf objects for
 
2014     comments.  We simply don't know what the correct parent should be.
 
2016     No matter though, we can live without this.  We really only need to
 
2017     differentiate between inline and standalone comments.  The latter don't
 
2018     share the line with any code.
 
2020     Inline comments are emitted as regular token.COMMENT leaves.  Standalone
 
2021     are emitted with a fake STANDALONE_COMMENT token identifier.
 
2023     for pc in list_comments(leaf.prefix, is_endmarker=leaf.type == token.ENDMARKER):
 
2024         yield Leaf(pc.type, pc.value, prefix="\n" * pc.newlines)
 
2029     """Describes a piece of syntax that is a comment.
 
2031     It's not a :class:`blib2to3.pytree.Leaf` so that:
 
2033     * it can be cached (`Leaf` objects should not be reused more than once as
 
2034       they store their lineno, column, prefix, and parent information);
 
2035     * `newlines` and `consumed` fields are kept separate from the `value`. This
 
2036       simplifies handling of special marker comments like ``# fmt: off/on``.
 
2039     type: int  # token.COMMENT or STANDALONE_COMMENT
 
2040     value: str  # content of the comment
 
2041     newlines: int  # how many newlines before the comment
 
2042     consumed: int  # how many characters of the original leaf's prefix did we consume
 
2045 @lru_cache(maxsize=4096)
 
2046 def list_comments(prefix: str, *, is_endmarker: bool) -> List[ProtoComment]:
 
2047     """Return a list of :class:`ProtoComment` objects parsed from the given `prefix`."""
 
2048     result: List[ProtoComment] = []
 
2049     if not prefix or "#" not in prefix:
 
2054     for index, line in enumerate(prefix.split("\n")):
 
2055         consumed += len(line) + 1  # adding the length of the split '\n'
 
2056         line = line.lstrip()
 
2059         if not line.startswith("#"):
 
2062         if index == 0 and not is_endmarker:
 
2063             comment_type = token.COMMENT  # simple trailing comment
 
2065             comment_type = STANDALONE_COMMENT
 
2066         comment = make_comment(line)
 
2069                 type=comment_type, value=comment, newlines=nlines, consumed=consumed
 
2076 def make_comment(content: str) -> str:
 
2077     """Return a consistently formatted comment from the given `content` string.
 
2079     All comments (except for "##", "#!", "#:", '#'", "#%%") should have a single
 
2080     space between the hash sign and the content.
 
2082     If `content` didn't start with a hash sign, one is provided.
 
2084     content = content.rstrip()
 
2088     if content[0] == "#":
 
2089         content = content[1:]
 
2090     if content and content[0] not in " !:#'%":
 
2091         content = " " + content
 
2092     return "#" + content
 
2096     line: Line, line_length: int, inner: bool = False, py36: bool = False
 
2097 ) -> Iterator[Line]:
 
2098     """Split a `line` into potentially many lines.
 
2100     They should fit in the allotted `line_length` but might not be able to.
 
2101     `inner` signifies that there were a pair of brackets somewhere around the
 
2102     current `line`, possibly transitively. This means we can fallback to splitting
 
2103     by delimiters if the LHS/RHS don't yield any results.
 
2105     If `py36` is True, splitting may generate syntax that is only compatible
 
2106     with Python 3.6 and later.
 
2112     line_str = str(line).strip("\n")
 
2113     if not line.should_explode and is_line_short_enough(
 
2114         line, line_length=line_length, line_str=line_str
 
2119     split_funcs: List[SplitFunc]
 
2121         split_funcs = [left_hand_split]
 
2124         def rhs(line: Line, py36: bool = False) -> Iterator[Line]:
 
2125             for omit in generate_trailers_to_omit(line, line_length):
 
2126                 lines = list(right_hand_split(line, line_length, py36, omit=omit))
 
2127                 if is_line_short_enough(lines[0], line_length=line_length):
 
2131             # All splits failed, best effort split with no omits.
 
2132             # This mostly happens to multiline strings that are by definition
 
2133             # reported as not fitting a single line.
 
2134             yield from right_hand_split(line, py36)
 
2136         if line.inside_brackets:
 
2137             split_funcs = [delimiter_split, standalone_comment_split, rhs]
 
2140     for split_func in split_funcs:
 
2141         # We are accumulating lines in `result` because we might want to abort
 
2142         # mission and return the original line in the end, or attempt a different
 
2144         result: List[Line] = []
 
2146             for l in split_func(line, py36):
 
2147                 if str(l).strip("\n") == line_str:
 
2148                     raise CannotSplit("Split function returned an unchanged result")
 
2151                     split_line(l, line_length=line_length, inner=True, py36=py36)
 
2164 def left_hand_split(line: Line, py36: bool = False) -> Iterator[Line]:
 
2165     """Split line into many lines, starting with the first matching bracket pair.
 
2167     Note: this usually looks weird, only use this for function definitions.
 
2168     Prefer RHS otherwise.  This is why this function is not symmetrical with
 
2169     :func:`right_hand_split` which also handles optional parentheses.
 
2171     tail_leaves: List[Leaf] = []
 
2172     body_leaves: List[Leaf] = []
 
2173     head_leaves: List[Leaf] = []
 
2174     current_leaves = head_leaves
 
2175     matching_bracket = None
 
2176     for leaf in line.leaves:
 
2178             current_leaves is body_leaves
 
2179             and leaf.type in CLOSING_BRACKETS
 
2180             and leaf.opening_bracket is matching_bracket
 
2182             current_leaves = tail_leaves if body_leaves else head_leaves
 
2183         current_leaves.append(leaf)
 
2184         if current_leaves is head_leaves:
 
2185             if leaf.type in OPENING_BRACKETS:
 
2186                 matching_bracket = leaf
 
2187                 current_leaves = body_leaves
 
2188     if not matching_bracket:
 
2189         raise CannotSplit("No brackets found")
 
2191     head = bracket_split_build_line(head_leaves, line, matching_bracket)
 
2192     body = bracket_split_build_line(body_leaves, line, matching_bracket, is_body=True)
 
2193     tail = bracket_split_build_line(tail_leaves, line, matching_bracket)
 
2194     bracket_split_succeeded_or_raise(head, body, tail)
 
2195     for result in (head, body, tail):
 
2200 def right_hand_split(
 
2201     line: Line, line_length: int, py36: bool = False, omit: Collection[LeafID] = ()
 
2202 ) -> Iterator[Line]:
 
2203     """Split line into many lines, starting with the last matching bracket pair.
 
2205     If the split was by optional parentheses, attempt splitting without them, too.
 
2206     `omit` is a collection of closing bracket IDs that shouldn't be considered for
 
2209     Note: running this function modifies `bracket_depth` on the leaves of `line`.
 
2211     tail_leaves: List[Leaf] = []
 
2212     body_leaves: List[Leaf] = []
 
2213     head_leaves: List[Leaf] = []
 
2214     current_leaves = tail_leaves
 
2215     opening_bracket = None
 
2216     closing_bracket = None
 
2217     for leaf in reversed(line.leaves):
 
2218         if current_leaves is body_leaves:
 
2219             if leaf is opening_bracket:
 
2220                 current_leaves = head_leaves if body_leaves else tail_leaves
 
2221         current_leaves.append(leaf)
 
2222         if current_leaves is tail_leaves:
 
2223             if leaf.type in CLOSING_BRACKETS and id(leaf) not in omit:
 
2224                 opening_bracket = leaf.opening_bracket
 
2225                 closing_bracket = leaf
 
2226                 current_leaves = body_leaves
 
2227     if not (opening_bracket and closing_bracket and head_leaves):
 
2228         # If there is no opening or closing_bracket that means the split failed and
 
2229         # all content is in the tail.  Otherwise, if `head_leaves` are empty, it means
 
2230         # the matching `opening_bracket` wasn't available on `line` anymore.
 
2231         raise CannotSplit("No brackets found")
 
2233     tail_leaves.reverse()
 
2234     body_leaves.reverse()
 
2235     head_leaves.reverse()
 
2236     head = bracket_split_build_line(head_leaves, line, opening_bracket)
 
2237     body = bracket_split_build_line(body_leaves, line, opening_bracket, is_body=True)
 
2238     tail = bracket_split_build_line(tail_leaves, line, opening_bracket)
 
2239     bracket_split_succeeded_or_raise(head, body, tail)
 
2241         # the body shouldn't be exploded
 
2242         not body.should_explode
 
2243         # the opening bracket is an optional paren
 
2244         and opening_bracket.type == token.LPAR
 
2245         and not opening_bracket.value
 
2246         # the closing bracket is an optional paren
 
2247         and closing_bracket.type == token.RPAR
 
2248         and not closing_bracket.value
 
2249         # it's not an import (optional parens are the only thing we can split on
 
2250         # in this case; attempting a split without them is a waste of time)
 
2251         and not line.is_import
 
2252         # there are no standalone comments in the body
 
2253         and not body.contains_standalone_comments(0)
 
2254         # and we can actually remove the parens
 
2255         and can_omit_invisible_parens(body, line_length)
 
2257         omit = {id(closing_bracket), *omit}
 
2259             yield from right_hand_split(line, line_length, py36=py36, omit=omit)
 
2265                 or is_line_short_enough(body, line_length=line_length)
 
2268                     "Splitting failed, body is still too long and can't be split."
 
2271             elif head.contains_multiline_strings() or tail.contains_multiline_strings():
 
2273                     "The current optional pair of parentheses is bound to fail to "
 
2274                     "satisfy the splitting algorithm because the head or the tail "
 
2275                     "contains multiline strings which by definition never fit one "
 
2279     ensure_visible(opening_bracket)
 
2280     ensure_visible(closing_bracket)
 
2281     for result in (head, body, tail):
 
2286 def bracket_split_succeeded_or_raise(head: Line, body: Line, tail: Line) -> None:
 
2287     """Raise :exc:`CannotSplit` if the last left- or right-hand split failed.
 
2289     Do nothing otherwise.
 
2291     A left- or right-hand split is based on a pair of brackets. Content before
 
2292     (and including) the opening bracket is left on one line, content inside the
 
2293     brackets is put on a separate line, and finally content starting with and
 
2294     following the closing bracket is put on a separate line.
 
2296     Those are called `head`, `body`, and `tail`, respectively. If the split
 
2297     produced the same line (all content in `head`) or ended up with an empty `body`
 
2298     and the `tail` is just the closing bracket, then it's considered failed.
 
2300     tail_len = len(str(tail).strip())
 
2303             raise CannotSplit("Splitting brackets produced the same line")
 
2307                 f"Splitting brackets on an empty body to save "
 
2308                 f"{tail_len} characters is not worth it"
 
2312 def bracket_split_build_line(
 
2313     leaves: List[Leaf], original: Line, opening_bracket: Leaf, *, is_body: bool = False
 
2315     """Return a new line with given `leaves` and respective comments from `original`.
 
2317     If `is_body` is True, the result line is one-indented inside brackets and as such
 
2318     has its first leaf's prefix normalized and a trailing comma added when expected.
 
2320     result = Line(depth=original.depth)
 
2322         result.inside_brackets = True
 
2325             # Since body is a new indent level, remove spurious leading whitespace.
 
2326             normalize_prefix(leaves[0], inside_brackets=True)
 
2327             # Ensure a trailing comma when expected.
 
2328             if original.is_import:
 
2329                 if leaves[-1].type != token.COMMA:
 
2330                     leaves.append(Leaf(token.COMMA, ","))
 
2333         result.append(leaf, preformatted=True)
 
2334         for comment_after in original.comments_after(leaf):
 
2335             result.append(comment_after, preformatted=True)
 
2337         result.should_explode = should_explode(result, opening_bracket)
 
2341 def dont_increase_indentation(split_func: SplitFunc) -> SplitFunc:
 
2342     """Normalize prefix of the first leaf in every line returned by `split_func`.
 
2344     This is a decorator over relevant split functions.
 
2348     def split_wrapper(line: Line, py36: bool = False) -> Iterator[Line]:
 
2349         for l in split_func(line, py36):
 
2350             normalize_prefix(l.leaves[0], inside_brackets=True)
 
2353     return split_wrapper
 
2356 @dont_increase_indentation
 
2357 def delimiter_split(line: Line, py36: bool = False) -> Iterator[Line]:
 
2358     """Split according to delimiters of the highest priority.
 
2360     If `py36` is True, the split will add trailing commas also in function
 
2361     signatures that contain `*` and `**`.
 
2364         last_leaf = line.leaves[-1]
 
2366         raise CannotSplit("Line empty")
 
2368     bt = line.bracket_tracker
 
2370         delimiter_priority = bt.max_delimiter_priority(exclude={id(last_leaf)})
 
2372         raise CannotSplit("No delimiters found")
 
2374     if delimiter_priority == DOT_PRIORITY:
 
2375         if bt.delimiter_count_with_priority(delimiter_priority) == 1:
 
2376             raise CannotSplit("Splitting a single attribute from its owner looks wrong")
 
2378     current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
 
2379     lowest_depth = sys.maxsize
 
2380     trailing_comma_safe = True
 
2382     def append_to_line(leaf: Leaf) -> Iterator[Line]:
 
2383         """Append `leaf` to current line or to new line if appending impossible."""
 
2384         nonlocal current_line
 
2386             current_line.append_safe(leaf, preformatted=True)
 
2390             current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
 
2391             current_line.append(leaf)
 
2393     for leaf in line.leaves:
 
2394         yield from append_to_line(leaf)
 
2396         for comment_after in line.comments_after(leaf):
 
2397             yield from append_to_line(comment_after)
 
2399         lowest_depth = min(lowest_depth, leaf.bracket_depth)
 
2400         if leaf.bracket_depth == lowest_depth and is_vararg(
 
2401             leaf, within=VARARGS_PARENTS
 
2403             trailing_comma_safe = trailing_comma_safe and py36
 
2404         leaf_priority = bt.delimiters.get(id(leaf))
 
2405         if leaf_priority == delimiter_priority:
 
2408             current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
 
2412             and delimiter_priority == COMMA_PRIORITY
 
2413             and current_line.leaves[-1].type != token.COMMA
 
2414             and current_line.leaves[-1].type != STANDALONE_COMMENT
 
2416             current_line.append(Leaf(token.COMMA, ","))
 
2420 @dont_increase_indentation
 
2421 def standalone_comment_split(line: Line, py36: bool = False) -> Iterator[Line]:
 
2422     """Split standalone comments from the rest of the line."""
 
2423     if not line.contains_standalone_comments(0):
 
2424         raise CannotSplit("Line does not have any standalone comments")
 
2426     current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
 
2428     def append_to_line(leaf: Leaf) -> Iterator[Line]:
 
2429         """Append `leaf` to current line or to new line if appending impossible."""
 
2430         nonlocal current_line
 
2432             current_line.append_safe(leaf, preformatted=True)
 
2436             current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
 
2437             current_line.append(leaf)
 
2439     for leaf in line.leaves:
 
2440         yield from append_to_line(leaf)
 
2442         for comment_after in line.comments_after(leaf):
 
2443             yield from append_to_line(comment_after)
 
2449 def is_import(leaf: Leaf) -> bool:
 
2450     """Return True if the given leaf starts an import statement."""
 
2457             (v == "import" and p and p.type == syms.import_name)
 
2458             or (v == "from" and p and p.type == syms.import_from)
 
2463 def normalize_prefix(leaf: Leaf, *, inside_brackets: bool) -> None:
 
2464     """Leave existing extra newlines if not `inside_brackets`. Remove everything
 
2467     Note: don't use backslashes for formatting or you'll lose your voting rights.
 
2469     if not inside_brackets:
 
2470         spl = leaf.prefix.split("#")
 
2471         if "\\" not in spl[0]:
 
2472             nl_count = spl[-1].count("\n")
 
2475             leaf.prefix = "\n" * nl_count
 
2481 def normalize_string_prefix(leaf: Leaf, remove_u_prefix: bool = False) -> None:
 
2482     """Make all string prefixes lowercase.
 
2484     If remove_u_prefix is given, also removes any u prefix from the string.
 
2486     Note: Mutates its argument.
 
2488     match = re.match(r"^([furbFURB]*)(.*)$", leaf.value, re.DOTALL)
 
2489     assert match is not None, f"failed to match string {leaf.value!r}"
 
2490     orig_prefix = match.group(1)
 
2491     new_prefix = orig_prefix.lower()
 
2493         new_prefix = new_prefix.replace("u", "")
 
2494     leaf.value = f"{new_prefix}{match.group(2)}"
 
2497 def normalize_string_quotes(leaf: Leaf) -> None:
 
2498     """Prefer double quotes but only if it doesn't cause more escaping.
 
2500     Adds or removes backslashes as appropriate. Doesn't parse and fix
 
2501     strings nested in f-strings (yet).
 
2503     Note: Mutates its argument.
 
2505     value = leaf.value.lstrip("furbFURB")
 
2506     if value[:3] == '"""':
 
2509     elif value[:3] == "'''":
 
2512     elif value[0] == '"':
 
2518     first_quote_pos = leaf.value.find(orig_quote)
 
2519     if first_quote_pos == -1:
 
2520         return  # There's an internal error
 
2522     prefix = leaf.value[:first_quote_pos]
 
2523     unescaped_new_quote = re.compile(rf"(([^\\]|^)(\\\\)*){new_quote}")
 
2524     escaped_new_quote = re.compile(rf"([^\\]|^)\\((?:\\\\)*){new_quote}")
 
2525     escaped_orig_quote = re.compile(rf"([^\\]|^)\\((?:\\\\)*){orig_quote}")
 
2526     body = leaf.value[first_quote_pos + len(orig_quote) : -len(orig_quote)]
 
2527     if "r" in prefix.casefold():
 
2528         if unescaped_new_quote.search(body):
 
2529             # There's at least one unescaped new_quote in this raw string
 
2530             # so converting is impossible
 
2533         # Do not introduce or remove backslashes in raw strings
 
2536         # remove unnecessary escapes
 
2537         new_body = sub_twice(escaped_new_quote, rf"\1\2{new_quote}", body)
 
2538         if body != new_body:
 
2539             # Consider the string without unnecessary escapes as the original
 
2541             leaf.value = f"{prefix}{orig_quote}{body}{orig_quote}"
 
2542         new_body = sub_twice(escaped_orig_quote, rf"\1\2{orig_quote}", new_body)
 
2543         new_body = sub_twice(unescaped_new_quote, rf"\1\\{new_quote}", new_body)
 
2544     if "f" in prefix.casefold():
 
2545         matches = re.findall(r"[^{]\{(.*?)\}[^}]", new_body)
 
2548                 # Do not introduce backslashes in interpolated expressions
 
2550     if new_quote == '"""' and new_body[-1:] == '"':
 
2552         new_body = new_body[:-1] + '\\"'
 
2553     orig_escape_count = body.count("\\")
 
2554     new_escape_count = new_body.count("\\")
 
2555     if new_escape_count > orig_escape_count:
 
2556         return  # Do not introduce more escaping
 
2558     if new_escape_count == orig_escape_count and orig_quote == '"':
 
2559         return  # Prefer double quotes
 
2561     leaf.value = f"{prefix}{new_quote}{new_body}{new_quote}"
 
2564 def normalize_numeric_literal(leaf: Leaf, allow_underscores: bool) -> None:
 
2565     """Normalizes numeric (float, int, and complex) literals.
 
2567     All letters used in the representation are normalized to lowercase (except
 
2568     in Python 2 long literals), and long number literals are split using underscores.
 
2570     text = leaf.value.lower()
 
2571     if text.startswith(("0o", "0b")):
 
2572         # Leave octal and binary literals alone.
 
2574     elif text.startswith("0x"):
 
2575         # Change hex literals to upper case.
 
2576         before, after = text[:2], text[2:]
 
2577         text = f"{before}{after.upper()}"
 
2579         before, after = text.split("e")
 
2581         if after.startswith("-"):
 
2584         elif after.startswith("+"):
 
2586         before = format_float_or_int_string(before, allow_underscores)
 
2587         after = format_int_string(after, allow_underscores)
 
2588         text = f"{before}e{sign}{after}"
 
2589     elif text.endswith(("j", "l")):
 
2592         # Capitalize in "2L" because "l" looks too similar to "1".
 
2595         text = f"{format_float_or_int_string(number, allow_underscores)}{suffix}"
 
2597         text = format_float_or_int_string(text, allow_underscores)
 
2601 def format_float_or_int_string(text: str, allow_underscores: bool) -> str:
 
2602     """Formats a float string like "1.0"."""
 
2604         return format_int_string(text, allow_underscores)
 
2606     before, after = text.split(".")
 
2607     before = format_int_string(before, allow_underscores) if before else "0"
 
2609         after = format_int_string(after, allow_underscores, count_from_end=False)
 
2612     return f"{before}.{after}"
 
2615 def format_int_string(
 
2616     text: str, allow_underscores: bool, count_from_end: bool = True
 
2618     """Normalizes underscores in a string to e.g. 1_000_000.
 
2620     Input must be a string of digits and optional underscores.
 
2621     If count_from_end is False, we add underscores after groups of three digits
 
2622     counting from the beginning instead of the end of the strings. This is used
 
2623     for the fractional part of float literals.
 
2625     if not allow_underscores:
 
2628     text = text.replace("_", "")
 
2630         # No underscores for numbers <= 5 digits long.
 
2634         # Avoid removing leading zeros, which are important if we're formatting
 
2635         # part of a number like "0.001".
 
2636         return format(int("1" + text), "3_")[1:].lstrip("_")
 
2638         return "_".join(text[i : i + 3] for i in range(0, len(text), 3))
 
2641 def normalize_invisible_parens(node: Node, parens_after: Set[str]) -> None:
 
2642     """Make existing optional parentheses invisible or create new ones.
 
2644     `parens_after` is a set of string leaf values immeditely after which parens
 
2647     Standardizes on visible parentheses for single-element tuples, and keeps
 
2648     existing visible parentheses for other tuples and generator expressions.
 
2650     for pc in list_comments(node.prefix, is_endmarker=False):
 
2651         if pc.value in FMT_OFF:
 
2652             # This `node` has a prefix with `# fmt: off`, don't mess with parens.
 
2656     for index, child in enumerate(list(node.children)):
 
2658             if child.type == syms.atom:
 
2659                 if maybe_make_parens_invisible_in_atom(child):
 
2660                     lpar = Leaf(token.LPAR, "")
 
2661                     rpar = Leaf(token.RPAR, "")
 
2662                     index = child.remove() or 0
 
2663                     node.insert_child(index, Node(syms.atom, [lpar, child, rpar]))
 
2664             elif is_one_tuple(child):
 
2665                 # wrap child in visible parentheses
 
2666                 lpar = Leaf(token.LPAR, "(")
 
2667                 rpar = Leaf(token.RPAR, ")")
 
2669                 node.insert_child(index, Node(syms.atom, [lpar, child, rpar]))
 
2670             elif node.type == syms.import_from:
 
2671                 # "import from" nodes store parentheses directly as part of
 
2673                 if child.type == token.LPAR:
 
2674                     # make parentheses invisible
 
2675                     child.value = ""  # type: ignore
 
2676                     node.children[-1].value = ""  # type: ignore
 
2677                 elif child.type != token.STAR:
 
2678                     # insert invisible parentheses
 
2679                     node.insert_child(index, Leaf(token.LPAR, ""))
 
2680                     node.append_child(Leaf(token.RPAR, ""))
 
2683             elif not (isinstance(child, Leaf) and is_multiline_string(child)):
 
2684                 # wrap child in invisible parentheses
 
2685                 lpar = Leaf(token.LPAR, "")
 
2686                 rpar = Leaf(token.RPAR, "")
 
2687                 index = child.remove() or 0
 
2688                 node.insert_child(index, Node(syms.atom, [lpar, child, rpar]))
 
2690         check_lpar = isinstance(child, Leaf) and child.value in parens_after
 
2693 def normalize_fmt_off(node: Node) -> None:
 
2694     """Convert content between `# fmt: off`/`# fmt: on` into standalone comments."""
 
2697         try_again = convert_one_fmt_off_pair(node)
 
2700 def convert_one_fmt_off_pair(node: Node) -> bool:
 
2701     """Convert content of a single `# fmt: off`/`# fmt: on` into a standalone comment.
 
2703     Returns True if a pair was converted.
 
2705     for leaf in node.leaves():
 
2706         previous_consumed = 0
 
2707         for comment in list_comments(leaf.prefix, is_endmarker=False):
 
2708             if comment.value in FMT_OFF:
 
2709                 # We only want standalone comments. If there's no previous leaf or
 
2710                 # the previous leaf is indentation, it's a standalone comment in
 
2712                 if comment.type != STANDALONE_COMMENT:
 
2713                     prev = preceding_leaf(leaf)
 
2714                     if prev and prev.type not in WHITESPACE:
 
2717                 ignored_nodes = list(generate_ignored_nodes(leaf))
 
2718                 if not ignored_nodes:
 
2721                 first = ignored_nodes[0]  # Can be a container node with the `leaf`.
 
2722                 parent = first.parent
 
2723                 prefix = first.prefix
 
2724                 first.prefix = prefix[comment.consumed :]
 
2726                     comment.value + "\n" + "".join(str(n) for n in ignored_nodes)
 
2728                 if hidden_value.endswith("\n"):
 
2729                     # That happens when one of the `ignored_nodes` ended with a NEWLINE
 
2730                     # leaf (possibly followed by a DEDENT).
 
2731                     hidden_value = hidden_value[:-1]
 
2733                 for ignored in ignored_nodes:
 
2734                     index = ignored.remove()
 
2735                     if first_idx is None:
 
2737                 assert parent is not None, "INTERNAL ERROR: fmt: on/off handling (1)"
 
2738                 assert first_idx is not None, "INTERNAL ERROR: fmt: on/off handling (2)"
 
2739                 parent.insert_child(
 
2744                         prefix=prefix[:previous_consumed] + "\n" * comment.newlines,
 
2749             previous_consumed = comment.consumed
 
2754 def generate_ignored_nodes(leaf: Leaf) -> Iterator[LN]:
 
2755     """Starting from the container of `leaf`, generate all leaves until `# fmt: on`.
 
2757     Stops at the end of the block.
 
2759     container: Optional[LN] = container_of(leaf)
 
2760     while container is not None and container.type != token.ENDMARKER:
 
2761         for comment in list_comments(container.prefix, is_endmarker=False):
 
2762             if comment.value in FMT_ON:
 
2767         container = container.next_sibling
 
2770 def maybe_make_parens_invisible_in_atom(node: LN) -> bool:
 
2771     """If it's safe, make the parens in the atom `node` invisible, recursively.
 
2773     Returns whether the node should itself be wrapped in invisible parentheses.
 
2777         node.type != syms.atom
 
2778         or is_empty_tuple(node)
 
2779         or is_one_tuple(node)
 
2781         or max_delimiter_priority_in_atom(node) >= COMMA_PRIORITY
 
2785     first = node.children[0]
 
2786     last = node.children[-1]
 
2787     if first.type == token.LPAR and last.type == token.RPAR:
 
2788         # make parentheses invisible
 
2789         first.value = ""  # type: ignore
 
2790         last.value = ""  # type: ignore
 
2791         if len(node.children) > 1:
 
2792             maybe_make_parens_invisible_in_atom(node.children[1])
 
2798 def is_empty_tuple(node: LN) -> bool:
 
2799     """Return True if `node` holds an empty tuple."""
 
2801         node.type == syms.atom
 
2802         and len(node.children) == 2
 
2803         and node.children[0].type == token.LPAR
 
2804         and node.children[1].type == token.RPAR
 
2808 def is_one_tuple(node: LN) -> bool:
 
2809     """Return True if `node` holds a tuple with one element, with or without parens."""
 
2810     if node.type == syms.atom:
 
2811         if len(node.children) != 3:
 
2814         lpar, gexp, rpar = node.children
 
2816             lpar.type == token.LPAR
 
2817             and gexp.type == syms.testlist_gexp
 
2818             and rpar.type == token.RPAR
 
2822         return len(gexp.children) == 2 and gexp.children[1].type == token.COMMA
 
2825         node.type in IMPLICIT_TUPLE
 
2826         and len(node.children) == 2
 
2827         and node.children[1].type == token.COMMA
 
2831 def is_yield(node: LN) -> bool:
 
2832     """Return True if `node` holds a `yield` or `yield from` expression."""
 
2833     if node.type == syms.yield_expr:
 
2836     if node.type == token.NAME and node.value == "yield":  # type: ignore
 
2839     if node.type != syms.atom:
 
2842     if len(node.children) != 3:
 
2845     lpar, expr, rpar = node.children
 
2846     if lpar.type == token.LPAR and rpar.type == token.RPAR:
 
2847         return is_yield(expr)
 
2852 def is_vararg(leaf: Leaf, within: Set[NodeType]) -> bool:
 
2853     """Return True if `leaf` is a star or double star in a vararg or kwarg.
 
2855     If `within` includes VARARGS_PARENTS, this applies to function signatures.
 
2856     If `within` includes UNPACKING_PARENTS, it applies to right hand-side
 
2857     extended iterable unpacking (PEP 3132) and additional unpacking
 
2858     generalizations (PEP 448).
 
2860     if leaf.type not in STARS or not leaf.parent:
 
2864     if p.type == syms.star_expr:
 
2865         # Star expressions are also used as assignment targets in extended
 
2866         # iterable unpacking (PEP 3132).  See what its parent is instead.
 
2872     return p.type in within
 
2875 def is_multiline_string(leaf: Leaf) -> bool:
 
2876     """Return True if `leaf` is a multiline string that actually spans many lines."""
 
2877     value = leaf.value.lstrip("furbFURB")
 
2878     return value[:3] in {'"""', "'''"} and "\n" in value
 
2881 def is_stub_suite(node: Node) -> bool:
 
2882     """Return True if `node` is a suite with a stub body."""
 
2884         len(node.children) != 4
 
2885         or node.children[0].type != token.NEWLINE
 
2886         or node.children[1].type != token.INDENT
 
2887         or node.children[3].type != token.DEDENT
 
2891     return is_stub_body(node.children[2])
 
2894 def is_stub_body(node: LN) -> bool:
 
2895     """Return True if `node` is a simple statement containing an ellipsis."""
 
2896     if not isinstance(node, Node) or node.type != syms.simple_stmt:
 
2899     if len(node.children) != 2:
 
2902     child = node.children[0]
 
2904         child.type == syms.atom
 
2905         and len(child.children) == 3
 
2906         and all(leaf == Leaf(token.DOT, ".") for leaf in child.children)
 
2910 def max_delimiter_priority_in_atom(node: LN) -> int:
 
2911     """Return maximum delimiter priority inside `node`.
 
2913     This is specific to atoms with contents contained in a pair of parentheses.
 
2914     If `node` isn't an atom or there are no enclosing parentheses, returns 0.
 
2916     if node.type != syms.atom:
 
2919     first = node.children[0]
 
2920     last = node.children[-1]
 
2921     if not (first.type == token.LPAR and last.type == token.RPAR):
 
2924     bt = BracketTracker()
 
2925     for c in node.children[1:-1]:
 
2926         if isinstance(c, Leaf):
 
2929             for leaf in c.leaves():
 
2932         return bt.max_delimiter_priority()
 
2938 def ensure_visible(leaf: Leaf) -> None:
 
2939     """Make sure parentheses are visible.
 
2941     They could be invisible as part of some statements (see
 
2942     :func:`normalize_invible_parens` and :func:`visit_import_from`).
 
2944     if leaf.type == token.LPAR:
 
2946     elif leaf.type == token.RPAR:
 
2950 def should_explode(line: Line, opening_bracket: Leaf) -> bool:
 
2951     """Should `line` immediately be split with `delimiter_split()` after RHS?"""
 
2953         opening_bracket.parent
 
2954         and opening_bracket.parent.type in {syms.atom, syms.import_from}
 
2955         and opening_bracket.value in "[{("
 
2960         last_leaf = line.leaves[-1]
 
2961         exclude = {id(last_leaf)} if last_leaf.type == token.COMMA else set()
 
2962         max_priority = line.bracket_tracker.max_delimiter_priority(exclude=exclude)
 
2963     except (IndexError, ValueError):
 
2966     return max_priority == COMMA_PRIORITY
 
2969 def is_python36(node: Node) -> bool:
 
2970     """Return True if the current file is using Python 3.6+ features.
 
2972     Currently looking for:
 
2974     - underscores in numeric literals; and
 
2975     - trailing commas after * or ** in function signatures and calls.
 
2977     for n in node.pre_order():
 
2978         if n.type == token.STRING:
 
2979             value_head = n.value[:2]  # type: ignore
 
2980             if value_head in {'f"', 'F"', "f'", "F'", "rf", "fr", "RF", "FR"}:
 
2983         elif n.type == token.NUMBER:
 
2984             if "_" in n.value:  # type: ignore
 
2988             n.type in {syms.typedargslist, syms.arglist}
 
2990             and n.children[-1].type == token.COMMA
 
2992             for ch in n.children:
 
2993                 if ch.type in STARS:
 
2996                 if ch.type == syms.argument:
 
2997                     for argch in ch.children:
 
2998                         if argch.type in STARS:
 
3004 def generate_trailers_to_omit(line: Line, line_length: int) -> Iterator[Set[LeafID]]:
 
3005     """Generate sets of closing bracket IDs that should be omitted in a RHS.
 
3007     Brackets can be omitted if the entire trailer up to and including
 
3008     a preceding closing bracket fits in one line.
 
3010     Yielded sets are cumulative (contain results of previous yields, too).  First
 
3014     omit: Set[LeafID] = set()
 
3017     length = 4 * line.depth
 
3018     opening_bracket = None
 
3019     closing_bracket = None
 
3020     inner_brackets: Set[LeafID] = set()
 
3021     for index, leaf, leaf_length in enumerate_with_length(line, reversed=True):
 
3022         length += leaf_length
 
3023         if length > line_length:
 
3026         has_inline_comment = leaf_length > len(leaf.value) + len(leaf.prefix)
 
3027         if leaf.type == STANDALONE_COMMENT or has_inline_comment:
 
3031             if leaf is opening_bracket:
 
3032                 opening_bracket = None
 
3033             elif leaf.type in CLOSING_BRACKETS:
 
3034                 inner_brackets.add(id(leaf))
 
3035         elif leaf.type in CLOSING_BRACKETS:
 
3036             if index > 0 and line.leaves[index - 1].type in OPENING_BRACKETS:
 
3037                 # Empty brackets would fail a split so treat them as "inner"
 
3038                 # brackets (e.g. only add them to the `omit` set if another
 
3039                 # pair of brackets was good enough.
 
3040                 inner_brackets.add(id(leaf))
 
3044                 omit.add(id(closing_bracket))
 
3045                 omit.update(inner_brackets)
 
3046                 inner_brackets.clear()
 
3050                 opening_bracket = leaf.opening_bracket
 
3051                 closing_bracket = leaf
 
3054 def get_future_imports(node: Node) -> Set[str]:
 
3055     """Return a set of __future__ imports in the file."""
 
3056     imports: Set[str] = set()
 
3058     def get_imports_from_children(children: List[LN]) -> Generator[str, None, None]:
 
3059         for child in children:
 
3060             if isinstance(child, Leaf):
 
3061                 if child.type == token.NAME:
 
3063             elif child.type == syms.import_as_name:
 
3064                 orig_name = child.children[0]
 
3065                 assert isinstance(orig_name, Leaf), "Invalid syntax parsing imports"
 
3066                 assert orig_name.type == token.NAME, "Invalid syntax parsing imports"
 
3067                 yield orig_name.value
 
3068             elif child.type == syms.import_as_names:
 
3069                 yield from get_imports_from_children(child.children)
 
3071                 assert False, "Invalid syntax parsing imports"
 
3073     for child in node.children:
 
3074         if child.type != syms.simple_stmt:
 
3076         first_child = child.children[0]
 
3077         if isinstance(first_child, Leaf):
 
3078             # Continue looking if we see a docstring; otherwise stop.
 
3080                 len(child.children) == 2
 
3081                 and first_child.type == token.STRING
 
3082                 and child.children[1].type == token.NEWLINE
 
3087         elif first_child.type == syms.import_from:
 
3088             module_name = first_child.children[1]
 
3089             if not isinstance(module_name, Leaf) or module_name.value != "__future__":
 
3091             imports |= set(get_imports_from_children(first_child.children[3:]))
 
3097 def gen_python_files_in_dir(
 
3100     include: Pattern[str],
 
3101     exclude: Pattern[str],
 
3103 ) -> Iterator[Path]:
 
3104     """Generate all files under `path` whose paths are not excluded by the
 
3105     `exclude` regex, but are included by the `include` regex.
 
3107     Symbolic links pointing outside of the `root` directory are ignored.
 
3109     `report` is where output about exclusions goes.
 
3111     assert root.is_absolute(), f"INTERNAL ERROR: `root` must be absolute but is {root}"
 
3112     for child in path.iterdir():
 
3114             normalized_path = "/" + child.resolve().relative_to(root).as_posix()
 
3116             if child.is_symlink():
 
3117                 report.path_ignored(
 
3118                     child, f"is a symbolic link that points outside {root}"
 
3125             normalized_path += "/"
 
3126         exclude_match = exclude.search(normalized_path)
 
3127         if exclude_match and exclude_match.group(0):
 
3128             report.path_ignored(child, f"matches the --exclude regular expression")
 
3132             yield from gen_python_files_in_dir(child, root, include, exclude, report)
 
3134         elif child.is_file():
 
3135             include_match = include.search(normalized_path)
 
3141 def find_project_root(srcs: Iterable[str]) -> Path:
 
3142     """Return a directory containing .git, .hg, or pyproject.toml.
 
3144     That directory can be one of the directories passed in `srcs` or their
 
3147     If no directory in the tree contains a marker that would specify it's the
 
3148     project root, the root of the file system is returned.
 
3151         return Path("/").resolve()
 
3153     common_base = min(Path(src).resolve() for src in srcs)
 
3154     if common_base.is_dir():
 
3155         # Append a fake file so `parents` below returns `common_base_dir`, too.
 
3156         common_base /= "fake-file"
 
3157     for directory in common_base.parents:
 
3158         if (directory / ".git").is_dir():
 
3161         if (directory / ".hg").is_dir():
 
3164         if (directory / "pyproject.toml").is_file():
 
3172     """Provides a reformatting counter. Can be rendered with `str(report)`."""
 
3176     verbose: bool = False
 
3177     change_count: int = 0
 
3179     failure_count: int = 0
 
3181     def done(self, src: Path, changed: Changed) -> None:
 
3182         """Increment the counter for successful reformatting. Write out a message."""
 
3183         if changed is Changed.YES:
 
3184             reformatted = "would reformat" if self.check else "reformatted"
 
3185             if self.verbose or not self.quiet:
 
3186                 out(f"{reformatted} {src}")
 
3187             self.change_count += 1
 
3190                 if changed is Changed.NO:
 
3191                     msg = f"{src} already well formatted, good job."
 
3193                     msg = f"{src} wasn't modified on disk since last run."
 
3194                 out(msg, bold=False)
 
3195             self.same_count += 1
 
3197     def failed(self, src: Path, message: str) -> None:
 
3198         """Increment the counter for failed reformatting. Write out a message."""
 
3199         err(f"error: cannot format {src}: {message}")
 
3200         self.failure_count += 1
 
3202     def path_ignored(self, path: Path, message: str) -> None:
 
3204             out(f"{path} ignored: {message}", bold=False)
 
3207     def return_code(self) -> int:
 
3208         """Return the exit code that the app should use.
 
3210         This considers the current state of changed files and failures:
 
3211         - if there were any failures, return 123;
 
3212         - if any files were changed and --check is being used, return 1;
 
3213         - otherwise return 0.
 
3215         # According to http://tldp.org/LDP/abs/html/exitcodes.html starting with
 
3216         # 126 we have special return codes reserved by the shell.
 
3217         if self.failure_count:
 
3220         elif self.change_count and self.check:
 
3225     def __str__(self) -> str:
 
3226         """Render a color report of the current state.
 
3228         Use `click.unstyle` to remove colors.
 
3231             reformatted = "would be reformatted"
 
3232             unchanged = "would be left unchanged"
 
3233             failed = "would fail to reformat"
 
3235             reformatted = "reformatted"
 
3236             unchanged = "left unchanged"
 
3237             failed = "failed to reformat"
 
3239         if self.change_count:
 
3240             s = "s" if self.change_count > 1 else ""
 
3242                 click.style(f"{self.change_count} file{s} {reformatted}", bold=True)
 
3245             s = "s" if self.same_count > 1 else ""
 
3246             report.append(f"{self.same_count} file{s} {unchanged}")
 
3247         if self.failure_count:
 
3248             s = "s" if self.failure_count > 1 else ""
 
3250                 click.style(f"{self.failure_count} file{s} {failed}", fg="red")
 
3252         return ", ".join(report) + "."
 
3255 def assert_equivalent(src: str, dst: str) -> None:
 
3256     """Raise AssertionError if `src` and `dst` aren't equivalent."""
 
3261     def _v(node: ast.AST, depth: int = 0) -> Iterator[str]:
 
3262         """Simple visitor generating strings to compare ASTs by content."""
 
3263         yield f"{'  ' * depth}{node.__class__.__name__}("
 
3265         for field in sorted(node._fields):
 
3267                 value = getattr(node, field)
 
3268             except AttributeError:
 
3271             yield f"{'  ' * (depth+1)}{field}="
 
3273             if isinstance(value, list):
 
3275                     if isinstance(item, ast.AST):
 
3276                         yield from _v(item, depth + 2)
 
3278             elif isinstance(value, ast.AST):
 
3279                 yield from _v(value, depth + 2)
 
3282                 yield f"{'  ' * (depth+2)}{value!r},  # {value.__class__.__name__}"
 
3284         yield f"{'  ' * depth})  # /{node.__class__.__name__}"
 
3287         src_ast = ast.parse(src)
 
3288     except Exception as exc:
 
3289         major, minor = sys.version_info[:2]
 
3290         raise AssertionError(
 
3291             f"cannot use --safe with this file; failed to parse source file "
 
3292             f"with Python {major}.{minor}'s builtin AST. Re-run with --fast "
 
3293             f"or stop using deprecated Python 2 syntax. AST error message: {exc}"
 
3297         dst_ast = ast.parse(dst)
 
3298     except Exception as exc:
 
3299         log = dump_to_file("".join(traceback.format_tb(exc.__traceback__)), dst)
 
3300         raise AssertionError(
 
3301             f"INTERNAL ERROR: Black produced invalid code: {exc}. "
 
3302             f"Please report a bug on https://github.com/ambv/black/issues.  "
 
3303             f"This invalid output might be helpful: {log}"
 
3306     src_ast_str = "\n".join(_v(src_ast))
 
3307     dst_ast_str = "\n".join(_v(dst_ast))
 
3308     if src_ast_str != dst_ast_str:
 
3309         log = dump_to_file(diff(src_ast_str, dst_ast_str, "src", "dst"))
 
3310         raise AssertionError(
 
3311             f"INTERNAL ERROR: Black produced code that is not equivalent to "
 
3313             f"Please report a bug on https://github.com/ambv/black/issues.  "
 
3314             f"This diff might be helpful: {log}"
 
3319     src: str, dst: str, line_length: int, mode: FileMode = FileMode.AUTO_DETECT
 
3321     """Raise AssertionError if `dst` reformats differently the second time."""
 
3322     newdst = format_str(dst, line_length=line_length, mode=mode)
 
3325             diff(src, dst, "source", "first pass"),
 
3326             diff(dst, newdst, "first pass", "second pass"),
 
3328         raise AssertionError(
 
3329             f"INTERNAL ERROR: Black produced different code on the second pass "
 
3330             f"of the formatter.  "
 
3331             f"Please report a bug on https://github.com/ambv/black/issues.  "
 
3332             f"This diff might be helpful: {log}"
 
3336 def dump_to_file(*output: str) -> str:
 
3337     """Dump `output` to a temporary file. Return path to the file."""
 
3340     with tempfile.NamedTemporaryFile(
 
3341         mode="w", prefix="blk_", suffix=".log", delete=False, encoding="utf8"
 
3343         for lines in output:
 
3345             if lines and lines[-1] != "\n":
 
3350 def diff(a: str, b: str, a_name: str, b_name: str) -> str:
 
3351     """Return a unified diff string between strings `a` and `b`."""
 
3354     a_lines = [line + "\n" for line in a.split("\n")]
 
3355     b_lines = [line + "\n" for line in b.split("\n")]
 
3357         difflib.unified_diff(a_lines, b_lines, fromfile=a_name, tofile=b_name, n=5)
 
3361 def cancel(tasks: Iterable[asyncio.Task]) -> None:
 
3362     """asyncio signal handler that cancels all `tasks` and reports to stderr."""
 
3368 def shutdown(loop: BaseEventLoop) -> None:
 
3369     """Cancel all pending tasks on `loop`, wait for them, and close the loop."""
 
3371         # This part is borrowed from asyncio/runners.py in Python 3.7b2.
 
3372         to_cancel = [task for task in asyncio.Task.all_tasks(loop) if not task.done()]
 
3376         for task in to_cancel:
 
3378         loop.run_until_complete(
 
3379             asyncio.gather(*to_cancel, loop=loop, return_exceptions=True)
 
3382         # `concurrent.futures.Future` objects cannot be cancelled once they
 
3383         # are already running. There might be some when the `shutdown()` happened.
 
3384         # Silence their logger's spew about the event loop being closed.
 
3385         cf_logger = logging.getLogger("concurrent.futures")
 
3386         cf_logger.setLevel(logging.CRITICAL)
 
3390 def sub_twice(regex: Pattern[str], replacement: str, original: str) -> str:
 
3391     """Replace `regex` with `replacement` twice on `original`.
 
3393     This is used by string normalization to perform replaces on
 
3394     overlapping matches.
 
3396     return regex.sub(replacement, regex.sub(replacement, original))
 
3399 def re_compile_maybe_verbose(regex: str) -> Pattern[str]:
 
3400     """Compile a regular expression string in `regex`.
 
3402     If it contains newlines, use verbose mode.
 
3405         regex = "(?x)" + regex
 
3406     return re.compile(regex)
 
3409 def enumerate_reversed(sequence: Sequence[T]) -> Iterator[Tuple[Index, T]]:
 
3410     """Like `reversed(enumerate(sequence))` if that were possible."""
 
3411     index = len(sequence) - 1
 
3412     for element in reversed(sequence):
 
3413         yield (index, element)
 
3417 def enumerate_with_length(
 
3418     line: Line, reversed: bool = False
 
3419 ) -> Iterator[Tuple[Index, Leaf, int]]:
 
3420     """Return an enumeration of leaves with their length.
 
3422     Stops prematurely on multiline strings and standalone comments.
 
3425         Callable[[Sequence[Leaf]], Iterator[Tuple[Index, Leaf]]],
 
3426         enumerate_reversed if reversed else enumerate,
 
3428     for index, leaf in op(line.leaves):
 
3429         length = len(leaf.prefix) + len(leaf.value)
 
3430         if "\n" in leaf.value:
 
3431             return  # Multiline strings, we can't continue.
 
3433         comment: Optional[Leaf]
 
3434         for comment in line.comments_after(leaf):
 
3435             length += len(comment.value)
 
3437         yield index, leaf, length
 
3440 def is_line_short_enough(line: Line, *, line_length: int, line_str: str = "") -> bool:
 
3441     """Return True if `line` is no longer than `line_length`.
 
3443     Uses the provided `line_str` rendering, if any, otherwise computes a new one.
 
3446         line_str = str(line).strip("\n")
 
3448         len(line_str) <= line_length
 
3449         and "\n" not in line_str  # multiline strings
 
3450         and not line.contains_standalone_comments()
 
3454 def can_be_split(line: Line) -> bool:
 
3455     """Return False if the line cannot be split *for sure*.
 
3457     This is not an exhaustive search but a cheap heuristic that we can use to
 
3458     avoid some unfortunate formattings (mostly around wrapping unsplittable code
 
3459     in unnecessary parentheses).
 
3461     leaves = line.leaves
 
3465     if leaves[0].type == token.STRING and leaves[1].type == token.DOT:
 
3469         for leaf in leaves[-2::-1]:
 
3470             if leaf.type in OPENING_BRACKETS:
 
3471                 if next.type not in CLOSING_BRACKETS:
 
3475             elif leaf.type == token.DOT:
 
3477             elif leaf.type == token.NAME:
 
3478                 if not (next.type == token.DOT or next.type in OPENING_BRACKETS):
 
3481             elif leaf.type not in CLOSING_BRACKETS:
 
3484             if dot_count > 1 and call_count > 1:
 
3490 def can_omit_invisible_parens(line: Line, line_length: int) -> bool:
 
3491     """Does `line` have a shape safe to reformat without optional parens around it?
 
3493     Returns True for only a subset of potentially nice looking formattings but
 
3494     the point is to not return false positives that end up producing lines that
 
3497     bt = line.bracket_tracker
 
3498     if not bt.delimiters:
 
3499         # Without delimiters the optional parentheses are useless.
 
3502     max_priority = bt.max_delimiter_priority()
 
3503     if bt.delimiter_count_with_priority(max_priority) > 1:
 
3504         # With more than one delimiter of a kind the optional parentheses read better.
 
3507     if max_priority == DOT_PRIORITY:
 
3508         # A single stranded method call doesn't require optional parentheses.
 
3511     assert len(line.leaves) >= 2, "Stranded delimiter"
 
3513     first = line.leaves[0]
 
3514     second = line.leaves[1]
 
3515     penultimate = line.leaves[-2]
 
3516     last = line.leaves[-1]
 
3518     # With a single delimiter, omit if the expression starts or ends with
 
3520     if first.type in OPENING_BRACKETS and second.type not in CLOSING_BRACKETS:
 
3522         length = 4 * line.depth
 
3523         for _index, leaf, leaf_length in enumerate_with_length(line):
 
3524             if leaf.type in CLOSING_BRACKETS and leaf.opening_bracket is first:
 
3527                 length += leaf_length
 
3528                 if length > line_length:
 
3531                 if leaf.type in OPENING_BRACKETS:
 
3532                     # There are brackets we can further split on.
 
3536             # checked the entire string and line length wasn't exceeded
 
3537             if len(line.leaves) == _index + 1:
 
3540         # Note: we are not returning False here because a line might have *both*
 
3541         # a leading opening bracket and a trailing closing bracket.  If the
 
3542         # opening bracket doesn't match our rule, maybe the closing will.
 
3545         last.type == token.RPAR
 
3546         or last.type == token.RBRACE
 
3548             # don't use indexing for omitting optional parentheses;
 
3550             last.type == token.RSQB
 
3552             and last.parent.type != syms.trailer
 
3555         if penultimate.type in OPENING_BRACKETS:
 
3556             # Empty brackets don't help.
 
3559         if is_multiline_string(first):
 
3560             # Additional wrapping of a multiline string in this situation is
 
3564         length = 4 * line.depth
 
3565         seen_other_brackets = False
 
3566         for _index, leaf, leaf_length in enumerate_with_length(line):
 
3567             length += leaf_length
 
3568             if leaf is last.opening_bracket:
 
3569                 if seen_other_brackets or length <= line_length:
 
3572             elif leaf.type in OPENING_BRACKETS:
 
3573                 # There are brackets we can further split on.
 
3574                 seen_other_brackets = True
 
3579 def get_cache_file(line_length: int, mode: FileMode) -> Path:
 
3580     return CACHE_DIR / f"cache.{line_length}.{mode.value}.pickle"
 
3583 def read_cache(line_length: int, mode: FileMode) -> Cache:
 
3584     """Read the cache if it exists and is well formed.
 
3586     If it is not well formed, the call to write_cache later should resolve the issue.
 
3588     cache_file = get_cache_file(line_length, mode)
 
3589     if not cache_file.exists():
 
3592     with cache_file.open("rb") as fobj:
 
3594             cache: Cache = pickle.load(fobj)
 
3595         except pickle.UnpicklingError:
 
3601 def get_cache_info(path: Path) -> CacheInfo:
 
3602     """Return the information used to check if a file is already formatted or not."""
 
3604     return stat.st_mtime, stat.st_size
 
3607 def filter_cached(cache: Cache, sources: Iterable[Path]) -> Tuple[Set[Path], Set[Path]]:
 
3608     """Split an iterable of paths in `sources` into two sets.
 
3610     The first contains paths of files that modified on disk or are not in the
 
3611     cache. The other contains paths to non-modified files.
 
3613     todo, done = set(), set()
 
3616         if cache.get(src) != get_cache_info(src):
 
3624     cache: Cache, sources: Iterable[Path], line_length: int, mode: FileMode
 
3626     """Update the cache file."""
 
3627     cache_file = get_cache_file(line_length, mode)
 
3629         if not CACHE_DIR.exists():
 
3630             CACHE_DIR.mkdir(parents=True)
 
3631         new_cache = {**cache, **{src.resolve(): get_cache_info(src) for src in sources}}
 
3632         with cache_file.open("wb") as fobj:
 
3633             pickle.dump(new_cache, fobj, protocol=pickle.HIGHEST_PROTOCOL)
 
3638 def patch_click() -> None:
 
3639     """Make Click not crash.
 
3641     On certain misconfigured environments, Python 3 selects the ASCII encoding as the
 
3642     default which restricts paths that it can access during the lifetime of the
 
3643     application.  Click refuses to work in this scenario by raising a RuntimeError.
 
3645     In case of Black the likelihood that non-ASCII characters are going to be used in
 
3646     file paths is minimal since it's Python source code.  Moreover, this crash was
 
3647     spurious on Python 3.7 thanks to PEP 538 and PEP 540.
 
3650         from click import core
 
3651         from click import _unicodefun  # type: ignore
 
3652     except ModuleNotFoundError:
 
3655     for module in (core, _unicodefun):
 
3656         if hasattr(module, "_verify_python3_env"):
 
3657             module._verify_python3_env = lambda: None
 
3660 def patched_main() -> None:
 
3666 if __name__ == "__main__":