]> 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:

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