]> git.madduck.net Git - etc/vim.git/blob - src/black/__init__.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:

Fix crash on assert and parenthesized % format (fixes #1597, fixes #1605) (#1681)
[etc/vim.git] / src / black / __init__.py
1 import ast
2 import asyncio
3 from abc import ABC, abstractmethod
4 from collections import defaultdict
5 from concurrent.futures import Executor, ThreadPoolExecutor, ProcessPoolExecutor
6 from contextlib import contextmanager
7 from datetime import datetime
8 from enum import Enum
9 from functools import lru_cache, partial, wraps
10 import io
11 import itertools
12 import logging
13 from multiprocessing import Manager, freeze_support
14 import os
15 from pathlib import Path
16 import pickle
17 import regex as re
18 import signal
19 import sys
20 import tempfile
21 import tokenize
22 import traceback
23 from typing import (
24     Any,
25     Callable,
26     Collection,
27     Dict,
28     Generator,
29     Generic,
30     Iterable,
31     Iterator,
32     List,
33     Optional,
34     Pattern,
35     Sequence,
36     Set,
37     Sized,
38     Tuple,
39     Type,
40     TypeVar,
41     Union,
42     cast,
43     TYPE_CHECKING,
44 )
45 from typing_extensions import Final
46 from mypy_extensions import mypyc_attr
47
48 from appdirs import user_cache_dir
49 from dataclasses import dataclass, field, replace
50 import click
51 import toml
52 from typed_ast import ast3, ast27
53 from pathspec import PathSpec
54
55 # lib2to3 fork
56 from blib2to3.pytree import Node, Leaf, type_repr
57 from blib2to3 import pygram, pytree
58 from blib2to3.pgen2 import driver, token
59 from blib2to3.pgen2.grammar import Grammar
60 from blib2to3.pgen2.parse import ParseError
61
62 from _black_version import version as __version__
63
64 if TYPE_CHECKING:
65     import colorama  # noqa: F401
66
67 DEFAULT_LINE_LENGTH = 88
68 DEFAULT_EXCLUDES = r"/(\.direnv|\.eggs|\.git|\.hg|\.mypy_cache|\.nox|\.tox|\.venv|\.svn|_build|buck-out|build|dist)/"  # noqa: B950
69 DEFAULT_INCLUDES = r"\.pyi?$"
70 CACHE_DIR = Path(user_cache_dir("black", version=__version__))
71
72 STRING_PREFIX_CHARS: Final = "furbFURB"  # All possible string prefix characters.
73
74
75 # types
76 FileContent = str
77 Encoding = str
78 NewLine = str
79 Depth = int
80 NodeType = int
81 ParserState = int
82 LeafID = int
83 StringID = int
84 Priority = int
85 Index = int
86 LN = Union[Leaf, Node]
87 Transformer = Callable[["Line", Collection["Feature"]], Iterator["Line"]]
88 Timestamp = float
89 FileSize = int
90 CacheInfo = Tuple[Timestamp, FileSize]
91 Cache = Dict[Path, CacheInfo]
92 out = partial(click.secho, bold=True, err=True)
93 err = partial(click.secho, fg="red", err=True)
94
95 pygram.initialize(CACHE_DIR)
96 syms = pygram.python_symbols
97
98
99 class NothingChanged(UserWarning):
100     """Raised when reformatted code is the same as source."""
101
102
103 class CannotTransform(Exception):
104     """Base class for errors raised by Transformers."""
105
106
107 class CannotSplit(CannotTransform):
108     """A readable split that fits the allotted line length is impossible."""
109
110
111 class InvalidInput(ValueError):
112     """Raised when input source code fails all parse attempts."""
113
114
115 class BracketMatchError(KeyError):
116     """Raised when an opening bracket is unable to be matched to a closing bracket."""
117
118
119 T = TypeVar("T")
120 E = TypeVar("E", bound=Exception)
121
122
123 class Ok(Generic[T]):
124     def __init__(self, value: T) -> None:
125         self._value = value
126
127     def ok(self) -> T:
128         return self._value
129
130
131 class Err(Generic[E]):
132     def __init__(self, e: E) -> None:
133         self._e = e
134
135     def err(self) -> E:
136         return self._e
137
138
139 # The 'Result' return type is used to implement an error-handling model heavily
140 # influenced by that used by the Rust programming language
141 # (see https://doc.rust-lang.org/book/ch09-00-error-handling.html).
142 Result = Union[Ok[T], Err[E]]
143 TResult = Result[T, CannotTransform]  # (T)ransform Result
144 TMatchResult = TResult[Index]
145
146
147 class WriteBack(Enum):
148     NO = 0
149     YES = 1
150     DIFF = 2
151     CHECK = 3
152     COLOR_DIFF = 4
153
154     @classmethod
155     def from_configuration(
156         cls, *, check: bool, diff: bool, color: bool = False
157     ) -> "WriteBack":
158         if check and not diff:
159             return cls.CHECK
160
161         if diff and color:
162             return cls.COLOR_DIFF
163
164         return cls.DIFF if diff else cls.YES
165
166
167 class Changed(Enum):
168     NO = 0
169     CACHED = 1
170     YES = 2
171
172
173 class TargetVersion(Enum):
174     PY27 = 2
175     PY33 = 3
176     PY34 = 4
177     PY35 = 5
178     PY36 = 6
179     PY37 = 7
180     PY38 = 8
181
182     def is_python2(self) -> bool:
183         return self is TargetVersion.PY27
184
185
186 PY36_VERSIONS = {TargetVersion.PY36, TargetVersion.PY37, TargetVersion.PY38}
187
188
189 class Feature(Enum):
190     # All string literals are unicode
191     UNICODE_LITERALS = 1
192     F_STRINGS = 2
193     NUMERIC_UNDERSCORES = 3
194     TRAILING_COMMA_IN_CALL = 4
195     TRAILING_COMMA_IN_DEF = 5
196     # The following two feature-flags are mutually exclusive, and exactly one should be
197     # set for every version of python.
198     ASYNC_IDENTIFIERS = 6
199     ASYNC_KEYWORDS = 7
200     ASSIGNMENT_EXPRESSIONS = 8
201     POS_ONLY_ARGUMENTS = 9
202     FORCE_OPTIONAL_PARENTHESES = 50
203
204
205 VERSION_TO_FEATURES: Dict[TargetVersion, Set[Feature]] = {
206     TargetVersion.PY27: {Feature.ASYNC_IDENTIFIERS},
207     TargetVersion.PY33: {Feature.UNICODE_LITERALS, Feature.ASYNC_IDENTIFIERS},
208     TargetVersion.PY34: {Feature.UNICODE_LITERALS, Feature.ASYNC_IDENTIFIERS},
209     TargetVersion.PY35: {
210         Feature.UNICODE_LITERALS,
211         Feature.TRAILING_COMMA_IN_CALL,
212         Feature.ASYNC_IDENTIFIERS,
213     },
214     TargetVersion.PY36: {
215         Feature.UNICODE_LITERALS,
216         Feature.F_STRINGS,
217         Feature.NUMERIC_UNDERSCORES,
218         Feature.TRAILING_COMMA_IN_CALL,
219         Feature.TRAILING_COMMA_IN_DEF,
220         Feature.ASYNC_IDENTIFIERS,
221     },
222     TargetVersion.PY37: {
223         Feature.UNICODE_LITERALS,
224         Feature.F_STRINGS,
225         Feature.NUMERIC_UNDERSCORES,
226         Feature.TRAILING_COMMA_IN_CALL,
227         Feature.TRAILING_COMMA_IN_DEF,
228         Feature.ASYNC_KEYWORDS,
229     },
230     TargetVersion.PY38: {
231         Feature.UNICODE_LITERALS,
232         Feature.F_STRINGS,
233         Feature.NUMERIC_UNDERSCORES,
234         Feature.TRAILING_COMMA_IN_CALL,
235         Feature.TRAILING_COMMA_IN_DEF,
236         Feature.ASYNC_KEYWORDS,
237         Feature.ASSIGNMENT_EXPRESSIONS,
238         Feature.POS_ONLY_ARGUMENTS,
239     },
240 }
241
242
243 @dataclass
244 class Mode:
245     target_versions: Set[TargetVersion] = field(default_factory=set)
246     line_length: int = DEFAULT_LINE_LENGTH
247     string_normalization: bool = True
248     experimental_string_processing: bool = False
249     is_pyi: bool = False
250
251     def get_cache_key(self) -> str:
252         if self.target_versions:
253             version_str = ",".join(
254                 str(version.value)
255                 for version in sorted(self.target_versions, key=lambda v: v.value)
256             )
257         else:
258             version_str = "-"
259         parts = [
260             version_str,
261             str(self.line_length),
262             str(int(self.string_normalization)),
263             str(int(self.is_pyi)),
264         ]
265         return ".".join(parts)
266
267
268 # Legacy name, left for integrations.
269 FileMode = Mode
270
271
272 def supports_feature(target_versions: Set[TargetVersion], feature: Feature) -> bool:
273     return all(feature in VERSION_TO_FEATURES[version] for version in target_versions)
274
275
276 def find_pyproject_toml(path_search_start: Iterable[str]) -> Optional[str]:
277     """Find the absolute filepath to a pyproject.toml if it exists"""
278     path_project_root = find_project_root(path_search_start)
279     path_pyproject_toml = path_project_root / "pyproject.toml"
280     return str(path_pyproject_toml) if path_pyproject_toml.is_file() else None
281
282
283 def parse_pyproject_toml(path_config: str) -> Dict[str, Any]:
284     """Parse a pyproject toml file, pulling out relevant parts for Black
285
286     If parsing fails, will raise a toml.TomlDecodeError
287     """
288     pyproject_toml = toml.load(path_config)
289     config = pyproject_toml.get("tool", {}).get("black", {})
290     return {k.replace("--", "").replace("-", "_"): v for k, v in config.items()}
291
292
293 def read_pyproject_toml(
294     ctx: click.Context, param: click.Parameter, value: Optional[str]
295 ) -> Optional[str]:
296     """Inject Black configuration from "pyproject.toml" into defaults in `ctx`.
297
298     Returns the path to a successfully found and read configuration file, None
299     otherwise.
300     """
301     if not value:
302         value = find_pyproject_toml(ctx.params.get("src", ()))
303         if value is None:
304             return None
305
306     try:
307         config = parse_pyproject_toml(value)
308     except (toml.TomlDecodeError, OSError) as e:
309         raise click.FileError(
310             filename=value, hint=f"Error reading configuration file: {e}"
311         )
312
313     if not config:
314         return None
315     else:
316         # Sanitize the values to be Click friendly. For more information please see:
317         # https://github.com/psf/black/issues/1458
318         # https://github.com/pallets/click/issues/1567
319         config = {
320             k: str(v) if not isinstance(v, (list, dict)) else v
321             for k, v in config.items()
322         }
323
324     target_version = config.get("target_version")
325     if target_version is not None and not isinstance(target_version, list):
326         raise click.BadOptionUsage(
327             "target-version", "Config key target-version must be a list"
328         )
329
330     default_map: Dict[str, Any] = {}
331     if ctx.default_map:
332         default_map.update(ctx.default_map)
333     default_map.update(config)
334
335     ctx.default_map = default_map
336     return value
337
338
339 def target_version_option_callback(
340     c: click.Context, p: Union[click.Option, click.Parameter], v: Tuple[str, ...]
341 ) -> List[TargetVersion]:
342     """Compute the target versions from a --target-version flag.
343
344     This is its own function because mypy couldn't infer the type correctly
345     when it was a lambda, causing mypyc trouble.
346     """
347     return [TargetVersion[val.upper()] for val in v]
348
349
350 @click.command(context_settings=dict(help_option_names=["-h", "--help"]))
351 @click.option("-c", "--code", type=str, help="Format the code passed in as a string.")
352 @click.option(
353     "-l",
354     "--line-length",
355     type=int,
356     default=DEFAULT_LINE_LENGTH,
357     help="How many characters per line to allow.",
358     show_default=True,
359 )
360 @click.option(
361     "-t",
362     "--target-version",
363     type=click.Choice([v.name.lower() for v in TargetVersion]),
364     callback=target_version_option_callback,
365     multiple=True,
366     help=(
367         "Python versions that should be supported by Black's output. [default: per-file"
368         " auto-detection]"
369     ),
370 )
371 @click.option(
372     "--pyi",
373     is_flag=True,
374     help=(
375         "Format all input files like typing stubs regardless of file extension (useful"
376         " when piping source on standard input)."
377     ),
378 )
379 @click.option(
380     "-S",
381     "--skip-string-normalization",
382     is_flag=True,
383     help="Don't normalize string quotes or prefixes.",
384 )
385 @click.option(
386     "--experimental-string-processing",
387     is_flag=True,
388     hidden=True,
389     help=(
390         "Experimental option that performs more normalization on string literals."
391         " Currently disabled because it leads to some crashes."
392     ),
393 )
394 @click.option(
395     "--check",
396     is_flag=True,
397     help=(
398         "Don't write the files back, just return the status.  Return code 0 means"
399         " nothing would change.  Return code 1 means some files would be reformatted."
400         " Return code 123 means there was an internal error."
401     ),
402 )
403 @click.option(
404     "--diff",
405     is_flag=True,
406     help="Don't write the files back, just output a diff for each file on stdout.",
407 )
408 @click.option(
409     "--color/--no-color",
410     is_flag=True,
411     help="Show colored diff. Only applies when `--diff` is given.",
412 )
413 @click.option(
414     "--fast/--safe",
415     is_flag=True,
416     help="If --fast given, skip temporary sanity checks. [default: --safe]",
417 )
418 @click.option(
419     "--include",
420     type=str,
421     default=DEFAULT_INCLUDES,
422     help=(
423         "A regular expression that matches files and directories that should be"
424         " included on recursive searches.  An empty value means all files are included"
425         " regardless of the name.  Use forward slashes for directories on all platforms"
426         " (Windows, too).  Exclusions are calculated first, inclusions later."
427     ),
428     show_default=True,
429 )
430 @click.option(
431     "--exclude",
432     type=str,
433     default=DEFAULT_EXCLUDES,
434     help=(
435         "A regular expression that matches files and directories that should be"
436         " excluded on recursive searches.  An empty value means no paths are excluded."
437         " Use forward slashes for directories on all platforms (Windows, too). "
438         " Exclusions are calculated first, inclusions later."
439     ),
440     show_default=True,
441 )
442 @click.option(
443     "--force-exclude",
444     type=str,
445     help=(
446         "Like --exclude, but files and directories matching this regex will be "
447         "excluded even when they are passed explicitly as arguments"
448     ),
449 )
450 @click.option(
451     "-q",
452     "--quiet",
453     is_flag=True,
454     help=(
455         "Don't emit non-error messages to stderr. Errors are still emitted; silence"
456         " those with 2>/dev/null."
457     ),
458 )
459 @click.option(
460     "-v",
461     "--verbose",
462     is_flag=True,
463     help=(
464         "Also emit messages to stderr about files that were not changed or were ignored"
465         " due to --exclude=."
466     ),
467 )
468 @click.version_option(version=__version__)
469 @click.argument(
470     "src",
471     nargs=-1,
472     type=click.Path(
473         exists=True, file_okay=True, dir_okay=True, readable=True, allow_dash=True
474     ),
475     is_eager=True,
476 )
477 @click.option(
478     "--config",
479     type=click.Path(
480         exists=True,
481         file_okay=True,
482         dir_okay=False,
483         readable=True,
484         allow_dash=False,
485         path_type=str,
486     ),
487     is_eager=True,
488     callback=read_pyproject_toml,
489     help="Read configuration from FILE path.",
490 )
491 @click.pass_context
492 def main(
493     ctx: click.Context,
494     code: Optional[str],
495     line_length: int,
496     target_version: List[TargetVersion],
497     check: bool,
498     diff: bool,
499     color: bool,
500     fast: bool,
501     pyi: bool,
502     skip_string_normalization: bool,
503     experimental_string_processing: bool,
504     quiet: bool,
505     verbose: bool,
506     include: str,
507     exclude: str,
508     force_exclude: Optional[str],
509     src: Tuple[str, ...],
510     config: Optional[str],
511 ) -> None:
512     """The uncompromising code formatter."""
513     write_back = WriteBack.from_configuration(check=check, diff=diff, color=color)
514     if target_version:
515         versions = set(target_version)
516     else:
517         # We'll autodetect later.
518         versions = set()
519     mode = Mode(
520         target_versions=versions,
521         line_length=line_length,
522         is_pyi=pyi,
523         string_normalization=not skip_string_normalization,
524         experimental_string_processing=experimental_string_processing,
525     )
526     if config and verbose:
527         out(f"Using configuration from {config}.", bold=False, fg="blue")
528     if code is not None:
529         print(format_str(code, mode=mode))
530         ctx.exit(0)
531     report = Report(check=check, diff=diff, quiet=quiet, verbose=verbose)
532     sources = get_sources(
533         ctx=ctx,
534         src=src,
535         quiet=quiet,
536         verbose=verbose,
537         include=include,
538         exclude=exclude,
539         force_exclude=force_exclude,
540         report=report,
541     )
542
543     path_empty(
544         sources,
545         "No Python files are present to be formatted. Nothing to do 😴",
546         quiet,
547         verbose,
548         ctx,
549     )
550
551     if len(sources) == 1:
552         reformat_one(
553             src=sources.pop(),
554             fast=fast,
555             write_back=write_back,
556             mode=mode,
557             report=report,
558         )
559     else:
560         reformat_many(
561             sources=sources, fast=fast, write_back=write_back, mode=mode, report=report
562         )
563
564     if verbose or not quiet:
565         out("Oh no! 💥 💔 💥" if report.return_code else "All done! ✨ 🍰 ✨")
566         click.secho(str(report), err=True)
567     ctx.exit(report.return_code)
568
569
570 def get_sources(
571     *,
572     ctx: click.Context,
573     src: Tuple[str, ...],
574     quiet: bool,
575     verbose: bool,
576     include: str,
577     exclude: str,
578     force_exclude: Optional[str],
579     report: "Report",
580 ) -> Set[Path]:
581     """Compute the set of files to be formatted."""
582     try:
583         include_regex = re_compile_maybe_verbose(include)
584     except re.error:
585         err(f"Invalid regular expression for include given: {include!r}")
586         ctx.exit(2)
587     try:
588         exclude_regex = re_compile_maybe_verbose(exclude)
589     except re.error:
590         err(f"Invalid regular expression for exclude given: {exclude!r}")
591         ctx.exit(2)
592     try:
593         force_exclude_regex = (
594             re_compile_maybe_verbose(force_exclude) if force_exclude else None
595         )
596     except re.error:
597         err(f"Invalid regular expression for force_exclude given: {force_exclude!r}")
598         ctx.exit(2)
599
600     root = find_project_root(src)
601     sources: Set[Path] = set()
602     path_empty(src, "No Path provided. Nothing to do 😴", quiet, verbose, ctx)
603     gitignore = get_gitignore(root)
604
605     for s in src:
606         p = Path(s)
607         if p.is_dir():
608             sources.update(
609                 gen_python_files(
610                     p.iterdir(),
611                     root,
612                     include_regex,
613                     exclude_regex,
614                     force_exclude_regex,
615                     report,
616                     gitignore,
617                 )
618             )
619         elif s == "-":
620             sources.add(p)
621         elif p.is_file():
622             normalized_path = normalize_path_maybe_ignore(p, root, report)
623             if normalized_path is None:
624                 continue
625
626             normalized_path = "/" + normalized_path
627             # Hard-exclude any files that matches the `--force-exclude` regex.
628             if force_exclude_regex:
629                 force_exclude_match = force_exclude_regex.search(normalized_path)
630             else:
631                 force_exclude_match = None
632             if force_exclude_match and force_exclude_match.group(0):
633                 report.path_ignored(p, "matches the --force-exclude regular expression")
634                 continue
635
636             sources.add(p)
637         else:
638             err(f"invalid path: {s}")
639     return sources
640
641
642 def path_empty(
643     src: Sized, msg: str, quiet: bool, verbose: bool, ctx: click.Context
644 ) -> None:
645     """
646     Exit if there is no `src` provided for formatting
647     """
648     if not src and (verbose or not quiet):
649         out(msg)
650         ctx.exit(0)
651
652
653 def reformat_one(
654     src: Path, fast: bool, write_back: WriteBack, mode: Mode, report: "Report"
655 ) -> None:
656     """Reformat a single file under `src` without spawning child processes.
657
658     `fast`, `write_back`, and `mode` options are passed to
659     :func:`format_file_in_place` or :func:`format_stdin_to_stdout`.
660     """
661     try:
662         changed = Changed.NO
663         if not src.is_file() and str(src) == "-":
664             if format_stdin_to_stdout(fast=fast, write_back=write_back, mode=mode):
665                 changed = Changed.YES
666         else:
667             cache: Cache = {}
668             if write_back not in (WriteBack.DIFF, WriteBack.COLOR_DIFF):
669                 cache = read_cache(mode)
670                 res_src = src.resolve()
671                 if res_src in cache and cache[res_src] == get_cache_info(res_src):
672                     changed = Changed.CACHED
673             if changed is not Changed.CACHED and format_file_in_place(
674                 src, fast=fast, write_back=write_back, mode=mode
675             ):
676                 changed = Changed.YES
677             if (write_back is WriteBack.YES and changed is not Changed.CACHED) or (
678                 write_back is WriteBack.CHECK and changed is Changed.NO
679             ):
680                 write_cache(cache, [src], mode)
681         report.done(src, changed)
682     except Exception as exc:
683         if report.verbose:
684             traceback.print_exc()
685         report.failed(src, str(exc))
686
687
688 def reformat_many(
689     sources: Set[Path], fast: bool, write_back: WriteBack, mode: Mode, report: "Report"
690 ) -> None:
691     """Reformat multiple files using a ProcessPoolExecutor."""
692     executor: Executor
693     loop = asyncio.get_event_loop()
694     worker_count = os.cpu_count()
695     if sys.platform == "win32":
696         # Work around https://bugs.python.org/issue26903
697         worker_count = min(worker_count, 61)
698     try:
699         executor = ProcessPoolExecutor(max_workers=worker_count)
700     except (ImportError, OSError):
701         # we arrive here if the underlying system does not support multi-processing
702         # like in AWS Lambda or Termux, in which case we gracefully fallback to
703         # a ThreadPollExecutor with just a single worker (more workers would not do us
704         # any good due to the Global Interpreter Lock)
705         executor = ThreadPoolExecutor(max_workers=1)
706
707     try:
708         loop.run_until_complete(
709             schedule_formatting(
710                 sources=sources,
711                 fast=fast,
712                 write_back=write_back,
713                 mode=mode,
714                 report=report,
715                 loop=loop,
716                 executor=executor,
717             )
718         )
719     finally:
720         shutdown(loop)
721         if executor is not None:
722             executor.shutdown()
723
724
725 async def schedule_formatting(
726     sources: Set[Path],
727     fast: bool,
728     write_back: WriteBack,
729     mode: Mode,
730     report: "Report",
731     loop: asyncio.AbstractEventLoop,
732     executor: Executor,
733 ) -> None:
734     """Run formatting of `sources` in parallel using the provided `executor`.
735
736     (Use ProcessPoolExecutors for actual parallelism.)
737
738     `write_back`, `fast`, and `mode` options are passed to
739     :func:`format_file_in_place`.
740     """
741     cache: Cache = {}
742     if write_back not in (WriteBack.DIFF, WriteBack.COLOR_DIFF):
743         cache = read_cache(mode)
744         sources, cached = filter_cached(cache, sources)
745         for src in sorted(cached):
746             report.done(src, Changed.CACHED)
747     if not sources:
748         return
749
750     cancelled = []
751     sources_to_cache = []
752     lock = None
753     if write_back in (WriteBack.DIFF, WriteBack.COLOR_DIFF):
754         # For diff output, we need locks to ensure we don't interleave output
755         # from different processes.
756         manager = Manager()
757         lock = manager.Lock()
758     tasks = {
759         asyncio.ensure_future(
760             loop.run_in_executor(
761                 executor, format_file_in_place, src, fast, mode, write_back, lock
762             )
763         ): src
764         for src in sorted(sources)
765     }
766     pending: Iterable["asyncio.Future[bool]"] = tasks.keys()
767     try:
768         loop.add_signal_handler(signal.SIGINT, cancel, pending)
769         loop.add_signal_handler(signal.SIGTERM, cancel, pending)
770     except NotImplementedError:
771         # There are no good alternatives for these on Windows.
772         pass
773     while pending:
774         done, _ = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
775         for task in done:
776             src = tasks.pop(task)
777             if task.cancelled():
778                 cancelled.append(task)
779             elif task.exception():
780                 report.failed(src, str(task.exception()))
781             else:
782                 changed = Changed.YES if task.result() else Changed.NO
783                 # If the file was written back or was successfully checked as
784                 # well-formatted, store this information in the cache.
785                 if write_back is WriteBack.YES or (
786                     write_back is WriteBack.CHECK and changed is Changed.NO
787                 ):
788                     sources_to_cache.append(src)
789                 report.done(src, changed)
790     if cancelled:
791         await asyncio.gather(*cancelled, loop=loop, return_exceptions=True)
792     if sources_to_cache:
793         write_cache(cache, sources_to_cache, mode)
794
795
796 def format_file_in_place(
797     src: Path,
798     fast: bool,
799     mode: Mode,
800     write_back: WriteBack = WriteBack.NO,
801     lock: Any = None,  # multiprocessing.Manager().Lock() is some crazy proxy
802 ) -> bool:
803     """Format file under `src` path. Return True if changed.
804
805     If `write_back` is DIFF, write a diff to stdout. If it is YES, write reformatted
806     code to the file.
807     `mode` and `fast` options are passed to :func:`format_file_contents`.
808     """
809     if src.suffix == ".pyi":
810         mode = replace(mode, is_pyi=True)
811
812     then = datetime.utcfromtimestamp(src.stat().st_mtime)
813     with open(src, "rb") as buf:
814         src_contents, encoding, newline = decode_bytes(buf.read())
815     try:
816         dst_contents = format_file_contents(src_contents, fast=fast, mode=mode)
817     except NothingChanged:
818         return False
819
820     if write_back == WriteBack.YES:
821         with open(src, "w", encoding=encoding, newline=newline) as f:
822             f.write(dst_contents)
823     elif write_back in (WriteBack.DIFF, WriteBack.COLOR_DIFF):
824         now = datetime.utcnow()
825         src_name = f"{src}\t{then} +0000"
826         dst_name = f"{src}\t{now} +0000"
827         diff_contents = diff(src_contents, dst_contents, src_name, dst_name)
828
829         if write_back == write_back.COLOR_DIFF:
830             diff_contents = color_diff(diff_contents)
831
832         with lock or nullcontext():
833             f = io.TextIOWrapper(
834                 sys.stdout.buffer,
835                 encoding=encoding,
836                 newline=newline,
837                 write_through=True,
838             )
839             f = wrap_stream_for_windows(f)
840             f.write(diff_contents)
841             f.detach()
842
843     return True
844
845
846 def color_diff(contents: str) -> str:
847     """Inject the ANSI color codes to the diff."""
848     lines = contents.split("\n")
849     for i, line in enumerate(lines):
850         if line.startswith("+++") or line.startswith("---"):
851             line = "\033[1;37m" + line + "\033[0m"  # bold white, reset
852         if line.startswith("@@"):
853             line = "\033[36m" + line + "\033[0m"  # cyan, reset
854         if line.startswith("+"):
855             line = "\033[32m" + line + "\033[0m"  # green, reset
856         elif line.startswith("-"):
857             line = "\033[31m" + line + "\033[0m"  # red, reset
858         lines[i] = line
859     return "\n".join(lines)
860
861
862 def wrap_stream_for_windows(
863     f: io.TextIOWrapper,
864 ) -> Union[io.TextIOWrapper, "colorama.AnsiToWin32.AnsiToWin32"]:
865     """
866     Wrap the stream in colorama's wrap_stream so colors are shown on Windows.
867
868     If `colorama` is not found, then no change is made. If `colorama` does
869     exist, then it handles the logic to determine whether or not to change
870     things.
871     """
872     try:
873         from colorama import initialise
874
875         # We set `strip=False` so that we can don't have to modify
876         # test_express_diff_with_color.
877         f = initialise.wrap_stream(
878             f, convert=None, strip=False, autoreset=False, wrap=True
879         )
880
881         # wrap_stream returns a `colorama.AnsiToWin32.AnsiToWin32` object
882         # which does not have a `detach()` method. So we fake one.
883         f.detach = lambda *args, **kwargs: None  # type: ignore
884     except ImportError:
885         pass
886
887     return f
888
889
890 def format_stdin_to_stdout(
891     fast: bool, *, write_back: WriteBack = WriteBack.NO, mode: Mode
892 ) -> bool:
893     """Format file on stdin. Return True if changed.
894
895     If `write_back` is YES, write reformatted code back to stdout. If it is DIFF,
896     write a diff to stdout. The `mode` argument is passed to
897     :func:`format_file_contents`.
898     """
899     then = datetime.utcnow()
900     src, encoding, newline = decode_bytes(sys.stdin.buffer.read())
901     dst = src
902     try:
903         dst = format_file_contents(src, fast=fast, mode=mode)
904         return True
905
906     except NothingChanged:
907         return False
908
909     finally:
910         f = io.TextIOWrapper(
911             sys.stdout.buffer, encoding=encoding, newline=newline, write_through=True
912         )
913         if write_back == WriteBack.YES:
914             f.write(dst)
915         elif write_back in (WriteBack.DIFF, WriteBack.COLOR_DIFF):
916             now = datetime.utcnow()
917             src_name = f"STDIN\t{then} +0000"
918             dst_name = f"STDOUT\t{now} +0000"
919             d = diff(src, dst, src_name, dst_name)
920             if write_back == WriteBack.COLOR_DIFF:
921                 d = color_diff(d)
922                 f = wrap_stream_for_windows(f)
923             f.write(d)
924         f.detach()
925
926
927 def format_file_contents(src_contents: str, *, fast: bool, mode: Mode) -> FileContent:
928     """Reformat contents a file and return new contents.
929
930     If `fast` is False, additionally confirm that the reformatted code is
931     valid by calling :func:`assert_equivalent` and :func:`assert_stable` on it.
932     `mode` is passed to :func:`format_str`.
933     """
934     if not src_contents.strip():
935         raise NothingChanged
936
937     dst_contents = format_str(src_contents, mode=mode)
938     if src_contents == dst_contents:
939         raise NothingChanged
940
941     if not fast:
942         assert_equivalent(src_contents, dst_contents)
943         assert_stable(src_contents, dst_contents, mode=mode)
944     return dst_contents
945
946
947 def format_str(src_contents: str, *, mode: Mode) -> FileContent:
948     """Reformat a string and return new contents.
949
950     `mode` determines formatting options, such as how many characters per line are
951     allowed.  Example:
952
953     >>> import black
954     >>> print(black.format_str("def f(arg:str='')->None:...", mode=Mode()))
955     def f(arg: str = "") -> None:
956         ...
957
958     A more complex example:
959
960     >>> print(
961     ...   black.format_str(
962     ...     "def f(arg:str='')->None: hey",
963     ...     mode=black.Mode(
964     ...       target_versions={black.TargetVersion.PY36},
965     ...       line_length=10,
966     ...       string_normalization=False,
967     ...       is_pyi=False,
968     ...     ),
969     ...   ),
970     ... )
971     def f(
972         arg: str = '',
973     ) -> None:
974         hey
975
976     """
977     src_node = lib2to3_parse(src_contents.lstrip(), mode.target_versions)
978     dst_contents = []
979     future_imports = get_future_imports(src_node)
980     if mode.target_versions:
981         versions = mode.target_versions
982     else:
983         versions = detect_target_versions(src_node)
984     normalize_fmt_off(src_node)
985     lines = LineGenerator(
986         remove_u_prefix="unicode_literals" in future_imports
987         or supports_feature(versions, Feature.UNICODE_LITERALS),
988         is_pyi=mode.is_pyi,
989         normalize_strings=mode.string_normalization,
990     )
991     elt = EmptyLineTracker(is_pyi=mode.is_pyi)
992     empty_line = Line()
993     after = 0
994     split_line_features = {
995         feature
996         for feature in {Feature.TRAILING_COMMA_IN_CALL, Feature.TRAILING_COMMA_IN_DEF}
997         if supports_feature(versions, feature)
998     }
999     for current_line in lines.visit(src_node):
1000         dst_contents.append(str(empty_line) * after)
1001         before, after = elt.maybe_empty_lines(current_line)
1002         dst_contents.append(str(empty_line) * before)
1003         for line in transform_line(
1004             current_line, mode=mode, features=split_line_features
1005         ):
1006             dst_contents.append(str(line))
1007     return "".join(dst_contents)
1008
1009
1010 def decode_bytes(src: bytes) -> Tuple[FileContent, Encoding, NewLine]:
1011     """Return a tuple of (decoded_contents, encoding, newline).
1012
1013     `newline` is either CRLF or LF but `decoded_contents` is decoded with
1014     universal newlines (i.e. only contains LF).
1015     """
1016     srcbuf = io.BytesIO(src)
1017     encoding, lines = tokenize.detect_encoding(srcbuf.readline)
1018     if not lines:
1019         return "", encoding, "\n"
1020
1021     newline = "\r\n" if b"\r\n" == lines[0][-2:] else "\n"
1022     srcbuf.seek(0)
1023     with io.TextIOWrapper(srcbuf, encoding) as tiow:
1024         return tiow.read(), encoding, newline
1025
1026
1027 def get_grammars(target_versions: Set[TargetVersion]) -> List[Grammar]:
1028     if not target_versions:
1029         # No target_version specified, so try all grammars.
1030         return [
1031             # Python 3.7+
1032             pygram.python_grammar_no_print_statement_no_exec_statement_async_keywords,
1033             # Python 3.0-3.6
1034             pygram.python_grammar_no_print_statement_no_exec_statement,
1035             # Python 2.7 with future print_function import
1036             pygram.python_grammar_no_print_statement,
1037             # Python 2.7
1038             pygram.python_grammar,
1039         ]
1040
1041     if all(version.is_python2() for version in target_versions):
1042         # Python 2-only code, so try Python 2 grammars.
1043         return [
1044             # Python 2.7 with future print_function import
1045             pygram.python_grammar_no_print_statement,
1046             # Python 2.7
1047             pygram.python_grammar,
1048         ]
1049
1050     # Python 3-compatible code, so only try Python 3 grammar.
1051     grammars = []
1052     # If we have to parse both, try to parse async as a keyword first
1053     if not supports_feature(target_versions, Feature.ASYNC_IDENTIFIERS):
1054         # Python 3.7+
1055         grammars.append(
1056             pygram.python_grammar_no_print_statement_no_exec_statement_async_keywords
1057         )
1058     if not supports_feature(target_versions, Feature.ASYNC_KEYWORDS):
1059         # Python 3.0-3.6
1060         grammars.append(pygram.python_grammar_no_print_statement_no_exec_statement)
1061     # At least one of the above branches must have been taken, because every Python
1062     # version has exactly one of the two 'ASYNC_*' flags
1063     return grammars
1064
1065
1066 def lib2to3_parse(src_txt: str, target_versions: Iterable[TargetVersion] = ()) -> Node:
1067     """Given a string with source, return the lib2to3 Node."""
1068     if not src_txt.endswith("\n"):
1069         src_txt += "\n"
1070
1071     for grammar in get_grammars(set(target_versions)):
1072         drv = driver.Driver(grammar, pytree.convert)
1073         try:
1074             result = drv.parse_string(src_txt, True)
1075             break
1076
1077         except ParseError as pe:
1078             lineno, column = pe.context[1]
1079             lines = src_txt.splitlines()
1080             try:
1081                 faulty_line = lines[lineno - 1]
1082             except IndexError:
1083                 faulty_line = "<line number missing in source>"
1084             exc = InvalidInput(f"Cannot parse: {lineno}:{column}: {faulty_line}")
1085     else:
1086         raise exc from None
1087
1088     if isinstance(result, Leaf):
1089         result = Node(syms.file_input, [result])
1090     return result
1091
1092
1093 def lib2to3_unparse(node: Node) -> str:
1094     """Given a lib2to3 node, return its string representation."""
1095     code = str(node)
1096     return code
1097
1098
1099 class Visitor(Generic[T]):
1100     """Basic lib2to3 visitor that yields things of type `T` on `visit()`."""
1101
1102     def visit(self, node: LN) -> Iterator[T]:
1103         """Main method to visit `node` and its children.
1104
1105         It tries to find a `visit_*()` method for the given `node.type`, like
1106         `visit_simple_stmt` for Node objects or `visit_INDENT` for Leaf objects.
1107         If no dedicated `visit_*()` method is found, chooses `visit_default()`
1108         instead.
1109
1110         Then yields objects of type `T` from the selected visitor.
1111         """
1112         if node.type < 256:
1113             name = token.tok_name[node.type]
1114         else:
1115             name = str(type_repr(node.type))
1116         # We explicitly branch on whether a visitor exists (instead of
1117         # using self.visit_default as the default arg to getattr) in order
1118         # to save needing to create a bound method object and so mypyc can
1119         # generate a native call to visit_default.
1120         visitf = getattr(self, f"visit_{name}", None)
1121         if visitf:
1122             yield from visitf(node)
1123         else:
1124             yield from self.visit_default(node)
1125
1126     def visit_default(self, node: LN) -> Iterator[T]:
1127         """Default `visit_*()` implementation. Recurses to children of `node`."""
1128         if isinstance(node, Node):
1129             for child in node.children:
1130                 yield from self.visit(child)
1131
1132
1133 @dataclass
1134 class DebugVisitor(Visitor[T]):
1135     tree_depth: int = 0
1136
1137     def visit_default(self, node: LN) -> Iterator[T]:
1138         indent = " " * (2 * self.tree_depth)
1139         if isinstance(node, Node):
1140             _type = type_repr(node.type)
1141             out(f"{indent}{_type}", fg="yellow")
1142             self.tree_depth += 1
1143             for child in node.children:
1144                 yield from self.visit(child)
1145
1146             self.tree_depth -= 1
1147             out(f"{indent}/{_type}", fg="yellow", bold=False)
1148         else:
1149             _type = token.tok_name.get(node.type, str(node.type))
1150             out(f"{indent}{_type}", fg="blue", nl=False)
1151             if node.prefix:
1152                 # We don't have to handle prefixes for `Node` objects since
1153                 # that delegates to the first child anyway.
1154                 out(f" {node.prefix!r}", fg="green", bold=False, nl=False)
1155             out(f" {node.value!r}", fg="blue", bold=False)
1156
1157     @classmethod
1158     def show(cls, code: Union[str, Leaf, Node]) -> None:
1159         """Pretty-print the lib2to3 AST of a given string of `code`.
1160
1161         Convenience method for debugging.
1162         """
1163         v: DebugVisitor[None] = DebugVisitor()
1164         if isinstance(code, str):
1165             code = lib2to3_parse(code)
1166         list(v.visit(code))
1167
1168
1169 WHITESPACE: Final = {token.DEDENT, token.INDENT, token.NEWLINE}
1170 STATEMENT: Final = {
1171     syms.if_stmt,
1172     syms.while_stmt,
1173     syms.for_stmt,
1174     syms.try_stmt,
1175     syms.except_clause,
1176     syms.with_stmt,
1177     syms.funcdef,
1178     syms.classdef,
1179 }
1180 STANDALONE_COMMENT: Final = 153
1181 token.tok_name[STANDALONE_COMMENT] = "STANDALONE_COMMENT"
1182 LOGIC_OPERATORS: Final = {"and", "or"}
1183 COMPARATORS: Final = {
1184     token.LESS,
1185     token.GREATER,
1186     token.EQEQUAL,
1187     token.NOTEQUAL,
1188     token.LESSEQUAL,
1189     token.GREATEREQUAL,
1190 }
1191 MATH_OPERATORS: Final = {
1192     token.VBAR,
1193     token.CIRCUMFLEX,
1194     token.AMPER,
1195     token.LEFTSHIFT,
1196     token.RIGHTSHIFT,
1197     token.PLUS,
1198     token.MINUS,
1199     token.STAR,
1200     token.SLASH,
1201     token.DOUBLESLASH,
1202     token.PERCENT,
1203     token.AT,
1204     token.TILDE,
1205     token.DOUBLESTAR,
1206 }
1207 STARS: Final = {token.STAR, token.DOUBLESTAR}
1208 VARARGS_SPECIALS: Final = STARS | {token.SLASH}
1209 VARARGS_PARENTS: Final = {
1210     syms.arglist,
1211     syms.argument,  # double star in arglist
1212     syms.trailer,  # single argument to call
1213     syms.typedargslist,
1214     syms.varargslist,  # lambdas
1215 }
1216 UNPACKING_PARENTS: Final = {
1217     syms.atom,  # single element of a list or set literal
1218     syms.dictsetmaker,
1219     syms.listmaker,
1220     syms.testlist_gexp,
1221     syms.testlist_star_expr,
1222 }
1223 TEST_DESCENDANTS: Final = {
1224     syms.test,
1225     syms.lambdef,
1226     syms.or_test,
1227     syms.and_test,
1228     syms.not_test,
1229     syms.comparison,
1230     syms.star_expr,
1231     syms.expr,
1232     syms.xor_expr,
1233     syms.and_expr,
1234     syms.shift_expr,
1235     syms.arith_expr,
1236     syms.trailer,
1237     syms.term,
1238     syms.power,
1239 }
1240 ASSIGNMENTS: Final = {
1241     "=",
1242     "+=",
1243     "-=",
1244     "*=",
1245     "@=",
1246     "/=",
1247     "%=",
1248     "&=",
1249     "|=",
1250     "^=",
1251     "<<=",
1252     ">>=",
1253     "**=",
1254     "//=",
1255 }
1256 COMPREHENSION_PRIORITY: Final = 20
1257 COMMA_PRIORITY: Final = 18
1258 TERNARY_PRIORITY: Final = 16
1259 LOGIC_PRIORITY: Final = 14
1260 STRING_PRIORITY: Final = 12
1261 COMPARATOR_PRIORITY: Final = 10
1262 MATH_PRIORITIES: Final = {
1263     token.VBAR: 9,
1264     token.CIRCUMFLEX: 8,
1265     token.AMPER: 7,
1266     token.LEFTSHIFT: 6,
1267     token.RIGHTSHIFT: 6,
1268     token.PLUS: 5,
1269     token.MINUS: 5,
1270     token.STAR: 4,
1271     token.SLASH: 4,
1272     token.DOUBLESLASH: 4,
1273     token.PERCENT: 4,
1274     token.AT: 4,
1275     token.TILDE: 3,
1276     token.DOUBLESTAR: 2,
1277 }
1278 DOT_PRIORITY: Final = 1
1279
1280
1281 @dataclass
1282 class BracketTracker:
1283     """Keeps track of brackets on a line."""
1284
1285     depth: int = 0
1286     bracket_match: Dict[Tuple[Depth, NodeType], Leaf] = field(default_factory=dict)
1287     delimiters: Dict[LeafID, Priority] = field(default_factory=dict)
1288     previous: Optional[Leaf] = None
1289     _for_loop_depths: List[int] = field(default_factory=list)
1290     _lambda_argument_depths: List[int] = field(default_factory=list)
1291     invisible: List[Leaf] = field(default_factory=list)
1292
1293     def mark(self, leaf: Leaf) -> None:
1294         """Mark `leaf` with bracket-related metadata. Keep track of delimiters.
1295
1296         All leaves receive an int `bracket_depth` field that stores how deep
1297         within brackets a given leaf is. 0 means there are no enclosing brackets
1298         that started on this line.
1299
1300         If a leaf is itself a closing bracket, it receives an `opening_bracket`
1301         field that it forms a pair with. This is a one-directional link to
1302         avoid reference cycles.
1303
1304         If a leaf is a delimiter (a token on which Black can split the line if
1305         needed) and it's on depth 0, its `id()` is stored in the tracker's
1306         `delimiters` field.
1307         """
1308         if leaf.type == token.COMMENT:
1309             return
1310
1311         self.maybe_decrement_after_for_loop_variable(leaf)
1312         self.maybe_decrement_after_lambda_arguments(leaf)
1313         if leaf.type in CLOSING_BRACKETS:
1314             self.depth -= 1
1315             try:
1316                 opening_bracket = self.bracket_match.pop((self.depth, leaf.type))
1317             except KeyError as e:
1318                 raise BracketMatchError(
1319                     "Unable to match a closing bracket to the following opening"
1320                     f" bracket: {leaf}"
1321                 ) from e
1322             leaf.opening_bracket = opening_bracket
1323             if not leaf.value:
1324                 self.invisible.append(leaf)
1325         leaf.bracket_depth = self.depth
1326         if self.depth == 0:
1327             delim = is_split_before_delimiter(leaf, self.previous)
1328             if delim and self.previous is not None:
1329                 self.delimiters[id(self.previous)] = delim
1330             else:
1331                 delim = is_split_after_delimiter(leaf, self.previous)
1332                 if delim:
1333                     self.delimiters[id(leaf)] = delim
1334         if leaf.type in OPENING_BRACKETS:
1335             self.bracket_match[self.depth, BRACKET[leaf.type]] = leaf
1336             self.depth += 1
1337             if not leaf.value:
1338                 self.invisible.append(leaf)
1339         self.previous = leaf
1340         self.maybe_increment_lambda_arguments(leaf)
1341         self.maybe_increment_for_loop_variable(leaf)
1342
1343     def any_open_brackets(self) -> bool:
1344         """Return True if there is an yet unmatched open bracket on the line."""
1345         return bool(self.bracket_match)
1346
1347     def max_delimiter_priority(self, exclude: Iterable[LeafID] = ()) -> Priority:
1348         """Return the highest priority of a delimiter found on the line.
1349
1350         Values are consistent with what `is_split_*_delimiter()` return.
1351         Raises ValueError on no delimiters.
1352         """
1353         return max(v for k, v in self.delimiters.items() if k not in exclude)
1354
1355     def delimiter_count_with_priority(self, priority: Priority = 0) -> int:
1356         """Return the number of delimiters with the given `priority`.
1357
1358         If no `priority` is passed, defaults to max priority on the line.
1359         """
1360         if not self.delimiters:
1361             return 0
1362
1363         priority = priority or self.max_delimiter_priority()
1364         return sum(1 for p in self.delimiters.values() if p == priority)
1365
1366     def maybe_increment_for_loop_variable(self, leaf: Leaf) -> bool:
1367         """In a for loop, or comprehension, the variables are often unpacks.
1368
1369         To avoid splitting on the comma in this situation, increase the depth of
1370         tokens between `for` and `in`.
1371         """
1372         if leaf.type == token.NAME and leaf.value == "for":
1373             self.depth += 1
1374             self._for_loop_depths.append(self.depth)
1375             return True
1376
1377         return False
1378
1379     def maybe_decrement_after_for_loop_variable(self, leaf: Leaf) -> bool:
1380         """See `maybe_increment_for_loop_variable` above for explanation."""
1381         if (
1382             self._for_loop_depths
1383             and self._for_loop_depths[-1] == self.depth
1384             and leaf.type == token.NAME
1385             and leaf.value == "in"
1386         ):
1387             self.depth -= 1
1388             self._for_loop_depths.pop()
1389             return True
1390
1391         return False
1392
1393     def maybe_increment_lambda_arguments(self, leaf: Leaf) -> bool:
1394         """In a lambda expression, there might be more than one argument.
1395
1396         To avoid splitting on the comma in this situation, increase the depth of
1397         tokens between `lambda` and `:`.
1398         """
1399         if leaf.type == token.NAME and leaf.value == "lambda":
1400             self.depth += 1
1401             self._lambda_argument_depths.append(self.depth)
1402             return True
1403
1404         return False
1405
1406     def maybe_decrement_after_lambda_arguments(self, leaf: Leaf) -> bool:
1407         """See `maybe_increment_lambda_arguments` above for explanation."""
1408         if (
1409             self._lambda_argument_depths
1410             and self._lambda_argument_depths[-1] == self.depth
1411             and leaf.type == token.COLON
1412         ):
1413             self.depth -= 1
1414             self._lambda_argument_depths.pop()
1415             return True
1416
1417         return False
1418
1419     def get_open_lsqb(self) -> Optional[Leaf]:
1420         """Return the most recent opening square bracket (if any)."""
1421         return self.bracket_match.get((self.depth - 1, token.RSQB))
1422
1423
1424 @dataclass
1425 class Line:
1426     """Holds leaves and comments. Can be printed with `str(line)`."""
1427
1428     depth: int = 0
1429     leaves: List[Leaf] = field(default_factory=list)
1430     # keys ordered like `leaves`
1431     comments: Dict[LeafID, List[Leaf]] = field(default_factory=dict)
1432     bracket_tracker: BracketTracker = field(default_factory=BracketTracker)
1433     inside_brackets: bool = False
1434     should_explode: bool = False
1435
1436     def append(self, leaf: Leaf, preformatted: bool = False) -> None:
1437         """Add a new `leaf` to the end of the line.
1438
1439         Unless `preformatted` is True, the `leaf` will receive a new consistent
1440         whitespace prefix and metadata applied by :class:`BracketTracker`.
1441         Trailing commas are maybe removed, unpacked for loop variables are
1442         demoted from being delimiters.
1443
1444         Inline comments are put aside.
1445         """
1446         has_value = leaf.type in BRACKETS or bool(leaf.value.strip())
1447         if not has_value:
1448             return
1449
1450         if token.COLON == leaf.type and self.is_class_paren_empty:
1451             del self.leaves[-2:]
1452         if self.leaves and not preformatted:
1453             # Note: at this point leaf.prefix should be empty except for
1454             # imports, for which we only preserve newlines.
1455             leaf.prefix += whitespace(
1456                 leaf, complex_subscript=self.is_complex_subscript(leaf)
1457             )
1458         if self.inside_brackets or not preformatted:
1459             self.bracket_tracker.mark(leaf)
1460             if self.maybe_should_explode(leaf):
1461                 self.should_explode = True
1462         if not self.append_comment(leaf):
1463             self.leaves.append(leaf)
1464
1465     def append_safe(self, leaf: Leaf, preformatted: bool = False) -> None:
1466         """Like :func:`append()` but disallow invalid standalone comment structure.
1467
1468         Raises ValueError when any `leaf` is appended after a standalone comment
1469         or when a standalone comment is not the first leaf on the line.
1470         """
1471         if self.bracket_tracker.depth == 0:
1472             if self.is_comment:
1473                 raise ValueError("cannot append to standalone comments")
1474
1475             if self.leaves and leaf.type == STANDALONE_COMMENT:
1476                 raise ValueError(
1477                     "cannot append standalone comments to a populated line"
1478                 )
1479
1480         self.append(leaf, preformatted=preformatted)
1481
1482     @property
1483     def is_comment(self) -> bool:
1484         """Is this line a standalone comment?"""
1485         return len(self.leaves) == 1 and self.leaves[0].type == STANDALONE_COMMENT
1486
1487     @property
1488     def is_decorator(self) -> bool:
1489         """Is this line a decorator?"""
1490         return bool(self) and self.leaves[0].type == token.AT
1491
1492     @property
1493     def is_import(self) -> bool:
1494         """Is this an import line?"""
1495         return bool(self) and is_import(self.leaves[0])
1496
1497     @property
1498     def is_class(self) -> bool:
1499         """Is this line a class definition?"""
1500         return (
1501             bool(self)
1502             and self.leaves[0].type == token.NAME
1503             and self.leaves[0].value == "class"
1504         )
1505
1506     @property
1507     def is_stub_class(self) -> bool:
1508         """Is this line a class definition with a body consisting only of "..."?"""
1509         return self.is_class and self.leaves[-3:] == [
1510             Leaf(token.DOT, ".") for _ in range(3)
1511         ]
1512
1513     @property
1514     def is_def(self) -> bool:
1515         """Is this a function definition? (Also returns True for async defs.)"""
1516         try:
1517             first_leaf = self.leaves[0]
1518         except IndexError:
1519             return False
1520
1521         try:
1522             second_leaf: Optional[Leaf] = self.leaves[1]
1523         except IndexError:
1524             second_leaf = None
1525         return (first_leaf.type == token.NAME and first_leaf.value == "def") or (
1526             first_leaf.type == token.ASYNC
1527             and second_leaf is not None
1528             and second_leaf.type == token.NAME
1529             and second_leaf.value == "def"
1530         )
1531
1532     @property
1533     def is_class_paren_empty(self) -> bool:
1534         """Is this a class with no base classes but using parentheses?
1535
1536         Those are unnecessary and should be removed.
1537         """
1538         return (
1539             bool(self)
1540             and len(self.leaves) == 4
1541             and self.is_class
1542             and self.leaves[2].type == token.LPAR
1543             and self.leaves[2].value == "("
1544             and self.leaves[3].type == token.RPAR
1545             and self.leaves[3].value == ")"
1546         )
1547
1548     @property
1549     def is_triple_quoted_string(self) -> bool:
1550         """Is the line a triple quoted string?"""
1551         return (
1552             bool(self)
1553             and self.leaves[0].type == token.STRING
1554             and self.leaves[0].value.startswith(('"""', "'''"))
1555         )
1556
1557     def contains_standalone_comments(self, depth_limit: int = sys.maxsize) -> bool:
1558         """If so, needs to be split before emitting."""
1559         for leaf in self.leaves:
1560             if leaf.type == STANDALONE_COMMENT and leaf.bracket_depth <= depth_limit:
1561                 return True
1562
1563         return False
1564
1565     def contains_uncollapsable_type_comments(self) -> bool:
1566         ignored_ids = set()
1567         try:
1568             last_leaf = self.leaves[-1]
1569             ignored_ids.add(id(last_leaf))
1570             if last_leaf.type == token.COMMA or (
1571                 last_leaf.type == token.RPAR and not last_leaf.value
1572             ):
1573                 # When trailing commas or optional parens are inserted by Black for
1574                 # consistency, comments after the previous last element are not moved
1575                 # (they don't have to, rendering will still be correct).  So we ignore
1576                 # trailing commas and invisible.
1577                 last_leaf = self.leaves[-2]
1578                 ignored_ids.add(id(last_leaf))
1579         except IndexError:
1580             return False
1581
1582         # A type comment is uncollapsable if it is attached to a leaf
1583         # that isn't at the end of the line (since that could cause it
1584         # to get associated to a different argument) or if there are
1585         # comments before it (since that could cause it to get hidden
1586         # behind a comment.
1587         comment_seen = False
1588         for leaf_id, comments in self.comments.items():
1589             for comment in comments:
1590                 if is_type_comment(comment):
1591                     if comment_seen or (
1592                         not is_type_comment(comment, " ignore")
1593                         and leaf_id not in ignored_ids
1594                     ):
1595                         return True
1596
1597                 comment_seen = True
1598
1599         return False
1600
1601     def contains_unsplittable_type_ignore(self) -> bool:
1602         if not self.leaves:
1603             return False
1604
1605         # If a 'type: ignore' is attached to the end of a line, we
1606         # can't split the line, because we can't know which of the
1607         # subexpressions the ignore was meant to apply to.
1608         #
1609         # We only want this to apply to actual physical lines from the
1610         # original source, though: we don't want the presence of a
1611         # 'type: ignore' at the end of a multiline expression to
1612         # justify pushing it all onto one line. Thus we
1613         # (unfortunately) need to check the actual source lines and
1614         # only report an unsplittable 'type: ignore' if this line was
1615         # one line in the original code.
1616
1617         # Grab the first and last line numbers, skipping generated leaves
1618         first_line = next((leaf.lineno for leaf in self.leaves if leaf.lineno != 0), 0)
1619         last_line = next(
1620             (leaf.lineno for leaf in reversed(self.leaves) if leaf.lineno != 0), 0
1621         )
1622
1623         if first_line == last_line:
1624             # We look at the last two leaves since a comma or an
1625             # invisible paren could have been added at the end of the
1626             # line.
1627             for node in self.leaves[-2:]:
1628                 for comment in self.comments.get(id(node), []):
1629                     if is_type_comment(comment, " ignore"):
1630                         return True
1631
1632         return False
1633
1634     def contains_multiline_strings(self) -> bool:
1635         return any(is_multiline_string(leaf) for leaf in self.leaves)
1636
1637     def maybe_should_explode(self, closing: Leaf) -> bool:
1638         """Return True if this line should explode (always be split), that is when:
1639         - there's a trailing comma here; and
1640         - it's not a one-tuple.
1641         """
1642         if not (
1643             closing.type in CLOSING_BRACKETS
1644             and self.leaves
1645             and self.leaves[-1].type == token.COMMA
1646         ):
1647             return False
1648
1649         if closing.type in {token.RBRACE, token.RSQB}:
1650             return True
1651
1652         if self.is_import:
1653             return True
1654
1655         if not is_one_tuple_between(closing.opening_bracket, closing, self.leaves):
1656             return True
1657
1658         return False
1659
1660     def append_comment(self, comment: Leaf) -> bool:
1661         """Add an inline or standalone comment to the line."""
1662         if (
1663             comment.type == STANDALONE_COMMENT
1664             and self.bracket_tracker.any_open_brackets()
1665         ):
1666             comment.prefix = ""
1667             return False
1668
1669         if comment.type != token.COMMENT:
1670             return False
1671
1672         if not self.leaves:
1673             comment.type = STANDALONE_COMMENT
1674             comment.prefix = ""
1675             return False
1676
1677         last_leaf = self.leaves[-1]
1678         if (
1679             last_leaf.type == token.RPAR
1680             and not last_leaf.value
1681             and last_leaf.parent
1682             and len(list(last_leaf.parent.leaves())) <= 3
1683             and not is_type_comment(comment)
1684         ):
1685             # Comments on an optional parens wrapping a single leaf should belong to
1686             # the wrapped node except if it's a type comment. Pinning the comment like
1687             # this avoids unstable formatting caused by comment migration.
1688             if len(self.leaves) < 2:
1689                 comment.type = STANDALONE_COMMENT
1690                 comment.prefix = ""
1691                 return False
1692
1693             last_leaf = self.leaves[-2]
1694         self.comments.setdefault(id(last_leaf), []).append(comment)
1695         return True
1696
1697     def comments_after(self, leaf: Leaf) -> List[Leaf]:
1698         """Generate comments that should appear directly after `leaf`."""
1699         return self.comments.get(id(leaf), [])
1700
1701     def remove_trailing_comma(self) -> None:
1702         """Remove the trailing comma and moves the comments attached to it."""
1703         trailing_comma = self.leaves.pop()
1704         trailing_comma_comments = self.comments.pop(id(trailing_comma), [])
1705         self.comments.setdefault(id(self.leaves[-1]), []).extend(
1706             trailing_comma_comments
1707         )
1708
1709     def is_complex_subscript(self, leaf: Leaf) -> bool:
1710         """Return True iff `leaf` is part of a slice with non-trivial exprs."""
1711         open_lsqb = self.bracket_tracker.get_open_lsqb()
1712         if open_lsqb is None:
1713             return False
1714
1715         subscript_start = open_lsqb.next_sibling
1716
1717         if isinstance(subscript_start, Node):
1718             if subscript_start.type == syms.listmaker:
1719                 return False
1720
1721             if subscript_start.type == syms.subscriptlist:
1722                 subscript_start = child_towards(subscript_start, leaf)
1723         return subscript_start is not None and any(
1724             n.type in TEST_DESCENDANTS for n in subscript_start.pre_order()
1725         )
1726
1727     def clone(self) -> "Line":
1728         return Line(
1729             depth=self.depth,
1730             inside_brackets=self.inside_brackets,
1731             should_explode=self.should_explode,
1732         )
1733
1734     def __str__(self) -> str:
1735         """Render the line."""
1736         if not self:
1737             return "\n"
1738
1739         indent = "    " * self.depth
1740         leaves = iter(self.leaves)
1741         first = next(leaves)
1742         res = f"{first.prefix}{indent}{first.value}"
1743         for leaf in leaves:
1744             res += str(leaf)
1745         for comment in itertools.chain.from_iterable(self.comments.values()):
1746             res += str(comment)
1747
1748         return res + "\n"
1749
1750     def __bool__(self) -> bool:
1751         """Return True if the line has leaves or comments."""
1752         return bool(self.leaves or self.comments)
1753
1754
1755 @dataclass
1756 class EmptyLineTracker:
1757     """Provides a stateful method that returns the number of potential extra
1758     empty lines needed before and after the currently processed line.
1759
1760     Note: this tracker works on lines that haven't been split yet.  It assumes
1761     the prefix of the first leaf consists of optional newlines.  Those newlines
1762     are consumed by `maybe_empty_lines()` and included in the computation.
1763     """
1764
1765     is_pyi: bool = False
1766     previous_line: Optional[Line] = None
1767     previous_after: int = 0
1768     previous_defs: List[int] = field(default_factory=list)
1769
1770     def maybe_empty_lines(self, current_line: Line) -> Tuple[int, int]:
1771         """Return the number of extra empty lines before and after the `current_line`.
1772
1773         This is for separating `def`, `async def` and `class` with extra empty
1774         lines (two on module-level).
1775         """
1776         before, after = self._maybe_empty_lines(current_line)
1777         before = (
1778             # Black should not insert empty lines at the beginning
1779             # of the file
1780             0
1781             if self.previous_line is None
1782             else before - self.previous_after
1783         )
1784         self.previous_after = after
1785         self.previous_line = current_line
1786         return before, after
1787
1788     def _maybe_empty_lines(self, current_line: Line) -> Tuple[int, int]:
1789         max_allowed = 1
1790         if current_line.depth == 0:
1791             max_allowed = 1 if self.is_pyi else 2
1792         if current_line.leaves:
1793             # Consume the first leaf's extra newlines.
1794             first_leaf = current_line.leaves[0]
1795             before = first_leaf.prefix.count("\n")
1796             before = min(before, max_allowed)
1797             first_leaf.prefix = ""
1798         else:
1799             before = 0
1800         depth = current_line.depth
1801         while self.previous_defs and self.previous_defs[-1] >= depth:
1802             self.previous_defs.pop()
1803             if self.is_pyi:
1804                 before = 0 if depth else 1
1805             else:
1806                 before = 1 if depth else 2
1807         if current_line.is_decorator or current_line.is_def or current_line.is_class:
1808             return self._maybe_empty_lines_for_class_or_def(current_line, before)
1809
1810         if (
1811             self.previous_line
1812             and self.previous_line.is_import
1813             and not current_line.is_import
1814             and depth == self.previous_line.depth
1815         ):
1816             return (before or 1), 0
1817
1818         if (
1819             self.previous_line
1820             and self.previous_line.is_class
1821             and current_line.is_triple_quoted_string
1822         ):
1823             return before, 1
1824
1825         return before, 0
1826
1827     def _maybe_empty_lines_for_class_or_def(
1828         self, current_line: Line, before: int
1829     ) -> Tuple[int, int]:
1830         if not current_line.is_decorator:
1831             self.previous_defs.append(current_line.depth)
1832         if self.previous_line is None:
1833             # Don't insert empty lines before the first line in the file.
1834             return 0, 0
1835
1836         if self.previous_line.is_decorator:
1837             return 0, 0
1838
1839         if self.previous_line.depth < current_line.depth and (
1840             self.previous_line.is_class or self.previous_line.is_def
1841         ):
1842             return 0, 0
1843
1844         if (
1845             self.previous_line.is_comment
1846             and self.previous_line.depth == current_line.depth
1847             and before == 0
1848         ):
1849             return 0, 0
1850
1851         if self.is_pyi:
1852             if self.previous_line.depth > current_line.depth:
1853                 newlines = 1
1854             elif current_line.is_class or self.previous_line.is_class:
1855                 if current_line.is_stub_class and self.previous_line.is_stub_class:
1856                     # No blank line between classes with an empty body
1857                     newlines = 0
1858                 else:
1859                     newlines = 1
1860             elif current_line.is_def and not self.previous_line.is_def:
1861                 # Blank line between a block of functions and a block of non-functions
1862                 newlines = 1
1863             else:
1864                 newlines = 0
1865         else:
1866             newlines = 2
1867         if current_line.depth and newlines:
1868             newlines -= 1
1869         return newlines, 0
1870
1871
1872 @dataclass
1873 class LineGenerator(Visitor[Line]):
1874     """Generates reformatted Line objects.  Empty lines are not emitted.
1875
1876     Note: destroys the tree it's visiting by mutating prefixes of its leaves
1877     in ways that will no longer stringify to valid Python code on the tree.
1878     """
1879
1880     is_pyi: bool = False
1881     normalize_strings: bool = True
1882     current_line: Line = field(default_factory=Line)
1883     remove_u_prefix: bool = False
1884
1885     def line(self, indent: int = 0) -> Iterator[Line]:
1886         """Generate a line.
1887
1888         If the line is empty, only emit if it makes sense.
1889         If the line is too long, split it first and then generate.
1890
1891         If any lines were generated, set up a new current_line.
1892         """
1893         if not self.current_line:
1894             self.current_line.depth += indent
1895             return  # Line is empty, don't emit. Creating a new one unnecessary.
1896
1897         complete_line = self.current_line
1898         self.current_line = Line(depth=complete_line.depth + indent)
1899         yield complete_line
1900
1901     def visit_default(self, node: LN) -> Iterator[Line]:
1902         """Default `visit_*()` implementation. Recurses to children of `node`."""
1903         if isinstance(node, Leaf):
1904             any_open_brackets = self.current_line.bracket_tracker.any_open_brackets()
1905             for comment in generate_comments(node):
1906                 if any_open_brackets:
1907                     # any comment within brackets is subject to splitting
1908                     self.current_line.append(comment)
1909                 elif comment.type == token.COMMENT:
1910                     # regular trailing comment
1911                     self.current_line.append(comment)
1912                     yield from self.line()
1913
1914                 else:
1915                     # regular standalone comment
1916                     yield from self.line()
1917
1918                     self.current_line.append(comment)
1919                     yield from self.line()
1920
1921             normalize_prefix(node, inside_brackets=any_open_brackets)
1922             if self.normalize_strings and node.type == token.STRING:
1923                 normalize_string_prefix(node, remove_u_prefix=self.remove_u_prefix)
1924                 normalize_string_quotes(node)
1925             if node.type == token.NUMBER:
1926                 normalize_numeric_literal(node)
1927             if node.type not in WHITESPACE:
1928                 self.current_line.append(node)
1929         yield from super().visit_default(node)
1930
1931     def visit_INDENT(self, node: Leaf) -> Iterator[Line]:
1932         """Increase indentation level, maybe yield a line."""
1933         # In blib2to3 INDENT never holds comments.
1934         yield from self.line(+1)
1935         yield from self.visit_default(node)
1936
1937     def visit_DEDENT(self, node: Leaf) -> Iterator[Line]:
1938         """Decrease indentation level, maybe yield a line."""
1939         # The current line might still wait for trailing comments.  At DEDENT time
1940         # there won't be any (they would be prefixes on the preceding NEWLINE).
1941         # Emit the line then.
1942         yield from self.line()
1943
1944         # While DEDENT has no value, its prefix may contain standalone comments
1945         # that belong to the current indentation level.  Get 'em.
1946         yield from self.visit_default(node)
1947
1948         # Finally, emit the dedent.
1949         yield from self.line(-1)
1950
1951     def visit_stmt(
1952         self, node: Node, keywords: Set[str], parens: Set[str]
1953     ) -> Iterator[Line]:
1954         """Visit a statement.
1955
1956         This implementation is shared for `if`, `while`, `for`, `try`, `except`,
1957         `def`, `with`, `class`, `assert` and assignments.
1958
1959         The relevant Python language `keywords` for a given statement will be
1960         NAME leaves within it. This methods puts those on a separate line.
1961
1962         `parens` holds a set of string leaf values immediately after which
1963         invisible parens should be put.
1964         """
1965         normalize_invisible_parens(node, parens_after=parens)
1966         for child in node.children:
1967             if child.type == token.NAME and child.value in keywords:  # type: ignore
1968                 yield from self.line()
1969
1970             yield from self.visit(child)
1971
1972     def visit_suite(self, node: Node) -> Iterator[Line]:
1973         """Visit a suite."""
1974         if self.is_pyi and is_stub_suite(node):
1975             yield from self.visit(node.children[2])
1976         else:
1977             yield from self.visit_default(node)
1978
1979     def visit_simple_stmt(self, node: Node) -> Iterator[Line]:
1980         """Visit a statement without nested statements."""
1981         is_suite_like = node.parent and node.parent.type in STATEMENT
1982         if is_suite_like:
1983             if self.is_pyi and is_stub_body(node):
1984                 yield from self.visit_default(node)
1985             else:
1986                 yield from self.line(+1)
1987                 yield from self.visit_default(node)
1988                 yield from self.line(-1)
1989
1990         else:
1991             if not self.is_pyi or not node.parent or not is_stub_suite(node.parent):
1992                 yield from self.line()
1993             yield from self.visit_default(node)
1994
1995     def visit_async_stmt(self, node: Node) -> Iterator[Line]:
1996         """Visit `async def`, `async for`, `async with`."""
1997         yield from self.line()
1998
1999         children = iter(node.children)
2000         for child in children:
2001             yield from self.visit(child)
2002
2003             if child.type == token.ASYNC:
2004                 break
2005
2006         internal_stmt = next(children)
2007         for child in internal_stmt.children:
2008             yield from self.visit(child)
2009
2010     def visit_decorators(self, node: Node) -> Iterator[Line]:
2011         """Visit decorators."""
2012         for child in node.children:
2013             yield from self.line()
2014             yield from self.visit(child)
2015
2016     def visit_SEMI(self, leaf: Leaf) -> Iterator[Line]:
2017         """Remove a semicolon and put the other statement on a separate line."""
2018         yield from self.line()
2019
2020     def visit_ENDMARKER(self, leaf: Leaf) -> Iterator[Line]:
2021         """End of file. Process outstanding comments and end with a newline."""
2022         yield from self.visit_default(leaf)
2023         yield from self.line()
2024
2025     def visit_STANDALONE_COMMENT(self, leaf: Leaf) -> Iterator[Line]:
2026         if not self.current_line.bracket_tracker.any_open_brackets():
2027             yield from self.line()
2028         yield from self.visit_default(leaf)
2029
2030     def visit_factor(self, node: Node) -> Iterator[Line]:
2031         """Force parentheses between a unary op and a binary power:
2032
2033         -2 ** 8 -> -(2 ** 8)
2034         """
2035         _operator, operand = node.children
2036         if (
2037             operand.type == syms.power
2038             and len(operand.children) == 3
2039             and operand.children[1].type == token.DOUBLESTAR
2040         ):
2041             lpar = Leaf(token.LPAR, "(")
2042             rpar = Leaf(token.RPAR, ")")
2043             index = operand.remove() or 0
2044             node.insert_child(index, Node(syms.atom, [lpar, operand, rpar]))
2045         yield from self.visit_default(node)
2046
2047     def visit_STRING(self, leaf: Leaf) -> Iterator[Line]:
2048         if is_docstring(leaf) and "\\\n" not in leaf.value:
2049             # We're ignoring docstrings with backslash newline escapes because changing
2050             # indentation of those changes the AST representation of the code.
2051             prefix = get_string_prefix(leaf.value)
2052             lead_len = len(prefix) + 3
2053             tail_len = -3
2054             indent = " " * 4 * self.current_line.depth
2055             docstring = fix_docstring(leaf.value[lead_len:tail_len], indent)
2056             if docstring:
2057                 if leaf.value[lead_len - 1] == docstring[0]:
2058                     docstring = " " + docstring
2059                 if leaf.value[tail_len + 1] == docstring[-1]:
2060                     docstring = docstring + " "
2061             leaf.value = leaf.value[0:lead_len] + docstring + leaf.value[tail_len:]
2062
2063         yield from self.visit_default(leaf)
2064
2065     def __post_init__(self) -> None:
2066         """You are in a twisty little maze of passages."""
2067         v = self.visit_stmt
2068         Ø: Set[str] = set()
2069         self.visit_assert_stmt = partial(v, keywords={"assert"}, parens={"assert", ","})
2070         self.visit_if_stmt = partial(
2071             v, keywords={"if", "else", "elif"}, parens={"if", "elif"}
2072         )
2073         self.visit_while_stmt = partial(v, keywords={"while", "else"}, parens={"while"})
2074         self.visit_for_stmt = partial(v, keywords={"for", "else"}, parens={"for", "in"})
2075         self.visit_try_stmt = partial(
2076             v, keywords={"try", "except", "else", "finally"}, parens=Ø
2077         )
2078         self.visit_except_clause = partial(v, keywords={"except"}, parens=Ø)
2079         self.visit_with_stmt = partial(v, keywords={"with"}, parens=Ø)
2080         self.visit_funcdef = partial(v, keywords={"def"}, parens=Ø)
2081         self.visit_classdef = partial(v, keywords={"class"}, parens=Ø)
2082         self.visit_expr_stmt = partial(v, keywords=Ø, parens=ASSIGNMENTS)
2083         self.visit_return_stmt = partial(v, keywords={"return"}, parens={"return"})
2084         self.visit_import_from = partial(v, keywords=Ø, parens={"import"})
2085         self.visit_del_stmt = partial(v, keywords=Ø, parens={"del"})
2086         self.visit_async_funcdef = self.visit_async_stmt
2087         self.visit_decorated = self.visit_decorators
2088
2089
2090 IMPLICIT_TUPLE = {syms.testlist, syms.testlist_star_expr, syms.exprlist}
2091 BRACKET = {token.LPAR: token.RPAR, token.LSQB: token.RSQB, token.LBRACE: token.RBRACE}
2092 OPENING_BRACKETS = set(BRACKET.keys())
2093 CLOSING_BRACKETS = set(BRACKET.values())
2094 BRACKETS = OPENING_BRACKETS | CLOSING_BRACKETS
2095 ALWAYS_NO_SPACE = CLOSING_BRACKETS | {token.COMMA, STANDALONE_COMMENT}
2096
2097
2098 def whitespace(leaf: Leaf, *, complex_subscript: bool) -> str:  # noqa: C901
2099     """Return whitespace prefix if needed for the given `leaf`.
2100
2101     `complex_subscript` signals whether the given leaf is part of a subscription
2102     which has non-trivial arguments, like arithmetic expressions or function calls.
2103     """
2104     NO = ""
2105     SPACE = " "
2106     DOUBLESPACE = "  "
2107     t = leaf.type
2108     p = leaf.parent
2109     v = leaf.value
2110     if t in ALWAYS_NO_SPACE:
2111         return NO
2112
2113     if t == token.COMMENT:
2114         return DOUBLESPACE
2115
2116     assert p is not None, f"INTERNAL ERROR: hand-made leaf without parent: {leaf!r}"
2117     if t == token.COLON and p.type not in {
2118         syms.subscript,
2119         syms.subscriptlist,
2120         syms.sliceop,
2121     }:
2122         return NO
2123
2124     prev = leaf.prev_sibling
2125     if not prev:
2126         prevp = preceding_leaf(p)
2127         if not prevp or prevp.type in OPENING_BRACKETS:
2128             return NO
2129
2130         if t == token.COLON:
2131             if prevp.type == token.COLON:
2132                 return NO
2133
2134             elif prevp.type != token.COMMA and not complex_subscript:
2135                 return NO
2136
2137             return SPACE
2138
2139         if prevp.type == token.EQUAL:
2140             if prevp.parent:
2141                 if prevp.parent.type in {
2142                     syms.arglist,
2143                     syms.argument,
2144                     syms.parameters,
2145                     syms.varargslist,
2146                 }:
2147                     return NO
2148
2149                 elif prevp.parent.type == syms.typedargslist:
2150                     # A bit hacky: if the equal sign has whitespace, it means we
2151                     # previously found it's a typed argument.  So, we're using
2152                     # that, too.
2153                     return prevp.prefix
2154
2155         elif prevp.type in VARARGS_SPECIALS:
2156             if is_vararg(prevp, within=VARARGS_PARENTS | UNPACKING_PARENTS):
2157                 return NO
2158
2159         elif prevp.type == token.COLON:
2160             if prevp.parent and prevp.parent.type in {syms.subscript, syms.sliceop}:
2161                 return SPACE if complex_subscript else NO
2162
2163         elif (
2164             prevp.parent
2165             and prevp.parent.type == syms.factor
2166             and prevp.type in MATH_OPERATORS
2167         ):
2168             return NO
2169
2170         elif (
2171             prevp.type == token.RIGHTSHIFT
2172             and prevp.parent
2173             and prevp.parent.type == syms.shift_expr
2174             and prevp.prev_sibling
2175             and prevp.prev_sibling.type == token.NAME
2176             and prevp.prev_sibling.value == "print"  # type: ignore
2177         ):
2178             # Python 2 print chevron
2179             return NO
2180
2181     elif prev.type in OPENING_BRACKETS:
2182         return NO
2183
2184     if p.type in {syms.parameters, syms.arglist}:
2185         # untyped function signatures or calls
2186         if not prev or prev.type != token.COMMA:
2187             return NO
2188
2189     elif p.type == syms.varargslist:
2190         # lambdas
2191         if prev and prev.type != token.COMMA:
2192             return NO
2193
2194     elif p.type == syms.typedargslist:
2195         # typed function signatures
2196         if not prev:
2197             return NO
2198
2199         if t == token.EQUAL:
2200             if prev.type != syms.tname:
2201                 return NO
2202
2203         elif prev.type == token.EQUAL:
2204             # A bit hacky: if the equal sign has whitespace, it means we
2205             # previously found it's a typed argument.  So, we're using that, too.
2206             return prev.prefix
2207
2208         elif prev.type != token.COMMA:
2209             return NO
2210
2211     elif p.type == syms.tname:
2212         # type names
2213         if not prev:
2214             prevp = preceding_leaf(p)
2215             if not prevp or prevp.type != token.COMMA:
2216                 return NO
2217
2218     elif p.type == syms.trailer:
2219         # attributes and calls
2220         if t == token.LPAR or t == token.RPAR:
2221             return NO
2222
2223         if not prev:
2224             if t == token.DOT:
2225                 prevp = preceding_leaf(p)
2226                 if not prevp or prevp.type != token.NUMBER:
2227                     return NO
2228
2229             elif t == token.LSQB:
2230                 return NO
2231
2232         elif prev.type != token.COMMA:
2233             return NO
2234
2235     elif p.type == syms.argument:
2236         # single argument
2237         if t == token.EQUAL:
2238             return NO
2239
2240         if not prev:
2241             prevp = preceding_leaf(p)
2242             if not prevp or prevp.type == token.LPAR:
2243                 return NO
2244
2245         elif prev.type in {token.EQUAL} | VARARGS_SPECIALS:
2246             return NO
2247
2248     elif p.type == syms.decorator:
2249         # decorators
2250         return NO
2251
2252     elif p.type == syms.dotted_name:
2253         if prev:
2254             return NO
2255
2256         prevp = preceding_leaf(p)
2257         if not prevp or prevp.type == token.AT or prevp.type == token.DOT:
2258             return NO
2259
2260     elif p.type == syms.classdef:
2261         if t == token.LPAR:
2262             return NO
2263
2264         if prev and prev.type == token.LPAR:
2265             return NO
2266
2267     elif p.type in {syms.subscript, syms.sliceop}:
2268         # indexing
2269         if not prev:
2270             assert p.parent is not None, "subscripts are always parented"
2271             if p.parent.type == syms.subscriptlist:
2272                 return SPACE
2273
2274             return NO
2275
2276         elif not complex_subscript:
2277             return NO
2278
2279     elif p.type == syms.atom:
2280         if prev and t == token.DOT:
2281             # dots, but not the first one.
2282             return NO
2283
2284     elif p.type == syms.dictsetmaker:
2285         # dict unpacking
2286         if prev and prev.type == token.DOUBLESTAR:
2287             return NO
2288
2289     elif p.type in {syms.factor, syms.star_expr}:
2290         # unary ops
2291         if not prev:
2292             prevp = preceding_leaf(p)
2293             if not prevp or prevp.type in OPENING_BRACKETS:
2294                 return NO
2295
2296             prevp_parent = prevp.parent
2297             assert prevp_parent is not None
2298             if prevp.type == token.COLON and prevp_parent.type in {
2299                 syms.subscript,
2300                 syms.sliceop,
2301             }:
2302                 return NO
2303
2304             elif prevp.type == token.EQUAL and prevp_parent.type == syms.argument:
2305                 return NO
2306
2307         elif t in {token.NAME, token.NUMBER, token.STRING}:
2308             return NO
2309
2310     elif p.type == syms.import_from:
2311         if t == token.DOT:
2312             if prev and prev.type == token.DOT:
2313                 return NO
2314
2315         elif t == token.NAME:
2316             if v == "import":
2317                 return SPACE
2318
2319             if prev and prev.type == token.DOT:
2320                 return NO
2321
2322     elif p.type == syms.sliceop:
2323         return NO
2324
2325     return SPACE
2326
2327
2328 def preceding_leaf(node: Optional[LN]) -> Optional[Leaf]:
2329     """Return the first leaf that precedes `node`, if any."""
2330     while node:
2331         res = node.prev_sibling
2332         if res:
2333             if isinstance(res, Leaf):
2334                 return res
2335
2336             try:
2337                 return list(res.leaves())[-1]
2338
2339             except IndexError:
2340                 return None
2341
2342         node = node.parent
2343     return None
2344
2345
2346 def prev_siblings_are(node: Optional[LN], tokens: List[Optional[NodeType]]) -> bool:
2347     """Return if the `node` and its previous siblings match types against the provided
2348     list of tokens; the provided `node`has its type matched against the last element in
2349     the list.  `None` can be used as the first element to declare that the start of the
2350     list is anchored at the start of its parent's children."""
2351     if not tokens:
2352         return True
2353     if tokens[-1] is None:
2354         return node is None
2355     if not node:
2356         return False
2357     if node.type != tokens[-1]:
2358         return False
2359     return prev_siblings_are(node.prev_sibling, tokens[:-1])
2360
2361
2362 def child_towards(ancestor: Node, descendant: LN) -> Optional[LN]:
2363     """Return the child of `ancestor` that contains `descendant`."""
2364     node: Optional[LN] = descendant
2365     while node and node.parent != ancestor:
2366         node = node.parent
2367     return node
2368
2369
2370 def container_of(leaf: Leaf) -> LN:
2371     """Return `leaf` or one of its ancestors that is the topmost container of it.
2372
2373     By "container" we mean a node where `leaf` is the very first child.
2374     """
2375     same_prefix = leaf.prefix
2376     container: LN = leaf
2377     while container:
2378         parent = container.parent
2379         if parent is None:
2380             break
2381
2382         if parent.children[0].prefix != same_prefix:
2383             break
2384
2385         if parent.type == syms.file_input:
2386             break
2387
2388         if parent.prev_sibling is not None and parent.prev_sibling.type in BRACKETS:
2389             break
2390
2391         container = parent
2392     return container
2393
2394
2395 def is_split_after_delimiter(leaf: Leaf, previous: Optional[Leaf] = None) -> Priority:
2396     """Return the priority of the `leaf` delimiter, given a line break after it.
2397
2398     The delimiter priorities returned here are from those delimiters that would
2399     cause a line break after themselves.
2400
2401     Higher numbers are higher priority.
2402     """
2403     if leaf.type == token.COMMA:
2404         return COMMA_PRIORITY
2405
2406     return 0
2407
2408
2409 def is_split_before_delimiter(leaf: Leaf, previous: Optional[Leaf] = None) -> Priority:
2410     """Return the priority of the `leaf` delimiter, given a line break before it.
2411
2412     The delimiter priorities returned here are from those delimiters that would
2413     cause a line break before themselves.
2414
2415     Higher numbers are higher priority.
2416     """
2417     if is_vararg(leaf, within=VARARGS_PARENTS | UNPACKING_PARENTS):
2418         # * and ** might also be MATH_OPERATORS but in this case they are not.
2419         # Don't treat them as a delimiter.
2420         return 0
2421
2422     if (
2423         leaf.type == token.DOT
2424         and leaf.parent
2425         and leaf.parent.type not in {syms.import_from, syms.dotted_name}
2426         and (previous is None or previous.type in CLOSING_BRACKETS)
2427     ):
2428         return DOT_PRIORITY
2429
2430     if (
2431         leaf.type in MATH_OPERATORS
2432         and leaf.parent
2433         and leaf.parent.type not in {syms.factor, syms.star_expr}
2434     ):
2435         return MATH_PRIORITIES[leaf.type]
2436
2437     if leaf.type in COMPARATORS:
2438         return COMPARATOR_PRIORITY
2439
2440     if (
2441         leaf.type == token.STRING
2442         and previous is not None
2443         and previous.type == token.STRING
2444     ):
2445         return STRING_PRIORITY
2446
2447     if leaf.type not in {token.NAME, token.ASYNC}:
2448         return 0
2449
2450     if (
2451         leaf.value == "for"
2452         and leaf.parent
2453         and leaf.parent.type in {syms.comp_for, syms.old_comp_for}
2454         or leaf.type == token.ASYNC
2455     ):
2456         if (
2457             not isinstance(leaf.prev_sibling, Leaf)
2458             or leaf.prev_sibling.value != "async"
2459         ):
2460             return COMPREHENSION_PRIORITY
2461
2462     if (
2463         leaf.value == "if"
2464         and leaf.parent
2465         and leaf.parent.type in {syms.comp_if, syms.old_comp_if}
2466     ):
2467         return COMPREHENSION_PRIORITY
2468
2469     if leaf.value in {"if", "else"} and leaf.parent and leaf.parent.type == syms.test:
2470         return TERNARY_PRIORITY
2471
2472     if leaf.value == "is":
2473         return COMPARATOR_PRIORITY
2474
2475     if (
2476         leaf.value == "in"
2477         and leaf.parent
2478         and leaf.parent.type in {syms.comp_op, syms.comparison}
2479         and not (
2480             previous is not None
2481             and previous.type == token.NAME
2482             and previous.value == "not"
2483         )
2484     ):
2485         return COMPARATOR_PRIORITY
2486
2487     if (
2488         leaf.value == "not"
2489         and leaf.parent
2490         and leaf.parent.type == syms.comp_op
2491         and not (
2492             previous is not None
2493             and previous.type == token.NAME
2494             and previous.value == "is"
2495         )
2496     ):
2497         return COMPARATOR_PRIORITY
2498
2499     if leaf.value in LOGIC_OPERATORS and leaf.parent:
2500         return LOGIC_PRIORITY
2501
2502     return 0
2503
2504
2505 FMT_OFF = {"# fmt: off", "# fmt:off", "# yapf: disable"}
2506 FMT_ON = {"# fmt: on", "# fmt:on", "# yapf: enable"}
2507
2508
2509 def generate_comments(leaf: LN) -> Iterator[Leaf]:
2510     """Clean the prefix of the `leaf` and generate comments from it, if any.
2511
2512     Comments in lib2to3 are shoved into the whitespace prefix.  This happens
2513     in `pgen2/driver.py:Driver.parse_tokens()`.  This was a brilliant implementation
2514     move because it does away with modifying the grammar to include all the
2515     possible places in which comments can be placed.
2516
2517     The sad consequence for us though is that comments don't "belong" anywhere.
2518     This is why this function generates simple parentless Leaf objects for
2519     comments.  We simply don't know what the correct parent should be.
2520
2521     No matter though, we can live without this.  We really only need to
2522     differentiate between inline and standalone comments.  The latter don't
2523     share the line with any code.
2524
2525     Inline comments are emitted as regular token.COMMENT leaves.  Standalone
2526     are emitted with a fake STANDALONE_COMMENT token identifier.
2527     """
2528     for pc in list_comments(leaf.prefix, is_endmarker=leaf.type == token.ENDMARKER):
2529         yield Leaf(pc.type, pc.value, prefix="\n" * pc.newlines)
2530
2531
2532 @dataclass
2533 class ProtoComment:
2534     """Describes a piece of syntax that is a comment.
2535
2536     It's not a :class:`blib2to3.pytree.Leaf` so that:
2537
2538     * it can be cached (`Leaf` objects should not be reused more than once as
2539       they store their lineno, column, prefix, and parent information);
2540     * `newlines` and `consumed` fields are kept separate from the `value`. This
2541       simplifies handling of special marker comments like ``# fmt: off/on``.
2542     """
2543
2544     type: int  # token.COMMENT or STANDALONE_COMMENT
2545     value: str  # content of the comment
2546     newlines: int  # how many newlines before the comment
2547     consumed: int  # how many characters of the original leaf's prefix did we consume
2548
2549
2550 @lru_cache(maxsize=4096)
2551 def list_comments(prefix: str, *, is_endmarker: bool) -> List[ProtoComment]:
2552     """Return a list of :class:`ProtoComment` objects parsed from the given `prefix`."""
2553     result: List[ProtoComment] = []
2554     if not prefix or "#" not in prefix:
2555         return result
2556
2557     consumed = 0
2558     nlines = 0
2559     ignored_lines = 0
2560     for index, line in enumerate(prefix.split("\n")):
2561         consumed += len(line) + 1  # adding the length of the split '\n'
2562         line = line.lstrip()
2563         if not line:
2564             nlines += 1
2565         if not line.startswith("#"):
2566             # Escaped newlines outside of a comment are not really newlines at
2567             # all. We treat a single-line comment following an escaped newline
2568             # as a simple trailing comment.
2569             if line.endswith("\\"):
2570                 ignored_lines += 1
2571             continue
2572
2573         if index == ignored_lines and not is_endmarker:
2574             comment_type = token.COMMENT  # simple trailing comment
2575         else:
2576             comment_type = STANDALONE_COMMENT
2577         comment = make_comment(line)
2578         result.append(
2579             ProtoComment(
2580                 type=comment_type, value=comment, newlines=nlines, consumed=consumed
2581             )
2582         )
2583         nlines = 0
2584     return result
2585
2586
2587 def make_comment(content: str) -> str:
2588     """Return a consistently formatted comment from the given `content` string.
2589
2590     All comments (except for "##", "#!", "#:", '#'", "#%%") should have a single
2591     space between the hash sign and the content.
2592
2593     If `content` didn't start with a hash sign, one is provided.
2594     """
2595     content = content.rstrip()
2596     if not content:
2597         return "#"
2598
2599     if content[0] == "#":
2600         content = content[1:]
2601     if content and content[0] not in " !:#'%":
2602         content = " " + content
2603     return "#" + content
2604
2605
2606 def transform_line(
2607     line: Line, mode: Mode, features: Collection[Feature] = ()
2608 ) -> Iterator[Line]:
2609     """Transform a `line`, potentially splitting it into many lines.
2610
2611     They should fit in the allotted `line_length` but might not be able to.
2612
2613     `features` are syntactical features that may be used in the output.
2614     """
2615     if line.is_comment:
2616         yield line
2617         return
2618
2619     line_str = line_to_string(line)
2620
2621     def init_st(ST: Type[StringTransformer]) -> StringTransformer:
2622         """Initialize StringTransformer"""
2623         return ST(mode.line_length, mode.string_normalization)
2624
2625     string_merge = init_st(StringMerger)
2626     string_paren_strip = init_st(StringParenStripper)
2627     string_split = init_st(StringSplitter)
2628     string_paren_wrap = init_st(StringParenWrapper)
2629
2630     transformers: List[Transformer]
2631     if (
2632         not line.contains_uncollapsable_type_comments()
2633         and not line.should_explode
2634         and (
2635             is_line_short_enough(line, line_length=mode.line_length, line_str=line_str)
2636             or line.contains_unsplittable_type_ignore()
2637         )
2638         and not (line.inside_brackets and line.contains_standalone_comments())
2639     ):
2640         # Only apply basic string preprocessing, since lines shouldn't be split here.
2641         if mode.experimental_string_processing:
2642             transformers = [string_merge, string_paren_strip]
2643         else:
2644             transformers = []
2645     elif line.is_def:
2646         transformers = [left_hand_split]
2647     else:
2648
2649         def rhs(line: Line, features: Collection[Feature]) -> Iterator[Line]:
2650             """Wraps calls to `right_hand_split`.
2651
2652             The calls increasingly `omit` right-hand trailers (bracket pairs with
2653             content), meaning the trailers get glued together to split on another
2654             bracket pair instead.
2655             """
2656             for omit in generate_trailers_to_omit(line, mode.line_length):
2657                 lines = list(
2658                     right_hand_split(line, mode.line_length, features, omit=omit)
2659                 )
2660                 # Note: this check is only able to figure out if the first line of the
2661                 # *current* transformation fits in the line length.  This is true only
2662                 # for simple cases.  All others require running more transforms via
2663                 # `transform_line()`.  This check doesn't know if those would succeed.
2664                 if is_line_short_enough(lines[0], line_length=mode.line_length):
2665                     yield from lines
2666                     return
2667
2668             # All splits failed, best effort split with no omits.
2669             # This mostly happens to multiline strings that are by definition
2670             # reported as not fitting a single line, as well as lines that contain
2671             # trailing commas (those have to be exploded).
2672             yield from right_hand_split(
2673                 line, line_length=mode.line_length, features=features
2674             )
2675
2676         if mode.experimental_string_processing:
2677             if line.inside_brackets:
2678                 transformers = [
2679                     string_merge,
2680                     string_paren_strip,
2681                     string_split,
2682                     delimiter_split,
2683                     standalone_comment_split,
2684                     string_paren_wrap,
2685                     rhs,
2686                 ]
2687             else:
2688                 transformers = [
2689                     string_merge,
2690                     string_paren_strip,
2691                     string_split,
2692                     string_paren_wrap,
2693                     rhs,
2694                 ]
2695         else:
2696             if line.inside_brackets:
2697                 transformers = [delimiter_split, standalone_comment_split, rhs]
2698             else:
2699                 transformers = [rhs]
2700
2701     for transform in transformers:
2702         # We are accumulating lines in `result` because we might want to abort
2703         # mission and return the original line in the end, or attempt a different
2704         # split altogether.
2705         try:
2706             result = run_transformer(line, transform, mode, features, line_str=line_str)
2707         except CannotTransform:
2708             continue
2709         else:
2710             yield from result
2711             break
2712
2713     else:
2714         yield line
2715
2716
2717 @dataclass  # type: ignore
2718 class StringTransformer(ABC):
2719     """
2720     An implementation of the Transformer protocol that relies on its
2721     subclasses overriding the template methods `do_match(...)` and
2722     `do_transform(...)`.
2723
2724     This Transformer works exclusively on strings (for example, by merging
2725     or splitting them).
2726
2727     The following sections can be found among the docstrings of each concrete
2728     StringTransformer subclass.
2729
2730     Requirements:
2731         Which requirements must be met of the given Line for this
2732         StringTransformer to be applied?
2733
2734     Transformations:
2735         If the given Line meets all of the above requirements, which string
2736         transformations can you expect to be applied to it by this
2737         StringTransformer?
2738
2739     Collaborations:
2740         What contractual agreements does this StringTransformer have with other
2741         StringTransfomers? Such collaborations should be eliminated/minimized
2742         as much as possible.
2743     """
2744
2745     line_length: int
2746     normalize_strings: bool
2747     __name__ = "StringTransformer"
2748
2749     @abstractmethod
2750     def do_match(self, line: Line) -> TMatchResult:
2751         """
2752         Returns:
2753             * Ok(string_idx) such that `line.leaves[string_idx]` is our target
2754             string, if a match was able to be made.
2755                 OR
2756             * Err(CannotTransform), if a match was not able to be made.
2757         """
2758
2759     @abstractmethod
2760     def do_transform(self, line: Line, string_idx: int) -> Iterator[TResult[Line]]:
2761         """
2762         Yields:
2763             * Ok(new_line) where new_line is the new transformed line.
2764                 OR
2765             * Err(CannotTransform) if the transformation failed for some reason. The
2766             `do_match(...)` template method should usually be used to reject
2767             the form of the given Line, but in some cases it is difficult to
2768             know whether or not a Line meets the StringTransformer's
2769             requirements until the transformation is already midway.
2770
2771         Side Effects:
2772             This method should NOT mutate @line directly, but it MAY mutate the
2773             Line's underlying Node structure. (WARNING: If the underlying Node
2774             structure IS altered, then this method should NOT be allowed to
2775             yield an CannotTransform after that point.)
2776         """
2777
2778     def __call__(self, line: Line, _features: Collection[Feature]) -> Iterator[Line]:
2779         """
2780         StringTransformer instances have a call signature that mirrors that of
2781         the Transformer type.
2782
2783         Raises:
2784             CannotTransform(...) if the concrete StringTransformer class is unable
2785             to transform @line.
2786         """
2787         # Optimization to avoid calling `self.do_match(...)` when the line does
2788         # not contain any string.
2789         if not any(leaf.type == token.STRING for leaf in line.leaves):
2790             raise CannotTransform("There are no strings in this line.")
2791
2792         match_result = self.do_match(line)
2793
2794         if isinstance(match_result, Err):
2795             cant_transform = match_result.err()
2796             raise CannotTransform(
2797                 f"The string transformer {self.__class__.__name__} does not recognize"
2798                 " this line as one that it can transform."
2799             ) from cant_transform
2800
2801         string_idx = match_result.ok()
2802
2803         for line_result in self.do_transform(line, string_idx):
2804             if isinstance(line_result, Err):
2805                 cant_transform = line_result.err()
2806                 raise CannotTransform(
2807                     "StringTransformer failed while attempting to transform string."
2808                 ) from cant_transform
2809             line = line_result.ok()
2810             yield line
2811
2812
2813 @dataclass
2814 class CustomSplit:
2815     """A custom (i.e. manual) string split.
2816
2817     A single CustomSplit instance represents a single substring.
2818
2819     Examples:
2820         Consider the following string:
2821         ```
2822         "Hi there friend."
2823         " This is a custom"
2824         f" string {split}."
2825         ```
2826
2827         This string will correspond to the following three CustomSplit instances:
2828         ```
2829         CustomSplit(False, 16)
2830         CustomSplit(False, 17)
2831         CustomSplit(True, 16)
2832         ```
2833     """
2834
2835     has_prefix: bool
2836     break_idx: int
2837
2838
2839 class CustomSplitMapMixin:
2840     """
2841     This mixin class is used to map merged strings to a sequence of
2842     CustomSplits, which will then be used to re-split the strings iff none of
2843     the resultant substrings go over the configured max line length.
2844     """
2845
2846     _Key = Tuple[StringID, str]
2847     _CUSTOM_SPLIT_MAP: Dict[_Key, Tuple[CustomSplit, ...]] = defaultdict(tuple)
2848
2849     @staticmethod
2850     def _get_key(string: str) -> "CustomSplitMapMixin._Key":
2851         """
2852         Returns:
2853             A unique identifier that is used internally to map @string to a
2854             group of custom splits.
2855         """
2856         return (id(string), string)
2857
2858     def add_custom_splits(
2859         self, string: str, custom_splits: Iterable[CustomSplit]
2860     ) -> None:
2861         """Custom Split Map Setter Method
2862
2863         Side Effects:
2864             Adds a mapping from @string to the custom splits @custom_splits.
2865         """
2866         key = self._get_key(string)
2867         self._CUSTOM_SPLIT_MAP[key] = tuple(custom_splits)
2868
2869     def pop_custom_splits(self, string: str) -> List[CustomSplit]:
2870         """Custom Split Map Getter Method
2871
2872         Returns:
2873             * A list of the custom splits that are mapped to @string, if any
2874             exist.
2875                 OR
2876             * [], otherwise.
2877
2878         Side Effects:
2879             Deletes the mapping between @string and its associated custom
2880             splits (which are returned to the caller).
2881         """
2882         key = self._get_key(string)
2883
2884         custom_splits = self._CUSTOM_SPLIT_MAP[key]
2885         del self._CUSTOM_SPLIT_MAP[key]
2886
2887         return list(custom_splits)
2888
2889     def has_custom_splits(self, string: str) -> bool:
2890         """
2891         Returns:
2892             True iff @string is associated with a set of custom splits.
2893         """
2894         key = self._get_key(string)
2895         return key in self._CUSTOM_SPLIT_MAP
2896
2897
2898 class StringMerger(CustomSplitMapMixin, StringTransformer):
2899     """StringTransformer that merges strings together.
2900
2901     Requirements:
2902         (A) The line contains adjacent strings such that ALL of the validation checks
2903         listed in StringMerger.__validate_msg(...)'s docstring pass.
2904             OR
2905         (B) The line contains a string which uses line continuation backslashes.
2906
2907     Transformations:
2908         Depending on which of the two requirements above where met, either:
2909
2910         (A) The string group associated with the target string is merged.
2911             OR
2912         (B) All line-continuation backslashes are removed from the target string.
2913
2914     Collaborations:
2915         StringMerger provides custom split information to StringSplitter.
2916     """
2917
2918     def do_match(self, line: Line) -> TMatchResult:
2919         LL = line.leaves
2920
2921         is_valid_index = is_valid_index_factory(LL)
2922
2923         for (i, leaf) in enumerate(LL):
2924             if (
2925                 leaf.type == token.STRING
2926                 and is_valid_index(i + 1)
2927                 and LL[i + 1].type == token.STRING
2928             ):
2929                 return Ok(i)
2930
2931             if leaf.type == token.STRING and "\\\n" in leaf.value:
2932                 return Ok(i)
2933
2934         return TErr("This line has no strings that need merging.")
2935
2936     def do_transform(self, line: Line, string_idx: int) -> Iterator[TResult[Line]]:
2937         new_line = line
2938         rblc_result = self.__remove_backslash_line_continuation_chars(
2939             new_line, string_idx
2940         )
2941         if isinstance(rblc_result, Ok):
2942             new_line = rblc_result.ok()
2943
2944         msg_result = self.__merge_string_group(new_line, string_idx)
2945         if isinstance(msg_result, Ok):
2946             new_line = msg_result.ok()
2947
2948         if isinstance(rblc_result, Err) and isinstance(msg_result, Err):
2949             msg_cant_transform = msg_result.err()
2950             rblc_cant_transform = rblc_result.err()
2951             cant_transform = CannotTransform(
2952                 "StringMerger failed to merge any strings in this line."
2953             )
2954
2955             # Chain the errors together using `__cause__`.
2956             msg_cant_transform.__cause__ = rblc_cant_transform
2957             cant_transform.__cause__ = msg_cant_transform
2958
2959             yield Err(cant_transform)
2960         else:
2961             yield Ok(new_line)
2962
2963     @staticmethod
2964     def __remove_backslash_line_continuation_chars(
2965         line: Line, string_idx: int
2966     ) -> TResult[Line]:
2967         """
2968         Merge strings that were split across multiple lines using
2969         line-continuation backslashes.
2970
2971         Returns:
2972             Ok(new_line), if @line contains backslash line-continuation
2973             characters.
2974                 OR
2975             Err(CannotTransform), otherwise.
2976         """
2977         LL = line.leaves
2978
2979         string_leaf = LL[string_idx]
2980         if not (
2981             string_leaf.type == token.STRING
2982             and "\\\n" in string_leaf.value
2983             and not has_triple_quotes(string_leaf.value)
2984         ):
2985             return TErr(
2986                 f"String leaf {string_leaf} does not contain any backslash line"
2987                 " continuation characters."
2988             )
2989
2990         new_line = line.clone()
2991         new_line.comments = line.comments.copy()
2992         append_leaves(new_line, line, LL)
2993
2994         new_string_leaf = new_line.leaves[string_idx]
2995         new_string_leaf.value = new_string_leaf.value.replace("\\\n", "")
2996
2997         return Ok(new_line)
2998
2999     def __merge_string_group(self, line: Line, string_idx: int) -> TResult[Line]:
3000         """
3001         Merges string group (i.e. set of adjacent strings) where the first
3002         string in the group is `line.leaves[string_idx]`.
3003
3004         Returns:
3005             Ok(new_line), if ALL of the validation checks found in
3006             __validate_msg(...) pass.
3007                 OR
3008             Err(CannotTransform), otherwise.
3009         """
3010         LL = line.leaves
3011
3012         is_valid_index = is_valid_index_factory(LL)
3013
3014         vresult = self.__validate_msg(line, string_idx)
3015         if isinstance(vresult, Err):
3016             return vresult
3017
3018         # If the string group is wrapped inside an Atom node, we must make sure
3019         # to later replace that Atom with our new (merged) string leaf.
3020         atom_node = LL[string_idx].parent
3021
3022         # We will place BREAK_MARK in between every two substrings that we
3023         # merge. We will then later go through our final result and use the
3024         # various instances of BREAK_MARK we find to add the right values to
3025         # the custom split map.
3026         BREAK_MARK = "@@@@@ BLACK BREAKPOINT MARKER @@@@@"
3027
3028         QUOTE = LL[string_idx].value[-1]
3029
3030         def make_naked(string: str, string_prefix: str) -> str:
3031             """Strip @string (i.e. make it a "naked" string)
3032
3033             Pre-conditions:
3034                 * assert_is_leaf_string(@string)
3035
3036             Returns:
3037                 A string that is identical to @string except that
3038                 @string_prefix has been stripped, the surrounding QUOTE
3039                 characters have been removed, and any remaining QUOTE
3040                 characters have been escaped.
3041             """
3042             assert_is_leaf_string(string)
3043
3044             RE_EVEN_BACKSLASHES = r"(?:(?<!\\)(?:\\\\)*)"
3045             naked_string = string[len(string_prefix) + 1 : -1]
3046             naked_string = re.sub(
3047                 "(" + RE_EVEN_BACKSLASHES + ")" + QUOTE, r"\1\\" + QUOTE, naked_string
3048             )
3049             return naked_string
3050
3051         # Holds the CustomSplit objects that will later be added to the custom
3052         # split map.
3053         custom_splits = []
3054
3055         # Temporary storage for the 'has_prefix' part of the CustomSplit objects.
3056         prefix_tracker = []
3057
3058         # Sets the 'prefix' variable. This is the prefix that the final merged
3059         # string will have.
3060         next_str_idx = string_idx
3061         prefix = ""
3062         while (
3063             not prefix
3064             and is_valid_index(next_str_idx)
3065             and LL[next_str_idx].type == token.STRING
3066         ):
3067             prefix = get_string_prefix(LL[next_str_idx].value)
3068             next_str_idx += 1
3069
3070         # The next loop merges the string group. The final string will be
3071         # contained in 'S'.
3072         #
3073         # The following convenience variables are used:
3074         #
3075         #   S: string
3076         #   NS: naked string
3077         #   SS: next string
3078         #   NSS: naked next string
3079         S = ""
3080         NS = ""
3081         num_of_strings = 0
3082         next_str_idx = string_idx
3083         while is_valid_index(next_str_idx) and LL[next_str_idx].type == token.STRING:
3084             num_of_strings += 1
3085
3086             SS = LL[next_str_idx].value
3087             next_prefix = get_string_prefix(SS)
3088
3089             # If this is an f-string group but this substring is not prefixed
3090             # with 'f'...
3091             if "f" in prefix and "f" not in next_prefix:
3092                 # Then we must escape any braces contained in this substring.
3093                 SS = re.subf(r"(\{|\})", "{1}{1}", SS)
3094
3095             NSS = make_naked(SS, next_prefix)
3096
3097             has_prefix = bool(next_prefix)
3098             prefix_tracker.append(has_prefix)
3099
3100             S = prefix + QUOTE + NS + NSS + BREAK_MARK + QUOTE
3101             NS = make_naked(S, prefix)
3102
3103             next_str_idx += 1
3104
3105         S_leaf = Leaf(token.STRING, S)
3106         if self.normalize_strings:
3107             normalize_string_quotes(S_leaf)
3108
3109         # Fill the 'custom_splits' list with the appropriate CustomSplit objects.
3110         temp_string = S_leaf.value[len(prefix) + 1 : -1]
3111         for has_prefix in prefix_tracker:
3112             mark_idx = temp_string.find(BREAK_MARK)
3113             assert (
3114                 mark_idx >= 0
3115             ), "Logic error while filling the custom string breakpoint cache."
3116
3117             temp_string = temp_string[mark_idx + len(BREAK_MARK) :]
3118             breakpoint_idx = mark_idx + (len(prefix) if has_prefix else 0) + 1
3119             custom_splits.append(CustomSplit(has_prefix, breakpoint_idx))
3120
3121         string_leaf = Leaf(token.STRING, S_leaf.value.replace(BREAK_MARK, ""))
3122
3123         if atom_node is not None:
3124             replace_child(atom_node, string_leaf)
3125
3126         # Build the final line ('new_line') that this method will later return.
3127         new_line = line.clone()
3128         for (i, leaf) in enumerate(LL):
3129             if i == string_idx:
3130                 new_line.append(string_leaf)
3131
3132             if string_idx <= i < string_idx + num_of_strings:
3133                 for comment_leaf in line.comments_after(LL[i]):
3134                     new_line.append(comment_leaf, preformatted=True)
3135                 continue
3136
3137             append_leaves(new_line, line, [leaf])
3138
3139         self.add_custom_splits(string_leaf.value, custom_splits)
3140         return Ok(new_line)
3141
3142     @staticmethod
3143     def __validate_msg(line: Line, string_idx: int) -> TResult[None]:
3144         """Validate (M)erge (S)tring (G)roup
3145
3146         Transform-time string validation logic for __merge_string_group(...).
3147
3148         Returns:
3149             * Ok(None), if ALL validation checks (listed below) pass.
3150                 OR
3151             * Err(CannotTransform), if any of the following are true:
3152                 - The target string group does not contain ANY stand-alone comments.
3153                 - The target string is not in a string group (i.e. it has no
3154                   adjacent strings).
3155                 - The string group has more than one inline comment.
3156                 - The string group has an inline comment that appears to be a pragma.
3157                 - The set of all string prefixes in the string group is of
3158                   length greater than one and is not equal to {"", "f"}.
3159                 - The string group consists of raw strings.
3160         """
3161         # We first check for "inner" stand-alone comments (i.e. stand-alone
3162         # comments that have a string leaf before them AND after them).
3163         for inc in [1, -1]:
3164             i = string_idx
3165             found_sa_comment = False
3166             is_valid_index = is_valid_index_factory(line.leaves)
3167             while is_valid_index(i) and line.leaves[i].type in [
3168                 token.STRING,
3169                 STANDALONE_COMMENT,
3170             ]:
3171                 if line.leaves[i].type == STANDALONE_COMMENT:
3172                     found_sa_comment = True
3173                 elif found_sa_comment:
3174                     return TErr(
3175                         "StringMerger does NOT merge string groups which contain "
3176                         "stand-alone comments."
3177                     )
3178
3179                 i += inc
3180
3181         num_of_inline_string_comments = 0
3182         set_of_prefixes = set()
3183         num_of_strings = 0
3184         for leaf in line.leaves[string_idx:]:
3185             if leaf.type != token.STRING:
3186                 # If the string group is trailed by a comma, we count the
3187                 # comments trailing the comma to be one of the string group's
3188                 # comments.
3189                 if leaf.type == token.COMMA and id(leaf) in line.comments:
3190                     num_of_inline_string_comments += 1
3191                 break
3192
3193             if has_triple_quotes(leaf.value):
3194                 return TErr("StringMerger does NOT merge multiline strings.")
3195
3196             num_of_strings += 1
3197             prefix = get_string_prefix(leaf.value)
3198             if "r" in prefix:
3199                 return TErr("StringMerger does NOT merge raw strings.")
3200
3201             set_of_prefixes.add(prefix)
3202
3203             if id(leaf) in line.comments:
3204                 num_of_inline_string_comments += 1
3205                 if contains_pragma_comment(line.comments[id(leaf)]):
3206                     return TErr("Cannot merge strings which have pragma comments.")
3207
3208         if num_of_strings < 2:
3209             return TErr(
3210                 f"Not enough strings to merge (num_of_strings={num_of_strings})."
3211             )
3212
3213         if num_of_inline_string_comments > 1:
3214             return TErr(
3215                 f"Too many inline string comments ({num_of_inline_string_comments})."
3216             )
3217
3218         if len(set_of_prefixes) > 1 and set_of_prefixes != {"", "f"}:
3219             return TErr(f"Too many different prefixes ({set_of_prefixes}).")
3220
3221         return Ok(None)
3222
3223
3224 class StringParenStripper(StringTransformer):
3225     """StringTransformer that strips surrounding parentheses from strings.
3226
3227     Requirements:
3228         The line contains a string which is surrounded by parentheses and:
3229             - The target string is NOT the only argument to a function call).
3230             - If the target string contains a PERCENT, the brackets are not
3231               preceeded or followed by an operator with higher precedence than
3232               PERCENT.
3233
3234     Transformations:
3235         The parentheses mentioned in the 'Requirements' section are stripped.
3236
3237     Collaborations:
3238         StringParenStripper has its own inherent usefulness, but it is also
3239         relied on to clean up the parentheses created by StringParenWrapper (in
3240         the event that they are no longer needed).
3241     """
3242
3243     def do_match(self, line: Line) -> TMatchResult:
3244         LL = line.leaves
3245
3246         is_valid_index = is_valid_index_factory(LL)
3247
3248         for (idx, leaf) in enumerate(LL):
3249             # Should be a string...
3250             if leaf.type != token.STRING:
3251                 continue
3252
3253             # Should be preceded by a non-empty LPAR...
3254             if (
3255                 not is_valid_index(idx - 1)
3256                 or LL[idx - 1].type != token.LPAR
3257                 or is_empty_lpar(LL[idx - 1])
3258             ):
3259                 continue
3260
3261             # That LPAR should NOT be preceded by a function name or a closing
3262             # bracket (which could be a function which returns a function or a
3263             # list/dictionary that contains a function)...
3264             if is_valid_index(idx - 2) and (
3265                 LL[idx - 2].type == token.NAME or LL[idx - 2].type in CLOSING_BRACKETS
3266             ):
3267                 continue
3268
3269             string_idx = idx
3270
3271             # Skip the string trailer, if one exists.
3272             string_parser = StringParser()
3273             next_idx = string_parser.parse(LL, string_idx)
3274
3275             # if the leaves in the parsed string include a PERCENT, we need to
3276             # make sure the initial LPAR is NOT preceded by an operator with
3277             # higher or equal precedence to PERCENT
3278             if is_valid_index(idx - 2):
3279                 # mypy can't quite follow unless we name this
3280                 before_lpar = LL[idx - 2]
3281                 if token.PERCENT in {leaf.type for leaf in LL[idx - 1 : next_idx]} and (
3282                     (
3283                         before_lpar.type
3284                         in {
3285                             token.STAR,
3286                             token.AT,
3287                             token.SLASH,
3288                             token.DOUBLESLASH,
3289                             token.PERCENT,
3290                             token.TILDE,
3291                             token.DOUBLESTAR,
3292                             token.AWAIT,
3293                             token.LSQB,
3294                             token.LPAR,
3295                         }
3296                     )
3297                     or (
3298                         # only unary PLUS/MINUS
3299                         before_lpar.parent
3300                         and before_lpar.parent.type == syms.factor
3301                         and (before_lpar.type in {token.PLUS, token.MINUS})
3302                     )
3303                 ):
3304                     continue
3305
3306             # Should be followed by a non-empty RPAR...
3307             if (
3308                 is_valid_index(next_idx)
3309                 and LL[next_idx].type == token.RPAR
3310                 and not is_empty_rpar(LL[next_idx])
3311             ):
3312                 # That RPAR should NOT be followed by anything with higher
3313                 # precedence than PERCENT
3314                 if is_valid_index(next_idx + 1) and LL[next_idx + 1].type in {
3315                     token.DOUBLESTAR,
3316                     token.LSQB,
3317                     token.LPAR,
3318                     token.DOT,
3319                 }:
3320                     continue
3321
3322                 return Ok(string_idx)
3323
3324         return TErr("This line has no strings wrapped in parens.")
3325
3326     def do_transform(self, line: Line, string_idx: int) -> Iterator[TResult[Line]]:
3327         LL = line.leaves
3328
3329         string_parser = StringParser()
3330         rpar_idx = string_parser.parse(LL, string_idx)
3331
3332         for leaf in (LL[string_idx - 1], LL[rpar_idx]):
3333             if line.comments_after(leaf):
3334                 yield TErr(
3335                     "Will not strip parentheses which have comments attached to them."
3336                 )
3337                 return
3338
3339         new_line = line.clone()
3340         new_line.comments = line.comments.copy()
3341         try:
3342             append_leaves(new_line, line, LL[: string_idx - 1])
3343         except BracketMatchError:
3344             # HACK: I believe there is currently a bug somewhere in
3345             # right_hand_split() that is causing brackets to not be tracked
3346             # properly by a shared BracketTracker.
3347             append_leaves(new_line, line, LL[: string_idx - 1], preformatted=True)
3348
3349         string_leaf = Leaf(token.STRING, LL[string_idx].value)
3350         LL[string_idx - 1].remove()
3351         replace_child(LL[string_idx], string_leaf)
3352         new_line.append(string_leaf)
3353
3354         append_leaves(
3355             new_line, line, LL[string_idx + 1 : rpar_idx] + LL[rpar_idx + 1 :]
3356         )
3357
3358         LL[rpar_idx].remove()
3359
3360         yield Ok(new_line)
3361
3362
3363 class BaseStringSplitter(StringTransformer):
3364     """
3365     Abstract class for StringTransformers which transform a Line's strings by splitting
3366     them or placing them on their own lines where necessary to avoid going over
3367     the configured line length.
3368
3369     Requirements:
3370         * The target string value is responsible for the line going over the
3371         line length limit. It follows that after all of black's other line
3372         split methods have been exhausted, this line (or one of the resulting
3373         lines after all line splits are performed) would still be over the
3374         line_length limit unless we split this string.
3375             AND
3376         * The target string is NOT a "pointless" string (i.e. a string that has
3377         no parent or siblings).
3378             AND
3379         * The target string is not followed by an inline comment that appears
3380         to be a pragma.
3381             AND
3382         * The target string is not a multiline (i.e. triple-quote) string.
3383     """
3384
3385     @abstractmethod
3386     def do_splitter_match(self, line: Line) -> TMatchResult:
3387         """
3388         BaseStringSplitter asks its clients to override this method instead of
3389         `StringTransformer.do_match(...)`.
3390
3391         Follows the same protocol as `StringTransformer.do_match(...)`.
3392
3393         Refer to `help(StringTransformer.do_match)` for more information.
3394         """
3395
3396     def do_match(self, line: Line) -> TMatchResult:
3397         match_result = self.do_splitter_match(line)
3398         if isinstance(match_result, Err):
3399             return match_result
3400
3401         string_idx = match_result.ok()
3402         vresult = self.__validate(line, string_idx)
3403         if isinstance(vresult, Err):
3404             return vresult
3405
3406         return match_result
3407
3408     def __validate(self, line: Line, string_idx: int) -> TResult[None]:
3409         """
3410         Checks that @line meets all of the requirements listed in this classes'
3411         docstring. Refer to `help(BaseStringSplitter)` for a detailed
3412         description of those requirements.
3413
3414         Returns:
3415             * Ok(None), if ALL of the requirements are met.
3416                 OR
3417             * Err(CannotTransform), if ANY of the requirements are NOT met.
3418         """
3419         LL = line.leaves
3420
3421         string_leaf = LL[string_idx]
3422
3423         max_string_length = self.__get_max_string_length(line, string_idx)
3424         if len(string_leaf.value) <= max_string_length:
3425             return TErr(
3426                 "The string itself is not what is causing this line to be too long."
3427             )
3428
3429         if not string_leaf.parent or [L.type for L in string_leaf.parent.children] == [
3430             token.STRING,
3431             token.NEWLINE,
3432         ]:
3433             return TErr(
3434                 f"This string ({string_leaf.value}) appears to be pointless (i.e. has"
3435                 " no parent)."
3436             )
3437
3438         if id(line.leaves[string_idx]) in line.comments and contains_pragma_comment(
3439             line.comments[id(line.leaves[string_idx])]
3440         ):
3441             return TErr(
3442                 "Line appears to end with an inline pragma comment. Splitting the line"
3443                 " could modify the pragma's behavior."
3444             )
3445
3446         if has_triple_quotes(string_leaf.value):
3447             return TErr("We cannot split multiline strings.")
3448
3449         return Ok(None)
3450
3451     def __get_max_string_length(self, line: Line, string_idx: int) -> int:
3452         """
3453         Calculates the max string length used when attempting to determine
3454         whether or not the target string is responsible for causing the line to
3455         go over the line length limit.
3456
3457         WARNING: This method is tightly coupled to both StringSplitter and
3458         (especially) StringParenWrapper. There is probably a better way to
3459         accomplish what is being done here.
3460
3461         Returns:
3462             max_string_length: such that `line.leaves[string_idx].value >
3463             max_string_length` implies that the target string IS responsible
3464             for causing this line to exceed the line length limit.
3465         """
3466         LL = line.leaves
3467
3468         is_valid_index = is_valid_index_factory(LL)
3469
3470         # We use the shorthand "WMA4" in comments to abbreviate "We must
3471         # account for". When giving examples, we use STRING to mean some/any
3472         # valid string.
3473         #
3474         # Finally, we use the following convenience variables:
3475         #
3476         #   P:  The leaf that is before the target string leaf.
3477         #   N:  The leaf that is after the target string leaf.
3478         #   NN: The leaf that is after N.
3479
3480         # WMA4 the whitespace at the beginning of the line.
3481         offset = line.depth * 4
3482
3483         if is_valid_index(string_idx - 1):
3484             p_idx = string_idx - 1
3485             if (
3486                 LL[string_idx - 1].type == token.LPAR
3487                 and LL[string_idx - 1].value == ""
3488                 and string_idx >= 2
3489             ):
3490                 # If the previous leaf is an empty LPAR placeholder, we should skip it.
3491                 p_idx -= 1
3492
3493             P = LL[p_idx]
3494             if P.type == token.PLUS:
3495                 # WMA4 a space and a '+' character (e.g. `+ STRING`).
3496                 offset += 2
3497
3498             if P.type == token.COMMA:
3499                 # WMA4 a space, a comma, and a closing bracket [e.g. `), STRING`].
3500                 offset += 3
3501
3502             if P.type in [token.COLON, token.EQUAL, token.NAME]:
3503                 # This conditional branch is meant to handle dictionary keys,
3504                 # variable assignments, 'return STRING' statement lines, and
3505                 # 'else STRING' ternary expression lines.
3506
3507                 # WMA4 a single space.
3508                 offset += 1
3509
3510                 # WMA4 the lengths of any leaves that came before that space.
3511                 for leaf in LL[: p_idx + 1]:
3512                     offset += len(str(leaf))
3513
3514         if is_valid_index(string_idx + 1):
3515             N = LL[string_idx + 1]
3516             if N.type == token.RPAR and N.value == "" and len(LL) > string_idx + 2:
3517                 # If the next leaf is an empty RPAR placeholder, we should skip it.
3518                 N = LL[string_idx + 2]
3519
3520             if N.type == token.COMMA:
3521                 # WMA4 a single comma at the end of the string (e.g `STRING,`).
3522                 offset += 1
3523
3524             if is_valid_index(string_idx + 2):
3525                 NN = LL[string_idx + 2]
3526
3527                 if N.type == token.DOT and NN.type == token.NAME:
3528                     # This conditional branch is meant to handle method calls invoked
3529                     # off of a string literal up to and including the LPAR character.
3530
3531                     # WMA4 the '.' character.
3532                     offset += 1
3533
3534                     if (
3535                         is_valid_index(string_idx + 3)
3536                         and LL[string_idx + 3].type == token.LPAR
3537                     ):
3538                         # WMA4 the left parenthesis character.
3539                         offset += 1
3540
3541                     # WMA4 the length of the method's name.
3542                     offset += len(NN.value)
3543
3544         has_comments = False
3545         for comment_leaf in line.comments_after(LL[string_idx]):
3546             if not has_comments:
3547                 has_comments = True
3548                 # WMA4 two spaces before the '#' character.
3549                 offset += 2
3550
3551             # WMA4 the length of the inline comment.
3552             offset += len(comment_leaf.value)
3553
3554         max_string_length = self.line_length - offset
3555         return max_string_length
3556
3557
3558 class StringSplitter(CustomSplitMapMixin, BaseStringSplitter):
3559     """
3560     StringTransformer that splits "atom" strings (i.e. strings which exist on
3561     lines by themselves).
3562
3563     Requirements:
3564         * The line consists ONLY of a single string (with the exception of a
3565         '+' symbol which MAY exist at the start of the line), MAYBE a string
3566         trailer, and MAYBE a trailing comma.
3567             AND
3568         * All of the requirements listed in BaseStringSplitter's docstring.
3569
3570     Transformations:
3571         The string mentioned in the 'Requirements' section is split into as
3572         many substrings as necessary to adhere to the configured line length.
3573
3574         In the final set of substrings, no substring should be smaller than
3575         MIN_SUBSTR_SIZE characters.
3576
3577         The string will ONLY be split on spaces (i.e. each new substring should
3578         start with a space).
3579
3580         If the string is an f-string, it will NOT be split in the middle of an
3581         f-expression (e.g. in f"FooBar: {foo() if x else bar()}", {foo() if x
3582         else bar()} is an f-expression).
3583
3584         If the string that is being split has an associated set of custom split
3585         records and those custom splits will NOT result in any line going over
3586         the configured line length, those custom splits are used. Otherwise the
3587         string is split as late as possible (from left-to-right) while still
3588         adhering to the transformation rules listed above.
3589
3590     Collaborations:
3591         StringSplitter relies on StringMerger to construct the appropriate
3592         CustomSplit objects and add them to the custom split map.
3593     """
3594
3595     MIN_SUBSTR_SIZE = 6
3596     # Matches an "f-expression" (e.g. {var}) that might be found in an f-string.
3597     RE_FEXPR = r"""
3598     (?<!\{)\{
3599         (?:
3600             [^\{\}]
3601             | \{\{
3602             | \}\}
3603         )+?
3604     (?<!\})(?:\}\})*\}(?!\})
3605     """
3606
3607     def do_splitter_match(self, line: Line) -> TMatchResult:
3608         LL = line.leaves
3609
3610         is_valid_index = is_valid_index_factory(LL)
3611
3612         idx = 0
3613
3614         # The first leaf MAY be a '+' symbol...
3615         if is_valid_index(idx) and LL[idx].type == token.PLUS:
3616             idx += 1
3617
3618         # The next/first leaf MAY be an empty LPAR...
3619         if is_valid_index(idx) and is_empty_lpar(LL[idx]):
3620             idx += 1
3621
3622         # The next/first leaf MUST be a string...
3623         if not is_valid_index(idx) or LL[idx].type != token.STRING:
3624             return TErr("Line does not start with a string.")
3625
3626         string_idx = idx
3627
3628         # Skip the string trailer, if one exists.
3629         string_parser = StringParser()
3630         idx = string_parser.parse(LL, string_idx)
3631
3632         # That string MAY be followed by an empty RPAR...
3633         if is_valid_index(idx) and is_empty_rpar(LL[idx]):
3634             idx += 1
3635
3636         # That string / empty RPAR leaf MAY be followed by a comma...
3637         if is_valid_index(idx) and LL[idx].type == token.COMMA:
3638             idx += 1
3639
3640         # But no more leaves are allowed...
3641         if is_valid_index(idx):
3642             return TErr("This line does not end with a string.")
3643
3644         return Ok(string_idx)
3645
3646     def do_transform(self, line: Line, string_idx: int) -> Iterator[TResult[Line]]:
3647         LL = line.leaves
3648
3649         QUOTE = LL[string_idx].value[-1]
3650
3651         is_valid_index = is_valid_index_factory(LL)
3652         insert_str_child = insert_str_child_factory(LL[string_idx])
3653
3654         prefix = get_string_prefix(LL[string_idx].value)
3655
3656         # We MAY choose to drop the 'f' prefix from substrings that don't
3657         # contain any f-expressions, but ONLY if the original f-string
3658         # contains at least one f-expression. Otherwise, we will alter the AST
3659         # of the program.
3660         drop_pointless_f_prefix = ("f" in prefix) and re.search(
3661             self.RE_FEXPR, LL[string_idx].value, re.VERBOSE
3662         )
3663
3664         first_string_line = True
3665         starts_with_plus = LL[0].type == token.PLUS
3666
3667         def line_needs_plus() -> bool:
3668             return first_string_line and starts_with_plus
3669
3670         def maybe_append_plus(new_line: Line) -> None:
3671             """
3672             Side Effects:
3673                 If @line starts with a plus and this is the first line we are
3674                 constructing, this function appends a PLUS leaf to @new_line
3675                 and replaces the old PLUS leaf in the node structure. Otherwise
3676                 this function does nothing.
3677             """
3678             if line_needs_plus():
3679                 plus_leaf = Leaf(token.PLUS, "+")
3680                 replace_child(LL[0], plus_leaf)
3681                 new_line.append(plus_leaf)
3682
3683         ends_with_comma = (
3684             is_valid_index(string_idx + 1) and LL[string_idx + 1].type == token.COMMA
3685         )
3686
3687         def max_last_string() -> int:
3688             """
3689             Returns:
3690                 The max allowed length of the string value used for the last
3691                 line we will construct.
3692             """
3693             result = self.line_length
3694             result -= line.depth * 4
3695             result -= 1 if ends_with_comma else 0
3696             result -= 2 if line_needs_plus() else 0
3697             return result
3698
3699         # --- Calculate Max Break Index (for string value)
3700         # We start with the line length limit
3701         max_break_idx = self.line_length
3702         # The last index of a string of length N is N-1.
3703         max_break_idx -= 1
3704         # Leading whitespace is not present in the string value (e.g. Leaf.value).
3705         max_break_idx -= line.depth * 4
3706         if max_break_idx < 0:
3707             yield TErr(
3708                 f"Unable to split {LL[string_idx].value} at such high of a line depth:"
3709                 f" {line.depth}"
3710             )
3711             return
3712
3713         # Check if StringMerger registered any custom splits.
3714         custom_splits = self.pop_custom_splits(LL[string_idx].value)
3715         # We use them ONLY if none of them would produce lines that exceed the
3716         # line limit.
3717         use_custom_breakpoints = bool(
3718             custom_splits
3719             and all(csplit.break_idx <= max_break_idx for csplit in custom_splits)
3720         )
3721
3722         # Temporary storage for the remaining chunk of the string line that
3723         # can't fit onto the line currently being constructed.
3724         rest_value = LL[string_idx].value
3725
3726         def more_splits_should_be_made() -> bool:
3727             """
3728             Returns:
3729                 True iff `rest_value` (the remaining string value from the last
3730                 split), should be split again.
3731             """
3732             if use_custom_breakpoints:
3733                 return len(custom_splits) > 1
3734             else:
3735                 return len(rest_value) > max_last_string()
3736
3737         string_line_results: List[Ok[Line]] = []
3738         while more_splits_should_be_made():
3739             if use_custom_breakpoints:
3740                 # Custom User Split (manual)
3741                 csplit = custom_splits.pop(0)
3742                 break_idx = csplit.break_idx
3743             else:
3744                 # Algorithmic Split (automatic)
3745                 max_bidx = max_break_idx - 2 if line_needs_plus() else max_break_idx
3746                 maybe_break_idx = self.__get_break_idx(rest_value, max_bidx)
3747                 if maybe_break_idx is None:
3748                     # If we are unable to algorithmically determine a good split
3749                     # and this string has custom splits registered to it, we
3750                     # fall back to using them--which means we have to start
3751                     # over from the beginning.
3752                     if custom_splits:
3753                         rest_value = LL[string_idx].value
3754                         string_line_results = []
3755                         first_string_line = True
3756                         use_custom_breakpoints = True
3757                         continue
3758
3759                     # Otherwise, we stop splitting here.
3760                     break
3761
3762                 break_idx = maybe_break_idx
3763
3764             # --- Construct `next_value`
3765             next_value = rest_value[:break_idx] + QUOTE
3766             if (
3767                 # Are we allowed to try to drop a pointless 'f' prefix?
3768                 drop_pointless_f_prefix
3769                 # If we are, will we be successful?
3770                 and next_value != self.__normalize_f_string(next_value, prefix)
3771             ):
3772                 # If the current custom split did NOT originally use a prefix,
3773                 # then `csplit.break_idx` will be off by one after removing
3774                 # the 'f' prefix.
3775                 break_idx = (
3776                     break_idx + 1
3777                     if use_custom_breakpoints and not csplit.has_prefix
3778                     else break_idx
3779                 )
3780                 next_value = rest_value[:break_idx] + QUOTE
3781                 next_value = self.__normalize_f_string(next_value, prefix)
3782
3783             # --- Construct `next_leaf`
3784             next_leaf = Leaf(token.STRING, next_value)
3785             insert_str_child(next_leaf)
3786             self.__maybe_normalize_string_quotes(next_leaf)
3787
3788             # --- Construct `next_line`
3789             next_line = line.clone()
3790             maybe_append_plus(next_line)
3791             next_line.append(next_leaf)
3792             string_line_results.append(Ok(next_line))
3793
3794             rest_value = prefix + QUOTE + rest_value[break_idx:]
3795             first_string_line = False
3796
3797         yield from string_line_results
3798
3799         if drop_pointless_f_prefix:
3800             rest_value = self.__normalize_f_string(rest_value, prefix)
3801
3802         rest_leaf = Leaf(token.STRING, rest_value)
3803         insert_str_child(rest_leaf)
3804
3805         # NOTE: I could not find a test case that verifies that the following
3806         # line is actually necessary, but it seems to be. Otherwise we risk
3807         # not normalizing the last substring, right?
3808         self.__maybe_normalize_string_quotes(rest_leaf)
3809
3810         last_line = line.clone()
3811         maybe_append_plus(last_line)
3812
3813         # If there are any leaves to the right of the target string...
3814         if is_valid_index(string_idx + 1):
3815             # We use `temp_value` here to determine how long the last line
3816             # would be if we were to append all the leaves to the right of the
3817             # target string to the last string line.
3818             temp_value = rest_value
3819             for leaf in LL[string_idx + 1 :]:
3820                 temp_value += str(leaf)
3821                 if leaf.type == token.LPAR:
3822                     break
3823
3824             # Try to fit them all on the same line with the last substring...
3825             if (
3826                 len(temp_value) <= max_last_string()
3827                 or LL[string_idx + 1].type == token.COMMA
3828             ):
3829                 last_line.append(rest_leaf)
3830                 append_leaves(last_line, line, LL[string_idx + 1 :])
3831                 yield Ok(last_line)
3832             # Otherwise, place the last substring on one line and everything
3833             # else on a line below that...
3834             else:
3835                 last_line.append(rest_leaf)
3836                 yield Ok(last_line)
3837
3838                 non_string_line = line.clone()
3839                 append_leaves(non_string_line, line, LL[string_idx + 1 :])
3840                 yield Ok(non_string_line)
3841         # Else the target string was the last leaf...
3842         else:
3843             last_line.append(rest_leaf)
3844             last_line.comments = line.comments.copy()
3845             yield Ok(last_line)
3846
3847     def __get_break_idx(self, string: str, max_break_idx: int) -> Optional[int]:
3848         """
3849         This method contains the algorithm that StringSplitter uses to
3850         determine which character to split each string at.
3851
3852         Args:
3853             @string: The substring that we are attempting to split.
3854             @max_break_idx: The ideal break index. We will return this value if it
3855             meets all the necessary conditions. In the likely event that it
3856             doesn't we will try to find the closest index BELOW @max_break_idx
3857             that does. If that fails, we will expand our search by also
3858             considering all valid indices ABOVE @max_break_idx.
3859
3860         Pre-Conditions:
3861             * assert_is_leaf_string(@string)
3862             * 0 <= @max_break_idx < len(@string)
3863
3864         Returns:
3865             break_idx, if an index is able to be found that meets all of the
3866             conditions listed in the 'Transformations' section of this classes'
3867             docstring.
3868                 OR
3869             None, otherwise.
3870         """
3871         is_valid_index = is_valid_index_factory(string)
3872
3873         assert is_valid_index(max_break_idx)
3874         assert_is_leaf_string(string)
3875
3876         _fexpr_slices: Optional[List[Tuple[Index, Index]]] = None
3877
3878         def fexpr_slices() -> Iterator[Tuple[Index, Index]]:
3879             """
3880             Yields:
3881                 All ranges of @string which, if @string were to be split there,
3882                 would result in the splitting of an f-expression (which is NOT
3883                 allowed).
3884             """
3885             nonlocal _fexpr_slices
3886
3887             if _fexpr_slices is None:
3888                 _fexpr_slices = []
3889                 for match in re.finditer(self.RE_FEXPR, string, re.VERBOSE):
3890                     _fexpr_slices.append(match.span())
3891
3892             yield from _fexpr_slices
3893
3894         is_fstring = "f" in get_string_prefix(string)
3895
3896         def breaks_fstring_expression(i: Index) -> bool:
3897             """
3898             Returns:
3899                 True iff returning @i would result in the splitting of an
3900                 f-expression (which is NOT allowed).
3901             """
3902             if not is_fstring:
3903                 return False
3904
3905             for (start, end) in fexpr_slices():
3906                 if start <= i < end:
3907                     return True
3908
3909             return False
3910
3911         def passes_all_checks(i: Index) -> bool:
3912             """
3913             Returns:
3914                 True iff ALL of the conditions listed in the 'Transformations'
3915                 section of this classes' docstring would be be met by returning @i.
3916             """
3917             is_space = string[i] == " "
3918             is_big_enough = (
3919                 len(string[i:]) >= self.MIN_SUBSTR_SIZE
3920                 and len(string[:i]) >= self.MIN_SUBSTR_SIZE
3921             )
3922             return is_space and is_big_enough and not breaks_fstring_expression(i)
3923
3924         # First, we check all indices BELOW @max_break_idx.
3925         break_idx = max_break_idx
3926         while is_valid_index(break_idx - 1) and not passes_all_checks(break_idx):
3927             break_idx -= 1
3928
3929         if not passes_all_checks(break_idx):
3930             # If that fails, we check all indices ABOVE @max_break_idx.
3931             #
3932             # If we are able to find a valid index here, the next line is going
3933             # to be longer than the specified line length, but it's probably
3934             # better than doing nothing at all.
3935             break_idx = max_break_idx + 1
3936             while is_valid_index(break_idx + 1) and not passes_all_checks(break_idx):
3937                 break_idx += 1
3938
3939             if not is_valid_index(break_idx) or not passes_all_checks(break_idx):
3940                 return None
3941
3942         return break_idx
3943
3944     def __maybe_normalize_string_quotes(self, leaf: Leaf) -> None:
3945         if self.normalize_strings:
3946             normalize_string_quotes(leaf)
3947
3948     def __normalize_f_string(self, string: str, prefix: str) -> str:
3949         """
3950         Pre-Conditions:
3951             * assert_is_leaf_string(@string)
3952
3953         Returns:
3954             * If @string is an f-string that contains no f-expressions, we
3955             return a string identical to @string except that the 'f' prefix
3956             has been stripped and all double braces (i.e. '{{' or '}}') have
3957             been normalized (i.e. turned into '{' or '}').
3958                 OR
3959             * Otherwise, we return @string.
3960         """
3961         assert_is_leaf_string(string)
3962
3963         if "f" in prefix and not re.search(self.RE_FEXPR, string, re.VERBOSE):
3964             new_prefix = prefix.replace("f", "")
3965
3966             temp = string[len(prefix) :]
3967             temp = re.sub(r"\{\{", "{", temp)
3968             temp = re.sub(r"\}\}", "}", temp)
3969             new_string = temp
3970
3971             return f"{new_prefix}{new_string}"
3972         else:
3973             return string
3974
3975
3976 class StringParenWrapper(CustomSplitMapMixin, BaseStringSplitter):
3977     """
3978     StringTransformer that splits non-"atom" strings (i.e. strings that do not
3979     exist on lines by themselves).
3980
3981     Requirements:
3982         All of the requirements listed in BaseStringSplitter's docstring in
3983         addition to the requirements listed below:
3984
3985         * The line is a return/yield statement, which returns/yields a string.
3986             OR
3987         * The line is part of a ternary expression (e.g. `x = y if cond else
3988         z`) such that the line starts with `else <string>`, where <string> is
3989         some string.
3990             OR
3991         * The line is an assert statement, which ends with a string.
3992             OR
3993         * The line is an assignment statement (e.g. `x = <string>` or `x +=
3994         <string>`) such that the variable is being assigned the value of some
3995         string.
3996             OR
3997         * The line is a dictionary key assignment where some valid key is being
3998         assigned the value of some string.
3999
4000     Transformations:
4001         The chosen string is wrapped in parentheses and then split at the LPAR.
4002
4003         We then have one line which ends with an LPAR and another line that
4004         starts with the chosen string. The latter line is then split again at
4005         the RPAR. This results in the RPAR (and possibly a trailing comma)
4006         being placed on its own line.
4007
4008         NOTE: If any leaves exist to the right of the chosen string (except
4009         for a trailing comma, which would be placed after the RPAR), those
4010         leaves are placed inside the parentheses.  In effect, the chosen
4011         string is not necessarily being "wrapped" by parentheses. We can,
4012         however, count on the LPAR being placed directly before the chosen
4013         string.
4014
4015         In other words, StringParenWrapper creates "atom" strings. These
4016         can then be split again by StringSplitter, if necessary.
4017
4018     Collaborations:
4019         In the event that a string line split by StringParenWrapper is
4020         changed such that it no longer needs to be given its own line,
4021         StringParenWrapper relies on StringParenStripper to clean up the
4022         parentheses it created.
4023     """
4024
4025     def do_splitter_match(self, line: Line) -> TMatchResult:
4026         LL = line.leaves
4027
4028         string_idx = (
4029             self._return_match(LL)
4030             or self._else_match(LL)
4031             or self._assert_match(LL)
4032             or self._assign_match(LL)
4033             or self._dict_match(LL)
4034         )
4035
4036         if string_idx is not None:
4037             string_value = line.leaves[string_idx].value
4038             # If the string has no spaces...
4039             if " " not in string_value:
4040                 # And will still violate the line length limit when split...
4041                 max_string_length = self.line_length - ((line.depth + 1) * 4)
4042                 if len(string_value) > max_string_length:
4043                     # And has no associated custom splits...
4044                     if not self.has_custom_splits(string_value):
4045                         # Then we should NOT put this string on its own line.
4046                         return TErr(
4047                             "We do not wrap long strings in parentheses when the"
4048                             " resultant line would still be over the specified line"
4049                             " length and can't be split further by StringSplitter."
4050                         )
4051             return Ok(string_idx)
4052
4053         return TErr("This line does not contain any non-atomic strings.")
4054
4055     @staticmethod
4056     def _return_match(LL: List[Leaf]) -> Optional[int]:
4057         """
4058         Returns:
4059             string_idx such that @LL[string_idx] is equal to our target (i.e.
4060             matched) string, if this line matches the return/yield statement
4061             requirements listed in the 'Requirements' section of this classes'
4062             docstring.
4063                 OR
4064             None, otherwise.
4065         """
4066         # If this line is apart of a return/yield statement and the first leaf
4067         # contains either the "return" or "yield" keywords...
4068         if parent_type(LL[0]) in [syms.return_stmt, syms.yield_expr] and LL[
4069             0
4070         ].value in ["return", "yield"]:
4071             is_valid_index = is_valid_index_factory(LL)
4072
4073             idx = 2 if is_valid_index(1) and is_empty_par(LL[1]) else 1
4074             # The next visible leaf MUST contain a string...
4075             if is_valid_index(idx) and LL[idx].type == token.STRING:
4076                 return idx
4077
4078         return None
4079
4080     @staticmethod
4081     def _else_match(LL: List[Leaf]) -> Optional[int]:
4082         """
4083         Returns:
4084             string_idx such that @LL[string_idx] is equal to our target (i.e.
4085             matched) string, if this line matches the ternary expression
4086             requirements listed in the 'Requirements' section of this classes'
4087             docstring.
4088                 OR
4089             None, otherwise.
4090         """
4091         # If this line is apart of a ternary expression and the first leaf
4092         # contains the "else" keyword...
4093         if (
4094             parent_type(LL[0]) == syms.test
4095             and LL[0].type == token.NAME
4096             and LL[0].value == "else"
4097         ):
4098             is_valid_index = is_valid_index_factory(LL)
4099
4100             idx = 2 if is_valid_index(1) and is_empty_par(LL[1]) else 1
4101             # The next visible leaf MUST contain a string...
4102             if is_valid_index(idx) and LL[idx].type == token.STRING:
4103                 return idx
4104
4105         return None
4106
4107     @staticmethod
4108     def _assert_match(LL: List[Leaf]) -> Optional[int]:
4109         """
4110         Returns:
4111             string_idx such that @LL[string_idx] is equal to our target (i.e.
4112             matched) string, if this line matches the assert statement
4113             requirements listed in the 'Requirements' section of this classes'
4114             docstring.
4115                 OR
4116             None, otherwise.
4117         """
4118         # If this line is apart of an assert statement and the first leaf
4119         # contains the "assert" keyword...
4120         if parent_type(LL[0]) == syms.assert_stmt and LL[0].value == "assert":
4121             is_valid_index = is_valid_index_factory(LL)
4122
4123             for (i, leaf) in enumerate(LL):
4124                 # We MUST find a comma...
4125                 if leaf.type == token.COMMA:
4126                     idx = i + 2 if is_empty_par(LL[i + 1]) else i + 1
4127
4128                     # That comma MUST be followed by a string...
4129                     if is_valid_index(idx) and LL[idx].type == token.STRING:
4130                         string_idx = idx
4131
4132                         # Skip the string trailer, if one exists.
4133                         string_parser = StringParser()
4134                         idx = string_parser.parse(LL, string_idx)
4135
4136                         # But no more leaves are allowed...
4137                         if not is_valid_index(idx):
4138                             return string_idx
4139
4140         return None
4141
4142     @staticmethod
4143     def _assign_match(LL: List[Leaf]) -> Optional[int]:
4144         """
4145         Returns:
4146             string_idx such that @LL[string_idx] is equal to our target (i.e.
4147             matched) string, if this line matches the assignment statement
4148             requirements listed in the 'Requirements' section of this classes'
4149             docstring.
4150                 OR
4151             None, otherwise.
4152         """
4153         # If this line is apart of an expression statement or is a function
4154         # argument AND the first leaf contains a variable name...
4155         if (
4156             parent_type(LL[0]) in [syms.expr_stmt, syms.argument, syms.power]
4157             and LL[0].type == token.NAME
4158         ):
4159             is_valid_index = is_valid_index_factory(LL)
4160
4161             for (i, leaf) in enumerate(LL):
4162                 # We MUST find either an '=' or '+=' symbol...
4163                 if leaf.type in [token.EQUAL, token.PLUSEQUAL]:
4164                     idx = i + 2 if is_empty_par(LL[i + 1]) else i + 1
4165
4166                     # That symbol MUST be followed by a string...
4167                     if is_valid_index(idx) and LL[idx].type == token.STRING:
4168                         string_idx = idx
4169
4170                         # Skip the string trailer, if one exists.
4171                         string_parser = StringParser()
4172                         idx = string_parser.parse(LL, string_idx)
4173
4174                         # The next leaf MAY be a comma iff this line is apart
4175                         # of a function argument...
4176                         if (
4177                             parent_type(LL[0]) == syms.argument
4178                             and is_valid_index(idx)
4179                             and LL[idx].type == token.COMMA
4180                         ):
4181                             idx += 1
4182
4183                         # But no more leaves are allowed...
4184                         if not is_valid_index(idx):
4185                             return string_idx
4186
4187         return None
4188
4189     @staticmethod
4190     def _dict_match(LL: List[Leaf]) -> Optional[int]:
4191         """
4192         Returns:
4193             string_idx such that @LL[string_idx] is equal to our target (i.e.
4194             matched) string, if this line matches the dictionary key assignment
4195             statement requirements listed in the 'Requirements' section of this
4196             classes' docstring.
4197                 OR
4198             None, otherwise.
4199         """
4200         # If this line is apart of a dictionary key assignment...
4201         if syms.dictsetmaker in [parent_type(LL[0]), parent_type(LL[0].parent)]:
4202             is_valid_index = is_valid_index_factory(LL)
4203
4204             for (i, leaf) in enumerate(LL):
4205                 # We MUST find a colon...
4206                 if leaf.type == token.COLON:
4207                     idx = i + 2 if is_empty_par(LL[i + 1]) else i + 1
4208
4209                     # That colon MUST be followed by a string...
4210                     if is_valid_index(idx) and LL[idx].type == token.STRING:
4211                         string_idx = idx
4212
4213                         # Skip the string trailer, if one exists.
4214                         string_parser = StringParser()
4215                         idx = string_parser.parse(LL, string_idx)
4216
4217                         # That string MAY be followed by a comma...
4218                         if is_valid_index(idx) and LL[idx].type == token.COMMA:
4219                             idx += 1
4220
4221                         # But no more leaves are allowed...
4222                         if not is_valid_index(idx):
4223                             return string_idx
4224
4225         return None
4226
4227     def do_transform(self, line: Line, string_idx: int) -> Iterator[TResult[Line]]:
4228         LL = line.leaves
4229
4230         is_valid_index = is_valid_index_factory(LL)
4231         insert_str_child = insert_str_child_factory(LL[string_idx])
4232
4233         comma_idx = -1
4234         ends_with_comma = False
4235         if LL[comma_idx].type == token.COMMA:
4236             ends_with_comma = True
4237
4238         leaves_to_steal_comments_from = [LL[string_idx]]
4239         if ends_with_comma:
4240             leaves_to_steal_comments_from.append(LL[comma_idx])
4241
4242         # --- First Line
4243         first_line = line.clone()
4244         left_leaves = LL[:string_idx]
4245
4246         # We have to remember to account for (possibly invisible) LPAR and RPAR
4247         # leaves that already wrapped the target string. If these leaves do
4248         # exist, we will replace them with our own LPAR and RPAR leaves.
4249         old_parens_exist = False
4250         if left_leaves and left_leaves[-1].type == token.LPAR:
4251             old_parens_exist = True
4252             leaves_to_steal_comments_from.append(left_leaves[-1])
4253             left_leaves.pop()
4254
4255         append_leaves(first_line, line, left_leaves)
4256
4257         lpar_leaf = Leaf(token.LPAR, "(")
4258         if old_parens_exist:
4259             replace_child(LL[string_idx - 1], lpar_leaf)
4260         else:
4261             insert_str_child(lpar_leaf)
4262         first_line.append(lpar_leaf)
4263
4264         # We throw inline comments that were originally to the right of the
4265         # target string to the top line. They will now be shown to the right of
4266         # the LPAR.
4267         for leaf in leaves_to_steal_comments_from:
4268             for comment_leaf in line.comments_after(leaf):
4269                 first_line.append(comment_leaf, preformatted=True)
4270
4271         yield Ok(first_line)
4272
4273         # --- Middle (String) Line
4274         # We only need to yield one (possibly too long) string line, since the
4275         # `StringSplitter` will break it down further if necessary.
4276         string_value = LL[string_idx].value
4277         string_line = Line(
4278             depth=line.depth + 1,
4279             inside_brackets=True,
4280             should_explode=line.should_explode,
4281         )
4282         string_leaf = Leaf(token.STRING, string_value)
4283         insert_str_child(string_leaf)
4284         string_line.append(string_leaf)
4285
4286         old_rpar_leaf = None
4287         if is_valid_index(string_idx + 1):
4288             right_leaves = LL[string_idx + 1 :]
4289             if ends_with_comma:
4290                 right_leaves.pop()
4291
4292             if old_parens_exist:
4293                 assert (
4294                     right_leaves and right_leaves[-1].type == token.RPAR
4295                 ), "Apparently, old parentheses do NOT exist?!"
4296                 old_rpar_leaf = right_leaves.pop()
4297
4298             append_leaves(string_line, line, right_leaves)
4299
4300         yield Ok(string_line)
4301
4302         # --- Last Line
4303         last_line = line.clone()
4304         last_line.bracket_tracker = first_line.bracket_tracker
4305
4306         new_rpar_leaf = Leaf(token.RPAR, ")")
4307         if old_rpar_leaf is not None:
4308             replace_child(old_rpar_leaf, new_rpar_leaf)
4309         else:
4310             insert_str_child(new_rpar_leaf)
4311         last_line.append(new_rpar_leaf)
4312
4313         # If the target string ended with a comma, we place this comma to the
4314         # right of the RPAR on the last line.
4315         if ends_with_comma:
4316             comma_leaf = Leaf(token.COMMA, ",")
4317             replace_child(LL[comma_idx], comma_leaf)
4318             last_line.append(comma_leaf)
4319
4320         yield Ok(last_line)
4321
4322
4323 class StringParser:
4324     """
4325     A state machine that aids in parsing a string's "trailer", which can be
4326     either non-existent, an old-style formatting sequence (e.g. `% varX` or `%
4327     (varX, varY)`), or a method-call / attribute access (e.g. `.format(varX,
4328     varY)`).
4329
4330     NOTE: A new StringParser object MUST be instantiated for each string
4331     trailer we need to parse.
4332
4333     Examples:
4334         We shall assume that `line` equals the `Line` object that corresponds
4335         to the following line of python code:
4336         ```
4337         x = "Some {}.".format("String") + some_other_string
4338         ```
4339
4340         Furthermore, we will assume that `string_idx` is some index such that:
4341         ```
4342         assert line.leaves[string_idx].value == "Some {}."
4343         ```
4344
4345         The following code snippet then holds:
4346         ```
4347         string_parser = StringParser()
4348         idx = string_parser.parse(line.leaves, string_idx)
4349         assert line.leaves[idx].type == token.PLUS
4350         ```
4351     """
4352
4353     DEFAULT_TOKEN = -1
4354
4355     # String Parser States
4356     START = 1
4357     DOT = 2
4358     NAME = 3
4359     PERCENT = 4
4360     SINGLE_FMT_ARG = 5
4361     LPAR = 6
4362     RPAR = 7
4363     DONE = 8
4364
4365     # Lookup Table for Next State
4366     _goto: Dict[Tuple[ParserState, NodeType], ParserState] = {
4367         # A string trailer may start with '.' OR '%'.
4368         (START, token.DOT): DOT,
4369         (START, token.PERCENT): PERCENT,
4370         (START, DEFAULT_TOKEN): DONE,
4371         # A '.' MUST be followed by an attribute or method name.
4372         (DOT, token.NAME): NAME,
4373         # A method name MUST be followed by an '(', whereas an attribute name
4374         # is the last symbol in the string trailer.
4375         (NAME, token.LPAR): LPAR,
4376         (NAME, DEFAULT_TOKEN): DONE,
4377         # A '%' symbol can be followed by an '(' or a single argument (e.g. a
4378         # string or variable name).
4379         (PERCENT, token.LPAR): LPAR,
4380         (PERCENT, DEFAULT_TOKEN): SINGLE_FMT_ARG,
4381         # If a '%' symbol is followed by a single argument, that argument is
4382         # the last leaf in the string trailer.
4383         (SINGLE_FMT_ARG, DEFAULT_TOKEN): DONE,
4384         # If present, a ')' symbol is the last symbol in a string trailer.
4385         # (NOTE: LPARS and nested RPARS are not included in this lookup table,
4386         # since they are treated as a special case by the parsing logic in this
4387         # classes' implementation.)
4388         (RPAR, DEFAULT_TOKEN): DONE,
4389     }
4390
4391     def __init__(self) -> None:
4392         self._state = self.START
4393         self._unmatched_lpars = 0
4394
4395     def parse(self, leaves: List[Leaf], string_idx: int) -> int:
4396         """
4397         Pre-conditions:
4398             * @leaves[@string_idx].type == token.STRING
4399
4400         Returns:
4401             The index directly after the last leaf which is apart of the string
4402             trailer, if a "trailer" exists.
4403                 OR
4404             @string_idx + 1, if no string "trailer" exists.
4405         """
4406         assert leaves[string_idx].type == token.STRING
4407
4408         idx = string_idx + 1
4409         while idx < len(leaves) and self._next_state(leaves[idx]):
4410             idx += 1
4411         return idx
4412
4413     def _next_state(self, leaf: Leaf) -> bool:
4414         """
4415         Pre-conditions:
4416             * On the first call to this function, @leaf MUST be the leaf that
4417             was directly after the string leaf in question (e.g. if our target
4418             string is `line.leaves[i]` then the first call to this method must
4419             be `line.leaves[i + 1]`).
4420             * On the next call to this function, the leaf parameter passed in
4421             MUST be the leaf directly following @leaf.
4422
4423         Returns:
4424             True iff @leaf is apart of the string's trailer.
4425         """
4426         # We ignore empty LPAR or RPAR leaves.
4427         if is_empty_par(leaf):
4428             return True
4429
4430         next_token = leaf.type
4431         if next_token == token.LPAR:
4432             self._unmatched_lpars += 1
4433
4434         current_state = self._state
4435
4436         # The LPAR parser state is a special case. We will return True until we
4437         # find the matching RPAR token.
4438         if current_state == self.LPAR:
4439             if next_token == token.RPAR:
4440                 self._unmatched_lpars -= 1
4441                 if self._unmatched_lpars == 0:
4442                     self._state = self.RPAR
4443         # Otherwise, we use a lookup table to determine the next state.
4444         else:
4445             # If the lookup table matches the current state to the next
4446             # token, we use the lookup table.
4447             if (current_state, next_token) in self._goto:
4448                 self._state = self._goto[current_state, next_token]
4449             else:
4450                 # Otherwise, we check if a the current state was assigned a
4451                 # default.
4452                 if (current_state, self.DEFAULT_TOKEN) in self._goto:
4453                     self._state = self._goto[current_state, self.DEFAULT_TOKEN]
4454                 # If no default has been assigned, then this parser has a logic
4455                 # error.
4456                 else:
4457                     raise RuntimeError(f"{self.__class__.__name__} LOGIC ERROR!")
4458
4459             if self._state == self.DONE:
4460                 return False
4461
4462         return True
4463
4464
4465 def TErr(err_msg: str) -> Err[CannotTransform]:
4466     """(T)ransform Err
4467
4468     Convenience function used when working with the TResult type.
4469     """
4470     cant_transform = CannotTransform(err_msg)
4471     return Err(cant_transform)
4472
4473
4474 def contains_pragma_comment(comment_list: List[Leaf]) -> bool:
4475     """
4476     Returns:
4477         True iff one of the comments in @comment_list is a pragma used by one
4478         of the more common static analysis tools for python (e.g. mypy, flake8,
4479         pylint).
4480     """
4481     for comment in comment_list:
4482         if comment.value.startswith(("# type:", "# noqa", "# pylint:")):
4483             return True
4484
4485     return False
4486
4487
4488 def insert_str_child_factory(string_leaf: Leaf) -> Callable[[LN], None]:
4489     """
4490     Factory for a convenience function that is used to orphan @string_leaf
4491     and then insert multiple new leaves into the same part of the node
4492     structure that @string_leaf had originally occupied.
4493
4494     Examples:
4495         Let `string_leaf = Leaf(token.STRING, '"foo"')` and `N =
4496         string_leaf.parent`. Assume the node `N` has the following
4497         original structure:
4498
4499         Node(
4500             expr_stmt, [
4501                 Leaf(NAME, 'x'),
4502                 Leaf(EQUAL, '='),
4503                 Leaf(STRING, '"foo"'),
4504             ]
4505         )
4506
4507         We then run the code snippet shown below.
4508         ```
4509         insert_str_child = insert_str_child_factory(string_leaf)
4510
4511         lpar = Leaf(token.LPAR, '(')
4512         insert_str_child(lpar)
4513
4514         bar = Leaf(token.STRING, '"bar"')
4515         insert_str_child(bar)
4516
4517         rpar = Leaf(token.RPAR, ')')
4518         insert_str_child(rpar)
4519         ```
4520
4521         After which point, it follows that `string_leaf.parent is None` and
4522         the node `N` now has the following structure:
4523
4524         Node(
4525             expr_stmt, [
4526                 Leaf(NAME, 'x'),
4527                 Leaf(EQUAL, '='),
4528                 Leaf(LPAR, '('),
4529                 Leaf(STRING, '"bar"'),
4530                 Leaf(RPAR, ')'),
4531             ]
4532         )
4533     """
4534     string_parent = string_leaf.parent
4535     string_child_idx = string_leaf.remove()
4536
4537     def insert_str_child(child: LN) -> None:
4538         nonlocal string_child_idx
4539
4540         assert string_parent is not None
4541         assert string_child_idx is not None
4542
4543         string_parent.insert_child(string_child_idx, child)
4544         string_child_idx += 1
4545
4546     return insert_str_child
4547
4548
4549 def has_triple_quotes(string: str) -> bool:
4550     """
4551     Returns:
4552         True iff @string starts with three quotation characters.
4553     """
4554     raw_string = string.lstrip(STRING_PREFIX_CHARS)
4555     return raw_string[:3] in {'"""', "'''"}
4556
4557
4558 def parent_type(node: Optional[LN]) -> Optional[NodeType]:
4559     """
4560     Returns:
4561         @node.parent.type, if @node is not None and has a parent.
4562             OR
4563         None, otherwise.
4564     """
4565     if node is None or node.parent is None:
4566         return None
4567
4568     return node.parent.type
4569
4570
4571 def is_empty_par(leaf: Leaf) -> bool:
4572     return is_empty_lpar(leaf) or is_empty_rpar(leaf)
4573
4574
4575 def is_empty_lpar(leaf: Leaf) -> bool:
4576     return leaf.type == token.LPAR and leaf.value == ""
4577
4578
4579 def is_empty_rpar(leaf: Leaf) -> bool:
4580     return leaf.type == token.RPAR and leaf.value == ""
4581
4582
4583 def is_valid_index_factory(seq: Sequence[Any]) -> Callable[[int], bool]:
4584     """
4585     Examples:
4586         ```
4587         my_list = [1, 2, 3]
4588
4589         is_valid_index = is_valid_index_factory(my_list)
4590
4591         assert is_valid_index(0)
4592         assert is_valid_index(2)
4593
4594         assert not is_valid_index(3)
4595         assert not is_valid_index(-1)
4596         ```
4597     """
4598
4599     def is_valid_index(idx: int) -> bool:
4600         """
4601         Returns:
4602             True iff @idx is positive AND seq[@idx] does NOT raise an
4603             IndexError.
4604         """
4605         return 0 <= idx < len(seq)
4606
4607     return is_valid_index
4608
4609
4610 def line_to_string(line: Line) -> str:
4611     """Returns the string representation of @line.
4612
4613     WARNING: This is known to be computationally expensive.
4614     """
4615     return str(line).strip("\n")
4616
4617
4618 def append_leaves(
4619     new_line: Line, old_line: Line, leaves: List[Leaf], preformatted: bool = False
4620 ) -> None:
4621     """
4622     Append leaves (taken from @old_line) to @new_line, making sure to fix the
4623     underlying Node structure where appropriate.
4624
4625     All of the leaves in @leaves are duplicated. The duplicates are then
4626     appended to @new_line and used to replace their originals in the underlying
4627     Node structure. Any comments attached to the old leaves are reattached to
4628     the new leaves.
4629
4630     Pre-conditions:
4631         set(@leaves) is a subset of set(@old_line.leaves).
4632     """
4633     for old_leaf in leaves:
4634         new_leaf = Leaf(old_leaf.type, old_leaf.value)
4635         replace_child(old_leaf, new_leaf)
4636         new_line.append(new_leaf, preformatted=preformatted)
4637
4638         for comment_leaf in old_line.comments_after(old_leaf):
4639             new_line.append(comment_leaf, preformatted=True)
4640
4641
4642 def replace_child(old_child: LN, new_child: LN) -> None:
4643     """
4644     Side Effects:
4645         * If @old_child.parent is set, replace @old_child with @new_child in
4646         @old_child's underlying Node structure.
4647             OR
4648         * Otherwise, this function does nothing.
4649     """
4650     parent = old_child.parent
4651     if not parent:
4652         return
4653
4654     child_idx = old_child.remove()
4655     if child_idx is not None:
4656         parent.insert_child(child_idx, new_child)
4657
4658
4659 def get_string_prefix(string: str) -> str:
4660     """
4661     Pre-conditions:
4662         * assert_is_leaf_string(@string)
4663
4664     Returns:
4665         @string's prefix (e.g. '', 'r', 'f', or 'rf').
4666     """
4667     assert_is_leaf_string(string)
4668
4669     prefix = ""
4670     prefix_idx = 0
4671     while string[prefix_idx] in STRING_PREFIX_CHARS:
4672         prefix += string[prefix_idx].lower()
4673         prefix_idx += 1
4674
4675     return prefix
4676
4677
4678 def assert_is_leaf_string(string: str) -> None:
4679     """
4680     Checks the pre-condition that @string has the format that you would expect
4681     of `leaf.value` where `leaf` is some Leaf such that `leaf.type ==
4682     token.STRING`. A more precise description of the pre-conditions that are
4683     checked are listed below.
4684
4685     Pre-conditions:
4686         * @string starts with either ', ", <prefix>', or <prefix>" where
4687         `set(<prefix>)` is some subset of `set(STRING_PREFIX_CHARS)`.
4688         * @string ends with a quote character (' or ").
4689
4690     Raises:
4691         AssertionError(...) if the pre-conditions listed above are not
4692         satisfied.
4693     """
4694     dquote_idx = string.find('"')
4695     squote_idx = string.find("'")
4696     if -1 in [dquote_idx, squote_idx]:
4697         quote_idx = max(dquote_idx, squote_idx)
4698     else:
4699         quote_idx = min(squote_idx, dquote_idx)
4700
4701     assert (
4702         0 <= quote_idx < len(string) - 1
4703     ), f"{string!r} is missing a starting quote character (' or \")."
4704     assert string[-1] in (
4705         "'",
4706         '"',
4707     ), f"{string!r} is missing an ending quote character (' or \")."
4708     assert set(string[:quote_idx]).issubset(
4709         set(STRING_PREFIX_CHARS)
4710     ), f"{set(string[:quote_idx])} is NOT a subset of {set(STRING_PREFIX_CHARS)}."
4711
4712
4713 def left_hand_split(line: Line, _features: Collection[Feature] = ()) -> Iterator[Line]:
4714     """Split line into many lines, starting with the first matching bracket pair.
4715
4716     Note: this usually looks weird, only use this for function definitions.
4717     Prefer RHS otherwise.  This is why this function is not symmetrical with
4718     :func:`right_hand_split` which also handles optional parentheses.
4719     """
4720     tail_leaves: List[Leaf] = []
4721     body_leaves: List[Leaf] = []
4722     head_leaves: List[Leaf] = []
4723     current_leaves = head_leaves
4724     matching_bracket: Optional[Leaf] = None
4725     for leaf in line.leaves:
4726         if (
4727             current_leaves is body_leaves
4728             and leaf.type in CLOSING_BRACKETS
4729             and leaf.opening_bracket is matching_bracket
4730         ):
4731             current_leaves = tail_leaves if body_leaves else head_leaves
4732         current_leaves.append(leaf)
4733         if current_leaves is head_leaves:
4734             if leaf.type in OPENING_BRACKETS:
4735                 matching_bracket = leaf
4736                 current_leaves = body_leaves
4737     if not matching_bracket:
4738         raise CannotSplit("No brackets found")
4739
4740     head = bracket_split_build_line(head_leaves, line, matching_bracket)
4741     body = bracket_split_build_line(body_leaves, line, matching_bracket, is_body=True)
4742     tail = bracket_split_build_line(tail_leaves, line, matching_bracket)
4743     bracket_split_succeeded_or_raise(head, body, tail)
4744     for result in (head, body, tail):
4745         if result:
4746             yield result
4747
4748
4749 def right_hand_split(
4750     line: Line,
4751     line_length: int,
4752     features: Collection[Feature] = (),
4753     omit: Collection[LeafID] = (),
4754 ) -> Iterator[Line]:
4755     """Split line into many lines, starting with the last matching bracket pair.
4756
4757     If the split was by optional parentheses, attempt splitting without them, too.
4758     `omit` is a collection of closing bracket IDs that shouldn't be considered for
4759     this split.
4760
4761     Note: running this function modifies `bracket_depth` on the leaves of `line`.
4762     """
4763     tail_leaves: List[Leaf] = []
4764     body_leaves: List[Leaf] = []
4765     head_leaves: List[Leaf] = []
4766     current_leaves = tail_leaves
4767     opening_bracket: Optional[Leaf] = None
4768     closing_bracket: Optional[Leaf] = None
4769     for leaf in reversed(line.leaves):
4770         if current_leaves is body_leaves:
4771             if leaf is opening_bracket:
4772                 current_leaves = head_leaves if body_leaves else tail_leaves
4773         current_leaves.append(leaf)
4774         if current_leaves is tail_leaves:
4775             if leaf.type in CLOSING_BRACKETS and id(leaf) not in omit:
4776                 opening_bracket = leaf.opening_bracket
4777                 closing_bracket = leaf
4778                 current_leaves = body_leaves
4779     if not (opening_bracket and closing_bracket and head_leaves):
4780         # If there is no opening or closing_bracket that means the split failed and
4781         # all content is in the tail.  Otherwise, if `head_leaves` are empty, it means
4782         # the matching `opening_bracket` wasn't available on `line` anymore.
4783         raise CannotSplit("No brackets found")
4784
4785     tail_leaves.reverse()
4786     body_leaves.reverse()
4787     head_leaves.reverse()
4788     head = bracket_split_build_line(head_leaves, line, opening_bracket)
4789     body = bracket_split_build_line(body_leaves, line, opening_bracket, is_body=True)
4790     tail = bracket_split_build_line(tail_leaves, line, opening_bracket)
4791     bracket_split_succeeded_or_raise(head, body, tail)
4792     if (
4793         Feature.FORCE_OPTIONAL_PARENTHESES not in features
4794         # the opening bracket is an optional paren
4795         and opening_bracket.type == token.LPAR
4796         and not opening_bracket.value
4797         # the closing bracket is an optional paren
4798         and closing_bracket.type == token.RPAR
4799         and not closing_bracket.value
4800         # it's not an import (optional parens are the only thing we can split on
4801         # in this case; attempting a split without them is a waste of time)
4802         and not line.is_import
4803         # there are no standalone comments in the body
4804         and not body.contains_standalone_comments(0)
4805         # and we can actually remove the parens
4806         and can_omit_invisible_parens(body, line_length, omit_on_explode=omit)
4807     ):
4808         omit = {id(closing_bracket), *omit}
4809         try:
4810             yield from right_hand_split(line, line_length, features=features, omit=omit)
4811             return
4812
4813         except CannotSplit:
4814             if not (
4815                 can_be_split(body)
4816                 or is_line_short_enough(body, line_length=line_length)
4817             ):
4818                 raise CannotSplit(
4819                     "Splitting failed, body is still too long and can't be split."
4820                 )
4821
4822             elif head.contains_multiline_strings() or tail.contains_multiline_strings():
4823                 raise CannotSplit(
4824                     "The current optional pair of parentheses is bound to fail to"
4825                     " satisfy the splitting algorithm because the head or the tail"
4826                     " contains multiline strings which by definition never fit one"
4827                     " line."
4828                 )
4829
4830     ensure_visible(opening_bracket)
4831     ensure_visible(closing_bracket)
4832     for result in (head, body, tail):
4833         if result:
4834             yield result
4835
4836
4837 def bracket_split_succeeded_or_raise(head: Line, body: Line, tail: Line) -> None:
4838     """Raise :exc:`CannotSplit` if the last left- or right-hand split failed.
4839
4840     Do nothing otherwise.
4841
4842     A left- or right-hand split is based on a pair of brackets. Content before
4843     (and including) the opening bracket is left on one line, content inside the
4844     brackets is put on a separate line, and finally content starting with and
4845     following the closing bracket is put on a separate line.
4846
4847     Those are called `head`, `body`, and `tail`, respectively. If the split
4848     produced the same line (all content in `head`) or ended up with an empty `body`
4849     and the `tail` is just the closing bracket, then it's considered failed.
4850     """
4851     tail_len = len(str(tail).strip())
4852     if not body:
4853         if tail_len == 0:
4854             raise CannotSplit("Splitting brackets produced the same line")
4855
4856         elif tail_len < 3:
4857             raise CannotSplit(
4858                 f"Splitting brackets on an empty body to save {tail_len} characters is"
4859                 " not worth it"
4860             )
4861
4862
4863 def bracket_split_build_line(
4864     leaves: List[Leaf], original: Line, opening_bracket: Leaf, *, is_body: bool = False
4865 ) -> Line:
4866     """Return a new line with given `leaves` and respective comments from `original`.
4867
4868     If `is_body` is True, the result line is one-indented inside brackets and as such
4869     has its first leaf's prefix normalized and a trailing comma added when expected.
4870     """
4871     result = Line(depth=original.depth)
4872     if is_body:
4873         result.inside_brackets = True
4874         result.depth += 1
4875         if leaves:
4876             # Since body is a new indent level, remove spurious leading whitespace.
4877             normalize_prefix(leaves[0], inside_brackets=True)
4878             # Ensure a trailing comma for imports and standalone function arguments, but
4879             # be careful not to add one after any comments or within type annotations.
4880             no_commas = (
4881                 original.is_def
4882                 and opening_bracket.value == "("
4883                 and not any(leaf.type == token.COMMA for leaf in leaves)
4884             )
4885
4886             if original.is_import or no_commas:
4887                 for i in range(len(leaves) - 1, -1, -1):
4888                     if leaves[i].type == STANDALONE_COMMENT:
4889                         continue
4890
4891                     if leaves[i].type != token.COMMA:
4892                         new_comma = Leaf(token.COMMA, ",")
4893                         leaves.insert(i + 1, new_comma)
4894                     break
4895
4896     # Populate the line
4897     for leaf in leaves:
4898         result.append(leaf, preformatted=True)
4899         for comment_after in original.comments_after(leaf):
4900             result.append(comment_after, preformatted=True)
4901     if is_body and should_split_body_explode(result, opening_bracket):
4902         result.should_explode = True
4903     return result
4904
4905
4906 def dont_increase_indentation(split_func: Transformer) -> Transformer:
4907     """Normalize prefix of the first leaf in every line returned by `split_func`.
4908
4909     This is a decorator over relevant split functions.
4910     """
4911
4912     @wraps(split_func)
4913     def split_wrapper(line: Line, features: Collection[Feature] = ()) -> Iterator[Line]:
4914         for line in split_func(line, features):
4915             normalize_prefix(line.leaves[0], inside_brackets=True)
4916             yield line
4917
4918     return split_wrapper
4919
4920
4921 @dont_increase_indentation
4922 def delimiter_split(line: Line, features: Collection[Feature] = ()) -> Iterator[Line]:
4923     """Split according to delimiters of the highest priority.
4924
4925     If the appropriate Features are given, the split will add trailing commas
4926     also in function signatures and calls that contain `*` and `**`.
4927     """
4928     try:
4929         last_leaf = line.leaves[-1]
4930     except IndexError:
4931         raise CannotSplit("Line empty")
4932
4933     bt = line.bracket_tracker
4934     try:
4935         delimiter_priority = bt.max_delimiter_priority(exclude={id(last_leaf)})
4936     except ValueError:
4937         raise CannotSplit("No delimiters found")
4938
4939     if delimiter_priority == DOT_PRIORITY:
4940         if bt.delimiter_count_with_priority(delimiter_priority) == 1:
4941             raise CannotSplit("Splitting a single attribute from its owner looks wrong")
4942
4943     current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
4944     lowest_depth = sys.maxsize
4945     trailing_comma_safe = True
4946
4947     def append_to_line(leaf: Leaf) -> Iterator[Line]:
4948         """Append `leaf` to current line or to new line if appending impossible."""
4949         nonlocal current_line
4950         try:
4951             current_line.append_safe(leaf, preformatted=True)
4952         except ValueError:
4953             yield current_line
4954
4955             current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
4956             current_line.append(leaf)
4957
4958     for leaf in line.leaves:
4959         yield from append_to_line(leaf)
4960
4961         for comment_after in line.comments_after(leaf):
4962             yield from append_to_line(comment_after)
4963
4964         lowest_depth = min(lowest_depth, leaf.bracket_depth)
4965         if leaf.bracket_depth == lowest_depth:
4966             if is_vararg(leaf, within={syms.typedargslist}):
4967                 trailing_comma_safe = (
4968                     trailing_comma_safe and Feature.TRAILING_COMMA_IN_DEF in features
4969                 )
4970             elif is_vararg(leaf, within={syms.arglist, syms.argument}):
4971                 trailing_comma_safe = (
4972                     trailing_comma_safe and Feature.TRAILING_COMMA_IN_CALL in features
4973                 )
4974
4975         leaf_priority = bt.delimiters.get(id(leaf))
4976         if leaf_priority == delimiter_priority:
4977             yield current_line
4978
4979             current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
4980     if current_line:
4981         if (
4982             trailing_comma_safe
4983             and delimiter_priority == COMMA_PRIORITY
4984             and current_line.leaves[-1].type != token.COMMA
4985             and current_line.leaves[-1].type != STANDALONE_COMMENT
4986         ):
4987             new_comma = Leaf(token.COMMA, ",")
4988             current_line.append(new_comma)
4989         yield current_line
4990
4991
4992 @dont_increase_indentation
4993 def standalone_comment_split(
4994     line: Line, features: Collection[Feature] = ()
4995 ) -> Iterator[Line]:
4996     """Split standalone comments from the rest of the line."""
4997     if not line.contains_standalone_comments(0):
4998         raise CannotSplit("Line does not have any standalone comments")
4999
5000     current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
5001
5002     def append_to_line(leaf: Leaf) -> Iterator[Line]:
5003         """Append `leaf` to current line or to new line if appending impossible."""
5004         nonlocal current_line
5005         try:
5006             current_line.append_safe(leaf, preformatted=True)
5007         except ValueError:
5008             yield current_line
5009
5010             current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
5011             current_line.append(leaf)
5012
5013     for leaf in line.leaves:
5014         yield from append_to_line(leaf)
5015
5016         for comment_after in line.comments_after(leaf):
5017             yield from append_to_line(comment_after)
5018
5019     if current_line:
5020         yield current_line
5021
5022
5023 def is_import(leaf: Leaf) -> bool:
5024     """Return True if the given leaf starts an import statement."""
5025     p = leaf.parent
5026     t = leaf.type
5027     v = leaf.value
5028     return bool(
5029         t == token.NAME
5030         and (
5031             (v == "import" and p and p.type == syms.import_name)
5032             or (v == "from" and p and p.type == syms.import_from)
5033         )
5034     )
5035
5036
5037 def is_type_comment(leaf: Leaf, suffix: str = "") -> bool:
5038     """Return True if the given leaf is a special comment.
5039     Only returns true for type comments for now."""
5040     t = leaf.type
5041     v = leaf.value
5042     return t in {token.COMMENT, STANDALONE_COMMENT} and v.startswith("# type:" + suffix)
5043
5044
5045 def normalize_prefix(leaf: Leaf, *, inside_brackets: bool) -> None:
5046     """Leave existing extra newlines if not `inside_brackets`. Remove everything
5047     else.
5048
5049     Note: don't use backslashes for formatting or you'll lose your voting rights.
5050     """
5051     if not inside_brackets:
5052         spl = leaf.prefix.split("#")
5053         if "\\" not in spl[0]:
5054             nl_count = spl[-1].count("\n")
5055             if len(spl) > 1:
5056                 nl_count -= 1
5057             leaf.prefix = "\n" * nl_count
5058             return
5059
5060     leaf.prefix = ""
5061
5062
5063 def normalize_string_prefix(leaf: Leaf, remove_u_prefix: bool = False) -> None:
5064     """Make all string prefixes lowercase.
5065
5066     If remove_u_prefix is given, also removes any u prefix from the string.
5067
5068     Note: Mutates its argument.
5069     """
5070     match = re.match(r"^([" + STRING_PREFIX_CHARS + r"]*)(.*)$", leaf.value, re.DOTALL)
5071     assert match is not None, f"failed to match string {leaf.value!r}"
5072     orig_prefix = match.group(1)
5073     new_prefix = orig_prefix.replace("F", "f").replace("B", "b").replace("U", "u")
5074     if remove_u_prefix:
5075         new_prefix = new_prefix.replace("u", "")
5076     leaf.value = f"{new_prefix}{match.group(2)}"
5077
5078
5079 def normalize_string_quotes(leaf: Leaf) -> None:
5080     """Prefer double quotes but only if it doesn't cause more escaping.
5081
5082     Adds or removes backslashes as appropriate. Doesn't parse and fix
5083     strings nested in f-strings (yet).
5084
5085     Note: Mutates its argument.
5086     """
5087     value = leaf.value.lstrip(STRING_PREFIX_CHARS)
5088     if value[:3] == '"""':
5089         return
5090
5091     elif value[:3] == "'''":
5092         orig_quote = "'''"
5093         new_quote = '"""'
5094     elif value[0] == '"':
5095         orig_quote = '"'
5096         new_quote = "'"
5097     else:
5098         orig_quote = "'"
5099         new_quote = '"'
5100     first_quote_pos = leaf.value.find(orig_quote)
5101     if first_quote_pos == -1:
5102         return  # There's an internal error
5103
5104     prefix = leaf.value[:first_quote_pos]
5105     unescaped_new_quote = re.compile(rf"(([^\\]|^)(\\\\)*){new_quote}")
5106     escaped_new_quote = re.compile(rf"([^\\]|^)\\((?:\\\\)*){new_quote}")
5107     escaped_orig_quote = re.compile(rf"([^\\]|^)\\((?:\\\\)*){orig_quote}")
5108     body = leaf.value[first_quote_pos + len(orig_quote) : -len(orig_quote)]
5109     if "r" in prefix.casefold():
5110         if unescaped_new_quote.search(body):
5111             # There's at least one unescaped new_quote in this raw string
5112             # so converting is impossible
5113             return
5114
5115         # Do not introduce or remove backslashes in raw strings
5116         new_body = body
5117     else:
5118         # remove unnecessary escapes
5119         new_body = sub_twice(escaped_new_quote, rf"\1\2{new_quote}", body)
5120         if body != new_body:
5121             # Consider the string without unnecessary escapes as the original
5122             body = new_body
5123             leaf.value = f"{prefix}{orig_quote}{body}{orig_quote}"
5124         new_body = sub_twice(escaped_orig_quote, rf"\1\2{orig_quote}", new_body)
5125         new_body = sub_twice(unescaped_new_quote, rf"\1\\{new_quote}", new_body)
5126     if "f" in prefix.casefold():
5127         matches = re.findall(
5128             r"""
5129             (?:[^{]|^)\{  # start of the string or a non-{ followed by a single {
5130                 ([^{].*?)  # contents of the brackets except if begins with {{
5131             \}(?:[^}]|$)  # A } followed by end of the string or a non-}
5132             """,
5133             new_body,
5134             re.VERBOSE,
5135         )
5136         for m in matches:
5137             if "\\" in str(m):
5138                 # Do not introduce backslashes in interpolated expressions
5139                 return
5140
5141     if new_quote == '"""' and new_body[-1:] == '"':
5142         # edge case:
5143         new_body = new_body[:-1] + '\\"'
5144     orig_escape_count = body.count("\\")
5145     new_escape_count = new_body.count("\\")
5146     if new_escape_count > orig_escape_count:
5147         return  # Do not introduce more escaping
5148
5149     if new_escape_count == orig_escape_count and orig_quote == '"':
5150         return  # Prefer double quotes
5151
5152     leaf.value = f"{prefix}{new_quote}{new_body}{new_quote}"
5153
5154
5155 def normalize_numeric_literal(leaf: Leaf) -> None:
5156     """Normalizes numeric (float, int, and complex) literals.
5157
5158     All letters used in the representation are normalized to lowercase (except
5159     in Python 2 long literals).
5160     """
5161     text = leaf.value.lower()
5162     if text.startswith(("0o", "0b")):
5163         # Leave octal and binary literals alone.
5164         pass
5165     elif text.startswith("0x"):
5166         # Change hex literals to upper case.
5167         before, after = text[:2], text[2:]
5168         text = f"{before}{after.upper()}"
5169     elif "e" in text:
5170         before, after = text.split("e")
5171         sign = ""
5172         if after.startswith("-"):
5173             after = after[1:]
5174             sign = "-"
5175         elif after.startswith("+"):
5176             after = after[1:]
5177         before = format_float_or_int_string(before)
5178         text = f"{before}e{sign}{after}"
5179     elif text.endswith(("j", "l")):
5180         number = text[:-1]
5181         suffix = text[-1]
5182         # Capitalize in "2L" because "l" looks too similar to "1".
5183         if suffix == "l":
5184             suffix = "L"
5185         text = f"{format_float_or_int_string(number)}{suffix}"
5186     else:
5187         text = format_float_or_int_string(text)
5188     leaf.value = text
5189
5190
5191 def format_float_or_int_string(text: str) -> str:
5192     """Formats a float string like "1.0"."""
5193     if "." not in text:
5194         return text
5195
5196     before, after = text.split(".")
5197     return f"{before or 0}.{after or 0}"
5198
5199
5200 def normalize_invisible_parens(node: Node, parens_after: Set[str]) -> None:
5201     """Make existing optional parentheses invisible or create new ones.
5202
5203     `parens_after` is a set of string leaf values immediately after which parens
5204     should be put.
5205
5206     Standardizes on visible parentheses for single-element tuples, and keeps
5207     existing visible parentheses for other tuples and generator expressions.
5208     """
5209     for pc in list_comments(node.prefix, is_endmarker=False):
5210         if pc.value in FMT_OFF:
5211             # This `node` has a prefix with `# fmt: off`, don't mess with parens.
5212             return
5213     check_lpar = False
5214     for index, child in enumerate(list(node.children)):
5215         # Fixes a bug where invisible parens are not properly stripped from
5216         # assignment statements that contain type annotations.
5217         if isinstance(child, Node) and child.type == syms.annassign:
5218             normalize_invisible_parens(child, parens_after=parens_after)
5219
5220         # Add parentheses around long tuple unpacking in assignments.
5221         if (
5222             index == 0
5223             and isinstance(child, Node)
5224             and child.type == syms.testlist_star_expr
5225         ):
5226             check_lpar = True
5227
5228         if check_lpar:
5229             if is_walrus_assignment(child):
5230                 pass
5231
5232             elif child.type == syms.atom:
5233                 if maybe_make_parens_invisible_in_atom(child, parent=node):
5234                     wrap_in_parentheses(node, child, visible=False)
5235             elif is_one_tuple(child):
5236                 wrap_in_parentheses(node, child, visible=True)
5237             elif node.type == syms.import_from:
5238                 # "import from" nodes store parentheses directly as part of
5239                 # the statement
5240                 if child.type == token.LPAR:
5241                     # make parentheses invisible
5242                     child.value = ""  # type: ignore
5243                     node.children[-1].value = ""  # type: ignore
5244                 elif child.type != token.STAR:
5245                     # insert invisible parentheses
5246                     node.insert_child(index, Leaf(token.LPAR, ""))
5247                     node.append_child(Leaf(token.RPAR, ""))
5248                 break
5249
5250             elif not (isinstance(child, Leaf) and is_multiline_string(child)):
5251                 wrap_in_parentheses(node, child, visible=False)
5252
5253         check_lpar = isinstance(child, Leaf) and child.value in parens_after
5254
5255
5256 def normalize_fmt_off(node: Node) -> None:
5257     """Convert content between `# fmt: off`/`# fmt: on` into standalone comments."""
5258     try_again = True
5259     while try_again:
5260         try_again = convert_one_fmt_off_pair(node)
5261
5262
5263 def convert_one_fmt_off_pair(node: Node) -> bool:
5264     """Convert content of a single `# fmt: off`/`# fmt: on` into a standalone comment.
5265
5266     Returns True if a pair was converted.
5267     """
5268     for leaf in node.leaves():
5269         previous_consumed = 0
5270         for comment in list_comments(leaf.prefix, is_endmarker=False):
5271             if comment.value in FMT_OFF:
5272                 # We only want standalone comments. If there's no previous leaf or
5273                 # the previous leaf is indentation, it's a standalone comment in
5274                 # disguise.
5275                 if comment.type != STANDALONE_COMMENT:
5276                     prev = preceding_leaf(leaf)
5277                     if prev and prev.type not in WHITESPACE:
5278                         continue
5279
5280                 ignored_nodes = list(generate_ignored_nodes(leaf))
5281                 if not ignored_nodes:
5282                     continue
5283
5284                 first = ignored_nodes[0]  # Can be a container node with the `leaf`.
5285                 parent = first.parent
5286                 prefix = first.prefix
5287                 first.prefix = prefix[comment.consumed :]
5288                 hidden_value = (
5289                     comment.value + "\n" + "".join(str(n) for n in ignored_nodes)
5290                 )
5291                 if hidden_value.endswith("\n"):
5292                     # That happens when one of the `ignored_nodes` ended with a NEWLINE
5293                     # leaf (possibly followed by a DEDENT).
5294                     hidden_value = hidden_value[:-1]
5295                 first_idx: Optional[int] = None
5296                 for ignored in ignored_nodes:
5297                     index = ignored.remove()
5298                     if first_idx is None:
5299                         first_idx = index
5300                 assert parent is not None, "INTERNAL ERROR: fmt: on/off handling (1)"
5301                 assert first_idx is not None, "INTERNAL ERROR: fmt: on/off handling (2)"
5302                 parent.insert_child(
5303                     first_idx,
5304                     Leaf(
5305                         STANDALONE_COMMENT,
5306                         hidden_value,
5307                         prefix=prefix[:previous_consumed] + "\n" * comment.newlines,
5308                     ),
5309                 )
5310                 return True
5311
5312             previous_consumed = comment.consumed
5313
5314     return False
5315
5316
5317 def generate_ignored_nodes(leaf: Leaf) -> Iterator[LN]:
5318     """Starting from the container of `leaf`, generate all leaves until `# fmt: on`.
5319
5320     Stops at the end of the block.
5321     """
5322     container: Optional[LN] = container_of(leaf)
5323     while container is not None and container.type != token.ENDMARKER:
5324         if is_fmt_on(container):
5325             return
5326
5327         # fix for fmt: on in children
5328         if contains_fmt_on_at_column(container, leaf.column):
5329             for child in container.children:
5330                 if contains_fmt_on_at_column(child, leaf.column):
5331                     return
5332                 yield child
5333         else:
5334             yield container
5335             container = container.next_sibling
5336
5337
5338 def is_fmt_on(container: LN) -> bool:
5339     """Determine whether formatting is switched on within a container.
5340     Determined by whether the last `# fmt:` comment is `on` or `off`.
5341     """
5342     fmt_on = False
5343     for comment in list_comments(container.prefix, is_endmarker=False):
5344         if comment.value in FMT_ON:
5345             fmt_on = True
5346         elif comment.value in FMT_OFF:
5347             fmt_on = False
5348     return fmt_on
5349
5350
5351 def contains_fmt_on_at_column(container: LN, column: int) -> bool:
5352     """Determine if children at a given column have formatting switched on."""
5353     for child in container.children:
5354         if (
5355             isinstance(child, Node)
5356             and first_leaf_column(child) == column
5357             or isinstance(child, Leaf)
5358             and child.column == column
5359         ):
5360             if is_fmt_on(child):
5361                 return True
5362
5363     return False
5364
5365
5366 def first_leaf_column(node: Node) -> Optional[int]:
5367     """Returns the column of the first leaf child of a node."""
5368     for child in node.children:
5369         if isinstance(child, Leaf):
5370             return child.column
5371     return None
5372
5373
5374 def maybe_make_parens_invisible_in_atom(node: LN, parent: LN) -> bool:
5375     """If it's safe, make the parens in the atom `node` invisible, recursively.
5376     Additionally, remove repeated, adjacent invisible parens from the atom `node`
5377     as they are redundant.
5378
5379     Returns whether the node should itself be wrapped in invisible parentheses.
5380
5381     """
5382     if (
5383         node.type != syms.atom
5384         or is_empty_tuple(node)
5385         or is_one_tuple(node)
5386         or (is_yield(node) and parent.type != syms.expr_stmt)
5387         or max_delimiter_priority_in_atom(node) >= COMMA_PRIORITY
5388     ):
5389         return False
5390
5391     first = node.children[0]
5392     last = node.children[-1]
5393     if first.type == token.LPAR and last.type == token.RPAR:
5394         middle = node.children[1]
5395         # make parentheses invisible
5396         first.value = ""  # type: ignore
5397         last.value = ""  # type: ignore
5398         maybe_make_parens_invisible_in_atom(middle, parent=parent)
5399
5400         if is_atom_with_invisible_parens(middle):
5401             # Strip the invisible parens from `middle` by replacing
5402             # it with the child in-between the invisible parens
5403             middle.replace(middle.children[1])
5404
5405         return False
5406
5407     return True
5408
5409
5410 def is_atom_with_invisible_parens(node: LN) -> bool:
5411     """Given a `LN`, determines whether it's an atom `node` with invisible
5412     parens. Useful in dedupe-ing and normalizing parens.
5413     """
5414     if isinstance(node, Leaf) or node.type != syms.atom:
5415         return False
5416
5417     first, last = node.children[0], node.children[-1]
5418     return (
5419         isinstance(first, Leaf)
5420         and first.type == token.LPAR
5421         and first.value == ""
5422         and isinstance(last, Leaf)
5423         and last.type == token.RPAR
5424         and last.value == ""
5425     )
5426
5427
5428 def is_empty_tuple(node: LN) -> bool:
5429     """Return True if `node` holds an empty tuple."""
5430     return (
5431         node.type == syms.atom
5432         and len(node.children) == 2
5433         and node.children[0].type == token.LPAR
5434         and node.children[1].type == token.RPAR
5435     )
5436
5437
5438 def unwrap_singleton_parenthesis(node: LN) -> Optional[LN]:
5439     """Returns `wrapped` if `node` is of the shape ( wrapped ).
5440
5441     Parenthesis can be optional. Returns None otherwise"""
5442     if len(node.children) != 3:
5443         return None
5444
5445     lpar, wrapped, rpar = node.children
5446     if not (lpar.type == token.LPAR and rpar.type == token.RPAR):
5447         return None
5448
5449     return wrapped
5450
5451
5452 def wrap_in_parentheses(parent: Node, child: LN, *, visible: bool = True) -> None:
5453     """Wrap `child` in parentheses.
5454
5455     This replaces `child` with an atom holding the parentheses and the old
5456     child.  That requires moving the prefix.
5457
5458     If `visible` is False, the leaves will be valueless (and thus invisible).
5459     """
5460     lpar = Leaf(token.LPAR, "(" if visible else "")
5461     rpar = Leaf(token.RPAR, ")" if visible else "")
5462     prefix = child.prefix
5463     child.prefix = ""
5464     index = child.remove() or 0
5465     new_child = Node(syms.atom, [lpar, child, rpar])
5466     new_child.prefix = prefix
5467     parent.insert_child(index, new_child)
5468
5469
5470 def is_one_tuple(node: LN) -> bool:
5471     """Return True if `node` holds a tuple with one element, with or without parens."""
5472     if node.type == syms.atom:
5473         gexp = unwrap_singleton_parenthesis(node)
5474         if gexp is None or gexp.type != syms.testlist_gexp:
5475             return False
5476
5477         return len(gexp.children) == 2 and gexp.children[1].type == token.COMMA
5478
5479     return (
5480         node.type in IMPLICIT_TUPLE
5481         and len(node.children) == 2
5482         and node.children[1].type == token.COMMA
5483     )
5484
5485
5486 def is_walrus_assignment(node: LN) -> bool:
5487     """Return True iff `node` is of the shape ( test := test )"""
5488     inner = unwrap_singleton_parenthesis(node)
5489     return inner is not None and inner.type == syms.namedexpr_test
5490
5491
5492 def is_yield(node: LN) -> bool:
5493     """Return True if `node` holds a `yield` or `yield from` expression."""
5494     if node.type == syms.yield_expr:
5495         return True
5496
5497     if node.type == token.NAME and node.value == "yield":  # type: ignore
5498         return True
5499
5500     if node.type != syms.atom:
5501         return False
5502
5503     if len(node.children) != 3:
5504         return False
5505
5506     lpar, expr, rpar = node.children
5507     if lpar.type == token.LPAR and rpar.type == token.RPAR:
5508         return is_yield(expr)
5509
5510     return False
5511
5512
5513 def is_vararg(leaf: Leaf, within: Set[NodeType]) -> bool:
5514     """Return True if `leaf` is a star or double star in a vararg or kwarg.
5515
5516     If `within` includes VARARGS_PARENTS, this applies to function signatures.
5517     If `within` includes UNPACKING_PARENTS, it applies to right hand-side
5518     extended iterable unpacking (PEP 3132) and additional unpacking
5519     generalizations (PEP 448).
5520     """
5521     if leaf.type not in VARARGS_SPECIALS or not leaf.parent:
5522         return False
5523
5524     p = leaf.parent
5525     if p.type == syms.star_expr:
5526         # Star expressions are also used as assignment targets in extended
5527         # iterable unpacking (PEP 3132).  See what its parent is instead.
5528         if not p.parent:
5529             return False
5530
5531         p = p.parent
5532
5533     return p.type in within
5534
5535
5536 def is_multiline_string(leaf: Leaf) -> bool:
5537     """Return True if `leaf` is a multiline string that actually spans many lines."""
5538     return has_triple_quotes(leaf.value) and "\n" in leaf.value
5539
5540
5541 def is_stub_suite(node: Node) -> bool:
5542     """Return True if `node` is a suite with a stub body."""
5543     if (
5544         len(node.children) != 4
5545         or node.children[0].type != token.NEWLINE
5546         or node.children[1].type != token.INDENT
5547         or node.children[3].type != token.DEDENT
5548     ):
5549         return False
5550
5551     return is_stub_body(node.children[2])
5552
5553
5554 def is_stub_body(node: LN) -> bool:
5555     """Return True if `node` is a simple statement containing an ellipsis."""
5556     if not isinstance(node, Node) or node.type != syms.simple_stmt:
5557         return False
5558
5559     if len(node.children) != 2:
5560         return False
5561
5562     child = node.children[0]
5563     return (
5564         child.type == syms.atom
5565         and len(child.children) == 3
5566         and all(leaf == Leaf(token.DOT, ".") for leaf in child.children)
5567     )
5568
5569
5570 def max_delimiter_priority_in_atom(node: LN) -> Priority:
5571     """Return maximum delimiter priority inside `node`.
5572
5573     This is specific to atoms with contents contained in a pair of parentheses.
5574     If `node` isn't an atom or there are no enclosing parentheses, returns 0.
5575     """
5576     if node.type != syms.atom:
5577         return 0
5578
5579     first = node.children[0]
5580     last = node.children[-1]
5581     if not (first.type == token.LPAR and last.type == token.RPAR):
5582         return 0
5583
5584     bt = BracketTracker()
5585     for c in node.children[1:-1]:
5586         if isinstance(c, Leaf):
5587             bt.mark(c)
5588         else:
5589             for leaf in c.leaves():
5590                 bt.mark(leaf)
5591     try:
5592         return bt.max_delimiter_priority()
5593
5594     except ValueError:
5595         return 0
5596
5597
5598 def ensure_visible(leaf: Leaf) -> None:
5599     """Make sure parentheses are visible.
5600
5601     They could be invisible as part of some statements (see
5602     :func:`normalize_invisible_parens` and :func:`visit_import_from`).
5603     """
5604     if leaf.type == token.LPAR:
5605         leaf.value = "("
5606     elif leaf.type == token.RPAR:
5607         leaf.value = ")"
5608
5609
5610 def should_split_body_explode(line: Line, opening_bracket: Leaf) -> bool:
5611     """Should `line` be immediately split with `delimiter_split()` after RHS?"""
5612
5613     if not (opening_bracket.parent and opening_bracket.value in "[{("):
5614         return False
5615
5616     # We're essentially checking if the body is delimited by commas and there's more
5617     # than one of them (we're excluding the trailing comma and if the delimiter priority
5618     # is still commas, that means there's more).
5619     exclude = set()
5620     trailing_comma = False
5621     try:
5622         last_leaf = line.leaves[-1]
5623         if last_leaf.type == token.COMMA:
5624             trailing_comma = True
5625             exclude.add(id(last_leaf))
5626         max_priority = line.bracket_tracker.max_delimiter_priority(exclude=exclude)
5627     except (IndexError, ValueError):
5628         return False
5629
5630     return max_priority == COMMA_PRIORITY and (
5631         trailing_comma
5632         # always explode imports
5633         or opening_bracket.parent.type in {syms.atom, syms.import_from}
5634     )
5635
5636
5637 def is_one_tuple_between(opening: Leaf, closing: Leaf, leaves: List[Leaf]) -> bool:
5638     """Return True if content between `opening` and `closing` looks like a one-tuple."""
5639     if opening.type != token.LPAR and closing.type != token.RPAR:
5640         return False
5641
5642     depth = closing.bracket_depth + 1
5643     for _opening_index, leaf in enumerate(leaves):
5644         if leaf is opening:
5645             break
5646
5647     else:
5648         raise LookupError("Opening paren not found in `leaves`")
5649
5650     commas = 0
5651     _opening_index += 1
5652     for leaf in leaves[_opening_index:]:
5653         if leaf is closing:
5654             break
5655
5656         bracket_depth = leaf.bracket_depth
5657         if bracket_depth == depth and leaf.type == token.COMMA:
5658             commas += 1
5659             if leaf.parent and leaf.parent.type in {
5660                 syms.arglist,
5661                 syms.typedargslist,
5662             }:
5663                 commas += 1
5664                 break
5665
5666     return commas < 2
5667
5668
5669 def get_features_used(node: Node) -> Set[Feature]:
5670     """Return a set of (relatively) new Python features used in this file.
5671
5672     Currently looking for:
5673     - f-strings;
5674     - underscores in numeric literals;
5675     - trailing commas after * or ** in function signatures and calls;
5676     - positional only arguments in function signatures and lambdas;
5677     """
5678     features: Set[Feature] = set()
5679     for n in node.pre_order():
5680         if n.type == token.STRING:
5681             value_head = n.value[:2]  # type: ignore
5682             if value_head in {'f"', 'F"', "f'", "F'", "rf", "fr", "RF", "FR"}:
5683                 features.add(Feature.F_STRINGS)
5684
5685         elif n.type == token.NUMBER:
5686             if "_" in n.value:  # type: ignore
5687                 features.add(Feature.NUMERIC_UNDERSCORES)
5688
5689         elif n.type == token.SLASH:
5690             if n.parent and n.parent.type in {syms.typedargslist, syms.arglist}:
5691                 features.add(Feature.POS_ONLY_ARGUMENTS)
5692
5693         elif n.type == token.COLONEQUAL:
5694             features.add(Feature.ASSIGNMENT_EXPRESSIONS)
5695
5696         elif (
5697             n.type in {syms.typedargslist, syms.arglist}
5698             and n.children
5699             and n.children[-1].type == token.COMMA
5700         ):
5701             if n.type == syms.typedargslist:
5702                 feature = Feature.TRAILING_COMMA_IN_DEF
5703             else:
5704                 feature = Feature.TRAILING_COMMA_IN_CALL
5705
5706             for ch in n.children:
5707                 if ch.type in STARS:
5708                     features.add(feature)
5709
5710                 if ch.type == syms.argument:
5711                     for argch in ch.children:
5712                         if argch.type in STARS:
5713                             features.add(feature)
5714
5715     return features
5716
5717
5718 def detect_target_versions(node: Node) -> Set[TargetVersion]:
5719     """Detect the version to target based on the nodes used."""
5720     features = get_features_used(node)
5721     return {
5722         version for version in TargetVersion if features <= VERSION_TO_FEATURES[version]
5723     }
5724
5725
5726 def generate_trailers_to_omit(line: Line, line_length: int) -> Iterator[Set[LeafID]]:
5727     """Generate sets of closing bracket IDs that should be omitted in a RHS.
5728
5729     Brackets can be omitted if the entire trailer up to and including
5730     a preceding closing bracket fits in one line.
5731
5732     Yielded sets are cumulative (contain results of previous yields, too).  First
5733     set is empty, unless the line should explode, in which case bracket pairs until
5734     the one that needs to explode are omitted.
5735     """
5736
5737     omit: Set[LeafID] = set()
5738     if not line.should_explode:
5739         yield omit
5740
5741     length = 4 * line.depth
5742     opening_bracket: Optional[Leaf] = None
5743     closing_bracket: Optional[Leaf] = None
5744     inner_brackets: Set[LeafID] = set()
5745     for index, leaf, leaf_length in enumerate_with_length(line, reversed=True):
5746         length += leaf_length
5747         if length > line_length:
5748             break
5749
5750         has_inline_comment = leaf_length > len(leaf.value) + len(leaf.prefix)
5751         if leaf.type == STANDALONE_COMMENT or has_inline_comment:
5752             break
5753
5754         if opening_bracket:
5755             if leaf is opening_bracket:
5756                 opening_bracket = None
5757             elif leaf.type in CLOSING_BRACKETS:
5758                 prev = line.leaves[index - 1] if index > 0 else None
5759                 if (
5760                     line.should_explode
5761                     and prev
5762                     and prev.type == token.COMMA
5763                     and not is_one_tuple_between(
5764                         leaf.opening_bracket, leaf, line.leaves
5765                     )
5766                 ):
5767                     # Never omit bracket pairs with trailing commas.
5768                     # We need to explode on those.
5769                     break
5770
5771                 inner_brackets.add(id(leaf))
5772         elif leaf.type in CLOSING_BRACKETS:
5773             prev = line.leaves[index - 1] if index > 0 else None
5774             if prev and prev.type in OPENING_BRACKETS:
5775                 # Empty brackets would fail a split so treat them as "inner"
5776                 # brackets (e.g. only add them to the `omit` set if another
5777                 # pair of brackets was good enough.
5778                 inner_brackets.add(id(leaf))
5779                 continue
5780
5781             if closing_bracket:
5782                 omit.add(id(closing_bracket))
5783                 omit.update(inner_brackets)
5784                 inner_brackets.clear()
5785                 yield omit
5786
5787             if (
5788                 line.should_explode
5789                 and prev
5790                 and prev.type == token.COMMA
5791                 and not is_one_tuple_between(leaf.opening_bracket, leaf, line.leaves)
5792             ):
5793                 # Never omit bracket pairs with trailing commas.
5794                 # We need to explode on those.
5795                 break
5796
5797             if leaf.value:
5798                 opening_bracket = leaf.opening_bracket
5799                 closing_bracket = leaf
5800
5801
5802 def get_future_imports(node: Node) -> Set[str]:
5803     """Return a set of __future__ imports in the file."""
5804     imports: Set[str] = set()
5805
5806     def get_imports_from_children(children: List[LN]) -> Generator[str, None, None]:
5807         for child in children:
5808             if isinstance(child, Leaf):
5809                 if child.type == token.NAME:
5810                     yield child.value
5811
5812             elif child.type == syms.import_as_name:
5813                 orig_name = child.children[0]
5814                 assert isinstance(orig_name, Leaf), "Invalid syntax parsing imports"
5815                 assert orig_name.type == token.NAME, "Invalid syntax parsing imports"
5816                 yield orig_name.value
5817
5818             elif child.type == syms.import_as_names:
5819                 yield from get_imports_from_children(child.children)
5820
5821             else:
5822                 raise AssertionError("Invalid syntax parsing imports")
5823
5824     for child in node.children:
5825         if child.type != syms.simple_stmt:
5826             break
5827
5828         first_child = child.children[0]
5829         if isinstance(first_child, Leaf):
5830             # Continue looking if we see a docstring; otherwise stop.
5831             if (
5832                 len(child.children) == 2
5833                 and first_child.type == token.STRING
5834                 and child.children[1].type == token.NEWLINE
5835             ):
5836                 continue
5837
5838             break
5839
5840         elif first_child.type == syms.import_from:
5841             module_name = first_child.children[1]
5842             if not isinstance(module_name, Leaf) or module_name.value != "__future__":
5843                 break
5844
5845             imports |= set(get_imports_from_children(first_child.children[3:]))
5846         else:
5847             break
5848
5849     return imports
5850
5851
5852 @lru_cache()
5853 def get_gitignore(root: Path) -> PathSpec:
5854     """ Return a PathSpec matching gitignore content if present."""
5855     gitignore = root / ".gitignore"
5856     lines: List[str] = []
5857     if gitignore.is_file():
5858         with gitignore.open() as gf:
5859             lines = gf.readlines()
5860     return PathSpec.from_lines("gitwildmatch", lines)
5861
5862
5863 def normalize_path_maybe_ignore(
5864     path: Path, root: Path, report: "Report"
5865 ) -> Optional[str]:
5866     """Normalize `path`. May return `None` if `path` was ignored.
5867
5868     `report` is where "path ignored" output goes.
5869     """
5870     try:
5871         abspath = path if path.is_absolute() else Path.cwd() / path
5872         normalized_path = abspath.resolve().relative_to(root).as_posix()
5873     except OSError as e:
5874         report.path_ignored(path, f"cannot be read because {e}")
5875         return None
5876
5877     except ValueError:
5878         if path.is_symlink():
5879             report.path_ignored(path, f"is a symbolic link that points outside {root}")
5880             return None
5881
5882         raise
5883
5884     return normalized_path
5885
5886
5887 def gen_python_files(
5888     paths: Iterable[Path],
5889     root: Path,
5890     include: Optional[Pattern[str]],
5891     exclude: Pattern[str],
5892     force_exclude: Optional[Pattern[str]],
5893     report: "Report",
5894     gitignore: PathSpec,
5895 ) -> Iterator[Path]:
5896     """Generate all files under `path` whose paths are not excluded by the
5897     `exclude_regex` or `force_exclude` regexes, but are included by the `include` regex.
5898
5899     Symbolic links pointing outside of the `root` directory are ignored.
5900
5901     `report` is where output about exclusions goes.
5902     """
5903     assert root.is_absolute(), f"INTERNAL ERROR: `root` must be absolute but is {root}"
5904     for child in paths:
5905         normalized_path = normalize_path_maybe_ignore(child, root, report)
5906         if normalized_path is None:
5907             continue
5908
5909         # First ignore files matching .gitignore
5910         if gitignore.match_file(normalized_path):
5911             report.path_ignored(child, "matches the .gitignore file content")
5912             continue
5913
5914         # Then ignore with `--exclude` and `--force-exclude` options.
5915         normalized_path = "/" + normalized_path
5916         if child.is_dir():
5917             normalized_path += "/"
5918
5919         exclude_match = exclude.search(normalized_path) if exclude else None
5920         if exclude_match and exclude_match.group(0):
5921             report.path_ignored(child, "matches the --exclude regular expression")
5922             continue
5923
5924         force_exclude_match = (
5925             force_exclude.search(normalized_path) if force_exclude else None
5926         )
5927         if force_exclude_match and force_exclude_match.group(0):
5928             report.path_ignored(child, "matches the --force-exclude regular expression")
5929             continue
5930
5931         if child.is_dir():
5932             yield from gen_python_files(
5933                 child.iterdir(),
5934                 root,
5935                 include,
5936                 exclude,
5937                 force_exclude,
5938                 report,
5939                 gitignore,
5940             )
5941
5942         elif child.is_file():
5943             include_match = include.search(normalized_path) if include else True
5944             if include_match:
5945                 yield child
5946
5947
5948 @lru_cache()
5949 def find_project_root(srcs: Iterable[str]) -> Path:
5950     """Return a directory containing .git, .hg, or pyproject.toml.
5951
5952     That directory will be a common parent of all files and directories
5953     passed in `srcs`.
5954
5955     If no directory in the tree contains a marker that would specify it's the
5956     project root, the root of the file system is returned.
5957     """
5958     if not srcs:
5959         return Path("/").resolve()
5960
5961     path_srcs = [Path(Path.cwd(), src).resolve() for src in srcs]
5962
5963     # A list of lists of parents for each 'src'. 'src' is included as a
5964     # "parent" of itself if it is a directory
5965     src_parents = [
5966         list(path.parents) + ([path] if path.is_dir() else []) for path in path_srcs
5967     ]
5968
5969     common_base = max(
5970         set.intersection(*(set(parents) for parents in src_parents)),
5971         key=lambda path: path.parts,
5972     )
5973
5974     for directory in (common_base, *common_base.parents):
5975         if (directory / ".git").exists():
5976             return directory
5977
5978         if (directory / ".hg").is_dir():
5979             return directory
5980
5981         if (directory / "pyproject.toml").is_file():
5982             return directory
5983
5984     return directory
5985
5986
5987 @dataclass
5988 class Report:
5989     """Provides a reformatting counter. Can be rendered with `str(report)`."""
5990
5991     check: bool = False
5992     diff: bool = False
5993     quiet: bool = False
5994     verbose: bool = False
5995     change_count: int = 0
5996     same_count: int = 0
5997     failure_count: int = 0
5998
5999     def done(self, src: Path, changed: Changed) -> None:
6000         """Increment the counter for successful reformatting. Write out a message."""
6001         if changed is Changed.YES:
6002             reformatted = "would reformat" if self.check or self.diff else "reformatted"
6003             if self.verbose or not self.quiet:
6004                 out(f"{reformatted} {src}")
6005             self.change_count += 1
6006         else:
6007             if self.verbose:
6008                 if changed is Changed.NO:
6009                     msg = f"{src} already well formatted, good job."
6010                 else:
6011                     msg = f"{src} wasn't modified on disk since last run."
6012                 out(msg, bold=False)
6013             self.same_count += 1
6014
6015     def failed(self, src: Path, message: str) -> None:
6016         """Increment the counter for failed reformatting. Write out a message."""
6017         err(f"error: cannot format {src}: {message}")
6018         self.failure_count += 1
6019
6020     def path_ignored(self, path: Path, message: str) -> None:
6021         if self.verbose:
6022             out(f"{path} ignored: {message}", bold=False)
6023
6024     @property
6025     def return_code(self) -> int:
6026         """Return the exit code that the app should use.
6027
6028         This considers the current state of changed files and failures:
6029         - if there were any failures, return 123;
6030         - if any files were changed and --check is being used, return 1;
6031         - otherwise return 0.
6032         """
6033         # According to http://tldp.org/LDP/abs/html/exitcodes.html starting with
6034         # 126 we have special return codes reserved by the shell.
6035         if self.failure_count:
6036             return 123
6037
6038         elif self.change_count and self.check:
6039             return 1
6040
6041         return 0
6042
6043     def __str__(self) -> str:
6044         """Render a color report of the current state.
6045
6046         Use `click.unstyle` to remove colors.
6047         """
6048         if self.check or self.diff:
6049             reformatted = "would be reformatted"
6050             unchanged = "would be left unchanged"
6051             failed = "would fail to reformat"
6052         else:
6053             reformatted = "reformatted"
6054             unchanged = "left unchanged"
6055             failed = "failed to reformat"
6056         report = []
6057         if self.change_count:
6058             s = "s" if self.change_count > 1 else ""
6059             report.append(
6060                 click.style(f"{self.change_count} file{s} {reformatted}", bold=True)
6061             )
6062         if self.same_count:
6063             s = "s" if self.same_count > 1 else ""
6064             report.append(f"{self.same_count} file{s} {unchanged}")
6065         if self.failure_count:
6066             s = "s" if self.failure_count > 1 else ""
6067             report.append(
6068                 click.style(f"{self.failure_count} file{s} {failed}", fg="red")
6069             )
6070         return ", ".join(report) + "."
6071
6072
6073 def parse_ast(src: str) -> Union[ast.AST, ast3.AST, ast27.AST]:
6074     filename = "<unknown>"
6075     if sys.version_info >= (3, 8):
6076         # TODO: support Python 4+ ;)
6077         for minor_version in range(sys.version_info[1], 4, -1):
6078             try:
6079                 return ast.parse(src, filename, feature_version=(3, minor_version))
6080             except SyntaxError:
6081                 continue
6082     else:
6083         for feature_version in (7, 6):
6084             try:
6085                 return ast3.parse(src, filename, feature_version=feature_version)
6086             except SyntaxError:
6087                 continue
6088
6089     return ast27.parse(src)
6090
6091
6092 def _fixup_ast_constants(
6093     node: Union[ast.AST, ast3.AST, ast27.AST]
6094 ) -> Union[ast.AST, ast3.AST, ast27.AST]:
6095     """Map ast nodes deprecated in 3.8 to Constant."""
6096     if isinstance(node, (ast.Str, ast3.Str, ast27.Str, ast.Bytes, ast3.Bytes)):
6097         return ast.Constant(value=node.s)
6098
6099     if isinstance(node, (ast.Num, ast3.Num, ast27.Num)):
6100         return ast.Constant(value=node.n)
6101
6102     if isinstance(node, (ast.NameConstant, ast3.NameConstant)):
6103         return ast.Constant(value=node.value)
6104
6105     return node
6106
6107
6108 def _stringify_ast(
6109     node: Union[ast.AST, ast3.AST, ast27.AST], depth: int = 0
6110 ) -> Iterator[str]:
6111     """Simple visitor generating strings to compare ASTs by content."""
6112
6113     node = _fixup_ast_constants(node)
6114
6115     yield f"{'  ' * depth}{node.__class__.__name__}("
6116
6117     for field in sorted(node._fields):  # noqa: F402
6118         # TypeIgnore has only one field 'lineno' which breaks this comparison
6119         type_ignore_classes = (ast3.TypeIgnore, ast27.TypeIgnore)
6120         if sys.version_info >= (3, 8):
6121             type_ignore_classes += (ast.TypeIgnore,)
6122         if isinstance(node, type_ignore_classes):
6123             break
6124
6125         try:
6126             value = getattr(node, field)
6127         except AttributeError:
6128             continue
6129
6130         yield f"{'  ' * (depth+1)}{field}="
6131
6132         if isinstance(value, list):
6133             for item in value:
6134                 # Ignore nested tuples within del statements, because we may insert
6135                 # parentheses and they change the AST.
6136                 if (
6137                     field == "targets"
6138                     and isinstance(node, (ast.Delete, ast3.Delete, ast27.Delete))
6139                     and isinstance(item, (ast.Tuple, ast3.Tuple, ast27.Tuple))
6140                 ):
6141                     for item in item.elts:
6142                         yield from _stringify_ast(item, depth + 2)
6143
6144                 elif isinstance(item, (ast.AST, ast3.AST, ast27.AST)):
6145                     yield from _stringify_ast(item, depth + 2)
6146
6147         elif isinstance(value, (ast.AST, ast3.AST, ast27.AST)):
6148             yield from _stringify_ast(value, depth + 2)
6149
6150         else:
6151             # Constant strings may be indented across newlines, if they are
6152             # docstrings; fold spaces after newlines when comparing. Similarly,
6153             # trailing and leading space may be removed.
6154             if (
6155                 isinstance(node, ast.Constant)
6156                 and field == "value"
6157                 and isinstance(value, str)
6158             ):
6159                 normalized = re.sub(r" *\n[ \t]*", "\n", value).strip()
6160             else:
6161                 normalized = value
6162             yield f"{'  ' * (depth+2)}{normalized!r},  # {value.__class__.__name__}"
6163
6164     yield f"{'  ' * depth})  # /{node.__class__.__name__}"
6165
6166
6167 def assert_equivalent(src: str, dst: str) -> None:
6168     """Raise AssertionError if `src` and `dst` aren't equivalent."""
6169     try:
6170         src_ast = parse_ast(src)
6171     except Exception as exc:
6172         raise AssertionError(
6173             "cannot use --safe with this file; failed to parse source file.  AST"
6174             f" error message: {exc}"
6175         )
6176
6177     try:
6178         dst_ast = parse_ast(dst)
6179     except Exception as exc:
6180         log = dump_to_file("".join(traceback.format_tb(exc.__traceback__)), dst)
6181         raise AssertionError(
6182             f"INTERNAL ERROR: Black produced invalid code: {exc}. Please report a bug"
6183             " on https://github.com/psf/black/issues.  This invalid output might be"
6184             f" helpful: {log}"
6185         ) from None
6186
6187     src_ast_str = "\n".join(_stringify_ast(src_ast))
6188     dst_ast_str = "\n".join(_stringify_ast(dst_ast))
6189     if src_ast_str != dst_ast_str:
6190         log = dump_to_file(diff(src_ast_str, dst_ast_str, "src", "dst"))
6191         raise AssertionError(
6192             "INTERNAL ERROR: Black produced code that is not equivalent to the"
6193             " source.  Please report a bug on https://github.com/psf/black/issues. "
6194             f" This diff might be helpful: {log}"
6195         ) from None
6196
6197
6198 def assert_stable(src: str, dst: str, mode: Mode) -> None:
6199     """Raise AssertionError if `dst` reformats differently the second time."""
6200     newdst = format_str(dst, mode=mode)
6201     if dst != newdst:
6202         log = dump_to_file(
6203             str(mode),
6204             diff(src, dst, "source", "first pass"),
6205             diff(dst, newdst, "first pass", "second pass"),
6206         )
6207         raise AssertionError(
6208             "INTERNAL ERROR: Black produced different code on the second pass of the"
6209             " formatter.  Please report a bug on https://github.com/psf/black/issues."
6210             f"  This diff might be helpful: {log}"
6211         ) from None
6212
6213
6214 @mypyc_attr(patchable=True)
6215 def dump_to_file(*output: str) -> str:
6216     """Dump `output` to a temporary file. Return path to the file."""
6217     with tempfile.NamedTemporaryFile(
6218         mode="w", prefix="blk_", suffix=".log", delete=False, encoding="utf8"
6219     ) as f:
6220         for lines in output:
6221             f.write(lines)
6222             if lines and lines[-1] != "\n":
6223                 f.write("\n")
6224     return f.name
6225
6226
6227 @contextmanager
6228 def nullcontext() -> Iterator[None]:
6229     """Return an empty context manager.
6230
6231     To be used like `nullcontext` in Python 3.7.
6232     """
6233     yield
6234
6235
6236 def diff(a: str, b: str, a_name: str, b_name: str) -> str:
6237     """Return a unified diff string between strings `a` and `b`."""
6238     import difflib
6239
6240     a_lines = [line + "\n" for line in a.splitlines()]
6241     b_lines = [line + "\n" for line in b.splitlines()]
6242     return "".join(
6243         difflib.unified_diff(a_lines, b_lines, fromfile=a_name, tofile=b_name, n=5)
6244     )
6245
6246
6247 def cancel(tasks: Iterable["asyncio.Task[Any]"]) -> None:
6248     """asyncio signal handler that cancels all `tasks` and reports to stderr."""
6249     err("Aborted!")
6250     for task in tasks:
6251         task.cancel()
6252
6253
6254 def shutdown(loop: asyncio.AbstractEventLoop) -> None:
6255     """Cancel all pending tasks on `loop`, wait for them, and close the loop."""
6256     try:
6257         if sys.version_info[:2] >= (3, 7):
6258             all_tasks = asyncio.all_tasks
6259         else:
6260             all_tasks = asyncio.Task.all_tasks
6261         # This part is borrowed from asyncio/runners.py in Python 3.7b2.
6262         to_cancel = [task for task in all_tasks(loop) if not task.done()]
6263         if not to_cancel:
6264             return
6265
6266         for task in to_cancel:
6267             task.cancel()
6268         loop.run_until_complete(
6269             asyncio.gather(*to_cancel, loop=loop, return_exceptions=True)
6270         )
6271     finally:
6272         # `concurrent.futures.Future` objects cannot be cancelled once they
6273         # are already running. There might be some when the `shutdown()` happened.
6274         # Silence their logger's spew about the event loop being closed.
6275         cf_logger = logging.getLogger("concurrent.futures")
6276         cf_logger.setLevel(logging.CRITICAL)
6277         loop.close()
6278
6279
6280 def sub_twice(regex: Pattern[str], replacement: str, original: str) -> str:
6281     """Replace `regex` with `replacement` twice on `original`.
6282
6283     This is used by string normalization to perform replaces on
6284     overlapping matches.
6285     """
6286     return regex.sub(replacement, regex.sub(replacement, original))
6287
6288
6289 def re_compile_maybe_verbose(regex: str) -> Pattern[str]:
6290     """Compile a regular expression string in `regex`.
6291
6292     If it contains newlines, use verbose mode.
6293     """
6294     if "\n" in regex:
6295         regex = "(?x)" + regex
6296     compiled: Pattern[str] = re.compile(regex)
6297     return compiled
6298
6299
6300 def enumerate_reversed(sequence: Sequence[T]) -> Iterator[Tuple[Index, T]]:
6301     """Like `reversed(enumerate(sequence))` if that were possible."""
6302     index = len(sequence) - 1
6303     for element in reversed(sequence):
6304         yield (index, element)
6305         index -= 1
6306
6307
6308 def enumerate_with_length(
6309     line: Line, reversed: bool = False
6310 ) -> Iterator[Tuple[Index, Leaf, int]]:
6311     """Return an enumeration of leaves with their length.
6312
6313     Stops prematurely on multiline strings and standalone comments.
6314     """
6315     op = cast(
6316         Callable[[Sequence[Leaf]], Iterator[Tuple[Index, Leaf]]],
6317         enumerate_reversed if reversed else enumerate,
6318     )
6319     for index, leaf in op(line.leaves):
6320         length = len(leaf.prefix) + len(leaf.value)
6321         if "\n" in leaf.value:
6322             return  # Multiline strings, we can't continue.
6323
6324         for comment in line.comments_after(leaf):
6325             length += len(comment.value)
6326
6327         yield index, leaf, length
6328
6329
6330 def is_line_short_enough(line: Line, *, line_length: int, line_str: str = "") -> bool:
6331     """Return True if `line` is no longer than `line_length`.
6332
6333     Uses the provided `line_str` rendering, if any, otherwise computes a new one.
6334     """
6335     if not line_str:
6336         line_str = line_to_string(line)
6337     return (
6338         len(line_str) <= line_length
6339         and "\n" not in line_str  # multiline strings
6340         and not line.contains_standalone_comments()
6341     )
6342
6343
6344 def can_be_split(line: Line) -> bool:
6345     """Return False if the line cannot be split *for sure*.
6346
6347     This is not an exhaustive search but a cheap heuristic that we can use to
6348     avoid some unfortunate formattings (mostly around wrapping unsplittable code
6349     in unnecessary parentheses).
6350     """
6351     leaves = line.leaves
6352     if len(leaves) < 2:
6353         return False
6354
6355     if leaves[0].type == token.STRING and leaves[1].type == token.DOT:
6356         call_count = 0
6357         dot_count = 0
6358         next = leaves[-1]
6359         for leaf in leaves[-2::-1]:
6360             if leaf.type in OPENING_BRACKETS:
6361                 if next.type not in CLOSING_BRACKETS:
6362                     return False
6363
6364                 call_count += 1
6365             elif leaf.type == token.DOT:
6366                 dot_count += 1
6367             elif leaf.type == token.NAME:
6368                 if not (next.type == token.DOT or next.type in OPENING_BRACKETS):
6369                     return False
6370
6371             elif leaf.type not in CLOSING_BRACKETS:
6372                 return False
6373
6374             if dot_count > 1 and call_count > 1:
6375                 return False
6376
6377     return True
6378
6379
6380 def can_omit_invisible_parens(
6381     line: Line,
6382     line_length: int,
6383     omit_on_explode: Collection[LeafID] = (),
6384 ) -> bool:
6385     """Does `line` have a shape safe to reformat without optional parens around it?
6386
6387     Returns True for only a subset of potentially nice looking formattings but
6388     the point is to not return false positives that end up producing lines that
6389     are too long.
6390     """
6391     bt = line.bracket_tracker
6392     if not bt.delimiters:
6393         # Without delimiters the optional parentheses are useless.
6394         return True
6395
6396     max_priority = bt.max_delimiter_priority()
6397     if bt.delimiter_count_with_priority(max_priority) > 1:
6398         # With more than one delimiter of a kind the optional parentheses read better.
6399         return False
6400
6401     if max_priority == DOT_PRIORITY:
6402         # A single stranded method call doesn't require optional parentheses.
6403         return True
6404
6405     assert len(line.leaves) >= 2, "Stranded delimiter"
6406
6407     # With a single delimiter, omit if the expression starts or ends with
6408     # a bracket.
6409     first = line.leaves[0]
6410     second = line.leaves[1]
6411     if first.type in OPENING_BRACKETS and second.type not in CLOSING_BRACKETS:
6412         if _can_omit_opening_paren(line, first=first, line_length=line_length):
6413             return True
6414
6415         # Note: we are not returning False here because a line might have *both*
6416         # a leading opening bracket and a trailing closing bracket.  If the
6417         # opening bracket doesn't match our rule, maybe the closing will.
6418
6419     penultimate = line.leaves[-2]
6420     last = line.leaves[-1]
6421     if line.should_explode:
6422         try:
6423             penultimate, last = last_two_except(line.leaves, omit=omit_on_explode)
6424         except LookupError:
6425             # Turns out we'd omit everything.  We cannot skip the optional parentheses.
6426             return False
6427
6428     if (
6429         last.type == token.RPAR
6430         or last.type == token.RBRACE
6431         or (
6432             # don't use indexing for omitting optional parentheses;
6433             # it looks weird
6434             last.type == token.RSQB
6435             and last.parent
6436             and last.parent.type != syms.trailer
6437         )
6438     ):
6439         if penultimate.type in OPENING_BRACKETS:
6440             # Empty brackets don't help.
6441             return False
6442
6443         if is_multiline_string(first):
6444             # Additional wrapping of a multiline string in this situation is
6445             # unnecessary.
6446             return True
6447
6448         if line.should_explode and penultimate.type == token.COMMA:
6449             # The rightmost non-omitted bracket pair is the one we want to explode on.
6450             return True
6451
6452         if _can_omit_closing_paren(line, last=last, line_length=line_length):
6453             return True
6454
6455     return False
6456
6457
6458 def _can_omit_opening_paren(line: Line, *, first: Leaf, line_length: int) -> bool:
6459     """See `can_omit_invisible_parens`."""
6460     remainder = False
6461     length = 4 * line.depth
6462     _index = -1
6463     for _index, leaf, leaf_length in enumerate_with_length(line):
6464         if leaf.type in CLOSING_BRACKETS and leaf.opening_bracket is first:
6465             remainder = True
6466         if remainder:
6467             length += leaf_length
6468             if length > line_length:
6469                 break
6470
6471             if leaf.type in OPENING_BRACKETS:
6472                 # There are brackets we can further split on.
6473                 remainder = False
6474
6475     else:
6476         # checked the entire string and line length wasn't exceeded
6477         if len(line.leaves) == _index + 1:
6478             return True
6479
6480     return False
6481
6482
6483 def _can_omit_closing_paren(line: Line, *, last: Leaf, line_length: int) -> bool:
6484     """See `can_omit_invisible_parens`."""
6485     length = 4 * line.depth
6486     seen_other_brackets = False
6487     for _index, leaf, leaf_length in enumerate_with_length(line):
6488         length += leaf_length
6489         if leaf is last.opening_bracket:
6490             if seen_other_brackets or length <= line_length:
6491                 return True
6492
6493         elif leaf.type in OPENING_BRACKETS:
6494             # There are brackets we can further split on.
6495             seen_other_brackets = True
6496
6497     return False
6498
6499
6500 def last_two_except(leaves: List[Leaf], omit: Collection[LeafID]) -> Tuple[Leaf, Leaf]:
6501     """Return (penultimate, last) leaves skipping brackets in `omit` and contents."""
6502     stop_after = None
6503     last = None
6504     for leaf in reversed(leaves):
6505         if stop_after:
6506             if leaf is stop_after:
6507                 stop_after = None
6508             continue
6509
6510         if last:
6511             return leaf, last
6512
6513         if id(leaf) in omit:
6514             stop_after = leaf.opening_bracket
6515         else:
6516             last = leaf
6517     else:
6518         raise LookupError("Last two leaves were also skipped")
6519
6520
6521 def run_transformer(
6522     line: Line,
6523     transform: Transformer,
6524     mode: Mode,
6525     features: Collection[Feature],
6526     *,
6527     line_str: str = "",
6528 ) -> List[Line]:
6529     if not line_str:
6530         line_str = line_to_string(line)
6531     result: List[Line] = []
6532     for transformed_line in transform(line, features):
6533         if str(transformed_line).strip("\n") == line_str:
6534             raise CannotTransform("Line transformer returned an unchanged result")
6535
6536         result.extend(transform_line(transformed_line, mode=mode, features=features))
6537
6538     if not (
6539         transform.__name__ == "rhs"
6540         and line.bracket_tracker.invisible
6541         and not any(bracket.value for bracket in line.bracket_tracker.invisible)
6542         and not line.contains_multiline_strings()
6543         and not result[0].contains_uncollapsable_type_comments()
6544         and not result[0].contains_unsplittable_type_ignore()
6545         and not is_line_short_enough(result[0], line_length=mode.line_length)
6546     ):
6547         return result
6548
6549     line_copy = line.clone()
6550     append_leaves(line_copy, line, line.leaves)
6551     features_fop = set(features) | {Feature.FORCE_OPTIONAL_PARENTHESES}
6552     second_opinion = run_transformer(
6553         line_copy, transform, mode, features_fop, line_str=line_str
6554     )
6555     if all(
6556         is_line_short_enough(ln, line_length=mode.line_length) for ln in second_opinion
6557     ):
6558         result = second_opinion
6559     return result
6560
6561
6562 def get_cache_file(mode: Mode) -> Path:
6563     return CACHE_DIR / f"cache.{mode.get_cache_key()}.pickle"
6564
6565
6566 def read_cache(mode: Mode) -> Cache:
6567     """Read the cache if it exists and is well formed.
6568
6569     If it is not well formed, the call to write_cache later should resolve the issue.
6570     """
6571     cache_file = get_cache_file(mode)
6572     if not cache_file.exists():
6573         return {}
6574
6575     with cache_file.open("rb") as fobj:
6576         try:
6577             cache: Cache = pickle.load(fobj)
6578         except (pickle.UnpicklingError, ValueError):
6579             return {}
6580
6581     return cache
6582
6583
6584 def get_cache_info(path: Path) -> CacheInfo:
6585     """Return the information used to check if a file is already formatted or not."""
6586     stat = path.stat()
6587     return stat.st_mtime, stat.st_size
6588
6589
6590 def filter_cached(cache: Cache, sources: Iterable[Path]) -> Tuple[Set[Path], Set[Path]]:
6591     """Split an iterable of paths in `sources` into two sets.
6592
6593     The first contains paths of files that modified on disk or are not in the
6594     cache. The other contains paths to non-modified files.
6595     """
6596     todo, done = set(), set()
6597     for src in sources:
6598         src = src.resolve()
6599         if cache.get(src) != get_cache_info(src):
6600             todo.add(src)
6601         else:
6602             done.add(src)
6603     return todo, done
6604
6605
6606 def write_cache(cache: Cache, sources: Iterable[Path], mode: Mode) -> None:
6607     """Update the cache file."""
6608     cache_file = get_cache_file(mode)
6609     try:
6610         CACHE_DIR.mkdir(parents=True, exist_ok=True)
6611         new_cache = {**cache, **{src.resolve(): get_cache_info(src) for src in sources}}
6612         with tempfile.NamedTemporaryFile(dir=str(cache_file.parent), delete=False) as f:
6613             pickle.dump(new_cache, f, protocol=4)
6614         os.replace(f.name, cache_file)
6615     except OSError:
6616         pass
6617
6618
6619 def patch_click() -> None:
6620     """Make Click not crash.
6621
6622     On certain misconfigured environments, Python 3 selects the ASCII encoding as the
6623     default which restricts paths that it can access during the lifetime of the
6624     application.  Click refuses to work in this scenario by raising a RuntimeError.
6625
6626     In case of Black the likelihood that non-ASCII characters are going to be used in
6627     file paths is minimal since it's Python source code.  Moreover, this crash was
6628     spurious on Python 3.7 thanks to PEP 538 and PEP 540.
6629     """
6630     try:
6631         from click import core
6632         from click import _unicodefun  # type: ignore
6633     except ModuleNotFoundError:
6634         return
6635
6636     for module in (core, _unicodefun):
6637         if hasattr(module, "_verify_python3_env"):
6638             module._verify_python3_env = lambda: None
6639
6640
6641 def patched_main() -> None:
6642     freeze_support()
6643     patch_click()
6644     main()
6645
6646
6647 def is_docstring(leaf: Leaf) -> bool:
6648     if not is_multiline_string(leaf):
6649         # For the purposes of docstring re-indentation, we don't need to do anything
6650         # with single-line docstrings.
6651         return False
6652
6653     if prev_siblings_are(
6654         leaf.parent, [None, token.NEWLINE, token.INDENT, syms.simple_stmt]
6655     ):
6656         return True
6657
6658     # Multiline docstring on the same line as the `def`.
6659     if prev_siblings_are(leaf.parent, [syms.parameters, token.COLON, syms.simple_stmt]):
6660         # `syms.parameters` is only used in funcdefs and async_funcdefs in the Python
6661         # grammar. We're safe to return True without further checks.
6662         return True
6663
6664     return False
6665
6666
6667 def fix_docstring(docstring: str, prefix: str) -> str:
6668     # https://www.python.org/dev/peps/pep-0257/#handling-docstring-indentation
6669     if not docstring:
6670         return ""
6671     # Convert tabs to spaces (following the normal Python rules)
6672     # and split into a list of lines:
6673     lines = docstring.expandtabs().splitlines()
6674     # Determine minimum indentation (first line doesn't count):
6675     indent = sys.maxsize
6676     for line in lines[1:]:
6677         stripped = line.lstrip()
6678         if stripped:
6679             indent = min(indent, len(line) - len(stripped))
6680     # Remove indentation (first line is special):
6681     trimmed = [lines[0].strip()]
6682     if indent < sys.maxsize:
6683         last_line_idx = len(lines) - 2
6684         for i, line in enumerate(lines[1:]):
6685             stripped_line = line[indent:].rstrip()
6686             if stripped_line or i == last_line_idx:
6687                 trimmed.append(prefix + stripped_line)
6688             else:
6689                 trimmed.append("")
6690     return "\n".join(trimmed)
6691
6692
6693 if __name__ == "__main__":
6694     patched_main()