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.
2 String transformers that can split and merge strings.
4 from abc import ABC, abstractmethod
5 from collections import defaultdict
6 from dataclasses import dataclass
24 from black.rusty import Result, Ok, Err
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
36 from blib2to3.pytree import Leaf, Node
37 from blib2to3.pgen2 import token
40 class CannotTransform(Exception):
41 """Base class for errors raised by Transformers."""
46 LN = Union[Leaf, Node]
47 Transformer = Callable[[Line, Collection[Feature]], Iterator[Line]]
52 TResult = Result[T, CannotTransform] # (T)ransform Result
53 TMatchResult = TResult[Index]
56 def TErr(err_msg: str) -> Err[CannotTransform]:
59 Convenience function used when working with the TResult type.
61 cant_transform = CannotTransform(err_msg)
62 return Err(cant_transform)
65 @dataclass # type: ignore
66 class StringTransformer(ABC):
68 An implementation of the Transformer protocol that relies on its
69 subclasses overriding the template methods `do_match(...)` and
72 This Transformer works exclusively on strings (for example, by merging
75 The following sections can be found among the docstrings of each concrete
76 StringTransformer subclass.
79 Which requirements must be met of the given Line for this
80 StringTransformer to be applied?
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
88 What contractual agreements does this StringTransformer have with other
89 StringTransfomers? Such collaborations should be eliminated/minimized
94 normalize_strings: bool
95 __name__ = "StringTransformer"
98 def do_match(self, line: Line) -> TMatchResult:
101 * Ok(string_idx) such that `line.leaves[string_idx]` is our target
102 string, if a match was able to be made.
104 * Err(CannotTransform), if a match was not able to be made.
108 def do_transform(self, line: Line, string_idx: int) -> Iterator[TResult[Line]]:
111 * Ok(new_line) where new_line is the new transformed line.
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.
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.)
126 def __call__(self, line: Line, _features: Collection[Feature]) -> Iterator[Line]:
128 StringTransformer instances have a call signature that mirrors that of
129 the Transformer type.
132 CannotTransform(...) if the concrete StringTransformer class is unable
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.")
140 match_result = self.do_match(line)
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
149 string_idx = match_result.ok()
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()
163 """A custom (i.e. manual) string split.
165 A single CustomSplit instance represents a single substring.
168 Consider the following string:
175 This string will correspond to the following three CustomSplit instances:
177 CustomSplit(False, 16)
178 CustomSplit(False, 17)
179 CustomSplit(True, 16)
187 class CustomSplitMapMixin:
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.
194 _Key = Tuple[StringID, str]
195 _CUSTOM_SPLIT_MAP: Dict[_Key, Tuple[CustomSplit, ...]] = defaultdict(tuple)
198 def _get_key(string: str) -> "CustomSplitMapMixin._Key":
201 A unique identifier that is used internally to map @string to a
202 group of custom splits.
204 return (id(string), string)
206 def add_custom_splits(
207 self, string: str, custom_splits: Iterable[CustomSplit]
209 """Custom Split Map Setter Method
212 Adds a mapping from @string to the custom splits @custom_splits.
214 key = self._get_key(string)
215 self._CUSTOM_SPLIT_MAP[key] = tuple(custom_splits)
217 def pop_custom_splits(self, string: str) -> List[CustomSplit]:
218 """Custom Split Map Getter Method
221 * A list of the custom splits that are mapped to @string, if any
227 Deletes the mapping between @string and its associated custom
228 splits (which are returned to the caller).
230 key = self._get_key(string)
232 custom_splits = self._CUSTOM_SPLIT_MAP[key]
233 del self._CUSTOM_SPLIT_MAP[key]
235 return list(custom_splits)
237 def has_custom_splits(self, string: str) -> bool:
240 True iff @string is associated with a set of custom splits.
242 key = self._get_key(string)
243 return key in self._CUSTOM_SPLIT_MAP
246 class StringMerger(CustomSplitMapMixin, StringTransformer):
247 """StringTransformer that merges strings together.
250 (A) The line contains adjacent strings such that ALL of the validation checks
251 listed in StringMerger.__validate_msg(...)'s docstring pass.
253 (B) The line contains a string which uses line continuation backslashes.
256 Depending on which of the two requirements above where met, either:
258 (A) The string group associated with the target string is merged.
260 (B) All line-continuation backslashes are removed from the target string.
263 StringMerger provides custom split information to StringSplitter.
266 def do_match(self, line: Line) -> TMatchResult:
269 is_valid_index = is_valid_index_factory(LL)
271 for (i, leaf) in enumerate(LL):
273 leaf.type == token.STRING
274 and is_valid_index(i + 1)
275 and LL[i + 1].type == token.STRING
279 if leaf.type == token.STRING and "\\\n" in leaf.value:
282 return TErr("This line has no strings that need merging.")
284 def do_transform(self, line: Line, string_idx: int) -> Iterator[TResult[Line]]:
286 rblc_result = self._remove_backslash_line_continuation_chars(
289 if isinstance(rblc_result, Ok):
290 new_line = rblc_result.ok()
292 msg_result = self._merge_string_group(new_line, string_idx)
293 if isinstance(msg_result, Ok):
294 new_line = msg_result.ok()
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."
303 # Chain the errors together using `__cause__`.
304 msg_cant_transform.__cause__ = rblc_cant_transform
305 cant_transform.__cause__ = msg_cant_transform
307 yield Err(cant_transform)
312 def _remove_backslash_line_continuation_chars(
313 line: Line, string_idx: int
316 Merge strings that were split across multiple lines using
317 line-continuation backslashes.
320 Ok(new_line), if @line contains backslash line-continuation
323 Err(CannotTransform), otherwise.
327 string_leaf = LL[string_idx]
329 string_leaf.type == token.STRING
330 and "\\\n" in string_leaf.value
331 and not has_triple_quotes(string_leaf.value)
334 f"String leaf {string_leaf} does not contain any backslash line"
335 " continuation characters."
338 new_line = line.clone()
339 new_line.comments = line.comments.copy()
340 append_leaves(new_line, line, LL)
342 new_string_leaf = new_line.leaves[string_idx]
343 new_string_leaf.value = new_string_leaf.value.replace("\\\n", "")
347 def _merge_string_group(self, line: Line, string_idx: int) -> TResult[Line]:
349 Merges string group (i.e. set of adjacent strings) where the first
350 string in the group is `line.leaves[string_idx]`.
353 Ok(new_line), if ALL of the validation checks found in
354 __validate_msg(...) pass.
356 Err(CannotTransform), otherwise.
360 is_valid_index = is_valid_index_factory(LL)
362 vresult = self._validate_msg(line, string_idx)
363 if isinstance(vresult, Err):
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
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 @@@@@"
376 QUOTE = LL[string_idx].value[-1]
378 def make_naked(string: str, string_prefix: str) -> str:
379 """Strip @string (i.e. make it a "naked" string)
382 * assert_is_leaf_string(@string)
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.
390 assert_is_leaf_string(string)
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
399 # Holds the CustomSplit objects that will later be added to the custom
403 # Temporary storage for the 'has_prefix' part of the CustomSplit objects.
406 # Sets the 'prefix' variable. This is the prefix that the final merged
408 next_str_idx = string_idx
412 and is_valid_index(next_str_idx)
413 and LL[next_str_idx].type == token.STRING
415 prefix = get_string_prefix(LL[next_str_idx].value).lower()
418 # The next loop merges the string group. The final string will be
421 # The following convenience variables are used:
426 # NSS: naked next string
430 next_str_idx = string_idx
431 while is_valid_index(next_str_idx) and LL[next_str_idx].type == token.STRING:
434 SS = LL[next_str_idx].value
435 next_prefix = get_string_prefix(SS).lower()
437 # If this is an f-string group but this substring is not prefixed
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)
443 NSS = make_naked(SS, next_prefix)
445 has_prefix = bool(next_prefix)
446 prefix_tracker.append(has_prefix)
448 S = prefix + QUOTE + NS + NSS + BREAK_MARK + QUOTE
449 NS = make_naked(S, prefix)
453 S_leaf = Leaf(token.STRING, S)
454 if self.normalize_strings:
455 S_leaf.value = normalize_string_quotes(S_leaf.value)
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)
463 ), "Logic error while filling the custom string breakpoint cache."
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))
469 string_leaf = Leaf(token.STRING, S_leaf.value.replace(BREAK_MARK, ""))
471 if atom_node is not None:
472 replace_child(atom_node, string_leaf)
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):
478 new_line.append(string_leaf)
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)
485 append_leaves(new_line, line, [leaf])
487 self.add_custom_splits(string_leaf.value, custom_splits)
491 def _validate_msg(line: Line, string_idx: int) -> TResult[None]:
492 """Validate (M)erge (S)tring (G)roup
494 Transform-time string validation logic for __merge_string_group(...).
497 * Ok(None), if ALL validation checks (listed below) pass.
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
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.
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).
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 [
519 if line.leaves[i].type == STANDALONE_COMMENT:
520 found_sa_comment = True
521 elif found_sa_comment:
523 "StringMerger does NOT merge string groups which contain "
524 "stand-alone comments."
529 num_of_inline_string_comments = 0
530 set_of_prefixes = set()
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
537 if leaf.type == token.COMMA and id(leaf) in line.comments:
538 num_of_inline_string_comments += 1
541 if has_triple_quotes(leaf.value):
542 return TErr("StringMerger does NOT merge multiline strings.")
545 prefix = get_string_prefix(leaf.value).lower()
547 return TErr("StringMerger does NOT merge raw strings.")
549 set_of_prefixes.add(prefix)
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.")
556 if num_of_strings < 2:
558 f"Not enough strings to merge (num_of_strings={num_of_strings})."
561 if num_of_inline_string_comments > 1:
563 f"Too many inline string comments ({num_of_inline_string_comments})."
566 if len(set_of_prefixes) > 1 and set_of_prefixes != {"", "f"}:
567 return TErr(f"Too many different prefixes ({set_of_prefixes}).")
572 class StringParenStripper(StringTransformer):
573 """StringTransformer that strips surrounding parentheses from strings.
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
584 The parentheses mentioned in the 'Requirements' section are stripped.
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).
592 def do_match(self, line: Line) -> TMatchResult:
595 is_valid_index = is_valid_index_factory(LL)
597 for (idx, leaf) in enumerate(LL):
598 # Should be a string...
599 if leaf.type != token.STRING:
602 # If this is a "pointless" string...
605 and leaf.parent.parent
606 and leaf.parent.parent.type == syms.simple_stmt
610 # Should be preceded by a non-empty LPAR...
612 not is_valid_index(idx - 1)
613 or LL[idx - 1].type != token.LPAR
614 or is_empty_lpar(LL[idx - 1])
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
628 # Skip the string trailer, if one exists.
629 string_parser = StringParser()
630 next_idx = string_parser.parse(LL, string_idx)
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 (
655 # only unary PLUS/MINUS
657 and before_lpar.parent.type == syms.factor
658 and (before_lpar.type in {token.PLUS, token.MINUS})
663 # Should be followed by a non-empty RPAR...
665 is_valid_index(next_idx)
666 and LL[next_idx].type == token.RPAR
667 and not is_empty_rpar(LL[next_idx])
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 {
679 return Ok(string_idx)
681 return TErr("This line has no strings wrapped in parens.")
683 def do_transform(self, line: Line, string_idx: int) -> Iterator[TResult[Line]]:
686 string_parser = StringParser()
687 rpar_idx = string_parser.parse(LL, string_idx)
689 for leaf in (LL[string_idx - 1], LL[rpar_idx]):
690 if line.comments_after(leaf):
692 "Will not strip parentheses which have comments attached to them."
696 new_line = line.clone()
697 new_line.comments = line.comments.copy()
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)
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)
712 new_line, line, LL[string_idx + 1 : rpar_idx] + LL[rpar_idx + 1 :]
715 LL[rpar_idx].remove()
720 class BaseStringSplitter(StringTransformer):
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.
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.
733 * The target string is NOT a "pointless" string (i.e. a string that has
734 no parent or siblings).
736 * The target string is not followed by an inline comment that appears
739 * The target string is not a multiline (i.e. triple-quote) string.
755 def do_splitter_match(self, line: Line) -> TMatchResult:
757 BaseStringSplitter asks its clients to override this method instead of
758 `StringTransformer.do_match(...)`.
760 Follows the same protocol as `StringTransformer.do_match(...)`.
762 Refer to `help(StringTransformer.do_match)` for more information.
765 def do_match(self, line: Line) -> TMatchResult:
766 match_result = self.do_splitter_match(line)
767 if isinstance(match_result, Err):
770 string_idx = match_result.ok()
771 vresult = self._validate(line, string_idx)
772 if isinstance(vresult, Err):
777 def _validate(self, line: Line, string_idx: int) -> TResult[None]:
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.
784 * Ok(None), if ALL of the requirements are met.
786 * Err(CannotTransform), if ANY of the requirements are NOT met.
790 string_leaf = LL[string_idx]
792 max_string_length = self._get_max_string_length(line, string_idx)
793 if len(string_leaf.value) <= max_string_length:
795 "The string itself is not what is causing this line to be too long."
798 if not string_leaf.parent or [L.type for L in string_leaf.parent.children] == [
803 f"This string ({string_leaf.value}) appears to be pointless (i.e. has"
807 if id(line.leaves[string_idx]) in line.comments and contains_pragma_comment(
808 line.comments[id(line.leaves[string_idx])]
811 "Line appears to end with an inline pragma comment. Splitting the line"
812 " could modify the pragma's behavior."
815 if has_triple_quotes(string_leaf.value):
816 return TErr("We cannot split multiline strings.")
820 def _get_max_string_length(self, line: Line, string_idx: int) -> int:
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.
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.
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.
837 is_valid_index = is_valid_index_factory(LL)
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
843 # Finally, we use the following convenience variables:
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.
849 # WMA4 the whitespace at the beginning of the line.
850 offset = line.depth * 4
852 if is_valid_index(string_idx - 1):
853 p_idx = string_idx - 1
855 LL[string_idx - 1].type == token.LPAR
856 and LL[string_idx - 1].value == ""
859 # If the previous leaf is an empty LPAR placeholder, we should skip it.
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
867 if P.type == token.COMMA:
868 # WMA4 a space, a comma, and a closing bracket [e.g. `), STRING`].
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.
876 # WMA4 a single space.
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:
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]
892 if N.type == token.COMMA:
893 # WMA4 a single comma at the end of the string (e.g `STRING,`).
896 if is_valid_index(string_idx + 2):
897 NN = LL[string_idx + 2]
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.
903 # WMA4 the '.' character.
907 is_valid_index(string_idx + 3)
908 and LL[string_idx + 3].type == token.LPAR
910 # WMA4 the left parenthesis character.
913 # WMA4 the length of the method's name.
914 offset += len(NN.value)
917 for comment_leaf in line.comments_after(LL[string_idx]):
920 # WMA4 two spaces before the '#' character.
923 # WMA4 the length of the inline comment.
924 offset += len(comment_leaf.value)
926 max_string_length = self.line_length - offset
927 return max_string_length
930 class StringSplitter(CustomSplitMapMixin, BaseStringSplitter):
932 StringTransformer that splits "atom" strings (i.e. strings which exist on
933 lines by themselves).
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
940 * All of the requirements listed in BaseStringSplitter's docstring.
943 The string mentioned in the 'Requirements' section is split into as
944 many substrings as necessary to adhere to the configured line length.
946 In the final set of substrings, no substring should be smaller than
947 MIN_SUBSTR_SIZE characters.
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.
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).
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.
964 StringSplitter relies on StringMerger to construct the appropriate
965 CustomSplit objects and add them to the custom split map.
969 # Matches an "f-expression" (e.g. {var}) that might be found in an f-string.
971 (?<!\{) (?:\{\{)* \{ (?!\{)
981 def do_splitter_match(self, line: Line) -> TMatchResult:
984 is_valid_index = is_valid_index_factory(LL)
988 # The first two leaves MAY be the 'not in' keywords...
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"
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"
1004 # The next/first leaf MAY be an empty LPAR...
1005 if is_valid_index(idx) and is_empty_lpar(LL[idx]):
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.")
1014 # Skip the string trailer, if one exists.
1015 string_parser = StringParser()
1016 idx = string_parser.parse(LL, string_idx)
1018 # That string MAY be followed by an empty RPAR...
1019 if is_valid_index(idx) and is_empty_rpar(LL[idx]):
1022 # That string / empty RPAR leaf MAY be followed by a comma...
1023 if is_valid_index(idx) and LL[idx].type == token.COMMA:
1026 # But no more leaves are allowed...
1027 if is_valid_index(idx):
1028 return TErr("This line does not end with a string.")
1030 return Ok(string_idx)
1032 def do_transform(self, line: Line, string_idx: int) -> Iterator[TResult[Line]]:
1035 QUOTE = LL[string_idx].value[-1]
1037 is_valid_index = is_valid_index_factory(LL)
1038 insert_str_child = insert_str_child_factory(LL[string_idx])
1040 prefix = get_string_prefix(LL[string_idx].value).lower()
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
1046 drop_pointless_f_prefix = ("f" in prefix) and re.search(
1047 self.RE_FEXPR, LL[string_idx].value, re.VERBOSE
1050 first_string_line = True
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
1059 def maybe_append_string_operators(new_line: Line) -> None:
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.
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)
1073 is_valid_index(string_idx + 1) and LL[string_idx + 1].type == token.COMMA
1076 def max_last_string() -> int:
1079 The max allowed length of the string value used for the last
1080 line we will construct.
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
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.
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:
1097 f"Unable to split {LL[string_idx].value} at such high of a line depth:"
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
1106 use_custom_breakpoints = bool(
1108 and all(csplit.break_idx <= max_break_idx for csplit in custom_splits)
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
1115 def more_splits_should_be_made() -> bool:
1118 True iff `rest_value` (the remaining string value from the last
1119 split), should be split again.
1121 if use_custom_breakpoints:
1122 return len(custom_splits) > 1
1124 return len(rest_value) > max_last_string()
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
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.
1142 rest_value = LL[string_idx].value
1143 string_line_results = []
1144 first_string_line = True
1145 use_custom_breakpoints = True
1148 # Otherwise, we stop splitting here.
1151 break_idx = maybe_break_idx
1153 # --- Construct `next_value`
1154 next_value = rest_value[:break_idx] + QUOTE
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).
1164 # There is probably a better way to accomplish what is being done
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
1171 next_value != self._normalize_f_string(next_value, prefix)
1172 and use_custom_breakpoints
1173 and not csplit.has_prefix
1175 # Then `csplit.break_idx` will be off by one after removing
1178 next_value = rest_value[:break_idx] + QUOTE
1180 if drop_pointless_f_prefix:
1181 next_value = self._normalize_f_string(next_value, prefix)
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)
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))
1194 rest_value = prefix + QUOTE + rest_value[break_idx:]
1195 first_string_line = False
1197 yield from string_line_results
1199 if drop_pointless_f_prefix:
1200 rest_value = self._normalize_f_string(rest_value, prefix)
1202 rest_leaf = Leaf(token.STRING, rest_value)
1203 insert_str_child(rest_leaf)
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)
1210 last_line = line.clone()
1211 maybe_append_string_operators(last_line)
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:
1224 # Try to fit them all on the same line with the last substring...
1226 len(temp_value) <= max_last_string()
1227 or LL[string_idx + 1].type == token.COMMA
1229 last_line.append(rest_leaf)
1230 append_leaves(last_line, line, LL[string_idx + 1 :])
1232 # Otherwise, place the last substring on one line and everything
1233 # else on a line below that...
1235 last_line.append(rest_leaf)
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...
1243 last_line.append(rest_leaf)
1244 last_line.comments = line.comments.copy()
1247 def _iter_nameescape_slices(self, string: str) -> Iterator[Tuple[Index, Index]]:
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
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))
1260 previous_was_unescaped_backslash = not previous_was_unescaped_backslash
1262 if not previous_was_unescaped_backslash or c != "N":
1263 previous_was_unescaped_backslash = False
1265 previous_was_unescaped_backslash = False
1267 begin = idx - 1 # the position of backslash before \N{...}
1273 # malformed nameescape expression?
1274 # should have been detected by AST parsing earlier...
1275 raise RuntimeError(f"{self.__class__.__name__} LOGIC ERROR!")
1278 def _iter_fexpr_slices(self, string: str) -> Iterator[Tuple[Index, Index]]:
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
1285 if "f" not in get_string_prefix(string).lower():
1288 for match in re.finditer(self.RE_FEXPR, string, re.VERBOSE):
1291 def _get_illegal_split_indices(self, string: str) -> Set[Index]:
1292 illegal_indices: Set[Index] = set()
1294 self._iter_fexpr_slices(string),
1295 self._iter_nameescape_slices(string),
1297 for it in iterators:
1298 for begin, end in it:
1299 illegal_indices.update(range(begin, end + 1))
1300 return illegal_indices
1302 def _get_break_idx(self, string: str, max_break_idx: int) -> Optional[int]:
1304 This method contains the algorithm that StringSplitter uses to
1305 determine which character to split each string at.
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.
1316 * assert_is_leaf_string(@string)
1317 * 0 <= @max_break_idx < len(@string)
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'
1326 is_valid_index = is_valid_index_factory(string)
1328 assert is_valid_index(max_break_idx)
1329 assert_is_leaf_string(string)
1331 _illegal_split_indices = self._get_illegal_split_indices(string)
1333 def breaks_unsplittable_expression(i: Index) -> bool:
1336 True iff returning @i would result in the splitting of an
1337 unsplittable expression (which is NOT allowed).
1339 return i in _illegal_split_indices
1341 def passes_all_checks(i: Index) -> bool:
1344 True iff ALL of the conditions listed in the 'Transformations'
1345 section of this classes' docstring would be be met by returning @i.
1347 is_space = string[i] == " "
1349 is_not_escaped = True
1351 while is_valid_index(j) and string[j] == "\\":
1352 is_not_escaped = not is_not_escaped
1356 len(string[i:]) >= self.MIN_SUBSTR_SIZE
1357 and len(string[:i]) >= self.MIN_SUBSTR_SIZE
1363 and not breaks_unsplittable_expression(i)
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):
1371 if not passes_all_checks(break_idx):
1372 # If that fails, we check all indices ABOVE @max_break_idx.
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):
1381 if not is_valid_index(break_idx) or not passes_all_checks(break_idx):
1386 def _maybe_normalize_string_quotes(self, leaf: Leaf) -> None:
1387 if self.normalize_strings:
1388 leaf.value = normalize_string_quotes(leaf.value)
1390 def _normalize_f_string(self, string: str, prefix: str) -> str:
1393 * assert_is_leaf_string(@string)
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 '}').
1401 * Otherwise, we return @string.
1403 assert_is_leaf_string(string)
1405 if "f" in prefix and not re.search(self.RE_FEXPR, string, re.VERBOSE):
1406 new_prefix = prefix.replace("f", "")
1408 temp = string[len(prefix) :]
1409 temp = re.sub(r"\{\{", "{", temp)
1410 temp = re.sub(r"\}\}", "}", temp)
1413 return f"{new_prefix}{new_string}"
1417 def _get_string_operator_leaves(self, leaves: Iterable[Leaf]) -> List[Leaf]:
1420 string_op_leaves = []
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)
1426 return string_op_leaves
1429 class StringParenWrapper(CustomSplitMapMixin, BaseStringSplitter):
1431 StringTransformer that splits non-"atom" strings (i.e. strings that do not
1432 exist on lines by themselves).
1435 All of the requirements listed in BaseStringSplitter's docstring in
1436 addition to the requirements listed below:
1438 * The line is a return/yield statement, which returns/yields a string.
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
1444 * The line is an assert statement, which ends with a string.
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
1450 * The line is a dictionary key assignment where some valid key is being
1451 assigned the value of some string.
1454 The chosen string is wrapped in parentheses and then split at the LPAR.
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.
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
1468 In other words, StringParenWrapper creates "atom" strings. These
1469 can then be split again by StringSplitter, if necessary.
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.
1478 def do_splitter_match(self, line: Line) -> TMatchResult:
1481 if line.leaves[-1].type in OPENING_BRACKETS:
1483 "Cannot wrap parens around a line that ends in an opening bracket."
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)
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.
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."
1509 return Ok(string_idx)
1511 return TErr("This line does not contain any non-atomic strings.")
1514 def _return_match(LL: List[Leaf]) -> Optional[int]:
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'
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[
1528 ].value in ["return", "yield"]:
1529 is_valid_index = is_valid_index_factory(LL)
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:
1539 def _else_match(LL: List[Leaf]) -> Optional[int]:
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'
1549 # If this line is apart of a ternary expression and the first leaf
1550 # contains the "else" keyword...
1552 parent_type(LL[0]) == syms.test
1553 and LL[0].type == token.NAME
1554 and LL[0].value == "else"
1556 is_valid_index = is_valid_index_factory(LL)
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:
1566 def _assert_match(LL: List[Leaf]) -> Optional[int]:
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'
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)
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
1586 # That comma MUST be followed by a string...
1587 if is_valid_index(idx) and LL[idx].type == token.STRING:
1590 # Skip the string trailer, if one exists.
1591 string_parser = StringParser()
1592 idx = string_parser.parse(LL, string_idx)
1594 # But no more leaves are allowed...
1595 if not is_valid_index(idx):
1601 def _assign_match(LL: List[Leaf]) -> Optional[int]:
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'
1611 # If this line is apart of an expression statement or is a function
1612 # argument AND the first leaf contains a variable name...
1614 parent_type(LL[0]) in [syms.expr_stmt, syms.argument, syms.power]
1615 and LL[0].type == token.NAME
1617 is_valid_index = is_valid_index_factory(LL)
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
1624 # That symbol MUST be followed by a string...
1625 if is_valid_index(idx) and LL[idx].type == token.STRING:
1628 # Skip the string trailer, if one exists.
1629 string_parser = StringParser()
1630 idx = string_parser.parse(LL, string_idx)
1632 # The next leaf MAY be a comma iff this line is apart
1633 # of a function argument...
1635 parent_type(LL[0]) == syms.argument
1636 and is_valid_index(idx)
1637 and LL[idx].type == token.COMMA
1641 # But no more leaves are allowed...
1642 if not is_valid_index(idx):
1648 def _dict_match(LL: List[Leaf]) -> Optional[int]:
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
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)
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
1667 # That colon MUST be followed by a string...
1668 if is_valid_index(idx) and LL[idx].type == token.STRING:
1671 # Skip the string trailer, if one exists.
1672 string_parser = StringParser()
1673 idx = string_parser.parse(LL, string_idx)
1675 # That string MAY be followed by a comma...
1676 if is_valid_index(idx) and LL[idx].type == token.COMMA:
1679 # But no more leaves are allowed...
1680 if not is_valid_index(idx):
1685 def do_transform(self, line: Line, string_idx: int) -> Iterator[TResult[Line]]:
1688 is_valid_index = is_valid_index_factory(LL)
1689 insert_str_child = insert_str_child_factory(LL[string_idx])
1692 ends_with_comma = False
1693 if LL[comma_idx].type == token.COMMA:
1694 ends_with_comma = True
1696 leaves_to_steal_comments_from = [LL[string_idx]]
1698 leaves_to_steal_comments_from.append(LL[comma_idx])
1701 first_line = line.clone()
1702 left_leaves = LL[:string_idx]
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])
1713 append_leaves(first_line, line, left_leaves)
1715 lpar_leaf = Leaf(token.LPAR, "(")
1716 if old_parens_exist:
1717 replace_child(LL[string_idx - 1], lpar_leaf)
1719 insert_str_child(lpar_leaf)
1720 first_line.append(lpar_leaf)
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
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)
1729 yield Ok(first_line)
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
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,
1742 string_leaf = Leaf(token.STRING, string_value)
1743 insert_str_child(string_leaf)
1744 string_line.append(string_leaf)
1746 old_rpar_leaf = None
1747 if is_valid_index(string_idx + 1):
1748 right_leaves = LL[string_idx + 1 :]
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})"
1757 old_rpar_leaf = right_leaves.pop()
1759 append_leaves(string_line, line, right_leaves)
1761 yield Ok(string_line)
1764 last_line = line.clone()
1765 last_line.bracket_tracker = first_line.bracket_tracker
1767 new_rpar_leaf = Leaf(token.RPAR, ")")
1768 if old_rpar_leaf is not None:
1769 replace_child(old_rpar_leaf, new_rpar_leaf)
1771 insert_str_child(new_rpar_leaf)
1772 last_line.append(new_rpar_leaf)
1774 # If the target string ended with a comma, we place this comma to the
1775 # right of the RPAR on the last line.
1777 comma_leaf = Leaf(token.COMMA, ",")
1778 replace_child(LL[comma_idx], comma_leaf)
1779 last_line.append(comma_leaf)
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,
1791 NOTE: A new StringParser object MUST be instantiated for each string
1792 trailer we need to parse.
1795 We shall assume that `line` equals the `Line` object that corresponds
1796 to the following line of python code:
1798 x = "Some {}.".format("String") + some_other_string
1801 Furthermore, we will assume that `string_idx` is some index such that:
1803 assert line.leaves[string_idx].value == "Some {}."
1806 The following code snippet then holds:
1808 string_parser = StringParser()
1809 idx = string_parser.parse(line.leaves, string_idx)
1810 assert line.leaves[idx].type == token.PLUS
1816 # String Parser States
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,
1852 def __init__(self) -> None:
1853 self._state = self.START
1854 self._unmatched_lpars = 0
1856 def parse(self, leaves: List[Leaf], string_idx: int) -> int:
1859 * @leaves[@string_idx].type == token.STRING
1862 The index directly after the last leaf which is apart of the string
1863 trailer, if a "trailer" exists.
1865 @string_idx + 1, if no string "trailer" exists.
1867 assert leaves[string_idx].type == token.STRING
1869 idx = string_idx + 1
1870 while idx < len(leaves) and self._next_state(leaves[idx]):
1874 def _next_state(self, leaf: Leaf) -> bool:
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.
1885 True iff @leaf is apart of the string's trailer.
1887 # We ignore empty LPAR or RPAR leaves.
1888 if is_empty_par(leaf):
1891 next_token = leaf.type
1892 if next_token == token.LPAR:
1893 self._unmatched_lpars += 1
1895 current_state = self._state
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.
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]
1911 # Otherwise, we check if a the current state was assigned a
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
1918 raise RuntimeError(f"{self.__class__.__name__} LOGIC ERROR!")
1920 if self._state == self.DONE:
1926 def insert_str_child_factory(string_leaf: Leaf) -> Callable[[LN], None]:
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.
1933 Let `string_leaf = Leaf(token.STRING, '"foo"')` and `N =
1934 string_leaf.parent`. Assume the node `N` has the following
1941 Leaf(STRING, '"foo"'),
1945 We then run the code snippet shown below.
1947 insert_str_child = insert_str_child_factory(string_leaf)
1949 lpar = Leaf(token.LPAR, '(')
1950 insert_str_child(lpar)
1952 bar = Leaf(token.STRING, '"bar"')
1953 insert_str_child(bar)
1955 rpar = Leaf(token.RPAR, ')')
1956 insert_str_child(rpar)
1959 After which point, it follows that `string_leaf.parent is None` and
1960 the node `N` now has the following structure:
1967 Leaf(STRING, '"bar"'),
1972 string_parent = string_leaf.parent
1973 string_child_idx = string_leaf.remove()
1975 def insert_str_child(child: LN) -> None:
1976 nonlocal string_child_idx
1978 assert string_parent is not None
1979 assert string_child_idx is not None
1981 string_parent.insert_child(string_child_idx, child)
1982 string_child_idx += 1
1984 return insert_str_child
1987 def is_valid_index_factory(seq: Sequence[Any]) -> Callable[[int], bool]:
1993 is_valid_index = is_valid_index_factory(my_list)
1995 assert is_valid_index(0)
1996 assert is_valid_index(2)
1998 assert not is_valid_index(3)
1999 assert not is_valid_index(-1)
2003 def is_valid_index(idx: int) -> bool:
2006 True iff @idx is positive AND seq[@idx] does NOT raise an
2009 return 0 <= idx < len(seq)
2011 return is_valid_index