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.
3 from concurrent.futures import Executor, ProcessPoolExecutor
4 from contextlib import contextmanager
5 from datetime import datetime
7 from functools import lru_cache, partial, wraps
11 from multiprocessing import Manager, freeze_support
13 from pathlib import Path
41 from appdirs import user_cache_dir
42 from attr import dataclass, evolve, Factory
45 from typed_ast import ast3, ast27
48 from blib2to3.pytree import Node, Leaf, type_repr
49 from blib2to3 import pygram, pytree
50 from blib2to3.pgen2 import driver, token
51 from blib2to3.pgen2.grammar import Grammar
52 from blib2to3.pgen2.parse import ParseError
55 __version__ = "19.3b0"
56 DEFAULT_LINE_LENGTH = 88
58 r"/(\.eggs|\.git|\.hg|\.mypy_cache|\.nox|\.tox|\.venv|_build|buck-out|build|dist)/"
60 DEFAULT_INCLUDES = r"\.pyi?$"
61 CACHE_DIR = Path(user_cache_dir("black", version=__version__))
73 LN = Union[Leaf, Node]
74 SplitFunc = Callable[["Line", Collection["Feature"]], Iterator["Line"]]
77 CacheInfo = Tuple[Timestamp, FileSize]
78 Cache = Dict[Path, CacheInfo]
79 out = partial(click.secho, bold=True, err=True)
80 err = partial(click.secho, fg="red", err=True)
82 pygram.initialize(CACHE_DIR)
83 syms = pygram.python_symbols
86 class NothingChanged(UserWarning):
87 """Raised when reformatted code is the same as source."""
90 class CannotSplit(Exception):
91 """A readable split that fits the allotted line length is impossible."""
94 class InvalidInput(ValueError):
95 """Raised when input source code fails all parse attempts."""
98 class WriteBack(Enum):
105 def from_configuration(cls, *, check: bool, diff: bool) -> "WriteBack":
106 if check and not diff:
109 return cls.DIFF if diff else cls.YES
118 class TargetVersion(Enum):
127 def is_python2(self) -> bool:
128 return self is TargetVersion.PY27
131 PY36_VERSIONS = {TargetVersion.PY36, TargetVersion.PY37, TargetVersion.PY38}
135 # All string literals are unicode
138 NUMERIC_UNDERSCORES = 3
139 TRAILING_COMMA_IN_CALL = 4
140 TRAILING_COMMA_IN_DEF = 5
141 # The following two feature-flags are mutually exclusive, and exactly one should be
142 # set for every version of python.
143 ASYNC_IDENTIFIERS = 6
145 ASSIGNMENT_EXPRESSIONS = 8
146 POS_ONLY_ARGUMENTS = 9
149 VERSION_TO_FEATURES: Dict[TargetVersion, Set[Feature]] = {
150 TargetVersion.PY27: {Feature.ASYNC_IDENTIFIERS},
151 TargetVersion.PY33: {Feature.UNICODE_LITERALS, Feature.ASYNC_IDENTIFIERS},
152 TargetVersion.PY34: {Feature.UNICODE_LITERALS, Feature.ASYNC_IDENTIFIERS},
153 TargetVersion.PY35: {
154 Feature.UNICODE_LITERALS,
155 Feature.TRAILING_COMMA_IN_CALL,
156 Feature.ASYNC_IDENTIFIERS,
158 TargetVersion.PY36: {
159 Feature.UNICODE_LITERALS,
161 Feature.NUMERIC_UNDERSCORES,
162 Feature.TRAILING_COMMA_IN_CALL,
163 Feature.TRAILING_COMMA_IN_DEF,
164 Feature.ASYNC_IDENTIFIERS,
166 TargetVersion.PY37: {
167 Feature.UNICODE_LITERALS,
169 Feature.NUMERIC_UNDERSCORES,
170 Feature.TRAILING_COMMA_IN_CALL,
171 Feature.TRAILING_COMMA_IN_DEF,
172 Feature.ASYNC_KEYWORDS,
174 TargetVersion.PY38: {
175 Feature.UNICODE_LITERALS,
177 Feature.NUMERIC_UNDERSCORES,
178 Feature.TRAILING_COMMA_IN_CALL,
179 Feature.TRAILING_COMMA_IN_DEF,
180 Feature.ASYNC_KEYWORDS,
181 Feature.ASSIGNMENT_EXPRESSIONS,
182 Feature.POS_ONLY_ARGUMENTS,
189 target_versions: Set[TargetVersion] = Factory(set)
190 line_length: int = DEFAULT_LINE_LENGTH
191 string_normalization: bool = True
194 def get_cache_key(self) -> str:
195 if self.target_versions:
196 version_str = ",".join(
198 for version in sorted(self.target_versions, key=lambda v: v.value)
204 str(self.line_length),
205 str(int(self.string_normalization)),
206 str(int(self.is_pyi)),
208 return ".".join(parts)
211 def supports_feature(target_versions: Set[TargetVersion], feature: Feature) -> bool:
212 return all(feature in VERSION_TO_FEATURES[version] for version in target_versions)
215 def read_pyproject_toml(
216 ctx: click.Context, param: click.Parameter, value: Union[str, int, bool, None]
218 """Inject Black configuration from "pyproject.toml" into defaults in `ctx`.
220 Returns the path to a successfully found and read configuration file, None
223 assert not isinstance(value, (int, bool)), "Invalid parameter type passed"
225 root = find_project_root(ctx.params.get("src", ()))
226 path = root / "pyproject.toml"
233 pyproject_toml = toml.load(value)
234 config = pyproject_toml.get("tool", {}).get("black", {})
235 except (toml.TomlDecodeError, OSError) as e:
236 raise click.FileError(
237 filename=value, hint=f"Error reading configuration file: {e}"
243 if ctx.default_map is None:
245 ctx.default_map.update( # type: ignore # bad types in .pyi
246 {k.replace("--", "").replace("-", "_"): v for k, v in config.items()}
251 @click.command(context_settings=dict(help_option_names=["-h", "--help"]))
252 @click.option("-c", "--code", type=str, help="Format the code passed in as a string.")
257 default=DEFAULT_LINE_LENGTH,
258 help="How many characters per line to allow.",
264 type=click.Choice([v.name.lower() for v in TargetVersion]),
265 callback=lambda c, p, v: [TargetVersion[val.upper()] for val in v],
268 "Python versions that should be supported by Black's output. [default: "
269 "per-file auto-detection]"
276 "Allow using Python 3.6-only syntax on all input files. This will put "
277 "trailing commas in function signatures and calls also after *args and "
278 "**kwargs. Deprecated; use --target-version instead. "
279 "[default: per-file auto-detection]"
286 "Format all input files like typing stubs regardless of file extension "
287 "(useful when piping source on standard input)."
292 "--skip-string-normalization",
294 help="Don't normalize string quotes or prefixes.",
300 "Don't write the files back, just return the status. Return code 0 "
301 "means nothing would change. Return code 1 means some files would be "
302 "reformatted. Return code 123 means there was an internal error."
308 help="Don't write the files back, just output a diff for each file on stdout.",
313 help="If --fast given, skip temporary sanity checks. [default: --safe]",
318 default=DEFAULT_INCLUDES,
320 "A regular expression that matches files and directories that should be "
321 "included on recursive searches. An empty value means all files are "
322 "included regardless of the name. Use forward slashes for directories on "
323 "all platforms (Windows, too). Exclusions are calculated first, inclusions "
331 default=DEFAULT_EXCLUDES,
333 "A regular expression that matches files and directories that should be "
334 "excluded on recursive searches. An empty value means no paths are excluded. "
335 "Use forward slashes for directories on all platforms (Windows, too). "
336 "Exclusions are calculated first, inclusions later."
345 "Don't emit non-error messages to stderr. Errors are still emitted; "
346 "silence those with 2>/dev/null."
354 "Also emit messages to stderr about files that were not changed or were "
355 "ignored due to --exclude=."
358 @click.version_option(version=__version__)
363 exists=True, file_okay=True, dir_okay=True, readable=True, allow_dash=True
370 exists=False, file_okay=True, dir_okay=False, readable=True, allow_dash=False
373 callback=read_pyproject_toml,
374 help="Read configuration from PATH.",
381 target_version: List[TargetVersion],
387 skip_string_normalization: bool,
393 config: Optional[str],
395 """The uncompromising code formatter."""
396 write_back = WriteBack.from_configuration(check=check, diff=diff)
399 err(f"Cannot use both --target-version and --py36")
402 versions = set(target_version)
405 "--py36 is deprecated and will be removed in a future version. "
406 "Use --target-version py36 instead."
408 versions = PY36_VERSIONS
410 # We'll autodetect later.
413 target_versions=versions,
414 line_length=line_length,
416 string_normalization=not skip_string_normalization,
418 if config and verbose:
419 out(f"Using configuration from {config}.", bold=False, fg="blue")
421 print(format_str(code, mode=mode))
424 include_regex = re_compile_maybe_verbose(include)
426 err(f"Invalid regular expression for include given: {include!r}")
429 exclude_regex = re_compile_maybe_verbose(exclude)
431 err(f"Invalid regular expression for exclude given: {exclude!r}")
433 report = Report(check=check, quiet=quiet, verbose=verbose)
434 root = find_project_root(src)
435 sources: Set[Path] = set()
440 gen_python_files_in_dir(p, root, include_regex, exclude_regex, report)
442 elif p.is_file() or s == "-":
443 # if a file was explicitly given, we don't care about its extension
446 err(f"invalid path: {s}")
447 if len(sources) == 0:
448 if verbose or not quiet:
449 out("No paths given. Nothing to do 😴")
452 if len(sources) == 1:
456 write_back=write_back,
462 sources=sources, fast=fast, write_back=write_back, mode=mode, report=report
465 if verbose or not quiet:
466 out("Oh no! 💥 💔 💥" if report.return_code else "All done! ✨ 🍰 ✨")
467 click.secho(str(report), err=True)
468 ctx.exit(report.return_code)
472 src: Path, fast: bool, write_back: WriteBack, mode: FileMode, report: "Report"
474 """Reformat a single file under `src` without spawning child processes.
476 `fast`, `write_back`, and `mode` options are passed to
477 :func:`format_file_in_place` or :func:`format_stdin_to_stdout`.
481 if not src.is_file() and str(src) == "-":
482 if format_stdin_to_stdout(fast=fast, write_back=write_back, mode=mode):
483 changed = Changed.YES
486 if write_back != WriteBack.DIFF:
487 cache = read_cache(mode)
488 res_src = src.resolve()
489 if res_src in cache and cache[res_src] == get_cache_info(res_src):
490 changed = Changed.CACHED
491 if changed is not Changed.CACHED and format_file_in_place(
492 src, fast=fast, write_back=write_back, mode=mode
494 changed = Changed.YES
495 if (write_back is WriteBack.YES and changed is not Changed.CACHED) or (
496 write_back is WriteBack.CHECK and changed is Changed.NO
498 write_cache(cache, [src], mode)
499 report.done(src, changed)
500 except Exception as exc:
501 report.failed(src, str(exc))
507 write_back: WriteBack,
511 """Reformat multiple files using a ProcessPoolExecutor."""
512 loop = asyncio.get_event_loop()
513 worker_count = os.cpu_count()
514 if sys.platform == "win32":
515 # Work around https://bugs.python.org/issue26903
516 worker_count = min(worker_count, 61)
517 executor = ProcessPoolExecutor(max_workers=worker_count)
519 loop.run_until_complete(
523 write_back=write_back,
535 async def schedule_formatting(
538 write_back: WriteBack,
541 loop: asyncio.AbstractEventLoop,
544 """Run formatting of `sources` in parallel using the provided `executor`.
546 (Use ProcessPoolExecutors for actual parallelism.)
548 `write_back`, `fast`, and `mode` options are passed to
549 :func:`format_file_in_place`.
552 if write_back != WriteBack.DIFF:
553 cache = read_cache(mode)
554 sources, cached = filter_cached(cache, sources)
555 for src in sorted(cached):
556 report.done(src, Changed.CACHED)
561 sources_to_cache = []
563 if write_back == WriteBack.DIFF:
564 # For diff output, we need locks to ensure we don't interleave output
565 # from different processes.
567 lock = manager.Lock()
569 asyncio.ensure_future(
570 loop.run_in_executor(
571 executor, format_file_in_place, src, fast, mode, write_back, lock
574 for src in sorted(sources)
576 pending: Iterable[asyncio.Future] = tasks.keys()
578 loop.add_signal_handler(signal.SIGINT, cancel, pending)
579 loop.add_signal_handler(signal.SIGTERM, cancel, pending)
580 except NotImplementedError:
581 # There are no good alternatives for these on Windows.
584 done, _ = await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)
586 src = tasks.pop(task)
588 cancelled.append(task)
589 elif task.exception():
590 report.failed(src, str(task.exception()))
592 changed = Changed.YES if task.result() else Changed.NO
593 # If the file was written back or was successfully checked as
594 # well-formatted, store this information in the cache.
595 if write_back is WriteBack.YES or (
596 write_back is WriteBack.CHECK and changed is Changed.NO
598 sources_to_cache.append(src)
599 report.done(src, changed)
601 await asyncio.gather(*cancelled, loop=loop, return_exceptions=True)
603 write_cache(cache, sources_to_cache, mode)
606 def format_file_in_place(
610 write_back: WriteBack = WriteBack.NO,
611 lock: Any = None, # multiprocessing.Manager().Lock() is some crazy proxy
613 """Format file under `src` path. Return True if changed.
615 If `write_back` is DIFF, write a diff to stdout. If it is YES, write reformatted
617 `mode` and `fast` options are passed to :func:`format_file_contents`.
619 if src.suffix == ".pyi":
620 mode = evolve(mode, is_pyi=True)
622 then = datetime.utcfromtimestamp(src.stat().st_mtime)
623 with open(src, "rb") as buf:
624 src_contents, encoding, newline = decode_bytes(buf.read())
626 dst_contents = format_file_contents(src_contents, fast=fast, mode=mode)
627 except NothingChanged:
630 if write_back == write_back.YES:
631 with open(src, "w", encoding=encoding, newline=newline) as f:
632 f.write(dst_contents)
633 elif write_back == write_back.DIFF:
634 now = datetime.utcnow()
635 src_name = f"{src}\t{then} +0000"
636 dst_name = f"{src}\t{now} +0000"
637 diff_contents = diff(src_contents, dst_contents, src_name, dst_name)
639 with lock or nullcontext():
640 f = io.TextIOWrapper(
646 f.write(diff_contents)
652 def format_stdin_to_stdout(
653 fast: bool, *, write_back: WriteBack = WriteBack.NO, mode: FileMode
655 """Format file on stdin. Return True if changed.
657 If `write_back` is YES, write reformatted code back to stdout. If it is DIFF,
658 write a diff to stdout. The `mode` argument is passed to
659 :func:`format_file_contents`.
661 then = datetime.utcnow()
662 src, encoding, newline = decode_bytes(sys.stdin.buffer.read())
665 dst = format_file_contents(src, fast=fast, mode=mode)
668 except NothingChanged:
672 f = io.TextIOWrapper(
673 sys.stdout.buffer, encoding=encoding, newline=newline, write_through=True
675 if write_back == WriteBack.YES:
677 elif write_back == WriteBack.DIFF:
678 now = datetime.utcnow()
679 src_name = f"STDIN\t{then} +0000"
680 dst_name = f"STDOUT\t{now} +0000"
681 f.write(diff(src, dst, src_name, dst_name))
685 def format_file_contents(
686 src_contents: str, *, fast: bool, mode: FileMode
688 """Reformat contents a file and return new contents.
690 If `fast` is False, additionally confirm that the reformatted code is
691 valid by calling :func:`assert_equivalent` and :func:`assert_stable` on it.
692 `mode` is passed to :func:`format_str`.
694 if src_contents.strip() == "":
697 dst_contents = format_str(src_contents, mode=mode)
698 if src_contents == dst_contents:
702 assert_equivalent(src_contents, dst_contents)
703 assert_stable(src_contents, dst_contents, mode=mode)
707 def format_str(src_contents: str, *, mode: FileMode) -> FileContent:
708 """Reformat a string and return new contents.
710 `mode` determines formatting options, such as how many characters per line are
713 src_node = lib2to3_parse(src_contents.lstrip(), mode.target_versions)
715 future_imports = get_future_imports(src_node)
716 if mode.target_versions:
717 versions = mode.target_versions
719 versions = detect_target_versions(src_node)
720 normalize_fmt_off(src_node)
721 lines = LineGenerator(
722 remove_u_prefix="unicode_literals" in future_imports
723 or supports_feature(versions, Feature.UNICODE_LITERALS),
725 normalize_strings=mode.string_normalization,
727 elt = EmptyLineTracker(is_pyi=mode.is_pyi)
730 split_line_features = {
732 for feature in {Feature.TRAILING_COMMA_IN_CALL, Feature.TRAILING_COMMA_IN_DEF}
733 if supports_feature(versions, feature)
735 for current_line in lines.visit(src_node):
736 for _ in range(after):
737 dst_contents.append(str(empty_line))
738 before, after = elt.maybe_empty_lines(current_line)
739 for _ in range(before):
740 dst_contents.append(str(empty_line))
741 for line in split_line(
742 current_line, line_length=mode.line_length, features=split_line_features
744 dst_contents.append(str(line))
745 return "".join(dst_contents)
748 def decode_bytes(src: bytes) -> Tuple[FileContent, Encoding, NewLine]:
749 """Return a tuple of (decoded_contents, encoding, newline).
751 `newline` is either CRLF or LF but `decoded_contents` is decoded with
752 universal newlines (i.e. only contains LF).
754 srcbuf = io.BytesIO(src)
755 encoding, lines = tokenize.detect_encoding(srcbuf.readline)
757 return "", encoding, "\n"
759 newline = "\r\n" if b"\r\n" == lines[0][-2:] else "\n"
761 with io.TextIOWrapper(srcbuf, encoding) as tiow:
762 return tiow.read(), encoding, newline
765 def get_grammars(target_versions: Set[TargetVersion]) -> List[Grammar]:
766 if not target_versions:
767 # No target_version specified, so try all grammars.
770 pygram.python_grammar_no_print_statement_no_exec_statement_async_keywords,
772 pygram.python_grammar_no_print_statement_no_exec_statement,
773 # Python 2.7 with future print_function import
774 pygram.python_grammar_no_print_statement,
776 pygram.python_grammar,
778 elif all(version.is_python2() for version in target_versions):
779 # Python 2-only code, so try Python 2 grammars.
781 # Python 2.7 with future print_function import
782 pygram.python_grammar_no_print_statement,
784 pygram.python_grammar,
787 # Python 3-compatible code, so only try Python 3 grammar.
789 # If we have to parse both, try to parse async as a keyword first
790 if not supports_feature(target_versions, Feature.ASYNC_IDENTIFIERS):
793 pygram.python_grammar_no_print_statement_no_exec_statement_async_keywords # noqa: B950
795 if not supports_feature(target_versions, Feature.ASYNC_KEYWORDS):
797 grammars.append(pygram.python_grammar_no_print_statement_no_exec_statement)
798 # At least one of the above branches must have been taken, because every Python
799 # version has exactly one of the two 'ASYNC_*' flags
803 def lib2to3_parse(src_txt: str, target_versions: Iterable[TargetVersion] = ()) -> Node:
804 """Given a string with source, return the lib2to3 Node."""
805 if src_txt[-1:] != "\n":
808 for grammar in get_grammars(set(target_versions)):
809 drv = driver.Driver(grammar, pytree.convert)
811 result = drv.parse_string(src_txt, True)
814 except ParseError as pe:
815 lineno, column = pe.context[1]
816 lines = src_txt.splitlines()
818 faulty_line = lines[lineno - 1]
820 faulty_line = "<line number missing in source>"
821 exc = InvalidInput(f"Cannot parse: {lineno}:{column}: {faulty_line}")
825 if isinstance(result, Leaf):
826 result = Node(syms.file_input, [result])
830 def lib2to3_unparse(node: Node) -> str:
831 """Given a lib2to3 node, return its string representation."""
839 class Visitor(Generic[T]):
840 """Basic lib2to3 visitor that yields things of type `T` on `visit()`."""
842 def visit(self, node: LN) -> Iterator[T]:
843 """Main method to visit `node` and its children.
845 It tries to find a `visit_*()` method for the given `node.type`, like
846 `visit_simple_stmt` for Node objects or `visit_INDENT` for Leaf objects.
847 If no dedicated `visit_*()` method is found, chooses `visit_default()`
850 Then yields objects of type `T` from the selected visitor.
853 name = token.tok_name[node.type]
855 name = type_repr(node.type)
856 yield from getattr(self, f"visit_{name}", self.visit_default)(node)
858 def visit_default(self, node: LN) -> Iterator[T]:
859 """Default `visit_*()` implementation. Recurses to children of `node`."""
860 if isinstance(node, Node):
861 for child in node.children:
862 yield from self.visit(child)
866 class DebugVisitor(Visitor[T]):
869 def visit_default(self, node: LN) -> Iterator[T]:
870 indent = " " * (2 * self.tree_depth)
871 if isinstance(node, Node):
872 _type = type_repr(node.type)
873 out(f"{indent}{_type}", fg="yellow")
875 for child in node.children:
876 yield from self.visit(child)
879 out(f"{indent}/{_type}", fg="yellow", bold=False)
881 _type = token.tok_name.get(node.type, str(node.type))
882 out(f"{indent}{_type}", fg="blue", nl=False)
884 # We don't have to handle prefixes for `Node` objects since
885 # that delegates to the first child anyway.
886 out(f" {node.prefix!r}", fg="green", bold=False, nl=False)
887 out(f" {node.value!r}", fg="blue", bold=False)
890 def show(cls, code: Union[str, Leaf, Node]) -> None:
891 """Pretty-print the lib2to3 AST of a given string of `code`.
893 Convenience method for debugging.
895 v: DebugVisitor[None] = DebugVisitor()
896 if isinstance(code, str):
897 code = lib2to3_parse(code)
901 WHITESPACE = {token.DEDENT, token.INDENT, token.NEWLINE}
912 STANDALONE_COMMENT = 153
913 token.tok_name[STANDALONE_COMMENT] = "STANDALONE_COMMENT"
914 LOGIC_OPERATORS = {"and", "or"}
939 STARS = {token.STAR, token.DOUBLESTAR}
940 VARARGS_SPECIALS = STARS | {token.SLASH}
943 syms.argument, # double star in arglist
944 syms.trailer, # single argument to call
946 syms.varargslist, # lambdas
948 UNPACKING_PARENTS = {
949 syms.atom, # single element of a list or set literal
953 syms.testlist_star_expr,
988 COMPREHENSION_PRIORITY = 20
990 TERNARY_PRIORITY = 16
993 COMPARATOR_PRIORITY = 10
1004 token.DOUBLESLASH: 4,
1008 token.DOUBLESTAR: 2,
1014 class BracketTracker:
1015 """Keeps track of brackets on a line."""
1018 bracket_match: Dict[Tuple[Depth, NodeType], Leaf] = Factory(dict)
1019 delimiters: Dict[LeafID, Priority] = Factory(dict)
1020 previous: Optional[Leaf] = None
1021 _for_loop_depths: List[int] = Factory(list)
1022 _lambda_argument_depths: List[int] = Factory(list)
1024 def mark(self, leaf: Leaf) -> None:
1025 """Mark `leaf` with bracket-related metadata. Keep track of delimiters.
1027 All leaves receive an int `bracket_depth` field that stores how deep
1028 within brackets a given leaf is. 0 means there are no enclosing brackets
1029 that started on this line.
1031 If a leaf is itself a closing bracket, it receives an `opening_bracket`
1032 field that it forms a pair with. This is a one-directional link to
1033 avoid reference cycles.
1035 If a leaf is a delimiter (a token on which Black can split the line if
1036 needed) and it's on depth 0, its `id()` is stored in the tracker's
1039 if leaf.type == token.COMMENT:
1042 self.maybe_decrement_after_for_loop_variable(leaf)
1043 self.maybe_decrement_after_lambda_arguments(leaf)
1044 if leaf.type in CLOSING_BRACKETS:
1046 opening_bracket = self.bracket_match.pop((self.depth, leaf.type))
1047 leaf.opening_bracket = opening_bracket
1048 leaf.bracket_depth = self.depth
1050 delim = is_split_before_delimiter(leaf, self.previous)
1051 if delim and self.previous is not None:
1052 self.delimiters[id(self.previous)] = delim
1054 delim = is_split_after_delimiter(leaf, self.previous)
1056 self.delimiters[id(leaf)] = delim
1057 if leaf.type in OPENING_BRACKETS:
1058 self.bracket_match[self.depth, BRACKET[leaf.type]] = leaf
1060 self.previous = leaf
1061 self.maybe_increment_lambda_arguments(leaf)
1062 self.maybe_increment_for_loop_variable(leaf)
1064 def any_open_brackets(self) -> bool:
1065 """Return True if there is an yet unmatched open bracket on the line."""
1066 return bool(self.bracket_match)
1068 def max_delimiter_priority(self, exclude: Iterable[LeafID] = ()) -> Priority:
1069 """Return the highest priority of a delimiter found on the line.
1071 Values are consistent with what `is_split_*_delimiter()` return.
1072 Raises ValueError on no delimiters.
1074 return max(v for k, v in self.delimiters.items() if k not in exclude)
1076 def delimiter_count_with_priority(self, priority: Priority = 0) -> int:
1077 """Return the number of delimiters with the given `priority`.
1079 If no `priority` is passed, defaults to max priority on the line.
1081 if not self.delimiters:
1084 priority = priority or self.max_delimiter_priority()
1085 return sum(1 for p in self.delimiters.values() if p == priority)
1087 def maybe_increment_for_loop_variable(self, leaf: Leaf) -> bool:
1088 """In a for loop, or comprehension, the variables are often unpacks.
1090 To avoid splitting on the comma in this situation, increase the depth of
1091 tokens between `for` and `in`.
1093 if leaf.type == token.NAME and leaf.value == "for":
1095 self._for_loop_depths.append(self.depth)
1100 def maybe_decrement_after_for_loop_variable(self, leaf: Leaf) -> bool:
1101 """See `maybe_increment_for_loop_variable` above for explanation."""
1103 self._for_loop_depths
1104 and self._for_loop_depths[-1] == self.depth
1105 and leaf.type == token.NAME
1106 and leaf.value == "in"
1109 self._for_loop_depths.pop()
1114 def maybe_increment_lambda_arguments(self, leaf: Leaf) -> bool:
1115 """In a lambda expression, there might be more than one argument.
1117 To avoid splitting on the comma in this situation, increase the depth of
1118 tokens between `lambda` and `:`.
1120 if leaf.type == token.NAME and leaf.value == "lambda":
1122 self._lambda_argument_depths.append(self.depth)
1127 def maybe_decrement_after_lambda_arguments(self, leaf: Leaf) -> bool:
1128 """See `maybe_increment_lambda_arguments` above for explanation."""
1130 self._lambda_argument_depths
1131 and self._lambda_argument_depths[-1] == self.depth
1132 and leaf.type == token.COLON
1135 self._lambda_argument_depths.pop()
1140 def get_open_lsqb(self) -> Optional[Leaf]:
1141 """Return the most recent opening square bracket (if any)."""
1142 return self.bracket_match.get((self.depth - 1, token.RSQB))
1147 """Holds leaves and comments. Can be printed with `str(line)`."""
1150 leaves: List[Leaf] = Factory(list)
1151 comments: Dict[LeafID, List[Leaf]] = Factory(dict) # keys ordered like `leaves`
1152 bracket_tracker: BracketTracker = Factory(BracketTracker)
1153 inside_brackets: bool = False
1154 should_explode: bool = False
1156 def append(self, leaf: Leaf, preformatted: bool = False) -> None:
1157 """Add a new `leaf` to the end of the line.
1159 Unless `preformatted` is True, the `leaf` will receive a new consistent
1160 whitespace prefix and metadata applied by :class:`BracketTracker`.
1161 Trailing commas are maybe removed, unpacked for loop variables are
1162 demoted from being delimiters.
1164 Inline comments are put aside.
1166 has_value = leaf.type in BRACKETS or bool(leaf.value.strip())
1170 if token.COLON == leaf.type and self.is_class_paren_empty:
1171 del self.leaves[-2:]
1172 if self.leaves and not preformatted:
1173 # Note: at this point leaf.prefix should be empty except for
1174 # imports, for which we only preserve newlines.
1175 leaf.prefix += whitespace(
1176 leaf, complex_subscript=self.is_complex_subscript(leaf)
1178 if self.inside_brackets or not preformatted:
1179 self.bracket_tracker.mark(leaf)
1180 self.maybe_remove_trailing_comma(leaf)
1181 if not self.append_comment(leaf):
1182 self.leaves.append(leaf)
1184 def append_safe(self, leaf: Leaf, preformatted: bool = False) -> None:
1185 """Like :func:`append()` but disallow invalid standalone comment structure.
1187 Raises ValueError when any `leaf` is appended after a standalone comment
1188 or when a standalone comment is not the first leaf on the line.
1190 if self.bracket_tracker.depth == 0:
1192 raise ValueError("cannot append to standalone comments")
1194 if self.leaves and leaf.type == STANDALONE_COMMENT:
1196 "cannot append standalone comments to a populated line"
1199 self.append(leaf, preformatted=preformatted)
1202 def is_comment(self) -> bool:
1203 """Is this line a standalone comment?"""
1204 return len(self.leaves) == 1 and self.leaves[0].type == STANDALONE_COMMENT
1207 def is_decorator(self) -> bool:
1208 """Is this line a decorator?"""
1209 return bool(self) and self.leaves[0].type == token.AT
1212 def is_import(self) -> bool:
1213 """Is this an import line?"""
1214 return bool(self) and is_import(self.leaves[0])
1217 def is_class(self) -> bool:
1218 """Is this line a class definition?"""
1221 and self.leaves[0].type == token.NAME
1222 and self.leaves[0].value == "class"
1226 def is_stub_class(self) -> bool:
1227 """Is this line a class definition with a body consisting only of "..."?"""
1228 return self.is_class and self.leaves[-3:] == [
1229 Leaf(token.DOT, ".") for _ in range(3)
1233 def is_def(self) -> bool:
1234 """Is this a function definition? (Also returns True for async defs.)"""
1236 first_leaf = self.leaves[0]
1241 second_leaf: Optional[Leaf] = self.leaves[1]
1244 return (first_leaf.type == token.NAME and first_leaf.value == "def") or (
1245 first_leaf.type == token.ASYNC
1246 and second_leaf is not None
1247 and second_leaf.type == token.NAME
1248 and second_leaf.value == "def"
1252 def is_class_paren_empty(self) -> bool:
1253 """Is this a class with no base classes but using parentheses?
1255 Those are unnecessary and should be removed.
1259 and len(self.leaves) == 4
1261 and self.leaves[2].type == token.LPAR
1262 and self.leaves[2].value == "("
1263 and self.leaves[3].type == token.RPAR
1264 and self.leaves[3].value == ")"
1268 def is_triple_quoted_string(self) -> bool:
1269 """Is the line a triple quoted string?"""
1272 and self.leaves[0].type == token.STRING
1273 and self.leaves[0].value.startswith(('"""', "'''"))
1276 def contains_standalone_comments(self, depth_limit: int = sys.maxsize) -> bool:
1277 """If so, needs to be split before emitting."""
1278 for leaf in self.leaves:
1279 if leaf.type == STANDALONE_COMMENT:
1280 if leaf.bracket_depth <= depth_limit:
1284 def contains_inner_type_comments(self) -> bool:
1287 last_leaf = self.leaves[-1]
1288 ignored_ids.add(id(last_leaf))
1289 if last_leaf.type == token.COMMA or (
1290 last_leaf.type == token.RPAR and not last_leaf.value
1292 # When trailing commas or optional parens are inserted by Black for
1293 # consistency, comments after the previous last element are not moved
1294 # (they don't have to, rendering will still be correct). So we ignore
1295 # trailing commas and invisible.
1296 last_leaf = self.leaves[-2]
1297 ignored_ids.add(id(last_leaf))
1301 for leaf_id, comments in self.comments.items():
1302 if leaf_id in ignored_ids:
1305 for comment in comments:
1306 if is_type_comment(comment):
1311 def contains_multiline_strings(self) -> bool:
1312 for leaf in self.leaves:
1313 if is_multiline_string(leaf):
1318 def maybe_remove_trailing_comma(self, closing: Leaf) -> bool:
1319 """Remove trailing comma if there is one and it's safe."""
1322 and self.leaves[-1].type == token.COMMA
1323 and closing.type in CLOSING_BRACKETS
1327 if closing.type == token.RBRACE:
1328 self.remove_trailing_comma()
1331 if closing.type == token.RSQB:
1332 comma = self.leaves[-1]
1333 if comma.parent and comma.parent.type == syms.listmaker:
1334 self.remove_trailing_comma()
1337 # For parens let's check if it's safe to remove the comma.
1338 # Imports are always safe.
1340 self.remove_trailing_comma()
1343 # Otherwise, if the trailing one is the only one, we might mistakenly
1344 # change a tuple into a different type by removing the comma.
1345 depth = closing.bracket_depth + 1
1347 opening = closing.opening_bracket
1348 for _opening_index, leaf in enumerate(self.leaves):
1355 for leaf in self.leaves[_opening_index + 1 :]:
1359 bracket_depth = leaf.bracket_depth
1360 if bracket_depth == depth and leaf.type == token.COMMA:
1362 if leaf.parent and leaf.parent.type in {
1370 self.remove_trailing_comma()
1375 def append_comment(self, comment: Leaf) -> bool:
1376 """Add an inline or standalone comment to the line."""
1378 comment.type == STANDALONE_COMMENT
1379 and self.bracket_tracker.any_open_brackets()
1384 if comment.type != token.COMMENT:
1388 comment.type = STANDALONE_COMMENT
1392 last_leaf = self.leaves[-1]
1394 last_leaf.type == token.RPAR
1395 and not last_leaf.value
1396 and last_leaf.parent
1397 and len(list(last_leaf.parent.leaves())) <= 3
1398 and not is_type_comment(comment)
1400 # Comments on an optional parens wrapping a single leaf should belong to
1401 # the wrapped node except if it's a type comment. Pinning the comment like
1402 # this avoids unstable formatting caused by comment migration.
1403 if len(self.leaves) < 2:
1404 comment.type = STANDALONE_COMMENT
1407 last_leaf = self.leaves[-2]
1408 self.comments.setdefault(id(last_leaf), []).append(comment)
1411 def comments_after(self, leaf: Leaf) -> List[Leaf]:
1412 """Generate comments that should appear directly after `leaf`."""
1413 return self.comments.get(id(leaf), [])
1415 def remove_trailing_comma(self) -> None:
1416 """Remove the trailing comma and moves the comments attached to it."""
1417 trailing_comma = self.leaves.pop()
1418 trailing_comma_comments = self.comments.pop(id(trailing_comma), [])
1419 self.comments.setdefault(id(self.leaves[-1]), []).extend(
1420 trailing_comma_comments
1423 def is_complex_subscript(self, leaf: Leaf) -> bool:
1424 """Return True iff `leaf` is part of a slice with non-trivial exprs."""
1425 open_lsqb = self.bracket_tracker.get_open_lsqb()
1426 if open_lsqb is None:
1429 subscript_start = open_lsqb.next_sibling
1431 if isinstance(subscript_start, Node):
1432 if subscript_start.type == syms.listmaker:
1435 if subscript_start.type == syms.subscriptlist:
1436 subscript_start = child_towards(subscript_start, leaf)
1437 return subscript_start is not None and any(
1438 n.type in TEST_DESCENDANTS for n in subscript_start.pre_order()
1441 def __str__(self) -> str:
1442 """Render the line."""
1446 indent = " " * self.depth
1447 leaves = iter(self.leaves)
1448 first = next(leaves)
1449 res = f"{first.prefix}{indent}{first.value}"
1452 for comment in itertools.chain.from_iterable(self.comments.values()):
1456 def __bool__(self) -> bool:
1457 """Return True if the line has leaves or comments."""
1458 return bool(self.leaves or self.comments)
1462 class EmptyLineTracker:
1463 """Provides a stateful method that returns the number of potential extra
1464 empty lines needed before and after the currently processed line.
1466 Note: this tracker works on lines that haven't been split yet. It assumes
1467 the prefix of the first leaf consists of optional newlines. Those newlines
1468 are consumed by `maybe_empty_lines()` and included in the computation.
1471 is_pyi: bool = False
1472 previous_line: Optional[Line] = None
1473 previous_after: int = 0
1474 previous_defs: List[int] = Factory(list)
1476 def maybe_empty_lines(self, current_line: Line) -> Tuple[int, int]:
1477 """Return the number of extra empty lines before and after the `current_line`.
1479 This is for separating `def`, `async def` and `class` with extra empty
1480 lines (two on module-level).
1482 before, after = self._maybe_empty_lines(current_line)
1484 # Black should not insert empty lines at the beginning
1487 if self.previous_line is None
1488 else before - self.previous_after
1490 self.previous_after = after
1491 self.previous_line = current_line
1492 return before, after
1494 def _maybe_empty_lines(self, current_line: Line) -> Tuple[int, int]:
1496 if current_line.depth == 0:
1497 max_allowed = 1 if self.is_pyi else 2
1498 if current_line.leaves:
1499 # Consume the first leaf's extra newlines.
1500 first_leaf = current_line.leaves[0]
1501 before = first_leaf.prefix.count("\n")
1502 before = min(before, max_allowed)
1503 first_leaf.prefix = ""
1506 depth = current_line.depth
1507 while self.previous_defs and self.previous_defs[-1] >= depth:
1508 self.previous_defs.pop()
1510 before = 0 if depth else 1
1512 before = 1 if depth else 2
1513 if current_line.is_decorator or current_line.is_def or current_line.is_class:
1514 return self._maybe_empty_lines_for_class_or_def(current_line, before)
1518 and self.previous_line.is_import
1519 and not current_line.is_import
1520 and depth == self.previous_line.depth
1522 return (before or 1), 0
1526 and self.previous_line.is_class
1527 and current_line.is_triple_quoted_string
1533 def _maybe_empty_lines_for_class_or_def(
1534 self, current_line: Line, before: int
1535 ) -> Tuple[int, int]:
1536 if not current_line.is_decorator:
1537 self.previous_defs.append(current_line.depth)
1538 if self.previous_line is None:
1539 # Don't insert empty lines before the first line in the file.
1542 if self.previous_line.is_decorator:
1545 if self.previous_line.depth < current_line.depth and (
1546 self.previous_line.is_class or self.previous_line.is_def
1551 self.previous_line.is_comment
1552 and self.previous_line.depth == current_line.depth
1558 if self.previous_line.depth > current_line.depth:
1560 elif current_line.is_class or self.previous_line.is_class:
1561 if current_line.is_stub_class and self.previous_line.is_stub_class:
1562 # No blank line between classes with an empty body
1566 elif current_line.is_def and not self.previous_line.is_def:
1567 # Blank line between a block of functions and a block of non-functions
1573 if current_line.depth and newlines:
1579 class LineGenerator(Visitor[Line]):
1580 """Generates reformatted Line objects. Empty lines are not emitted.
1582 Note: destroys the tree it's visiting by mutating prefixes of its leaves
1583 in ways that will no longer stringify to valid Python code on the tree.
1586 is_pyi: bool = False
1587 normalize_strings: bool = True
1588 current_line: Line = Factory(Line)
1589 remove_u_prefix: bool = False
1591 def line(self, indent: int = 0) -> Iterator[Line]:
1594 If the line is empty, only emit if it makes sense.
1595 If the line is too long, split it first and then generate.
1597 If any lines were generated, set up a new current_line.
1599 if not self.current_line:
1600 self.current_line.depth += indent
1601 return # Line is empty, don't emit. Creating a new one unnecessary.
1603 complete_line = self.current_line
1604 self.current_line = Line(depth=complete_line.depth + indent)
1607 def visit_default(self, node: LN) -> Iterator[Line]:
1608 """Default `visit_*()` implementation. Recurses to children of `node`."""
1609 if isinstance(node, Leaf):
1610 any_open_brackets = self.current_line.bracket_tracker.any_open_brackets()
1611 for comment in generate_comments(node):
1612 if any_open_brackets:
1613 # any comment within brackets is subject to splitting
1614 self.current_line.append(comment)
1615 elif comment.type == token.COMMENT:
1616 # regular trailing comment
1617 self.current_line.append(comment)
1618 yield from self.line()
1621 # regular standalone comment
1622 yield from self.line()
1624 self.current_line.append(comment)
1625 yield from self.line()
1627 normalize_prefix(node, inside_brackets=any_open_brackets)
1628 if self.normalize_strings and node.type == token.STRING:
1629 normalize_string_prefix(node, remove_u_prefix=self.remove_u_prefix)
1630 normalize_string_quotes(node)
1631 if node.type == token.NUMBER:
1632 normalize_numeric_literal(node)
1633 if node.type not in WHITESPACE:
1634 self.current_line.append(node)
1635 yield from super().visit_default(node)
1637 def visit_atom(self, node: Node) -> Iterator[Line]:
1638 # Always make parentheses invisible around a single node, because it should
1639 # not be needed (except in the case of yield, where removing the parentheses
1640 # produces a SyntaxError).
1642 len(node.children) == 3
1643 and isinstance(node.children[0], Leaf)
1644 and node.children[0].type == token.LPAR
1645 and isinstance(node.children[2], Leaf)
1646 and node.children[2].type == token.RPAR
1647 and isinstance(node.children[1], Leaf)
1649 node.children[1].type == token.NAME
1650 and node.children[1].value == "yield"
1653 node.children[0].value = ""
1654 node.children[2].value = ""
1655 yield from super().visit_default(node)
1657 def visit_factor(self, node: Node) -> Iterator[Line]:
1658 """Force parentheses between a unary op and a binary power:
1660 -2 ** 8 -> -(2 ** 8)
1662 child = node.children[1]
1663 if child.type == syms.power and len(child.children) == 3:
1664 lpar = Leaf(token.LPAR, "(")
1665 rpar = Leaf(token.RPAR, ")")
1666 index = child.remove() or 0
1667 node.insert_child(index, Node(syms.atom, [lpar, child, rpar]))
1668 yield from self.visit_default(node)
1670 def visit_INDENT(self, node: Node) -> Iterator[Line]:
1671 """Increase indentation level, maybe yield a line."""
1672 # In blib2to3 INDENT never holds comments.
1673 yield from self.line(+1)
1674 yield from self.visit_default(node)
1676 def visit_DEDENT(self, node: Node) -> Iterator[Line]:
1677 """Decrease indentation level, maybe yield a line."""
1678 # The current line might still wait for trailing comments. At DEDENT time
1679 # there won't be any (they would be prefixes on the preceding NEWLINE).
1680 # Emit the line then.
1681 yield from self.line()
1683 # While DEDENT has no value, its prefix may contain standalone comments
1684 # that belong to the current indentation level. Get 'em.
1685 yield from self.visit_default(node)
1687 # Finally, emit the dedent.
1688 yield from self.line(-1)
1691 self, node: Node, keywords: Set[str], parens: Set[str]
1692 ) -> Iterator[Line]:
1693 """Visit a statement.
1695 This implementation is shared for `if`, `while`, `for`, `try`, `except`,
1696 `def`, `with`, `class`, `assert` and assignments.
1698 The relevant Python language `keywords` for a given statement will be
1699 NAME leaves within it. This methods puts those on a separate line.
1701 `parens` holds a set of string leaf values immediately after which
1702 invisible parens should be put.
1704 normalize_invisible_parens(node, parens_after=parens)
1705 for child in node.children:
1706 if child.type == token.NAME and child.value in keywords: # type: ignore
1707 yield from self.line()
1709 yield from self.visit(child)
1711 def visit_suite(self, node: Node) -> Iterator[Line]:
1712 """Visit a suite."""
1713 if self.is_pyi and is_stub_suite(node):
1714 yield from self.visit(node.children[2])
1716 yield from self.visit_default(node)
1718 def visit_simple_stmt(self, node: Node) -> Iterator[Line]:
1719 """Visit a statement without nested statements."""
1720 is_suite_like = node.parent and node.parent.type in STATEMENT
1722 if self.is_pyi and is_stub_body(node):
1723 yield from self.visit_default(node)
1725 yield from self.line(+1)
1726 yield from self.visit_default(node)
1727 yield from self.line(-1)
1730 if not self.is_pyi or not node.parent or not is_stub_suite(node.parent):
1731 yield from self.line()
1732 yield from self.visit_default(node)
1734 def visit_async_stmt(self, node: Node) -> Iterator[Line]:
1735 """Visit `async def`, `async for`, `async with`."""
1736 yield from self.line()
1738 children = iter(node.children)
1739 for child in children:
1740 yield from self.visit(child)
1742 if child.type == token.ASYNC:
1745 internal_stmt = next(children)
1746 for child in internal_stmt.children:
1747 yield from self.visit(child)
1749 def visit_decorators(self, node: Node) -> Iterator[Line]:
1750 """Visit decorators."""
1751 for child in node.children:
1752 yield from self.line()
1753 yield from self.visit(child)
1755 def visit_SEMI(self, leaf: Leaf) -> Iterator[Line]:
1756 """Remove a semicolon and put the other statement on a separate line."""
1757 yield from self.line()
1759 def visit_ENDMARKER(self, leaf: Leaf) -> Iterator[Line]:
1760 """End of file. Process outstanding comments and end with a newline."""
1761 yield from self.visit_default(leaf)
1762 yield from self.line()
1764 def visit_STANDALONE_COMMENT(self, leaf: Leaf) -> Iterator[Line]:
1765 if not self.current_line.bracket_tracker.any_open_brackets():
1766 yield from self.line()
1767 yield from self.visit_default(leaf)
1769 def __attrs_post_init__(self) -> None:
1770 """You are in a twisty little maze of passages."""
1773 self.visit_assert_stmt = partial(v, keywords={"assert"}, parens={"assert", ","})
1774 self.visit_if_stmt = partial(
1775 v, keywords={"if", "else", "elif"}, parens={"if", "elif"}
1777 self.visit_while_stmt = partial(v, keywords={"while", "else"}, parens={"while"})
1778 self.visit_for_stmt = partial(v, keywords={"for", "else"}, parens={"for", "in"})
1779 self.visit_try_stmt = partial(
1780 v, keywords={"try", "except", "else", "finally"}, parens=Ø
1782 self.visit_except_clause = partial(v, keywords={"except"}, parens=Ø)
1783 self.visit_with_stmt = partial(v, keywords={"with"}, parens=Ø)
1784 self.visit_funcdef = partial(v, keywords={"def"}, parens=Ø)
1785 self.visit_classdef = partial(v, keywords={"class"}, parens=Ø)
1786 self.visit_expr_stmt = partial(v, keywords=Ø, parens=ASSIGNMENTS)
1787 self.visit_return_stmt = partial(v, keywords={"return"}, parens={"return"})
1788 self.visit_import_from = partial(v, keywords=Ø, parens={"import"})
1789 self.visit_del_stmt = partial(v, keywords=Ø, parens={"del"})
1790 self.visit_async_funcdef = self.visit_async_stmt
1791 self.visit_decorated = self.visit_decorators
1794 IMPLICIT_TUPLE = {syms.testlist, syms.testlist_star_expr, syms.exprlist}
1795 BRACKET = {token.LPAR: token.RPAR, token.LSQB: token.RSQB, token.LBRACE: token.RBRACE}
1796 OPENING_BRACKETS = set(BRACKET.keys())
1797 CLOSING_BRACKETS = set(BRACKET.values())
1798 BRACKETS = OPENING_BRACKETS | CLOSING_BRACKETS
1799 ALWAYS_NO_SPACE = CLOSING_BRACKETS | {token.COMMA, STANDALONE_COMMENT}
1802 def whitespace(leaf: Leaf, *, complex_subscript: bool) -> str: # noqa: C901
1803 """Return whitespace prefix if needed for the given `leaf`.
1805 `complex_subscript` signals whether the given leaf is part of a subscription
1806 which has non-trivial arguments, like arithmetic expressions or function calls.
1814 if t in ALWAYS_NO_SPACE:
1817 if t == token.COMMENT:
1820 assert p is not None, f"INTERNAL ERROR: hand-made leaf without parent: {leaf!r}"
1821 if t == token.COLON and p.type not in {
1828 prev = leaf.prev_sibling
1830 prevp = preceding_leaf(p)
1831 if not prevp or prevp.type in OPENING_BRACKETS:
1834 if t == token.COLON:
1835 if prevp.type == token.COLON:
1838 elif prevp.type != token.COMMA and not complex_subscript:
1843 if prevp.type == token.EQUAL:
1845 if prevp.parent.type in {
1853 elif prevp.parent.type == syms.typedargslist:
1854 # A bit hacky: if the equal sign has whitespace, it means we
1855 # previously found it's a typed argument. So, we're using
1859 elif prevp.type in VARARGS_SPECIALS:
1860 if is_vararg(prevp, within=VARARGS_PARENTS | UNPACKING_PARENTS):
1863 elif prevp.type == token.COLON:
1864 if prevp.parent and prevp.parent.type in {syms.subscript, syms.sliceop}:
1865 return SPACE if complex_subscript else NO
1869 and prevp.parent.type == syms.factor
1870 and prevp.type in MATH_OPERATORS
1875 prevp.type == token.RIGHTSHIFT
1877 and prevp.parent.type == syms.shift_expr
1878 and prevp.prev_sibling
1879 and prevp.prev_sibling.type == token.NAME
1880 and prevp.prev_sibling.value == "print" # type: ignore
1882 # Python 2 print chevron
1885 elif prev.type in OPENING_BRACKETS:
1888 if p.type in {syms.parameters, syms.arglist}:
1889 # untyped function signatures or calls
1890 if not prev or prev.type != token.COMMA:
1893 elif p.type == syms.varargslist:
1895 if prev and prev.type != token.COMMA:
1898 elif p.type == syms.typedargslist:
1899 # typed function signatures
1903 if t == token.EQUAL:
1904 if prev.type != syms.tname:
1907 elif prev.type == token.EQUAL:
1908 # A bit hacky: if the equal sign has whitespace, it means we
1909 # previously found it's a typed argument. So, we're using that, too.
1912 elif prev.type != token.COMMA:
1915 elif p.type == syms.tname:
1918 prevp = preceding_leaf(p)
1919 if not prevp or prevp.type != token.COMMA:
1922 elif p.type == syms.trailer:
1923 # attributes and calls
1924 if t == token.LPAR or t == token.RPAR:
1929 prevp = preceding_leaf(p)
1930 if not prevp or prevp.type != token.NUMBER:
1933 elif t == token.LSQB:
1936 elif prev.type != token.COMMA:
1939 elif p.type == syms.argument:
1941 if t == token.EQUAL:
1945 prevp = preceding_leaf(p)
1946 if not prevp or prevp.type == token.LPAR:
1949 elif prev.type in {token.EQUAL} | VARARGS_SPECIALS:
1952 elif p.type == syms.decorator:
1956 elif p.type == syms.dotted_name:
1960 prevp = preceding_leaf(p)
1961 if not prevp or prevp.type == token.AT or prevp.type == token.DOT:
1964 elif p.type == syms.classdef:
1968 if prev and prev.type == token.LPAR:
1971 elif p.type in {syms.subscript, syms.sliceop}:
1974 assert p.parent is not None, "subscripts are always parented"
1975 if p.parent.type == syms.subscriptlist:
1980 elif not complex_subscript:
1983 elif p.type == syms.atom:
1984 if prev and t == token.DOT:
1985 # dots, but not the first one.
1988 elif p.type == syms.dictsetmaker:
1990 if prev and prev.type == token.DOUBLESTAR:
1993 elif p.type in {syms.factor, syms.star_expr}:
1996 prevp = preceding_leaf(p)
1997 if not prevp or prevp.type in OPENING_BRACKETS:
2000 prevp_parent = prevp.parent
2001 assert prevp_parent is not None
2002 if prevp.type == token.COLON and prevp_parent.type in {
2008 elif prevp.type == token.EQUAL and prevp_parent.type == syms.argument:
2011 elif t in {token.NAME, token.NUMBER, token.STRING}:
2014 elif p.type == syms.import_from:
2016 if prev and prev.type == token.DOT:
2019 elif t == token.NAME:
2023 if prev and prev.type == token.DOT:
2026 elif p.type == syms.sliceop:
2032 def preceding_leaf(node: Optional[LN]) -> Optional[Leaf]:
2033 """Return the first leaf that precedes `node`, if any."""
2035 res = node.prev_sibling
2037 if isinstance(res, Leaf):
2041 return list(res.leaves())[-1]
2050 def child_towards(ancestor: Node, descendant: LN) -> Optional[LN]:
2051 """Return the child of `ancestor` that contains `descendant`."""
2052 node: Optional[LN] = descendant
2053 while node and node.parent != ancestor:
2058 def container_of(leaf: Leaf) -> LN:
2059 """Return `leaf` or one of its ancestors that is the topmost container of it.
2061 By "container" we mean a node where `leaf` is the very first child.
2063 same_prefix = leaf.prefix
2064 container: LN = leaf
2066 parent = container.parent
2070 if parent.children[0].prefix != same_prefix:
2073 if parent.type == syms.file_input:
2076 if parent.prev_sibling is not None and parent.prev_sibling.type in BRACKETS:
2083 def is_split_after_delimiter(leaf: Leaf, previous: Optional[Leaf] = None) -> Priority:
2084 """Return the priority of the `leaf` delimiter, given a line break after it.
2086 The delimiter priorities returned here are from those delimiters that would
2087 cause a line break after themselves.
2089 Higher numbers are higher priority.
2091 if leaf.type == token.COMMA:
2092 return COMMA_PRIORITY
2097 def is_split_before_delimiter(leaf: Leaf, previous: Optional[Leaf] = None) -> Priority:
2098 """Return the priority of the `leaf` delimiter, given a line break before it.
2100 The delimiter priorities returned here are from those delimiters that would
2101 cause a line break before themselves.
2103 Higher numbers are higher priority.
2105 if is_vararg(leaf, within=VARARGS_PARENTS | UNPACKING_PARENTS):
2106 # * and ** might also be MATH_OPERATORS but in this case they are not.
2107 # Don't treat them as a delimiter.
2111 leaf.type == token.DOT
2113 and leaf.parent.type not in {syms.import_from, syms.dotted_name}
2114 and (previous is None or previous.type in CLOSING_BRACKETS)
2119 leaf.type in MATH_OPERATORS
2121 and leaf.parent.type not in {syms.factor, syms.star_expr}
2123 return MATH_PRIORITIES[leaf.type]
2125 if leaf.type in COMPARATORS:
2126 return COMPARATOR_PRIORITY
2129 leaf.type == token.STRING
2130 and previous is not None
2131 and previous.type == token.STRING
2133 return STRING_PRIORITY
2135 if leaf.type not in {token.NAME, token.ASYNC}:
2141 and leaf.parent.type in {syms.comp_for, syms.old_comp_for}
2142 or leaf.type == token.ASYNC
2145 not isinstance(leaf.prev_sibling, Leaf)
2146 or leaf.prev_sibling.value != "async"
2148 return COMPREHENSION_PRIORITY
2153 and leaf.parent.type in {syms.comp_if, syms.old_comp_if}
2155 return COMPREHENSION_PRIORITY
2157 if leaf.value in {"if", "else"} and leaf.parent and leaf.parent.type == syms.test:
2158 return TERNARY_PRIORITY
2160 if leaf.value == "is":
2161 return COMPARATOR_PRIORITY
2166 and leaf.parent.type in {syms.comp_op, syms.comparison}
2168 previous is not None
2169 and previous.type == token.NAME
2170 and previous.value == "not"
2173 return COMPARATOR_PRIORITY
2178 and leaf.parent.type == syms.comp_op
2180 previous is not None
2181 and previous.type == token.NAME
2182 and previous.value == "is"
2185 return COMPARATOR_PRIORITY
2187 if leaf.value in LOGIC_OPERATORS and leaf.parent:
2188 return LOGIC_PRIORITY
2193 FMT_OFF = {"# fmt: off", "# fmt:off", "# yapf: disable"}
2194 FMT_ON = {"# fmt: on", "# fmt:on", "# yapf: enable"}
2197 def generate_comments(leaf: LN) -> Iterator[Leaf]:
2198 """Clean the prefix of the `leaf` and generate comments from it, if any.
2200 Comments in lib2to3 are shoved into the whitespace prefix. This happens
2201 in `pgen2/driver.py:Driver.parse_tokens()`. This was a brilliant implementation
2202 move because it does away with modifying the grammar to include all the
2203 possible places in which comments can be placed.
2205 The sad consequence for us though is that comments don't "belong" anywhere.
2206 This is why this function generates simple parentless Leaf objects for
2207 comments. We simply don't know what the correct parent should be.
2209 No matter though, we can live without this. We really only need to
2210 differentiate between inline and standalone comments. The latter don't
2211 share the line with any code.
2213 Inline comments are emitted as regular token.COMMENT leaves. Standalone
2214 are emitted with a fake STANDALONE_COMMENT token identifier.
2216 for pc in list_comments(leaf.prefix, is_endmarker=leaf.type == token.ENDMARKER):
2217 yield Leaf(pc.type, pc.value, prefix="\n" * pc.newlines)
2222 """Describes a piece of syntax that is a comment.
2224 It's not a :class:`blib2to3.pytree.Leaf` so that:
2226 * it can be cached (`Leaf` objects should not be reused more than once as
2227 they store their lineno, column, prefix, and parent information);
2228 * `newlines` and `consumed` fields are kept separate from the `value`. This
2229 simplifies handling of special marker comments like ``# fmt: off/on``.
2232 type: int # token.COMMENT or STANDALONE_COMMENT
2233 value: str # content of the comment
2234 newlines: int # how many newlines before the comment
2235 consumed: int # how many characters of the original leaf's prefix did we consume
2238 @lru_cache(maxsize=4096)
2239 def list_comments(prefix: str, *, is_endmarker: bool) -> List[ProtoComment]:
2240 """Return a list of :class:`ProtoComment` objects parsed from the given `prefix`."""
2241 result: List[ProtoComment] = []
2242 if not prefix or "#" not in prefix:
2248 for index, line in enumerate(prefix.split("\n")):
2249 consumed += len(line) + 1 # adding the length of the split '\n'
2250 line = line.lstrip()
2253 if not line.startswith("#"):
2254 # Escaped newlines outside of a comment are not really newlines at
2255 # all. We treat a single-line comment following an escaped newline
2256 # as a simple trailing comment.
2257 if line.endswith("\\"):
2261 if index == ignored_lines and not is_endmarker:
2262 comment_type = token.COMMENT # simple trailing comment
2264 comment_type = STANDALONE_COMMENT
2265 comment = make_comment(line)
2268 type=comment_type, value=comment, newlines=nlines, consumed=consumed
2275 def make_comment(content: str) -> str:
2276 """Return a consistently formatted comment from the given `content` string.
2278 All comments (except for "##", "#!", "#:", '#'", "#%%") should have a single
2279 space between the hash sign and the content.
2281 If `content` didn't start with a hash sign, one is provided.
2283 content = content.rstrip()
2287 if content[0] == "#":
2288 content = content[1:]
2289 if content and content[0] not in " !:#'%":
2290 content = " " + content
2291 return "#" + content
2297 inner: bool = False,
2298 features: Collection[Feature] = (),
2299 ) -> Iterator[Line]:
2300 """Split a `line` into potentially many lines.
2302 They should fit in the allotted `line_length` but might not be able to.
2303 `inner` signifies that there were a pair of brackets somewhere around the
2304 current `line`, possibly transitively. This means we can fallback to splitting
2305 by delimiters if the LHS/RHS don't yield any results.
2307 `features` are syntactical features that may be used in the output.
2313 line_str = str(line).strip("\n")
2316 not line.contains_inner_type_comments()
2317 and not line.should_explode
2318 and is_line_short_enough(line, line_length=line_length, line_str=line_str)
2323 split_funcs: List[SplitFunc]
2325 split_funcs = [left_hand_split]
2328 def rhs(line: Line, features: Collection[Feature]) -> Iterator[Line]:
2329 for omit in generate_trailers_to_omit(line, line_length):
2330 lines = list(right_hand_split(line, line_length, features, omit=omit))
2331 if is_line_short_enough(lines[0], line_length=line_length):
2335 # All splits failed, best effort split with no omits.
2336 # This mostly happens to multiline strings that are by definition
2337 # reported as not fitting a single line.
2338 yield from right_hand_split(line, line_length, features=features)
2340 if line.inside_brackets:
2341 split_funcs = [delimiter_split, standalone_comment_split, rhs]
2344 for split_func in split_funcs:
2345 # We are accumulating lines in `result` because we might want to abort
2346 # mission and return the original line in the end, or attempt a different
2348 result: List[Line] = []
2350 for l in split_func(line, features):
2351 if str(l).strip("\n") == line_str:
2352 raise CannotSplit("Split function returned an unchanged result")
2356 l, line_length=line_length, inner=True, features=features
2370 def left_hand_split(line: Line, features: Collection[Feature] = ()) -> Iterator[Line]:
2371 """Split line into many lines, starting with the first matching bracket pair.
2373 Note: this usually looks weird, only use this for function definitions.
2374 Prefer RHS otherwise. This is why this function is not symmetrical with
2375 :func:`right_hand_split` which also handles optional parentheses.
2377 tail_leaves: List[Leaf] = []
2378 body_leaves: List[Leaf] = []
2379 head_leaves: List[Leaf] = []
2380 current_leaves = head_leaves
2381 matching_bracket = None
2382 for leaf in line.leaves:
2384 current_leaves is body_leaves
2385 and leaf.type in CLOSING_BRACKETS
2386 and leaf.opening_bracket is matching_bracket
2388 current_leaves = tail_leaves if body_leaves else head_leaves
2389 current_leaves.append(leaf)
2390 if current_leaves is head_leaves:
2391 if leaf.type in OPENING_BRACKETS:
2392 matching_bracket = leaf
2393 current_leaves = body_leaves
2394 if not matching_bracket:
2395 raise CannotSplit("No brackets found")
2397 head = bracket_split_build_line(head_leaves, line, matching_bracket)
2398 body = bracket_split_build_line(body_leaves, line, matching_bracket, is_body=True)
2399 tail = bracket_split_build_line(tail_leaves, line, matching_bracket)
2400 bracket_split_succeeded_or_raise(head, body, tail)
2401 for result in (head, body, tail):
2406 def right_hand_split(
2409 features: Collection[Feature] = (),
2410 omit: Collection[LeafID] = (),
2411 ) -> Iterator[Line]:
2412 """Split line into many lines, starting with the last matching bracket pair.
2414 If the split was by optional parentheses, attempt splitting without them, too.
2415 `omit` is a collection of closing bracket IDs that shouldn't be considered for
2418 Note: running this function modifies `bracket_depth` on the leaves of `line`.
2420 tail_leaves: List[Leaf] = []
2421 body_leaves: List[Leaf] = []
2422 head_leaves: List[Leaf] = []
2423 current_leaves = tail_leaves
2424 opening_bracket = None
2425 closing_bracket = None
2426 for leaf in reversed(line.leaves):
2427 if current_leaves is body_leaves:
2428 if leaf is opening_bracket:
2429 current_leaves = head_leaves if body_leaves else tail_leaves
2430 current_leaves.append(leaf)
2431 if current_leaves is tail_leaves:
2432 if leaf.type in CLOSING_BRACKETS and id(leaf) not in omit:
2433 opening_bracket = leaf.opening_bracket
2434 closing_bracket = leaf
2435 current_leaves = body_leaves
2436 if not (opening_bracket and closing_bracket and head_leaves):
2437 # If there is no opening or closing_bracket that means the split failed and
2438 # all content is in the tail. Otherwise, if `head_leaves` are empty, it means
2439 # the matching `opening_bracket` wasn't available on `line` anymore.
2440 raise CannotSplit("No brackets found")
2442 tail_leaves.reverse()
2443 body_leaves.reverse()
2444 head_leaves.reverse()
2445 head = bracket_split_build_line(head_leaves, line, opening_bracket)
2446 body = bracket_split_build_line(body_leaves, line, opening_bracket, is_body=True)
2447 tail = bracket_split_build_line(tail_leaves, line, opening_bracket)
2448 bracket_split_succeeded_or_raise(head, body, tail)
2450 # the body shouldn't be exploded
2451 not body.should_explode
2452 # the opening bracket is an optional paren
2453 and opening_bracket.type == token.LPAR
2454 and not opening_bracket.value
2455 # the closing bracket is an optional paren
2456 and closing_bracket.type == token.RPAR
2457 and not closing_bracket.value
2458 # it's not an import (optional parens are the only thing we can split on
2459 # in this case; attempting a split without them is a waste of time)
2460 and not line.is_import
2461 # there are no standalone comments in the body
2462 and not body.contains_standalone_comments(0)
2463 # and we can actually remove the parens
2464 and can_omit_invisible_parens(body, line_length)
2466 omit = {id(closing_bracket), *omit}
2468 yield from right_hand_split(line, line_length, features=features, omit=omit)
2474 or is_line_short_enough(body, line_length=line_length)
2477 "Splitting failed, body is still too long and can't be split."
2480 elif head.contains_multiline_strings() or tail.contains_multiline_strings():
2482 "The current optional pair of parentheses is bound to fail to "
2483 "satisfy the splitting algorithm because the head or the tail "
2484 "contains multiline strings which by definition never fit one "
2488 ensure_visible(opening_bracket)
2489 ensure_visible(closing_bracket)
2490 for result in (head, body, tail):
2495 def bracket_split_succeeded_or_raise(head: Line, body: Line, tail: Line) -> None:
2496 """Raise :exc:`CannotSplit` if the last left- or right-hand split failed.
2498 Do nothing otherwise.
2500 A left- or right-hand split is based on a pair of brackets. Content before
2501 (and including) the opening bracket is left on one line, content inside the
2502 brackets is put on a separate line, and finally content starting with and
2503 following the closing bracket is put on a separate line.
2505 Those are called `head`, `body`, and `tail`, respectively. If the split
2506 produced the same line (all content in `head`) or ended up with an empty `body`
2507 and the `tail` is just the closing bracket, then it's considered failed.
2509 tail_len = len(str(tail).strip())
2512 raise CannotSplit("Splitting brackets produced the same line")
2516 f"Splitting brackets on an empty body to save "
2517 f"{tail_len} characters is not worth it"
2521 def bracket_split_build_line(
2522 leaves: List[Leaf], original: Line, opening_bracket: Leaf, *, is_body: bool = False
2524 """Return a new line with given `leaves` and respective comments from `original`.
2526 If `is_body` is True, the result line is one-indented inside brackets and as such
2527 has its first leaf's prefix normalized and a trailing comma added when expected.
2529 result = Line(depth=original.depth)
2531 result.inside_brackets = True
2534 # Since body is a new indent level, remove spurious leading whitespace.
2535 normalize_prefix(leaves[0], inside_brackets=True)
2536 # Ensure a trailing comma for imports and standalone function arguments, but
2537 # be careful not to add one after any comments.
2538 no_commas = original.is_def and not any(
2539 l.type == token.COMMA for l in leaves
2542 if original.is_import or no_commas:
2543 for i in range(len(leaves) - 1, -1, -1):
2544 if leaves[i].type == STANDALONE_COMMENT:
2546 elif leaves[i].type == token.COMMA:
2549 leaves.insert(i + 1, Leaf(token.COMMA, ","))
2553 result.append(leaf, preformatted=True)
2554 for comment_after in original.comments_after(leaf):
2555 result.append(comment_after, preformatted=True)
2557 result.should_explode = should_explode(result, opening_bracket)
2561 def dont_increase_indentation(split_func: SplitFunc) -> SplitFunc:
2562 """Normalize prefix of the first leaf in every line returned by `split_func`.
2564 This is a decorator over relevant split functions.
2568 def split_wrapper(line: Line, features: Collection[Feature] = ()) -> Iterator[Line]:
2569 for l in split_func(line, features):
2570 normalize_prefix(l.leaves[0], inside_brackets=True)
2573 return split_wrapper
2576 @dont_increase_indentation
2577 def delimiter_split(line: Line, features: Collection[Feature] = ()) -> Iterator[Line]:
2578 """Split according to delimiters of the highest priority.
2580 If the appropriate Features are given, the split will add trailing commas
2581 also in function signatures and calls that contain `*` and `**`.
2584 last_leaf = line.leaves[-1]
2586 raise CannotSplit("Line empty")
2588 bt = line.bracket_tracker
2590 delimiter_priority = bt.max_delimiter_priority(exclude={id(last_leaf)})
2592 raise CannotSplit("No delimiters found")
2594 if delimiter_priority == DOT_PRIORITY:
2595 if bt.delimiter_count_with_priority(delimiter_priority) == 1:
2596 raise CannotSplit("Splitting a single attribute from its owner looks wrong")
2598 current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
2599 lowest_depth = sys.maxsize
2600 trailing_comma_safe = True
2602 def append_to_line(leaf: Leaf) -> Iterator[Line]:
2603 """Append `leaf` to current line or to new line if appending impossible."""
2604 nonlocal current_line
2606 current_line.append_safe(leaf, preformatted=True)
2610 current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
2611 current_line.append(leaf)
2613 for leaf in line.leaves:
2614 yield from append_to_line(leaf)
2616 for comment_after in line.comments_after(leaf):
2617 yield from append_to_line(comment_after)
2619 lowest_depth = min(lowest_depth, leaf.bracket_depth)
2620 if leaf.bracket_depth == lowest_depth:
2621 if is_vararg(leaf, within={syms.typedargslist}):
2622 trailing_comma_safe = (
2623 trailing_comma_safe and Feature.TRAILING_COMMA_IN_DEF in features
2625 elif is_vararg(leaf, within={syms.arglist, syms.argument}):
2626 trailing_comma_safe = (
2627 trailing_comma_safe and Feature.TRAILING_COMMA_IN_CALL in features
2630 leaf_priority = bt.delimiters.get(id(leaf))
2631 if leaf_priority == delimiter_priority:
2634 current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
2638 and delimiter_priority == COMMA_PRIORITY
2639 and current_line.leaves[-1].type != token.COMMA
2640 and current_line.leaves[-1].type != STANDALONE_COMMENT
2642 current_line.append(Leaf(token.COMMA, ","))
2646 @dont_increase_indentation
2647 def standalone_comment_split(
2648 line: Line, features: Collection[Feature] = ()
2649 ) -> Iterator[Line]:
2650 """Split standalone comments from the rest of the line."""
2651 if not line.contains_standalone_comments(0):
2652 raise CannotSplit("Line does not have any standalone comments")
2654 current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
2656 def append_to_line(leaf: Leaf) -> Iterator[Line]:
2657 """Append `leaf` to current line or to new line if appending impossible."""
2658 nonlocal current_line
2660 current_line.append_safe(leaf, preformatted=True)
2664 current_line = Line(depth=line.depth, inside_brackets=line.inside_brackets)
2665 current_line.append(leaf)
2667 for leaf in line.leaves:
2668 yield from append_to_line(leaf)
2670 for comment_after in line.comments_after(leaf):
2671 yield from append_to_line(comment_after)
2677 def is_import(leaf: Leaf) -> bool:
2678 """Return True if the given leaf starts an import statement."""
2685 (v == "import" and p and p.type == syms.import_name)
2686 or (v == "from" and p and p.type == syms.import_from)
2691 def is_type_comment(leaf: Leaf) -> bool:
2692 """Return True if the given leaf is a special comment.
2693 Only returns true for type comments for now."""
2696 return t in {token.COMMENT, t == STANDALONE_COMMENT} and v.startswith("# type:")
2699 def normalize_prefix(leaf: Leaf, *, inside_brackets: bool) -> None:
2700 """Leave existing extra newlines if not `inside_brackets`. Remove everything
2703 Note: don't use backslashes for formatting or you'll lose your voting rights.
2705 if not inside_brackets:
2706 spl = leaf.prefix.split("#")
2707 if "\\" not in spl[0]:
2708 nl_count = spl[-1].count("\n")
2711 leaf.prefix = "\n" * nl_count
2717 def normalize_string_prefix(leaf: Leaf, remove_u_prefix: bool = False) -> None:
2718 """Make all string prefixes lowercase.
2720 If remove_u_prefix is given, also removes any u prefix from the string.
2722 Note: Mutates its argument.
2724 match = re.match(r"^([furbFURB]*)(.*)$", leaf.value, re.DOTALL)
2725 assert match is not None, f"failed to match string {leaf.value!r}"
2726 orig_prefix = match.group(1)
2727 new_prefix = orig_prefix.lower()
2729 new_prefix = new_prefix.replace("u", "")
2730 leaf.value = f"{new_prefix}{match.group(2)}"
2733 def normalize_string_quotes(leaf: Leaf) -> None:
2734 """Prefer double quotes but only if it doesn't cause more escaping.
2736 Adds or removes backslashes as appropriate. Doesn't parse and fix
2737 strings nested in f-strings (yet).
2739 Note: Mutates its argument.
2741 value = leaf.value.lstrip("furbFURB")
2742 if value[:3] == '"""':
2745 elif value[:3] == "'''":
2748 elif value[0] == '"':
2754 first_quote_pos = leaf.value.find(orig_quote)
2755 if first_quote_pos == -1:
2756 return # There's an internal error
2758 prefix = leaf.value[:first_quote_pos]
2759 unescaped_new_quote = re.compile(rf"(([^\\]|^)(\\\\)*){new_quote}")
2760 escaped_new_quote = re.compile(rf"([^\\]|^)\\((?:\\\\)*){new_quote}")
2761 escaped_orig_quote = re.compile(rf"([^\\]|^)\\((?:\\\\)*){orig_quote}")
2762 body = leaf.value[first_quote_pos + len(orig_quote) : -len(orig_quote)]
2763 if "r" in prefix.casefold():
2764 if unescaped_new_quote.search(body):
2765 # There's at least one unescaped new_quote in this raw string
2766 # so converting is impossible
2769 # Do not introduce or remove backslashes in raw strings
2772 # remove unnecessary escapes
2773 new_body = sub_twice(escaped_new_quote, rf"\1\2{new_quote}", body)
2774 if body != new_body:
2775 # Consider the string without unnecessary escapes as the original
2777 leaf.value = f"{prefix}{orig_quote}{body}{orig_quote}"
2778 new_body = sub_twice(escaped_orig_quote, rf"\1\2{orig_quote}", new_body)
2779 new_body = sub_twice(unescaped_new_quote, rf"\1\\{new_quote}", new_body)
2780 if "f" in prefix.casefold():
2781 matches = re.findall(
2783 (?:[^{]|^)\{ # start of the string or a non-{ followed by a single {
2784 ([^{].*?) # contents of the brackets except if begins with {{
2785 \}(?:[^}]|$) # A } followed by end of the string or a non-}
2792 # Do not introduce backslashes in interpolated expressions
2794 if new_quote == '"""' and new_body[-1:] == '"':
2796 new_body = new_body[:-1] + '\\"'
2797 orig_escape_count = body.count("\\")
2798 new_escape_count = new_body.count("\\")
2799 if new_escape_count > orig_escape_count:
2800 return # Do not introduce more escaping
2802 if new_escape_count == orig_escape_count and orig_quote == '"':
2803 return # Prefer double quotes
2805 leaf.value = f"{prefix}{new_quote}{new_body}{new_quote}"
2808 def normalize_numeric_literal(leaf: Leaf) -> None:
2809 """Normalizes numeric (float, int, and complex) literals.
2811 All letters used in the representation are normalized to lowercase (except
2812 in Python 2 long literals).
2814 text = leaf.value.lower()
2815 if text.startswith(("0o", "0b")):
2816 # Leave octal and binary literals alone.
2818 elif text.startswith("0x"):
2819 # Change hex literals to upper case.
2820 before, after = text[:2], text[2:]
2821 text = f"{before}{after.upper()}"
2823 before, after = text.split("e")
2825 if after.startswith("-"):
2828 elif after.startswith("+"):
2830 before = format_float_or_int_string(before)
2831 text = f"{before}e{sign}{after}"
2832 elif text.endswith(("j", "l")):
2835 # Capitalize in "2L" because "l" looks too similar to "1".
2838 text = f"{format_float_or_int_string(number)}{suffix}"
2840 text = format_float_or_int_string(text)
2844 def format_float_or_int_string(text: str) -> str:
2845 """Formats a float string like "1.0"."""
2849 before, after = text.split(".")
2850 return f"{before or 0}.{after or 0}"
2853 def normalize_invisible_parens(node: Node, parens_after: Set[str]) -> None:
2854 """Make existing optional parentheses invisible or create new ones.
2856 `parens_after` is a set of string leaf values immediately after which parens
2859 Standardizes on visible parentheses for single-element tuples, and keeps
2860 existing visible parentheses for other tuples and generator expressions.
2862 for pc in list_comments(node.prefix, is_endmarker=False):
2863 if pc.value in FMT_OFF:
2864 # This `node` has a prefix with `# fmt: off`, don't mess with parens.
2868 for index, child in enumerate(list(node.children)):
2869 # Add parentheses around long tuple unpacking in assignments.
2872 and isinstance(child, Node)
2873 and child.type == syms.testlist_star_expr
2878 if is_walrus_assignment(child):
2880 if child.type == syms.atom:
2881 if maybe_make_parens_invisible_in_atom(child, parent=node):
2882 lpar = Leaf(token.LPAR, "")
2883 rpar = Leaf(token.RPAR, "")
2884 index = child.remove() or 0
2885 node.insert_child(index, Node(syms.atom, [lpar, child, rpar]))
2886 elif is_one_tuple(child):
2887 # wrap child in visible parentheses
2888 lpar = Leaf(token.LPAR, "(")
2889 rpar = Leaf(token.RPAR, ")")
2891 node.insert_child(index, Node(syms.atom, [lpar, child, rpar]))
2892 elif node.type == syms.import_from:
2893 # "import from" nodes store parentheses directly as part of
2895 if child.type == token.LPAR:
2896 # make parentheses invisible
2897 child.value = "" # type: ignore
2898 node.children[-1].value = "" # type: ignore
2899 elif child.type != token.STAR:
2900 # insert invisible parentheses
2901 node.insert_child(index, Leaf(token.LPAR, ""))
2902 node.append_child(Leaf(token.RPAR, ""))
2905 elif not (isinstance(child, Leaf) and is_multiline_string(child)):
2906 # wrap child in invisible parentheses
2907 lpar = Leaf(token.LPAR, "")
2908 rpar = Leaf(token.RPAR, "")
2909 index = child.remove() or 0
2910 prefix = child.prefix
2912 new_child = Node(syms.atom, [lpar, child, rpar])
2913 new_child.prefix = prefix
2914 node.insert_child(index, new_child)
2916 check_lpar = isinstance(child, Leaf) and child.value in parens_after
2919 def normalize_fmt_off(node: Node) -> None:
2920 """Convert content between `# fmt: off`/`# fmt: on` into standalone comments."""
2923 try_again = convert_one_fmt_off_pair(node)
2926 def convert_one_fmt_off_pair(node: Node) -> bool:
2927 """Convert content of a single `# fmt: off`/`# fmt: on` into a standalone comment.
2929 Returns True if a pair was converted.
2931 for leaf in node.leaves():
2932 previous_consumed = 0
2933 for comment in list_comments(leaf.prefix, is_endmarker=False):
2934 if comment.value in FMT_OFF:
2935 # We only want standalone comments. If there's no previous leaf or
2936 # the previous leaf is indentation, it's a standalone comment in
2938 if comment.type != STANDALONE_COMMENT:
2939 prev = preceding_leaf(leaf)
2940 if prev and prev.type not in WHITESPACE:
2943 ignored_nodes = list(generate_ignored_nodes(leaf))
2944 if not ignored_nodes:
2947 first = ignored_nodes[0] # Can be a container node with the `leaf`.
2948 parent = first.parent
2949 prefix = first.prefix
2950 first.prefix = prefix[comment.consumed :]
2952 comment.value + "\n" + "".join(str(n) for n in ignored_nodes)
2954 if hidden_value.endswith("\n"):
2955 # That happens when one of the `ignored_nodes` ended with a NEWLINE
2956 # leaf (possibly followed by a DEDENT).
2957 hidden_value = hidden_value[:-1]
2959 for ignored in ignored_nodes:
2960 index = ignored.remove()
2961 if first_idx is None:
2963 assert parent is not None, "INTERNAL ERROR: fmt: on/off handling (1)"
2964 assert first_idx is not None, "INTERNAL ERROR: fmt: on/off handling (2)"
2965 parent.insert_child(
2970 prefix=prefix[:previous_consumed] + "\n" * comment.newlines,
2975 previous_consumed = comment.consumed
2980 def generate_ignored_nodes(leaf: Leaf) -> Iterator[LN]:
2981 """Starting from the container of `leaf`, generate all leaves until `# fmt: on`.
2983 Stops at the end of the block.
2985 container: Optional[LN] = container_of(leaf)
2986 while container is not None and container.type != token.ENDMARKER:
2987 for comment in list_comments(container.prefix, is_endmarker=False):
2988 if comment.value in FMT_ON:
2993 container = container.next_sibling
2996 def maybe_make_parens_invisible_in_atom(node: LN, parent: LN) -> bool:
2997 """If it's safe, make the parens in the atom `node` invisible, recursively.
2999 Returns whether the node should itself be wrapped in invisible parentheses.
3003 node.type != syms.atom
3004 or is_empty_tuple(node)
3005 or is_one_tuple(node)
3006 or (is_yield(node) and parent.type != syms.expr_stmt)
3007 or max_delimiter_priority_in_atom(node) >= COMMA_PRIORITY
3011 first = node.children[0]
3012 last = node.children[-1]
3013 if first.type == token.LPAR and last.type == token.RPAR:
3014 # make parentheses invisible
3015 first.value = "" # type: ignore
3016 last.value = "" # type: ignore
3017 maybe_make_parens_invisible_in_atom(node.children[1], parent=parent)
3023 def is_empty_tuple(node: LN) -> bool:
3024 """Return True if `node` holds an empty tuple."""
3026 node.type == syms.atom
3027 and len(node.children) == 2
3028 and node.children[0].type == token.LPAR
3029 and node.children[1].type == token.RPAR
3033 def unwrap_singleton_parenthesis(node: LN) -> Optional[LN]:
3034 """Returns `wrapped` if `node` is of the shape ( wrapped ).
3036 Parenthesis can be optional. Returns None otherwise"""
3037 if len(node.children) != 3:
3039 lpar, wrapped, rpar = node.children
3040 if not (lpar.type == token.LPAR and rpar.type == token.RPAR):
3046 def is_one_tuple(node: LN) -> bool:
3047 """Return True if `node` holds a tuple with one element, with or without parens."""
3048 if node.type == syms.atom:
3049 gexp = unwrap_singleton_parenthesis(node)
3050 if gexp is None or gexp.type != syms.testlist_gexp:
3053 return len(gexp.children) == 2 and gexp.children[1].type == token.COMMA
3056 node.type in IMPLICIT_TUPLE
3057 and len(node.children) == 2
3058 and node.children[1].type == token.COMMA
3062 def is_walrus_assignment(node: LN) -> bool:
3063 """Return True iff `node` is of the shape ( test := test )"""
3064 inner = unwrap_singleton_parenthesis(node)
3065 return inner is not None and inner.type == syms.namedexpr_test
3068 def is_yield(node: LN) -> bool:
3069 """Return True if `node` holds a `yield` or `yield from` expression."""
3070 if node.type == syms.yield_expr:
3073 if node.type == token.NAME and node.value == "yield": # type: ignore
3076 if node.type != syms.atom:
3079 if len(node.children) != 3:
3082 lpar, expr, rpar = node.children
3083 if lpar.type == token.LPAR and rpar.type == token.RPAR:
3084 return is_yield(expr)
3089 def is_vararg(leaf: Leaf, within: Set[NodeType]) -> bool:
3090 """Return True if `leaf` is a star or double star in a vararg or kwarg.
3092 If `within` includes VARARGS_PARENTS, this applies to function signatures.
3093 If `within` includes UNPACKING_PARENTS, it applies to right hand-side
3094 extended iterable unpacking (PEP 3132) and additional unpacking
3095 generalizations (PEP 448).
3097 if leaf.type not in VARARGS_SPECIALS or not leaf.parent:
3101 if p.type == syms.star_expr:
3102 # Star expressions are also used as assignment targets in extended
3103 # iterable unpacking (PEP 3132). See what its parent is instead.
3109 return p.type in within
3112 def is_multiline_string(leaf: Leaf) -> bool:
3113 """Return True if `leaf` is a multiline string that actually spans many lines."""
3114 value = leaf.value.lstrip("furbFURB")
3115 return value[:3] in {'"""', "'''"} and "\n" in value
3118 def is_stub_suite(node: Node) -> bool:
3119 """Return True if `node` is a suite with a stub body."""
3121 len(node.children) != 4
3122 or node.children[0].type != token.NEWLINE
3123 or node.children[1].type != token.INDENT
3124 or node.children[3].type != token.DEDENT
3128 return is_stub_body(node.children[2])
3131 def is_stub_body(node: LN) -> bool:
3132 """Return True if `node` is a simple statement containing an ellipsis."""
3133 if not isinstance(node, Node) or node.type != syms.simple_stmt:
3136 if len(node.children) != 2:
3139 child = node.children[0]
3141 child.type == syms.atom
3142 and len(child.children) == 3
3143 and all(leaf == Leaf(token.DOT, ".") for leaf in child.children)
3147 def max_delimiter_priority_in_atom(node: LN) -> Priority:
3148 """Return maximum delimiter priority inside `node`.
3150 This is specific to atoms with contents contained in a pair of parentheses.
3151 If `node` isn't an atom or there are no enclosing parentheses, returns 0.
3153 if node.type != syms.atom:
3156 first = node.children[0]
3157 last = node.children[-1]
3158 if not (first.type == token.LPAR and last.type == token.RPAR):
3161 bt = BracketTracker()
3162 for c in node.children[1:-1]:
3163 if isinstance(c, Leaf):
3166 for leaf in c.leaves():
3169 return bt.max_delimiter_priority()
3175 def ensure_visible(leaf: Leaf) -> None:
3176 """Make sure parentheses are visible.
3178 They could be invisible as part of some statements (see
3179 :func:`normalize_invisible_parens` and :func:`visit_import_from`).
3181 if leaf.type == token.LPAR:
3183 elif leaf.type == token.RPAR:
3187 def should_explode(line: Line, opening_bracket: Leaf) -> bool:
3188 """Should `line` immediately be split with `delimiter_split()` after RHS?"""
3191 opening_bracket.parent
3192 and opening_bracket.parent.type in {syms.atom, syms.import_from}
3193 and opening_bracket.value in "[{("
3198 last_leaf = line.leaves[-1]
3199 exclude = {id(last_leaf)} if last_leaf.type == token.COMMA else set()
3200 max_priority = line.bracket_tracker.max_delimiter_priority(exclude=exclude)
3201 except (IndexError, ValueError):
3204 return max_priority == COMMA_PRIORITY
3207 def get_features_used(node: Node) -> Set[Feature]:
3208 """Return a set of (relatively) new Python features used in this file.
3210 Currently looking for:
3212 - underscores in numeric literals;
3213 - trailing commas after * or ** in function signatures and calls;
3214 - positional only arguments in function signatures and lambdas;
3216 features: Set[Feature] = set()
3217 for n in node.pre_order():
3218 if n.type == token.STRING:
3219 value_head = n.value[:2] # type: ignore
3220 if value_head in {'f"', 'F"', "f'", "F'", "rf", "fr", "RF", "FR"}:
3221 features.add(Feature.F_STRINGS)
3223 elif n.type == token.NUMBER:
3224 if "_" in n.value: # type: ignore
3225 features.add(Feature.NUMERIC_UNDERSCORES)
3227 elif n.type == token.SLASH:
3228 if n.parent and n.parent.type in {syms.typedargslist, syms.arglist}:
3229 features.add(Feature.POS_ONLY_ARGUMENTS)
3231 elif n.type == token.COLONEQUAL:
3232 features.add(Feature.ASSIGNMENT_EXPRESSIONS)
3235 n.type in {syms.typedargslist, syms.arglist}
3237 and n.children[-1].type == token.COMMA
3239 if n.type == syms.typedargslist:
3240 feature = Feature.TRAILING_COMMA_IN_DEF
3242 feature = Feature.TRAILING_COMMA_IN_CALL
3244 for ch in n.children:
3245 if ch.type in STARS:
3246 features.add(feature)
3248 if ch.type == syms.argument:
3249 for argch in ch.children:
3250 if argch.type in STARS:
3251 features.add(feature)
3256 def detect_target_versions(node: Node) -> Set[TargetVersion]:
3257 """Detect the version to target based on the nodes used."""
3258 features = get_features_used(node)
3260 version for version in TargetVersion if features <= VERSION_TO_FEATURES[version]
3264 def generate_trailers_to_omit(line: Line, line_length: int) -> Iterator[Set[LeafID]]:
3265 """Generate sets of closing bracket IDs that should be omitted in a RHS.
3267 Brackets can be omitted if the entire trailer up to and including
3268 a preceding closing bracket fits in one line.
3270 Yielded sets are cumulative (contain results of previous yields, too). First
3274 omit: Set[LeafID] = set()
3277 length = 4 * line.depth
3278 opening_bracket = None
3279 closing_bracket = None
3280 inner_brackets: Set[LeafID] = set()
3281 for index, leaf, leaf_length in enumerate_with_length(line, reversed=True):
3282 length += leaf_length
3283 if length > line_length:
3286 has_inline_comment = leaf_length > len(leaf.value) + len(leaf.prefix)
3287 if leaf.type == STANDALONE_COMMENT or has_inline_comment:
3291 if leaf is opening_bracket:
3292 opening_bracket = None
3293 elif leaf.type in CLOSING_BRACKETS:
3294 inner_brackets.add(id(leaf))
3295 elif leaf.type in CLOSING_BRACKETS:
3296 if index > 0 and line.leaves[index - 1].type in OPENING_BRACKETS:
3297 # Empty brackets would fail a split so treat them as "inner"
3298 # brackets (e.g. only add them to the `omit` set if another
3299 # pair of brackets was good enough.
3300 inner_brackets.add(id(leaf))
3304 omit.add(id(closing_bracket))
3305 omit.update(inner_brackets)
3306 inner_brackets.clear()
3310 opening_bracket = leaf.opening_bracket
3311 closing_bracket = leaf
3314 def get_future_imports(node: Node) -> Set[str]:
3315 """Return a set of __future__ imports in the file."""
3316 imports: Set[str] = set()
3318 def get_imports_from_children(children: List[LN]) -> Generator[str, None, None]:
3319 for child in children:
3320 if isinstance(child, Leaf):
3321 if child.type == token.NAME:
3323 elif child.type == syms.import_as_name:
3324 orig_name = child.children[0]
3325 assert isinstance(orig_name, Leaf), "Invalid syntax parsing imports"
3326 assert orig_name.type == token.NAME, "Invalid syntax parsing imports"
3327 yield orig_name.value
3328 elif child.type == syms.import_as_names:
3329 yield from get_imports_from_children(child.children)
3331 raise AssertionError("Invalid syntax parsing imports")
3333 for child in node.children:
3334 if child.type != syms.simple_stmt:
3336 first_child = child.children[0]
3337 if isinstance(first_child, Leaf):
3338 # Continue looking if we see a docstring; otherwise stop.
3340 len(child.children) == 2
3341 and first_child.type == token.STRING
3342 and child.children[1].type == token.NEWLINE
3347 elif first_child.type == syms.import_from:
3348 module_name = first_child.children[1]
3349 if not isinstance(module_name, Leaf) or module_name.value != "__future__":
3351 imports |= set(get_imports_from_children(first_child.children[3:]))
3357 def gen_python_files_in_dir(
3360 include: Pattern[str],
3361 exclude: Pattern[str],
3363 ) -> Iterator[Path]:
3364 """Generate all files under `path` whose paths are not excluded by the
3365 `exclude` regex, but are included by the `include` regex.
3367 Symbolic links pointing outside of the `root` directory are ignored.
3369 `report` is where output about exclusions goes.
3371 assert root.is_absolute(), f"INTERNAL ERROR: `root` must be absolute but is {root}"
3372 for child in path.iterdir():
3374 normalized_path = "/" + child.resolve().relative_to(root).as_posix()
3376 if child.is_symlink():
3377 report.path_ignored(
3378 child, f"is a symbolic link that points outside {root}"
3385 normalized_path += "/"
3386 exclude_match = exclude.search(normalized_path)
3387 if exclude_match and exclude_match.group(0):
3388 report.path_ignored(child, f"matches the --exclude regular expression")
3392 yield from gen_python_files_in_dir(child, root, include, exclude, report)
3394 elif child.is_file():
3395 include_match = include.search(normalized_path)
3401 def find_project_root(srcs: Iterable[str]) -> Path:
3402 """Return a directory containing .git, .hg, or pyproject.toml.
3404 That directory can be one of the directories passed in `srcs` or their
3407 If no directory in the tree contains a marker that would specify it's the
3408 project root, the root of the file system is returned.
3411 return Path("/").resolve()
3413 common_base = min(Path(src).resolve() for src in srcs)
3414 if common_base.is_dir():
3415 # Append a fake file so `parents` below returns `common_base_dir`, too.
3416 common_base /= "fake-file"
3417 for directory in common_base.parents:
3418 if (directory / ".git").is_dir():
3421 if (directory / ".hg").is_dir():
3424 if (directory / "pyproject.toml").is_file():
3432 """Provides a reformatting counter. Can be rendered with `str(report)`."""
3436 verbose: bool = False
3437 change_count: int = 0
3439 failure_count: int = 0
3441 def done(self, src: Path, changed: Changed) -> None:
3442 """Increment the counter for successful reformatting. Write out a message."""
3443 if changed is Changed.YES:
3444 reformatted = "would reformat" if self.check else "reformatted"
3445 if self.verbose or not self.quiet:
3446 out(f"{reformatted} {src}")
3447 self.change_count += 1
3450 if changed is Changed.NO:
3451 msg = f"{src} already well formatted, good job."
3453 msg = f"{src} wasn't modified on disk since last run."
3454 out(msg, bold=False)
3455 self.same_count += 1
3457 def failed(self, src: Path, message: str) -> None:
3458 """Increment the counter for failed reformatting. Write out a message."""
3459 err(f"error: cannot format {src}: {message}")
3460 self.failure_count += 1
3462 def path_ignored(self, path: Path, message: str) -> None:
3464 out(f"{path} ignored: {message}", bold=False)
3467 def return_code(self) -> int:
3468 """Return the exit code that the app should use.
3470 This considers the current state of changed files and failures:
3471 - if there were any failures, return 123;
3472 - if any files were changed and --check is being used, return 1;
3473 - otherwise return 0.
3475 # According to http://tldp.org/LDP/abs/html/exitcodes.html starting with
3476 # 126 we have special return codes reserved by the shell.
3477 if self.failure_count:
3480 elif self.change_count and self.check:
3485 def __str__(self) -> str:
3486 """Render a color report of the current state.
3488 Use `click.unstyle` to remove colors.
3491 reformatted = "would be reformatted"
3492 unchanged = "would be left unchanged"
3493 failed = "would fail to reformat"
3495 reformatted = "reformatted"
3496 unchanged = "left unchanged"
3497 failed = "failed to reformat"
3499 if self.change_count:
3500 s = "s" if self.change_count > 1 else ""
3502 click.style(f"{self.change_count} file{s} {reformatted}", bold=True)
3505 s = "s" if self.same_count > 1 else ""
3506 report.append(f"{self.same_count} file{s} {unchanged}")
3507 if self.failure_count:
3508 s = "s" if self.failure_count > 1 else ""
3510 click.style(f"{self.failure_count} file{s} {failed}", fg="red")
3512 return ", ".join(report) + "."
3515 def parse_ast(src: str) -> Union[ast.AST, ast3.AST, ast27.AST]:
3516 filename = "<unknown>"
3517 if sys.version_info >= (3, 8):
3518 # TODO: support Python 4+ ;)
3519 for minor_version in range(sys.version_info[1], 4, -1):
3521 return ast.parse(src, filename, feature_version=(3, minor_version))
3525 for feature_version in (7, 6):
3527 return ast3.parse(src, filename, feature_version=feature_version)
3531 return ast27.parse(src)
3534 def _fixup_ast_constants(
3535 node: Union[ast.AST, ast3.AST, ast27.AST]
3536 ) -> Union[ast.AST, ast3.AST, ast27.AST]:
3537 """Map ast nodes deprecated in 3.8 to Constant."""
3538 # casts are required until this is released:
3539 # https://github.com/python/typeshed/pull/3142
3540 if isinstance(node, (ast.Str, ast3.Str, ast27.Str, ast.Bytes, ast3.Bytes)):
3541 return cast(ast.AST, ast.Constant(value=node.s))
3542 elif isinstance(node, (ast.Num, ast3.Num, ast27.Num)):
3543 return cast(ast.AST, ast.Constant(value=node.n))
3544 elif isinstance(node, (ast.NameConstant, ast3.NameConstant)):
3545 return cast(ast.AST, ast.Constant(value=node.value))
3549 def assert_equivalent(src: str, dst: str) -> None:
3550 """Raise AssertionError if `src` and `dst` aren't equivalent."""
3552 def _v(node: Union[ast.AST, ast3.AST, ast27.AST], depth: int = 0) -> Iterator[str]:
3553 """Simple visitor generating strings to compare ASTs by content."""
3555 node = _fixup_ast_constants(node)
3557 yield f"{' ' * depth}{node.__class__.__name__}("
3559 for field in sorted(node._fields):
3560 # TypeIgnore has only one field 'lineno' which breaks this comparison
3561 type_ignore_classes = (ast3.TypeIgnore, ast27.TypeIgnore)
3562 if sys.version_info >= (3, 8):
3563 type_ignore_classes += (ast.TypeIgnore,)
3564 if isinstance(node, type_ignore_classes):
3568 value = getattr(node, field)
3569 except AttributeError:
3572 yield f"{' ' * (depth+1)}{field}="
3574 if isinstance(value, list):
3576 # Ignore nested tuples within del statements, because we may insert
3577 # parentheses and they change the AST.
3580 and isinstance(node, (ast.Delete, ast3.Delete, ast27.Delete))
3581 and isinstance(item, (ast.Tuple, ast3.Tuple, ast27.Tuple))
3583 for item in item.elts:
3584 yield from _v(item, depth + 2)
3585 elif isinstance(item, (ast.AST, ast3.AST, ast27.AST)):
3586 yield from _v(item, depth + 2)
3588 elif isinstance(value, (ast.AST, ast3.AST, ast27.AST)):
3589 yield from _v(value, depth + 2)
3592 yield f"{' ' * (depth+2)}{value!r}, # {value.__class__.__name__}"
3594 yield f"{' ' * depth}) # /{node.__class__.__name__}"
3597 src_ast = parse_ast(src)
3598 except Exception as exc:
3599 raise AssertionError(
3600 f"cannot use --safe with this file; failed to parse source file. "
3601 f"AST error message: {exc}"
3605 dst_ast = parse_ast(dst)
3606 except Exception as exc:
3607 log = dump_to_file("".join(traceback.format_tb(exc.__traceback__)), dst)
3608 raise AssertionError(
3609 f"INTERNAL ERROR: Black produced invalid code: {exc}. "
3610 f"Please report a bug on https://github.com/psf/black/issues. "
3611 f"This invalid output might be helpful: {log}"
3614 src_ast_str = "\n".join(_v(src_ast))
3615 dst_ast_str = "\n".join(_v(dst_ast))
3616 if src_ast_str != dst_ast_str:
3617 log = dump_to_file(diff(src_ast_str, dst_ast_str, "src", "dst"))
3618 raise AssertionError(
3619 f"INTERNAL ERROR: Black produced code that is not equivalent to "
3621 f"Please report a bug on https://github.com/psf/black/issues. "
3622 f"This diff might be helpful: {log}"
3626 def assert_stable(src: str, dst: str, mode: FileMode) -> None:
3627 """Raise AssertionError if `dst` reformats differently the second time."""
3628 newdst = format_str(dst, mode=mode)
3631 diff(src, dst, "source", "first pass"),
3632 diff(dst, newdst, "first pass", "second pass"),
3634 raise AssertionError(
3635 f"INTERNAL ERROR: Black produced different code on the second pass "
3636 f"of the formatter. "
3637 f"Please report a bug on https://github.com/psf/black/issues. "
3638 f"This diff might be helpful: {log}"
3642 def dump_to_file(*output: str) -> str:
3643 """Dump `output` to a temporary file. Return path to the file."""
3644 with tempfile.NamedTemporaryFile(
3645 mode="w", prefix="blk_", suffix=".log", delete=False, encoding="utf8"
3647 for lines in output:
3649 if lines and lines[-1] != "\n":
3655 def nullcontext() -> Iterator[None]:
3656 """Return context manager that does nothing.
3657 Similar to `nullcontext` from python 3.7"""
3661 def diff(a: str, b: str, a_name: str, b_name: str) -> str:
3662 """Return a unified diff string between strings `a` and `b`."""
3665 a_lines = [line + "\n" for line in a.split("\n")]
3666 b_lines = [line + "\n" for line in b.split("\n")]
3668 difflib.unified_diff(a_lines, b_lines, fromfile=a_name, tofile=b_name, n=5)
3672 def cancel(tasks: Iterable[asyncio.Task]) -> None:
3673 """asyncio signal handler that cancels all `tasks` and reports to stderr."""
3679 def shutdown(loop: asyncio.AbstractEventLoop) -> None:
3680 """Cancel all pending tasks on `loop`, wait for them, and close the loop."""
3682 if sys.version_info[:2] >= (3, 7):
3683 all_tasks = asyncio.all_tasks
3685 all_tasks = asyncio.Task.all_tasks
3686 # This part is borrowed from asyncio/runners.py in Python 3.7b2.
3687 to_cancel = [task for task in all_tasks(loop) if not task.done()]
3691 for task in to_cancel:
3693 loop.run_until_complete(
3694 asyncio.gather(*to_cancel, loop=loop, return_exceptions=True)
3697 # `concurrent.futures.Future` objects cannot be cancelled once they
3698 # are already running. There might be some when the `shutdown()` happened.
3699 # Silence their logger's spew about the event loop being closed.
3700 cf_logger = logging.getLogger("concurrent.futures")
3701 cf_logger.setLevel(logging.CRITICAL)
3705 def sub_twice(regex: Pattern[str], replacement: str, original: str) -> str:
3706 """Replace `regex` with `replacement` twice on `original`.
3708 This is used by string normalization to perform replaces on
3709 overlapping matches.
3711 return regex.sub(replacement, regex.sub(replacement, original))
3714 def re_compile_maybe_verbose(regex: str) -> Pattern[str]:
3715 """Compile a regular expression string in `regex`.
3717 If it contains newlines, use verbose mode.
3720 regex = "(?x)" + regex
3721 return re.compile(regex)
3724 def enumerate_reversed(sequence: Sequence[T]) -> Iterator[Tuple[Index, T]]:
3725 """Like `reversed(enumerate(sequence))` if that were possible."""
3726 index = len(sequence) - 1
3727 for element in reversed(sequence):
3728 yield (index, element)
3732 def enumerate_with_length(
3733 line: Line, reversed: bool = False
3734 ) -> Iterator[Tuple[Index, Leaf, int]]:
3735 """Return an enumeration of leaves with their length.
3737 Stops prematurely on multiline strings and standalone comments.
3740 Callable[[Sequence[Leaf]], Iterator[Tuple[Index, Leaf]]],
3741 enumerate_reversed if reversed else enumerate,
3743 for index, leaf in op(line.leaves):
3744 length = len(leaf.prefix) + len(leaf.value)
3745 if "\n" in leaf.value:
3746 return # Multiline strings, we can't continue.
3748 for comment in line.comments_after(leaf):
3749 length += len(comment.value)
3751 yield index, leaf, length
3754 def is_line_short_enough(line: Line, *, line_length: int, line_str: str = "") -> bool:
3755 """Return True if `line` is no longer than `line_length`.
3757 Uses the provided `line_str` rendering, if any, otherwise computes a new one.
3760 line_str = str(line).strip("\n")
3762 len(line_str) <= line_length
3763 and "\n" not in line_str # multiline strings
3764 and not line.contains_standalone_comments()
3768 def can_be_split(line: Line) -> bool:
3769 """Return False if the line cannot be split *for sure*.
3771 This is not an exhaustive search but a cheap heuristic that we can use to
3772 avoid some unfortunate formattings (mostly around wrapping unsplittable code
3773 in unnecessary parentheses).
3775 leaves = line.leaves
3779 if leaves[0].type == token.STRING and leaves[1].type == token.DOT:
3783 for leaf in leaves[-2::-1]:
3784 if leaf.type in OPENING_BRACKETS:
3785 if next.type not in CLOSING_BRACKETS:
3789 elif leaf.type == token.DOT:
3791 elif leaf.type == token.NAME:
3792 if not (next.type == token.DOT or next.type in OPENING_BRACKETS):
3795 elif leaf.type not in CLOSING_BRACKETS:
3798 if dot_count > 1 and call_count > 1:
3804 def can_omit_invisible_parens(line: Line, line_length: int) -> bool:
3805 """Does `line` have a shape safe to reformat without optional parens around it?
3807 Returns True for only a subset of potentially nice looking formattings but
3808 the point is to not return false positives that end up producing lines that
3811 bt = line.bracket_tracker
3812 if not bt.delimiters:
3813 # Without delimiters the optional parentheses are useless.
3816 max_priority = bt.max_delimiter_priority()
3817 if bt.delimiter_count_with_priority(max_priority) > 1:
3818 # With more than one delimiter of a kind the optional parentheses read better.
3821 if max_priority == DOT_PRIORITY:
3822 # A single stranded method call doesn't require optional parentheses.
3825 assert len(line.leaves) >= 2, "Stranded delimiter"
3827 first = line.leaves[0]
3828 second = line.leaves[1]
3829 penultimate = line.leaves[-2]
3830 last = line.leaves[-1]
3832 # With a single delimiter, omit if the expression starts or ends with
3834 if first.type in OPENING_BRACKETS and second.type not in CLOSING_BRACKETS:
3836 length = 4 * line.depth
3837 for _index, leaf, leaf_length in enumerate_with_length(line):
3838 if leaf.type in CLOSING_BRACKETS and leaf.opening_bracket is first:
3841 length += leaf_length
3842 if length > line_length:
3845 if leaf.type in OPENING_BRACKETS:
3846 # There are brackets we can further split on.
3850 # checked the entire string and line length wasn't exceeded
3851 if len(line.leaves) == _index + 1:
3854 # Note: we are not returning False here because a line might have *both*
3855 # a leading opening bracket and a trailing closing bracket. If the
3856 # opening bracket doesn't match our rule, maybe the closing will.
3859 last.type == token.RPAR
3860 or last.type == token.RBRACE
3862 # don't use indexing for omitting optional parentheses;
3864 last.type == token.RSQB
3866 and last.parent.type != syms.trailer
3869 if penultimate.type in OPENING_BRACKETS:
3870 # Empty brackets don't help.
3873 if is_multiline_string(first):
3874 # Additional wrapping of a multiline string in this situation is
3878 length = 4 * line.depth
3879 seen_other_brackets = False
3880 for _index, leaf, leaf_length in enumerate_with_length(line):
3881 length += leaf_length
3882 if leaf is last.opening_bracket:
3883 if seen_other_brackets or length <= line_length:
3886 elif leaf.type in OPENING_BRACKETS:
3887 # There are brackets we can further split on.
3888 seen_other_brackets = True
3893 def get_cache_file(mode: FileMode) -> Path:
3894 return CACHE_DIR / f"cache.{mode.get_cache_key()}.pickle"
3897 def read_cache(mode: FileMode) -> Cache:
3898 """Read the cache if it exists and is well formed.
3900 If it is not well formed, the call to write_cache later should resolve the issue.
3902 cache_file = get_cache_file(mode)
3903 if not cache_file.exists():
3906 with cache_file.open("rb") as fobj:
3908 cache: Cache = pickle.load(fobj)
3909 except pickle.UnpicklingError:
3915 def get_cache_info(path: Path) -> CacheInfo:
3916 """Return the information used to check if a file is already formatted or not."""
3918 return stat.st_mtime, stat.st_size
3921 def filter_cached(cache: Cache, sources: Iterable[Path]) -> Tuple[Set[Path], Set[Path]]:
3922 """Split an iterable of paths in `sources` into two sets.
3924 The first contains paths of files that modified on disk or are not in the
3925 cache. The other contains paths to non-modified files.
3927 todo, done = set(), set()
3930 if cache.get(src) != get_cache_info(src):
3937 def write_cache(cache: Cache, sources: Iterable[Path], mode: FileMode) -> None:
3938 """Update the cache file."""
3939 cache_file = get_cache_file(mode)
3941 CACHE_DIR.mkdir(parents=True, exist_ok=True)
3942 new_cache = {**cache, **{src.resolve(): get_cache_info(src) for src in sources}}
3943 with tempfile.NamedTemporaryFile(dir=str(cache_file.parent), delete=False) as f:
3944 pickle.dump(new_cache, f, protocol=pickle.HIGHEST_PROTOCOL)
3945 os.replace(f.name, cache_file)
3950 def patch_click() -> None:
3951 """Make Click not crash.
3953 On certain misconfigured environments, Python 3 selects the ASCII encoding as the
3954 default which restricts paths that it can access during the lifetime of the
3955 application. Click refuses to work in this scenario by raising a RuntimeError.
3957 In case of Black the likelihood that non-ASCII characters are going to be used in
3958 file paths is minimal since it's Python source code. Moreover, this crash was
3959 spurious on Python 3.7 thanks to PEP 538 and PEP 540.
3962 from click import core
3963 from click import _unicodefun # type: ignore
3964 except ModuleNotFoundError:
3967 for module in (core, _unicodefun):
3968 if hasattr(module, "_verify_python3_env"):
3969 module._verify_python3_env = lambda: None
3972 def patched_main() -> None:
3978 if __name__ == "__main__":