/
ast.py
1671 lines (1422 loc) · 59.8 KB
/
ast.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 2007 Neal Norwitz
# Portions Copyright 2007 Google Inc.
#
# 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.
"""Generate an Abstract Syntax Tree (AST) for C++."""
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import os
import collections
from . import keywords
from . import tokenize
try:
unicode
except NameError:
unicode = str
__author__ = 'nnorwitz@google.com (Neal Norwitz)'
# TODO:
# * Tokens should never be exported, need to convert to Nodes
# (return types, parameters, etc.)
# * Handle static class data for templatized classes
# * Handle casts (both C++ and C-style)
# * Handle conditions and loops (if/else, switch, for, while/do)
#
# TODO much, much later:
# * Handle #define
# * exceptions
FUNCTION_NONE = 0x00
FUNCTION_SPECIFIER = 0x01
FUNCTION_VIRTUAL = 0x02
FUNCTION_PURE_VIRTUAL = 0x04
FUNCTION_CTOR = 0x08
FUNCTION_DTOR = 0x10
FUNCTION_ATTRIBUTE = 0x20
FUNCTION_UNKNOWN_ANNOTATION = 0x40
FUNCTION_THROW = 0x80
class ParseError(Exception):
"""Raise exception on parsing problems."""
# TODO(nnorwitz): move AST nodes into a separate module.
class Node(object):
"""Base AST node."""
def __init__(self, start, end):
self.start = start
self.end = end
def is_declaration(self):
"""Returns bool if this node is a declaration."""
return False
def is_definition(self):
"""Returns bool if this node is a definition."""
return False
def is_exportable(self):
"""Returns bool if this node exportable from a header file."""
return False
def _string_helper(self, name, suffix):
return '%s(%d, %d, %s)' % (name, self.start, self.end, suffix)
def __repr__(self):
return unicode(self)
class Define(Node):
def __init__(self, start, end, name, definition):
Node.__init__(self, start, end)
self.name = name
self.definition = definition
# TODO(christarazi):
# Defines aren't bound to namespaces, so this is just a stopgap
# solution.
self.namespace = []
def __str__(self):
value = '%s %s' % (self.name, self.definition)
return self._string_helper(self.__class__.__name__, value)
def is_exportable(self):
return True
class Include(Node):
def __init__(self, start, end, filename, system):
Node.__init__(self, start, end)
self.filename = filename
self.system = system
def __str__(self):
fmt = '"%s"'
if self.system:
fmt = '<%s>'
return self._string_helper(self.__class__.__name__,
fmt % self.filename)
class Expr(Node):
def __init__(self, start, end, expr):
Node.__init__(self, start, end)
self.expr = expr
def __str__(self):
return self._string_helper(self.__class__.__name__, unicode(self.expr))
class Friend(Expr):
def __init__(self, start, end, expr, namespace):
Expr.__init__(self, start, end, expr)
self.namespace = namespace[:]
class Using(Node):
def __init__(self, start, end, names):
Node.__init__(self, start, end)
self.names = names
def __str__(self):
return self._string_helper(self.__class__.__name__,
unicode(self.names))
class Parameter(Node):
def __init__(self, start, end, name, parameter_type, default):
Node.__init__(self, start, end)
self.name = name
self.type = parameter_type
self.default = default
def __str__(self):
name = unicode(self.type)
suffix = '%s %s' % (name, self.name)
if self.default:
suffix += ' = ' + ''.join([d.name for d in self.default])
return self._string_helper(self.__class__.__name__, suffix)
class _GenericDeclaration(Node):
def __init__(self, start, end, name, namespace):
Node.__init__(self, start, end)
self.name = name
self.namespace = namespace[:]
def full_name(self):
prefix = ''
names = [n for n in self.namespace if n is not None]
if names:
prefix = '::'.join(names) + '::'
return prefix + self.name
def _type_string_helper(self, suffix):
if self.namespace:
names = [n or '<anonymous>' for n in self.namespace]
suffix += ' in ' + '::'.join(names)
return self._string_helper(self.__class__.__name__, suffix)
# TODO(nnorwitz): merge with Parameter in some way?
class VariableDeclaration(_GenericDeclaration):
def __init__(self, start, end, name, var_type, initial_value, namespace):
_GenericDeclaration.__init__(self, start, end, name, namespace)
self.type = var_type
self.initial_value = initial_value
def to_string(self):
"""Return a string that tries to reconstitute the variable decl."""
suffix = '%s %s' % (self.type, self.name)
if self.initial_value:
suffix += ' = ' + self.initial_value
return suffix
def __str__(self):
return self._string_helper(self.__class__.__name__, self.to_string())
class Typedef(_GenericDeclaration):
def __init__(self, start, end, name, alias, namespace):
_GenericDeclaration.__init__(self, start, end, name, namespace)
self.alias = alias
def is_definition(self):
return True
def is_exportable(self):
return True
def __str__(self):
suffix = '%s, %s' % (self.name, self.alias)
return self._type_string_helper(suffix)
class Enum(_GenericDeclaration):
def __init__(self, start, end, name, fields, namespace):
_GenericDeclaration.__init__(self, start, end, name, namespace)
self.fields = fields
def is_definition(self):
return True
def is_exportable(self):
return True
def __str__(self):
suffix = '%s, {%s}' % (self.name, self.fields)
return self._type_string_helper(suffix)
class Class(_GenericDeclaration):
def __init__(self, start, end, name,
bases, templated_types, body, namespace):
_GenericDeclaration.__init__(self, start, end, name, namespace)
self.bases = bases
self.body = body
self.templated_types = templated_types
def is_declaration(self):
return self.bases is None and self.body is None
def is_definition(self):
return not self.is_declaration()
def is_exportable(self):
return not self.is_declaration()
def __str__(self):
name = self.name
if self.templated_types:
types = ','.join([t for t in self.templated_types])
name += '<%s>' % types
suffix = '%s, %s, %s' % (name, self.bases, self.body)
return self._type_string_helper(suffix)
class Struct(Class):
pass
class Union(Class):
pass
class Function(_GenericDeclaration):
def __init__(self, start, end, name, return_type, parameters,
specializations, modifiers, templated_types, body, namespace,
initializers=None):
if initializers is None:
initializers = {}
_GenericDeclaration.__init__(self, start, end, name, namespace)
converter = TypeConverter(namespace)
self.return_type = converter.create_return_type(return_type)
self.parameters = converter.to_parameters(parameters)
self.specializations = converter.to_type(specializations)
self.modifiers = modifiers
self.body = body
self.templated_types = templated_types
self.initializers = initializers
def is_declaration(self):
return self.body is None
def is_definition(self):
return self.body is not None
def is_exportable(self):
if self.return_type:
if (
'static' in self.return_type.modifiers or
'constexpr' in self.return_type.modifiers
):
return False
return None not in self.namespace
def __str__(self):
# TODO(nnorwitz): add templated_types.
suffix = ('%s %s(%s), 0x%02x, %s' %
(self.return_type, self.name, self.parameters,
self.modifiers, self.body))
return self._type_string_helper(suffix)
class Method(Function):
def __init__(self, start, end, name, in_class, return_type, parameters,
specializations, modifiers, templated_types, body, namespace):
# TODO(christarazi):
# Add support for ctor initializers.
# For now, only inline defined ctors are supported because we would
# need to figure out how to keep state of which class is currently
# being processed in order to modify its body (var decls).
#
# Note: ctor initializers are inside Function because a inline defined
# class members are parsed as functions rather than methods.
Function.__init__(self, start, end, name, return_type, parameters,
specializations, modifiers, templated_types,
body, namespace)
# TODO(nnorwitz): in_class could also be a namespace which can
# mess up finding functions properly.
self.in_class = in_class
class Type(_GenericDeclaration):
"""Type used for any variable (eg class, primitive, struct, etc)."""
def __init__(self, start, end, name, templated_types, modifiers,
reference, pointer, array):
"""Args:
name: str name of main type
templated_types: [Class (Type?)] template type info between <>
modifiers: [str] type modifiers (keywords) eg, const, mutable, etc.
reference, pointer, array: bools
"""
_GenericDeclaration.__init__(self, start, end, name, [])
self.templated_types = templated_types
if not name and modifiers:
self.name = modifiers.pop()
self.modifiers = modifiers
self.reference = reference
self.pointer = pointer
self.array = array
def __str__(self):
prefix = ''
if self.modifiers:
prefix = ' '.join(self.modifiers) + ' '
name = unicode(self.name)
if self.templated_types:
name += '<%s>' % self.templated_types
suffix = prefix + name
if self.reference:
suffix += '&'
if self.pointer:
suffix += '*'
if self.array:
suffix += '[]'
return self._type_string_helper(suffix)
# By definition, Is* are always False. A Type can only exist in
# some sort of variable declaration, parameter, or return value.
def is_declaration(self):
return False
def is_definition(self):
return False
def is_exportable(self):
return False
class TypeConverter(object):
def __init__(self, namespace_stack):
self.namespace_stack = namespace_stack
def _get_template_end(self, tokens, start):
count = 1
end = start
while count and end < len(tokens):
token = tokens[end]
end += 1
if token.name == '<':
count += 1
elif token.name == '>':
count -= 1
return tokens[start:end - 1], end
def to_type(self, tokens):
"""Convert [Token,...] to [Class(...), ] useful for base classes.
For example, code like class Foo : public Bar<x, y> { ... };
the "Bar<x, y>" portion gets converted to an AST.
Returns:
[Class(...), ...]
"""
result = []
name_tokens = []
reference = pointer = array = False
inside_array = False
empty_array = True
templated_tokens = []
def add_type():
if not name_tokens:
return
# Partition tokens into name and modifier tokens.
names = []
modifiers = []
for t in name_tokens:
if keywords.is_keyword(t.name):
modifiers.append(t.name)
else:
names.append(t.name)
name = ''.join(names)
templated_types = self.to_type(templated_tokens)
result.append(Type(name_tokens[0].start, name_tokens[-1].end,
name, templated_types, modifiers,
reference, pointer, array))
del name_tokens[:]
del templated_tokens[:]
i = 0
end = len(tokens)
while i < end:
token = tokens[i]
if token.name == ']':
inside_array = False
if empty_array:
pointer = True
else:
array = True
elif inside_array:
empty_array = False
elif token.name == '<':
templated_tokens, i = self._get_template_end(tokens, i + 1)
continue
elif token.name == ',' or token.name == '(':
add_type()
reference = pointer = array = False
empty_array = True
elif token.name == '*':
pointer = True
elif token.name == '&':
reference = True
elif token.name == '[':
inside_array = True
elif token.name != ')':
name_tokens.append(token)
i += 1
add_type()
return result
def declaration_to_parts(self, parts, needs_name_removed):
arrayBegin = 0
arrayEnd = 0
default = []
other_tokens = []
# Handle default (initial) values properly.
for i, t in enumerate(parts):
if t.name == '[' and arrayBegin == 0:
arrayBegin = i
other_tokens.append(t)
elif t.name == ']':
arrayEnd = i
other_tokens.append(t)
elif t.name == '=':
default = parts[i + 1:]
parts = parts[:i]
break
if arrayBegin < arrayEnd:
parts = parts[:arrayBegin] + parts[arrayEnd + 1:]
modifiers = []
type_name = ['']
last_type = tokenize.SYNTAX
templated_types = []
i = 0
end = len(parts)
while i < end:
p = parts[i]
if keywords.is_builtin_modifiers(p.name):
modifiers.append(p.name)
elif p.name == '<':
templated_tokens, new_end = self._get_template_end(
parts, i + 1)
templated_types = self.to_type(templated_tokens)
i = new_end - 1
elif p.name not in ('*', '&'):
if (
last_type == tokenize.NAME and
p.token_type == tokenize.NAME
):
type_name.append('')
type_name[-1] += p.name
last_type = p.token_type
else:
other_tokens.append(p)
i += 1
name = None
if len(type_name) == 1 or keywords.is_builtin_type(type_name[-1]):
needs_name_removed = False
if needs_name_removed:
name = type_name.pop()
return (name,
' '.join([t for t in type_name]),
templated_types,
modifiers,
default,
other_tokens)
def to_parameters(self, tokens):
if not tokens:
return []
result = []
type_modifiers = []
pointer = reference = False
first_token = None
default = []
def add_parameter():
if not type_modifiers:
return
if default:
del default[0] # Remove flag.
end = type_modifiers[-1].end
(name, type_name, templated_types, modifiers,
_, __) = self.declaration_to_parts(type_modifiers,
True)
if type_name:
parameter_type = Type(first_token.start, first_token.end,
type_name, templated_types, modifiers,
reference, pointer, False)
p = Parameter(first_token.start, end, name,
parameter_type, default)
result.append(p)
template_count = 0
for s in tokens:
if not first_token:
first_token = s
if s.name == '<':
template_count += 1
elif s.name == '>':
template_count -= 1
if template_count > 0:
if default:
default.append(s)
else:
type_modifiers.append(s)
continue
if s.name == ',':
add_parameter()
type_modifiers = []
pointer = reference = False
first_token = None
default = []
elif default:
default.append(s)
elif s.name == '*':
pointer = True
elif s.name == '&':
reference = True
elif s.name == '[':
pointer = True
elif s.name == ']':
pass # Just don't add to type_modifiers.
elif s.name == '=':
# Got a default value. Add any value (None) as a flag.
default.append(None)
else:
type_modifiers.append(s)
add_parameter()
return result
def create_return_type(self, return_type_seq):
if not return_type_seq:
return None
start = return_type_seq[0].start
end = return_type_seq[-1].end
_, name, templated_types, modifiers, __, other_tokens = (
self.declaration_to_parts(return_type_seq, False))
names = [n.name for n in other_tokens]
reference = '&' in names
pointer = '*' in names
array = '[' in names
return Type(start, end, name, templated_types, modifiers,
reference, pointer, array)
def get_template_indices(self, names):
# names is a list of strings.
start = names.index('<')
end = len(names) - 1
while end > 0:
if names[end] == '>':
break
end -= 1
return start, end + 1
class ASTBuilder(object):
def __init__(self, token_stream, filename, system_includes=tuple(),
nonsystem_includes=tuple(), in_class=None,
namespace_stack=None, quiet=False):
if namespace_stack is None:
namespace_stack = []
self.system_includes = system_includes
self.nonsystem_includes = nonsystem_includes
self.tokens = token_stream
self.filename = filename
self.token_queue = []
self.namespace_stack = namespace_stack[:]
self.namespaces = []
self.define = set()
self.quiet = quiet
self.in_class = in_class
if in_class:
self.namespaces.append(False)
# Keep the state whether we are currently handling a typedef or not.
self._handling_typedef = False
self._handling_const = False
self.converter = TypeConverter(self.namespace_stack)
def generate(self):
while True:
try:
token = self._get_next_token()
except StopIteration:
break
if token.name == '{':
self.namespaces.append(False)
continue
if token.name == '}':
if self.namespaces and self.namespaces.pop():
self.namespace_stack.pop()
continue
try:
result = self._generate_one(token)
except StopIteration:
pass
else:
if result:
yield result
def _create_variable(self, pos_token, name, type_name, type_modifiers,
ref_pointer_name_seq, templated_types=None, value=''):
if templated_types is None:
templated_types = []
reference = '&' in ref_pointer_name_seq
pointer = '*' in ref_pointer_name_seq
array = '[' in ref_pointer_name_seq
var_type = Type(pos_token.start, pos_token.end, type_name,
templated_types, type_modifiers,
reference, pointer, array)
return VariableDeclaration(pos_token.start, pos_token.end,
name, var_type, value, self.namespace_stack)
def _generate_one(self, token):
if token.token_type == tokenize.NAME:
if (keywords.is_keyword(token.name) and
not keywords.is_builtin_type(token.name)):
method = getattr(self, 'handle_' + token.name, None)
assert_parse(method, 'unexpected token: {}'.format(token))
return method()
# Handle data or function declaration/definition.
temp_tokens, last_token = \
self._get_var_tokens_up_to(True, '(', ';', '{')
temp_tokens.insert(0, token)
if last_token.name == '(' or last_token.name == '{':
# Ignore static_assert
if temp_tokens[-1].name == 'static_assert':
self._ignore_up_to(';')
return None
# Ignore __declspec
if temp_tokens[-1].name == '__declspec':
list(self._get_parameters())
return None
# Ignore __attribute__
if temp_tokens[-1].name == '__attribute__':
list(self._get_parameters())
new_temp, last_token = \
self._get_var_tokens_up_to(True, '(', ';', '{')
del temp_tokens[-1]
temp_tokens.extend(new_temp)
# If there is an assignment before the paren,
# this is an expression, not a method.
for i, elt in reversed(list(enumerate(temp_tokens))):
if (
elt.name == '=' and
temp_tokens[i - 1].name != 'operator'
):
temp_tokens.append(last_token)
new_temp, last_token = \
self._get_var_tokens_up_to(False, ';')
temp_tokens.extend(new_temp)
break
if last_token.name == ';':
return self._get_variable(temp_tokens)
if last_token.name == '{':
assert_parse(temp_tokens, 'not enough tokens')
self._add_back_token(last_token)
self._add_back_tokens(temp_tokens[1:])
method_name = temp_tokens[0].name
method = getattr(self, 'handle_' + method_name, None)
if not method:
return None
return method()
return self._get_method(temp_tokens, 0, None, False)
elif token.token_type == tokenize.SYNTAX:
if token.name == '~' and self.in_class:
# Must be a dtor (probably not in method body).
token = self._get_next_token()
return self._get_method([token], FUNCTION_DTOR, None, True)
# TODO(nnorwitz): handle a lot more syntax.
elif token.token_type == tokenize.PREPROCESSOR:
# TODO(nnorwitz): handle more preprocessor directives.
# token starts with a #, so remove it and strip whitespace.
name = token.name[1:].lstrip()
if name.startswith('include'):
# Remove "include".
name = name[7:].strip()
assert name
# Handle #include \<newline> "header-on-second-line.h".
if name.startswith('\\'):
name = name[1:].strip()
filename = name.strip('<>"')
def _is_file(prefix):
return os.path.isfile(os.path.join(prefix, filename))
if any([d for d in self.system_includes if _is_file(d)]):
system = True
elif any([d for d in self.nonsystem_includes if _is_file(d)]):
system = False
else:
system = True
filename = name
if name[0] in '<"':
assert_parse(name[-1] in '>"', token)
system = name[0] == '<'
filename = name[1:-1]
return Include(token.start, token.end, filename, system)
if name.startswith('define'):
# Remove "define".
name = name[6:].strip()
assert name
# Handle #define \<newline> MACRO.
if name.startswith('\\'):
name = name[1:].strip()
value = ''
paren = 0
for i, c in enumerate(name):
if not paren and c.isspace():
value = name[i:].lstrip()
name = name[:i]
break
if c == ')':
value = name[i + 1:].lstrip()
name = name[:paren]
self.define.add(name)
break
if c == '(':
paren = i
if value.startswith('\\'):
value = value[1:].strip()
return Define(token.start, token.end, name, value)
if name.startswith('undef'):
# Remove "undef".
name = name[5:].strip()
assert name
self.define.discard(name)
return None
def _get_tokens_up_to(self, expected_token):
return self._get_var_tokens_up_to(False,
expected_token)[0]
def _get_var_tokens_up_to_w_function(self, skip_bracket_content,
*expected_tokens):
# handle the std::function and boost::function case
tokens, last = self._get_var_tokens_up_to(False, *expected_tokens)
names = [token.name for token in tokens]
ctr = collections.Counter(names)
if ('(' in expected_tokens and
ctr['<'] != ctr['>'] and
ctr['function'] == 1 and
last.name == '('):
idx = names.index('function')
if idx + 1 < len(tokens) and tokens[idx + 1].name == '<':
new_tokens, new_last = \
self._get_var_tokens_up_to(False, '(', ';')
tokens.append(last)
last = new_last
tokens += new_tokens
return tokens, last
def _get_var_tokens_up_to(self, skip_bracket_content, *expected_tokens):
last_token = self._get_next_token()
tokens = []
count1 = 0
count2 = 0
while (count1 != 0 or
count2 != 0 or
last_token.token_type != tokenize.SYNTAX or
last_token.name not in expected_tokens):
if last_token.name == '[':
count1 += 1
elif last_token.name == ']':
count1 -= 1
if skip_bracket_content and count1 == 0:
if last_token.name == 'operator':
skip_bracket_content = False
elif last_token.name == '<':
count2 += 1
elif last_token.name == '>':
count2 -= 1
if last_token.token_type != tokenize.PREPROCESSOR:
tokens.append(last_token)
temp_token = self._get_next_token()
if temp_token.name == '(' and last_token.name in self.define:
# TODO: for now just ignore the tokens inside the parenthesis
list(self._get_parameters())
temp_token = self._get_next_token()
last_token = temp_token
return tokens, last_token
def _ignore_up_to(self, token):
self._get_tokens_up_to(token)
def _get_matching_char(self, open_paren, close_paren, get_next_token=None):
if get_next_token is None:
get_next_token = self._get_next_token
# Assumes the current token is open_paren and we will consume
# and return up to the close_paren.
count = 1
while count != 0:
token = get_next_token()
if token.token_type == tokenize.SYNTAX:
if token.name == open_paren:
count += 1
elif token.name == close_paren:
count -= 1
yield token
def _get_parameters(self):
return self._get_matching_char('(', ')')
def get_scope(self):
return self._get_matching_char('{', '}')
def _get_next_token(self):
if self.token_queue:
return self.token_queue.pop()
return next(self.tokens)
def _add_back_token(self, token):
self.token_queue.append(token)
def _add_back_tokens(self, tokens):
if tokens:
self.token_queue.extend(reversed(tokens))
def get_name(self, seq=None):
"""Returns ([tokens], next_token_info)."""
if seq is not None:
it = iter(seq)
def get_next_token():
return next(it)
else:
get_next_token = self._get_next_token
next_token = get_next_token()
tokens = []
last_token_was_name = False
while (next_token.token_type == tokenize.NAME or
(next_token.token_type == tokenize.SYNTAX and
next_token.name in ('::', '<'))):
# Two NAMEs in a row means the identifier should terminate.
# It's probably some sort of variable declaration.
if last_token_was_name and next_token.token_type == tokenize.NAME:
break
last_token_was_name = next_token.token_type == tokenize.NAME
tokens.append(next_token)
# Handle templated names.
if next_token.name == '<':
tokens.extend(self._get_matching_char('<', '>',
get_next_token))
last_token_was_name = True
next_token = get_next_token()
return tokens, next_token
def get_method(self, modifiers, templated_types):
return_type_and_name = \
self._get_var_tokens_up_to_w_function(False, '(')[0]
assert len(return_type_and_name) >= 1
return self._get_method(
return_type_and_name, modifiers, templated_types,
False)
def _get_method(self, return_type_and_name, modifiers, templated_types,
get_paren):
specializations = []
if get_paren:
token = self._get_next_token()
assert_parse(token.token_type == tokenize.SYNTAX, token)
if token.name == '<':
# Handle templatized dtors.
specializations = list(self._get_matching_char('<', '>'))
del specializations[-1]
token = self._get_next_token()
assert_parse(token.token_type == tokenize.SYNTAX, token)
assert_parse(token.name == '(', token)
name = return_type_and_name.pop()
if (len(return_type_and_name) > 2 and
return_type_and_name[-1].name == '>' and
return_type_and_name[-2].name == 'operator' and
(name.name == '>=' or name.name == '>')):
n = return_type_and_name.pop()
name = tokenize.Token(tokenize.SYNTAX,
n.name + name.name,
n.start, name.end)
if (len(return_type_and_name) > 1 and
(return_type_and_name[-1].name == 'operator' or
return_type_and_name[-1].name == '~')):
op = return_type_and_name.pop()
name = tokenize.Token(tokenize.NAME, op.name + name.name,
op.start, name.end)
# Handle templatized ctors.
elif name.name == '>':
count = 1
index = len(return_type_and_name)
while count and index > 0:
index -= 1
tok = return_type_and_name[index]
if tok.name == '<':
count -= 1
elif tok.name == '>':
count += 1
specializations = return_type_and_name[index + 1:]
del return_type_and_name[index:]
name = return_type_and_name.pop()
elif name.name == ']':
name_seq = return_type_and_name[-2]
del return_type_and_name[-2:]
name = tokenize.Token(tokenize.NAME, name_seq.name + '[]',
name_seq.start, name.end)