]> git.madduck.net Git - etc/vim.git/blob - black.py

madduck's git repository

Every one of the projects in this repository is available at the canonical URL git://git.madduck.net/madduck/pub/<projectpath> — see each project's metadata for the exact URL.

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.

SSH access, as well as push access can be individually arranged.

If you use my repositories frequently, consider adding the following snippet to ~/.gitconfig and using the third clone URL listed for each project:

[url "git://git.madduck.net/madduck/"]
  insteadOf = madduck:

Support `# fmt: off/on` pairs within brackets
[etc/vim.git] / black.py
1 import asyncio
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
7 import io
8 import keyword
9 import logging
10 from multiprocessing import Manager
11 import os
12 from pathlib import Path
13 import pickle
14 import re
15 import signal
16 import sys
17 import tokenize
18 from typing import (
19     Any,
20     Callable,
21     Collection,
22     Dict,
23     Generic,
24     Iterable,
25     Iterator,
26     List,
27     Optional,
28     Pattern,
29     Sequence,
30     Set,
31     Tuple,
32     Type,
33     TypeVar,
34     Union,
35     cast,
36 )
37
38 from appdirs import user_cache_dir
39 from attr import dataclass, Factory
40 import click
41 import toml
42
43 # lib2to3 fork
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
48
49
50 __version__ = "18.6b2"
51 DEFAULT_LINE_LENGTH = 88
52 DEFAULT_EXCLUDES = (
53     r"/(\.git|\.hg|\.mypy_cache|\.tox|\.venv|_build|buck-out|build|dist)/"
54 )
55 DEFAULT_INCLUDES = r"\.pyi?$"
56 CACHE_DIR = Path(user_cache_dir("black", version=__version__))
57
58
59 # types
60 FileContent = str
61 Encoding = str
62 NewLine = str
63 Depth = int
64 NodeType = int
65 LeafID = int
66 Priority = int
67 Index = int
68 LN = Union[Leaf, Node]
69 SplitFunc = Callable[["Line", bool], Iterator["Line"]]
70 Timestamp = float
71 FileSize = int
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)
76
77 pygram.initialize(CACHE_DIR)
78 syms = pygram.python_symbols
79
80
81 class NothingChanged(UserWarning):
82     """Raised by :func:`format_file` when reformatted code is the same as source."""
83
84
85 class CannotSplit(Exception):
86     """A readable split that fits the allotted line length is impossible.
87
88     Raised by :func:`left_hand_split`, :func:`right_hand_split`, and
89     :func:`delimiter_split`.
90     """
91
92
93 class FormatError(Exception):
94     """Base exception for `# fmt: on` and `# fmt: off` handling.
95
96     It holds the number of bytes of the prefix consumed before the format
97     control comment appeared.
98     """
99
100     def __init__(self, consumed: int) -> None:
101         super().__init__(consumed)
102         self.consumed = consumed
103
104     def trim_prefix(self, leaf: Leaf) -> None:
105         leaf.prefix = leaf.prefix[self.consumed :]
106
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)
111
112
113 class FormatOn(FormatError):
114     """Found a comment like `# fmt: on` in the file."""
115
116
117 class FormatOff(FormatError):
118     """Found a comment like `# fmt: off` in the file."""
119
120
121 class WriteBack(Enum):
122     NO = 0
123     YES = 1
124     DIFF = 2
125
126     @classmethod
127     def from_configuration(cls, *, check: bool, diff: bool) -> "WriteBack":
128         if check and not diff:
129             return cls.NO
130
131         return cls.DIFF if diff else cls.YES
132
133
134 class Changed(Enum):
135     NO = 0
136     CACHED = 1
137     YES = 2
138
139
140 class FileMode(Flag):
141     AUTO_DETECT = 0
142     PYTHON36 = 1
143     PYI = 2
144     NO_STRING_NORMALIZATION = 4
145
146     @classmethod
147     def from_configuration(
148         cls, *, py36: bool, pyi: bool, skip_string_normalization: bool
149     ) -> "FileMode":
150         mode = cls.AUTO_DETECT
151         if py36:
152             mode |= cls.PYTHON36
153         if pyi:
154             mode |= cls.PYI
155         if skip_string_normalization:
156             mode |= cls.NO_STRING_NORMALIZATION
157         return mode
158
159
160 def read_pyproject_toml(
161     ctx: click.Context, param: click.Parameter, value: Union[str, int, bool, None]
162 ) -> Optional[str]:
163     """Inject Black configuration from "pyproject.toml" into defaults in `ctx`.
164
165     Returns the path to a successfully found and read configuration file, None
166     otherwise.
167     """
168     assert not isinstance(value, (int, bool)), "Invalid parameter type passed"
169     if not value:
170         root = find_project_root(ctx.params.get("src", ()))
171         path = root / "pyproject.toml"
172         if path.is_file():
173             value = str(path)
174         else:
175             return None
176
177     try:
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)
182
183     if not config:
184         return None
185
186     if ctx.default_map is None:
187         ctx.default_map = {}
188     ctx.default_map.update(  # type: ignore  # bad types in .pyi
189         {k.replace("--", "").replace("-", "_"): v for k, v in config.items()}
190     )
191     return value
192
193
194 @click.command(context_settings=dict(help_option_names=["-h", "--help"]))
195 @click.option(
196     "-l",
197     "--line-length",
198     type=int,
199     default=DEFAULT_LINE_LENGTH,
200     help="How many character per line to allow.",
201     show_default=True,
202 )
203 @click.option(
204     "--py36",
205     is_flag=True,
206     help=(
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]"
210     ),
211 )
212 @click.option(
213     "--pyi",
214     is_flag=True,
215     help=(
216         "Format all input files like typing stubs regardless of file extension "
217         "(useful when piping source on standard input)."
218     ),
219 )
220 @click.option(
221     "-S",
222     "--skip-string-normalization",
223     is_flag=True,
224     help="Don't normalize string quotes or prefixes.",
225 )
226 @click.option(
227     "--check",
228     is_flag=True,
229     help=(
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."
233     ),
234 )
235 @click.option(
236     "--diff",
237     is_flag=True,
238     help="Don't write the files back, just output a diff for each file on stdout.",
239 )
240 @click.option(
241     "--fast/--safe",
242     is_flag=True,
243     help="If --fast given, skip temporary sanity checks. [default: --safe]",
244 )
245 @click.option(
246     "--include",
247     type=str,
248     default=DEFAULT_INCLUDES,
249     help=(
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 "
254         "later."
255     ),
256     show_default=True,
257 )
258 @click.option(
259     "--exclude",
260     type=str,
261     default=DEFAULT_EXCLUDES,
262     help=(
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."
267     ),
268     show_default=True,
269 )
270 @click.option(
271     "-q",
272     "--quiet",
273     is_flag=True,
274     help=(
275         "Don't emit non-error messages to stderr. Errors are still emitted, "
276         "silence those with 2>/dev/null."
277     ),
278 )
279 @click.option(
280     "-v",
281     "--verbose",
282     is_flag=True,
283     help=(
284         "Also emit messages to stderr about files that were not changed or were "
285         "ignored due to --exclude=."
286     ),
287 )
288 @click.version_option(version=__version__)
289 @click.argument(
290     "src",
291     nargs=-1,
292     type=click.Path(
293         exists=True, file_okay=True, dir_okay=True, readable=True, allow_dash=True
294     ),
295     is_eager=True,
296 )
297 @click.option(
298     "--config",
299     type=click.Path(
300         exists=False, file_okay=True, dir_okay=False, readable=True, allow_dash=False
301     ),
302     is_eager=True,
303     callback=read_pyproject_toml,
304     help="Read configuration from PATH.",
305 )
306 @click.pass_context
307 def main(
308     ctx: click.Context,
309     line_length: int,
310     check: bool,
311     diff: bool,
312     fast: bool,
313     pyi: bool,
314     py36: bool,
315     skip_string_normalization: bool,
316     quiet: bool,
317     verbose: bool,
318     include: str,
319     exclude: str,
320     src: Tuple[str],
321     config: Optional[str],
322 ) -> None:
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
327     )
328     if config and verbose:
329         out(f"Using configuration from {config}.", bold=False, fg="blue")
330     try:
331         include_regex = re_compile_maybe_verbose(include)
332     except re.error:
333         err(f"Invalid regular expression for include given: {include!r}")
334         ctx.exit(2)
335     try:
336         exclude_regex = re_compile_maybe_verbose(exclude)
337     except re.error:
338         err(f"Invalid regular expression for exclude given: {exclude!r}")
339         ctx.exit(2)
340     report = Report(check=check, quiet=quiet, verbose=verbose)
341     root = find_project_root(src)
342     sources: Set[Path] = set()
343     for s in src:
344         p = Path(s)
345         if p.is_dir():
346             sources.update(
347                 gen_python_files_in_dir(p, root, include_regex, exclude_regex, report)
348             )
349         elif p.is_file() or s == "-":
350             # if a file was explicitly given, we don't care about its extension
351             sources.add(p)
352         else:
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 😴")
357         ctx.exit(0)
358
359     if len(sources) == 1:
360         reformat_one(
361             src=sources.pop(),
362             line_length=line_length,
363             fast=fast,
364             write_back=write_back,
365             mode=mode,
366             report=report,
367         )
368     else:
369         loop = asyncio.get_event_loop()
370         executor = ProcessPoolExecutor(max_workers=os.cpu_count())
371         try:
372             loop.run_until_complete(
373                 schedule_formatting(
374                     sources=sources,
375                     line_length=line_length,
376                     fast=fast,
377                     write_back=write_back,
378                     mode=mode,
379                     report=report,
380                     loop=loop,
381                     executor=executor,
382                 )
383             )
384         finally:
385             shutdown(loop)
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)
391
392
393 def reformat_one(
394     src: Path,
395     line_length: int,
396     fast: bool,
397     write_back: WriteBack,
398     mode: FileMode,
399     report: "Report",
400 ) -> None:
401     """Reformat a single file under `src` without spawning child processes.
402
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`.
406     """
407     try:
408         changed = Changed.NO
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
412             ):
413                 changed = Changed.YES
414         else:
415             cache: Cache = {}
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(
422                 src,
423                 line_length=line_length,
424                 fast=fast,
425                 write_back=write_back,
426                 mode=mode,
427             ):
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))
434
435
436 async def schedule_formatting(
437     sources: Set[Path],
438     line_length: int,
439     fast: bool,
440     write_back: WriteBack,
441     mode: FileMode,
442     report: "Report",
443     loop: BaseEventLoop,
444     executor: Executor,
445 ) -> None:
446     """Run formatting of `sources` in parallel using the provided `executor`.
447
448     (Use ProcessPoolExecutors for actual parallelism.)
449
450     `line_length`, `write_back`, `fast`, and `pyi` options are passed to
451     :func:`format_file_in_place`.
452     """
453     cache: Cache = {}
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)
459     cancelled = []
460     formatted = []
461     if sources:
462         lock = None
463         if write_back == WriteBack.DIFF:
464             # For diff output, we need locks to ensure we don't interleave output
465             # from different processes.
466             manager = Manager()
467             lock = manager.Lock()
468         tasks = {
469             loop.run_in_executor(
470                 executor,
471                 format_file_in_place,
472                 src,
473                 line_length,
474                 fast,
475                 write_back,
476                 mode,
477                 lock,
478             ): src
479             for src in sorted(sources)
480         }
481         pending: Iterable[asyncio.Task] = tasks.keys()
482         try:
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
487             pass
488         while pending:
489             done, _ = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
490             for task in done:
491                 src = tasks.pop(task)
492                 if task.cancelled():
493                     cancelled.append(task)
494                 elif task.exception():
495                     report.failed(src, str(task.exception()))
496                 else:
497                     formatted.append(src)
498                     report.done(src, Changed.YES if task.result() else Changed.NO)
499     if cancelled:
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)
503
504
505 def format_file_in_place(
506     src: Path,
507     line_length: int,
508     fast: bool,
509     write_back: WriteBack = WriteBack.NO,
510     mode: FileMode = FileMode.AUTO_DETECT,
511     lock: Any = None,  # multiprocessing.Manager().Lock() is some crazy proxy
512 ) -> bool:
513     """Format file under `src` path. Return True if changed.
514
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`.
517     """
518     if src.suffix == ".pyi":
519         mode |= FileMode.PYI
520
521     then = datetime.utcfromtimestamp(src.stat().st_mtime)
522     with open(src, "rb") as buf:
523         src_contents, encoding, newline = decode_bytes(buf.read())
524     try:
525         dst_contents = format_file_contents(
526             src_contents, line_length=line_length, fast=fast, mode=mode
527         )
528     except NothingChanged:
529         return False
530
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)
539         if lock:
540             lock.acquire()
541         try:
542             f = io.TextIOWrapper(
543                 sys.stdout.buffer,
544                 encoding=encoding,
545                 newline=newline,
546                 write_through=True,
547             )
548             f.write(diff_contents)
549             f.detach()
550         finally:
551             if lock:
552                 lock.release()
553     return True
554
555
556 def format_stdin_to_stdout(
557     line_length: int,
558     fast: bool,
559     write_back: WriteBack = WriteBack.NO,
560     mode: FileMode = FileMode.AUTO_DETECT,
561 ) -> bool:
562     """Format file on stdin. Return True if changed.
563
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`.
567     """
568     then = datetime.utcnow()
569     src, encoding, newline = decode_bytes(sys.stdin.buffer.read())
570     dst = src
571     try:
572         dst = format_file_contents(src, line_length=line_length, fast=fast, mode=mode)
573         return True
574
575     except NothingChanged:
576         return False
577
578     finally:
579         f = io.TextIOWrapper(
580             sys.stdout.buffer, encoding=encoding, newline=newline, write_through=True
581         )
582         if write_back == WriteBack.YES:
583             f.write(dst)
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))
589         f.detach()
590
591
592 def format_file_contents(
593     src_contents: str,
594     *,
595     line_length: int,
596     fast: bool,
597     mode: FileMode = FileMode.AUTO_DETECT,
598 ) -> FileContent:
599     """Reformat contents a file and return new contents.
600
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`.
604     """
605     if src_contents.strip() == "":
606         raise NothingChanged
607
608     dst_contents = format_str(src_contents, line_length=line_length, mode=mode)
609     if src_contents == dst_contents:
610         raise NothingChanged
611
612     if not fast:
613         assert_equivalent(src_contents, dst_contents)
614         assert_stable(src_contents, dst_contents, line_length=line_length, mode=mode)
615     return dst_contents
616
617
618 def format_str(
619     src_contents: str, line_length: int, *, mode: FileMode = FileMode.AUTO_DETECT
620 ) -> FileContent:
621     """Reformat a string and return new contents.
622
623     `line_length` determines how many characters per line are allowed.
624     """
625     src_node = lib2to3_parse(src_contents)
626     dst_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     normalize_fmt_off(src_node)
632     lines = LineGenerator(
633         remove_u_prefix=py36 or "unicode_literals" in future_imports,
634         is_pyi=is_pyi,
635         normalize_strings=normalize_strings,
636     )
637     elt = EmptyLineTracker(is_pyi=is_pyi)
638     empty_line = Line()
639     after = 0
640     for current_line in lines.visit(src_node):
641         for _ in range(after):
642             dst_contents += str(empty_line)
643         before, after = elt.maybe_empty_lines(current_line)
644         for _ in range(before):
645             dst_contents += str(empty_line)
646         for line in split_line(current_line, line_length=line_length, py36=py36):
647             dst_contents += str(line)
648     return dst_contents
649
650
651 def decode_bytes(src: bytes) -> Tuple[FileContent, Encoding, NewLine]:
652     """Return a tuple of (decoded_contents, encoding, newline).
653
654     `newline` is either CRLF or LF but `decoded_contents` is decoded with
655     universal newlines (i.e. only contains LF).
656     """
657     srcbuf = io.BytesIO(src)
658     encoding, lines = tokenize.detect_encoding(srcbuf.readline)
659     if not lines:
660         return "", encoding, "\n"
661
662     newline = "\r\n" if b"\r\n" == lines[0][-2:] else "\n"
663     srcbuf.seek(0)
664     with io.TextIOWrapper(srcbuf, encoding) as tiow:
665         return tiow.read(), encoding, newline
666
667
668 GRAMMARS = [
669     pygram.python_grammar_no_print_statement_no_exec_statement,
670     pygram.python_grammar_no_print_statement,
671     pygram.python_grammar,
672 ]
673
674
675 def lib2to3_parse(src_txt: str) -> Node:
676     """Given a string with source, return the lib2to3 Node."""
677     grammar = pygram.python_grammar_no_print_statement
678     if src_txt[-1:] != "\n":
679         src_txt += "\n"
680     for grammar in GRAMMARS:
681         drv = driver.Driver(grammar, pytree.convert)
682         try:
683             result = drv.parse_string(src_txt, True)
684             break
685
686         except ParseError as pe:
687             lineno, column = pe.context[1]
688             lines = src_txt.splitlines()
689             try:
690                 faulty_line = lines[lineno - 1]
691             except IndexError:
692                 faulty_line = "<line number missing in source>"
693             exc = ValueError(f"Cannot parse: {lineno}:{column}: {faulty_line}")
694     else:
695         raise exc from None
696
697     if isinstance(result, Leaf):
698         result = Node(syms.file_input, [result])
699     return result
700
701
702 def lib2to3_unparse(node: Node) -> str:
703     """Given a lib2to3 node, return its string representation."""
704     code = str(node)
705     return code
706
707
708 T = TypeVar("T")
709
710
711 class Visitor(Generic[T]):
712     """Basic lib2to3 visitor that yields things of type `T` on `visit()`."""
713
714     def visit(self, node: LN) -> Iterator[T]:
715         """Main method to visit `node` and its children.
716
717         It tries to find a `visit_*()` method for the given `node.type`, like
718         `visit_simple_stmt` for Node objects or `visit_INDENT` for Leaf objects.
719         If no dedicated `visit_*()` method is found, chooses `visit_default()`
720         instead.
721
722         Then yields objects of type `T` from the selected visitor.
723         """
724         if node.type < 256:
725             name = token.tok_name[node.type]
726         else:
727             name = type_repr(node.type)
728         yield from getattr(self, f"visit_{name}", self.visit_default)(node)
729
730     def visit_default(self, node: LN) -> Iterator[T]:
731         """Default `visit_*()` implementation. Recurses to children of `node`."""
732         if isinstance(node, Node):
733             for child in node.children:
734                 yield from self.visit(child)
735
736
737 @dataclass
738 class DebugVisitor(Visitor[T]):
739     tree_depth: int = 0
740
741     def visit_default(self, node: LN) -> Iterator[T]:
742         indent = " " * (2 * self.tree_depth)
743         if isinstance(node, Node):
744             _type = type_repr(node.type)
745             out(f"{indent}{_type}", fg="yellow")
746             self.tree_depth += 1
747             for child in node.children:
748                 yield from self.visit(child)
749
750             self.tree_depth -= 1
751             out(f"{indent}/{_type}", fg="yellow", bold=False)
752         else:
753             _type = token.tok_name.get(node.type, str(node.type))
754             out(f"{indent}{_type}", fg="blue", nl=False)
755             if node.prefix:
756                 # We don't have to handle prefixes for `Node` objects since
757                 # that delegates to the first child anyway.
758                 out(f" {node.prefix!r}", fg="green", bold=False, nl=False)
759             out(f" {node.value!r}", fg="blue", bold=False)
760
761     @classmethod
762     def show(cls, code: str) -> None:
763         """Pretty-print the lib2to3 AST of a given string of `code`.
764
765         Convenience method for debugging.
766         """
767         v: DebugVisitor[None] = DebugVisitor()
768         list(v.visit(lib2to3_parse(code)))
769
770
771 KEYWORDS = set(keyword.kwlist)
772 WHITESPACE = {token.DEDENT, token.INDENT, token.NEWLINE}
773 FLOW_CONTROL = {"return", "raise", "break", "continue"}
774 STATEMENT = {
775     syms.if_stmt,
776     syms.while_stmt,
777     syms.for_stmt,
778     syms.try_stmt,
779     syms.except_clause,
780     syms.with_stmt,
781     syms.funcdef,
782     syms.classdef,
783 }
784 STANDALONE_COMMENT = 153
785 token.tok_name[STANDALONE_COMMENT] = "STANDALONE_COMMENT"
786 LOGIC_OPERATORS = {"and", "or"}
787 COMPARATORS = {
788     token.LESS,
789     token.GREATER,
790     token.EQEQUAL,
791     token.NOTEQUAL,
792     token.LESSEQUAL,
793     token.GREATEREQUAL,
794 }
795 MATH_OPERATORS = {
796     token.VBAR,
797     token.CIRCUMFLEX,
798     token.AMPER,
799     token.LEFTSHIFT,
800     token.RIGHTSHIFT,
801     token.PLUS,
802     token.MINUS,
803     token.STAR,
804     token.SLASH,
805     token.DOUBLESLASH,
806     token.PERCENT,
807     token.AT,
808     token.TILDE,
809     token.DOUBLESTAR,
810 }
811 STARS = {token.STAR, token.DOUBLESTAR}
812 VARARGS_PARENTS = {
813     syms.arglist,
814     syms.argument,  # double star in arglist
815     syms.trailer,  # single argument to call
816     syms.typedargslist,
817     syms.varargslist,  # lambdas
818 }
819 UNPACKING_PARENTS = {
820     syms.atom,  # single element of a list or set literal
821     syms.dictsetmaker,
822     syms.listmaker,
823     syms.testlist_gexp,
824     syms.testlist_star_expr,
825 }
826 SURROUNDED_BY_BRACKETS = {
827     syms.typedargslist,
828     syms.arglist,
829     syms.subscriptlist,
830     syms.vfplist,
831     syms.import_as_names,
832     syms.yield_expr,
833     syms.testlist_gexp,
834     syms.testlist_star_expr,
835     syms.listmaker,
836     syms.dictsetmaker,
837 }
838 TEST_DESCENDANTS = {
839     syms.test,
840     syms.lambdef,
841     syms.or_test,
842     syms.and_test,
843     syms.not_test,
844     syms.comparison,
845     syms.star_expr,
846     syms.expr,
847     syms.xor_expr,
848     syms.and_expr,
849     syms.shift_expr,
850     syms.arith_expr,
851     syms.trailer,
852     syms.term,
853     syms.power,
854 }
855 ASSIGNMENTS = {
856     "=",
857     "+=",
858     "-=",
859     "*=",
860     "@=",
861     "/=",
862     "%=",
863     "&=",
864     "|=",
865     "^=",
866     "<<=",
867     ">>=",
868     "**=",
869     "//=",
870 }
871 COMPREHENSION_PRIORITY = 20
872 COMMA_PRIORITY = 18
873 TERNARY_PRIORITY = 16
874 LOGIC_PRIORITY = 14
875 STRING_PRIORITY = 12
876 COMPARATOR_PRIORITY = 10
877 MATH_PRIORITIES = {
878     token.VBAR: 9,
879     token.CIRCUMFLEX: 8,
880     token.AMPER: 7,
881     token.LEFTSHIFT: 6,
882     token.RIGHTSHIFT: 6,
883     token.PLUS: 5,
884     token.MINUS: 5,
885     token.STAR: 4,
886     token.SLASH: 4,
887     token.DOUBLESLASH: 4,
888     token.PERCENT: 4,
889     token.AT: 4,
890     token.TILDE: 3,
891     token.DOUBLESTAR: 2,
892 }
893 DOT_PRIORITY = 1
894
895
896 @dataclass
897 class BracketTracker:
898     """Keeps track of brackets on a line."""
899
900     depth: int = 0
901     bracket_match: Dict[Tuple[Depth, NodeType], Leaf] = Factory(dict)
902     delimiters: Dict[LeafID, Priority] = Factory(dict)
903     previous: Optional[Leaf] = None
904     _for_loop_variable: int = 0
905     _lambda_arguments: int = 0
906
907     def mark(self, leaf: Leaf) -> None:
908         """Mark `leaf` with bracket-related metadata. Keep track of delimiters.
909
910         All leaves receive an int `bracket_depth` field that stores how deep
911         within brackets a given leaf is. 0 means there are no enclosing brackets
912         that started on this line.
913
914         If a leaf is itself a closing bracket, it receives an `opening_bracket`
915         field that it forms a pair with. This is a one-directional link to
916         avoid reference cycles.
917
918         If a leaf is a delimiter (a token on which Black can split the line if
919         needed) and it's on depth 0, its `id()` is stored in the tracker's
920         `delimiters` field.
921         """
922         if leaf.type == token.COMMENT:
923             return
924
925         self.maybe_decrement_after_for_loop_variable(leaf)
926         self.maybe_decrement_after_lambda_arguments(leaf)
927         if leaf.type in CLOSING_BRACKETS:
928             self.depth -= 1
929             opening_bracket = self.bracket_match.pop((self.depth, leaf.type))
930             leaf.opening_bracket = opening_bracket
931         leaf.bracket_depth = self.depth
932         if self.depth == 0:
933             delim = is_split_before_delimiter(leaf, self.previous)
934             if delim and self.previous is not None:
935                 self.delimiters[id(self.previous)] = delim
936             else:
937                 delim = is_split_after_delimiter(leaf, self.previous)
938                 if delim:
939                     self.delimiters[id(leaf)] = delim
940         if leaf.type in OPENING_BRACKETS:
941             self.bracket_match[self.depth, BRACKET[leaf.type]] = leaf
942             self.depth += 1
943         self.previous = leaf
944         self.maybe_increment_lambda_arguments(leaf)
945         self.maybe_increment_for_loop_variable(leaf)
946
947     def any_open_brackets(self) -> bool:
948         """Return True if there is an yet unmatched open bracket on the line."""
949         return bool(self.bracket_match)
950
951     def max_delimiter_priority(self, exclude: Iterable[LeafID] = ()) -> int:
952         """Return the highest priority of a delimiter found on the line.
953
954         Values are consistent with what `is_split_*_delimiter()` return.
955         Raises ValueError on no delimiters.
956         """
957         return max(v for k, v in self.delimiters.items() if k not in exclude)
958
959     def delimiter_count_with_priority(self, priority: int = 0) -> int:
960         """Return the number of delimiters with the given `priority`.
961
962         If no `priority` is passed, defaults to max priority on the line.
963         """
964         if not self.delimiters:
965             return 0
966
967         priority = priority or self.max_delimiter_priority()
968         return sum(1 for p in self.delimiters.values() if p == priority)
969
970     def maybe_increment_for_loop_variable(self, leaf: Leaf) -> bool:
971         """In a for loop, or comprehension, the variables are often unpacks.
972
973         To avoid splitting on the comma in this situation, increase the depth of
974         tokens between `for` and `in`.
975         """
976         if leaf.type == token.NAME and leaf.value == "for":
977             self.depth += 1
978             self._for_loop_variable += 1
979             return True
980
981         return False
982
983     def maybe_decrement_after_for_loop_variable(self, leaf: Leaf) -> bool:
984         """See `maybe_increment_for_loop_variable` above for explanation."""
985         if self._for_loop_variable and leaf.type == token.NAME and leaf.value == "in":
986             self.depth -= 1
987             self._for_loop_variable -= 1
988             return True
989
990         return False
991
992     def maybe_increment_lambda_arguments(self, leaf: Leaf) -> bool:
993         """In a lambda expression, there might be more than one argument.
994
995         To avoid splitting on the comma in this situation, increase the depth of
996         tokens between `lambda` and `:`.
997         """
998         if leaf.type == token.NAME and leaf.value == "lambda":
999             self.depth += 1
1000             self._lambda_arguments += 1
1001             return True
1002
1003         return False
1004
1005     def maybe_decrement_after_lambda_arguments(self, leaf: Leaf) -> bool:
1006         """See `maybe_increment_lambda_arguments` above for explanation."""
1007         if self._lambda_arguments and leaf.type == token.COLON:
1008             self.depth -= 1
1009             self._lambda_arguments -= 1
1010             return True
1011
1012         return False
1013
1014     def get_open_lsqb(self) -> Optional[Leaf]:
1015         """Return the most recent opening square bracket (if any)."""
1016         return self.bracket_match.get((self.depth - 1, token.RSQB))
1017
1018
1019 @dataclass
1020 class Line:
1021     """Holds leaves and comments. Can be printed with `str(line)`."""
1022
1023     depth: int = 0
1024     leaves: List[Leaf] = Factory(list)
1025     comments: List[Tuple[Index, Leaf]] = Factory(list)
1026     bracket_tracker: BracketTracker = Factory(BracketTracker)
1027     inside_brackets: bool = False
1028     should_explode: bool = False
1029
1030     def append(self, leaf: Leaf, preformatted: bool = False) -> None:
1031         """Add a new `leaf` to the end of the line.
1032
1033         Unless `preformatted` is True, the `leaf` will receive a new consistent
1034         whitespace prefix and metadata applied by :class:`BracketTracker`.
1035         Trailing commas are maybe removed, unpacked for loop variables are
1036         demoted from being delimiters.
1037
1038         Inline comments are put aside.
1039         """
1040         has_value = leaf.type in BRACKETS or bool(leaf.value.strip())
1041         if not has_value:
1042             return
1043
1044         if token.COLON == leaf.type and self.is_class_paren_empty:
1045             del self.leaves[-2:]
1046         if self.leaves and not preformatted:
1047             # Note: at this point leaf.prefix should be empty except for
1048             # imports, for which we only preserve newlines.
1049             leaf.prefix += whitespace(
1050                 leaf, complex_subscript=self.is_complex_subscript(leaf)
1051             )
1052         if self.inside_brackets or not preformatted:
1053             self.bracket_tracker.mark(leaf)
1054             self.maybe_remove_trailing_comma(leaf)
1055         if not self.append_comment(leaf):
1056             self.leaves.append(leaf)
1057
1058     def append_safe(self, leaf: Leaf, preformatted: bool = False) -> None:
1059         """Like :func:`append()` but disallow invalid standalone comment structure.
1060
1061         Raises ValueError when any `leaf` is appended after a standalone comment
1062         or when a standalone comment is not the first leaf on the line.
1063         """
1064         if self.bracket_tracker.depth == 0:
1065             if self.is_comment:
1066                 raise ValueError("cannot append to standalone comments")
1067
1068             if self.leaves and leaf.type == STANDALONE_COMMENT:
1069                 raise ValueError(
1070                     "cannot append standalone comments to a populated line"
1071                 )
1072
1073         self.append(leaf, preformatted=preformatted)
1074
1075     @property
1076     def is_comment(self) -> bool:
1077         """Is this line a standalone comment?"""
1078         return len(self.leaves) == 1 and self.leaves[0].type == STANDALONE_COMMENT
1079
1080     @property
1081     def is_decorator(self) -> bool:
1082         """Is this line a decorator?"""
1083         return bool(self) and self.leaves[0].type == token.AT
1084
1085     @property
1086     def is_import(self) -> bool:
1087         """Is this an import line?"""
1088         return bool(self) and is_import(self.leaves[0])
1089
1090     @property
1091     def is_class(self) -> bool:
1092         """Is this line a class definition?"""
1093         return (
1094             bool(self)
1095             and self.leaves[0].type == token.NAME
1096             and self.leaves[0].value == "class"
1097         )
1098
1099     @property
1100     def is_stub_class(self) -> bool:
1101         """Is this line a class definition with a body consisting only of "..."?"""
1102         return self.is_class and self.leaves[-3:] == [
1103             Leaf(token.DOT, ".") for _ in range(3)
1104         ]
1105
1106     @property
1107     def is_def(self) -> bool:
1108         """Is this a function definition? (Also returns True for async defs.)"""
1109         try:
1110             first_leaf = self.leaves[0]
1111         except IndexError:
1112             return False
1113
1114         try:
1115             second_leaf: Optional[Leaf] = self.leaves[1]
1116         except IndexError:
1117             second_leaf = None
1118         return (first_leaf.type == token.NAME and first_leaf.value == "def") or (
1119             first_leaf.type == token.ASYNC
1120             and second_leaf is not None
1121             and second_leaf.type == token.NAME
1122             and second_leaf.value == "def"
1123         )
1124
1125     @property
1126     def is_class_paren_empty(self) -> bool:
1127         """Is this a class with no base classes but using parentheses?
1128
1129         Those are unnecessary and should be removed.
1130         """
1131         return (
1132             bool(self)
1133             and len(self.leaves) == 4
1134             and self.is_class
1135             and self.leaves[2].type == token.LPAR
1136             and self.leaves[2].value == "("
1137             and self.leaves[3].type == token.RPAR
1138             and self.leaves[3].value == ")"
1139         )
1140
1141     @property
1142     def is_triple_quoted_string(self) -> bool:
1143         """Is the line a triple quoted string?"""
1144         return (
1145             bool(self)
1146             and self.leaves[0].type == token.STRING
1147             and self.leaves[0].value.startswith(('"""', "'''"))
1148         )
1149
1150     def contains_standalone_comments(self, depth_limit: int = sys.maxsize) -> bool:
1151         """If so, needs to be split before emitting."""
1152         for leaf in self.leaves:
1153             if leaf.type == STANDALONE_COMMENT:
1154                 if leaf.bracket_depth <= depth_limit:
1155                     return True
1156
1157         return False
1158
1159     def contains_multiline_strings(self) -> bool:
1160         for leaf in self.leaves:
1161             if is_multiline_string(leaf):
1162                 return True
1163
1164         return False
1165
1166     def maybe_remove_trailing_comma(self, closing: Leaf) -> bool:
1167         """Remove trailing comma if there is one and it's safe."""
1168         if not (
1169             self.leaves
1170             and self.leaves[-1].type == token.COMMA
1171             and closing.type in CLOSING_BRACKETS
1172         ):
1173             return False
1174
1175         if closing.type == token.RBRACE:
1176             self.remove_trailing_comma()
1177             return True
1178
1179         if closing.type == token.RSQB:
1180             comma = self.leaves[-1]
1181             if comma.parent and comma.parent.type == syms.listmaker:
1182                 self.remove_trailing_comma()
1183                 return True
1184
1185         # For parens let's check if it's safe to remove the comma.
1186         # Imports are always safe.
1187         if self.is_import:
1188             self.remove_trailing_comma()
1189             return True
1190
1191         # Otheriwsse, if the trailing one is the only one, we might mistakenly
1192         # change a tuple into a different type by removing the comma.
1193         depth = closing.bracket_depth + 1
1194         commas = 0
1195         opening = closing.opening_bracket
1196         for _opening_index, leaf in enumerate(self.leaves):
1197             if leaf is opening:
1198                 break
1199
1200         else:
1201             return False
1202
1203         for leaf in self.leaves[_opening_index + 1 :]:
1204             if leaf is closing:
1205                 break
1206
1207             bracket_depth = leaf.bracket_depth
1208             if bracket_depth == depth and leaf.type == token.COMMA:
1209                 commas += 1
1210                 if leaf.parent and leaf.parent.type == syms.arglist:
1211                     commas += 1
1212                     break
1213
1214         if commas > 1:
1215             self.remove_trailing_comma()
1216             return True
1217
1218         return False
1219
1220     def append_comment(self, comment: Leaf) -> bool:
1221         """Add an inline or standalone comment to the line."""
1222         if (
1223             comment.type == STANDALONE_COMMENT
1224             and self.bracket_tracker.any_open_brackets()
1225         ):
1226             comment.prefix = ""
1227             return False
1228
1229         if comment.type != token.COMMENT:
1230             return False
1231
1232         after = len(self.leaves) - 1
1233         if after == -1:
1234             comment.type = STANDALONE_COMMENT
1235             comment.prefix = ""
1236             return False
1237
1238         else:
1239             self.comments.append((after, comment))
1240             return True
1241
1242     def comments_after(self, leaf: Leaf, _index: int = -1) -> Iterator[Leaf]:
1243         """Generate comments that should appear directly after `leaf`.
1244
1245         Provide a non-negative leaf `_index` to speed up the function.
1246         """
1247         if not self.comments:
1248             return
1249
1250         if _index == -1:
1251             for _index, _leaf in enumerate(self.leaves):
1252                 if leaf is _leaf:
1253                     break
1254
1255             else:
1256                 return
1257
1258         for index, comment_after in self.comments:
1259             if _index == index:
1260                 yield comment_after
1261
1262     def remove_trailing_comma(self) -> None:
1263         """Remove the trailing comma and moves the comments attached to it."""
1264         comma_index = len(self.leaves) - 1
1265         for i in range(len(self.comments)):
1266             comment_index, comment = self.comments[i]
1267             if comment_index == comma_index:
1268                 self.comments[i] = (comma_index - 1, comment)
1269         self.leaves.pop()
1270
1271     def is_complex_subscript(self, leaf: Leaf) -> bool:
1272         """Return True iff `leaf` is part of a slice with non-trivial exprs."""
1273         open_lsqb = self.bracket_tracker.get_open_lsqb()
1274         if open_lsqb is None:
1275             return False
1276
1277         subscript_start = open_lsqb.next_sibling
1278
1279         if isinstance(subscript_start, Node):
1280             if subscript_start.type == syms.listmaker:
1281                 return False
1282
1283             if subscript_start.type == syms.subscriptlist:
1284                 subscript_start = child_towards(subscript_start, leaf)
1285         return subscript_start is not None and any(
1286             n.type in TEST_DESCENDANTS for n in subscript_start.pre_order()
1287         )
1288
1289     def __str__(self) -> str:
1290         """Render the line."""
1291         if not self:
1292             return "\n"
1293
1294         indent = "    " * self.depth
1295         leaves = iter(self.leaves)
1296         first = next(leaves)
1297         res = f"{first.prefix}{indent}{first.value}"
1298         for leaf in leaves:
1299             res += str(leaf)
1300         for _, comment in self.comments:
1301             res += str(comment)
1302         return res + "\n"
1303
1304     def __bool__(self) -> bool:
1305         """Return True if the line has leaves or comments."""
1306         return bool(self.leaves or self.comments)
1307
1308
1309 class UnformattedLines(Line):
1310     """Just like :class:`Line` but stores lines which aren't reformatted."""
1311
1312     def append(self, leaf: Leaf, preformatted: bool = True) -> None:
1313         """Just add a new `leaf` to the end of the lines.
1314
1315         The `preformatted` argument is ignored.
1316
1317         Keeps track of indentation `depth`, which is useful when the user
1318         says `# fmt: on`. Otherwise, doesn't do anything with the `leaf`.
1319         """
1320         try:
1321             list(generate_comments(leaf))
1322         except FormatOn as f_on:
1323             self.leaves.append(f_on.leaf_from_consumed(leaf))
1324             raise
1325
1326         self.leaves.append(leaf)
1327         if leaf.type == token.INDENT:
1328             self.depth += 1
1329         elif leaf.type == token.DEDENT:
1330             self.depth -= 1
1331
1332     def __str__(self) -> str:
1333         """Render unformatted lines from leaves which were added with `append()`.
1334
1335         `depth` is not used for indentation in this case.
1336         """
1337         if not self:
1338             return "\n"
1339
1340         res = ""
1341         for leaf in self.leaves:
1342             res += str(leaf)
1343         return res
1344
1345     def append_comment(self, comment: Leaf) -> bool:
1346         """Not implemented in this class. Raises `NotImplementedError`."""
1347         raise NotImplementedError("Unformatted lines don't store comments separately.")
1348
1349     def maybe_remove_trailing_comma(self, closing: Leaf) -> bool:
1350         """Does nothing and returns False."""
1351         return False
1352
1353     def maybe_increment_for_loop_variable(self, leaf: Leaf) -> bool:
1354         """Does nothing and returns False."""
1355         return False
1356
1357
1358 @dataclass
1359 class EmptyLineTracker:
1360     """Provides a stateful method that returns the number of potential extra
1361     empty lines needed before and after the currently processed line.
1362
1363     Note: this tracker works on lines that haven't been split yet.  It assumes
1364     the prefix of the first leaf consists of optional newlines.  Those newlines
1365     are consumed by `maybe_empty_lines()` and included in the computation.
1366     """
1367
1368     is_pyi: bool = False
1369     previous_line: Optional[Line] = None
1370     previous_after: int = 0
1371     previous_defs: List[int] = Factory(list)
1372
1373     def maybe_empty_lines(self, current_line: Line) -> Tuple[int, int]:
1374         """Return the number of extra empty lines before and after the `current_line`.
1375
1376         This is for separating `def`, `async def` and `class` with extra empty
1377         lines (two on module-level).
1378         """
1379         if isinstance(current_line, UnformattedLines):
1380             return 0, 0
1381
1382         before, after = self._maybe_empty_lines(current_line)
1383         before -= self.previous_after
1384         self.previous_after = after
1385         self.previous_line = current_line
1386         return before, after
1387
1388     def _maybe_empty_lines(self, current_line: Line) -> Tuple[int, int]:
1389         max_allowed = 1
1390         if current_line.depth == 0:
1391             max_allowed = 1 if self.is_pyi else 2
1392         if current_line.leaves:
1393             # Consume the first leaf's extra newlines.
1394             first_leaf = current_line.leaves[0]
1395             before = first_leaf.prefix.count("\n")
1396             before = min(before, max_allowed)
1397             first_leaf.prefix = ""
1398         else:
1399             before = 0
1400         depth = current_line.depth
1401         while self.previous_defs and self.previous_defs[-1] >= depth:
1402             self.previous_defs.pop()
1403             if self.is_pyi:
1404                 before = 0 if depth else 1
1405             else:
1406                 before = 1 if depth else 2
1407         if current_line.is_decorator or current_line.is_def or current_line.is_class:
1408             return self._maybe_empty_lines_for_class_or_def(current_line, before)
1409
1410         if (
1411             self.previous_line
1412             and self.previous_line.is_import
1413             and not current_line.is_import
1414             and depth == self.previous_line.depth
1415         ):
1416             return (before or 1), 0
1417
1418         if (
1419             self.previous_line
1420             and self.previous_line.is_class
1421             and current_line.is_triple_quoted_string
1422         ):
1423             return before, 1
1424
1425         return before, 0
1426
1427     def _maybe_empty_lines_for_class_or_def(
1428         self, current_line: Line, before: int
1429     ) -> Tuple[int, int]:
1430         if not current_line.is_decorator:
1431             self.previous_defs.append(current_line.depth)
1432         if self.previous_line is None:
1433             # Don't insert empty lines before the first line in the file.
1434             return 0, 0
1435
1436         if self.previous_line.is_decorator:
1437             return 0, 0
1438
1439         if self.previous_line.depth < current_line.depth and (
1440             self.previous_line.is_class or self.previous_line.is_def
1441         ):
1442             return 0, 0
1443
1444         if (
1445             self.previous_line.is_comment
1446             and self.previous_line.depth == current_line.depth
1447             and before == 0
1448         ):
1449             return 0, 0
1450
1451         if self.is_pyi:
1452             if self.previous_line.depth > current_line.depth:
1453                 newlines = 1
1454             elif current_line.is_class or self.previous_line.is_class:
1455                 if current_line.is_stub_class and self.previous_line.is_stub_class:
1456                     # No blank line between classes with an emty body
1457                     newlines = 0
1458                 else:
1459                     newlines = 1
1460             elif current_line.is_def and not self.previous_line.is_def:
1461                 # Blank line between a block of functions and a block of non-functions
1462                 newlines = 1
1463             else:
1464                 newlines = 0
1465         else:
1466             newlines = 2
1467         if current_line.depth and newlines:
1468             newlines -= 1
1469         return newlines, 0
1470
1471
1472 @dataclass
1473 class LineGenerator(Visitor[Line]):
1474     """Generates reformatted Line objects.  Empty lines are not emitted.
1475
1476     Note: destroys the tree it's visiting by mutating prefixes of its leaves
1477     in ways that will no longer stringify to valid Python code on the tree.
1478     """
1479
1480     is_pyi: bool = False
1481     normalize_strings: bool = True
1482     current_line: Line = Factory(Line)
1483     remove_u_prefix: bool = False
1484
1485     def line(self, indent: int = 0, type: Type[Line] = Line) -> Iterator[Line]:
1486         """Generate a line.
1487
1488         If the line is empty, only emit if it makes sense.
1489         If the line is too long, split it first and then generate.
1490
1491         If any lines were generated, set up a new current_line.
1492         """
1493         if not self.current_line:
1494             if self.current_line.__class__ == type:
1495                 self.current_line.depth += indent
1496             else:
1497                 self.current_line = type(depth=self.current_line.depth + indent)
1498             return  # Line is empty, don't emit. Creating a new one unnecessary.
1499
1500         complete_line = self.current_line
1501         self.current_line = type(depth=complete_line.depth + indent)
1502         yield complete_line
1503
1504     def visit(self, node: LN) -> Iterator[Line]:
1505         """Main method to visit `node` and its children.
1506
1507         Yields :class:`Line` objects.
1508         """
1509         if isinstance(self.current_line, UnformattedLines):
1510             # File contained `# fmt: off`
1511             yield from self.visit_unformatted(node)
1512
1513         else:
1514             yield from super().visit(node)
1515
1516     def visit_default(self, node: LN) -> Iterator[Line]:
1517         """Default `visit_*()` implementation. Recurses to children of `node`."""
1518         if isinstance(node, Leaf):
1519             any_open_brackets = self.current_line.bracket_tracker.any_open_brackets()
1520             try:
1521                 for comment in generate_comments(node):
1522                     if any_open_brackets:
1523                         # any comment within brackets is subject to splitting
1524                         self.current_line.append(comment)
1525                     elif comment.type == token.COMMENT:
1526                         # regular trailing comment
1527                         self.current_line.append(comment)
1528                         yield from self.line()
1529
1530                     else:
1531                         # regular standalone comment
1532                         yield from self.line()
1533
1534                         self.current_line.append(comment)
1535                         yield from self.line()
1536
1537             except FormatOff as f_off:
1538                 f_off.trim_prefix(node)
1539                 yield from self.line(type=UnformattedLines)
1540                 yield from self.visit(node)
1541
1542             except FormatOn as f_on:
1543                 # This only happens here if somebody says "fmt: on" multiple
1544                 # times in a row.
1545                 f_on.trim_prefix(node)
1546                 yield from self.visit_default(node)
1547
1548             else:
1549                 normalize_prefix(node, inside_brackets=any_open_brackets)
1550                 if self.normalize_strings and node.type == token.STRING:
1551                     normalize_string_prefix(node, remove_u_prefix=self.remove_u_prefix)
1552                     normalize_string_quotes(node)
1553                 if node.type not in WHITESPACE:
1554                     self.current_line.append(node)
1555         yield from super().visit_default(node)
1556
1557     def visit_INDENT(self, node: Node) -> Iterator[Line]:
1558         """Increase indentation level, maybe yield a line."""
1559         # In blib2to3 INDENT never holds comments.
1560         yield from self.line(+1)
1561         yield from self.visit_default(node)
1562
1563     def visit_DEDENT(self, node: Node) -> Iterator[Line]:
1564         """Decrease indentation level, maybe yield a line."""
1565         # The current line might still wait for trailing comments.  At DEDENT time
1566         # there won't be any (they would be prefixes on the preceding NEWLINE).
1567         # Emit the line then.
1568         yield from self.line()
1569
1570         # While DEDENT has no value, its prefix may contain standalone comments
1571         # that belong to the current indentation level.  Get 'em.
1572         yield from self.visit_default(node)
1573
1574         # Finally, emit the dedent.
1575         yield from self.line(-1)
1576
1577     def visit_stmt(
1578         self, node: Node, keywords: Set[str], parens: Set[str]
1579     ) -> Iterator[Line]:
1580         """Visit a statement.
1581
1582         This implementation is shared for `if`, `while`, `for`, `try`, `except`,
1583         `def`, `with`, `class`, `assert` and assignments.
1584
1585         The relevant Python language `keywords` for a given statement will be
1586         NAME leaves within it. This methods puts those on a separate line.
1587
1588         `parens` holds a set of string leaf values immediately after which
1589         invisible parens should be put.
1590         """
1591         normalize_invisible_parens(node, parens_after=parens)
1592         for child in node.children:
1593             if child.type == token.NAME and child.value in keywords:  # type: ignore
1594                 yield from self.line()
1595
1596             yield from self.visit(child)
1597
1598     def visit_suite(self, node: Node) -> Iterator[Line]:
1599         """Visit a suite."""
1600         if self.is_pyi and is_stub_suite(node):
1601             yield from self.visit(node.children[2])
1602         else:
1603             yield from self.visit_default(node)
1604
1605     def visit_simple_stmt(self, node: Node) -> Iterator[Line]:
1606         """Visit a statement without nested statements."""
1607         is_suite_like = node.parent and node.parent.type in STATEMENT
1608         if is_suite_like:
1609             if self.is_pyi and is_stub_body(node):
1610                 yield from self.visit_default(node)
1611             else:
1612                 yield from self.line(+1)
1613                 yield from self.visit_default(node)
1614                 yield from self.line(-1)
1615
1616         else:
1617             if not self.is_pyi or not node.parent or not is_stub_suite(node.parent):
1618                 yield from self.line()
1619             yield from self.visit_default(node)
1620
1621     def visit_async_stmt(self, node: Node) -> Iterator[Line]:
1622         """Visit `async def`, `async for`, `async with`."""
1623         yield from self.line()
1624
1625         children = iter(node.children)
1626         for child in children:
1627             yield from self.visit(child)
1628
1629             if child.type == token.ASYNC:
1630                 break
1631
1632         internal_stmt = next(children)
1633         for child in internal_stmt.children:
1634             yield from self.visit(child)
1635
1636     def visit_decorators(self, node: Node) -> Iterator[Line]:
1637         """Visit decorators."""
1638         for child in node.children:
1639             yield from self.line()
1640             yield from self.visit(child)
1641
1642     def visit_SEMI(self, leaf: Leaf) -> Iterator[Line]:
1643         """Remove a semicolon and put the other statement on a separate line."""
1644         yield from self.line()
1645
1646     def visit_ENDMARKER(self, leaf: Leaf) -> Iterator[Line]:
1647         """End of file. Process outstanding comments and end with a newline."""
1648         yield from self.visit_default(leaf)
1649         yield from self.line()
1650
1651     def visit_unformatted(self, node: LN) -> Iterator[Line]:
1652         """Used when file contained a `# fmt: off`."""
1653         if isinstance(node, Node):
1654             for child in node.children:
1655                 yield from self.visit(child)
1656
1657         else:
1658             try:
1659                 self.current_line.append(node)
1660             except FormatOn as f_on:
1661                 f_on.trim_prefix(node)
1662                 yield from self.line()
1663                 yield from self.visit(node)
1664
1665             if node.type == token.ENDMARKER:
1666                 # somebody decided not to put a final `# fmt: on`
1667                 yield from self.line()
1668
1669     def __attrs_post_init__(self) -> None:
1670         """You are in a twisty little maze of passages."""
1671         v = self.visit_stmt
1672         Ø: Set[str] = set()
1673         self.visit_assert_stmt = partial(v, keywords={"assert"}, parens={"assert", ","})
1674         self.visit_if_stmt = partial(
1675             v, keywords={"if", "else", "elif"}, parens={"if", "elif"}
1676         )
1677         self.visit_while_stmt = partial(v, keywords={"while", "else"}, parens={"while"})
1678         self.visit_for_stmt = partial(v, keywords={"for", "else"}, parens={"for", "in"})
1679         self.visit_try_stmt = partial(
1680             v, keywords={"try", "except", "else", "finally"}, parens=Ø
1681         )
1682         self.visit_except_clause = partial(v, keywords={"except"}, parens=Ø)
1683         self.visit_with_stmt = partial(v, keywords={"with"}, parens=Ø)
1684         self.visit_funcdef = partial(v, keywords={"def"}, parens=Ø)
1685         self.visit_classdef = partial(v, keywords={"class"}, parens=Ø)
1686         self.visit_expr_stmt = partial(v, keywords=Ø, parens=ASSIGNMENTS)
1687         self.visit_return_stmt = partial(v, keywords={"return"}, parens={"return"})
1688         self.visit_import_from = partial(v, keywords=Ø, parens={"import"})
1689         self.visit_async_funcdef = self.visit_async_stmt
1690         self.visit_decorated = self.visit_decorators
1691
1692
1693 IMPLICIT_TUPLE = {syms.testlist, syms.testlist_star_expr, syms.exprlist}
1694 BRACKET = {token.LPAR: token.RPAR, token.LSQB: token.RSQB, token.LBRACE: token.RBRACE}
1695 OPENING_BRACKETS = set(BRACKET.keys())
1696 CLOSING_BRACKETS = set(BRACKET.values())
1697 BRACKETS = OPENING_BRACKETS | CLOSING_BRACKETS
1698 ALWAYS_NO_SPACE = CLOSING_BRACKETS | {token.COMMA, STANDALONE_COMMENT}
1699
1700
1701 def whitespace(leaf: Leaf, *, complex_subscript: bool) -> str:  # noqa C901
1702     """Return whitespace prefix if needed for the given `leaf`.
1703
1704     `complex_subscript` signals whether the given leaf is part of a subscription
1705     which has non-trivial arguments, like arithmetic expressions or function calls.
1706     """
1707     NO = ""
1708     SPACE = " "
1709     DOUBLESPACE = "  "
1710     t = leaf.type
1711     p = leaf.parent
1712     v = leaf.value
1713     if t in ALWAYS_NO_SPACE:
1714         return NO
1715
1716     if t == token.COMMENT:
1717         return DOUBLESPACE
1718
1719     assert p is not None, f"INTERNAL ERROR: hand-made leaf without parent: {leaf!r}"
1720     if t == token.COLON and p.type not in {
1721         syms.subscript,
1722         syms.subscriptlist,
1723         syms.sliceop,
1724     }:
1725         return NO
1726
1727     prev = leaf.prev_sibling
1728     if not prev:
1729         prevp = preceding_leaf(p)
1730         if not prevp or prevp.type in OPENING_BRACKETS:
1731             return NO
1732
1733         if t == token.COLON:
1734             if prevp.type == token.COLON:
1735                 return NO
1736
1737             elif prevp.type != token.COMMA and not complex_subscript:
1738                 return NO
1739
1740             return SPACE
1741
1742         if prevp.type == token.EQUAL:
1743             if prevp.parent:
1744                 if prevp.parent.type in {
1745                     syms.arglist,
1746                     syms.argument,
1747                     syms.parameters,
1748                     syms.varargslist,
1749                 }:
1750                     return NO
1751
1752                 elif prevp.parent.type == syms.typedargslist:
1753                     # A bit hacky: if the equal sign has whitespace, it means we
1754                     # previously found it's a typed argument.  So, we're using
1755                     # that, too.
1756                     return prevp.prefix
1757
1758         elif prevp.type in STARS:
1759             if is_vararg(prevp, within=VARARGS_PARENTS | UNPACKING_PARENTS):
1760                 return NO
1761
1762         elif prevp.type == token.COLON:
1763             if prevp.parent and prevp.parent.type in {syms.subscript, syms.sliceop}:
1764                 return SPACE if complex_subscript else NO
1765
1766         elif (
1767             prevp.parent
1768             and prevp.parent.type == syms.factor
1769             and prevp.type in MATH_OPERATORS
1770         ):
1771             return NO
1772
1773         elif (
1774             prevp.type == token.RIGHTSHIFT
1775             and prevp.parent
1776             and prevp.parent.type == syms.shift_expr
1777             and prevp.prev_sibling
1778             and prevp.prev_sibling.type == token.NAME
1779             and prevp.prev_sibling.value == "print"  # type: ignore
1780         ):
1781             # Python 2 print chevron
1782             return NO
1783
1784     elif prev.type in OPENING_BRACKETS:
1785         return NO
1786
1787     if p.type in {syms.parameters, syms.arglist}:
1788         # untyped function signatures or calls
1789         if not prev or prev.type != token.COMMA:
1790             return NO
1791
1792     elif p.type == syms.varargslist:
1793         # lambdas
1794         if prev and prev.type != token.COMMA:
1795             return NO
1796
1797     elif p.type == syms.typedargslist:
1798         # typed function signatures
1799         if not prev:
1800             return NO
1801
1802         if t == token.EQUAL:
1803             if prev.type != syms.tname:
1804                 return NO
1805
1806         elif prev.type == token.EQUAL:
1807             # A bit hacky: if the equal sign has whitespace, it means we
1808             # previously found it's a typed argument.  So, we're using that, too.
1809             return prev.prefix
1810
1811         elif prev.type != token.COMMA:
1812             return NO
1813
1814     elif p.type == syms.tname:
1815         # type names
1816         if not prev:
1817             prevp = preceding_leaf(p)
1818             if not prevp or prevp.type != token.COMMA:
1819                 return NO
1820
1821     elif p.type == syms.trailer:
1822         # attributes and calls
1823         if t == token.LPAR or t == token.RPAR:
1824             return NO
1825
1826         if not prev:
1827             if t == token.DOT:
1828                 prevp = preceding_leaf(p)
1829                 if not prevp or prevp.type != token.NUMBER:
1830                     return NO
1831
1832             elif t == token.LSQB:
1833                 return NO
1834
1835         elif prev.type != token.COMMA:
1836             return NO
1837
1838     elif p.type == syms.argument:
1839         # single argument
1840         if t == token.EQUAL:
1841             return NO
1842
1843         if not prev:
1844             prevp = preceding_leaf(p)
1845             if not prevp or prevp.type == token.LPAR:
1846                 return NO
1847
1848         elif prev.type in {token.EQUAL} | STARS:
1849             return NO
1850
1851     elif p.type == syms.decorator:
1852         # decorators
1853         return NO
1854
1855     elif p.type == syms.dotted_name:
1856         if prev:
1857             return NO
1858
1859         prevp = preceding_leaf(p)
1860         if not prevp or prevp.type == token.AT or prevp.type == token.DOT:
1861             return NO
1862
1863     elif p.type == syms.classdef:
1864         if t == token.LPAR:
1865             return NO
1866
1867         if prev and prev.type == token.LPAR:
1868             return NO
1869
1870     elif p.type in {syms.subscript, syms.sliceop}:
1871         # indexing
1872         if not prev:
1873             assert p.parent is not None, "subscripts are always parented"
1874             if p.parent.type == syms.subscriptlist:
1875                 return SPACE
1876
1877             return NO
1878
1879         elif not complex_subscript:
1880             return NO
1881
1882     elif p.type == syms.atom:
1883         if prev and t == token.DOT:
1884             # dots, but not the first one.
1885             return NO
1886
1887     elif p.type == syms.dictsetmaker:
1888         # dict unpacking
1889         if prev and prev.type == token.DOUBLESTAR:
1890             return NO
1891
1892     elif p.type in {syms.factor, syms.star_expr}:
1893         # unary ops
1894         if not prev:
1895             prevp = preceding_leaf(p)
1896             if not prevp or prevp.type in OPENING_BRACKETS:
1897                 return NO
1898
1899             prevp_parent = prevp.parent
1900             assert prevp_parent is not None
1901             if prevp.type == token.COLON and prevp_parent.type in {
1902                 syms.subscript,
1903                 syms.sliceop,
1904             }:
1905                 return NO
1906
1907             elif prevp.type == token.EQUAL and prevp_parent.type == syms.argument:
1908                 return NO
1909
1910         elif t in {token.NAME, token.NUMBER, token.STRING}:
1911             return NO
1912
1913     elif p.type == syms.import_from:
1914         if t == token.DOT:
1915             if prev and prev.type == token.DOT:
1916                 return NO
1917
1918         elif t == token.NAME:
1919             if v == "import":
1920                 return SPACE
1921
1922             if prev and prev.type == token.DOT:
1923                 return NO
1924
1925     elif p.type == syms.sliceop:
1926         return NO
1927
1928     return SPACE
1929
1930
1931 def preceding_leaf(node: Optional[LN]) -> Optional[Leaf]:
1932     """Return the first leaf that precedes `node`, if any."""
1933     while node:
1934         res = node.prev_sibling
1935         if res:
1936             if isinstance(res, Leaf):
1937                 return res
1938
1939             try:
1940                 return list(res.leaves())[-1]
1941
1942             except IndexError:
1943                 return None
1944
1945         node = node.parent
1946     return None
1947
1948
1949 def child_towards(ancestor: Node, descendant: LN) -> Optional[LN]:
1950     """Return the child of `ancestor` that contains `descendant`."""
1951     node: Optional[LN] = descendant
1952     while node and node.parent != ancestor:
1953         node = node.parent
1954     return node
1955
1956
1957 def container_of(leaf: Leaf) -> LN:
1958     """Return `leaf` or one of its ancestors that is the topmost container of it.
1959
1960     By "container" we mean a node where `leaf` is the very first child.
1961     """
1962     same_prefix = leaf.prefix
1963     container: LN = leaf
1964     while container:
1965         parent = container.parent
1966         if parent is None:
1967             break
1968
1969         if parent.children[0].prefix != same_prefix:
1970             break
1971
1972         if parent.type in SURROUNDED_BY_BRACKETS:
1973             break
1974
1975         container = parent
1976     return container
1977
1978
1979 def is_split_after_delimiter(leaf: Leaf, previous: Leaf = None) -> int:
1980     """Return the priority of the `leaf` delimiter, given a line break after it.
1981
1982     The delimiter priorities returned here are from those delimiters that would
1983     cause a line break after themselves.
1984
1985     Higher numbers are higher priority.
1986     """
1987     if leaf.type == token.COMMA:
1988         return COMMA_PRIORITY
1989
1990     return 0
1991
1992
1993 def is_split_before_delimiter(leaf: Leaf, previous: Leaf = None) -> int:
1994     """Return the priority of the `leaf` delimiter, given a line before after it.
1995
1996     The delimiter priorities returned here are from those delimiters that would
1997     cause a line break before themselves.
1998
1999     Higher numbers are higher priority.
2000     """
2001     if is_vararg(leaf, within=VARARGS_PARENTS | UNPACKING_PARENTS):
2002         # * and ** might also be MATH_OPERATORS but in this case they are not.
2003         # Don't treat them as a delimiter.
2004         return 0
2005
2006     if (
2007         leaf.type == token.DOT
2008         and leaf.parent
2009         and leaf.parent.type not in {syms.import_from, syms.dotted_name}
2010         and (previous is None or previous.type in CLOSING_BRACKETS)
2011     ):
2012         return DOT_PRIORITY
2013
2014     if (
2015         leaf.type in MATH_OPERATORS
2016         and leaf.parent
2017         and leaf.parent.type not in {syms.factor, syms.star_expr}
2018     ):
2019         return MATH_PRIORITIES[leaf.type]
2020
2021     if leaf.type in COMPARATORS:
2022         return COMPARATOR_PRIORITY
2023
2024     if (
2025         leaf.type == token.STRING
2026         and previous is not None
2027         and previous.type == token.STRING
2028     ):
2029         return STRING_PRIORITY
2030
2031     if leaf.type != token.NAME:
2032         return 0
2033
2034     if (
2035         leaf.value == "for"
2036         and leaf.parent
2037         and leaf.parent.type in {syms.comp_for, syms.old_comp_for}
2038     ):
2039         return COMPREHENSION_PRIORITY
2040
2041     if (
2042         leaf.value == "if"
2043         and leaf.parent
2044         and leaf.parent.type in {syms.comp_if, syms.old_comp_if}
2045     ):
2046         return COMPREHENSION_PRIORITY
2047
2048     if leaf.value in {"if", "else"} and leaf.parent and leaf.parent.type == syms.test:
2049         return TERNARY_PRIORITY
2050
2051     if leaf.value == "is":
2052         return COMPARATOR_PRIORITY
2053
2054     if (
2055         leaf.value == "in"
2056         and leaf.parent
2057         and leaf.parent.type in {syms.comp_op, syms.comparison}
2058         and not (
2059             previous is not None
2060             and previous.type == token.NAME
2061             and previous.value == "not"
2062         )
2063     ):
2064         return COMPARATOR_PRIORITY
2065
2066     if (
2067         leaf.value == "not"
2068         and leaf.parent
2069         and leaf.parent.type == syms.comp_op
2070         and not (
2071             previous is not None
2072             and previous.type == token.NAME
2073             and previous.value == "is"
2074         )
2075     ):
2076         return COMPARATOR_PRIORITY
2077
2078     if leaf.value in LOGIC_OPERATORS and leaf.parent:
2079         return LOGIC_PRIORITY
2080
2081     return 0
2082
2083
2084 FMT_OFF = {"# fmt: off", "# fmt:off", "# yapf: disable"}
2085 FMT_ON = {"# fmt: on", "# fmt:on", "# yapf: enable"}
2086
2087
2088 def generate_comments(leaf: LN) -> Iterator[Leaf]:
2089     """Clean the prefix of the `leaf` and generate comments from it, if any.
2090
2091     Comments in lib2to3 are shoved into the whitespace prefix.  This happens
2092     in `pgen2/driver.py:Driver.parse_tokens()`.  This was a brilliant implementation
2093     move because it does away with modifying the grammar to include all the
2094     possible places in which comments can be placed.
2095
2096     The sad consequence for us though is that comments don't "belong" anywhere.
2097     This is why this function generates simple parentless Leaf objects for
2098     comments.  We simply don't know what the correct parent should be.
2099
2100     No matter though, we can live without this.  We really only need to
2101     differentiate between inline and standalone comments.  The latter don't
2102     share the line with any code.
2103
2104     Inline comments are emitted as regular token.COMMENT leaves.  Standalone
2105     are emitted with a fake STANDALONE_COMMENT token identifier.
2106     """
2107     for pc in list_comments(leaf.prefix, is_endmarker=leaf.type == token.ENDMARKER):
2108         yield Leaf(pc.type, pc.value, prefix="\n" * pc.newlines)
2109         if pc.value in FMT_ON:
2110             raise FormatOn(pc.consumed)
2111
2112         if pc.value in FMT_OFF:
2113             if pc.type == STANDALONE_COMMENT:
2114                 raise FormatOff(pc.consumed)
2115
2116             prev = preceding_leaf(leaf)
2117             if not prev or prev.type in WHITESPACE:  # standalone comment in disguise
2118                 raise FormatOff(pc.consumed)
2119
2120
2121 @dataclass
2122 class ProtoComment:
2123     type: int  # token.COMMENT or STANDALONE_COMMENT
2124     value: str  # content of the comment
2125     newlines: int  # how many newlines before the comment
2126     consumed: int  # how many characters of the original leaf's prefix did we consume
2127
2128
2129 @lru_cache(maxsize=4096)
2130 def list_comments(prefix: str, *, is_endmarker: bool) -> List[ProtoComment]:
2131     result: List[ProtoComment] = []
2132     if not prefix or "#" not in prefix:
2133         return result
2134
2135     consumed = 0
2136     nlines = 0
2137     for index, line in enumerate(prefix.split("\n")):
2138         consumed += len(line) + 1  # adding the length of the split '\n'
2139         line = line.lstrip()
2140         if not line:
2141             nlines += 1
2142         if not line.startswith("#"):
2143             continue
2144
2145         if index == 0 and not is_endmarker:
2146             comment_type = token.COMMENT  # simple trailing comment
2147         else:
2148             comment_type = STANDALONE_COMMENT
2149         comment = make_comment(line)
2150         result.append(
2151             ProtoComment(
2152                 type=comment_type, value=comment, newlines=nlines, consumed=consumed
2153             )
2154         )
2155         nlines = 0
2156     return result
2157
2158
2159 def make_comment(content: str) -> str:
2160     """Return a consistently formatted comment from the given `content` string.
2161
2162     All comments (except for "##", "#!", "#:") should have a single space between
2163     the hash sign and the content.
2164
2165     If `content` didn't start with a hash sign, one is provided.
2166     """
2167     content = content.rstrip()
2168     if not content:
2169         return "#"
2170
2171     if content[0] == "#":
2172         content = content[1:]
2173     if content and content[0] not in " !:#":
2174         content = " " + content
2175     return "#" + content
2176
2177
2178 def split_line(
2179     line: Line, line_length: int, inner: bool = False, py36: bool = False
2180 ) -> Iterator[Line]:
2181     """Split a `line` into potentially many lines.
2182
2183     They should fit in the allotted `line_length` but might not be able to.
2184     `inner` signifies that there were a pair of brackets somewhere around the
2185     current `line`, possibly transitively. This means we can fallback to splitting
2186     by delimiters if the LHS/RHS don't yield any results.
2187
2188     If `py36` is True, splitting may generate syntax that is only compatible
2189     with Python 3.6 and later.
2190     """
2191     if isinstance(line, UnformattedLines) or line.is_comment:
2192         yield line
2193         return
2194
2195     line_str = str(line).strip("\n")
2196     if not line.should_explode and is_line_short_enough(
2197         line, line_length=line_length, line_str=line_str
2198     ):
2199         yield line
2200         return
2201
2202     split_funcs: List[SplitFunc]
2203     if line.is_def:
2204         split_funcs = [left_hand_split]
2205     else:
2206
2207         def rhs(line: Line, py36: bool = False) -> Iterator[Line]:
2208             for omit in generate_trailers_to_omit(line, line_length):
2209                 lines = list(right_hand_split(line, line_length, py36, omit=omit))
2210                 if is_line_short_enough(lines[0], line_length=line_length):
2211                     yield from lines
2212                     return
2213
2214             # All splits failed, best effort split with no omits.
2215             # This mostly happens to multiline strings that are by definition
2216             # reported as not fitting a single line.
2217             yield from right_hand_split(line, py36)
2218
2219         if line.inside_brackets:
2220             split_funcs = [delimiter_split, standalone_comment_split, rhs]
2221         else:
2222             split_funcs = [rhs]
2223     for split_func in split_funcs:
2224         # We are accumulating lines in `result` because we might want to abort
2225         # mission and return the original line in the end, or attempt a different
2226         # split altogether.
2227         result: List[Line] = []
2228         try:
2229             for l in split_func(line, py36):
2230                 if str(l).strip("\n") == line_str:
2231                     raise CannotSplit("Split function returned an unchanged result")
2232
2233                 result.extend(
2234                     split_line(l, line_length=line_length, inner=True, py36=py36)
2235                 )
2236         except CannotSplit as cs:
2237             continue
2238
2239         else:
2240             yield from result
2241             break
2242
2243     else:
2244         yield line
2245
2246
2247 def left_hand_split(line: Line, py36: bool = False) -> Iterator[Line]:
2248     """Split line into many lines, starting with the first matching bracket pair.
2249
2250     Note: this usually looks weird, only use this for function definitions.
2251     Prefer RHS otherwise.  This is why this function is not symmetrical with
2252     :func:`right_hand_split` which also handles optional parentheses.
2253     """
2254     head = Line(depth=line.depth)
2255     body = Line(depth=line.depth + 1, inside_brackets=True)
2256     tail = Line(depth=line.depth)
2257     tail_leaves: List[Leaf] = []
2258     body_leaves: List[Leaf] = []
2259     head_leaves: List[Leaf] = []
2260     current_leaves = head_leaves
2261     matching_bracket = None
2262     for leaf in line.leaves:
2263         if (
2264             current_leaves is body_leaves
2265             and leaf.type in CLOSING_BRACKETS
2266             and leaf.opening_bracket is matching_bracket
2267         ):
2268             current_leaves = tail_leaves if body_leaves else head_leaves
2269         current_leaves.append(leaf)
2270         if current_leaves is head_leaves:
2271             if leaf.type in OPENING_BRACKETS:
2272                 matching_bracket = leaf
2273                 current_leaves = body_leaves
2274     # Since body is a new indent level, remove spurious leading whitespace.
2275     if body_leaves:
2276         normalize_prefix(body_leaves[0], inside_brackets=True)
2277     # Build the new lines.
2278     for result, leaves in (head, head_leaves), (body, body_leaves), (tail, tail_leaves):
2279         for leaf in leaves:
2280             result.append(leaf, preformatted=True)
2281             for comment_after in line.comments_after(leaf):
2282                 result.append(comment_after, preformatted=True)
2283     bracket_split_succeeded_or_raise(head, body, tail)
2284     for result in (head, body, tail):
2285         if result:
2286             yield result
2287
2288
2289 def right_hand_split(
2290     line: Line, line_length: int, py36: bool = False, omit: Collection[LeafID] = ()
2291 ) -> Iterator[Line]:
2292     """Split line into many lines, starting with the last matching bracket pair.
2293
2294     If the split was by optional parentheses, attempt splitting without them, too.
2295     `omit` is a collection of closing bracket IDs that shouldn't be considered for
2296     this split.
2297
2298     Note: running this function modifies `bracket_depth` on the leaves of `line`.
2299     """
2300     head = Line(depth=line.depth)
2301     body = Line(depth=line.depth + 1, inside_brackets=True)
2302     tail = Line(depth=line.depth)
2303     tail_leaves: List[Leaf] = []
2304     body_leaves: List[Leaf] = []
2305     head_leaves: List[Leaf] = []
2306     current_leaves = tail_leaves
2307     opening_bracket = None
2308     closing_bracket = None
2309     for leaf in reversed(line.leaves):
2310         if current_leaves is body_leaves:
2311             if leaf is opening_bracket:
2312                 current_leaves = head_leaves if body_leaves else tail_leaves
2313         current_leaves.append(leaf)
2314         if current_leaves is tail_leaves:
2315             if leaf.type in CLOSING_BRACKETS and id(leaf) not in omit:
2316                 opening_bracket = leaf.opening_bracket
2317                 closing_bracket = leaf
2318                 current_leaves = body_leaves
2319     tail_leaves.reverse()
2320     body_leaves.reverse()
2321     head_leaves.reverse()
2322     # Since body is a new indent level, remove spurious leading whitespace.
2323     if body_leaves:
2324         normalize_prefix(body_leaves[0], inside_brackets=True)
2325     if not head_leaves:
2326         # No `head` means the split failed. Either `tail` has all content or
2327         # the matching `opening_bracket` wasn't available on `line` anymore.
2328         raise CannotSplit("No brackets found")
2329
2330     # Build the new lines.
2331     for result, leaves in (head, head_leaves), (body, body_leaves), (tail, tail_leaves):
2332         for leaf in leaves:
2333             result.append(leaf, preformatted=True)
2334             for comment_after in line.comments_after(leaf):
2335                 result.append(comment_after, preformatted=True)
2336     assert opening_bracket and closing_bracket
2337     body.should_explode = should_explode(body, opening_bracket)
2338     bracket_split_succeeded_or_raise(head, body, tail)
2339     if (
2340         # the body shouldn't be exploded
2341         not body.should_explode
2342         # the opening bracket is an optional paren
2343         and opening_bracket.type == token.LPAR
2344         and not opening_bracket.value
2345         # the closing bracket is an optional paren
2346         and closing_bracket.type == token.RPAR
2347         and not closing_bracket.value
2348         # it's not an import (optional parens are the only thing we can split on
2349         # in this case; attempting a split without them is a waste of time)
2350         and not line.is_import
2351         # there are no standalone comments in the body
2352         and not body.contains_standalone_comments(0)
2353         # and we can actually remove the parens
2354         and can_omit_invisible_parens(body, line_length)
2355     ):
2356         omit = {id(closing_bracket), *omit}
2357         try:
2358             yield from right_hand_split(line, line_length, py36=py36, omit=omit)
2359             return
2360
2361         except CannotSplit:
2362             if not (
2363                 can_be_split(body)
2364                 or is_line_short_enough(body, line_length=line_length)
2365             ):
2366                 raise CannotSplit(
2367                     "Splitting failed, body is still too long and can't be split."
2368                 )
2369
2370             elif head.contains_multiline_strings() or tail.contains_multiline_strings():
2371                 raise CannotSplit(
2372                     "The current optional pair of parentheses is bound to fail to "
2373                     "satisfy the splitting algorithm because the head or the tail "
2374                     "contains multiline strings which by definition never fit one "
2375                     "line."
2376                 )
2377
2378     ensure_visible(opening_bracket)
2379     ensure_visible(closing_bracket)
2380     for result in (head, body, tail):
2381         if result:
2382             yield result
2383
2384
2385 def bracket_split_succeeded_or_raise(head: Line, body: Line, tail: Line) -> None:
2386     """Raise :exc:`CannotSplit` if the last left- or right-hand split failed.
2387
2388     Do nothing otherwise.
2389
2390     A left- or right-hand split is based on a pair of brackets. Content before
2391     (and including) the opening bracket is left on one line, content inside the
2392     brackets is put on a separate line, and finally content starting with and
2393     following the closing bracket is put on a separate line.
2394
2395     Those are called `head`, `body`, and `tail`, respectively. If the split
2396     produced the same line (all content in `head`) or ended up with an empty `body`
2397     and the `tail` is just the closing bracket, then it's considered failed.
2398     """
2399     tail_len = len(str(tail).strip())
2400     if not body:
2401         if tail_len == 0:
2402             raise CannotSplit("Splitting brackets produced the same line")
2403
2404         elif tail_len < 3:
2405             raise CannotSplit(
2406                 f"Splitting brackets on an empty body to save "
2407                 f"{tail_len} characters is not worth it"
2408             )
2409
2410
2411 def dont_increase_indentation(split_func: SplitFunc) -> SplitFunc:
2412     """Normalize prefix of the first leaf in every line returned by `split_func`.
2413
2414     This is a decorator over relevant split functions.
2415     """
2416
2417     @wraps(split_func)
2418     def split_wrapper(line: Line, py36: bool = False) -> Iterator[Line]:
2419         for l in split_func(line, py36):
2420             normalize_prefix(l.leaves[0], inside_brackets=True)
2421             yield l
2422
2423     return split_wrapper
2424
2425
2426 @dont_increase_indentation
2427 def delimiter_split(line: Line, py36: bool = False) -> Iterator[Line]:
2428     """Split according to delimiters of the highest priority.
2429
2430     If `py36` is True, the split will add trailing commas also in function
2431     signatures that contain `*` and `**`.
2432     """
2433     try:
2434         last_leaf = line.leaves[-1]
2435     except IndexError:
2436         raise CannotSplit("Line empty")
2437
2438     bt = line.bracket_tracker
2439     try:
2440         delimiter_priority = bt.max_delimiter_priority(exclude={id(last_leaf)})
2441     except ValueError:
2442         raise CannotSplit("No delimiters found")
2443
2444     if delimiter_priority == DOT_PRIORITY:
2445         if bt.delimiter_count_with_priority(delimiter_priority) == 1:
2446             raise CannotSplit("Splitting a single attribute from its owner looks wrong")
2447
2448     current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
2449     lowest_depth = sys.maxsize
2450     trailing_comma_safe = True
2451
2452     def append_to_line(leaf: Leaf) -> Iterator[Line]:
2453         """Append `leaf` to current line or to new line if appending impossible."""
2454         nonlocal current_line
2455         try:
2456             current_line.append_safe(leaf, preformatted=True)
2457         except ValueError as ve:
2458             yield current_line
2459
2460             current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
2461             current_line.append(leaf)
2462
2463     for index, leaf in enumerate(line.leaves):
2464         yield from append_to_line(leaf)
2465
2466         for comment_after in line.comments_after(leaf, index):
2467             yield from append_to_line(comment_after)
2468
2469         lowest_depth = min(lowest_depth, leaf.bracket_depth)
2470         if leaf.bracket_depth == lowest_depth and is_vararg(
2471             leaf, within=VARARGS_PARENTS
2472         ):
2473             trailing_comma_safe = trailing_comma_safe and py36
2474         leaf_priority = bt.delimiters.get(id(leaf))
2475         if leaf_priority == delimiter_priority:
2476             yield current_line
2477
2478             current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
2479     if current_line:
2480         if (
2481             trailing_comma_safe
2482             and delimiter_priority == COMMA_PRIORITY
2483             and current_line.leaves[-1].type != token.COMMA
2484             and current_line.leaves[-1].type != STANDALONE_COMMENT
2485         ):
2486             current_line.append(Leaf(token.COMMA, ","))
2487         yield current_line
2488
2489
2490 @dont_increase_indentation
2491 def standalone_comment_split(line: Line, py36: bool = False) -> Iterator[Line]:
2492     """Split standalone comments from the rest of the line."""
2493     if not line.contains_standalone_comments(0):
2494         raise CannotSplit("Line does not have any standalone comments")
2495
2496     current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
2497
2498     def append_to_line(leaf: Leaf) -> Iterator[Line]:
2499         """Append `leaf` to current line or to new line if appending impossible."""
2500         nonlocal current_line
2501         try:
2502             current_line.append_safe(leaf, preformatted=True)
2503         except ValueError as ve:
2504             yield current_line
2505
2506             current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
2507             current_line.append(leaf)
2508
2509     for index, leaf in enumerate(line.leaves):
2510         yield from append_to_line(leaf)
2511
2512         for comment_after in line.comments_after(leaf, index):
2513             yield from append_to_line(comment_after)
2514
2515     if current_line:
2516         yield current_line
2517
2518
2519 def is_import(leaf: Leaf) -> bool:
2520     """Return True if the given leaf starts an import statement."""
2521     p = leaf.parent
2522     t = leaf.type
2523     v = leaf.value
2524     return bool(
2525         t == token.NAME
2526         and (
2527             (v == "import" and p and p.type == syms.import_name)
2528             or (v == "from" and p and p.type == syms.import_from)
2529         )
2530     )
2531
2532
2533 def normalize_prefix(leaf: Leaf, *, inside_brackets: bool) -> None:
2534     """Leave existing extra newlines if not `inside_brackets`. Remove everything
2535     else.
2536
2537     Note: don't use backslashes for formatting or you'll lose your voting rights.
2538     """
2539     if not inside_brackets:
2540         spl = leaf.prefix.split("#")
2541         if "\\" not in spl[0]:
2542             nl_count = spl[-1].count("\n")
2543             if len(spl) > 1:
2544                 nl_count -= 1
2545             leaf.prefix = "\n" * nl_count
2546             return
2547
2548     leaf.prefix = ""
2549
2550
2551 def normalize_string_prefix(leaf: Leaf, remove_u_prefix: bool = False) -> None:
2552     """Make all string prefixes lowercase.
2553
2554     If remove_u_prefix is given, also removes any u prefix from the string.
2555
2556     Note: Mutates its argument.
2557     """
2558     match = re.match(r"^([furbFURB]*)(.*)$", leaf.value, re.DOTALL)
2559     assert match is not None, f"failed to match string {leaf.value!r}"
2560     orig_prefix = match.group(1)
2561     new_prefix = orig_prefix.lower()
2562     if remove_u_prefix:
2563         new_prefix = new_prefix.replace("u", "")
2564     leaf.value = f"{new_prefix}{match.group(2)}"
2565
2566
2567 def normalize_string_quotes(leaf: Leaf) -> None:
2568     """Prefer double quotes but only if it doesn't cause more escaping.
2569
2570     Adds or removes backslashes as appropriate. Doesn't parse and fix
2571     strings nested in f-strings (yet).
2572
2573     Note: Mutates its argument.
2574     """
2575     value = leaf.value.lstrip("furbFURB")
2576     if value[:3] == '"""':
2577         return
2578
2579     elif value[:3] == "'''":
2580         orig_quote = "'''"
2581         new_quote = '"""'
2582     elif value[0] == '"':
2583         orig_quote = '"'
2584         new_quote = "'"
2585     else:
2586         orig_quote = "'"
2587         new_quote = '"'
2588     first_quote_pos = leaf.value.find(orig_quote)
2589     if first_quote_pos == -1:
2590         return  # There's an internal error
2591
2592     prefix = leaf.value[:first_quote_pos]
2593     unescaped_new_quote = re.compile(rf"(([^\\]|^)(\\\\)*){new_quote}")
2594     escaped_new_quote = re.compile(rf"([^\\]|^)\\((?:\\\\)*){new_quote}")
2595     escaped_orig_quote = re.compile(rf"([^\\]|^)\\((?:\\\\)*){orig_quote}")
2596     body = leaf.value[first_quote_pos + len(orig_quote) : -len(orig_quote)]
2597     if "r" in prefix.casefold():
2598         if unescaped_new_quote.search(body):
2599             # There's at least one unescaped new_quote in this raw string
2600             # so converting is impossible
2601             return
2602
2603         # Do not introduce or remove backslashes in raw strings
2604         new_body = body
2605     else:
2606         # remove unnecessary escapes
2607         new_body = sub_twice(escaped_new_quote, rf"\1\2{new_quote}", body)
2608         if body != new_body:
2609             # Consider the string without unnecessary escapes as the original
2610             body = new_body
2611             leaf.value = f"{prefix}{orig_quote}{body}{orig_quote}"
2612         new_body = sub_twice(escaped_orig_quote, rf"\1\2{orig_quote}", new_body)
2613         new_body = sub_twice(unescaped_new_quote, rf"\1\\{new_quote}", new_body)
2614     if "f" in prefix.casefold():
2615         matches = re.findall(r"[^{]\{(.*?)\}[^}]", new_body)
2616         for m in matches:
2617             if "\\" in str(m):
2618                 # Do not introduce backslashes in interpolated expressions
2619                 return
2620     if new_quote == '"""' and new_body[-1:] == '"':
2621         # edge case:
2622         new_body = new_body[:-1] + '\\"'
2623     orig_escape_count = body.count("\\")
2624     new_escape_count = new_body.count("\\")
2625     if new_escape_count > orig_escape_count:
2626         return  # Do not introduce more escaping
2627
2628     if new_escape_count == orig_escape_count and orig_quote == '"':
2629         return  # Prefer double quotes
2630
2631     leaf.value = f"{prefix}{new_quote}{new_body}{new_quote}"
2632
2633
2634 def normalize_invisible_parens(node: Node, parens_after: Set[str]) -> None:
2635     """Make existing optional parentheses invisible or create new ones.
2636
2637     `parens_after` is a set of string leaf values immeditely after which parens
2638     should be put.
2639
2640     Standardizes on visible parentheses for single-element tuples, and keeps
2641     existing visible parentheses for other tuples and generator expressions.
2642     """
2643     for pc in list_comments(node.prefix, is_endmarker=False):
2644         if pc.value in FMT_OFF:
2645             # This `node` has a prefix with `# fmt: off`, don't mess with parens.
2646             return
2647
2648     check_lpar = False
2649     for index, child in enumerate(list(node.children)):
2650         if check_lpar:
2651             if child.type == syms.atom:
2652                 maybe_make_parens_invisible_in_atom(child)
2653             elif is_one_tuple(child):
2654                 # wrap child in visible parentheses
2655                 lpar = Leaf(token.LPAR, "(")
2656                 rpar = Leaf(token.RPAR, ")")
2657                 child.remove()
2658                 node.insert_child(index, Node(syms.atom, [lpar, child, rpar]))
2659             elif node.type == syms.import_from:
2660                 # "import from" nodes store parentheses directly as part of
2661                 # the statement
2662                 if child.type == token.LPAR:
2663                     # make parentheses invisible
2664                     child.value = ""  # type: ignore
2665                     node.children[-1].value = ""  # type: ignore
2666                 elif child.type != token.STAR:
2667                     # insert invisible parentheses
2668                     node.insert_child(index, Leaf(token.LPAR, ""))
2669                     node.append_child(Leaf(token.RPAR, ""))
2670                 break
2671
2672             elif not (isinstance(child, Leaf) and is_multiline_string(child)):
2673                 # wrap child in invisible parentheses
2674                 lpar = Leaf(token.LPAR, "")
2675                 rpar = Leaf(token.RPAR, "")
2676                 index = child.remove() or 0
2677                 node.insert_child(index, Node(syms.atom, [lpar, child, rpar]))
2678
2679         check_lpar = isinstance(child, Leaf) and child.value in parens_after
2680
2681
2682 def normalize_fmt_off(node: Node) -> None:
2683     """Allow `# fmt: off`/`# fmt: on` within bracket pairs.
2684
2685     Ignores `# fmt: off` and `# fmt: on` outside of brackets.
2686
2687     Raises :exc:`SyntaxError` if no matching `# fmt: on` is found for a `# fmt: off`
2688     given inside brackets.
2689     """
2690     try_again = True
2691     while try_again:
2692         try_again = hide_fmt_off(node)
2693
2694
2695 def hide_fmt_off(node: Node) -> bool:
2696     bt = BracketTracker()
2697     for leaf in node.leaves():
2698         bt.mark(leaf)
2699         if bt.depth == 0:
2700             continue
2701
2702         previous_consumed = 0
2703         for comment in list_comments(leaf.prefix, is_endmarker=False):
2704             if comment.value in FMT_OFF:
2705                 ignored_nodes = list(generate_ignored_nodes(leaf))
2706                 first = ignored_nodes[0]  # Can be a container node with the `leaf`.
2707                 parent = first.parent
2708                 prefix = first.prefix
2709                 first.prefix = prefix[comment.consumed :]
2710                 hidden_value = (
2711                     comment.value + "\n" + "".join(str(n) for n in ignored_nodes)
2712                 )
2713                 first_idx = None
2714                 for ignored in ignored_nodes:
2715                     index = ignored.remove()
2716                     if first_idx is None:
2717                         first_idx = index
2718                 assert parent is not None, "INTERNAL ERROR: fmt: on/off handling (1)"
2719                 assert first_idx is not None, "INTERNAL ERROR: fmt: on/off handling (2)"
2720                 parent.insert_child(
2721                     first_idx,
2722                     Leaf(
2723                         STANDALONE_COMMENT,
2724                         hidden_value,
2725                         prefix=prefix[:previous_consumed] + "\n" * comment.newlines,
2726                     ),
2727                 )
2728                 return True
2729
2730             previous_consumed += comment.consumed
2731
2732     return False
2733
2734
2735 def generate_ignored_nodes(leaf: Leaf) -> Iterator[LN]:
2736     container: Optional[LN] = container_of(leaf)
2737     while container is not None:
2738         for comment in list_comments(container.prefix, is_endmarker=False):
2739             if comment.value in FMT_ON:
2740                 return
2741
2742         yield container
2743
2744         container = container.next_sibling
2745
2746
2747 def maybe_make_parens_invisible_in_atom(node: LN) -> bool:
2748     """If it's safe, make the parens in the atom `node` invisible, recursively."""
2749     if (
2750         node.type != syms.atom
2751         or is_empty_tuple(node)
2752         or is_one_tuple(node)
2753         or is_yield(node)
2754         or max_delimiter_priority_in_atom(node) >= COMMA_PRIORITY
2755     ):
2756         return False
2757
2758     first = node.children[0]
2759     last = node.children[-1]
2760     if first.type == token.LPAR and last.type == token.RPAR:
2761         # make parentheses invisible
2762         first.value = ""  # type: ignore
2763         last.value = ""  # type: ignore
2764         if len(node.children) > 1:
2765             maybe_make_parens_invisible_in_atom(node.children[1])
2766         return True
2767
2768     return False
2769
2770
2771 def is_empty_tuple(node: LN) -> bool:
2772     """Return True if `node` holds an empty tuple."""
2773     return (
2774         node.type == syms.atom
2775         and len(node.children) == 2
2776         and node.children[0].type == token.LPAR
2777         and node.children[1].type == token.RPAR
2778     )
2779
2780
2781 def is_one_tuple(node: LN) -> bool:
2782     """Return True if `node` holds a tuple with one element, with or without parens."""
2783     if node.type == syms.atom:
2784         if len(node.children) != 3:
2785             return False
2786
2787         lpar, gexp, rpar = node.children
2788         if not (
2789             lpar.type == token.LPAR
2790             and gexp.type == syms.testlist_gexp
2791             and rpar.type == token.RPAR
2792         ):
2793             return False
2794
2795         return len(gexp.children) == 2 and gexp.children[1].type == token.COMMA
2796
2797     return (
2798         node.type in IMPLICIT_TUPLE
2799         and len(node.children) == 2
2800         and node.children[1].type == token.COMMA
2801     )
2802
2803
2804 def is_yield(node: LN) -> bool:
2805     """Return True if `node` holds a `yield` or `yield from` expression."""
2806     if node.type == syms.yield_expr:
2807         return True
2808
2809     if node.type == token.NAME and node.value == "yield":  # type: ignore
2810         return True
2811
2812     if node.type != syms.atom:
2813         return False
2814
2815     if len(node.children) != 3:
2816         return False
2817
2818     lpar, expr, rpar = node.children
2819     if lpar.type == token.LPAR and rpar.type == token.RPAR:
2820         return is_yield(expr)
2821
2822     return False
2823
2824
2825 def is_vararg(leaf: Leaf, within: Set[NodeType]) -> bool:
2826     """Return True if `leaf` is a star or double star in a vararg or kwarg.
2827
2828     If `within` includes VARARGS_PARENTS, this applies to function signatures.
2829     If `within` includes UNPACKING_PARENTS, it applies to right hand-side
2830     extended iterable unpacking (PEP 3132) and additional unpacking
2831     generalizations (PEP 448).
2832     """
2833     if leaf.type not in STARS or not leaf.parent:
2834         return False
2835
2836     p = leaf.parent
2837     if p.type == syms.star_expr:
2838         # Star expressions are also used as assignment targets in extended
2839         # iterable unpacking (PEP 3132).  See what its parent is instead.
2840         if not p.parent:
2841             return False
2842
2843         p = p.parent
2844
2845     return p.type in within
2846
2847
2848 def is_multiline_string(leaf: Leaf) -> bool:
2849     """Return True if `leaf` is a multiline string that actually spans many lines."""
2850     value = leaf.value.lstrip("furbFURB")
2851     return value[:3] in {'"""', "'''"} and "\n" in value
2852
2853
2854 def is_stub_suite(node: Node) -> bool:
2855     """Return True if `node` is a suite with a stub body."""
2856     if (
2857         len(node.children) != 4
2858         or node.children[0].type != token.NEWLINE
2859         or node.children[1].type != token.INDENT
2860         or node.children[3].type != token.DEDENT
2861     ):
2862         return False
2863
2864     return is_stub_body(node.children[2])
2865
2866
2867 def is_stub_body(node: LN) -> bool:
2868     """Return True if `node` is a simple statement containing an ellipsis."""
2869     if not isinstance(node, Node) or node.type != syms.simple_stmt:
2870         return False
2871
2872     if len(node.children) != 2:
2873         return False
2874
2875     child = node.children[0]
2876     return (
2877         child.type == syms.atom
2878         and len(child.children) == 3
2879         and all(leaf == Leaf(token.DOT, ".") for leaf in child.children)
2880     )
2881
2882
2883 def max_delimiter_priority_in_atom(node: LN) -> int:
2884     """Return maximum delimiter priority inside `node`.
2885
2886     This is specific to atoms with contents contained in a pair of parentheses.
2887     If `node` isn't an atom or there are no enclosing parentheses, returns 0.
2888     """
2889     if node.type != syms.atom:
2890         return 0
2891
2892     first = node.children[0]
2893     last = node.children[-1]
2894     if not (first.type == token.LPAR and last.type == token.RPAR):
2895         return 0
2896
2897     bt = BracketTracker()
2898     for c in node.children[1:-1]:
2899         if isinstance(c, Leaf):
2900             bt.mark(c)
2901         else:
2902             for leaf in c.leaves():
2903                 bt.mark(leaf)
2904     try:
2905         return bt.max_delimiter_priority()
2906
2907     except ValueError:
2908         return 0
2909
2910
2911 def ensure_visible(leaf: Leaf) -> None:
2912     """Make sure parentheses are visible.
2913
2914     They could be invisible as part of some statements (see
2915     :func:`normalize_invible_parens` and :func:`visit_import_from`).
2916     """
2917     if leaf.type == token.LPAR:
2918         leaf.value = "("
2919     elif leaf.type == token.RPAR:
2920         leaf.value = ")"
2921
2922
2923 def should_explode(line: Line, opening_bracket: Leaf) -> bool:
2924     """Should `line` immediately be split with `delimiter_split()` after RHS?"""
2925     if not (
2926         opening_bracket.parent
2927         and opening_bracket.parent.type in {syms.atom, syms.import_from}
2928         and opening_bracket.value in "[{("
2929     ):
2930         return False
2931
2932     try:
2933         last_leaf = line.leaves[-1]
2934         exclude = {id(last_leaf)} if last_leaf.type == token.COMMA else set()
2935         max_priority = line.bracket_tracker.max_delimiter_priority(exclude=exclude)
2936     except (IndexError, ValueError):
2937         return False
2938
2939     return max_priority == COMMA_PRIORITY
2940
2941
2942 def is_python36(node: Node) -> bool:
2943     """Return True if the current file is using Python 3.6+ features.
2944
2945     Currently looking for:
2946     - f-strings; and
2947     - trailing commas after * or ** in function signatures and calls.
2948     """
2949     for n in node.pre_order():
2950         if n.type == token.STRING:
2951             value_head = n.value[:2]  # type: ignore
2952             if value_head in {'f"', 'F"', "f'", "F'", "rf", "fr", "RF", "FR"}:
2953                 return True
2954
2955         elif (
2956             n.type in {syms.typedargslist, syms.arglist}
2957             and n.children
2958             and n.children[-1].type == token.COMMA
2959         ):
2960             for ch in n.children:
2961                 if ch.type in STARS:
2962                     return True
2963
2964                 if ch.type == syms.argument:
2965                     for argch in ch.children:
2966                         if argch.type in STARS:
2967                             return True
2968
2969     return False
2970
2971
2972 def generate_trailers_to_omit(line: Line, line_length: int) -> Iterator[Set[LeafID]]:
2973     """Generate sets of closing bracket IDs that should be omitted in a RHS.
2974
2975     Brackets can be omitted if the entire trailer up to and including
2976     a preceding closing bracket fits in one line.
2977
2978     Yielded sets are cumulative (contain results of previous yields, too).  First
2979     set is empty.
2980     """
2981
2982     omit: Set[LeafID] = set()
2983     yield omit
2984
2985     length = 4 * line.depth
2986     opening_bracket = None
2987     closing_bracket = None
2988     optional_brackets: Set[LeafID] = set()
2989     inner_brackets: Set[LeafID] = set()
2990     for index, leaf, leaf_length in enumerate_with_length(line, reversed=True):
2991         length += leaf_length
2992         if length > line_length:
2993             break
2994
2995         has_inline_comment = leaf_length > len(leaf.value) + len(leaf.prefix)
2996         if leaf.type == STANDALONE_COMMENT or has_inline_comment:
2997             break
2998
2999         optional_brackets.discard(id(leaf))
3000         if opening_bracket:
3001             if leaf is opening_bracket:
3002                 opening_bracket = None
3003             elif leaf.type in CLOSING_BRACKETS:
3004                 inner_brackets.add(id(leaf))
3005         elif leaf.type in CLOSING_BRACKETS:
3006             if not leaf.value:
3007                 optional_brackets.add(id(opening_bracket))
3008                 continue
3009
3010             if index > 0 and line.leaves[index - 1].type in OPENING_BRACKETS:
3011                 # Empty brackets would fail a split so treat them as "inner"
3012                 # brackets (e.g. only add them to the `omit` set if another
3013                 # pair of brackets was good enough.
3014                 inner_brackets.add(id(leaf))
3015                 continue
3016
3017             opening_bracket = leaf.opening_bracket
3018             if closing_bracket:
3019                 omit.add(id(closing_bracket))
3020                 omit.update(inner_brackets)
3021                 inner_brackets.clear()
3022                 yield omit
3023             closing_bracket = leaf
3024
3025
3026 def get_future_imports(node: Node) -> Set[str]:
3027     """Return a set of __future__ imports in the file."""
3028     imports = set()
3029     for child in node.children:
3030         if child.type != syms.simple_stmt:
3031             break
3032         first_child = child.children[0]
3033         if isinstance(first_child, Leaf):
3034             # Continue looking if we see a docstring; otherwise stop.
3035             if (
3036                 len(child.children) == 2
3037                 and first_child.type == token.STRING
3038                 and child.children[1].type == token.NEWLINE
3039             ):
3040                 continue
3041             else:
3042                 break
3043         elif first_child.type == syms.import_from:
3044             module_name = first_child.children[1]
3045             if not isinstance(module_name, Leaf) or module_name.value != "__future__":
3046                 break
3047             for import_from_child in first_child.children[3:]:
3048                 if isinstance(import_from_child, Leaf):
3049                     if import_from_child.type == token.NAME:
3050                         imports.add(import_from_child.value)
3051                 else:
3052                     assert import_from_child.type == syms.import_as_names
3053                     for leaf in import_from_child.children:
3054                         if isinstance(leaf, Leaf) and leaf.type == token.NAME:
3055                             imports.add(leaf.value)
3056         else:
3057             break
3058     return imports
3059
3060
3061 def gen_python_files_in_dir(
3062     path: Path,
3063     root: Path,
3064     include: Pattern[str],
3065     exclude: Pattern[str],
3066     report: "Report",
3067 ) -> Iterator[Path]:
3068     """Generate all files under `path` whose paths are not excluded by the
3069     `exclude` regex, but are included by the `include` regex.
3070
3071     Symbolic links pointing outside of the root directory are ignored.
3072
3073     `report` is where output about exclusions goes.
3074     """
3075     assert root.is_absolute(), f"INTERNAL ERROR: `root` must be absolute but is {root}"
3076     for child in path.iterdir():
3077         try:
3078             normalized_path = "/" + child.resolve().relative_to(root).as_posix()
3079         except ValueError:
3080             if child.is_symlink():
3081                 report.path_ignored(
3082                     child,
3083                     "is a symbolic link that points outside of the root directory",
3084                 )
3085                 continue
3086
3087             raise
3088
3089         if child.is_dir():
3090             normalized_path += "/"
3091         exclude_match = exclude.search(normalized_path)
3092         if exclude_match and exclude_match.group(0):
3093             report.path_ignored(child, f"matches the --exclude regular expression")
3094             continue
3095
3096         if child.is_dir():
3097             yield from gen_python_files_in_dir(child, root, include, exclude, report)
3098
3099         elif child.is_file():
3100             include_match = include.search(normalized_path)
3101             if include_match:
3102                 yield child
3103
3104
3105 @lru_cache()
3106 def find_project_root(srcs: Iterable[str]) -> Path:
3107     """Return a directory containing .git, .hg, or pyproject.toml.
3108
3109     That directory can be one of the directories passed in `srcs` or their
3110     common parent.
3111
3112     If no directory in the tree contains a marker that would specify it's the
3113     project root, the root of the file system is returned.
3114     """
3115     if not srcs:
3116         return Path("/").resolve()
3117
3118     common_base = min(Path(src).resolve() for src in srcs)
3119     if common_base.is_dir():
3120         # Append a fake file so `parents` below returns `common_base_dir`, too.
3121         common_base /= "fake-file"
3122     for directory in common_base.parents:
3123         if (directory / ".git").is_dir():
3124             return directory
3125
3126         if (directory / ".hg").is_dir():
3127             return directory
3128
3129         if (directory / "pyproject.toml").is_file():
3130             return directory
3131
3132     return directory
3133
3134
3135 @dataclass
3136 class Report:
3137     """Provides a reformatting counter. Can be rendered with `str(report)`."""
3138
3139     check: bool = False
3140     quiet: bool = False
3141     verbose: bool = False
3142     change_count: int = 0
3143     same_count: int = 0
3144     failure_count: int = 0
3145
3146     def done(self, src: Path, changed: Changed) -> None:
3147         """Increment the counter for successful reformatting. Write out a message."""
3148         if changed is Changed.YES:
3149             reformatted = "would reformat" if self.check else "reformatted"
3150             if self.verbose or not self.quiet:
3151                 out(f"{reformatted} {src}")
3152             self.change_count += 1
3153         else:
3154             if self.verbose:
3155                 if changed is Changed.NO:
3156                     msg = f"{src} already well formatted, good job."
3157                 else:
3158                     msg = f"{src} wasn't modified on disk since last run."
3159                 out(msg, bold=False)
3160             self.same_count += 1
3161
3162     def failed(self, src: Path, message: str) -> None:
3163         """Increment the counter for failed reformatting. Write out a message."""
3164         err(f"error: cannot format {src}: {message}")
3165         self.failure_count += 1
3166
3167     def path_ignored(self, path: Path, message: str) -> None:
3168         if self.verbose:
3169             out(f"{path} ignored: {message}", bold=False)
3170
3171     @property
3172     def return_code(self) -> int:
3173         """Return the exit code that the app should use.
3174
3175         This considers the current state of changed files and failures:
3176         - if there were any failures, return 123;
3177         - if any files were changed and --check is being used, return 1;
3178         - otherwise return 0.
3179         """
3180         # According to http://tldp.org/LDP/abs/html/exitcodes.html starting with
3181         # 126 we have special returncodes reserved by the shell.
3182         if self.failure_count:
3183             return 123
3184
3185         elif self.change_count and self.check:
3186             return 1
3187
3188         return 0
3189
3190     def __str__(self) -> str:
3191         """Render a color report of the current state.
3192
3193         Use `click.unstyle` to remove colors.
3194         """
3195         if self.check:
3196             reformatted = "would be reformatted"
3197             unchanged = "would be left unchanged"
3198             failed = "would fail to reformat"
3199         else:
3200             reformatted = "reformatted"
3201             unchanged = "left unchanged"
3202             failed = "failed to reformat"
3203         report = []
3204         if self.change_count:
3205             s = "s" if self.change_count > 1 else ""
3206             report.append(
3207                 click.style(f"{self.change_count} file{s} {reformatted}", bold=True)
3208             )
3209         if self.same_count:
3210             s = "s" if self.same_count > 1 else ""
3211             report.append(f"{self.same_count} file{s} {unchanged}")
3212         if self.failure_count:
3213             s = "s" if self.failure_count > 1 else ""
3214             report.append(
3215                 click.style(f"{self.failure_count} file{s} {failed}", fg="red")
3216             )
3217         return ", ".join(report) + "."
3218
3219
3220 def assert_equivalent(src: str, dst: str) -> None:
3221     """Raise AssertionError if `src` and `dst` aren't equivalent."""
3222
3223     import ast
3224     import traceback
3225
3226     def _v(node: ast.AST, depth: int = 0) -> Iterator[str]:
3227         """Simple visitor generating strings to compare ASTs by content."""
3228         yield f"{'  ' * depth}{node.__class__.__name__}("
3229
3230         for field in sorted(node._fields):
3231             try:
3232                 value = getattr(node, field)
3233             except AttributeError:
3234                 continue
3235
3236             yield f"{'  ' * (depth+1)}{field}="
3237
3238             if isinstance(value, list):
3239                 for item in value:
3240                     if isinstance(item, ast.AST):
3241                         yield from _v(item, depth + 2)
3242
3243             elif isinstance(value, ast.AST):
3244                 yield from _v(value, depth + 2)
3245
3246             else:
3247                 yield f"{'  ' * (depth+2)}{value!r},  # {value.__class__.__name__}"
3248
3249         yield f"{'  ' * depth})  # /{node.__class__.__name__}"
3250
3251     try:
3252         src_ast = ast.parse(src)
3253     except Exception as exc:
3254         major, minor = sys.version_info[:2]
3255         raise AssertionError(
3256             f"cannot use --safe with this file; failed to parse source file "
3257             f"with Python {major}.{minor}'s builtin AST. Re-run with --fast "
3258             f"or stop using deprecated Python 2 syntax. AST error message: {exc}"
3259         )
3260
3261     try:
3262         dst_ast = ast.parse(dst)
3263     except Exception as exc:
3264         log = dump_to_file("".join(traceback.format_tb(exc.__traceback__)), dst)
3265         raise AssertionError(
3266             f"INTERNAL ERROR: Black produced invalid code: {exc}. "
3267             f"Please report a bug on https://github.com/ambv/black/issues.  "
3268             f"This invalid output might be helpful: {log}"
3269         ) from None
3270
3271     src_ast_str = "\n".join(_v(src_ast))
3272     dst_ast_str = "\n".join(_v(dst_ast))
3273     if src_ast_str != dst_ast_str:
3274         log = dump_to_file(diff(src_ast_str, dst_ast_str, "src", "dst"))
3275         raise AssertionError(
3276             f"INTERNAL ERROR: Black produced code that is not equivalent to "
3277             f"the source.  "
3278             f"Please report a bug on https://github.com/ambv/black/issues.  "
3279             f"This diff might be helpful: {log}"
3280         ) from None
3281
3282
3283 def assert_stable(
3284     src: str, dst: str, line_length: int, mode: FileMode = FileMode.AUTO_DETECT
3285 ) -> None:
3286     """Raise AssertionError if `dst` reformats differently the second time."""
3287     newdst = format_str(dst, line_length=line_length, mode=mode)
3288     if dst != newdst:
3289         log = dump_to_file(
3290             diff(src, dst, "source", "first pass"),
3291             diff(dst, newdst, "first pass", "second pass"),
3292         )
3293         raise AssertionError(
3294             f"INTERNAL ERROR: Black produced different code on the second pass "
3295             f"of the formatter.  "
3296             f"Please report a bug on https://github.com/ambv/black/issues.  "
3297             f"This diff might be helpful: {log}"
3298         ) from None
3299
3300
3301 def dump_to_file(*output: str) -> str:
3302     """Dump `output` to a temporary file. Return path to the file."""
3303     import tempfile
3304
3305     with tempfile.NamedTemporaryFile(
3306         mode="w", prefix="blk_", suffix=".log", delete=False, encoding="utf8"
3307     ) as f:
3308         for lines in output:
3309             f.write(lines)
3310             if lines and lines[-1] != "\n":
3311                 f.write("\n")
3312     return f.name
3313
3314
3315 def diff(a: str, b: str, a_name: str, b_name: str) -> str:
3316     """Return a unified diff string between strings `a` and `b`."""
3317     import difflib
3318
3319     a_lines = [line + "\n" for line in a.split("\n")]
3320     b_lines = [line + "\n" for line in b.split("\n")]
3321     return "".join(
3322         difflib.unified_diff(a_lines, b_lines, fromfile=a_name, tofile=b_name, n=5)
3323     )
3324
3325
3326 def cancel(tasks: Iterable[asyncio.Task]) -> None:
3327     """asyncio signal handler that cancels all `tasks` and reports to stderr."""
3328     err("Aborted!")
3329     for task in tasks:
3330         task.cancel()
3331
3332
3333 def shutdown(loop: BaseEventLoop) -> None:
3334     """Cancel all pending tasks on `loop`, wait for them, and close the loop."""
3335     try:
3336         # This part is borrowed from asyncio/runners.py in Python 3.7b2.
3337         to_cancel = [task for task in asyncio.Task.all_tasks(loop) if not task.done()]
3338         if not to_cancel:
3339             return
3340
3341         for task in to_cancel:
3342             task.cancel()
3343         loop.run_until_complete(
3344             asyncio.gather(*to_cancel, loop=loop, return_exceptions=True)
3345         )
3346     finally:
3347         # `concurrent.futures.Future` objects cannot be cancelled once they
3348         # are already running. There might be some when the `shutdown()` happened.
3349         # Silence their logger's spew about the event loop being closed.
3350         cf_logger = logging.getLogger("concurrent.futures")
3351         cf_logger.setLevel(logging.CRITICAL)
3352         loop.close()
3353
3354
3355 def sub_twice(regex: Pattern[str], replacement: str, original: str) -> str:
3356     """Replace `regex` with `replacement` twice on `original`.
3357
3358     This is used by string normalization to perform replaces on
3359     overlapping matches.
3360     """
3361     return regex.sub(replacement, regex.sub(replacement, original))
3362
3363
3364 def re_compile_maybe_verbose(regex: str) -> Pattern[str]:
3365     """Compile a regular expression string in `regex`.
3366
3367     If it contains newlines, use verbose mode.
3368     """
3369     if "\n" in regex:
3370         regex = "(?x)" + regex
3371     return re.compile(regex)
3372
3373
3374 def enumerate_reversed(sequence: Sequence[T]) -> Iterator[Tuple[Index, T]]:
3375     """Like `reversed(enumerate(sequence))` if that were possible."""
3376     index = len(sequence) - 1
3377     for element in reversed(sequence):
3378         yield (index, element)
3379         index -= 1
3380
3381
3382 def enumerate_with_length(
3383     line: Line, reversed: bool = False
3384 ) -> Iterator[Tuple[Index, Leaf, int]]:
3385     """Return an enumeration of leaves with their length.
3386
3387     Stops prematurely on multiline strings and standalone comments.
3388     """
3389     op = cast(
3390         Callable[[Sequence[Leaf]], Iterator[Tuple[Index, Leaf]]],
3391         enumerate_reversed if reversed else enumerate,
3392     )
3393     for index, leaf in op(line.leaves):
3394         length = len(leaf.prefix) + len(leaf.value)
3395         if "\n" in leaf.value:
3396             return  # Multiline strings, we can't continue.
3397
3398         comment: Optional[Leaf]
3399         for comment in line.comments_after(leaf, index):
3400             length += len(comment.value)
3401
3402         yield index, leaf, length
3403
3404
3405 def is_line_short_enough(line: Line, *, line_length: int, line_str: str = "") -> bool:
3406     """Return True if `line` is no longer than `line_length`.
3407
3408     Uses the provided `line_str` rendering, if any, otherwise computes a new one.
3409     """
3410     if not line_str:
3411         line_str = str(line).strip("\n")
3412     return (
3413         len(line_str) <= line_length
3414         and "\n" not in line_str  # multiline strings
3415         and not line.contains_standalone_comments()
3416     )
3417
3418
3419 def can_be_split(line: Line) -> bool:
3420     """Return False if the line cannot be split *for sure*.
3421
3422     This is not an exhaustive search but a cheap heuristic that we can use to
3423     avoid some unfortunate formattings (mostly around wrapping unsplittable code
3424     in unnecessary parentheses).
3425     """
3426     leaves = line.leaves
3427     if len(leaves) < 2:
3428         return False
3429
3430     if leaves[0].type == token.STRING and leaves[1].type == token.DOT:
3431         call_count = 0
3432         dot_count = 0
3433         next = leaves[-1]
3434         for leaf in leaves[-2::-1]:
3435             if leaf.type in OPENING_BRACKETS:
3436                 if next.type not in CLOSING_BRACKETS:
3437                     return False
3438
3439                 call_count += 1
3440             elif leaf.type == token.DOT:
3441                 dot_count += 1
3442             elif leaf.type == token.NAME:
3443                 if not (next.type == token.DOT or next.type in OPENING_BRACKETS):
3444                     return False
3445
3446             elif leaf.type not in CLOSING_BRACKETS:
3447                 return False
3448
3449             if dot_count > 1 and call_count > 1:
3450                 return False
3451
3452     return True
3453
3454
3455 def can_omit_invisible_parens(line: Line, line_length: int) -> bool:
3456     """Does `line` have a shape safe to reformat without optional parens around it?
3457
3458     Returns True for only a subset of potentially nice looking formattings but
3459     the point is to not return false positives that end up producing lines that
3460     are too long.
3461     """
3462     bt = line.bracket_tracker
3463     if not bt.delimiters:
3464         # Without delimiters the optional parentheses are useless.
3465         return True
3466
3467     max_priority = bt.max_delimiter_priority()
3468     if bt.delimiter_count_with_priority(max_priority) > 1:
3469         # With more than one delimiter of a kind the optional parentheses read better.
3470         return False
3471
3472     if max_priority == DOT_PRIORITY:
3473         # A single stranded method call doesn't require optional parentheses.
3474         return True
3475
3476     assert len(line.leaves) >= 2, "Stranded delimiter"
3477
3478     first = line.leaves[0]
3479     second = line.leaves[1]
3480     penultimate = line.leaves[-2]
3481     last = line.leaves[-1]
3482
3483     # With a single delimiter, omit if the expression starts or ends with
3484     # a bracket.
3485     if first.type in OPENING_BRACKETS and second.type not in CLOSING_BRACKETS:
3486         remainder = False
3487         length = 4 * line.depth
3488         for _index, leaf, leaf_length in enumerate_with_length(line):
3489             if leaf.type in CLOSING_BRACKETS and leaf.opening_bracket is first:
3490                 remainder = True
3491             if remainder:
3492                 length += leaf_length
3493                 if length > line_length:
3494                     break
3495
3496                 if leaf.type in OPENING_BRACKETS:
3497                     # There are brackets we can further split on.
3498                     remainder = False
3499
3500         else:
3501             # checked the entire string and line length wasn't exceeded
3502             if len(line.leaves) == _index + 1:
3503                 return True
3504
3505         # Note: we are not returning False here because a line might have *both*
3506         # a leading opening bracket and a trailing closing bracket.  If the
3507         # opening bracket doesn't match our rule, maybe the closing will.
3508
3509     if (
3510         last.type == token.RPAR
3511         or last.type == token.RBRACE
3512         or (
3513             # don't use indexing for omitting optional parentheses;
3514             # it looks weird
3515             last.type == token.RSQB
3516             and last.parent
3517             and last.parent.type != syms.trailer
3518         )
3519     ):
3520         if penultimate.type in OPENING_BRACKETS:
3521             # Empty brackets don't help.
3522             return False
3523
3524         if is_multiline_string(first):
3525             # Additional wrapping of a multiline string in this situation is
3526             # unnecessary.
3527             return True
3528
3529         length = 4 * line.depth
3530         seen_other_brackets = False
3531         for _index, leaf, leaf_length in enumerate_with_length(line):
3532             length += leaf_length
3533             if leaf is last.opening_bracket:
3534                 if seen_other_brackets or length <= line_length:
3535                     return True
3536
3537             elif leaf.type in OPENING_BRACKETS:
3538                 # There are brackets we can further split on.
3539                 seen_other_brackets = True
3540
3541     return False
3542
3543
3544 def get_cache_file(line_length: int, mode: FileMode) -> Path:
3545     return CACHE_DIR / f"cache.{line_length}.{mode.value}.pickle"
3546
3547
3548 def read_cache(line_length: int, mode: FileMode) -> Cache:
3549     """Read the cache if it exists and is well formed.
3550
3551     If it is not well formed, the call to write_cache later should resolve the issue.
3552     """
3553     cache_file = get_cache_file(line_length, mode)
3554     if not cache_file.exists():
3555         return {}
3556
3557     with cache_file.open("rb") as fobj:
3558         try:
3559             cache: Cache = pickle.load(fobj)
3560         except pickle.UnpicklingError:
3561             return {}
3562
3563     return cache
3564
3565
3566 def get_cache_info(path: Path) -> CacheInfo:
3567     """Return the information used to check if a file is already formatted or not."""
3568     stat = path.stat()
3569     return stat.st_mtime, stat.st_size
3570
3571
3572 def filter_cached(cache: Cache, sources: Iterable[Path]) -> Tuple[Set[Path], Set[Path]]:
3573     """Split an iterable of paths in `sources` into two sets.
3574
3575     The first contains paths of files that modified on disk or are not in the
3576     cache. The other contains paths to non-modified files.
3577     """
3578     todo, done = set(), set()
3579     for src in sources:
3580         src = src.resolve()
3581         if cache.get(src) != get_cache_info(src):
3582             todo.add(src)
3583         else:
3584             done.add(src)
3585     return todo, done
3586
3587
3588 def write_cache(
3589     cache: Cache, sources: Iterable[Path], line_length: int, mode: FileMode
3590 ) -> None:
3591     """Update the cache file."""
3592     cache_file = get_cache_file(line_length, mode)
3593     try:
3594         if not CACHE_DIR.exists():
3595             CACHE_DIR.mkdir(parents=True)
3596         new_cache = {**cache, **{src.resolve(): get_cache_info(src) for src in sources}}
3597         with cache_file.open("wb") as fobj:
3598             pickle.dump(new_cache, fobj, protocol=pickle.HIGHEST_PROTOCOL)
3599     except OSError:
3600         pass
3601
3602
3603 if __name__ == "__main__":
3604     main()