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

madduck's git repository

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

All patches and comments are welcome. Please squash your changes to logical commits before using git-format-patch and git-send-email to patches@git.madduck.net. If you'd read over the Git project's submission guidelines and adhered to them, I'd be especially grateful.

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

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

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

74b932bb42256d041de728a012de1d3349197bbc
[etc/vim.git] / src / black / trans.py
1 """
2 String transformers that can split and merge strings.
3 """
4 import re
5 import sys
6 from abc import ABC, abstractmethod
7 from collections import defaultdict
8 from dataclasses import dataclass
9 from typing import (
10     Any,
11     Callable,
12     ClassVar,
13     Collection,
14     Dict,
15     Iterable,
16     Iterator,
17     List,
18     Optional,
19     Sequence,
20     Set,
21     Tuple,
22     TypeVar,
23     Union,
24 )
25
26 if sys.version_info < (3, 8):
27     from typing_extensions import Final, Literal
28 else:
29     from typing import Literal, Final
30
31 from mypy_extensions import trait
32
33 from black.brackets import BracketMatchError
34 from black.comments import contains_pragma_comment
35 from black.lines import Line, append_leaves
36 from black.mode import Feature
37 from black.nodes import (
38     CLOSING_BRACKETS,
39     OPENING_BRACKETS,
40     STANDALONE_COMMENT,
41     is_empty_lpar,
42     is_empty_par,
43     is_empty_rpar,
44     parent_type,
45     replace_child,
46     syms,
47 )
48 from black.rusty import Err, Ok, Result
49 from black.strings import (
50     assert_is_leaf_string,
51     get_string_prefix,
52     has_triple_quotes,
53     normalize_string_quotes,
54 )
55 from blib2to3.pgen2 import token
56 from blib2to3.pytree import Leaf, Node
57
58
59 class CannotTransform(Exception):
60     """Base class for errors raised by Transformers."""
61
62
63 # types
64 T = TypeVar("T")
65 LN = Union[Leaf, Node]
66 Transformer = Callable[[Line, Collection[Feature]], Iterator[Line]]
67 Index = int
68 NodeType = int
69 ParserState = int
70 StringID = int
71 TResult = Result[T, CannotTransform]  # (T)ransform Result
72 TMatchResult = TResult[Index]
73
74
75 def TErr(err_msg: str) -> Err[CannotTransform]:
76     """(T)ransform Err
77
78     Convenience function used when working with the TResult type.
79     """
80     cant_transform = CannotTransform(err_msg)
81     return Err(cant_transform)
82
83
84 def hug_power_op(line: Line, features: Collection[Feature]) -> Iterator[Line]:
85     """A transformer which normalizes spacing around power operators."""
86
87     # Performance optimization to avoid unnecessary Leaf clones and other ops.
88     for leaf in line.leaves:
89         if leaf.type == token.DOUBLESTAR:
90             break
91     else:
92         raise CannotTransform("No doublestar token was found in the line.")
93
94     def is_simple_lookup(index: int, step: Literal[1, -1]) -> bool:
95         # Brackets and parentheses indicate calls, subscripts, etc. ...
96         # basically stuff that doesn't count as "simple". Only a NAME lookup
97         # or dotted lookup (eg. NAME.NAME) is OK.
98         if step == -1:
99             disallowed = {token.RPAR, token.RSQB}
100         else:
101             disallowed = {token.LPAR, token.LSQB}
102
103         while 0 <= index < len(line.leaves):
104             current = line.leaves[index]
105             if current.type in disallowed:
106                 return False
107             if current.type not in {token.NAME, token.DOT} or current.value == "for":
108                 # If the current token isn't disallowed, we'll assume this is simple as
109                 # only the disallowed tokens are semantically attached to this lookup
110                 # expression we're checking. Also, stop early if we hit the 'for' bit
111                 # of a comprehension.
112                 return True
113
114             index += step
115
116         return True
117
118     def is_simple_operand(index: int, kind: Literal["base", "exponent"]) -> bool:
119         # An operand is considered "simple" if's a NAME, a numeric CONSTANT, a simple
120         # lookup (see above), with or without a preceding unary operator.
121         start = line.leaves[index]
122         if start.type in {token.NAME, token.NUMBER}:
123             return is_simple_lookup(index, step=(1 if kind == "exponent" else -1))
124
125         if start.type in {token.PLUS, token.MINUS, token.TILDE}:
126             if line.leaves[index + 1].type in {token.NAME, token.NUMBER}:
127                 # step is always one as bases with a preceding unary op will be checked
128                 # for simplicity starting from the next token (so it'll hit the check
129                 # above).
130                 return is_simple_lookup(index + 1, step=1)
131
132         return False
133
134     new_line = line.clone()
135     should_hug = False
136     for idx, leaf in enumerate(line.leaves):
137         new_leaf = leaf.clone()
138         if should_hug:
139             new_leaf.prefix = ""
140             should_hug = False
141
142         should_hug = (
143             (0 < idx < len(line.leaves) - 1)
144             and leaf.type == token.DOUBLESTAR
145             and is_simple_operand(idx - 1, kind="base")
146             and line.leaves[idx - 1].value != "lambda"
147             and is_simple_operand(idx + 1, kind="exponent")
148         )
149         if should_hug:
150             new_leaf.prefix = ""
151
152         # We have to be careful to make a new line properly:
153         # - bracket related metadata must be maintained (handled by Line.append)
154         # - comments need to copied over, updating the leaf IDs they're attached to
155         new_line.append(new_leaf, preformatted=True)
156         for comment_leaf in line.comments_after(leaf):
157             new_line.append(comment_leaf, preformatted=True)
158
159     yield new_line
160
161
162 class StringTransformer(ABC):
163     """
164     An implementation of the Transformer protocol that relies on its
165     subclasses overriding the template methods `do_match(...)` and
166     `do_transform(...)`.
167
168     This Transformer works exclusively on strings (for example, by merging
169     or splitting them).
170
171     The following sections can be found among the docstrings of each concrete
172     StringTransformer subclass.
173
174     Requirements:
175         Which requirements must be met of the given Line for this
176         StringTransformer to be applied?
177
178     Transformations:
179         If the given Line meets all of the above requirements, which string
180         transformations can you expect to be applied to it by this
181         StringTransformer?
182
183     Collaborations:
184         What contractual agreements does this StringTransformer have with other
185         StringTransfomers? Such collaborations should be eliminated/minimized
186         as much as possible.
187     """
188
189     __name__: Final = "StringTransformer"
190
191     # Ideally this would be a dataclass, but unfortunately mypyc breaks when used with
192     # `abc.ABC`.
193     def __init__(self, line_length: int, normalize_strings: bool) -> None:
194         self.line_length = line_length
195         self.normalize_strings = normalize_strings
196
197     @abstractmethod
198     def do_match(self, line: Line) -> TMatchResult:
199         """
200         Returns:
201             * Ok(string_idx) such that `line.leaves[string_idx]` is our target
202             string, if a match was able to be made.
203                 OR
204             * Err(CannotTransform), if a match was not able to be made.
205         """
206
207     @abstractmethod
208     def do_transform(self, line: Line, string_idx: int) -> Iterator[TResult[Line]]:
209         """
210         Yields:
211             * Ok(new_line) where new_line is the new transformed line.
212                 OR
213             * Err(CannotTransform) if the transformation failed for some reason. The
214             `do_match(...)` template method should usually be used to reject
215             the form of the given Line, but in some cases it is difficult to
216             know whether or not a Line meets the StringTransformer's
217             requirements until the transformation is already midway.
218
219         Side Effects:
220             This method should NOT mutate @line directly, but it MAY mutate the
221             Line's underlying Node structure. (WARNING: If the underlying Node
222             structure IS altered, then this method should NOT be allowed to
223             yield an CannotTransform after that point.)
224         """
225
226     def __call__(self, line: Line, _features: Collection[Feature]) -> Iterator[Line]:
227         """
228         StringTransformer instances have a call signature that mirrors that of
229         the Transformer type.
230
231         Raises:
232             CannotTransform(...) if the concrete StringTransformer class is unable
233             to transform @line.
234         """
235         # Optimization to avoid calling `self.do_match(...)` when the line does
236         # not contain any string.
237         if not any(leaf.type == token.STRING for leaf in line.leaves):
238             raise CannotTransform("There are no strings in this line.")
239
240         match_result = self.do_match(line)
241
242         if isinstance(match_result, Err):
243             cant_transform = match_result.err()
244             raise CannotTransform(
245                 f"The string transformer {self.__class__.__name__} does not recognize"
246                 " this line as one that it can transform."
247             ) from cant_transform
248
249         string_idx = match_result.ok()
250
251         for line_result in self.do_transform(line, string_idx):
252             if isinstance(line_result, Err):
253                 cant_transform = line_result.err()
254                 raise CannotTransform(
255                     "StringTransformer failed while attempting to transform string."
256                 ) from cant_transform
257             line = line_result.ok()
258             yield line
259
260
261 @dataclass
262 class CustomSplit:
263     """A custom (i.e. manual) string split.
264
265     A single CustomSplit instance represents a single substring.
266
267     Examples:
268         Consider the following string:
269         ```
270         "Hi there friend."
271         " This is a custom"
272         f" string {split}."
273         ```
274
275         This string will correspond to the following three CustomSplit instances:
276         ```
277         CustomSplit(False, 16)
278         CustomSplit(False, 17)
279         CustomSplit(True, 16)
280         ```
281     """
282
283     has_prefix: bool
284     break_idx: int
285
286
287 @trait
288 class CustomSplitMapMixin:
289     """
290     This mixin class is used to map merged strings to a sequence of
291     CustomSplits, which will then be used to re-split the strings iff none of
292     the resultant substrings go over the configured max line length.
293     """
294
295     _Key: ClassVar = Tuple[StringID, str]
296     _CUSTOM_SPLIT_MAP: ClassVar[Dict[_Key, Tuple[CustomSplit, ...]]] = defaultdict(
297         tuple
298     )
299
300     @staticmethod
301     def _get_key(string: str) -> "CustomSplitMapMixin._Key":
302         """
303         Returns:
304             A unique identifier that is used internally to map @string to a
305             group of custom splits.
306         """
307         return (id(string), string)
308
309     def add_custom_splits(
310         self, string: str, custom_splits: Iterable[CustomSplit]
311     ) -> None:
312         """Custom Split Map Setter Method
313
314         Side Effects:
315             Adds a mapping from @string to the custom splits @custom_splits.
316         """
317         key = self._get_key(string)
318         self._CUSTOM_SPLIT_MAP[key] = tuple(custom_splits)
319
320     def pop_custom_splits(self, string: str) -> List[CustomSplit]:
321         """Custom Split Map Getter Method
322
323         Returns:
324             * A list of the custom splits that are mapped to @string, if any
325             exist.
326                 OR
327             * [], otherwise.
328
329         Side Effects:
330             Deletes the mapping between @string and its associated custom
331             splits (which are returned to the caller).
332         """
333         key = self._get_key(string)
334
335         custom_splits = self._CUSTOM_SPLIT_MAP[key]
336         del self._CUSTOM_SPLIT_MAP[key]
337
338         return list(custom_splits)
339
340     def has_custom_splits(self, string: str) -> bool:
341         """
342         Returns:
343             True iff @string is associated with a set of custom splits.
344         """
345         key = self._get_key(string)
346         return key in self._CUSTOM_SPLIT_MAP
347
348
349 class StringMerger(StringTransformer, CustomSplitMapMixin):
350     """StringTransformer that merges strings together.
351
352     Requirements:
353         (A) The line contains adjacent strings such that ALL of the validation checks
354         listed in StringMerger.__validate_msg(...)'s docstring pass.
355             OR
356         (B) The line contains a string which uses line continuation backslashes.
357
358     Transformations:
359         Depending on which of the two requirements above where met, either:
360
361         (A) The string group associated with the target string is merged.
362             OR
363         (B) All line-continuation backslashes are removed from the target string.
364
365     Collaborations:
366         StringMerger provides custom split information to StringSplitter.
367     """
368
369     def do_match(self, line: Line) -> TMatchResult:
370         LL = line.leaves
371
372         is_valid_index = is_valid_index_factory(LL)
373
374         for i, leaf in enumerate(LL):
375             if (
376                 leaf.type == token.STRING
377                 and is_valid_index(i + 1)
378                 and LL[i + 1].type == token.STRING
379             ):
380                 return Ok(i)
381
382             if leaf.type == token.STRING and "\\\n" in leaf.value:
383                 return Ok(i)
384
385         return TErr("This line has no strings that need merging.")
386
387     def do_transform(self, line: Line, string_idx: int) -> Iterator[TResult[Line]]:
388         new_line = line
389         rblc_result = self._remove_backslash_line_continuation_chars(
390             new_line, string_idx
391         )
392         if isinstance(rblc_result, Ok):
393             new_line = rblc_result.ok()
394
395         msg_result = self._merge_string_group(new_line, string_idx)
396         if isinstance(msg_result, Ok):
397             new_line = msg_result.ok()
398
399         if isinstance(rblc_result, Err) and isinstance(msg_result, Err):
400             msg_cant_transform = msg_result.err()
401             rblc_cant_transform = rblc_result.err()
402             cant_transform = CannotTransform(
403                 "StringMerger failed to merge any strings in this line."
404             )
405
406             # Chain the errors together using `__cause__`.
407             msg_cant_transform.__cause__ = rblc_cant_transform
408             cant_transform.__cause__ = msg_cant_transform
409
410             yield Err(cant_transform)
411         else:
412             yield Ok(new_line)
413
414     @staticmethod
415     def _remove_backslash_line_continuation_chars(
416         line: Line, string_idx: int
417     ) -> TResult[Line]:
418         """
419         Merge strings that were split across multiple lines using
420         line-continuation backslashes.
421
422         Returns:
423             Ok(new_line), if @line contains backslash line-continuation
424             characters.
425                 OR
426             Err(CannotTransform), otherwise.
427         """
428         LL = line.leaves
429
430         string_leaf = LL[string_idx]
431         if not (
432             string_leaf.type == token.STRING
433             and "\\\n" in string_leaf.value
434             and not has_triple_quotes(string_leaf.value)
435         ):
436             return TErr(
437                 f"String leaf {string_leaf} does not contain any backslash line"
438                 " continuation characters."
439             )
440
441         new_line = line.clone()
442         new_line.comments = line.comments.copy()
443         append_leaves(new_line, line, LL)
444
445         new_string_leaf = new_line.leaves[string_idx]
446         new_string_leaf.value = new_string_leaf.value.replace("\\\n", "")
447
448         return Ok(new_line)
449
450     def _merge_string_group(self, line: Line, string_idx: int) -> TResult[Line]:
451         """
452         Merges string group (i.e. set of adjacent strings) where the first
453         string in the group is `line.leaves[string_idx]`.
454
455         Returns:
456             Ok(new_line), if ALL of the validation checks found in
457             __validate_msg(...) pass.
458                 OR
459             Err(CannotTransform), otherwise.
460         """
461         LL = line.leaves
462
463         is_valid_index = is_valid_index_factory(LL)
464
465         vresult = self._validate_msg(line, string_idx)
466         if isinstance(vresult, Err):
467             return vresult
468
469         # If the string group is wrapped inside an Atom node, we must make sure
470         # to later replace that Atom with our new (merged) string leaf.
471         atom_node = LL[string_idx].parent
472
473         # We will place BREAK_MARK in between every two substrings that we
474         # merge. We will then later go through our final result and use the
475         # various instances of BREAK_MARK we find to add the right values to
476         # the custom split map.
477         BREAK_MARK = "@@@@@ BLACK BREAKPOINT MARKER @@@@@"
478
479         QUOTE = LL[string_idx].value[-1]
480
481         def make_naked(string: str, string_prefix: str) -> str:
482             """Strip @string (i.e. make it a "naked" string)
483
484             Pre-conditions:
485                 * assert_is_leaf_string(@string)
486
487             Returns:
488                 A string that is identical to @string except that
489                 @string_prefix has been stripped, the surrounding QUOTE
490                 characters have been removed, and any remaining QUOTE
491                 characters have been escaped.
492             """
493             assert_is_leaf_string(string)
494
495             RE_EVEN_BACKSLASHES = r"(?:(?<!\\)(?:\\\\)*)"
496             naked_string = string[len(string_prefix) + 1 : -1]
497             naked_string = re.sub(
498                 "(" + RE_EVEN_BACKSLASHES + ")" + QUOTE, r"\1\\" + QUOTE, naked_string
499             )
500             return naked_string
501
502         # Holds the CustomSplit objects that will later be added to the custom
503         # split map.
504         custom_splits = []
505
506         # Temporary storage for the 'has_prefix' part of the CustomSplit objects.
507         prefix_tracker = []
508
509         # Sets the 'prefix' variable. This is the prefix that the final merged
510         # string will have.
511         next_str_idx = string_idx
512         prefix = ""
513         while (
514             not prefix
515             and is_valid_index(next_str_idx)
516             and LL[next_str_idx].type == token.STRING
517         ):
518             prefix = get_string_prefix(LL[next_str_idx].value).lower()
519             next_str_idx += 1
520
521         # The next loop merges the string group. The final string will be
522         # contained in 'S'.
523         #
524         # The following convenience variables are used:
525         #
526         #   S: string
527         #   NS: naked string
528         #   SS: next string
529         #   NSS: naked next string
530         S = ""
531         NS = ""
532         num_of_strings = 0
533         next_str_idx = string_idx
534         while is_valid_index(next_str_idx) and LL[next_str_idx].type == token.STRING:
535             num_of_strings += 1
536
537             SS = LL[next_str_idx].value
538             next_prefix = get_string_prefix(SS).lower()
539
540             # If this is an f-string group but this substring is not prefixed
541             # with 'f'...
542             if "f" in prefix and "f" not in next_prefix:
543                 # Then we must escape any braces contained in this substring.
544                 SS = re.sub(r"(\{|\})", r"\1\1", SS)
545
546             NSS = make_naked(SS, next_prefix)
547
548             has_prefix = bool(next_prefix)
549             prefix_tracker.append(has_prefix)
550
551             S = prefix + QUOTE + NS + NSS + BREAK_MARK + QUOTE
552             NS = make_naked(S, prefix)
553
554             next_str_idx += 1
555
556         # Take a note on the index of the non-STRING leaf.
557         non_string_idx = next_str_idx
558
559         S_leaf = Leaf(token.STRING, S)
560         if self.normalize_strings:
561             S_leaf.value = normalize_string_quotes(S_leaf.value)
562
563         # Fill the 'custom_splits' list with the appropriate CustomSplit objects.
564         temp_string = S_leaf.value[len(prefix) + 1 : -1]
565         for has_prefix in prefix_tracker:
566             mark_idx = temp_string.find(BREAK_MARK)
567             assert (
568                 mark_idx >= 0
569             ), "Logic error while filling the custom string breakpoint cache."
570
571             temp_string = temp_string[mark_idx + len(BREAK_MARK) :]
572             breakpoint_idx = mark_idx + (len(prefix) if has_prefix else 0) + 1
573             custom_splits.append(CustomSplit(has_prefix, breakpoint_idx))
574
575         string_leaf = Leaf(token.STRING, S_leaf.value.replace(BREAK_MARK, ""))
576
577         if atom_node is not None:
578             # If not all children of the atom node are merged (this can happen
579             # when there is a standalone comment in the middle) ...
580             if non_string_idx - string_idx < len(atom_node.children):
581                 # We need to replace the old STRING leaves with the new string leaf.
582                 first_child_idx = LL[string_idx].remove()
583                 for idx in range(string_idx + 1, non_string_idx):
584                     LL[idx].remove()
585                 if first_child_idx is not None:
586                     atom_node.insert_child(first_child_idx, string_leaf)
587             else:
588                 # Else replace the atom node with the new string leaf.
589                 replace_child(atom_node, string_leaf)
590
591         # Build the final line ('new_line') that this method will later return.
592         new_line = line.clone()
593         for i, leaf in enumerate(LL):
594             if i == string_idx:
595                 new_line.append(string_leaf)
596
597             if string_idx <= i < string_idx + num_of_strings:
598                 for comment_leaf in line.comments_after(LL[i]):
599                     new_line.append(comment_leaf, preformatted=True)
600                 continue
601
602             append_leaves(new_line, line, [leaf])
603
604         self.add_custom_splits(string_leaf.value, custom_splits)
605         return Ok(new_line)
606
607     @staticmethod
608     def _validate_msg(line: Line, string_idx: int) -> TResult[None]:
609         """Validate (M)erge (S)tring (G)roup
610
611         Transform-time string validation logic for __merge_string_group(...).
612
613         Returns:
614             * Ok(None), if ALL validation checks (listed below) pass.
615                 OR
616             * Err(CannotTransform), if any of the following are true:
617                 - The target string group does not contain ANY stand-alone comments.
618                 - The target string is not in a string group (i.e. it has no
619                   adjacent strings).
620                 - The string group has more than one inline comment.
621                 - The string group has an inline comment that appears to be a pragma.
622                 - The set of all string prefixes in the string group is of
623                   length greater than one and is not equal to {"", "f"}.
624                 - The string group consists of raw strings.
625         """
626         # We first check for "inner" stand-alone comments (i.e. stand-alone
627         # comments that have a string leaf before them AND after them).
628         for inc in [1, -1]:
629             i = string_idx
630             found_sa_comment = False
631             is_valid_index = is_valid_index_factory(line.leaves)
632             while is_valid_index(i) and line.leaves[i].type in [
633                 token.STRING,
634                 STANDALONE_COMMENT,
635             ]:
636                 if line.leaves[i].type == STANDALONE_COMMENT:
637                     found_sa_comment = True
638                 elif found_sa_comment:
639                     return TErr(
640                         "StringMerger does NOT merge string groups which contain "
641                         "stand-alone comments."
642                     )
643
644                 i += inc
645
646         num_of_inline_string_comments = 0
647         set_of_prefixes = set()
648         num_of_strings = 0
649         for leaf in line.leaves[string_idx:]:
650             if leaf.type != token.STRING:
651                 # If the string group is trailed by a comma, we count the
652                 # comments trailing the comma to be one of the string group's
653                 # comments.
654                 if leaf.type == token.COMMA and id(leaf) in line.comments:
655                     num_of_inline_string_comments += 1
656                 break
657
658             if has_triple_quotes(leaf.value):
659                 return TErr("StringMerger does NOT merge multiline strings.")
660
661             num_of_strings += 1
662             prefix = get_string_prefix(leaf.value).lower()
663             if "r" in prefix:
664                 return TErr("StringMerger does NOT merge raw strings.")
665
666             set_of_prefixes.add(prefix)
667
668             if id(leaf) in line.comments:
669                 num_of_inline_string_comments += 1
670                 if contains_pragma_comment(line.comments[id(leaf)]):
671                     return TErr("Cannot merge strings which have pragma comments.")
672
673         if num_of_strings < 2:
674             return TErr(
675                 f"Not enough strings to merge (num_of_strings={num_of_strings})."
676             )
677
678         if num_of_inline_string_comments > 1:
679             return TErr(
680                 f"Too many inline string comments ({num_of_inline_string_comments})."
681             )
682
683         if len(set_of_prefixes) > 1 and set_of_prefixes != {"", "f"}:
684             return TErr(f"Too many different prefixes ({set_of_prefixes}).")
685
686         return Ok(None)
687
688
689 class StringParenStripper(StringTransformer):
690     """StringTransformer that strips surrounding parentheses from strings.
691
692     Requirements:
693         The line contains a string which is surrounded by parentheses and:
694             - The target string is NOT the only argument to a function call.
695             - The target string is NOT a "pointless" string.
696             - If the target string contains a PERCENT, the brackets are not
697               preceded or followed by an operator with higher precedence than
698               PERCENT.
699
700     Transformations:
701         The parentheses mentioned in the 'Requirements' section are stripped.
702
703     Collaborations:
704         StringParenStripper has its own inherent usefulness, but it is also
705         relied on to clean up the parentheses created by StringParenWrapper (in
706         the event that they are no longer needed).
707     """
708
709     def do_match(self, line: Line) -> TMatchResult:
710         LL = line.leaves
711
712         is_valid_index = is_valid_index_factory(LL)
713
714         for idx, leaf in enumerate(LL):
715             # Should be a string...
716             if leaf.type != token.STRING:
717                 continue
718
719             # If this is a "pointless" string...
720             if (
721                 leaf.parent
722                 and leaf.parent.parent
723                 and leaf.parent.parent.type == syms.simple_stmt
724             ):
725                 continue
726
727             # Should be preceded by a non-empty LPAR...
728             if (
729                 not is_valid_index(idx - 1)
730                 or LL[idx - 1].type != token.LPAR
731                 or is_empty_lpar(LL[idx - 1])
732             ):
733                 continue
734
735             # That LPAR should NOT be preceded by a function name or a closing
736             # bracket (which could be a function which returns a function or a
737             # list/dictionary that contains a function)...
738             if is_valid_index(idx - 2) and (
739                 LL[idx - 2].type == token.NAME or LL[idx - 2].type in CLOSING_BRACKETS
740             ):
741                 continue
742
743             string_idx = idx
744
745             # Skip the string trailer, if one exists.
746             string_parser = StringParser()
747             next_idx = string_parser.parse(LL, string_idx)
748
749             # if the leaves in the parsed string include a PERCENT, we need to
750             # make sure the initial LPAR is NOT preceded by an operator with
751             # higher or equal precedence to PERCENT
752             if is_valid_index(idx - 2):
753                 # mypy can't quite follow unless we name this
754                 before_lpar = LL[idx - 2]
755                 if token.PERCENT in {leaf.type for leaf in LL[idx - 1 : next_idx]} and (
756                     (
757                         before_lpar.type
758                         in {
759                             token.STAR,
760                             token.AT,
761                             token.SLASH,
762                             token.DOUBLESLASH,
763                             token.PERCENT,
764                             token.TILDE,
765                             token.DOUBLESTAR,
766                             token.AWAIT,
767                             token.LSQB,
768                             token.LPAR,
769                         }
770                     )
771                     or (
772                         # only unary PLUS/MINUS
773                         before_lpar.parent
774                         and before_lpar.parent.type == syms.factor
775                         and (before_lpar.type in {token.PLUS, token.MINUS})
776                     )
777                 ):
778                     continue
779
780             # Should be followed by a non-empty RPAR...
781             if (
782                 is_valid_index(next_idx)
783                 and LL[next_idx].type == token.RPAR
784                 and not is_empty_rpar(LL[next_idx])
785             ):
786                 # That RPAR should NOT be followed by anything with higher
787                 # precedence than PERCENT
788                 if is_valid_index(next_idx + 1) and LL[next_idx + 1].type in {
789                     token.DOUBLESTAR,
790                     token.LSQB,
791                     token.LPAR,
792                     token.DOT,
793                 }:
794                     continue
795
796                 return Ok(string_idx)
797
798         return TErr("This line has no strings wrapped in parens.")
799
800     def do_transform(self, line: Line, string_idx: int) -> Iterator[TResult[Line]]:
801         LL = line.leaves
802
803         string_parser = StringParser()
804         rpar_idx = string_parser.parse(LL, string_idx)
805
806         for leaf in (LL[string_idx - 1], LL[rpar_idx]):
807             if line.comments_after(leaf):
808                 yield TErr(
809                     "Will not strip parentheses which have comments attached to them."
810                 )
811                 return
812
813         new_line = line.clone()
814         new_line.comments = line.comments.copy()
815         try:
816             append_leaves(new_line, line, LL[: string_idx - 1])
817         except BracketMatchError:
818             # HACK: I believe there is currently a bug somewhere in
819             # right_hand_split() that is causing brackets to not be tracked
820             # properly by a shared BracketTracker.
821             append_leaves(new_line, line, LL[: string_idx - 1], preformatted=True)
822
823         string_leaf = Leaf(token.STRING, LL[string_idx].value)
824         LL[string_idx - 1].remove()
825         replace_child(LL[string_idx], string_leaf)
826         new_line.append(string_leaf)
827
828         append_leaves(
829             new_line, line, LL[string_idx + 1 : rpar_idx] + LL[rpar_idx + 1 :]
830         )
831
832         LL[rpar_idx].remove()
833
834         yield Ok(new_line)
835
836
837 class BaseStringSplitter(StringTransformer):
838     """
839     Abstract class for StringTransformers which transform a Line's strings by splitting
840     them or placing them on their own lines where necessary to avoid going over
841     the configured line length.
842
843     Requirements:
844         * The target string value is responsible for the line going over the
845         line length limit. It follows that after all of black's other line
846         split methods have been exhausted, this line (or one of the resulting
847         lines after all line splits are performed) would still be over the
848         line_length limit unless we split this string.
849             AND
850         * The target string is NOT a "pointless" string (i.e. a string that has
851         no parent or siblings).
852             AND
853         * The target string is not followed by an inline comment that appears
854         to be a pragma.
855             AND
856         * The target string is not a multiline (i.e. triple-quote) string.
857     """
858
859     STRING_OPERATORS: Final = [
860         token.EQEQUAL,
861         token.GREATER,
862         token.GREATEREQUAL,
863         token.LESS,
864         token.LESSEQUAL,
865         token.NOTEQUAL,
866         token.PERCENT,
867         token.PLUS,
868         token.STAR,
869     ]
870
871     @abstractmethod
872     def do_splitter_match(self, line: Line) -> TMatchResult:
873         """
874         BaseStringSplitter asks its clients to override this method instead of
875         `StringTransformer.do_match(...)`.
876
877         Follows the same protocol as `StringTransformer.do_match(...)`.
878
879         Refer to `help(StringTransformer.do_match)` for more information.
880         """
881
882     def do_match(self, line: Line) -> TMatchResult:
883         match_result = self.do_splitter_match(line)
884         if isinstance(match_result, Err):
885             return match_result
886
887         string_idx = match_result.ok()
888         vresult = self._validate(line, string_idx)
889         if isinstance(vresult, Err):
890             return vresult
891
892         return match_result
893
894     def _validate(self, line: Line, string_idx: int) -> TResult[None]:
895         """
896         Checks that @line meets all of the requirements listed in this classes'
897         docstring. Refer to `help(BaseStringSplitter)` for a detailed
898         description of those requirements.
899
900         Returns:
901             * Ok(None), if ALL of the requirements are met.
902                 OR
903             * Err(CannotTransform), if ANY of the requirements are NOT met.
904         """
905         LL = line.leaves
906
907         string_leaf = LL[string_idx]
908
909         max_string_length = self._get_max_string_length(line, string_idx)
910         if len(string_leaf.value) <= max_string_length:
911             return TErr(
912                 "The string itself is not what is causing this line to be too long."
913             )
914
915         if not string_leaf.parent or [L.type for L in string_leaf.parent.children] == [
916             token.STRING,
917             token.NEWLINE,
918         ]:
919             return TErr(
920                 f"This string ({string_leaf.value}) appears to be pointless (i.e. has"
921                 " no parent)."
922             )
923
924         if id(line.leaves[string_idx]) in line.comments and contains_pragma_comment(
925             line.comments[id(line.leaves[string_idx])]
926         ):
927             return TErr(
928                 "Line appears to end with an inline pragma comment. Splitting the line"
929                 " could modify the pragma's behavior."
930             )
931
932         if has_triple_quotes(string_leaf.value):
933             return TErr("We cannot split multiline strings.")
934
935         return Ok(None)
936
937     def _get_max_string_length(self, line: Line, string_idx: int) -> int:
938         """
939         Calculates the max string length used when attempting to determine
940         whether or not the target string is responsible for causing the line to
941         go over the line length limit.
942
943         WARNING: This method is tightly coupled to both StringSplitter and
944         (especially) StringParenWrapper. There is probably a better way to
945         accomplish what is being done here.
946
947         Returns:
948             max_string_length: such that `line.leaves[string_idx].value >
949             max_string_length` implies that the target string IS responsible
950             for causing this line to exceed the line length limit.
951         """
952         LL = line.leaves
953
954         is_valid_index = is_valid_index_factory(LL)
955
956         # We use the shorthand "WMA4" in comments to abbreviate "We must
957         # account for". When giving examples, we use STRING to mean some/any
958         # valid string.
959         #
960         # Finally, we use the following convenience variables:
961         #
962         #   P:  The leaf that is before the target string leaf.
963         #   N:  The leaf that is after the target string leaf.
964         #   NN: The leaf that is after N.
965
966         # WMA4 the whitespace at the beginning of the line.
967         offset = line.depth * 4
968
969         if is_valid_index(string_idx - 1):
970             p_idx = string_idx - 1
971             if (
972                 LL[string_idx - 1].type == token.LPAR
973                 and LL[string_idx - 1].value == ""
974                 and string_idx >= 2
975             ):
976                 # If the previous leaf is an empty LPAR placeholder, we should skip it.
977                 p_idx -= 1
978
979             P = LL[p_idx]
980             if P.type in self.STRING_OPERATORS:
981                 # WMA4 a space and a string operator (e.g. `+ STRING` or `== STRING`).
982                 offset += len(str(P)) + 1
983
984             if P.type == token.COMMA:
985                 # WMA4 a space, a comma, and a closing bracket [e.g. `), STRING`].
986                 offset += 3
987
988             if P.type in [token.COLON, token.EQUAL, token.PLUSEQUAL, token.NAME]:
989                 # This conditional branch is meant to handle dictionary keys,
990                 # variable assignments, 'return STRING' statement lines, and
991                 # 'else STRING' ternary expression lines.
992
993                 # WMA4 a single space.
994                 offset += 1
995
996                 # WMA4 the lengths of any leaves that came before that space,
997                 # but after any closing bracket before that space.
998                 for leaf in reversed(LL[: p_idx + 1]):
999                     offset += len(str(leaf))
1000                     if leaf.type in CLOSING_BRACKETS:
1001                         break
1002
1003         if is_valid_index(string_idx + 1):
1004             N = LL[string_idx + 1]
1005             if N.type == token.RPAR and N.value == "" and len(LL) > string_idx + 2:
1006                 # If the next leaf is an empty RPAR placeholder, we should skip it.
1007                 N = LL[string_idx + 2]
1008
1009             if N.type == token.COMMA:
1010                 # WMA4 a single comma at the end of the string (e.g `STRING,`).
1011                 offset += 1
1012
1013             if is_valid_index(string_idx + 2):
1014                 NN = LL[string_idx + 2]
1015
1016                 if N.type == token.DOT and NN.type == token.NAME:
1017                     # This conditional branch is meant to handle method calls invoked
1018                     # off of a string literal up to and including the LPAR character.
1019
1020                     # WMA4 the '.' character.
1021                     offset += 1
1022
1023                     if (
1024                         is_valid_index(string_idx + 3)
1025                         and LL[string_idx + 3].type == token.LPAR
1026                     ):
1027                         # WMA4 the left parenthesis character.
1028                         offset += 1
1029
1030                     # WMA4 the length of the method's name.
1031                     offset += len(NN.value)
1032
1033         has_comments = False
1034         for comment_leaf in line.comments_after(LL[string_idx]):
1035             if not has_comments:
1036                 has_comments = True
1037                 # WMA4 two spaces before the '#' character.
1038                 offset += 2
1039
1040             # WMA4 the length of the inline comment.
1041             offset += len(comment_leaf.value)
1042
1043         max_string_length = self.line_length - offset
1044         return max_string_length
1045
1046     @staticmethod
1047     def _prefer_paren_wrap_match(LL: List[Leaf]) -> Optional[int]:
1048         """
1049         Returns:
1050             string_idx such that @LL[string_idx] is equal to our target (i.e.
1051             matched) string, if this line matches the "prefer paren wrap" statement
1052             requirements listed in the 'Requirements' section of the StringParenWrapper
1053             class's docstring.
1054                 OR
1055             None, otherwise.
1056         """
1057         # The line must start with a string.
1058         if LL[0].type != token.STRING:
1059             return None
1060
1061         matching_nodes = [
1062             syms.listmaker,
1063             syms.dictsetmaker,
1064             syms.testlist_gexp,
1065         ]
1066         # If the string is an immediate child of a list/set/tuple literal...
1067         if (
1068             parent_type(LL[0]) in matching_nodes
1069             or parent_type(LL[0].parent) in matching_nodes
1070         ):
1071             # And the string is surrounded by commas (or is the first/last child)...
1072             prev_sibling = LL[0].prev_sibling
1073             next_sibling = LL[0].next_sibling
1074             if (
1075                 not prev_sibling
1076                 and not next_sibling
1077                 and parent_type(LL[0]) == syms.atom
1078             ):
1079                 # If it's an atom string, we need to check the parent atom's siblings.
1080                 parent = LL[0].parent
1081                 assert parent is not None  # For type checkers.
1082                 prev_sibling = parent.prev_sibling
1083                 next_sibling = parent.next_sibling
1084             if (not prev_sibling or prev_sibling.type == token.COMMA) and (
1085                 not next_sibling or next_sibling.type == token.COMMA
1086             ):
1087                 return 0
1088
1089         return None
1090
1091
1092 def iter_fexpr_spans(s: str) -> Iterator[Tuple[int, int]]:
1093     """
1094     Yields spans corresponding to expressions in a given f-string.
1095     Spans are half-open ranges (left inclusive, right exclusive).
1096     Assumes the input string is a valid f-string, but will not crash if the input
1097     string is invalid.
1098     """
1099     stack: List[int] = []  # our curly paren stack
1100     i = 0
1101     while i < len(s):
1102         if s[i] == "{":
1103             # if we're in a string part of the f-string, ignore escaped curly braces
1104             if not stack and i + 1 < len(s) and s[i + 1] == "{":
1105                 i += 2
1106                 continue
1107             stack.append(i)
1108             i += 1
1109             continue
1110
1111         if s[i] == "}":
1112             if not stack:
1113                 i += 1
1114                 continue
1115             j = stack.pop()
1116             # we've made it back out of the expression! yield the span
1117             if not stack:
1118                 yield (j, i + 1)
1119             i += 1
1120             continue
1121
1122         # if we're in an expression part of the f-string, fast forward through strings
1123         # note that backslashes are not legal in the expression portion of f-strings
1124         if stack:
1125             delim = None
1126             if s[i : i + 3] in ("'''", '"""'):
1127                 delim = s[i : i + 3]
1128             elif s[i] in ("'", '"'):
1129                 delim = s[i]
1130             if delim:
1131                 i += len(delim)
1132                 while i < len(s) and s[i : i + len(delim)] != delim:
1133                     i += 1
1134                 i += len(delim)
1135                 continue
1136         i += 1
1137
1138
1139 def fstring_contains_expr(s: str) -> bool:
1140     return any(iter_fexpr_spans(s))
1141
1142
1143 class StringSplitter(BaseStringSplitter, CustomSplitMapMixin):
1144     """
1145     StringTransformer that splits "atom" strings (i.e. strings which exist on
1146     lines by themselves).
1147
1148     Requirements:
1149         * The line consists ONLY of a single string (possibly prefixed by a
1150         string operator [e.g. '+' or '==']), MAYBE a string trailer, and MAYBE
1151         a trailing comma.
1152             AND
1153         * All of the requirements listed in BaseStringSplitter's docstring.
1154
1155     Transformations:
1156         The string mentioned in the 'Requirements' section is split into as
1157         many substrings as necessary to adhere to the configured line length.
1158
1159         In the final set of substrings, no substring should be smaller than
1160         MIN_SUBSTR_SIZE characters.
1161
1162         The string will ONLY be split on spaces (i.e. each new substring should
1163         start with a space). Note that the string will NOT be split on a space
1164         which is escaped with a backslash.
1165
1166         If the string is an f-string, it will NOT be split in the middle of an
1167         f-expression (e.g. in f"FooBar: {foo() if x else bar()}", {foo() if x
1168         else bar()} is an f-expression).
1169
1170         If the string that is being split has an associated set of custom split
1171         records and those custom splits will NOT result in any line going over
1172         the configured line length, those custom splits are used. Otherwise the
1173         string is split as late as possible (from left-to-right) while still
1174         adhering to the transformation rules listed above.
1175
1176     Collaborations:
1177         StringSplitter relies on StringMerger to construct the appropriate
1178         CustomSplit objects and add them to the custom split map.
1179     """
1180
1181     MIN_SUBSTR_SIZE: Final = 6
1182
1183     def do_splitter_match(self, line: Line) -> TMatchResult:
1184         LL = line.leaves
1185
1186         if self._prefer_paren_wrap_match(LL) is not None:
1187             return TErr("Line needs to be wrapped in parens first.")
1188
1189         is_valid_index = is_valid_index_factory(LL)
1190
1191         idx = 0
1192
1193         # The first two leaves MAY be the 'not in' keywords...
1194         if (
1195             is_valid_index(idx)
1196             and is_valid_index(idx + 1)
1197             and [LL[idx].type, LL[idx + 1].type] == [token.NAME, token.NAME]
1198             and str(LL[idx]) + str(LL[idx + 1]) == "not in"
1199         ):
1200             idx += 2
1201         # Else the first leaf MAY be a string operator symbol or the 'in' keyword...
1202         elif is_valid_index(idx) and (
1203             LL[idx].type in self.STRING_OPERATORS
1204             or LL[idx].type == token.NAME
1205             and str(LL[idx]) == "in"
1206         ):
1207             idx += 1
1208
1209         # The next/first leaf MAY be an empty LPAR...
1210         if is_valid_index(idx) and is_empty_lpar(LL[idx]):
1211             idx += 1
1212
1213         # The next/first leaf MUST be a string...
1214         if not is_valid_index(idx) or LL[idx].type != token.STRING:
1215             return TErr("Line does not start with a string.")
1216
1217         string_idx = idx
1218
1219         # Skip the string trailer, if one exists.
1220         string_parser = StringParser()
1221         idx = string_parser.parse(LL, string_idx)
1222
1223         # That string MAY be followed by an empty RPAR...
1224         if is_valid_index(idx) and is_empty_rpar(LL[idx]):
1225             idx += 1
1226
1227         # That string / empty RPAR leaf MAY be followed by a comma...
1228         if is_valid_index(idx) and LL[idx].type == token.COMMA:
1229             idx += 1
1230
1231         # But no more leaves are allowed...
1232         if is_valid_index(idx):
1233             return TErr("This line does not end with a string.")
1234
1235         return Ok(string_idx)
1236
1237     def do_transform(self, line: Line, string_idx: int) -> Iterator[TResult[Line]]:
1238         LL = line.leaves
1239
1240         QUOTE = LL[string_idx].value[-1]
1241
1242         is_valid_index = is_valid_index_factory(LL)
1243         insert_str_child = insert_str_child_factory(LL[string_idx])
1244
1245         prefix = get_string_prefix(LL[string_idx].value).lower()
1246
1247         # We MAY choose to drop the 'f' prefix from substrings that don't
1248         # contain any f-expressions, but ONLY if the original f-string
1249         # contains at least one f-expression. Otherwise, we will alter the AST
1250         # of the program.
1251         drop_pointless_f_prefix = ("f" in prefix) and fstring_contains_expr(
1252             LL[string_idx].value
1253         )
1254
1255         first_string_line = True
1256
1257         string_op_leaves = self._get_string_operator_leaves(LL)
1258         string_op_leaves_length = (
1259             sum([len(str(prefix_leaf)) for prefix_leaf in string_op_leaves]) + 1
1260             if string_op_leaves
1261             else 0
1262         )
1263
1264         def maybe_append_string_operators(new_line: Line) -> None:
1265             """
1266             Side Effects:
1267                 If @line starts with a string operator and this is the first
1268                 line we are constructing, this function appends the string
1269                 operator to @new_line and replaces the old string operator leaf
1270                 in the node structure. Otherwise this function does nothing.
1271             """
1272             maybe_prefix_leaves = string_op_leaves if first_string_line else []
1273             for i, prefix_leaf in enumerate(maybe_prefix_leaves):
1274                 replace_child(LL[i], prefix_leaf)
1275                 new_line.append(prefix_leaf)
1276
1277         ends_with_comma = (
1278             is_valid_index(string_idx + 1) and LL[string_idx + 1].type == token.COMMA
1279         )
1280
1281         def max_last_string() -> int:
1282             """
1283             Returns:
1284                 The max allowed length of the string value used for the last
1285                 line we will construct.
1286             """
1287             result = self.line_length
1288             result -= line.depth * 4
1289             result -= 1 if ends_with_comma else 0
1290             result -= string_op_leaves_length
1291             return result
1292
1293         # --- Calculate Max Break Index (for string value)
1294         # We start with the line length limit
1295         max_break_idx = self.line_length
1296         # The last index of a string of length N is N-1.
1297         max_break_idx -= 1
1298         # Leading whitespace is not present in the string value (e.g. Leaf.value).
1299         max_break_idx -= line.depth * 4
1300         if max_break_idx < 0:
1301             yield TErr(
1302                 f"Unable to split {LL[string_idx].value} at such high of a line depth:"
1303                 f" {line.depth}"
1304             )
1305             return
1306
1307         # Check if StringMerger registered any custom splits.
1308         custom_splits = self.pop_custom_splits(LL[string_idx].value)
1309         # We use them ONLY if none of them would produce lines that exceed the
1310         # line limit.
1311         use_custom_breakpoints = bool(
1312             custom_splits
1313             and all(csplit.break_idx <= max_break_idx for csplit in custom_splits)
1314         )
1315
1316         # Temporary storage for the remaining chunk of the string line that
1317         # can't fit onto the line currently being constructed.
1318         rest_value = LL[string_idx].value
1319
1320         def more_splits_should_be_made() -> bool:
1321             """
1322             Returns:
1323                 True iff `rest_value` (the remaining string value from the last
1324                 split), should be split again.
1325             """
1326             if use_custom_breakpoints:
1327                 return len(custom_splits) > 1
1328             else:
1329                 return len(rest_value) > max_last_string()
1330
1331         string_line_results: List[Ok[Line]] = []
1332         while more_splits_should_be_made():
1333             if use_custom_breakpoints:
1334                 # Custom User Split (manual)
1335                 csplit = custom_splits.pop(0)
1336                 break_idx = csplit.break_idx
1337             else:
1338                 # Algorithmic Split (automatic)
1339                 max_bidx = max_break_idx - string_op_leaves_length
1340                 maybe_break_idx = self._get_break_idx(rest_value, max_bidx)
1341                 if maybe_break_idx is None:
1342                     # If we are unable to algorithmically determine a good split
1343                     # and this string has custom splits registered to it, we
1344                     # fall back to using them--which means we have to start
1345                     # over from the beginning.
1346                     if custom_splits:
1347                         rest_value = LL[string_idx].value
1348                         string_line_results = []
1349                         first_string_line = True
1350                         use_custom_breakpoints = True
1351                         continue
1352
1353                     # Otherwise, we stop splitting here.
1354                     break
1355
1356                 break_idx = maybe_break_idx
1357
1358             # --- Construct `next_value`
1359             next_value = rest_value[:break_idx] + QUOTE
1360
1361             # HACK: The following 'if' statement is a hack to fix the custom
1362             # breakpoint index in the case of either: (a) substrings that were
1363             # f-strings but will have the 'f' prefix removed OR (b) substrings
1364             # that were not f-strings but will now become f-strings because of
1365             # redundant use of the 'f' prefix (i.e. none of the substrings
1366             # contain f-expressions but one or more of them had the 'f' prefix
1367             # anyway; in which case, we will prepend 'f' to _all_ substrings).
1368             #
1369             # There is probably a better way to accomplish what is being done
1370             # here...
1371             #
1372             # If this substring is an f-string, we _could_ remove the 'f'
1373             # prefix, and the current custom split did NOT originally use a
1374             # prefix...
1375             if (
1376                 next_value != self._normalize_f_string(next_value, prefix)
1377                 and use_custom_breakpoints
1378                 and not csplit.has_prefix
1379             ):
1380                 # Then `csplit.break_idx` will be off by one after removing
1381                 # the 'f' prefix.
1382                 break_idx += 1
1383                 next_value = rest_value[:break_idx] + QUOTE
1384
1385             if drop_pointless_f_prefix:
1386                 next_value = self._normalize_f_string(next_value, prefix)
1387
1388             # --- Construct `next_leaf`
1389             next_leaf = Leaf(token.STRING, next_value)
1390             insert_str_child(next_leaf)
1391             self._maybe_normalize_string_quotes(next_leaf)
1392
1393             # --- Construct `next_line`
1394             next_line = line.clone()
1395             maybe_append_string_operators(next_line)
1396             next_line.append(next_leaf)
1397             string_line_results.append(Ok(next_line))
1398
1399             rest_value = prefix + QUOTE + rest_value[break_idx:]
1400             first_string_line = False
1401
1402         yield from string_line_results
1403
1404         if drop_pointless_f_prefix:
1405             rest_value = self._normalize_f_string(rest_value, prefix)
1406
1407         rest_leaf = Leaf(token.STRING, rest_value)
1408         insert_str_child(rest_leaf)
1409
1410         # NOTE: I could not find a test case that verifies that the following
1411         # line is actually necessary, but it seems to be. Otherwise we risk
1412         # not normalizing the last substring, right?
1413         self._maybe_normalize_string_quotes(rest_leaf)
1414
1415         last_line = line.clone()
1416         maybe_append_string_operators(last_line)
1417
1418         # If there are any leaves to the right of the target string...
1419         if is_valid_index(string_idx + 1):
1420             # We use `temp_value` here to determine how long the last line
1421             # would be if we were to append all the leaves to the right of the
1422             # target string to the last string line.
1423             temp_value = rest_value
1424             for leaf in LL[string_idx + 1 :]:
1425                 temp_value += str(leaf)
1426                 if leaf.type == token.LPAR:
1427                     break
1428
1429             # Try to fit them all on the same line with the last substring...
1430             if (
1431                 len(temp_value) <= max_last_string()
1432                 or LL[string_idx + 1].type == token.COMMA
1433             ):
1434                 last_line.append(rest_leaf)
1435                 append_leaves(last_line, line, LL[string_idx + 1 :])
1436                 yield Ok(last_line)
1437             # Otherwise, place the last substring on one line and everything
1438             # else on a line below that...
1439             else:
1440                 last_line.append(rest_leaf)
1441                 yield Ok(last_line)
1442
1443                 non_string_line = line.clone()
1444                 append_leaves(non_string_line, line, LL[string_idx + 1 :])
1445                 yield Ok(non_string_line)
1446         # Else the target string was the last leaf...
1447         else:
1448             last_line.append(rest_leaf)
1449             last_line.comments = line.comments.copy()
1450             yield Ok(last_line)
1451
1452     def _iter_nameescape_slices(self, string: str) -> Iterator[Tuple[Index, Index]]:
1453         """
1454         Yields:
1455             All ranges of @string which, if @string were to be split there,
1456             would result in the splitting of an \\N{...} expression (which is NOT
1457             allowed).
1458         """
1459         # True - the previous backslash was unescaped
1460         # False - the previous backslash was escaped *or* there was no backslash
1461         previous_was_unescaped_backslash = False
1462         it = iter(enumerate(string))
1463         for idx, c in it:
1464             if c == "\\":
1465                 previous_was_unescaped_backslash = not previous_was_unescaped_backslash
1466                 continue
1467             if not previous_was_unescaped_backslash or c != "N":
1468                 previous_was_unescaped_backslash = False
1469                 continue
1470             previous_was_unescaped_backslash = False
1471
1472             begin = idx - 1  # the position of backslash before \N{...}
1473             for idx, c in it:
1474                 if c == "}":
1475                     end = idx
1476                     break
1477             else:
1478                 # malformed nameescape expression?
1479                 # should have been detected by AST parsing earlier...
1480                 raise RuntimeError(f"{self.__class__.__name__} LOGIC ERROR!")
1481             yield begin, end
1482
1483     def _iter_fexpr_slices(self, string: str) -> Iterator[Tuple[Index, Index]]:
1484         """
1485         Yields:
1486             All ranges of @string which, if @string were to be split there,
1487             would result in the splitting of an f-expression (which is NOT
1488             allowed).
1489         """
1490         if "f" not in get_string_prefix(string).lower():
1491             return
1492         yield from iter_fexpr_spans(string)
1493
1494     def _get_illegal_split_indices(self, string: str) -> Set[Index]:
1495         illegal_indices: Set[Index] = set()
1496         iterators = [
1497             self._iter_fexpr_slices(string),
1498             self._iter_nameescape_slices(string),
1499         ]
1500         for it in iterators:
1501             for begin, end in it:
1502                 illegal_indices.update(range(begin, end + 1))
1503         return illegal_indices
1504
1505     def _get_break_idx(self, string: str, max_break_idx: int) -> Optional[int]:
1506         """
1507         This method contains the algorithm that StringSplitter uses to
1508         determine which character to split each string at.
1509
1510         Args:
1511             @string: The substring that we are attempting to split.
1512             @max_break_idx: The ideal break index. We will return this value if it
1513             meets all the necessary conditions. In the likely event that it
1514             doesn't we will try to find the closest index BELOW @max_break_idx
1515             that does. If that fails, we will expand our search by also
1516             considering all valid indices ABOVE @max_break_idx.
1517
1518         Pre-Conditions:
1519             * assert_is_leaf_string(@string)
1520             * 0 <= @max_break_idx < len(@string)
1521
1522         Returns:
1523             break_idx, if an index is able to be found that meets all of the
1524             conditions listed in the 'Transformations' section of this classes'
1525             docstring.
1526                 OR
1527             None, otherwise.
1528         """
1529         is_valid_index = is_valid_index_factory(string)
1530
1531         assert is_valid_index(max_break_idx)
1532         assert_is_leaf_string(string)
1533
1534         _illegal_split_indices = self._get_illegal_split_indices(string)
1535
1536         def breaks_unsplittable_expression(i: Index) -> bool:
1537             """
1538             Returns:
1539                 True iff returning @i would result in the splitting of an
1540                 unsplittable expression (which is NOT allowed).
1541             """
1542             return i in _illegal_split_indices
1543
1544         def passes_all_checks(i: Index) -> bool:
1545             """
1546             Returns:
1547                 True iff ALL of the conditions listed in the 'Transformations'
1548                 section of this classes' docstring would be be met by returning @i.
1549             """
1550             is_space = string[i] == " "
1551
1552             is_not_escaped = True
1553             j = i - 1
1554             while is_valid_index(j) and string[j] == "\\":
1555                 is_not_escaped = not is_not_escaped
1556                 j -= 1
1557
1558             is_big_enough = (
1559                 len(string[i:]) >= self.MIN_SUBSTR_SIZE
1560                 and len(string[:i]) >= self.MIN_SUBSTR_SIZE
1561             )
1562             return (
1563                 is_space
1564                 and is_not_escaped
1565                 and is_big_enough
1566                 and not breaks_unsplittable_expression(i)
1567             )
1568
1569         # First, we check all indices BELOW @max_break_idx.
1570         break_idx = max_break_idx
1571         while is_valid_index(break_idx - 1) and not passes_all_checks(break_idx):
1572             break_idx -= 1
1573
1574         if not passes_all_checks(break_idx):
1575             # If that fails, we check all indices ABOVE @max_break_idx.
1576             #
1577             # If we are able to find a valid index here, the next line is going
1578             # to be longer than the specified line length, but it's probably
1579             # better than doing nothing at all.
1580             break_idx = max_break_idx + 1
1581             while is_valid_index(break_idx + 1) and not passes_all_checks(break_idx):
1582                 break_idx += 1
1583
1584             if not is_valid_index(break_idx) or not passes_all_checks(break_idx):
1585                 return None
1586
1587         return break_idx
1588
1589     def _maybe_normalize_string_quotes(self, leaf: Leaf) -> None:
1590         if self.normalize_strings:
1591             leaf.value = normalize_string_quotes(leaf.value)
1592
1593     def _normalize_f_string(self, string: str, prefix: str) -> str:
1594         """
1595         Pre-Conditions:
1596             * assert_is_leaf_string(@string)
1597
1598         Returns:
1599             * If @string is an f-string that contains no f-expressions, we
1600             return a string identical to @string except that the 'f' prefix
1601             has been stripped and all double braces (i.e. '{{' or '}}') have
1602             been normalized (i.e. turned into '{' or '}').
1603                 OR
1604             * Otherwise, we return @string.
1605         """
1606         assert_is_leaf_string(string)
1607
1608         if "f" in prefix and not fstring_contains_expr(string):
1609             new_prefix = prefix.replace("f", "")
1610
1611             temp = string[len(prefix) :]
1612             temp = re.sub(r"\{\{", "{", temp)
1613             temp = re.sub(r"\}\}", "}", temp)
1614             new_string = temp
1615
1616             return f"{new_prefix}{new_string}"
1617         else:
1618             return string
1619
1620     def _get_string_operator_leaves(self, leaves: Iterable[Leaf]) -> List[Leaf]:
1621         LL = list(leaves)
1622
1623         string_op_leaves = []
1624         i = 0
1625         while LL[i].type in self.STRING_OPERATORS + [token.NAME]:
1626             prefix_leaf = Leaf(LL[i].type, str(LL[i]).strip())
1627             string_op_leaves.append(prefix_leaf)
1628             i += 1
1629         return string_op_leaves
1630
1631
1632 class StringParenWrapper(BaseStringSplitter, CustomSplitMapMixin):
1633     """
1634     StringTransformer that wraps strings in parens and then splits at the LPAR.
1635
1636     Requirements:
1637         All of the requirements listed in BaseStringSplitter's docstring in
1638         addition to the requirements listed below:
1639
1640         * The line is a return/yield statement, which returns/yields a string.
1641             OR
1642         * The line is part of a ternary expression (e.g. `x = y if cond else
1643         z`) such that the line starts with `else <string>`, where <string> is
1644         some string.
1645             OR
1646         * The line is an assert statement, which ends with a string.
1647             OR
1648         * The line is an assignment statement (e.g. `x = <string>` or `x +=
1649         <string>`) such that the variable is being assigned the value of some
1650         string.
1651             OR
1652         * The line is a dictionary key assignment where some valid key is being
1653         assigned the value of some string.
1654             OR
1655         * The line starts with an "atom" string that prefers to be wrapped in
1656         parens. It's preferred to be wrapped when it's is an immediate child of
1657         a list/set/tuple literal, AND the string is surrounded by commas (or is
1658         the first/last child).
1659
1660     Transformations:
1661         The chosen string is wrapped in parentheses and then split at the LPAR.
1662
1663         We then have one line which ends with an LPAR and another line that
1664         starts with the chosen string. The latter line is then split again at
1665         the RPAR. This results in the RPAR (and possibly a trailing comma)
1666         being placed on its own line.
1667
1668         NOTE: If any leaves exist to the right of the chosen string (except
1669         for a trailing comma, which would be placed after the RPAR), those
1670         leaves are placed inside the parentheses.  In effect, the chosen
1671         string is not necessarily being "wrapped" by parentheses. We can,
1672         however, count on the LPAR being placed directly before the chosen
1673         string.
1674
1675         In other words, StringParenWrapper creates "atom" strings. These
1676         can then be split again by StringSplitter, if necessary.
1677
1678     Collaborations:
1679         In the event that a string line split by StringParenWrapper is
1680         changed such that it no longer needs to be given its own line,
1681         StringParenWrapper relies on StringParenStripper to clean up the
1682         parentheses it created.
1683
1684         For "atom" strings that prefers to be wrapped in parens, it requires
1685         StringSplitter to hold the split until the string is wrapped in parens.
1686     """
1687
1688     def do_splitter_match(self, line: Line) -> TMatchResult:
1689         LL = line.leaves
1690
1691         if line.leaves[-1].type in OPENING_BRACKETS:
1692             return TErr(
1693                 "Cannot wrap parens around a line that ends in an opening bracket."
1694             )
1695
1696         string_idx = (
1697             self._return_match(LL)
1698             or self._else_match(LL)
1699             or self._assert_match(LL)
1700             or self._assign_match(LL)
1701             or self._dict_match(LL)
1702             or self._prefer_paren_wrap_match(LL)
1703         )
1704
1705         if string_idx is not None:
1706             string_value = line.leaves[string_idx].value
1707             # If the string has no spaces...
1708             if " " not in string_value:
1709                 # And will still violate the line length limit when split...
1710                 max_string_length = self.line_length - ((line.depth + 1) * 4)
1711                 if len(string_value) > max_string_length:
1712                     # And has no associated custom splits...
1713                     if not self.has_custom_splits(string_value):
1714                         # Then we should NOT put this string on its own line.
1715                         return TErr(
1716                             "We do not wrap long strings in parentheses when the"
1717                             " resultant line would still be over the specified line"
1718                             " length and can't be split further by StringSplitter."
1719                         )
1720             return Ok(string_idx)
1721
1722         return TErr("This line does not contain any non-atomic strings.")
1723
1724     @staticmethod
1725     def _return_match(LL: List[Leaf]) -> Optional[int]:
1726         """
1727         Returns:
1728             string_idx such that @LL[string_idx] is equal to our target (i.e.
1729             matched) string, if this line matches the return/yield statement
1730             requirements listed in the 'Requirements' section of this classes'
1731             docstring.
1732                 OR
1733             None, otherwise.
1734         """
1735         # If this line is apart of a return/yield statement and the first leaf
1736         # contains either the "return" or "yield" keywords...
1737         if parent_type(LL[0]) in [syms.return_stmt, syms.yield_expr] and LL[
1738             0
1739         ].value in ["return", "yield"]:
1740             is_valid_index = is_valid_index_factory(LL)
1741
1742             idx = 2 if is_valid_index(1) and is_empty_par(LL[1]) else 1
1743             # The next visible leaf MUST contain a string...
1744             if is_valid_index(idx) and LL[idx].type == token.STRING:
1745                 return idx
1746
1747         return None
1748
1749     @staticmethod
1750     def _else_match(LL: List[Leaf]) -> Optional[int]:
1751         """
1752         Returns:
1753             string_idx such that @LL[string_idx] is equal to our target (i.e.
1754             matched) string, if this line matches the ternary expression
1755             requirements listed in the 'Requirements' section of this classes'
1756             docstring.
1757                 OR
1758             None, otherwise.
1759         """
1760         # If this line is apart of a ternary expression and the first leaf
1761         # contains the "else" keyword...
1762         if (
1763             parent_type(LL[0]) == syms.test
1764             and LL[0].type == token.NAME
1765             and LL[0].value == "else"
1766         ):
1767             is_valid_index = is_valid_index_factory(LL)
1768
1769             idx = 2 if is_valid_index(1) and is_empty_par(LL[1]) else 1
1770             # The next visible leaf MUST contain a string...
1771             if is_valid_index(idx) and LL[idx].type == token.STRING:
1772                 return idx
1773
1774         return None
1775
1776     @staticmethod
1777     def _assert_match(LL: List[Leaf]) -> Optional[int]:
1778         """
1779         Returns:
1780             string_idx such that @LL[string_idx] is equal to our target (i.e.
1781             matched) string, if this line matches the assert statement
1782             requirements listed in the 'Requirements' section of this classes'
1783             docstring.
1784                 OR
1785             None, otherwise.
1786         """
1787         # If this line is apart of an assert statement and the first leaf
1788         # contains the "assert" keyword...
1789         if parent_type(LL[0]) == syms.assert_stmt and LL[0].value == "assert":
1790             is_valid_index = is_valid_index_factory(LL)
1791
1792             for i, leaf in enumerate(LL):
1793                 # We MUST find a comma...
1794                 if leaf.type == token.COMMA:
1795                     idx = i + 2 if is_empty_par(LL[i + 1]) else i + 1
1796
1797                     # That comma MUST be followed by a string...
1798                     if is_valid_index(idx) and LL[idx].type == token.STRING:
1799                         string_idx = idx
1800
1801                         # Skip the string trailer, if one exists.
1802                         string_parser = StringParser()
1803                         idx = string_parser.parse(LL, string_idx)
1804
1805                         # But no more leaves are allowed...
1806                         if not is_valid_index(idx):
1807                             return string_idx
1808
1809         return None
1810
1811     @staticmethod
1812     def _assign_match(LL: List[Leaf]) -> Optional[int]:
1813         """
1814         Returns:
1815             string_idx such that @LL[string_idx] is equal to our target (i.e.
1816             matched) string, if this line matches the assignment statement
1817             requirements listed in the 'Requirements' section of this classes'
1818             docstring.
1819                 OR
1820             None, otherwise.
1821         """
1822         # If this line is apart of an expression statement or is a function
1823         # argument AND the first leaf contains a variable name...
1824         if (
1825             parent_type(LL[0]) in [syms.expr_stmt, syms.argument, syms.power]
1826             and LL[0].type == token.NAME
1827         ):
1828             is_valid_index = is_valid_index_factory(LL)
1829
1830             for i, leaf in enumerate(LL):
1831                 # We MUST find either an '=' or '+=' symbol...
1832                 if leaf.type in [token.EQUAL, token.PLUSEQUAL]:
1833                     idx = i + 2 if is_empty_par(LL[i + 1]) else i + 1
1834
1835                     # That symbol MUST be followed by a string...
1836                     if is_valid_index(idx) and LL[idx].type == token.STRING:
1837                         string_idx = idx
1838
1839                         # Skip the string trailer, if one exists.
1840                         string_parser = StringParser()
1841                         idx = string_parser.parse(LL, string_idx)
1842
1843                         # The next leaf MAY be a comma iff this line is apart
1844                         # of a function argument...
1845                         if (
1846                             parent_type(LL[0]) == syms.argument
1847                             and is_valid_index(idx)
1848                             and LL[idx].type == token.COMMA
1849                         ):
1850                             idx += 1
1851
1852                         # But no more leaves are allowed...
1853                         if not is_valid_index(idx):
1854                             return string_idx
1855
1856         return None
1857
1858     @staticmethod
1859     def _dict_match(LL: List[Leaf]) -> Optional[int]:
1860         """
1861         Returns:
1862             string_idx such that @LL[string_idx] is equal to our target (i.e.
1863             matched) string, if this line matches the dictionary key assignment
1864             statement requirements listed in the 'Requirements' section of this
1865             classes' docstring.
1866                 OR
1867             None, otherwise.
1868         """
1869         # If this line is apart of a dictionary key assignment...
1870         if syms.dictsetmaker in [parent_type(LL[0]), parent_type(LL[0].parent)]:
1871             is_valid_index = is_valid_index_factory(LL)
1872
1873             for i, leaf in enumerate(LL):
1874                 # We MUST find a colon...
1875                 if leaf.type == token.COLON:
1876                     idx = i + 2 if is_empty_par(LL[i + 1]) else i + 1
1877
1878                     # That colon MUST be followed by a string...
1879                     if is_valid_index(idx) and LL[idx].type == token.STRING:
1880                         string_idx = idx
1881
1882                         # Skip the string trailer, if one exists.
1883                         string_parser = StringParser()
1884                         idx = string_parser.parse(LL, string_idx)
1885
1886                         # That string MAY be followed by a comma...
1887                         if is_valid_index(idx) and LL[idx].type == token.COMMA:
1888                             idx += 1
1889
1890                         # But no more leaves are allowed...
1891                         if not is_valid_index(idx):
1892                             return string_idx
1893
1894         return None
1895
1896     def do_transform(self, line: Line, string_idx: int) -> Iterator[TResult[Line]]:
1897         LL = line.leaves
1898
1899         is_valid_index = is_valid_index_factory(LL)
1900         insert_str_child = insert_str_child_factory(LL[string_idx])
1901
1902         comma_idx = -1
1903         ends_with_comma = False
1904         if LL[comma_idx].type == token.COMMA:
1905             ends_with_comma = True
1906
1907         leaves_to_steal_comments_from = [LL[string_idx]]
1908         if ends_with_comma:
1909             leaves_to_steal_comments_from.append(LL[comma_idx])
1910
1911         # --- First Line
1912         first_line = line.clone()
1913         left_leaves = LL[:string_idx]
1914
1915         # We have to remember to account for (possibly invisible) LPAR and RPAR
1916         # leaves that already wrapped the target string. If these leaves do
1917         # exist, we will replace them with our own LPAR and RPAR leaves.
1918         old_parens_exist = False
1919         if left_leaves and left_leaves[-1].type == token.LPAR:
1920             old_parens_exist = True
1921             leaves_to_steal_comments_from.append(left_leaves[-1])
1922             left_leaves.pop()
1923
1924         append_leaves(first_line, line, left_leaves)
1925
1926         lpar_leaf = Leaf(token.LPAR, "(")
1927         if old_parens_exist:
1928             replace_child(LL[string_idx - 1], lpar_leaf)
1929         else:
1930             insert_str_child(lpar_leaf)
1931         first_line.append(lpar_leaf)
1932
1933         # We throw inline comments that were originally to the right of the
1934         # target string to the top line. They will now be shown to the right of
1935         # the LPAR.
1936         for leaf in leaves_to_steal_comments_from:
1937             for comment_leaf in line.comments_after(leaf):
1938                 first_line.append(comment_leaf, preformatted=True)
1939
1940         yield Ok(first_line)
1941
1942         # --- Middle (String) Line
1943         # We only need to yield one (possibly too long) string line, since the
1944         # `StringSplitter` will break it down further if necessary.
1945         string_value = LL[string_idx].value
1946         string_line = Line(
1947             mode=line.mode,
1948             depth=line.depth + 1,
1949             inside_brackets=True,
1950             should_split_rhs=line.should_split_rhs,
1951             magic_trailing_comma=line.magic_trailing_comma,
1952         )
1953         string_leaf = Leaf(token.STRING, string_value)
1954         insert_str_child(string_leaf)
1955         string_line.append(string_leaf)
1956
1957         old_rpar_leaf = None
1958         if is_valid_index(string_idx + 1):
1959             right_leaves = LL[string_idx + 1 :]
1960             if ends_with_comma:
1961                 right_leaves.pop()
1962
1963             if old_parens_exist:
1964                 assert right_leaves and right_leaves[-1].type == token.RPAR, (
1965                     "Apparently, old parentheses do NOT exist?!"
1966                     f" (left_leaves={left_leaves}, right_leaves={right_leaves})"
1967                 )
1968                 old_rpar_leaf = right_leaves.pop()
1969
1970             append_leaves(string_line, line, right_leaves)
1971
1972         yield Ok(string_line)
1973
1974         # --- Last Line
1975         last_line = line.clone()
1976         last_line.bracket_tracker = first_line.bracket_tracker
1977
1978         new_rpar_leaf = Leaf(token.RPAR, ")")
1979         if old_rpar_leaf is not None:
1980             replace_child(old_rpar_leaf, new_rpar_leaf)
1981         else:
1982             insert_str_child(new_rpar_leaf)
1983         last_line.append(new_rpar_leaf)
1984
1985         # If the target string ended with a comma, we place this comma to the
1986         # right of the RPAR on the last line.
1987         if ends_with_comma:
1988             comma_leaf = Leaf(token.COMMA, ",")
1989             replace_child(LL[comma_idx], comma_leaf)
1990             last_line.append(comma_leaf)
1991
1992         yield Ok(last_line)
1993
1994
1995 class StringParser:
1996     """
1997     A state machine that aids in parsing a string's "trailer", which can be
1998     either non-existent, an old-style formatting sequence (e.g. `% varX` or `%
1999     (varX, varY)`), or a method-call / attribute access (e.g. `.format(varX,
2000     varY)`).
2001
2002     NOTE: A new StringParser object MUST be instantiated for each string
2003     trailer we need to parse.
2004
2005     Examples:
2006         We shall assume that `line` equals the `Line` object that corresponds
2007         to the following line of python code:
2008         ```
2009         x = "Some {}.".format("String") + some_other_string
2010         ```
2011
2012         Furthermore, we will assume that `string_idx` is some index such that:
2013         ```
2014         assert line.leaves[string_idx].value == "Some {}."
2015         ```
2016
2017         The following code snippet then holds:
2018         ```
2019         string_parser = StringParser()
2020         idx = string_parser.parse(line.leaves, string_idx)
2021         assert line.leaves[idx].type == token.PLUS
2022         ```
2023     """
2024
2025     DEFAULT_TOKEN: Final = 20210605
2026
2027     # String Parser States
2028     START: Final = 1
2029     DOT: Final = 2
2030     NAME: Final = 3
2031     PERCENT: Final = 4
2032     SINGLE_FMT_ARG: Final = 5
2033     LPAR: Final = 6
2034     RPAR: Final = 7
2035     DONE: Final = 8
2036
2037     # Lookup Table for Next State
2038     _goto: Final[Dict[Tuple[ParserState, NodeType], ParserState]] = {
2039         # A string trailer may start with '.' OR '%'.
2040         (START, token.DOT): DOT,
2041         (START, token.PERCENT): PERCENT,
2042         (START, DEFAULT_TOKEN): DONE,
2043         # A '.' MUST be followed by an attribute or method name.
2044         (DOT, token.NAME): NAME,
2045         # A method name MUST be followed by an '(', whereas an attribute name
2046         # is the last symbol in the string trailer.
2047         (NAME, token.LPAR): LPAR,
2048         (NAME, DEFAULT_TOKEN): DONE,
2049         # A '%' symbol can be followed by an '(' or a single argument (e.g. a
2050         # string or variable name).
2051         (PERCENT, token.LPAR): LPAR,
2052         (PERCENT, DEFAULT_TOKEN): SINGLE_FMT_ARG,
2053         # If a '%' symbol is followed by a single argument, that argument is
2054         # the last leaf in the string trailer.
2055         (SINGLE_FMT_ARG, DEFAULT_TOKEN): DONE,
2056         # If present, a ')' symbol is the last symbol in a string trailer.
2057         # (NOTE: LPARS and nested RPARS are not included in this lookup table,
2058         # since they are treated as a special case by the parsing logic in this
2059         # classes' implementation.)
2060         (RPAR, DEFAULT_TOKEN): DONE,
2061     }
2062
2063     def __init__(self) -> None:
2064         self._state = self.START
2065         self._unmatched_lpars = 0
2066
2067     def parse(self, leaves: List[Leaf], string_idx: int) -> int:
2068         """
2069         Pre-conditions:
2070             * @leaves[@string_idx].type == token.STRING
2071
2072         Returns:
2073             The index directly after the last leaf which is apart of the string
2074             trailer, if a "trailer" exists.
2075                 OR
2076             @string_idx + 1, if no string "trailer" exists.
2077         """
2078         assert leaves[string_idx].type == token.STRING
2079
2080         idx = string_idx + 1
2081         while idx < len(leaves) and self._next_state(leaves[idx]):
2082             idx += 1
2083         return idx
2084
2085     def _next_state(self, leaf: Leaf) -> bool:
2086         """
2087         Pre-conditions:
2088             * On the first call to this function, @leaf MUST be the leaf that
2089             was directly after the string leaf in question (e.g. if our target
2090             string is `line.leaves[i]` then the first call to this method must
2091             be `line.leaves[i + 1]`).
2092             * On the next call to this function, the leaf parameter passed in
2093             MUST be the leaf directly following @leaf.
2094
2095         Returns:
2096             True iff @leaf is apart of the string's trailer.
2097         """
2098         # We ignore empty LPAR or RPAR leaves.
2099         if is_empty_par(leaf):
2100             return True
2101
2102         next_token = leaf.type
2103         if next_token == token.LPAR:
2104             self._unmatched_lpars += 1
2105
2106         current_state = self._state
2107
2108         # The LPAR parser state is a special case. We will return True until we
2109         # find the matching RPAR token.
2110         if current_state == self.LPAR:
2111             if next_token == token.RPAR:
2112                 self._unmatched_lpars -= 1
2113                 if self._unmatched_lpars == 0:
2114                     self._state = self.RPAR
2115         # Otherwise, we use a lookup table to determine the next state.
2116         else:
2117             # If the lookup table matches the current state to the next
2118             # token, we use the lookup table.
2119             if (current_state, next_token) in self._goto:
2120                 self._state = self._goto[current_state, next_token]
2121             else:
2122                 # Otherwise, we check if a the current state was assigned a
2123                 # default.
2124                 if (current_state, self.DEFAULT_TOKEN) in self._goto:
2125                     self._state = self._goto[current_state, self.DEFAULT_TOKEN]
2126                 # If no default has been assigned, then this parser has a logic
2127                 # error.
2128                 else:
2129                     raise RuntimeError(f"{self.__class__.__name__} LOGIC ERROR!")
2130
2131             if self._state == self.DONE:
2132                 return False
2133
2134         return True
2135
2136
2137 def insert_str_child_factory(string_leaf: Leaf) -> Callable[[LN], None]:
2138     """
2139     Factory for a convenience function that is used to orphan @string_leaf
2140     and then insert multiple new leaves into the same part of the node
2141     structure that @string_leaf had originally occupied.
2142
2143     Examples:
2144         Let `string_leaf = Leaf(token.STRING, '"foo"')` and `N =
2145         string_leaf.parent`. Assume the node `N` has the following
2146         original structure:
2147
2148         Node(
2149             expr_stmt, [
2150                 Leaf(NAME, 'x'),
2151                 Leaf(EQUAL, '='),
2152                 Leaf(STRING, '"foo"'),
2153             ]
2154         )
2155
2156         We then run the code snippet shown below.
2157         ```
2158         insert_str_child = insert_str_child_factory(string_leaf)
2159
2160         lpar = Leaf(token.LPAR, '(')
2161         insert_str_child(lpar)
2162
2163         bar = Leaf(token.STRING, '"bar"')
2164         insert_str_child(bar)
2165
2166         rpar = Leaf(token.RPAR, ')')
2167         insert_str_child(rpar)
2168         ```
2169
2170         After which point, it follows that `string_leaf.parent is None` and
2171         the node `N` now has the following structure:
2172
2173         Node(
2174             expr_stmt, [
2175                 Leaf(NAME, 'x'),
2176                 Leaf(EQUAL, '='),
2177                 Leaf(LPAR, '('),
2178                 Leaf(STRING, '"bar"'),
2179                 Leaf(RPAR, ')'),
2180             ]
2181         )
2182     """
2183     string_parent = string_leaf.parent
2184     string_child_idx = string_leaf.remove()
2185
2186     def insert_str_child(child: LN) -> None:
2187         nonlocal string_child_idx
2188
2189         assert string_parent is not None
2190         assert string_child_idx is not None
2191
2192         string_parent.insert_child(string_child_idx, child)
2193         string_child_idx += 1
2194
2195     return insert_str_child
2196
2197
2198 def is_valid_index_factory(seq: Sequence[Any]) -> Callable[[int], bool]:
2199     """
2200     Examples:
2201         ```
2202         my_list = [1, 2, 3]
2203
2204         is_valid_index = is_valid_index_factory(my_list)
2205
2206         assert is_valid_index(0)
2207         assert is_valid_index(2)
2208
2209         assert not is_valid_index(3)
2210         assert not is_valid_index(-1)
2211         ```
2212     """
2213
2214     def is_valid_index(idx: int) -> bool:
2215         """
2216         Returns:
2217             True iff @idx is positive AND seq[@idx] does NOT raise an
2218             IndexError.
2219         """
2220         return 0 <= idx < len(seq)
2221
2222     return is_valid_index