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

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