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
 
  10 from multiprocessing import Manager
 
  12 from pathlib import Path
 
  38 from appdirs import user_cache_dir
 
  39 from attr import dataclass, Factory
 
  44 from blib2to3.pytree import Node, Leaf, type_repr
 
  45 from blib2to3 import pygram, pytree
 
  46 from blib2to3.pgen2 import driver, token
 
  47 from blib2to3.pgen2.parse import ParseError
 
  50 __version__ = "18.6b2"
 
  51 DEFAULT_LINE_LENGTH = 88
 
  53     r"/(\.git|\.hg|\.mypy_cache|\.tox|\.venv|_build|buck-out|build|dist)/"
 
  55 DEFAULT_INCLUDES = r"\.pyi?$"
 
  56 CACHE_DIR = Path(user_cache_dir("black", version=__version__))
 
  68 LN = Union[Leaf, Node]
 
  69 SplitFunc = Callable[["Line", bool], Iterator["Line"]]
 
  72 CacheInfo = Tuple[Timestamp, FileSize]
 
  73 Cache = Dict[Path, CacheInfo]
 
  74 out = partial(click.secho, bold=True, err=True)
 
  75 err = partial(click.secho, fg="red", err=True)
 
  77 pygram.initialize(CACHE_DIR)
 
  78 syms = pygram.python_symbols
 
  81 class NothingChanged(UserWarning):
 
  82     """Raised by :func:`format_file` when reformatted code is the same as source."""
 
  85 class CannotSplit(Exception):
 
  86     """A readable split that fits the allotted line length is impossible.
 
  88     Raised by :func:`left_hand_split`, :func:`right_hand_split`, and
 
  89     :func:`delimiter_split`.
 
  93 class FormatError(Exception):
 
  94     """Base exception for `# fmt: on` and `# fmt: off` handling.
 
  96     It holds the number of bytes of the prefix consumed before the format
 
  97     control comment appeared.
 
 100     def __init__(self, consumed: int) -> None:
 
 101         super().__init__(consumed)
 
 102         self.consumed = consumed
 
 104     def trim_prefix(self, leaf: Leaf) -> None:
 
 105         leaf.prefix = leaf.prefix[self.consumed :]
 
 107     def leaf_from_consumed(self, leaf: Leaf) -> Leaf:
 
 108         """Returns a new Leaf from the consumed part of the prefix."""
 
 109         unformatted_prefix = leaf.prefix[: self.consumed]
 
 110         return Leaf(token.NEWLINE, unformatted_prefix)
 
 113 class FormatOn(FormatError):
 
 114     """Found a comment like `# fmt: on` in the file."""
 
 117 class FormatOff(FormatError):
 
 118     """Found a comment like `# fmt: off` in the file."""
 
 121 class WriteBack(Enum):
 
 127     def from_configuration(cls, *, check: bool, diff: bool) -> "WriteBack":
 
 128         if check and not diff:
 
 131         return cls.DIFF if diff else cls.YES
 
 140 class FileMode(Flag):
 
 144     NO_STRING_NORMALIZATION = 4
 
 147     def from_configuration(
 
 148         cls, *, py36: bool, pyi: bool, skip_string_normalization: bool
 
 150         mode = cls.AUTO_DETECT
 
 155         if skip_string_normalization:
 
 156             mode |= cls.NO_STRING_NORMALIZATION
 
 160 def read_pyproject_toml(
 
 161     ctx: click.Context, param: click.Parameter, value: Union[str, int, bool, None]
 
 163     """Inject Black configuration from "pyproject.toml" into defaults in `ctx`.
 
 165     Returns the path to a successfully found and read configuration file, None
 
 168     assert not isinstance(value, (int, bool)), "Invalid parameter type passed"
 
 170         root = find_project_root(ctx.params.get("src", ()))
 
 171         path = root / "pyproject.toml"
 
 178         pyproject_toml = toml.load(value)
 
 179         config = pyproject_toml.get("tool", {}).get("black", {})
 
 180     except (toml.TomlDecodeError, OSError) as e:
 
 181         raise click.BadOptionUsage(f"Error reading configuration file: {e}", ctx)
 
 186     if ctx.default_map is None:
 
 188     ctx.default_map.update(  # type: ignore  # bad types in .pyi
 
 189         {k.replace("--", "").replace("-", "_"): v for k, v in config.items()}
 
 194 @click.command(context_settings=dict(help_option_names=["-h", "--help"]))
 
 199     default=DEFAULT_LINE_LENGTH,
 
 200     help="How many character per line to allow.",
 
 207         "Allow using Python 3.6-only syntax on all input files.  This will put "
 
 208         "trailing commas in function signatures and calls also after *args and "
 
 209         "**kwargs.  [default: per-file auto-detection]"
 
 216         "Format all input files like typing stubs regardless of file extension "
 
 217         "(useful when piping source on standard input)."
 
 222     "--skip-string-normalization",
 
 224     help="Don't normalize string quotes or prefixes.",
 
 230         "Don't write the files back, just return the status.  Return code 0 "
 
 231         "means nothing would change.  Return code 1 means some files would be "
 
 232         "reformatted.  Return code 123 means there was an internal error."
 
 238     help="Don't write the files back, just output a diff for each file on stdout.",
 
 243     help="If --fast given, skip temporary sanity checks. [default: --safe]",
 
 248     default=DEFAULT_INCLUDES,
 
 250         "A regular expression that matches files and directories that should be "
 
 251         "included on recursive searches.  An empty value means all files are "
 
 252         "included regardless of the name.  Use forward slashes for directories on "
 
 253         "all platforms (Windows, too).  Exclusions are calculated first, inclusions "
 
 261     default=DEFAULT_EXCLUDES,
 
 263         "A regular expression that matches files and directories that should be "
 
 264         "excluded on recursive searches.  An empty value means no paths are excluded. "
 
 265         "Use forward slashes for directories on all platforms (Windows, too).  "
 
 266         "Exclusions are calculated first, inclusions later."
 
 275         "Don't emit non-error messages to stderr. Errors are still emitted, "
 
 276         "silence those with 2>/dev/null."
 
 284         "Also emit messages to stderr about files that were not changed or were "
 
 285         "ignored due to --exclude=."
 
 288 @click.version_option(version=__version__)
 
 293         exists=True, file_okay=True, dir_okay=True, readable=True, allow_dash=True
 
 300         exists=False, file_okay=True, dir_okay=False, readable=True, allow_dash=False
 
 303     callback=read_pyproject_toml,
 
 304     help="Read configuration from PATH.",
 
 315     skip_string_normalization: bool,
 
 321     config: Optional[str],
 
 323     """The uncompromising code formatter."""
 
 324     write_back = WriteBack.from_configuration(check=check, diff=diff)
 
 325     mode = FileMode.from_configuration(
 
 326         py36=py36, pyi=pyi, skip_string_normalization=skip_string_normalization
 
 328     if config and verbose:
 
 329         out(f"Using configuration from {config}.", bold=False, fg="blue")
 
 331         include_regex = re_compile_maybe_verbose(include)
 
 333         err(f"Invalid regular expression for include given: {include!r}")
 
 336         exclude_regex = re_compile_maybe_verbose(exclude)
 
 338         err(f"Invalid regular expression for exclude given: {exclude!r}")
 
 340     report = Report(check=check, quiet=quiet, verbose=verbose)
 
 341     root = find_project_root(src)
 
 342     sources: Set[Path] = set()
 
 347                 gen_python_files_in_dir(p, root, include_regex, exclude_regex, report)
 
 349         elif p.is_file() or s == "-":
 
 350             # if a file was explicitly given, we don't care about its extension
 
 353             err(f"invalid path: {s}")
 
 354     if len(sources) == 0:
 
 355         if verbose or not quiet:
 
 356             out("No paths given. Nothing to do 😴")
 
 359     if len(sources) == 1:
 
 362             line_length=line_length,
 
 364             write_back=write_back,
 
 369         loop = asyncio.get_event_loop()
 
 370         executor = ProcessPoolExecutor(max_workers=os.cpu_count())
 
 372             loop.run_until_complete(
 
 375                     line_length=line_length,
 
 377                     write_back=write_back,
 
 386     if verbose or not quiet:
 
 387         bang = "💥 💔 💥" if report.return_code else "✨ 🍰 ✨"
 
 388         out(f"All done! {bang}")
 
 389         click.secho(str(report), err=True)
 
 390     ctx.exit(report.return_code)
 
 397     write_back: WriteBack,
 
 401     """Reformat a single file under `src` without spawning child processes.
 
 403     If `quiet` is True, non-error messages are not output. `line_length`,
 
 404     `write_back`, `fast` and `pyi` options are passed to
 
 405     :func:`format_file_in_place` or :func:`format_stdin_to_stdout`.
 
 409         if not src.is_file() and str(src) == "-":
 
 410             if format_stdin_to_stdout(
 
 411                 line_length=line_length, fast=fast, write_back=write_back, mode=mode
 
 413                 changed = Changed.YES
 
 416             if write_back != WriteBack.DIFF:
 
 417                 cache = read_cache(line_length, mode)
 
 418                 res_src = src.resolve()
 
 419                 if res_src in cache and cache[res_src] == get_cache_info(res_src):
 
 420                     changed = Changed.CACHED
 
 421             if changed is not Changed.CACHED and format_file_in_place(
 
 423                 line_length=line_length,
 
 425                 write_back=write_back,
 
 428                 changed = Changed.YES
 
 429             if write_back == WriteBack.YES and changed is not Changed.NO:
 
 430                 write_cache(cache, [src], line_length, mode)
 
 431         report.done(src, changed)
 
 432     except Exception as exc:
 
 433         report.failed(src, str(exc))
 
 436 async def schedule_formatting(
 
 440     write_back: WriteBack,
 
 446     """Run formatting of `sources` in parallel using the provided `executor`.
 
 448     (Use ProcessPoolExecutors for actual parallelism.)
 
 450     `line_length`, `write_back`, `fast`, and `pyi` options are passed to
 
 451     :func:`format_file_in_place`.
 
 454     if write_back != WriteBack.DIFF:
 
 455         cache = read_cache(line_length, mode)
 
 456         sources, cached = filter_cached(cache, sources)
 
 457         for src in sorted(cached):
 
 458             report.done(src, Changed.CACHED)
 
 463         if write_back == WriteBack.DIFF:
 
 464             # For diff output, we need locks to ensure we don't interleave output
 
 465             # from different processes.
 
 467             lock = manager.Lock()
 
 469             loop.run_in_executor(
 
 471                 format_file_in_place,
 
 479             for src in sorted(sources)
 
 481         pending: Iterable[asyncio.Task] = tasks.keys()
 
 483             loop.add_signal_handler(signal.SIGINT, cancel, pending)
 
 484             loop.add_signal_handler(signal.SIGTERM, cancel, pending)
 
 485         except NotImplementedError:
 
 486             # There are no good alternatives for these on Windows
 
 489             done, _ = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
 
 491                 src = tasks.pop(task)
 
 493                     cancelled.append(task)
 
 494                 elif task.exception():
 
 495                     report.failed(src, str(task.exception()))
 
 497                     formatted.append(src)
 
 498                     report.done(src, Changed.YES if task.result() else Changed.NO)
 
 500         await asyncio.gather(*cancelled, loop=loop, return_exceptions=True)
 
 501     if write_back == WriteBack.YES and formatted:
 
 502         write_cache(cache, formatted, line_length, mode)
 
 505 def format_file_in_place(
 
 509     write_back: WriteBack = WriteBack.NO,
 
 510     mode: FileMode = FileMode.AUTO_DETECT,
 
 511     lock: Any = None,  # multiprocessing.Manager().Lock() is some crazy proxy
 
 513     """Format file under `src` path. Return True if changed.
 
 515     If `write_back` is True, write reformatted code back to stdout.
 
 516     `line_length` and `fast` options are passed to :func:`format_file_contents`.
 
 518     if src.suffix == ".pyi":
 
 521     then = datetime.utcfromtimestamp(src.stat().st_mtime)
 
 522     with open(src, "rb") as buf:
 
 523         src_contents, encoding, newline = decode_bytes(buf.read())
 
 525         dst_contents = format_file_contents(
 
 526             src_contents, line_length=line_length, fast=fast, mode=mode
 
 528     except NothingChanged:
 
 531     if write_back == write_back.YES:
 
 532         with open(src, "w", encoding=encoding, newline=newline) as f:
 
 533             f.write(dst_contents)
 
 534     elif write_back == write_back.DIFF:
 
 535         now = datetime.utcnow()
 
 536         src_name = f"{src}\t{then} +0000"
 
 537         dst_name = f"{src}\t{now} +0000"
 
 538         diff_contents = diff(src_contents, dst_contents, src_name, dst_name)
 
 542             f = io.TextIOWrapper(
 
 548             f.write(diff_contents)
 
 556 def format_stdin_to_stdout(
 
 559     write_back: WriteBack = WriteBack.NO,
 
 560     mode: FileMode = FileMode.AUTO_DETECT,
 
 562     """Format file on stdin. Return True if changed.
 
 564     If `write_back` is True, write reformatted code back to stdout.
 
 565     `line_length`, `fast`, `is_pyi`, and `force_py36` arguments are passed to
 
 566     :func:`format_file_contents`.
 
 568     then = datetime.utcnow()
 
 569     src, encoding, newline = decode_bytes(sys.stdin.buffer.read())
 
 572         dst = format_file_contents(src, line_length=line_length, fast=fast, mode=mode)
 
 575     except NothingChanged:
 
 579         f = io.TextIOWrapper(
 
 580             sys.stdout.buffer, encoding=encoding, newline=newline, write_through=True
 
 582         if write_back == WriteBack.YES:
 
 584         elif write_back == WriteBack.DIFF:
 
 585             now = datetime.utcnow()
 
 586             src_name = f"STDIN\t{then} +0000"
 
 587             dst_name = f"STDOUT\t{now} +0000"
 
 588             f.write(diff(src, dst, src_name, dst_name))
 
 592 def format_file_contents(
 
 597     mode: FileMode = FileMode.AUTO_DETECT,
 
 599     """Reformat contents a file and return new contents.
 
 601     If `fast` is False, additionally confirm that the reformatted code is
 
 602     valid by calling :func:`assert_equivalent` and :func:`assert_stable` on it.
 
 603     `line_length` is passed to :func:`format_str`.
 
 605     if src_contents.strip() == "":
 
 608     dst_contents = format_str(src_contents, line_length=line_length, mode=mode)
 
 609     if src_contents == dst_contents:
 
 613         assert_equivalent(src_contents, dst_contents)
 
 614         assert_stable(src_contents, dst_contents, line_length=line_length, mode=mode)
 
 619     src_contents: str, line_length: int, *, mode: FileMode = FileMode.AUTO_DETECT
 
 621     """Reformat a string and return new contents.
 
 623     `line_length` determines how many characters per line are allowed.
 
 625     src_node = lib2to3_parse(src_contents)
 
 627     future_imports = get_future_imports(src_node)
 
 628     is_pyi = bool(mode & FileMode.PYI)
 
 629     py36 = bool(mode & FileMode.PYTHON36) or is_python36(src_node)
 
 630     normalize_strings = not bool(mode & FileMode.NO_STRING_NORMALIZATION)
 
 631     lines = LineGenerator(
 
 632         remove_u_prefix=py36 or "unicode_literals" in future_imports,
 
 634         normalize_strings=normalize_strings,
 
 636     elt = EmptyLineTracker(is_pyi=is_pyi)
 
 639     for current_line in lines.visit(src_node):
 
 640         for _ in range(after):
 
 641             dst_contents += str(empty_line)
 
 642         before, after = elt.maybe_empty_lines(current_line)
 
 643         for _ in range(before):
 
 644             dst_contents += str(empty_line)
 
 645         for line in split_line(current_line, line_length=line_length, py36=py36):
 
 646             dst_contents += str(line)
 
 650 def decode_bytes(src: bytes) -> Tuple[FileContent, Encoding, NewLine]:
 
 651     """Return a tuple of (decoded_contents, encoding, newline).
 
 653     `newline` is either CRLF or LF but `decoded_contents` is decoded with
 
 654     universal newlines (i.e. only contains LF).
 
 656     srcbuf = io.BytesIO(src)
 
 657     encoding, lines = tokenize.detect_encoding(srcbuf.readline)
 
 659         return "", encoding, "\n"
 
 661     newline = "\r\n" if b"\r\n" == lines[0][-2:] else "\n"
 
 663     with io.TextIOWrapper(srcbuf, encoding) as tiow:
 
 664         return tiow.read(), encoding, newline
 
 668     pygram.python_grammar_no_print_statement_no_exec_statement,
 
 669     pygram.python_grammar_no_print_statement,
 
 670     pygram.python_grammar,
 
 674 def lib2to3_parse(src_txt: str) -> Node:
 
 675     """Given a string with source, return the lib2to3 Node."""
 
 676     grammar = pygram.python_grammar_no_print_statement
 
 677     if src_txt[-1:] != "\n":
 
 679     for grammar in GRAMMARS:
 
 680         drv = driver.Driver(grammar, pytree.convert)
 
 682             result = drv.parse_string(src_txt, True)
 
 685         except ParseError as pe:
 
 686             lineno, column = pe.context[1]
 
 687             lines = src_txt.splitlines()
 
 689                 faulty_line = lines[lineno - 1]
 
 691                 faulty_line = "<line number missing in source>"
 
 692             exc = ValueError(f"Cannot parse: {lineno}:{column}: {faulty_line}")
 
 696     if isinstance(result, Leaf):
 
 697         result = Node(syms.file_input, [result])
 
 701 def lib2to3_unparse(node: Node) -> str:
 
 702     """Given a lib2to3 node, return its string representation."""
 
 710 class Visitor(Generic[T]):
 
 711     """Basic lib2to3 visitor that yields things of type `T` on `visit()`."""
 
 713     def visit(self, node: LN) -> Iterator[T]:
 
 714         """Main method to visit `node` and its children.
 
 716         It tries to find a `visit_*()` method for the given `node.type`, like
 
 717         `visit_simple_stmt` for Node objects or `visit_INDENT` for Leaf objects.
 
 718         If no dedicated `visit_*()` method is found, chooses `visit_default()`
 
 721         Then yields objects of type `T` from the selected visitor.
 
 724             name = token.tok_name[node.type]
 
 726             name = type_repr(node.type)
 
 727         yield from getattr(self, f"visit_{name}", self.visit_default)(node)
 
 729     def visit_default(self, node: LN) -> Iterator[T]:
 
 730         """Default `visit_*()` implementation. Recurses to children of `node`."""
 
 731         if isinstance(node, Node):
 
 732             for child in node.children:
 
 733                 yield from self.visit(child)
 
 737 class DebugVisitor(Visitor[T]):
 
 740     def visit_default(self, node: LN) -> Iterator[T]:
 
 741         indent = " " * (2 * self.tree_depth)
 
 742         if isinstance(node, Node):
 
 743             _type = type_repr(node.type)
 
 744             out(f"{indent}{_type}", fg="yellow")
 
 746             for child in node.children:
 
 747                 yield from self.visit(child)
 
 750             out(f"{indent}/{_type}", fg="yellow", bold=False)
 
 752             _type = token.tok_name.get(node.type, str(node.type))
 
 753             out(f"{indent}{_type}", fg="blue", nl=False)
 
 755                 # We don't have to handle prefixes for `Node` objects since
 
 756                 # that delegates to the first child anyway.
 
 757                 out(f" {node.prefix!r}", fg="green", bold=False, nl=False)
 
 758             out(f" {node.value!r}", fg="blue", bold=False)
 
 761     def show(cls, code: str) -> None:
 
 762         """Pretty-print the lib2to3 AST of a given string of `code`.
 
 764         Convenience method for debugging.
 
 766         v: DebugVisitor[None] = DebugVisitor()
 
 767         list(v.visit(lib2to3_parse(code)))
 
 770 KEYWORDS = set(keyword.kwlist)
 
 771 WHITESPACE = {token.DEDENT, token.INDENT, token.NEWLINE}
 
 772 FLOW_CONTROL = {"return", "raise", "break", "continue"}
 
 783 STANDALONE_COMMENT = 153
 
 784 LOGIC_OPERATORS = {"and", "or"}
 
 809 STARS = {token.STAR, token.DOUBLESTAR}
 
 812     syms.argument,  # double star in arglist
 
 813     syms.trailer,  # single argument to call
 
 815     syms.varargslist,  # lambdas
 
 817 UNPACKING_PARENTS = {
 
 818     syms.atom,  # single element of a list or set literal
 
 822     syms.testlist_star_expr,
 
 857 COMPREHENSION_PRIORITY = 20
 
 859 TERNARY_PRIORITY = 16
 
 862 COMPARATOR_PRIORITY = 10
 
 873     token.DOUBLESLASH: 4,
 
 883 class BracketTracker:
 
 884     """Keeps track of brackets on a line."""
 
 887     bracket_match: Dict[Tuple[Depth, NodeType], Leaf] = Factory(dict)
 
 888     delimiters: Dict[LeafID, Priority] = Factory(dict)
 
 889     previous: Optional[Leaf] = None
 
 890     _for_loop_variable: int = 0
 
 891     _lambda_arguments: int = 0
 
 893     def mark(self, leaf: Leaf) -> None:
 
 894         """Mark `leaf` with bracket-related metadata. Keep track of delimiters.
 
 896         All leaves receive an int `bracket_depth` field that stores how deep
 
 897         within brackets a given leaf is. 0 means there are no enclosing brackets
 
 898         that started on this line.
 
 900         If a leaf is itself a closing bracket, it receives an `opening_bracket`
 
 901         field that it forms a pair with. This is a one-directional link to
 
 902         avoid reference cycles.
 
 904         If a leaf is a delimiter (a token on which Black can split the line if
 
 905         needed) and it's on depth 0, its `id()` is stored in the tracker's
 
 908         if leaf.type == token.COMMENT:
 
 911         self.maybe_decrement_after_for_loop_variable(leaf)
 
 912         self.maybe_decrement_after_lambda_arguments(leaf)
 
 913         if leaf.type in CLOSING_BRACKETS:
 
 915             opening_bracket = self.bracket_match.pop((self.depth, leaf.type))
 
 916             leaf.opening_bracket = opening_bracket
 
 917         leaf.bracket_depth = self.depth
 
 919             delim = is_split_before_delimiter(leaf, self.previous)
 
 920             if delim and self.previous is not None:
 
 921                 self.delimiters[id(self.previous)] = delim
 
 923                 delim = is_split_after_delimiter(leaf, self.previous)
 
 925                     self.delimiters[id(leaf)] = delim
 
 926         if leaf.type in OPENING_BRACKETS:
 
 927             self.bracket_match[self.depth, BRACKET[leaf.type]] = leaf
 
 930         self.maybe_increment_lambda_arguments(leaf)
 
 931         self.maybe_increment_for_loop_variable(leaf)
 
 933     def any_open_brackets(self) -> bool:
 
 934         """Return True if there is an yet unmatched open bracket on the line."""
 
 935         return bool(self.bracket_match)
 
 937     def max_delimiter_priority(self, exclude: Iterable[LeafID] = ()) -> int:
 
 938         """Return the highest priority of a delimiter found on the line.
 
 940         Values are consistent with what `is_split_*_delimiter()` return.
 
 941         Raises ValueError on no delimiters.
 
 943         return max(v for k, v in self.delimiters.items() if k not in exclude)
 
 945     def delimiter_count_with_priority(self, priority: int = 0) -> int:
 
 946         """Return the number of delimiters with the given `priority`.
 
 948         If no `priority` is passed, defaults to max priority on the line.
 
 950         if not self.delimiters:
 
 953         priority = priority or self.max_delimiter_priority()
 
 954         return sum(1 for p in self.delimiters.values() if p == priority)
 
 956     def maybe_increment_for_loop_variable(self, leaf: Leaf) -> bool:
 
 957         """In a for loop, or comprehension, the variables are often unpacks.
 
 959         To avoid splitting on the comma in this situation, increase the depth of
 
 960         tokens between `for` and `in`.
 
 962         if leaf.type == token.NAME and leaf.value == "for":
 
 964             self._for_loop_variable += 1
 
 969     def maybe_decrement_after_for_loop_variable(self, leaf: Leaf) -> bool:
 
 970         """See `maybe_increment_for_loop_variable` above for explanation."""
 
 971         if self._for_loop_variable and leaf.type == token.NAME and leaf.value == "in":
 
 973             self._for_loop_variable -= 1
 
 978     def maybe_increment_lambda_arguments(self, leaf: Leaf) -> bool:
 
 979         """In a lambda expression, there might be more than one argument.
 
 981         To avoid splitting on the comma in this situation, increase the depth of
 
 982         tokens between `lambda` and `:`.
 
 984         if leaf.type == token.NAME and leaf.value == "lambda":
 
 986             self._lambda_arguments += 1
 
 991     def maybe_decrement_after_lambda_arguments(self, leaf: Leaf) -> bool:
 
 992         """See `maybe_increment_lambda_arguments` above for explanation."""
 
 993         if self._lambda_arguments and leaf.type == token.COLON:
 
 995             self._lambda_arguments -= 1
 
1000     def get_open_lsqb(self) -> Optional[Leaf]:
 
1001         """Return the most recent opening square bracket (if any)."""
 
1002         return self.bracket_match.get((self.depth - 1, token.RSQB))
 
1007     """Holds leaves and comments. Can be printed with `str(line)`."""
 
1010     leaves: List[Leaf] = Factory(list)
 
1011     comments: List[Tuple[Index, Leaf]] = Factory(list)
 
1012     bracket_tracker: BracketTracker = Factory(BracketTracker)
 
1013     inside_brackets: bool = False
 
1014     should_explode: bool = False
 
1016     def append(self, leaf: Leaf, preformatted: bool = False) -> None:
 
1017         """Add a new `leaf` to the end of the line.
 
1019         Unless `preformatted` is True, the `leaf` will receive a new consistent
 
1020         whitespace prefix and metadata applied by :class:`BracketTracker`.
 
1021         Trailing commas are maybe removed, unpacked for loop variables are
 
1022         demoted from being delimiters.
 
1024         Inline comments are put aside.
 
1026         has_value = leaf.type in BRACKETS or bool(leaf.value.strip())
 
1030         if token.COLON == leaf.type and self.is_class_paren_empty:
 
1031             del self.leaves[-2:]
 
1032         if self.leaves and not preformatted:
 
1033             # Note: at this point leaf.prefix should be empty except for
 
1034             # imports, for which we only preserve newlines.
 
1035             leaf.prefix += whitespace(
 
1036                 leaf, complex_subscript=self.is_complex_subscript(leaf)
 
1038         if self.inside_brackets or not preformatted:
 
1039             self.bracket_tracker.mark(leaf)
 
1040             self.maybe_remove_trailing_comma(leaf)
 
1041         if not self.append_comment(leaf):
 
1042             self.leaves.append(leaf)
 
1044     def append_safe(self, leaf: Leaf, preformatted: bool = False) -> None:
 
1045         """Like :func:`append()` but disallow invalid standalone comment structure.
 
1047         Raises ValueError when any `leaf` is appended after a standalone comment
 
1048         or when a standalone comment is not the first leaf on the line.
 
1050         if self.bracket_tracker.depth == 0:
 
1052                 raise ValueError("cannot append to standalone comments")
 
1054             if self.leaves and leaf.type == STANDALONE_COMMENT:
 
1056                     "cannot append standalone comments to a populated line"
 
1059         self.append(leaf, preformatted=preformatted)
 
1062     def is_comment(self) -> bool:
 
1063         """Is this line a standalone comment?"""
 
1064         return len(self.leaves) == 1 and self.leaves[0].type == STANDALONE_COMMENT
 
1067     def is_decorator(self) -> bool:
 
1068         """Is this line a decorator?"""
 
1069         return bool(self) and self.leaves[0].type == token.AT
 
1072     def is_import(self) -> bool:
 
1073         """Is this an import line?"""
 
1074         return bool(self) and is_import(self.leaves[0])
 
1077     def is_class(self) -> bool:
 
1078         """Is this line a class definition?"""
 
1081             and self.leaves[0].type == token.NAME
 
1082             and self.leaves[0].value == "class"
 
1086     def is_stub_class(self) -> bool:
 
1087         """Is this line a class definition with a body consisting only of "..."?"""
 
1088         return self.is_class and self.leaves[-3:] == [
 
1089             Leaf(token.DOT, ".") for _ in range(3)
 
1093     def is_def(self) -> bool:
 
1094         """Is this a function definition? (Also returns True for async defs.)"""
 
1096             first_leaf = self.leaves[0]
 
1101             second_leaf: Optional[Leaf] = self.leaves[1]
 
1104         return (first_leaf.type == token.NAME and first_leaf.value == "def") or (
 
1105             first_leaf.type == token.ASYNC
 
1106             and second_leaf is not None
 
1107             and second_leaf.type == token.NAME
 
1108             and second_leaf.value == "def"
 
1112     def is_class_paren_empty(self) -> bool:
 
1113         """Is this a class with no base classes but using parentheses?
 
1115         Those are unnecessary and should be removed.
 
1119             and len(self.leaves) == 4
 
1121             and self.leaves[2].type == token.LPAR
 
1122             and self.leaves[2].value == "("
 
1123             and self.leaves[3].type == token.RPAR
 
1124             and self.leaves[3].value == ")"
 
1128     def is_triple_quoted_string(self) -> bool:
 
1129         """Is the line a triple quoted string?"""
 
1132             and self.leaves[0].type == token.STRING
 
1133             and self.leaves[0].value.startswith(('"""', "'''"))
 
1136     def contains_standalone_comments(self, depth_limit: int = sys.maxsize) -> bool:
 
1137         """If so, needs to be split before emitting."""
 
1138         for leaf in self.leaves:
 
1139             if leaf.type == STANDALONE_COMMENT:
 
1140                 if leaf.bracket_depth <= depth_limit:
 
1145     def contains_multiline_strings(self) -> bool:
 
1146         for leaf in self.leaves:
 
1147             if is_multiline_string(leaf):
 
1152     def maybe_remove_trailing_comma(self, closing: Leaf) -> bool:
 
1153         """Remove trailing comma if there is one and it's safe."""
 
1156             and self.leaves[-1].type == token.COMMA
 
1157             and closing.type in CLOSING_BRACKETS
 
1161         if closing.type == token.RBRACE:
 
1162             self.remove_trailing_comma()
 
1165         if closing.type == token.RSQB:
 
1166             comma = self.leaves[-1]
 
1167             if comma.parent and comma.parent.type == syms.listmaker:
 
1168                 self.remove_trailing_comma()
 
1171         # For parens let's check if it's safe to remove the comma.
 
1172         # Imports are always safe.
 
1174             self.remove_trailing_comma()
 
1177         # Otheriwsse, if the trailing one is the only one, we might mistakenly
 
1178         # change a tuple into a different type by removing the comma.
 
1179         depth = closing.bracket_depth + 1
 
1181         opening = closing.opening_bracket
 
1182         for _opening_index, leaf in enumerate(self.leaves):
 
1189         for leaf in self.leaves[_opening_index + 1 :]:
 
1193             bracket_depth = leaf.bracket_depth
 
1194             if bracket_depth == depth and leaf.type == token.COMMA:
 
1196                 if leaf.parent and leaf.parent.type == syms.arglist:
 
1201             self.remove_trailing_comma()
 
1206     def append_comment(self, comment: Leaf) -> bool:
 
1207         """Add an inline or standalone comment to the line."""
 
1209             comment.type == STANDALONE_COMMENT
 
1210             and self.bracket_tracker.any_open_brackets()
 
1215         if comment.type != token.COMMENT:
 
1218         after = len(self.leaves) - 1
 
1220             comment.type = STANDALONE_COMMENT
 
1225             self.comments.append((after, comment))
 
1228     def comments_after(self, leaf: Leaf, _index: int = -1) -> Iterator[Leaf]:
 
1229         """Generate comments that should appear directly after `leaf`.
 
1231         Provide a non-negative leaf `_index` to speed up the function.
 
1233         if not self.comments:
 
1237             for _index, _leaf in enumerate(self.leaves):
 
1244         for index, comment_after in self.comments:
 
1248     def remove_trailing_comma(self) -> None:
 
1249         """Remove the trailing comma and moves the comments attached to it."""
 
1250         comma_index = len(self.leaves) - 1
 
1251         for i in range(len(self.comments)):
 
1252             comment_index, comment = self.comments[i]
 
1253             if comment_index == comma_index:
 
1254                 self.comments[i] = (comma_index - 1, comment)
 
1257     def is_complex_subscript(self, leaf: Leaf) -> bool:
 
1258         """Return True iff `leaf` is part of a slice with non-trivial exprs."""
 
1259         open_lsqb = self.bracket_tracker.get_open_lsqb()
 
1260         if open_lsqb is None:
 
1263         subscript_start = open_lsqb.next_sibling
 
1265         if isinstance(subscript_start, Node):
 
1266             if subscript_start.type == syms.listmaker:
 
1269             if subscript_start.type == syms.subscriptlist:
 
1270                 subscript_start = child_towards(subscript_start, leaf)
 
1271         return subscript_start is not None and any(
 
1272             n.type in TEST_DESCENDANTS for n in subscript_start.pre_order()
 
1275     def __str__(self) -> str:
 
1276         """Render the line."""
 
1280         indent = "    " * self.depth
 
1281         leaves = iter(self.leaves)
 
1282         first = next(leaves)
 
1283         res = f"{first.prefix}{indent}{first.value}"
 
1286         for _, comment in self.comments:
 
1290     def __bool__(self) -> bool:
 
1291         """Return True if the line has leaves or comments."""
 
1292         return bool(self.leaves or self.comments)
 
1295 class UnformattedLines(Line):
 
1296     """Just like :class:`Line` but stores lines which aren't reformatted."""
 
1298     def append(self, leaf: Leaf, preformatted: bool = True) -> None:
 
1299         """Just add a new `leaf` to the end of the lines.
 
1301         The `preformatted` argument is ignored.
 
1303         Keeps track of indentation `depth`, which is useful when the user
 
1304         says `# fmt: on`. Otherwise, doesn't do anything with the `leaf`.
 
1307             list(generate_comments(leaf))
 
1308         except FormatOn as f_on:
 
1309             self.leaves.append(f_on.leaf_from_consumed(leaf))
 
1312         self.leaves.append(leaf)
 
1313         if leaf.type == token.INDENT:
 
1315         elif leaf.type == token.DEDENT:
 
1318     def __str__(self) -> str:
 
1319         """Render unformatted lines from leaves which were added with `append()`.
 
1321         `depth` is not used for indentation in this case.
 
1327         for leaf in self.leaves:
 
1331     def append_comment(self, comment: Leaf) -> bool:
 
1332         """Not implemented in this class. Raises `NotImplementedError`."""
 
1333         raise NotImplementedError("Unformatted lines don't store comments separately.")
 
1335     def maybe_remove_trailing_comma(self, closing: Leaf) -> bool:
 
1336         """Does nothing and returns False."""
 
1339     def maybe_increment_for_loop_variable(self, leaf: Leaf) -> bool:
 
1340         """Does nothing and returns False."""
 
1345 class EmptyLineTracker:
 
1346     """Provides a stateful method that returns the number of potential extra
 
1347     empty lines needed before and after the currently processed line.
 
1349     Note: this tracker works on lines that haven't been split yet.  It assumes
 
1350     the prefix of the first leaf consists of optional newlines.  Those newlines
 
1351     are consumed by `maybe_empty_lines()` and included in the computation.
 
1354     is_pyi: bool = False
 
1355     previous_line: Optional[Line] = None
 
1356     previous_after: int = 0
 
1357     previous_defs: List[int] = Factory(list)
 
1359     def maybe_empty_lines(self, current_line: Line) -> Tuple[int, int]:
 
1360         """Return the number of extra empty lines before and after the `current_line`.
 
1362         This is for separating `def`, `async def` and `class` with extra empty
 
1363         lines (two on module-level).
 
1365         if isinstance(current_line, UnformattedLines):
 
1368         before, after = self._maybe_empty_lines(current_line)
 
1369         before -= self.previous_after
 
1370         self.previous_after = after
 
1371         self.previous_line = current_line
 
1372         return before, after
 
1374     def _maybe_empty_lines(self, current_line: Line) -> Tuple[int, int]:
 
1376         if current_line.depth == 0:
 
1377             max_allowed = 1 if self.is_pyi else 2
 
1378         if current_line.leaves:
 
1379             # Consume the first leaf's extra newlines.
 
1380             first_leaf = current_line.leaves[0]
 
1381             before = first_leaf.prefix.count("\n")
 
1382             before = min(before, max_allowed)
 
1383             first_leaf.prefix = ""
 
1386         depth = current_line.depth
 
1387         while self.previous_defs and self.previous_defs[-1] >= depth:
 
1388             self.previous_defs.pop()
 
1390                 before = 0 if depth else 1
 
1392                 before = 1 if depth else 2
 
1393         if current_line.is_decorator or current_line.is_def or current_line.is_class:
 
1394             return self._maybe_empty_lines_for_class_or_def(current_line, before)
 
1398             and self.previous_line.is_import
 
1399             and not current_line.is_import
 
1400             and depth == self.previous_line.depth
 
1402             return (before or 1), 0
 
1406             and self.previous_line.is_class
 
1407             and current_line.is_triple_quoted_string
 
1413     def _maybe_empty_lines_for_class_or_def(
 
1414         self, current_line: Line, before: int
 
1415     ) -> Tuple[int, int]:
 
1416         if not current_line.is_decorator:
 
1417             self.previous_defs.append(current_line.depth)
 
1418         if self.previous_line is None:
 
1419             # Don't insert empty lines before the first line in the file.
 
1422         if self.previous_line.is_decorator:
 
1425         if self.previous_line.depth < current_line.depth and (
 
1426             self.previous_line.is_class or self.previous_line.is_def
 
1431             self.previous_line.is_comment
 
1432             and self.previous_line.depth == current_line.depth
 
1438             if self.previous_line.depth > current_line.depth:
 
1440             elif current_line.is_class or self.previous_line.is_class:
 
1441                 if current_line.is_stub_class and self.previous_line.is_stub_class:
 
1442                     # No blank line between classes with an emty body
 
1446             elif current_line.is_def and not self.previous_line.is_def:
 
1447                 # Blank line between a block of functions and a block of non-functions
 
1453         if current_line.depth and newlines:
 
1459 class LineGenerator(Visitor[Line]):
 
1460     """Generates reformatted Line objects.  Empty lines are not emitted.
 
1462     Note: destroys the tree it's visiting by mutating prefixes of its leaves
 
1463     in ways that will no longer stringify to valid Python code on the tree.
 
1466     is_pyi: bool = False
 
1467     normalize_strings: bool = True
 
1468     current_line: Line = Factory(Line)
 
1469     remove_u_prefix: bool = False
 
1471     def line(self, indent: int = 0, type: Type[Line] = Line) -> Iterator[Line]:
 
1474         If the line is empty, only emit if it makes sense.
 
1475         If the line is too long, split it first and then generate.
 
1477         If any lines were generated, set up a new current_line.
 
1479         if not self.current_line:
 
1480             if self.current_line.__class__ == type:
 
1481                 self.current_line.depth += indent
 
1483                 self.current_line = type(depth=self.current_line.depth + indent)
 
1484             return  # Line is empty, don't emit. Creating a new one unnecessary.
 
1486         complete_line = self.current_line
 
1487         self.current_line = type(depth=complete_line.depth + indent)
 
1490     def visit(self, node: LN) -> Iterator[Line]:
 
1491         """Main method to visit `node` and its children.
 
1493         Yields :class:`Line` objects.
 
1495         if isinstance(self.current_line, UnformattedLines):
 
1496             # File contained `# fmt: off`
 
1497             yield from self.visit_unformatted(node)
 
1500             yield from super().visit(node)
 
1502     def visit_default(self, node: LN) -> Iterator[Line]:
 
1503         """Default `visit_*()` implementation. Recurses to children of `node`."""
 
1504         if isinstance(node, Leaf):
 
1505             any_open_brackets = self.current_line.bracket_tracker.any_open_brackets()
 
1507                 for comment in generate_comments(node):
 
1508                     if any_open_brackets:
 
1509                         # any comment within brackets is subject to splitting
 
1510                         self.current_line.append(comment)
 
1511                     elif comment.type == token.COMMENT:
 
1512                         # regular trailing comment
 
1513                         self.current_line.append(comment)
 
1514                         yield from self.line()
 
1517                         # regular standalone comment
 
1518                         yield from self.line()
 
1520                         self.current_line.append(comment)
 
1521                         yield from self.line()
 
1523             except FormatOff as f_off:
 
1524                 f_off.trim_prefix(node)
 
1525                 yield from self.line(type=UnformattedLines)
 
1526                 yield from self.visit(node)
 
1528             except FormatOn as f_on:
 
1529                 # This only happens here if somebody says "fmt: on" multiple
 
1531                 f_on.trim_prefix(node)
 
1532                 yield from self.visit_default(node)
 
1535                 normalize_prefix(node, inside_brackets=any_open_brackets)
 
1536                 if self.normalize_strings and node.type == token.STRING:
 
1537                     normalize_string_prefix(node, remove_u_prefix=self.remove_u_prefix)
 
1538                     normalize_string_quotes(node)
 
1539                 if node.type not in WHITESPACE:
 
1540                     self.current_line.append(node)
 
1541         yield from super().visit_default(node)
 
1543     def visit_INDENT(self, node: Node) -> Iterator[Line]:
 
1544         """Increase indentation level, maybe yield a line."""
 
1545         # In blib2to3 INDENT never holds comments.
 
1546         yield from self.line(+1)
 
1547         yield from self.visit_default(node)
 
1549     def visit_DEDENT(self, node: Node) -> Iterator[Line]:
 
1550         """Decrease indentation level, maybe yield a line."""
 
1551         # The current line might still wait for trailing comments.  At DEDENT time
 
1552         # there won't be any (they would be prefixes on the preceding NEWLINE).
 
1553         # Emit the line then.
 
1554         yield from self.line()
 
1556         # While DEDENT has no value, its prefix may contain standalone comments
 
1557         # that belong to the current indentation level.  Get 'em.
 
1558         yield from self.visit_default(node)
 
1560         # Finally, emit the dedent.
 
1561         yield from self.line(-1)
 
1564         self, node: Node, keywords: Set[str], parens: Set[str]
 
1565     ) -> Iterator[Line]:
 
1566         """Visit a statement.
 
1568         This implementation is shared for `if`, `while`, `for`, `try`, `except`,
 
1569         `def`, `with`, `class`, `assert` and assignments.
 
1571         The relevant Python language `keywords` for a given statement will be
 
1572         NAME leaves within it. This methods puts those on a separate line.
 
1574         `parens` holds a set of string leaf values immediately after which
 
1575         invisible parens should be put.
 
1577         normalize_invisible_parens(node, parens_after=parens)
 
1578         for child in node.children:
 
1579             if child.type == token.NAME and child.value in keywords:  # type: ignore
 
1580                 yield from self.line()
 
1582             yield from self.visit(child)
 
1584     def visit_suite(self, node: Node) -> Iterator[Line]:
 
1585         """Visit a suite."""
 
1586         if self.is_pyi and is_stub_suite(node):
 
1587             yield from self.visit(node.children[2])
 
1589             yield from self.visit_default(node)
 
1591     def visit_simple_stmt(self, node: Node) -> Iterator[Line]:
 
1592         """Visit a statement without nested statements."""
 
1593         is_suite_like = node.parent and node.parent.type in STATEMENT
 
1595             if self.is_pyi and is_stub_body(node):
 
1596                 yield from self.visit_default(node)
 
1598                 yield from self.line(+1)
 
1599                 yield from self.visit_default(node)
 
1600                 yield from self.line(-1)
 
1603             if not self.is_pyi or not node.parent or not is_stub_suite(node.parent):
 
1604                 yield from self.line()
 
1605             yield from self.visit_default(node)
 
1607     def visit_async_stmt(self, node: Node) -> Iterator[Line]:
 
1608         """Visit `async def`, `async for`, `async with`."""
 
1609         yield from self.line()
 
1611         children = iter(node.children)
 
1612         for child in children:
 
1613             yield from self.visit(child)
 
1615             if child.type == token.ASYNC:
 
1618         internal_stmt = next(children)
 
1619         for child in internal_stmt.children:
 
1620             yield from self.visit(child)
 
1622     def visit_decorators(self, node: Node) -> Iterator[Line]:
 
1623         """Visit decorators."""
 
1624         for child in node.children:
 
1625             yield from self.line()
 
1626             yield from self.visit(child)
 
1628     def visit_SEMI(self, leaf: Leaf) -> Iterator[Line]:
 
1629         """Remove a semicolon and put the other statement on a separate line."""
 
1630         yield from self.line()
 
1632     def visit_ENDMARKER(self, leaf: Leaf) -> Iterator[Line]:
 
1633         """End of file. Process outstanding comments and end with a newline."""
 
1634         yield from self.visit_default(leaf)
 
1635         yield from self.line()
 
1637     def visit_unformatted(self, node: LN) -> Iterator[Line]:
 
1638         """Used when file contained a `# fmt: off`."""
 
1639         if isinstance(node, Node):
 
1640             for child in node.children:
 
1641                 yield from self.visit(child)
 
1645                 self.current_line.append(node)
 
1646             except FormatOn as f_on:
 
1647                 f_on.trim_prefix(node)
 
1648                 yield from self.line()
 
1649                 yield from self.visit(node)
 
1651             if node.type == token.ENDMARKER:
 
1652                 # somebody decided not to put a final `# fmt: on`
 
1653                 yield from self.line()
 
1655     def __attrs_post_init__(self) -> None:
 
1656         """You are in a twisty little maze of passages."""
 
1659         self.visit_assert_stmt = partial(v, keywords={"assert"}, parens={"assert", ","})
 
1660         self.visit_if_stmt = partial(
 
1661             v, keywords={"if", "else", "elif"}, parens={"if", "elif"}
 
1663         self.visit_while_stmt = partial(v, keywords={"while", "else"}, parens={"while"})
 
1664         self.visit_for_stmt = partial(v, keywords={"for", "else"}, parens={"for", "in"})
 
1665         self.visit_try_stmt = partial(
 
1666             v, keywords={"try", "except", "else", "finally"}, parens=Ø
 
1668         self.visit_except_clause = partial(v, keywords={"except"}, parens=Ø)
 
1669         self.visit_with_stmt = partial(v, keywords={"with"}, parens=Ø)
 
1670         self.visit_funcdef = partial(v, keywords={"def"}, parens=Ø)
 
1671         self.visit_classdef = partial(v, keywords={"class"}, parens=Ø)
 
1672         self.visit_expr_stmt = partial(v, keywords=Ø, parens=ASSIGNMENTS)
 
1673         self.visit_return_stmt = partial(v, keywords={"return"}, parens={"return"})
 
1674         self.visit_import_from = partial(v, keywords=Ø, parens={"import"})
 
1675         self.visit_async_funcdef = self.visit_async_stmt
 
1676         self.visit_decorated = self.visit_decorators
 
1679 IMPLICIT_TUPLE = {syms.testlist, syms.testlist_star_expr, syms.exprlist}
 
1680 BRACKET = {token.LPAR: token.RPAR, token.LSQB: token.RSQB, token.LBRACE: token.RBRACE}
 
1681 OPENING_BRACKETS = set(BRACKET.keys())
 
1682 CLOSING_BRACKETS = set(BRACKET.values())
 
1683 BRACKETS = OPENING_BRACKETS | CLOSING_BRACKETS
 
1684 ALWAYS_NO_SPACE = CLOSING_BRACKETS | {token.COMMA, STANDALONE_COMMENT}
 
1687 def whitespace(leaf: Leaf, *, complex_subscript: bool) -> str:  # noqa C901
 
1688     """Return whitespace prefix if needed for the given `leaf`.
 
1690     `complex_subscript` signals whether the given leaf is part of a subscription
 
1691     which has non-trivial arguments, like arithmetic expressions or function calls.
 
1699     if t in ALWAYS_NO_SPACE:
 
1702     if t == token.COMMENT:
 
1705     assert p is not None, f"INTERNAL ERROR: hand-made leaf without parent: {leaf!r}"
 
1706     if t == token.COLON and p.type not in {
 
1713     prev = leaf.prev_sibling
 
1715         prevp = preceding_leaf(p)
 
1716         if not prevp or prevp.type in OPENING_BRACKETS:
 
1719         if t == token.COLON:
 
1720             if prevp.type == token.COLON:
 
1723             elif prevp.type != token.COMMA and not complex_subscript:
 
1728         if prevp.type == token.EQUAL:
 
1730                 if prevp.parent.type in {
 
1738                 elif prevp.parent.type == syms.typedargslist:
 
1739                     # A bit hacky: if the equal sign has whitespace, it means we
 
1740                     # previously found it's a typed argument.  So, we're using
 
1744         elif prevp.type in STARS:
 
1745             if is_vararg(prevp, within=VARARGS_PARENTS | UNPACKING_PARENTS):
 
1748         elif prevp.type == token.COLON:
 
1749             if prevp.parent and prevp.parent.type in {syms.subscript, syms.sliceop}:
 
1750                 return SPACE if complex_subscript else NO
 
1754             and prevp.parent.type == syms.factor
 
1755             and prevp.type in MATH_OPERATORS
 
1760             prevp.type == token.RIGHTSHIFT
 
1762             and prevp.parent.type == syms.shift_expr
 
1763             and prevp.prev_sibling
 
1764             and prevp.prev_sibling.type == token.NAME
 
1765             and prevp.prev_sibling.value == "print"  # type: ignore
 
1767             # Python 2 print chevron
 
1770     elif prev.type in OPENING_BRACKETS:
 
1773     if p.type in {syms.parameters, syms.arglist}:
 
1774         # untyped function signatures or calls
 
1775         if not prev or prev.type != token.COMMA:
 
1778     elif p.type == syms.varargslist:
 
1780         if prev and prev.type != token.COMMA:
 
1783     elif p.type == syms.typedargslist:
 
1784         # typed function signatures
 
1788         if t == token.EQUAL:
 
1789             if prev.type != syms.tname:
 
1792         elif prev.type == token.EQUAL:
 
1793             # A bit hacky: if the equal sign has whitespace, it means we
 
1794             # previously found it's a typed argument.  So, we're using that, too.
 
1797         elif prev.type != token.COMMA:
 
1800     elif p.type == syms.tname:
 
1803             prevp = preceding_leaf(p)
 
1804             if not prevp or prevp.type != token.COMMA:
 
1807     elif p.type == syms.trailer:
 
1808         # attributes and calls
 
1809         if t == token.LPAR or t == token.RPAR:
 
1814                 prevp = preceding_leaf(p)
 
1815                 if not prevp or prevp.type != token.NUMBER:
 
1818             elif t == token.LSQB:
 
1821         elif prev.type != token.COMMA:
 
1824     elif p.type == syms.argument:
 
1826         if t == token.EQUAL:
 
1830             prevp = preceding_leaf(p)
 
1831             if not prevp or prevp.type == token.LPAR:
 
1834         elif prev.type in {token.EQUAL} | STARS:
 
1837     elif p.type == syms.decorator:
 
1841     elif p.type == syms.dotted_name:
 
1845         prevp = preceding_leaf(p)
 
1846         if not prevp or prevp.type == token.AT or prevp.type == token.DOT:
 
1849     elif p.type == syms.classdef:
 
1853         if prev and prev.type == token.LPAR:
 
1856     elif p.type in {syms.subscript, syms.sliceop}:
 
1859             assert p.parent is not None, "subscripts are always parented"
 
1860             if p.parent.type == syms.subscriptlist:
 
1865         elif not complex_subscript:
 
1868     elif p.type == syms.atom:
 
1869         if prev and t == token.DOT:
 
1870             # dots, but not the first one.
 
1873     elif p.type == syms.dictsetmaker:
 
1875         if prev and prev.type == token.DOUBLESTAR:
 
1878     elif p.type in {syms.factor, syms.star_expr}:
 
1881             prevp = preceding_leaf(p)
 
1882             if not prevp or prevp.type in OPENING_BRACKETS:
 
1885             prevp_parent = prevp.parent
 
1886             assert prevp_parent is not None
 
1887             if prevp.type == token.COLON and prevp_parent.type in {
 
1893             elif prevp.type == token.EQUAL and prevp_parent.type == syms.argument:
 
1896         elif t in {token.NAME, token.NUMBER, token.STRING}:
 
1899     elif p.type == syms.import_from:
 
1901             if prev and prev.type == token.DOT:
 
1904         elif t == token.NAME:
 
1908             if prev and prev.type == token.DOT:
 
1911     elif p.type == syms.sliceop:
 
1917 def preceding_leaf(node: Optional[LN]) -> Optional[Leaf]:
 
1918     """Return the first leaf that precedes `node`, if any."""
 
1920         res = node.prev_sibling
 
1922             if isinstance(res, Leaf):
 
1926                 return list(res.leaves())[-1]
 
1935 def child_towards(ancestor: Node, descendant: LN) -> Optional[LN]:
 
1936     """Return the child of `ancestor` that contains `descendant`."""
 
1937     node: Optional[LN] = descendant
 
1938     while node and node.parent != ancestor:
 
1943 def is_split_after_delimiter(leaf: Leaf, previous: Leaf = None) -> int:
 
1944     """Return the priority of the `leaf` delimiter, given a line break after it.
 
1946     The delimiter priorities returned here are from those delimiters that would
 
1947     cause a line break after themselves.
 
1949     Higher numbers are higher priority.
 
1951     if leaf.type == token.COMMA:
 
1952         return COMMA_PRIORITY
 
1957 def is_split_before_delimiter(leaf: Leaf, previous: Leaf = None) -> int:
 
1958     """Return the priority of the `leaf` delimiter, given a line before after it.
 
1960     The delimiter priorities returned here are from those delimiters that would
 
1961     cause a line break before themselves.
 
1963     Higher numbers are higher priority.
 
1965     if is_vararg(leaf, within=VARARGS_PARENTS | UNPACKING_PARENTS):
 
1966         # * and ** might also be MATH_OPERATORS but in this case they are not.
 
1967         # Don't treat them as a delimiter.
 
1971         leaf.type == token.DOT
 
1973         and leaf.parent.type not in {syms.import_from, syms.dotted_name}
 
1974         and (previous is None or previous.type in CLOSING_BRACKETS)
 
1979         leaf.type in MATH_OPERATORS
 
1981         and leaf.parent.type not in {syms.factor, syms.star_expr}
 
1983         return MATH_PRIORITIES[leaf.type]
 
1985     if leaf.type in COMPARATORS:
 
1986         return COMPARATOR_PRIORITY
 
1989         leaf.type == token.STRING
 
1990         and previous is not None
 
1991         and previous.type == token.STRING
 
1993         return STRING_PRIORITY
 
1995     if leaf.type != token.NAME:
 
2001         and leaf.parent.type in {syms.comp_for, syms.old_comp_for}
 
2003         return COMPREHENSION_PRIORITY
 
2008         and leaf.parent.type in {syms.comp_if, syms.old_comp_if}
 
2010         return COMPREHENSION_PRIORITY
 
2012     if leaf.value in {"if", "else"} and leaf.parent and leaf.parent.type == syms.test:
 
2013         return TERNARY_PRIORITY
 
2015     if leaf.value == "is":
 
2016         return COMPARATOR_PRIORITY
 
2021         and leaf.parent.type in {syms.comp_op, syms.comparison}
 
2023             previous is not None
 
2024             and previous.type == token.NAME
 
2025             and previous.value == "not"
 
2028         return COMPARATOR_PRIORITY
 
2033         and leaf.parent.type == syms.comp_op
 
2035             previous is not None
 
2036             and previous.type == token.NAME
 
2037             and previous.value == "is"
 
2040         return COMPARATOR_PRIORITY
 
2042     if leaf.value in LOGIC_OPERATORS and leaf.parent:
 
2043         return LOGIC_PRIORITY
 
2048 FMT_OFF = {"# fmt: off", "# fmt:off", "# yapf: disable"}
 
2049 FMT_ON = {"# fmt: on", "# fmt:on", "# yapf: enable"}
 
2052 def generate_comments(leaf: LN) -> Iterator[Leaf]:
 
2053     """Clean the prefix of the `leaf` and generate comments from it, if any.
 
2055     Comments in lib2to3 are shoved into the whitespace prefix.  This happens
 
2056     in `pgen2/driver.py:Driver.parse_tokens()`.  This was a brilliant implementation
 
2057     move because it does away with modifying the grammar to include all the
 
2058     possible places in which comments can be placed.
 
2060     The sad consequence for us though is that comments don't "belong" anywhere.
 
2061     This is why this function generates simple parentless Leaf objects for
 
2062     comments.  We simply don't know what the correct parent should be.
 
2064     No matter though, we can live without this.  We really only need to
 
2065     differentiate between inline and standalone comments.  The latter don't
 
2066     share the line with any code.
 
2068     Inline comments are emitted as regular token.COMMENT leaves.  Standalone
 
2069     are emitted with a fake STANDALONE_COMMENT token identifier.
 
2071     for pc in list_comments(leaf.prefix, is_endmarker=leaf.type == token.ENDMARKER):
 
2072         yield Leaf(pc.type, pc.value, prefix="\n" * pc.newlines)
 
2073         if pc.value in FMT_ON:
 
2074             raise FormatOn(pc.consumed)
 
2076         if pc.value in FMT_OFF:
 
2077             if pc.type == STANDALONE_COMMENT:
 
2078                 raise FormatOff(pc.consumed)
 
2080             prev = preceding_leaf(leaf)
 
2081             if not prev or prev.type in WHITESPACE:  # standalone comment in disguise
 
2082                 raise FormatOff(pc.consumed)
 
2087     type: int  # token.COMMENT or STANDALONE_COMMENT
 
2088     value: str  # content of the comment
 
2089     newlines: int  # how many newlines before the comment
 
2090     consumed: int  # how many characters of the original leaf's prefix did we consume
 
2093 @lru_cache(maxsize=4096)
 
2094 def list_comments(prefix: str, is_endmarker: bool) -> List[ProtoComment]:
 
2095     result: List[ProtoComment] = []
 
2096     if not prefix or "#" not in prefix:
 
2101     for index, line in enumerate(prefix.split("\n")):
 
2102         consumed += len(line) + 1  # adding the length of the split '\n'
 
2103         line = line.lstrip()
 
2106         if not line.startswith("#"):
 
2109         if index == 0 and not is_endmarker:
 
2110             comment_type = token.COMMENT  # simple trailing comment
 
2112             comment_type = STANDALONE_COMMENT
 
2113         comment = make_comment(line)
 
2116                 type=comment_type, value=comment, newlines=nlines, consumed=consumed
 
2123 def make_comment(content: str) -> str:
 
2124     """Return a consistently formatted comment from the given `content` string.
 
2126     All comments (except for "##", "#!", "#:") should have a single space between
 
2127     the hash sign and the content.
 
2129     If `content` didn't start with a hash sign, one is provided.
 
2131     content = content.rstrip()
 
2135     if content[0] == "#":
 
2136         content = content[1:]
 
2137     if content and content[0] not in " !:#":
 
2138         content = " " + content
 
2139     return "#" + content
 
2143     line: Line, line_length: int, inner: bool = False, py36: bool = False
 
2144 ) -> Iterator[Line]:
 
2145     """Split a `line` into potentially many lines.
 
2147     They should fit in the allotted `line_length` but might not be able to.
 
2148     `inner` signifies that there were a pair of brackets somewhere around the
 
2149     current `line`, possibly transitively. This means we can fallback to splitting
 
2150     by delimiters if the LHS/RHS don't yield any results.
 
2152     If `py36` is True, splitting may generate syntax that is only compatible
 
2153     with Python 3.6 and later.
 
2155     if isinstance(line, UnformattedLines) or line.is_comment:
 
2159     line_str = str(line).strip("\n")
 
2160     if not line.should_explode and is_line_short_enough(
 
2161         line, line_length=line_length, line_str=line_str
 
2166     split_funcs: List[SplitFunc]
 
2168         split_funcs = [left_hand_split]
 
2171         def rhs(line: Line, py36: bool = False) -> Iterator[Line]:
 
2172             for omit in generate_trailers_to_omit(line, line_length):
 
2173                 lines = list(right_hand_split(line, line_length, py36, omit=omit))
 
2174                 if is_line_short_enough(lines[0], line_length=line_length):
 
2178             # All splits failed, best effort split with no omits.
 
2179             # This mostly happens to multiline strings that are by definition
 
2180             # reported as not fitting a single line.
 
2181             yield from right_hand_split(line, py36)
 
2183         if line.inside_brackets:
 
2184             split_funcs = [delimiter_split, standalone_comment_split, rhs]
 
2187     for split_func in split_funcs:
 
2188         # We are accumulating lines in `result` because we might want to abort
 
2189         # mission and return the original line in the end, or attempt a different
 
2191         result: List[Line] = []
 
2193             for l in split_func(line, py36):
 
2194                 if str(l).strip("\n") == line_str:
 
2195                     raise CannotSplit("Split function returned an unchanged result")
 
2198                     split_line(l, line_length=line_length, inner=True, py36=py36)
 
2200         except CannotSplit as cs:
 
2211 def left_hand_split(line: Line, py36: bool = False) -> Iterator[Line]:
 
2212     """Split line into many lines, starting with the first matching bracket pair.
 
2214     Note: this usually looks weird, only use this for function definitions.
 
2215     Prefer RHS otherwise.  This is why this function is not symmetrical with
 
2216     :func:`right_hand_split` which also handles optional parentheses.
 
2218     head = Line(depth=line.depth)
 
2219     body = Line(depth=line.depth + 1, inside_brackets=True)
 
2220     tail = Line(depth=line.depth)
 
2221     tail_leaves: List[Leaf] = []
 
2222     body_leaves: List[Leaf] = []
 
2223     head_leaves: List[Leaf] = []
 
2224     current_leaves = head_leaves
 
2225     matching_bracket = None
 
2226     for leaf in line.leaves:
 
2228             current_leaves is body_leaves
 
2229             and leaf.type in CLOSING_BRACKETS
 
2230             and leaf.opening_bracket is matching_bracket
 
2232             current_leaves = tail_leaves if body_leaves else head_leaves
 
2233         current_leaves.append(leaf)
 
2234         if current_leaves is head_leaves:
 
2235             if leaf.type in OPENING_BRACKETS:
 
2236                 matching_bracket = leaf
 
2237                 current_leaves = body_leaves
 
2238     # Since body is a new indent level, remove spurious leading whitespace.
 
2240         normalize_prefix(body_leaves[0], inside_brackets=True)
 
2241     # Build the new lines.
 
2242     for result, leaves in (head, head_leaves), (body, body_leaves), (tail, tail_leaves):
 
2244             result.append(leaf, preformatted=True)
 
2245             for comment_after in line.comments_after(leaf):
 
2246                 result.append(comment_after, preformatted=True)
 
2247     bracket_split_succeeded_or_raise(head, body, tail)
 
2248     for result in (head, body, tail):
 
2253 def right_hand_split(
 
2254     line: Line, line_length: int, py36: bool = False, omit: Collection[LeafID] = ()
 
2255 ) -> Iterator[Line]:
 
2256     """Split line into many lines, starting with the last matching bracket pair.
 
2258     If the split was by optional parentheses, attempt splitting without them, too.
 
2259     `omit` is a collection of closing bracket IDs that shouldn't be considered for
 
2262     Note: running this function modifies `bracket_depth` on the leaves of `line`.
 
2264     head = Line(depth=line.depth)
 
2265     body = Line(depth=line.depth + 1, inside_brackets=True)
 
2266     tail = Line(depth=line.depth)
 
2267     tail_leaves: List[Leaf] = []
 
2268     body_leaves: List[Leaf] = []
 
2269     head_leaves: List[Leaf] = []
 
2270     current_leaves = tail_leaves
 
2271     opening_bracket = None
 
2272     closing_bracket = None
 
2273     for leaf in reversed(line.leaves):
 
2274         if current_leaves is body_leaves:
 
2275             if leaf is opening_bracket:
 
2276                 current_leaves = head_leaves if body_leaves else tail_leaves
 
2277         current_leaves.append(leaf)
 
2278         if current_leaves is tail_leaves:
 
2279             if leaf.type in CLOSING_BRACKETS and id(leaf) not in omit:
 
2280                 opening_bracket = leaf.opening_bracket
 
2281                 closing_bracket = leaf
 
2282                 current_leaves = body_leaves
 
2283     tail_leaves.reverse()
 
2284     body_leaves.reverse()
 
2285     head_leaves.reverse()
 
2286     # Since body is a new indent level, remove spurious leading whitespace.
 
2288         normalize_prefix(body_leaves[0], inside_brackets=True)
 
2290         # No `head` means the split failed. Either `tail` has all content or
 
2291         # the matching `opening_bracket` wasn't available on `line` anymore.
 
2292         raise CannotSplit("No brackets found")
 
2294     # Build the new lines.
 
2295     for result, leaves in (head, head_leaves), (body, body_leaves), (tail, tail_leaves):
 
2297             result.append(leaf, preformatted=True)
 
2298             for comment_after in line.comments_after(leaf):
 
2299                 result.append(comment_after, preformatted=True)
 
2300     assert opening_bracket and closing_bracket
 
2301     body.should_explode = should_explode(body, opening_bracket)
 
2302     bracket_split_succeeded_or_raise(head, body, tail)
 
2304         # the body shouldn't be exploded
 
2305         not body.should_explode
 
2306         # the opening bracket is an optional paren
 
2307         and opening_bracket.type == token.LPAR
 
2308         and not opening_bracket.value
 
2309         # the closing bracket is an optional paren
 
2310         and closing_bracket.type == token.RPAR
 
2311         and not closing_bracket.value
 
2312         # it's not an import (optional parens are the only thing we can split on
 
2313         # in this case; attempting a split without them is a waste of time)
 
2314         and not line.is_import
 
2315         # there are no standalone comments in the body
 
2316         and not body.contains_standalone_comments(0)
 
2317         # and we can actually remove the parens
 
2318         and can_omit_invisible_parens(body, line_length)
 
2320         omit = {id(closing_bracket), *omit}
 
2322             yield from right_hand_split(line, line_length, py36=py36, omit=omit)
 
2328                 or is_line_short_enough(body, line_length=line_length)
 
2331                     "Splitting failed, body is still too long and can't be split."
 
2334             elif head.contains_multiline_strings() or tail.contains_multiline_strings():
 
2336                     "The current optional pair of parentheses is bound to fail to "
 
2337                     "satisfy the splitting algorithm because the head or the tail "
 
2338                     "contains multiline strings which by definition never fit one "
 
2342     ensure_visible(opening_bracket)
 
2343     ensure_visible(closing_bracket)
 
2344     for result in (head, body, tail):
 
2349 def bracket_split_succeeded_or_raise(head: Line, body: Line, tail: Line) -> None:
 
2350     """Raise :exc:`CannotSplit` if the last left- or right-hand split failed.
 
2352     Do nothing otherwise.
 
2354     A left- or right-hand split is based on a pair of brackets. Content before
 
2355     (and including) the opening bracket is left on one line, content inside the
 
2356     brackets is put on a separate line, and finally content starting with and
 
2357     following the closing bracket is put on a separate line.
 
2359     Those are called `head`, `body`, and `tail`, respectively. If the split
 
2360     produced the same line (all content in `head`) or ended up with an empty `body`
 
2361     and the `tail` is just the closing bracket, then it's considered failed.
 
2363     tail_len = len(str(tail).strip())
 
2366             raise CannotSplit("Splitting brackets produced the same line")
 
2370                 f"Splitting brackets on an empty body to save "
 
2371                 f"{tail_len} characters is not worth it"
 
2375 def dont_increase_indentation(split_func: SplitFunc) -> SplitFunc:
 
2376     """Normalize prefix of the first leaf in every line returned by `split_func`.
 
2378     This is a decorator over relevant split functions.
 
2382     def split_wrapper(line: Line, py36: bool = False) -> Iterator[Line]:
 
2383         for l in split_func(line, py36):
 
2384             normalize_prefix(l.leaves[0], inside_brackets=True)
 
2387     return split_wrapper
 
2390 @dont_increase_indentation
 
2391 def delimiter_split(line: Line, py36: bool = False) -> Iterator[Line]:
 
2392     """Split according to delimiters of the highest priority.
 
2394     If `py36` is True, the split will add trailing commas also in function
 
2395     signatures that contain `*` and `**`.
 
2398         last_leaf = line.leaves[-1]
 
2400         raise CannotSplit("Line empty")
 
2402     bt = line.bracket_tracker
 
2404         delimiter_priority = bt.max_delimiter_priority(exclude={id(last_leaf)})
 
2406         raise CannotSplit("No delimiters found")
 
2408     if delimiter_priority == DOT_PRIORITY:
 
2409         if bt.delimiter_count_with_priority(delimiter_priority) == 1:
 
2410             raise CannotSplit("Splitting a single attribute from its owner looks wrong")
 
2412     current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
 
2413     lowest_depth = sys.maxsize
 
2414     trailing_comma_safe = True
 
2416     def append_to_line(leaf: Leaf) -> Iterator[Line]:
 
2417         """Append `leaf` to current line or to new line if appending impossible."""
 
2418         nonlocal current_line
 
2420             current_line.append_safe(leaf, preformatted=True)
 
2421         except ValueError as ve:
 
2424             current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
 
2425             current_line.append(leaf)
 
2427     for index, leaf in enumerate(line.leaves):
 
2428         yield from append_to_line(leaf)
 
2430         for comment_after in line.comments_after(leaf, index):
 
2431             yield from append_to_line(comment_after)
 
2433         lowest_depth = min(lowest_depth, leaf.bracket_depth)
 
2434         if leaf.bracket_depth == lowest_depth and is_vararg(
 
2435             leaf, within=VARARGS_PARENTS
 
2437             trailing_comma_safe = trailing_comma_safe and py36
 
2438         leaf_priority = bt.delimiters.get(id(leaf))
 
2439         if leaf_priority == delimiter_priority:
 
2442             current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
 
2446             and delimiter_priority == COMMA_PRIORITY
 
2447             and current_line.leaves[-1].type != token.COMMA
 
2448             and current_line.leaves[-1].type != STANDALONE_COMMENT
 
2450             current_line.append(Leaf(token.COMMA, ","))
 
2454 @dont_increase_indentation
 
2455 def standalone_comment_split(line: Line, py36: bool = False) -> Iterator[Line]:
 
2456     """Split standalone comments from the rest of the line."""
 
2457     if not line.contains_standalone_comments(0):
 
2458         raise CannotSplit("Line does not have any standalone comments")
 
2460     current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
 
2462     def append_to_line(leaf: Leaf) -> Iterator[Line]:
 
2463         """Append `leaf` to current line or to new line if appending impossible."""
 
2464         nonlocal current_line
 
2466             current_line.append_safe(leaf, preformatted=True)
 
2467         except ValueError as ve:
 
2470             current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
 
2471             current_line.append(leaf)
 
2473     for index, leaf in enumerate(line.leaves):
 
2474         yield from append_to_line(leaf)
 
2476         for comment_after in line.comments_after(leaf, index):
 
2477             yield from append_to_line(comment_after)
 
2483 def is_import(leaf: Leaf) -> bool:
 
2484     """Return True if the given leaf starts an import statement."""
 
2491             (v == "import" and p and p.type == syms.import_name)
 
2492             or (v == "from" and p and p.type == syms.import_from)
 
2497 def normalize_prefix(leaf: Leaf, *, inside_brackets: bool) -> None:
 
2498     """Leave existing extra newlines if not `inside_brackets`. Remove everything
 
2501     Note: don't use backslashes for formatting or you'll lose your voting rights.
 
2503     if not inside_brackets:
 
2504         spl = leaf.prefix.split("#")
 
2505         if "\\" not in spl[0]:
 
2506             nl_count = spl[-1].count("\n")
 
2509             leaf.prefix = "\n" * nl_count
 
2515 def normalize_string_prefix(leaf: Leaf, remove_u_prefix: bool = False) -> None:
 
2516     """Make all string prefixes lowercase.
 
2518     If remove_u_prefix is given, also removes any u prefix from the string.
 
2520     Note: Mutates its argument.
 
2522     match = re.match(r"^([furbFURB]*)(.*)$", leaf.value, re.DOTALL)
 
2523     assert match is not None, f"failed to match string {leaf.value!r}"
 
2524     orig_prefix = match.group(1)
 
2525     new_prefix = orig_prefix.lower()
 
2527         new_prefix = new_prefix.replace("u", "")
 
2528     leaf.value = f"{new_prefix}{match.group(2)}"
 
2531 def normalize_string_quotes(leaf: Leaf) -> None:
 
2532     """Prefer double quotes but only if it doesn't cause more escaping.
 
2534     Adds or removes backslashes as appropriate. Doesn't parse and fix
 
2535     strings nested in f-strings (yet).
 
2537     Note: Mutates its argument.
 
2539     value = leaf.value.lstrip("furbFURB")
 
2540     if value[:3] == '"""':
 
2543     elif value[:3] == "'''":
 
2546     elif value[0] == '"':
 
2552     first_quote_pos = leaf.value.find(orig_quote)
 
2553     if first_quote_pos == -1:
 
2554         return  # There's an internal error
 
2556     prefix = leaf.value[:first_quote_pos]
 
2557     unescaped_new_quote = re.compile(rf"(([^\\]|^)(\\\\)*){new_quote}")
 
2558     escaped_new_quote = re.compile(rf"([^\\]|^)\\((?:\\\\)*){new_quote}")
 
2559     escaped_orig_quote = re.compile(rf"([^\\]|^)\\((?:\\\\)*){orig_quote}")
 
2560     body = leaf.value[first_quote_pos + len(orig_quote) : -len(orig_quote)]
 
2561     if "r" in prefix.casefold():
 
2562         if unescaped_new_quote.search(body):
 
2563             # There's at least one unescaped new_quote in this raw string
 
2564             # so converting is impossible
 
2567         # Do not introduce or remove backslashes in raw strings
 
2570         # remove unnecessary escapes
 
2571         new_body = sub_twice(escaped_new_quote, rf"\1\2{new_quote}", body)
 
2572         if body != new_body:
 
2573             # Consider the string without unnecessary escapes as the original
 
2575             leaf.value = f"{prefix}{orig_quote}{body}{orig_quote}"
 
2576         new_body = sub_twice(escaped_orig_quote, rf"\1\2{orig_quote}", new_body)
 
2577         new_body = sub_twice(unescaped_new_quote, rf"\1\\{new_quote}", new_body)
 
2578     if "f" in prefix.casefold():
 
2579         matches = re.findall(r"[^{]\{(.*?)\}[^}]", new_body)
 
2582                 # Do not introduce backslashes in interpolated expressions
 
2584     if new_quote == '"""' and new_body[-1:] == '"':
 
2586         new_body = new_body[:-1] + '\\"'
 
2587     orig_escape_count = body.count("\\")
 
2588     new_escape_count = new_body.count("\\")
 
2589     if new_escape_count > orig_escape_count:
 
2590         return  # Do not introduce more escaping
 
2592     if new_escape_count == orig_escape_count and orig_quote == '"':
 
2593         return  # Prefer double quotes
 
2595     leaf.value = f"{prefix}{new_quote}{new_body}{new_quote}"
 
2598 def normalize_invisible_parens(node: Node, parens_after: Set[str]) -> None:
 
2599     """Make existing optional parentheses invisible or create new ones.
 
2601     `parens_after` is a set of string leaf values immeditely after which parens
 
2604     Standardizes on visible parentheses for single-element tuples, and keeps
 
2605     existing visible parentheses for other tuples and generator expressions.
 
2607     for pc in list_comments(node.prefix, is_endmarker=False):
 
2608         if pc.value in FMT_OFF:
 
2609             # This `node` has a prefix with `# fmt: off`, don't mess with parens.
 
2613     for index, child in enumerate(list(node.children)):
 
2615             if child.type == syms.atom:
 
2616                 maybe_make_parens_invisible_in_atom(child)
 
2617             elif is_one_tuple(child):
 
2618                 # wrap child in visible parentheses
 
2619                 lpar = Leaf(token.LPAR, "(")
 
2620                 rpar = Leaf(token.RPAR, ")")
 
2622                 node.insert_child(index, Node(syms.atom, [lpar, child, rpar]))
 
2623             elif node.type == syms.import_from:
 
2624                 # "import from" nodes store parentheses directly as part of
 
2626                 if child.type == token.LPAR:
 
2627                     # make parentheses invisible
 
2628                     child.value = ""  # type: ignore
 
2629                     node.children[-1].value = ""  # type: ignore
 
2630                 elif child.type != token.STAR:
 
2631                     # insert invisible parentheses
 
2632                     node.insert_child(index, Leaf(token.LPAR, ""))
 
2633                     node.append_child(Leaf(token.RPAR, ""))
 
2636             elif not (isinstance(child, Leaf) and is_multiline_string(child)):
 
2637                 # wrap child in invisible parentheses
 
2638                 lpar = Leaf(token.LPAR, "")
 
2639                 rpar = Leaf(token.RPAR, "")
 
2640                 index = child.remove() or 0
 
2641                 node.insert_child(index, Node(syms.atom, [lpar, child, rpar]))
 
2643         check_lpar = isinstance(child, Leaf) and child.value in parens_after
 
2646 def maybe_make_parens_invisible_in_atom(node: LN) -> bool:
 
2647     """If it's safe, make the parens in the atom `node` invisible, recursively."""
 
2649         node.type != syms.atom
 
2650         or is_empty_tuple(node)
 
2651         or is_one_tuple(node)
 
2653         or max_delimiter_priority_in_atom(node) >= COMMA_PRIORITY
 
2657     first = node.children[0]
 
2658     last = node.children[-1]
 
2659     if first.type == token.LPAR and last.type == token.RPAR:
 
2660         # make parentheses invisible
 
2661         first.value = ""  # type: ignore
 
2662         last.value = ""  # type: ignore
 
2663         if len(node.children) > 1:
 
2664             maybe_make_parens_invisible_in_atom(node.children[1])
 
2670 def is_empty_tuple(node: LN) -> bool:
 
2671     """Return True if `node` holds an empty tuple."""
 
2673         node.type == syms.atom
 
2674         and len(node.children) == 2
 
2675         and node.children[0].type == token.LPAR
 
2676         and node.children[1].type == token.RPAR
 
2680 def is_one_tuple(node: LN) -> bool:
 
2681     """Return True if `node` holds a tuple with one element, with or without parens."""
 
2682     if node.type == syms.atom:
 
2683         if len(node.children) != 3:
 
2686         lpar, gexp, rpar = node.children
 
2688             lpar.type == token.LPAR
 
2689             and gexp.type == syms.testlist_gexp
 
2690             and rpar.type == token.RPAR
 
2694         return len(gexp.children) == 2 and gexp.children[1].type == token.COMMA
 
2697         node.type in IMPLICIT_TUPLE
 
2698         and len(node.children) == 2
 
2699         and node.children[1].type == token.COMMA
 
2703 def is_yield(node: LN) -> bool:
 
2704     """Return True if `node` holds a `yield` or `yield from` expression."""
 
2705     if node.type == syms.yield_expr:
 
2708     if node.type == token.NAME and node.value == "yield":  # type: ignore
 
2711     if node.type != syms.atom:
 
2714     if len(node.children) != 3:
 
2717     lpar, expr, rpar = node.children
 
2718     if lpar.type == token.LPAR and rpar.type == token.RPAR:
 
2719         return is_yield(expr)
 
2724 def is_vararg(leaf: Leaf, within: Set[NodeType]) -> bool:
 
2725     """Return True if `leaf` is a star or double star in a vararg or kwarg.
 
2727     If `within` includes VARARGS_PARENTS, this applies to function signatures.
 
2728     If `within` includes UNPACKING_PARENTS, it applies to right hand-side
 
2729     extended iterable unpacking (PEP 3132) and additional unpacking
 
2730     generalizations (PEP 448).
 
2732     if leaf.type not in STARS or not leaf.parent:
 
2736     if p.type == syms.star_expr:
 
2737         # Star expressions are also used as assignment targets in extended
 
2738         # iterable unpacking (PEP 3132).  See what its parent is instead.
 
2744     return p.type in within
 
2747 def is_multiline_string(leaf: Leaf) -> bool:
 
2748     """Return True if `leaf` is a multiline string that actually spans many lines."""
 
2749     value = leaf.value.lstrip("furbFURB")
 
2750     return value[:3] in {'"""', "'''"} and "\n" in value
 
2753 def is_stub_suite(node: Node) -> bool:
 
2754     """Return True if `node` is a suite with a stub body."""
 
2756         len(node.children) != 4
 
2757         or node.children[0].type != token.NEWLINE
 
2758         or node.children[1].type != token.INDENT
 
2759         or node.children[3].type != token.DEDENT
 
2763     return is_stub_body(node.children[2])
 
2766 def is_stub_body(node: LN) -> bool:
 
2767     """Return True if `node` is a simple statement containing an ellipsis."""
 
2768     if not isinstance(node, Node) or node.type != syms.simple_stmt:
 
2771     if len(node.children) != 2:
 
2774     child = node.children[0]
 
2776         child.type == syms.atom
 
2777         and len(child.children) == 3
 
2778         and all(leaf == Leaf(token.DOT, ".") for leaf in child.children)
 
2782 def max_delimiter_priority_in_atom(node: LN) -> int:
 
2783     """Return maximum delimiter priority inside `node`.
 
2785     This is specific to atoms with contents contained in a pair of parentheses.
 
2786     If `node` isn't an atom or there are no enclosing parentheses, returns 0.
 
2788     if node.type != syms.atom:
 
2791     first = node.children[0]
 
2792     last = node.children[-1]
 
2793     if not (first.type == token.LPAR and last.type == token.RPAR):
 
2796     bt = BracketTracker()
 
2797     for c in node.children[1:-1]:
 
2798         if isinstance(c, Leaf):
 
2801             for leaf in c.leaves():
 
2804         return bt.max_delimiter_priority()
 
2810 def ensure_visible(leaf: Leaf) -> None:
 
2811     """Make sure parentheses are visible.
 
2813     They could be invisible as part of some statements (see
 
2814     :func:`normalize_invible_parens` and :func:`visit_import_from`).
 
2816     if leaf.type == token.LPAR:
 
2818     elif leaf.type == token.RPAR:
 
2822 def should_explode(line: Line, opening_bracket: Leaf) -> bool:
 
2823     """Should `line` immediately be split with `delimiter_split()` after RHS?"""
 
2825         opening_bracket.parent
 
2826         and opening_bracket.parent.type in {syms.atom, syms.import_from}
 
2827         and opening_bracket.value in "[{("
 
2832         last_leaf = line.leaves[-1]
 
2833         exclude = {id(last_leaf)} if last_leaf.type == token.COMMA else set()
 
2834         max_priority = line.bracket_tracker.max_delimiter_priority(exclude=exclude)
 
2835     except (IndexError, ValueError):
 
2838     return max_priority == COMMA_PRIORITY
 
2841 def is_python36(node: Node) -> bool:
 
2842     """Return True if the current file is using Python 3.6+ features.
 
2844     Currently looking for:
 
2846     - trailing commas after * or ** in function signatures and calls.
 
2848     for n in node.pre_order():
 
2849         if n.type == token.STRING:
 
2850             value_head = n.value[:2]  # type: ignore
 
2851             if value_head in {'f"', 'F"', "f'", "F'", "rf", "fr", "RF", "FR"}:
 
2855             n.type in {syms.typedargslist, syms.arglist}
 
2857             and n.children[-1].type == token.COMMA
 
2859             for ch in n.children:
 
2860                 if ch.type in STARS:
 
2863                 if ch.type == syms.argument:
 
2864                     for argch in ch.children:
 
2865                         if argch.type in STARS:
 
2871 def generate_trailers_to_omit(line: Line, line_length: int) -> Iterator[Set[LeafID]]:
 
2872     """Generate sets of closing bracket IDs that should be omitted in a RHS.
 
2874     Brackets can be omitted if the entire trailer up to and including
 
2875     a preceding closing bracket fits in one line.
 
2877     Yielded sets are cumulative (contain results of previous yields, too).  First
 
2881     omit: Set[LeafID] = set()
 
2884     length = 4 * line.depth
 
2885     opening_bracket = None
 
2886     closing_bracket = None
 
2887     optional_brackets: Set[LeafID] = set()
 
2888     inner_brackets: Set[LeafID] = set()
 
2889     for index, leaf, leaf_length in enumerate_with_length(line, reversed=True):
 
2890         length += leaf_length
 
2891         if length > line_length:
 
2894         has_inline_comment = leaf_length > len(leaf.value) + len(leaf.prefix)
 
2895         if leaf.type == STANDALONE_COMMENT or has_inline_comment:
 
2898         optional_brackets.discard(id(leaf))
 
2900             if leaf is opening_bracket:
 
2901                 opening_bracket = None
 
2902             elif leaf.type in CLOSING_BRACKETS:
 
2903                 inner_brackets.add(id(leaf))
 
2904         elif leaf.type in CLOSING_BRACKETS:
 
2906                 optional_brackets.add(id(opening_bracket))
 
2909             if index > 0 and line.leaves[index - 1].type in OPENING_BRACKETS:
 
2910                 # Empty brackets would fail a split so treat them as "inner"
 
2911                 # brackets (e.g. only add them to the `omit` set if another
 
2912                 # pair of brackets was good enough.
 
2913                 inner_brackets.add(id(leaf))
 
2916             opening_bracket = leaf.opening_bracket
 
2918                 omit.add(id(closing_bracket))
 
2919                 omit.update(inner_brackets)
 
2920                 inner_brackets.clear()
 
2922             closing_bracket = leaf
 
2925 def get_future_imports(node: Node) -> Set[str]:
 
2926     """Return a set of __future__ imports in the file."""
 
2928     for child in node.children:
 
2929         if child.type != syms.simple_stmt:
 
2931         first_child = child.children[0]
 
2932         if isinstance(first_child, Leaf):
 
2933             # Continue looking if we see a docstring; otherwise stop.
 
2935                 len(child.children) == 2
 
2936                 and first_child.type == token.STRING
 
2937                 and child.children[1].type == token.NEWLINE
 
2942         elif first_child.type == syms.import_from:
 
2943             module_name = first_child.children[1]
 
2944             if not isinstance(module_name, Leaf) or module_name.value != "__future__":
 
2946             for import_from_child in first_child.children[3:]:
 
2947                 if isinstance(import_from_child, Leaf):
 
2948                     if import_from_child.type == token.NAME:
 
2949                         imports.add(import_from_child.value)
 
2951                     assert import_from_child.type == syms.import_as_names
 
2952                     for leaf in import_from_child.children:
 
2953                         if isinstance(leaf, Leaf) and leaf.type == token.NAME:
 
2954                             imports.add(leaf.value)
 
2960 def gen_python_files_in_dir(
 
2963     include: Pattern[str],
 
2964     exclude: Pattern[str],
 
2966 ) -> Iterator[Path]:
 
2967     """Generate all files under `path` whose paths are not excluded by the
 
2968     `exclude` regex, but are included by the `include` regex.
 
2970     Symbolic links pointing outside of the root directory are ignored.
 
2972     `report` is where output about exclusions goes.
 
2974     assert root.is_absolute(), f"INTERNAL ERROR: `root` must be absolute but is {root}"
 
2975     for child in path.iterdir():
 
2977             normalized_path = "/" + child.resolve().relative_to(root).as_posix()
 
2979             if child.is_symlink():
 
2980                 report.path_ignored(
 
2982                     "is a symbolic link that points outside of the root directory",
 
2989             normalized_path += "/"
 
2990         exclude_match = exclude.search(normalized_path)
 
2991         if exclude_match and exclude_match.group(0):
 
2992             report.path_ignored(child, f"matches the --exclude regular expression")
 
2996             yield from gen_python_files_in_dir(child, root, include, exclude, report)
 
2998         elif child.is_file():
 
2999             include_match = include.search(normalized_path)
 
3005 def find_project_root(srcs: Iterable[str]) -> Path:
 
3006     """Return a directory containing .git, .hg, or pyproject.toml.
 
3008     That directory can be one of the directories passed in `srcs` or their
 
3011     If no directory in the tree contains a marker that would specify it's the
 
3012     project root, the root of the file system is returned.
 
3015         return Path("/").resolve()
 
3017     common_base = min(Path(src).resolve() for src in srcs)
 
3018     if common_base.is_dir():
 
3019         # Append a fake file so `parents` below returns `common_base_dir`, too.
 
3020         common_base /= "fake-file"
 
3021     for directory in common_base.parents:
 
3022         if (directory / ".git").is_dir():
 
3025         if (directory / ".hg").is_dir():
 
3028         if (directory / "pyproject.toml").is_file():
 
3036     """Provides a reformatting counter. Can be rendered with `str(report)`."""
 
3040     verbose: bool = False
 
3041     change_count: int = 0
 
3043     failure_count: int = 0
 
3045     def done(self, src: Path, changed: Changed) -> None:
 
3046         """Increment the counter for successful reformatting. Write out a message."""
 
3047         if changed is Changed.YES:
 
3048             reformatted = "would reformat" if self.check else "reformatted"
 
3049             if self.verbose or not self.quiet:
 
3050                 out(f"{reformatted} {src}")
 
3051             self.change_count += 1
 
3054                 if changed is Changed.NO:
 
3055                     msg = f"{src} already well formatted, good job."
 
3057                     msg = f"{src} wasn't modified on disk since last run."
 
3058                 out(msg, bold=False)
 
3059             self.same_count += 1
 
3061     def failed(self, src: Path, message: str) -> None:
 
3062         """Increment the counter for failed reformatting. Write out a message."""
 
3063         err(f"error: cannot format {src}: {message}")
 
3064         self.failure_count += 1
 
3066     def path_ignored(self, path: Path, message: str) -> None:
 
3068             out(f"{path} ignored: {message}", bold=False)
 
3071     def return_code(self) -> int:
 
3072         """Return the exit code that the app should use.
 
3074         This considers the current state of changed files and failures:
 
3075         - if there were any failures, return 123;
 
3076         - if any files were changed and --check is being used, return 1;
 
3077         - otherwise return 0.
 
3079         # According to http://tldp.org/LDP/abs/html/exitcodes.html starting with
 
3080         # 126 we have special returncodes reserved by the shell.
 
3081         if self.failure_count:
 
3084         elif self.change_count and self.check:
 
3089     def __str__(self) -> str:
 
3090         """Render a color report of the current state.
 
3092         Use `click.unstyle` to remove colors.
 
3095             reformatted = "would be reformatted"
 
3096             unchanged = "would be left unchanged"
 
3097             failed = "would fail to reformat"
 
3099             reformatted = "reformatted"
 
3100             unchanged = "left unchanged"
 
3101             failed = "failed to reformat"
 
3103         if self.change_count:
 
3104             s = "s" if self.change_count > 1 else ""
 
3106                 click.style(f"{self.change_count} file{s} {reformatted}", bold=True)
 
3109             s = "s" if self.same_count > 1 else ""
 
3110             report.append(f"{self.same_count} file{s} {unchanged}")
 
3111         if self.failure_count:
 
3112             s = "s" if self.failure_count > 1 else ""
 
3114                 click.style(f"{self.failure_count} file{s} {failed}", fg="red")
 
3116         return ", ".join(report) + "."
 
3119 def assert_equivalent(src: str, dst: str) -> None:
 
3120     """Raise AssertionError if `src` and `dst` aren't equivalent."""
 
3125     def _v(node: ast.AST, depth: int = 0) -> Iterator[str]:
 
3126         """Simple visitor generating strings to compare ASTs by content."""
 
3127         yield f"{'  ' * depth}{node.__class__.__name__}("
 
3129         for field in sorted(node._fields):
 
3131                 value = getattr(node, field)
 
3132             except AttributeError:
 
3135             yield f"{'  ' * (depth+1)}{field}="
 
3137             if isinstance(value, list):
 
3139                     if isinstance(item, ast.AST):
 
3140                         yield from _v(item, depth + 2)
 
3142             elif isinstance(value, ast.AST):
 
3143                 yield from _v(value, depth + 2)
 
3146                 yield f"{'  ' * (depth+2)}{value!r},  # {value.__class__.__name__}"
 
3148         yield f"{'  ' * depth})  # /{node.__class__.__name__}"
 
3151         src_ast = ast.parse(src)
 
3152     except Exception as exc:
 
3153         major, minor = sys.version_info[:2]
 
3154         raise AssertionError(
 
3155             f"cannot use --safe with this file; failed to parse source file "
 
3156             f"with Python {major}.{minor}'s builtin AST. Re-run with --fast "
 
3157             f"or stop using deprecated Python 2 syntax. AST error message: {exc}"
 
3161         dst_ast = ast.parse(dst)
 
3162     except Exception as exc:
 
3163         log = dump_to_file("".join(traceback.format_tb(exc.__traceback__)), dst)
 
3164         raise AssertionError(
 
3165             f"INTERNAL ERROR: Black produced invalid code: {exc}. "
 
3166             f"Please report a bug on https://github.com/ambv/black/issues.  "
 
3167             f"This invalid output might be helpful: {log}"
 
3170     src_ast_str = "\n".join(_v(src_ast))
 
3171     dst_ast_str = "\n".join(_v(dst_ast))
 
3172     if src_ast_str != dst_ast_str:
 
3173         log = dump_to_file(diff(src_ast_str, dst_ast_str, "src", "dst"))
 
3174         raise AssertionError(
 
3175             f"INTERNAL ERROR: Black produced code that is not equivalent to "
 
3177             f"Please report a bug on https://github.com/ambv/black/issues.  "
 
3178             f"This diff might be helpful: {log}"
 
3183     src: str, dst: str, line_length: int, mode: FileMode = FileMode.AUTO_DETECT
 
3185     """Raise AssertionError if `dst` reformats differently the second time."""
 
3186     newdst = format_str(dst, line_length=line_length, mode=mode)
 
3189             diff(src, dst, "source", "first pass"),
 
3190             diff(dst, newdst, "first pass", "second pass"),
 
3192         raise AssertionError(
 
3193             f"INTERNAL ERROR: Black produced different code on the second pass "
 
3194             f"of the formatter.  "
 
3195             f"Please report a bug on https://github.com/ambv/black/issues.  "
 
3196             f"This diff might be helpful: {log}"
 
3200 def dump_to_file(*output: str) -> str:
 
3201     """Dump `output` to a temporary file. Return path to the file."""
 
3204     with tempfile.NamedTemporaryFile(
 
3205         mode="w", prefix="blk_", suffix=".log", delete=False, encoding="utf8"
 
3207         for lines in output:
 
3209             if lines and lines[-1] != "\n":
 
3214 def diff(a: str, b: str, a_name: str, b_name: str) -> str:
 
3215     """Return a unified diff string between strings `a` and `b`."""
 
3218     a_lines = [line + "\n" for line in a.split("\n")]
 
3219     b_lines = [line + "\n" for line in b.split("\n")]
 
3221         difflib.unified_diff(a_lines, b_lines, fromfile=a_name, tofile=b_name, n=5)
 
3225 def cancel(tasks: Iterable[asyncio.Task]) -> None:
 
3226     """asyncio signal handler that cancels all `tasks` and reports to stderr."""
 
3232 def shutdown(loop: BaseEventLoop) -> None:
 
3233     """Cancel all pending tasks on `loop`, wait for them, and close the loop."""
 
3235         # This part is borrowed from asyncio/runners.py in Python 3.7b2.
 
3236         to_cancel = [task for task in asyncio.Task.all_tasks(loop) if not task.done()]
 
3240         for task in to_cancel:
 
3242         loop.run_until_complete(
 
3243             asyncio.gather(*to_cancel, loop=loop, return_exceptions=True)
 
3246         # `concurrent.futures.Future` objects cannot be cancelled once they
 
3247         # are already running. There might be some when the `shutdown()` happened.
 
3248         # Silence their logger's spew about the event loop being closed.
 
3249         cf_logger = logging.getLogger("concurrent.futures")
 
3250         cf_logger.setLevel(logging.CRITICAL)
 
3254 def sub_twice(regex: Pattern[str], replacement: str, original: str) -> str:
 
3255     """Replace `regex` with `replacement` twice on `original`.
 
3257     This is used by string normalization to perform replaces on
 
3258     overlapping matches.
 
3260     return regex.sub(replacement, regex.sub(replacement, original))
 
3263 def re_compile_maybe_verbose(regex: str) -> Pattern[str]:
 
3264     """Compile a regular expression string in `regex`.
 
3266     If it contains newlines, use verbose mode.
 
3269         regex = "(?x)" + regex
 
3270     return re.compile(regex)
 
3273 def enumerate_reversed(sequence: Sequence[T]) -> Iterator[Tuple[Index, T]]:
 
3274     """Like `reversed(enumerate(sequence))` if that were possible."""
 
3275     index = len(sequence) - 1
 
3276     for element in reversed(sequence):
 
3277         yield (index, element)
 
3281 def enumerate_with_length(
 
3282     line: Line, reversed: bool = False
 
3283 ) -> Iterator[Tuple[Index, Leaf, int]]:
 
3284     """Return an enumeration of leaves with their length.
 
3286     Stops prematurely on multiline strings and standalone comments.
 
3289         Callable[[Sequence[Leaf]], Iterator[Tuple[Index, Leaf]]],
 
3290         enumerate_reversed if reversed else enumerate,
 
3292     for index, leaf in op(line.leaves):
 
3293         length = len(leaf.prefix) + len(leaf.value)
 
3294         if "\n" in leaf.value:
 
3295             return  # Multiline strings, we can't continue.
 
3297         comment: Optional[Leaf]
 
3298         for comment in line.comments_after(leaf, index):
 
3299             length += len(comment.value)
 
3301         yield index, leaf, length
 
3304 def is_line_short_enough(line: Line, *, line_length: int, line_str: str = "") -> bool:
 
3305     """Return True if `line` is no longer than `line_length`.
 
3307     Uses the provided `line_str` rendering, if any, otherwise computes a new one.
 
3310         line_str = str(line).strip("\n")
 
3312         len(line_str) <= line_length
 
3313         and "\n" not in line_str  # multiline strings
 
3314         and not line.contains_standalone_comments()
 
3318 def can_be_split(line: Line) -> bool:
 
3319     """Return False if the line cannot be split *for sure*.
 
3321     This is not an exhaustive search but a cheap heuristic that we can use to
 
3322     avoid some unfortunate formattings (mostly around wrapping unsplittable code
 
3323     in unnecessary parentheses).
 
3325     leaves = line.leaves
 
3329     if leaves[0].type == token.STRING and leaves[1].type == token.DOT:
 
3333         for leaf in leaves[-2::-1]:
 
3334             if leaf.type in OPENING_BRACKETS:
 
3335                 if next.type not in CLOSING_BRACKETS:
 
3339             elif leaf.type == token.DOT:
 
3341             elif leaf.type == token.NAME:
 
3342                 if not (next.type == token.DOT or next.type in OPENING_BRACKETS):
 
3345             elif leaf.type not in CLOSING_BRACKETS:
 
3348             if dot_count > 1 and call_count > 1:
 
3354 def can_omit_invisible_parens(line: Line, line_length: int) -> bool:
 
3355     """Does `line` have a shape safe to reformat without optional parens around it?
 
3357     Returns True for only a subset of potentially nice looking formattings but
 
3358     the point is to not return false positives that end up producing lines that
 
3361     bt = line.bracket_tracker
 
3362     if not bt.delimiters:
 
3363         # Without delimiters the optional parentheses are useless.
 
3366     max_priority = bt.max_delimiter_priority()
 
3367     if bt.delimiter_count_with_priority(max_priority) > 1:
 
3368         # With more than one delimiter of a kind the optional parentheses read better.
 
3371     if max_priority == DOT_PRIORITY:
 
3372         # A single stranded method call doesn't require optional parentheses.
 
3375     assert len(line.leaves) >= 2, "Stranded delimiter"
 
3377     first = line.leaves[0]
 
3378     second = line.leaves[1]
 
3379     penultimate = line.leaves[-2]
 
3380     last = line.leaves[-1]
 
3382     # With a single delimiter, omit if the expression starts or ends with
 
3384     if first.type in OPENING_BRACKETS and second.type not in CLOSING_BRACKETS:
 
3386         length = 4 * line.depth
 
3387         for _index, leaf, leaf_length in enumerate_with_length(line):
 
3388             if leaf.type in CLOSING_BRACKETS and leaf.opening_bracket is first:
 
3391                 length += leaf_length
 
3392                 if length > line_length:
 
3395                 if leaf.type in OPENING_BRACKETS:
 
3396                     # There are brackets we can further split on.
 
3400             # checked the entire string and line length wasn't exceeded
 
3401             if len(line.leaves) == _index + 1:
 
3404         # Note: we are not returning False here because a line might have *both*
 
3405         # a leading opening bracket and a trailing closing bracket.  If the
 
3406         # opening bracket doesn't match our rule, maybe the closing will.
 
3409         last.type == token.RPAR
 
3410         or last.type == token.RBRACE
 
3412             # don't use indexing for omitting optional parentheses;
 
3414             last.type == token.RSQB
 
3416             and last.parent.type != syms.trailer
 
3419         if penultimate.type in OPENING_BRACKETS:
 
3420             # Empty brackets don't help.
 
3423         if is_multiline_string(first):
 
3424             # Additional wrapping of a multiline string in this situation is
 
3428         length = 4 * line.depth
 
3429         seen_other_brackets = False
 
3430         for _index, leaf, leaf_length in enumerate_with_length(line):
 
3431             length += leaf_length
 
3432             if leaf is last.opening_bracket:
 
3433                 if seen_other_brackets or length <= line_length:
 
3436             elif leaf.type in OPENING_BRACKETS:
 
3437                 # There are brackets we can further split on.
 
3438                 seen_other_brackets = True
 
3443 def get_cache_file(line_length: int, mode: FileMode) -> Path:
 
3444     return CACHE_DIR / f"cache.{line_length}.{mode.value}.pickle"
 
3447 def read_cache(line_length: int, mode: FileMode) -> Cache:
 
3448     """Read the cache if it exists and is well formed.
 
3450     If it is not well formed, the call to write_cache later should resolve the issue.
 
3452     cache_file = get_cache_file(line_length, mode)
 
3453     if not cache_file.exists():
 
3456     with cache_file.open("rb") as fobj:
 
3458             cache: Cache = pickle.load(fobj)
 
3459         except pickle.UnpicklingError:
 
3465 def get_cache_info(path: Path) -> CacheInfo:
 
3466     """Return the information used to check if a file is already formatted or not."""
 
3468     return stat.st_mtime, stat.st_size
 
3471 def filter_cached(cache: Cache, sources: Iterable[Path]) -> Tuple[Set[Path], Set[Path]]:
 
3472     """Split an iterable of paths in `sources` into two sets.
 
3474     The first contains paths of files that modified on disk or are not in the
 
3475     cache. The other contains paths to non-modified files.
 
3477     todo, done = set(), set()
 
3480         if cache.get(src) != get_cache_info(src):
 
3488     cache: Cache, sources: Iterable[Path], line_length: int, mode: FileMode
 
3490     """Update the cache file."""
 
3491     cache_file = get_cache_file(line_length, mode)
 
3493         if not CACHE_DIR.exists():
 
3494             CACHE_DIR.mkdir(parents=True)
 
3495         new_cache = {**cache, **{src.resolve(): get_cache_info(src) for src in sources}}
 
3496         with cache_file.open("wb") as fobj:
 
3497             pickle.dump(new_cache, fobj, protocol=pickle.HIGHEST_PROTOCOL)
 
3502 if __name__ == "__main__":