This repository has been archived by the owner on Dec 29, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 12
/
source_match.py
1857 lines (1497 loc) · 57.7 KB
/
source_match.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Copyright 2014 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
Module for annotating an AST with .matcher objects. See README.
"""
import _ast
import pprint
import re
import create_node
import node_tree_util
class Error(Exception):
pass
class BadlySpecifiedTemplateError(Error):
pass
def GetDefaultQuoteType():
return '"'
def GetSource(field, text=None, starting_parens=None, assume_no_indent=False):
"""Gets the source corresponding with a given field.
If the node is not a string or a node with a .matcher function,
this will get the matcher for the node, attach the matcher, and
match the text provided. If no text is provided, it will rely on defaults.
Args:
field: {str|_ast.AST} The field we want the source from.
text: {str} The text to match if a matcher doesn't exist.
starting_parens: {[TextPlaceholder]} The list of parens that the field
starts with.
assume_no_indent: {bool} True if we can assume the node isn't indented.
Used for things like new nodes that aren't yet in a module.
Returns:
A string, representing the source code for the node.
Raises:
ValueError: When passing in a stmt node that has no string or module_node.
This is an error because we have no idea how much to indent it.
"""
if field is None:
return ''
if starting_parens is None:
starting_parens = []
if isinstance(field, str):
return field
if isinstance(field, int):
return str(field)
if hasattr(field, 'matcher') and field.matcher:
return field.matcher.GetSource()
else:
field.matcher = GetMatcher(field, starting_parens)
if text:
field.matcher.Match(text)
# TODO: Fix this to work with lambdas
elif isinstance(field, _ast.stmt) and not assume_no_indent:
if not hasattr(field, 'module_node'):
raise ValueError(
'No text was provided, and we try to get source from node {} which'
'is a statement, so it must have a .module_node field defined. '
'To add this automatically, call ast_annotate.AddBasicAnnotations'
.format(field))
FixSourceIndentation(field.module_node, field)
return field.matcher.GetSource()
def FixSourceIndentation(
module_node, node_to_fix, starting_parens=None):
if starting_parens is None:
starting_parens = []
default_source = node_to_fix.matcher.GetSource()
node_to_fix.matcher = GetMatcher(node_to_fix, starting_parens)
starting_indent = ' ' * node_tree_util.GetIndentLevel(
module_node, node_to_fix)
node_to_fix.matcher.Match(starting_indent + default_source)
def ValidateStart(full_string, starting_string):
stripped_full = StripStartParens(full_string)
stripped_start = StripStartParens(starting_string)
if not stripped_full.startswith(stripped_start):
raise BadlySpecifiedTemplateError(
'String "{}" should have started with string "{}"'
.format(stripped_full, stripped_start))
return True
def _GetListDefault(l, index, default):
if index < len(l):
return l[index]
else:
return default.Copy()
# TODO: Consolidate with StringParser
def MatchPlaceholder(string, node, placeholder):
"""Match a placeholder against a string."""
matched_text = placeholder.Match(node, string)
if not matched_text:
return string
ValidateStart(string, matched_text)
if not isinstance(placeholder, TextPlaceholder):
matched_text = StripStartParens(matched_text)
before, after = string.split(matched_text, 1)
if StripStartParens(before):
raise BadlySpecifiedTemplateError(
'string "{}" should have started with placeholder "{}"'
.format(string, placeholder))
return after
def MatchPlaceholderList(string, node, placeholders, starting_parens=None):
remaining_string = string
for placeholder in placeholders:
if remaining_string == string:
placeholder.SetStartingParens(starting_parens)
remaining_string = MatchPlaceholder(
remaining_string, node, placeholder)
return remaining_string
def StripStartParens(string):
remaining_string = string
while remaining_string.startswith('('):
matcher = GetStartParenMatcher()
matched_text = matcher.Match(None, remaining_string)
remaining_string = remaining_string[len(matched_text):]
return remaining_string
class StringParser(object):
"""Class encapsulating parsing a string while matching placeholders."""
def __init__(self, string, elements, starting_parens=None):
if not starting_parens:
starting_parens = []
self.starting_parens = starting_parens
self.string = string
self.before_string = None
self.remaining_string = string
self.elements = elements
self.matched_substrings = []
self.Parse()
def _ProcessSubstring(self, substring):
"""Process a substring, validating its state and calculating remaining."""
if not substring:
return
stripped_substring = StripStartParens(substring)
stripped_remaining = StripStartParens(self.remaining_string)
if not stripped_remaining.startswith(stripped_substring):
raise BadlySpecifiedTemplateError(
'string "{}" should be in string "{}"'
.format(stripped_substring, stripped_remaining))
self.remaining_string = self.remaining_string.split(
stripped_substring, 1)[1]
def _MatchTextPlaceholder(self, element):
if self.remaining_string == self.string:
element.SetStartingParens(self.starting_parens)
matched_text = element.Match(None, self.remaining_string)
self._ProcessSubstring(matched_text)
self.matched_substrings.append(matched_text)
def _MatchNode(self, node):
starting_parens = []
if self.remaining_string == self.string:
starting_parens = self.starting_parens
node_src = GetSource(node, self.remaining_string, starting_parens)
self._ProcessSubstring(node_src)
self.matched_substrings.append(node_src)
def GetMatchedText(self):
return ''.join(self.matched_substrings)
def Parse(self):
"""Parses the string, handling nodes and TextPlaceholders."""
for element in self.elements:
if isinstance(element, Placeholder):
self._MatchTextPlaceholder(element)
else:
self._MatchNode(element)
class Placeholder(object):
"""Base class for other placeholder objects."""
def __init__(self):
self.starting_parens = []
def Match(self, node, string):
raise NotImplementedError
def GetSource(self, node):
raise NotImplementedError
def SetStartingParens(self, starting_parens):
self.starting_parens = starting_parens
class NodePlaceholder(Placeholder):
"""Placeholder to wrap an AST node."""
def __init__(self, node):
super(NodePlaceholder, self).__init__()
self.node = node
def Match(self, unused_node, string):
node_src = GetSource(self.node, string, self.starting_parens)
ValidateStart(string, node_src)
return node_src
def GetSource(self, unused_node):
return GetSource(self.node)
class TextPlaceholder(Placeholder):
"""Placeholder for text (non-field). For example, 'def (' in FunctionDef."""
def __init__(self, regex, default=None):
super(TextPlaceholder, self).__init__()
self.original_regex = regex
self.regex = self._TransformRegex(regex)
if default is None:
self.default = regex
else:
self.default = default
self.matched_text = None
def _TransformRegex(self, regex):
non_whitespace_parts = regex.split(r'\s*')
regex = r'\s*(\\\s*|#.*\s*)*'.join(non_whitespace_parts)
non_linebreak_parts = regex.split(r'\n')
regex = r'( *#.*\n| *;| *\n)'.join(non_linebreak_parts)
return regex
def Match(self, unused_node, string, dotall=False):
"""Attempts to match string against self.regex.
Saves the matched section for use in GetSource.
Args:
unused_node: unused.
string: The string we attempt to match a substring of.
dotall: Whether to apply re.DOTALL to the match.
Raises:
BadlySpecifiedTemplateError: If the regex doesn't match anywhere.
Returns:
The substring of string that matches.
"""
if dotall:
match_attempt = re.match(self.regex, string, re.DOTALL)
else:
match_attempt = re.match(self.regex, string)
if not match_attempt:
raise BadlySpecifiedTemplateError(
'string "{}" does not match regex "{}" (technically, "{}")'
.format(string, self.original_regex, self.regex))
self.matched_text = match_attempt.group(0)
return self.matched_text
def GetSource(self, unused_node):
"""Returns self.matched_text if it exists, or self.default otherwise."""
if self.matched_text is None:
return self.default
return self.matched_text
def Copy(self):
return TextPlaceholder(self.regex, self.default)
def __repr__(self):
return 'TextPlaceholder with regex "{}" ("{}") and default "{}"'.format(
self.original_regex, self.regex, self.default)
class CompositePlaceholder(Placeholder):
"""Node which wraps one or more other nodes."""
def Match(self, node, string):
"""Makes sure node.(self.field_name) is in string."""
self.Validate(node)
parser = StringParser(
string, self.GetElements(node), starting_parens=self.starting_parens)
return parser.GetMatchedText()
def GetSource(self, node):
return ''.join(
element.GetSource(node) for element in self.GetElements(node))
def Validate(self, unused_node):
return True
class FieldPlaceholder(CompositePlaceholder):
"""Placeholder for a field."""
def __init__(
self, field_name, before_placeholder=None):
super(FieldPlaceholder, self).__init__()
self.field_name = field_name
self.before_placeholder = before_placeholder
def GetElements(self, node):
field_value = getattr(node, self.field_name)
if not field_value:
return []
elements = []
if self.before_placeholder:
elements.append(self.before_placeholder)
elements.append(NodePlaceholder(field_value))
return elements
def Validate(self, node):
field_value = getattr(node, self.field_name)
if isinstance(field_value, (list, tuple)):
raise BadlySpecifiedTemplateError(
'Field {} of node {} is a list. please use a ListFieldPlaceholder'
'instead of a FieldPlaceholder'.format(self.field_name, node))
def __repr__(self):
return 'FieldPlaceholder for field "{}"'.format(
self.field_name)
class ListFieldPlaceholder(CompositePlaceholder):
"""Placeholder for a field which is a list of child nodes."""
def __init__(self, field_name,
before_placeholder=None, after_placeholder=None,
prefix_placeholder=None,
exclude_first_before=False):
"""Initializes a field which is a list of child nodes.
Args:
field_name: {str} The name of the field
before_placeholder: {TextPlaceholder} Text to expect to come before the
child element.
after_placeholder: {TextPlaceholder} Text to expect to come after the
child element.
prefix_placeholder: {TextPlaceholder} Text to expect to come before
the list.
exclude_first_before: {bool} Whether to exclude the last
before_placholder, used for SeparatorListFieldPlaceholder.
"""
super(ListFieldPlaceholder, self).__init__()
self.field_name = field_name
self.prefix_placeholder = prefix_placeholder
self.before_placeholder = before_placeholder
self.after_placeholder = after_placeholder
self.exclude_first_before = exclude_first_before
self.matched_before = []
self.matched_after = []
def _GetBeforePlaceholder(self, index):
if index < len(self.matched_before):
return self.matched_before[index]
new_placeholder = self.before_placeholder.Copy()
self.matched_before.append(new_placeholder)
return new_placeholder
def _GetAfterPlaceholder(self, index):
if index < len(self.matched_after):
return self.matched_after[index]
new_placeholder = self.after_placeholder.Copy()
self.matched_after.append(new_placeholder)
return new_placeholder
def GetValueAtIndex(self, values, index):
"""Gets the set of node in values at index, including before and after."""
elements = []
child_value = values[index]
if isinstance(child_value, create_node.SyntaxFreeLine):
return [NodePlaceholder(child_value)]
if (self.before_placeholder and
not (self.exclude_first_before and index == 0)):
before_index = index-1 if self.exclude_first_before else index
elements.append(self._GetBeforePlaceholder(before_index))
elements.append(NodePlaceholder(child_value))
if self.after_placeholder:
elements.append(self._GetAfterPlaceholder(index))
return elements
def GetElements(self, node):
field_value = getattr(node, self.field_name) or []
elements = []
if self.prefix_placeholder and field_value:
elements.append(self.prefix_placeholder)
for i in xrange(len(field_value)):
elements.extend(self.GetValueAtIndex(field_value, i))
return elements
def Validate(self, node):
field_value = getattr(node, self.field_name)
if field_value and not isinstance(field_value, (list, tuple)):
raise BadlySpecifiedTemplateError(
'Field {} of node {} is a not list, so please use a FieldPlaceholder'
'instead of a ListFieldPlaceholder'.format(self.field_name, node))
def __repr__(self):
return ('ListFieldPlaceholder for field "{}" with before placeholder "{}"'
'and after placeholder "{}"'.format(
self.field_name, self.before_placeholder,
self.after_placeholder))
class SeparatedListFieldPlaceholder(ListFieldPlaceholder):
def __init__(self, field_name, separator_placeholder):
super(SeparatedListFieldPlaceholder, self).__init__(
field_name, before_placeholder=separator_placeholder,
exclude_first_before=True)
class ArgsDefaultsPlaceholder(CompositePlaceholder):
"""Placeholder to handle args and defaults for _ast.argument.
These fields behave differently than most other fields and therefore
don't fall into any of the other placeholders. Therefore, we have to define
a custom placeholder.
"""
def __init__(self, arg_separator_placeholder, kwarg_separator_placeholder):
super(ArgsDefaultsPlaceholder, self).__init__()
self.arg_separator_placeholder = arg_separator_placeholder
self.kwarg_separator_placeholder = kwarg_separator_placeholder
self.arg_separators = []
self.kwarg_separators = []
def _GetArgSeparator(self, index):
if index < len(self.arg_separators):
return self.arg_separators[index]
new_placeholder = self.arg_separator_placeholder.Copy()
self.arg_separators.append(new_placeholder)
return new_placeholder
def _GetKwargSeparator(self, index):
if index < len(self.kwarg_separators):
return self.kwarg_separators[index]
new_placeholder = self.kwarg_separator_placeholder.Copy()
self.kwarg_separators.append(new_placeholder)
return new_placeholder
def _GetArgsKwargs(self, node):
kwargs = zip(node.args[len(node.args)-len(node.defaults):], node.defaults)
args = node.args[:-len(kwargs)] if kwargs else node.args
return args, kwargs
def GetElements(self, node):
"""Gets the basic elements of this composite placeholder."""
args, kwargs = self._GetArgsKwargs(node)
elements = []
arg_index = 0
kwarg_index = 0
for index, arg in enumerate(args):
elements.append(NodePlaceholder(arg))
if index is not len(args)-1 or kwargs:
elements.append(self._GetArgSeparator(arg_index))
arg_index += 1
for index, (key, val) in enumerate(kwargs):
elements.append(NodePlaceholder(key))
elements.append(self._GetKwargSeparator(kwarg_index))
kwarg_index += 1
elements.append(NodePlaceholder(val))
if index is not len(kwargs)-1:
elements.append(self._GetArgSeparator(arg_index))
arg_index += 1
return elements
def __repr__(self):
return ('ArgsDefaultsPlaceholder separating args with "{}" '
'and kwargs with "{}"'
.format(self.arg_separator_placeholder,
self.kwarg_separator_placeholder))
class KeysValuesPlaceholder(ArgsDefaultsPlaceholder):
def _GetArgsKwargs(self, node):
return [], zip(node.keys, node.values)
class ArgsKeywordsPlaceholder(ArgsDefaultsPlaceholder):
def __init__(self, arg_separator_placeholder, kwarg_separator_placeholder):
super(ArgsKeywordsPlaceholder, self).__init__(
arg_separator_placeholder, kwarg_separator_placeholder)
self.stararg_separator = TextPlaceholder(r'\s*,?\s*\*', ', *')
def GetElements(self, node):
"""Gets the basic elements of this composite placeholder."""
args = node.args or []
keywords = node.keywords or []
elements = []
arg_index = 0
for index, arg in enumerate(args):
elements.append(NodePlaceholder(arg))
if index != len(args)-1 or keywords:
elements.append(self._GetArgSeparator(arg_index))
arg_index += 1
if node.starargs:
elements.append(self.stararg_separator)
elements.append(NodePlaceholder(node.starargs))
if keywords:
elements.append(self._GetArgSeparator(arg_index))
arg_index += 1
for index, arg in enumerate(keywords):
elements.append(NodePlaceholder(arg))
if index != len(keywords)-1:
elements.append(self._GetArgSeparator(arg_index))
arg_index += 1
return elements
class OpsComparatorsPlaceholder(ArgsDefaultsPlaceholder):
def _GetArgsKwargs(self, node):
return [], zip(node.ops, node.comparators)
class BodyPlaceholder(ListFieldPlaceholder):
"""Placeholder for a "body" field. Handles adding SyntaxFreeLine nodes."""
def __init__(self, *args, **kwargs):
self.match_after = kwargs.pop('match_after', False)
super(BodyPlaceholder, self).__init__(*args, **kwargs)
def MatchSyntaxFreeLine(self, remaining_string):
line, remaining_string = remaining_string.split('\n', 1)
syntax_free_node = create_node.SyntaxFreeLine()
line += '\n'
syntax_free_node.SetFromSrcLine(line)
GetSource(syntax_free_node, text=line)
return remaining_string, syntax_free_node
def Match(self, node, string):
remaining_string = string
new_node = []
field_value = getattr(node, self.field_name)
if not field_value:
return ''
if self.prefix_placeholder:
remaining_string = MatchPlaceholder(
remaining_string, node, self.prefix_placeholder)
field_value = getattr(node, self.field_name)
for index, child in enumerate(field_value):
while create_node.SyntaxFreeLine.MatchesStart(remaining_string):
remaining_string, syntax_free_node = self.MatchSyntaxFreeLine(
remaining_string)
new_node.append(syntax_free_node)
new_node.append(child)
indent_level = ' ' * (len(remaining_string) -
len(remaining_string.lstrip()))
remaining_string = MatchPlaceholderList(
remaining_string, node, self.GetValueAtIndex(field_value, index))
while (create_node.SyntaxFreeLine.MatchesStart(remaining_string) and
(remaining_string.startswith(indent_level) or self.match_after)):
remaining_string, syntax_free_node = self.MatchSyntaxFreeLine(
remaining_string)
new_node.append(syntax_free_node)
setattr(node, self.field_name, new_node)
matched_string = string
if remaining_string:
matched_string = string[:-len(remaining_string)]
return matched_string
def GetElements(self, node):
field_value = getattr(node, self.field_name)
elements = []
if not field_value:
return elements
if self.prefix_placeholder:
elements.append(self.prefix_placeholder)
for index, unused_child in enumerate(field_value):
elements.extend(self.GetValueAtIndex(field_value, index))
return elements
def GetStartParenMatcher():
return TextPlaceholder(r'\(\s*', '')
def GetEndParenMatcher():
return TextPlaceholder(r'\s*\)', '')
class SourceMatcher(object):
"""Base class for all SourceMatcher objects.
These are designed to match the source that corresponds to a given node.
"""
def __init__(self, node, stripped_parens=None):
self.node = node
self.end_paren_matchers = []
self.paren_wrapped = False
if not stripped_parens:
stripped_parens = []
self.start_paren_matchers = stripped_parens
def Match(self, string):
raise NotImplementedError
def GetSource(self):
raise NotImplementedError
def MatchStartParens(self, string):
"""Matches the starting parens in a string."""
remaining_string = string
matched_parts = []
try:
while True:
start_paren_matcher = GetStartParenMatcher()
remaining_string = MatchPlaceholder(
remaining_string, None, start_paren_matcher)
self.start_paren_matchers.append(start_paren_matcher)
matched_parts.append(start_paren_matcher.matched_text)
except BadlySpecifiedTemplateError:
pass
return remaining_string
def MatchEndParen(self, string):
"""Matches the ending parens in a string."""
if not self.start_paren_matchers:
return
remaining_string = string
matched_parts = []
try:
for unused_i in xrange(len(self.start_paren_matchers)):
end_paren_matcher = GetEndParenMatcher()
remaining_string = MatchPlaceholder(
remaining_string, None, end_paren_matcher)
self.end_paren_matchers.append(end_paren_matcher)
matched_parts.append(end_paren_matcher.matched_text)
self.paren_wrapped = True
except BadlySpecifiedTemplateError:
pass
new_end_matchers = []
new_start_matchers = []
min_size = min(len(self.start_paren_matchers), len(self.end_paren_matchers))
if min_size == 0:
return
for end_matcher in self.end_paren_matchers[:min_size]:
new_start_matchers.append(self.start_paren_matchers.pop())
new_end_matchers.append(end_matcher)
self.start_paren_matchers = new_start_matchers[::-1]
self.end_paren_matchers = new_end_matchers
def GetStartParenText(self):
if self.paren_wrapped:
return ''.join(matcher.GetSource(None)
for matcher in self.start_paren_matchers)
return ''
def GetEndParenText(self):
if self.paren_wrapped:
return ''.join(matcher.GetSource(None)
for matcher in self.end_paren_matchers)
return ''
class DefaultSourceMatcher(SourceMatcher):
"""Class to generate the source for a node."""
def __init__(self, node, expected_parts, starting_parens=None):
super(DefaultSourceMatcher, self).__init__(node, starting_parens)
previous_was_string = False
# We validate that the expected parts does not contain two strings in
# a row.
for part in expected_parts:
if not isinstance(part, Placeholder):
raise ValueError('All expected parts must be Placeholder objects')
if isinstance(part, TextPlaceholder) and not previous_was_string:
previous_was_string = True
elif isinstance(part, TextPlaceholder) and previous_was_string:
raise ValueError('Template cannot expect two strings in a row')
else:
previous_was_string = False
self.expected_parts = expected_parts
self.matched = False
def Match(self, string):
"""Matches the string against self.expected_parts.
Note that this is slightly peculiar in that it first matches fields,
then goes back to match text before them. This is because currently we
don't have matchers for every node, so by default, we separate each
field with a '.*' TextSeparator, which is basically the current behavior
of ast_annotate. This can change after we no longer have any need for
'.*' TextSeparators.
Args:
string: {str} The string to match.
Returns:
The matched text.
Raises:
BadlySpecifiedTemplateError: If there is a mismatch between the
expected_parts and the string.
ValueError: If there is more than one TextPlaceholder in a rwo
"""
remaining_string = self.MatchStartParens(string)
try:
remaining_string = MatchPlaceholderList(
remaining_string, self.node, self.expected_parts,
self.start_paren_matchers)
self.MatchEndParen(remaining_string)
except BadlySpecifiedTemplateError as e:
raise BadlySpecifiedTemplateError(
'When attempting to match string "{}" with {}, this '
'error resulted:\n\n{}'
.format(string, self, e.message))
matched_string = string
if remaining_string:
matched_string = string[:-len(remaining_string)]
return (self.GetStartParenText() +
matched_string +
self.GetEndParenText())
def GetSource(self):
source_list = []
for part in self.expected_parts:
source_list.append(part.GetSource(self.node))
source = ''.join(source_list)
if self.paren_wrapped:
source = '{}{}{}'.format(
self.GetStartParenText(),
source,
self.GetEndParenText())
return source
def __repr__(self):
return ('DefaultSourceMatcher "{}" for node "{}" expecting to match "{}"'
.format(super(DefaultSourceMatcher, self).__repr__(),
self.node,
pprint.pformat(self.expected_parts)))
def GetMatcher(node, starting_parens=None):
"""Gets an initialized matcher for the given node (doesnt call .Match).
If there is no corresponding matcher in _matchers, this will return a
default matcher, which starts with a placeholder for the first field, ends
with a placeholder for the last field, and includes TextPlaceholders
with '.*' regexes between.
Args:
node: The node to get a matcher for.
starting_parens: The parens the matcher may start with.
Returns:
A matcher corresponding to that node, or the default matcher (see above).
"""
if starting_parens is None:
starting_parens = []
parts_or_matcher = _matchers[node.__class__]
try:
parts = parts_or_matcher()
return DefaultSourceMatcher(node, parts, starting_parens)
except TypeError:
return parts_or_matcher(node, starting_parens)
# TODO: Add an indent placeholder that respects col_offset
def get_Add_expected_parts():
return [TextPlaceholder(r'\+', '+')]
def get_alias_expected_parts():
return [
FieldPlaceholder('name'),
FieldPlaceholder(
'asname',
before_placeholder=TextPlaceholder(r' *as *', ' as ')),
]
def get_And_expected_parts():
return [TextPlaceholder(r'and')]
def get_arguments_expected_parts():
return [
ArgsDefaultsPlaceholder(
TextPlaceholder(r'\s*,\s*', ', '),
TextPlaceholder(r'\s*=\s*', '=')),
FieldPlaceholder(
'vararg',
before_placeholder=TextPlaceholder(r'\s*,?\s*\*\s*', ', *')),
FieldPlaceholder(
'kwarg',
before_placeholder=TextPlaceholder(r'\s*,?\s*\*\*\s*', ', **'))
]
def get_Assert_expected_parts():
return [
TextPlaceholder(r' *assert *', 'assert '),
FieldPlaceholder('test'),
FieldPlaceholder(
'msg', before_placeholder=TextPlaceholder(r', *', ', ')),
TextPlaceholder(r' *\n', '\n'),
]
def get_Assign_expected_parts():
return [
TextPlaceholder(r'[ \t]*', ''),
SeparatedListFieldPlaceholder(
'targets', TextPlaceholder(r'\s*=\s*', ', ')),
TextPlaceholder(r'[ \t]*=[ \t]*', ' = '),
FieldPlaceholder('value'),
TextPlaceholder(r'\n', '\n')
]
def get_Attribute_expected_parts():
return [
FieldPlaceholder('value'),
TextPlaceholder(r'\s*\.\s*', '.'),
FieldPlaceholder('attr')
]
def get_AugAssign_expected_parts():
return [
TextPlaceholder(r' *', ''),
FieldPlaceholder('target'),
TextPlaceholder(r' *', ' '),
FieldPlaceholder('op'),
TextPlaceholder(r'= *', '= '),
FieldPlaceholder('value'),
TextPlaceholder(r'\n', '\n')
]
# TODO: Handle parens better
def get_BinOp_expected_parts():
return [
FieldPlaceholder('left'),
TextPlaceholder(r'\s*', ' '),
FieldPlaceholder('op'),
TextPlaceholder(r'\s*', ' '),
FieldPlaceholder('right'),
]
def get_BitAnd_expected_parts():
return [TextPlaceholder(r'&', '&')]
def get_BitOr_expected_parts():
return [
TextPlaceholder(r'\|', '|'),
]
def get_BitXor_expected_parts():
return [
TextPlaceholder(r'\^', '^'),
]
# TODO: Handle parens better
class BoolOpSourceMatcher(SourceMatcher):
"""Class to generate the source for an _ast.BoolOp node."""
def __init__(self, node, starting_parens=None):
super(BoolOpSourceMatcher, self).__init__(node, starting_parens)
self.separator_placeholder = TextPlaceholder(r'\s*', ' ')
self.matched_placeholders = []
def GetSeparatorCopy(self):
copy = self.separator_placeholder.Copy()
self.matched_placeholders.append(copy)
return copy
def Match(self, string):
remaining_string = self.MatchStartParens(string)
elements = [self.node.values[0]]
for value in self.node.values[1:]:
elements.append(self.GetSeparatorCopy())
elements.append(self.node.op)
elements.append(self.GetSeparatorCopy())
elements.append(value)
parser = StringParser(remaining_string, elements, self.start_paren_matchers)
matched_text = ''.join(parser.matched_substrings)
remaining_string = parser.remaining_string
self.MatchEndParen(remaining_string)
return self.GetStartParenText() + matched_text + self.GetEndParenText()
def GetSource(self):
source_list = []
if self.paren_wrapped:
source_list.append(self.GetStartParenText())
source_list.append(GetSource(self.node.values[0]))
index = 0
for value in self.node.values[1:]:
source_list.append(_GetListDefault(
self.matched_placeholders,
index,
self.separator_placeholder).GetSource(None))
source_list.append(GetSource(self.node.op))
index += 1
source_list.append(_GetListDefault(
self.matched_placeholders,
index,
self.separator_placeholder).GetSource(None))
source_list.append(GetSource(value))
index += 1
if self.paren_wrapped:
source_list.append(self.GetEndParenText())
return ''.join(source_list)
def get_Break_expected_parts():
return [TextPlaceholder(r' *break *\n', 'break\n')]
def get_Call_expected_parts():
return [
FieldPlaceholder('func'),
TextPlaceholder(r'\(\s*', '('),
ArgsKeywordsPlaceholder(
TextPlaceholder(r'\s*,\s*', ', '),
TextPlaceholder('')),
FieldPlaceholder(
'kwargs',
before_placeholder=TextPlaceholder(r'\s*,?\s*\*\*', ', **')),
TextPlaceholder(r'\s*,?\s*\)', ')'),
]
def get_ClassDef_expected_parts():
return [
ListFieldPlaceholder(
'decorator_list',
before_placeholder=TextPlaceholder('[ \t]*@', '@'),
after_placeholder=TextPlaceholder(r'\n', '\n')),
TextPlaceholder(r'[ \t]*class[ \t]*', 'class '),
FieldPlaceholder('name'),
TextPlaceholder(r'\(?\s*', '('),
SeparatedListFieldPlaceholder(
'bases', TextPlaceholder(r'\s*,\s*', ', ')),
TextPlaceholder(r'\s*,?\s*\)?:\n', '):\n'),
BodyPlaceholder('body')
]
def get_Compare_expected_parts():
return [
FieldPlaceholder('left'),
TextPlaceholder(r'\s*', ' '),
OpsComparatorsPlaceholder(
TextPlaceholder(r'\s*', ' '),
TextPlaceholder(r'\s*', ' '))
]
def get_comprehension_expected_parts():
return [
TextPlaceholder(r'\s*for\s*', 'for '),
FieldPlaceholder('target'),
TextPlaceholder(r'\s*in\s*', ' in '),
FieldPlaceholder('iter'),
ListFieldPlaceholder(
'ifs',
before_placeholder=TextPlaceholder(r'\s*if\s*', ' if '))