-
Notifications
You must be signed in to change notification settings - Fork 270
/
parser.py
1631 lines (1395 loc) · 59.2 KB
/
parser.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
"""Fast PYI parser."""
import collections
import hashlib
from pytype import file_utils
from pytype import module_utils
from pytype import utils
from pytype.pyi import parser_ext # pytype: disable=import-error
from pytype.pytd import pep484
from pytype.pytd import pytd
from pytype.pytd import pytd_utils
from pytype.pytd import slots as cmp_slots
from pytype.pytd import visitors
from pytype.pytd.parse import parser_constants # pylint: disable=g-importing-member
_DEFAULT_PLATFORM = "linux"
# Typing members that represent sets of types.
_TYPING_SETS = ("typing.Intersection", "typing.Optional", "typing.Union")
_Params = collections.namedtuple("_", ["required",
"starargs", "starstarargs",
"has_bare_star"])
_NameAndSig = collections.namedtuple("_", ["name", "signature",
"decorator", "is_abstract",
"is_coroutine"])
_SlotDecl = collections.namedtuple("_", ["slots"])
_Property = collections.namedtuple("_", ["precedence", "arity"])
class _ConditionScope(object):
"""State associated with a condition if/elif/else block."""
def __init__(self, parent):
self._parent = parent
if parent is None:
self._active = True
# The value of _can_trigger doesn't really matter since apply_condition
# shouldn't be called on the top scope.
self._can_trigger = False
else:
# By default new scopes are inactive and can be triggered iff the
# parent is active.
self._active = False
self._can_trigger = parent.active
def apply_condition(self, value):
"""Apply the value to this scope.
If the scope can be triggered and value is true, then the scope
becomes active, otherwise the scope is not active. Note that a scope
can trigger at most once since triggering also clears _can_trigger.
Args:
value: a bool.
"""
assert self._parent is not None
if self._can_trigger and value:
self._active = True
self._can_trigger = False
else:
self._active = False
@property
def active(self):
return self._active
@property
def parent(self):
return self._parent
class ParseError(Exception):
"""Exceptions raised by the parser."""
def __init__(self, msg, line=None, filename=None, column=None, text=None):
super(ParseError, self).__init__(msg)
self._line = line
self._filename = filename
self._column = column
self._text = text
@property
def line(self):
return self._line
def __str__(self):
lines = []
if self._filename or self._line is not None:
lines.append(' File: "%s", line %s' % (self._filename, self._line))
if self._column and self._text:
indent = 4
stripped = self._text.lstrip()
lines.append("%*s%s" % (indent, "", stripped))
# Output a pointer below the error column, adjusting for stripped spaces.
pos = indent + (self._column - 1) - (len(self._text) - len(stripped))
lines.append("%*s^" % (pos, ""))
lines.append("%s: %s" % (type(self).__name__, utils.message(self)))
return "\n".join(lines)
class OverloadedDecoratorError(ParseError):
"""Inconsistent decorators on an overloaded function."""
def __init__(self, name, typ, *args, **kwargs):
msg = "Overloaded signatures for %s disagree on %sdecorators" % (
name, (typ + " " if typ else ""))
super(OverloadedDecoratorError, self).__init__(msg, *args, **kwargs)
class _Mutator(visitors.Visitor):
"""Visitor for adding a mutated_type to parameters.
We model the parameter x in
def f(x: old_type):
x = new_type
as
Parameter(name=x, type=old_type, mutated_type=new_type)
.
This visitor applies the body "x = new_type" to the function signature.
"""
def __init__(self, name, new_type):
super(_Mutator, self).__init__()
self.name = name
self.new_type = new_type
self.successful = False
def VisitParameter(self, p):
if p.name == self.name:
self.successful = True
if p.optional:
raise NotImplementedError(
"Argument %s can not be both mutable and optional" % p.name)
return p.Replace(mutated_type=self.new_type)
else:
return p
class _InsertTypeParameters(visitors.Visitor):
"""Visitor for inserting TypeParameter instances."""
def __init__(self, type_params):
super(_InsertTypeParameters, self).__init__()
self.type_params = {p.name: p for p in type_params}
self.inserted = []
self._seen = set()
def VisitNamedType(self, node):
if node.name in self.type_params:
if node.name not in self._seen:
self.inserted.append(node.name)
self._seen.add(node.name)
return self.type_params[node.name]
else:
return node
class _VerifyMutators(visitors.Visitor):
"""Visitor for verifying TypeParameters used in mutations are in scope."""
def __init__(self):
super(_VerifyMutators, self).__init__()
# A stack of type parameters introduced into the scope. The top of the stack
# contains the currently accessible parameter set.
self.type_params_in_scope = [set()]
self.current_function = None
def _AddParams(self, params):
top = self.type_params_in_scope[-1]
self.type_params_in_scope.append(top | params)
def _GetTypeParameters(self, node):
collector = visitors.CollectTypeParameters()
node.Visit(collector)
return {x.name for x in collector.params}
def EnterClass(self, node):
params = set()
for cls in node.parents:
params |= self._GetTypeParameters(cls)
self._AddParams(params)
def LeaveClass(self, _):
self.type_params_in_scope.pop()
def EnterFunction(self, node):
self.current_function = node
params = set()
for sig in node.signatures:
for arg in sig.params:
params |= self._GetTypeParameters(arg.type)
self._AddParams(params)
def LeaveFunction(self, _):
self.type_params_in_scope.pop()
self.current_function = None
def EnterParameter(self, node):
if isinstance(node.mutated_type, pytd.GenericType):
params = self._GetTypeParameters(node.mutated_type)
extra = params - self.type_params_in_scope[-1]
if extra:
fn = pytd_utils.Print(self.current_function)
msg = "Type parameter(s) {%s} not in scope in\n\n%s" % (
", ".join(sorted(extra)), fn)
raise ParseError(msg)
class _ContainsAnyType(visitors.Visitor):
"""Check if a pytd object contains a type of any of the given names."""
def __init__(self, type_names):
super(_ContainsAnyType, self).__init__()
self._type_names = set(type_names)
self.found = False
def EnterNamedType(self, node):
if node.name in self._type_names:
self.found = True
def _contains_any_type(ast, type_names):
"""Convenience wrapper for _ContainsAnyType."""
out = _ContainsAnyType(type_names)
ast.Visit(out)
return out.found
class _PropertyToConstant(visitors.Visitor):
"""Convert some properties to constant types."""
def EnterTypeDeclUnit(self, node):
self.type_param_names = [x.name for x in node.type_params]
self.const_properties = []
def LeaveTypeDeclUnit(self, node):
self.type_param_names = None
def EnterClass(self, node):
self.const_properties.append([])
def LeaveClass(self, node):
self.const_properties.pop()
def VisitClass(self, node):
constants = list(node.constants)
for fn in self.const_properties[-1]:
types = [x.return_type for x in fn.signatures]
constants.append(
pytd.Constant(name=fn.name, type=pytd_utils.JoinTypes(types)))
methods = [x for x in node.methods if x not in self.const_properties[-1]]
return node.Replace(constants=tuple(constants), methods=tuple(methods))
def EnterFunction(self, node):
if (self.const_properties and
node.kind == pytd.PROPERTY and
not self._is_parametrised(node)):
self.const_properties[-1].append(node)
def _is_parametrised(self, method):
for sig in method.signatures:
if _contains_any_type(sig.return_type, self.type_param_names):
return True
class _Parser(object):
"""A class used to parse a single PYI file.
The PYI parser is split into two parts: a low level parser implemented in
in C++, and the high level parser written in Python.
The low level parser calls the lexer (also in C++) determines which
reductions to make, and performs simple actions such as building up lists or
strings. It relies on a "peer" to perform more complicated actions
associated with construction of the AST.
This class is the high level parser, which invokes the low level parser and
serves as the peer for AST construction. Thus it is both the caller and
callee of the low level parser.
The low level parser expects the following interface in its peer.
Attributes that return constant objects:
ELLIPSIS
PARSE_ERROR
NOTHING
ANYTHING
TUPLE
Methods used in AST construction:
new_constant()
add_alias_or_constant()
add_import()
new_class()
new_type()
new_union_type()
new_function()
new_named_tuple()
regiser_class_name()
add_type_var()
if_begin()
if_elif()
if_else()
if_end()
Other methods:
set_error_location()
Error handling is a bit tricky because it is important to associate
location information with errors, but undesireable to move location
information around for every call between the low level parser and the
peer. As a compromise, when errors are detected (either by the low level
parser or by the peer raising an exception), set_error_location() is called
with current location information, then the call to parse_ext.parse()
raises an exception (either a ParseError or whatever else was raised by
the peer in the first place). The high level parser can thus save location
information from set_error_location(), catch the exception raised by
parse_ext.parse(), and raise a new exception that includes a location.
Conditional pyi code (under an "if" statement) is handled similar to a
preprocessor, discarding any statements under False conditions rather than
representing the entire "if" tree in the AST. This approach allows methods
such as add_alias_or_constant() to have side effects provided that they
first check to see if the enclosing scope is active. There are four
peer calls used to support conditions:
if_begin(self, condition): This should be invoked after parsing the initial
condition but before processing any enclosed definitions. It establishes
a new _ConditionScope based on the evaluation of condition. It returns
a bool indicating if the scope will now be active.
if_elif(self, condition): This should be invoked after parsing the condition
following an "elif", but before any subsequent definitions. It evaluates
the condition and changes the scope's state appropriately. It returns
a bool indicating if the scope will now be active.
if_else(self): This should be invoked after parsing "else" but before any
subsequent definitions. The scope will become active if it hasn't
triggered on any previous conditions. It returns a bool indicating
if the scope will now be active.
if_end(self, clauses): This should be called at the end of the entire if
statement where clauses is a list of (active, defs) pairs. Active is
the return value of the corresponding if_begin/if_elif/if_else call, and
defs is a list of definitions within that block. The function returns
the list of defs that should be processed (i.e. the defs in the tuple
where active was True, or [] if no such tuple is present).
See _eval_condition for a description of conditions.
"""
# Values for the parsing context.
ELLIPSIS = object() # Special object to signal ELLIPSIS as a parameter.
PARSE_ERROR = ParseError # The class object (not an instance of it).
NOTHING = pytd.NothingType()
ANYTHING = pytd.AnythingType()
TUPLE = pytd.NamedType("tuple")
# Attributes that all namedtuple instances have.
_NAMEDTUPLE_MEMBERS = ("_asdict", "__dict__", "_fields", "__getnewargs__",
"__getstate__", "_make", "_replace")
def __init__(self, version, platform):
"""Initialize the parser.
Args:
version: A version tuple.
platform: A platform string.
"""
assert version
self._used = False
self._error_location = None
self._version = _three_tuple(utils.normalize_version(version))
self._platform = platform or _DEFAULT_PLATFORM
# Fields initialized in self.parse().
self._filename = None # type: str
self._ast_name = None # type: str
self._package_name = None # type: str
self._parent_name = None # type: str
self._type_map = None # type: dict
# The condition stack, start with a default scope that will always be
# active.
self._current_condition = _ConditionScope(None)
# These fields accumulate definitions that are used to build the
# final TypeDeclUnit.
self._constants = []
self._aliases = collections.OrderedDict()
self._type_params = []
self._module_path_map = {}
self._generated_classes = collections.defaultdict(list)
def parse(self, src, name, filename):
"""Parse a PYI file and return the corresponding AST.
Note that parse() should be called exactly once per _Parser instance. It
holds aggregated state during parsing and is not designed to be reused.
Args:
src: The source text to parse.
name: The name of the module to be created.
filename: The name of the source file.
Returns:
A pytd.TypeDeclUnit() representing the parsed pyi.
Raises:
ParseError: If the PYI source could not be parsed.
"""
# Ensure instances do not get reused.
assert not self._used
self._used = True
self._filename = filename
self._ast_name = name
self._type_map = {}
is_package = file_utils.is_pyi_directory_init(filename)
self._package_name = module_utils.get_package_name(name, is_package)
self._parent_name = module_utils.get_package_name(self._package_name, False)
try:
defs = parser_ext.parse(self, src)
ast = self._build_type_decl_unit(defs)
except ParseError as e:
if self._error_location:
line = e.line or self._error_location[0]
try:
text = src.splitlines()[line-1]
except IndexError:
text = None
raise ParseError(utils.message(e), line=line, filename=self._filename,
column=self._error_location[1], text=text)
else:
raise e
ast = ast.Visit(_PropertyToConstant())
ast = ast.Visit(_InsertTypeParameters(ast.type_params))
ast = ast.Visit(_VerifyMutators())
ast = ast.Visit(pep484.ConvertTypingToNative(name))
if name:
ast = ast.Replace(name=name)
ast = ast.Visit(visitors.AddNamePrefix())
else:
# If there's no unique name, hash the sourcecode.
ast = ast.Replace(name=hashlib.md5(src.encode("utf-8")).hexdigest())
ast = ast.Visit(visitors.StripExternalNamePrefix())
# Typeshed files that explicitly import and refer to "builtins" need to have
# that rewritten to __builtin__
return ast.Visit(visitors.RenameBuiltinsPrefix())
def _build_type_decl_unit(self, defs):
"""Return a pytd.TypeDeclUnit for the given defs (plus parser state)."""
# defs contains both constant and function definitions.
constants, functions, aliases, slots, classes = _split_definitions(defs)
assert not slots # slots aren't allowed on the module level
assert not aliases # We handle top-level aliases in add_alias_or_constant.
constants.extend(self._constants)
generated_classes = sum(self._generated_classes.values(), [])
classes = generated_classes + classes
functions = _merge_method_signatures(functions)
name_to_class = {c.name: c for c in classes}
aliases = []
for a in self._aliases.values():
t = _maybe_resolve_alias(a, name_to_class)
if t is None:
continue
elif isinstance(t, pytd.Function):
functions.append(t)
elif isinstance(t, pytd.Constant):
constants.append(t)
else:
assert isinstance(t, pytd.Alias)
aliases.append(t)
all_names = ([f.name for f in functions] +
[c.name for c in constants] +
[c.name for c in self._type_params] +
[c.name for c in classes] +
[c.name for c in aliases])
duplicates = [name
for name, count in collections.Counter(all_names).items()
if count >= 2]
if duplicates:
raise ParseError(
"Duplicate top-level identifier(s): " + ", ".join(duplicates))
properties = [x for x in functions if x.kind == pytd.PROPERTY]
if properties:
prop_names = ", ".join(p.name for p in properties)
raise ParseError(
"Module-level functions with property decorators: " + prop_names)
return pytd.TypeDeclUnit(name=None,
constants=tuple(constants),
type_params=tuple(self._type_params),
functions=tuple(functions),
classes=tuple(classes),
aliases=tuple(aliases))
def set_error_location(self, location):
"""Record the location of the current error.
Args:
location: A tuple (first_line, first_column, last_line, last_column).
"""
self._error_location = location
def _eval_condition(self, condition):
"""Evaluate a condition and return a bool.
Args:
condition: A tuple of (left, op, right). If op is "or" or "and", then left
and right are conditions. Otherwise, left is a name, op is one of the
comparison strings in cmp_slots.COMPARES, and right is the expected value.
Returns:
The boolean result of evaluating the condition.
Raises:
ParseError: If the condition cannot be evaluated.
"""
left, op, right = condition
if op == "or":
return self._eval_condition(left) or self._eval_condition(right)
elif op == "and":
return self._eval_condition(left) and self._eval_condition(right)
else:
return self._eval_comparison(left, op, right)
def _eval_comparison(self, ident, op, value):
"""Evaluate a comparison and return a bool.
Args:
ident: A tuple of a dotted name string and an optional __getitem__ key
(int or slice).
op: One of the comparison operator strings in cmp_slots.COMPARES.
value: Either a string, an integer, or a tuple of integers.
Returns:
The boolean result of the comparison.
Raises:
ParseError: If the comparison cannot be evaluated.
"""
name, key = ident
if name == "sys.version_info":
if key is None:
key = slice(None, None, None)
assert isinstance(key, (int, slice))
if isinstance(key, int) and not isinstance(value, int):
raise ParseError(
"an element of sys.version_info must be compared to an integer")
if isinstance(key, slice) and not _is_int_tuple(value):
raise ParseError(
"sys.version_info must be compared to a tuple of integers")
try:
actual = self._version[key]
except IndexError as e:
raise ParseError(utils.message(e))
if isinstance(key, slice):
actual = _three_tuple(actual)
value = _three_tuple(value)
elif name == "sys.platform":
if not isinstance(value, str):
raise ParseError("sys.platform must be compared to a string")
valid_cmps = (cmp_slots.EQ, cmp_slots.NE)
if op not in valid_cmps:
raise ParseError(
"sys.platform must be compared using %s or %s" % valid_cmps)
actual = self._platform
value = _handle_string_literal(value)
else:
raise ParseError("Unsupported condition: '%s'." % name)
return cmp_slots.COMPARES[op](actual, value)
def if_begin(self, condition):
"""Begin an "if" statement using the specified condition."""
self._current_condition = _ConditionScope(self._current_condition)
self._current_condition.apply_condition(self._eval_condition(condition))
return self._current_condition.active
def if_elif(self, condition):
"""Start an "elif" clause using the specified condition."""
self._current_condition.apply_condition(self._eval_condition(condition))
return self._current_condition.active
def if_else(self):
"""Start an "else" clause using the specified condition."""
self._current_condition.apply_condition(True)
return self._current_condition.active
def if_end(self, clauses):
"""Finish an "if" statement given a list of (active, defs) clauses."""
self._current_condition = self._current_condition.parent
for cond_value, stmts in clauses:
if cond_value:
return stmts
return []
def new_constant(self, name, value):
"""Return a Constant.
Args:
name: The name of the constant.
value: None, 0, or a pytd type.
Returns:
A Constant object.
Raises:
ParseError: if value is an int other than 0.
"""
if value is None:
t = pytd.AnythingType()
elif isinstance(value, int):
if value != 0:
raise ParseError("Only '0' allowed as int literal")
t = pytd.NamedType("int")
elif isinstance(value, float):
if value != 0.0:
raise ParseError("Only '0.0' allowed as float literal")
t = pytd.NamedType("float")
elif isinstance(value, str):
if value not in ("''", '""', "b''", 'b""', "u''", 'u""'):
raise ParseError("Only '', b'', and u'' allowed as string literals")
elif value.startswith("b"):
t = pytd.NamedType("bytes")
elif value.startswith("u"):
t = pytd.NamedType("unicode")
else:
t = pytd.NamedType("str")
else:
t = value
return pytd.Constant(name, t)
def new_alias_or_constant(self, name_and_value):
name, value = name_and_value
if name == "__slots__":
if not isinstance(value, list):
raise ParseError("__slots__ must be a list of strings")
return _SlotDecl(tuple(_handle_string_literal(s) for s in value))
elif value in [pytd.NamedType("True"), pytd.NamedType("False")]:
return pytd.Constant(name, pytd.NamedType("bool"))
else:
return pytd.Alias(name, value)
def add_alias_or_constant(self, name_and_value):
"""Add an alias or constant.
Args:
name_and_value: The name and value of the alias or constant.
Raises:
ParseError: For an invalid __slots__ declaration.
"""
if not self._current_condition.active:
return
alias_or_constant = self.new_alias_or_constant(name_and_value)
if isinstance(alias_or_constant, pytd.Constant):
self._constants.append(alias_or_constant)
elif isinstance(alias_or_constant, _SlotDecl):
# At this point, bison might not have full location information yet, so
# supply an explicit line number.
raise ParseError("__slots__ only allowed on the class level", line=1)
elif isinstance(alias_or_constant, pytd.Alias):
name, value = name_and_value
self._type_map[name] = value
self._aliases[name] = alias_or_constant
else:
assert False, "Unknown type of assignment"
def add_import(self, from_package, import_list):
"""Add an import.
Args:
from_package: A dotted package name if this is a "from" statement, or None
if it is an "import" statement.
import_list: A list of imported items, which are either strings or pairs
of strings. Pairs are used when items are renamed during import
using "as".
"""
if not self._current_condition.active:
return
if from_package:
# from a.b.c import d, ...
for item in import_list:
if isinstance(item, tuple):
name, new_name = item
else:
name = new_name = item
qualified_name = self._qualify_name("%s.%s" % (from_package, name))
if (from_package in ["__PACKAGE__", "__PARENT__"]
and isinstance(item, str)):
# This will always be a simple module import (from . cannot import a
# NamedType, and without 'as' the name will not be reexported).
t = pytd.Module(name=new_name, module_name=qualified_name)
else:
# We should ideally not need this check, but we have typing
# special-cased in some places.
if not qualified_name.startswith("typing.") and name != "*":
# Mark this as an externally imported type, so that AddNamePrefix
# does not prefix it with the current package name.
qualified_name = (parser_constants.EXTERNAL_NAME_PREFIX +
qualified_name)
t = pytd.NamedType(qualified_name)
if name == "*":
# A star import is stored as
# 'imported_mod.* = imported_mod.*'. The imported module needs to be
# in the alias name so that multiple star imports are handled
# properly. LookupExternalTypes() replaces the alias with the
# contents of the imported module.
assert new_name == name
new_name = t.name
self._type_map[new_name] = t
if (new_name != name or
from_package != "typing" or
self._ast_name == "protocols"):
self._aliases[new_name] = pytd.Alias(new_name, t)
self._module_path_map[new_name] = qualified_name
else:
# import a, b as c, ...
for item in import_list:
if isinstance(item, tuple):
name, new_name = item
t = pytd.Module(name=self._qualify_name(new_name),
module_name=self._qualify_name(name))
self._aliases[new_name] = pytd.Alias(new_name, t)
else:
# We don't care about imports that are not aliased.
pass
def new_type(self, name, parameters=None):
"""Return the AST for a type.
Args:
name: The name of the type.
parameters: List of type parameters.
Returns:
A pytd type node.
Raises:
ParseError: if the wrong number of parameters is supplied for the
base_type - e.g., 2 parameters to Optional or no parameters to Union.
"""
base_type = self._type_map.get(name)
if base_type is None:
module, dot, tail = name.partition(".")
full_name = self._module_path_map.get(module, module) + dot + tail
base_type = pytd.NamedType(full_name)
elif not isinstance(base_type, pytd.NamedType):
# If base_type is not a simple name, check if it is a generic type whose
# type parameters should be substituted by `parameters` (a "type macro").
# We assume that all type parameters have been defined. Since pytype
# orders type parameters to appear before classes and functions, this
# assumption is generally safe. AnyStr is special-cased because imported
# type parameters aren't recognized.
# TODO(rechen): Respect type parameters' bounds and constraints.
type_params = self._type_params + [pytd.TypeParameter("typing.AnyStr")]
inserter = _InsertTypeParameters(type_params)
# Records base_type's template without actually inserting type parameters.
base_type.Visit(inserter)
if inserter.inserted:
return self._type_macro(base_type, inserter.inserted, parameters)
if parameters is not None:
if (len(parameters) > 1 and isinstance(base_type, pytd.NamedType) and
base_type.name == "typing.Optional"):
raise ParseError("Too many options to %s" % base_type.name)
return self._parameterized_type(base_type, parameters)
else:
if (isinstance(base_type, pytd.NamedType) and
base_type.name in _TYPING_SETS):
raise ParseError("Missing options to %s" % base_type.name)
return base_type
def _type_macro(self, base_type, template, parameters):
if parameters is None:
mapping = {t: pytd.AnythingType() for t in template}
elif len(template) != len(parameters):
raise ParseError("%s expected %d parameters, got %s" % (
pytd_utils.Print(base_type), len(template), len(parameters)))
else:
mapping = dict(zip(template, parameters))
return base_type.Visit(visitors.ReplaceTypes(mapping))
def _matches_full_name(self, t, full_name):
"""Whether t.name matches full_name in format {module}.{member}."""
expected_module_name, expected_name = full_name.rsplit(".", 1)
if self._ast_name == expected_module_name:
# full_name is inside the current module, so check for the name without
# the module prefix.
return t.name == expected_name
elif "." not in t.name:
# full_name is not inside the current module, so a local type can't match.
return False
else:
module_name, name = t.name.rsplit(".", 1)
if module_name in self._aliases:
# Adjust the module name if it has been aliased with `import x as y`.
# See test_pyi.PYITest.testTypingAlias.
module = self._aliases[module_name].type
if isinstance(module, pytd.Module):
module_name = module.module_name
expected_module_names = {
expected_module_name,
parser_constants.EXTERNAL_NAME_PREFIX + expected_module_name}
return module_name in expected_module_names and name == expected_name
def _is_tuple_base_type(self, t):
return isinstance(t, pytd.NamedType) and (
t.name == "tuple" or self._matches_full_name(t, "__builtin__.tuple") or
self._matches_full_name(t, "typing.Tuple"))
def _is_callable_base_type(self, t):
return (isinstance(t, pytd.NamedType) and
self._matches_full_name(t, "typing.Callable"))
def _is_literal_base_type(self, t):
return isinstance(t, pytd.NamedType) and (
self._matches_full_name(t, "typing.Literal") or
self._matches_full_name(t, "typing_extensions.Literal"))
def _heterogeneous_tuple(self, base_type, parameters):
if parameters:
return pytd.TupleType(base_type=base_type, parameters=parameters)
else:
return pytd.GenericType(base_type=base_type,
parameters=(pytd.NothingType(),))
def _is_empty_tuple(self, t):
return (isinstance(t, pytd.GenericType) and
self._is_tuple_base_type(t.base_type) and
t.parameters == (pytd.NothingType(),))
def _is_heterogeneous_tuple(self, t):
# An empty tuple is represented as a GenericType rather than a TupleType,
# but we still consider it heterogeneous because we know exactly what the
# parameters are (there are none).
return isinstance(t, pytd.TupleType) or self._is_empty_tuple(t)
def _is_any(self, t):
return isinstance(t, pytd.AnythingType) or t == pytd.NamedType("typing.Any")
def _is_none(self, t):
return isinstance(t, pytd.NamedType) and t.name in ("None", "NoneType")
def _is_parameterized_protocol(self, t):
return (isinstance(t, pytd.GenericType) and
t.base_type.name == "typing.Protocol")
def _parameterized_type(self, base_type, parameters):
"""Return a parameterized type."""
if self._is_literal_base_type(base_type):
literal_parameters = []
for p in parameters:
if self._is_none(p):
literal_parameters.append(p)
elif isinstance(p, pytd.NamedType) and p.name not in ("True", "False"):
# TODO(b/123775699): support enums.
literal_parameters.append(pytd.AnythingType())
else:
literal_parameters.append(pytd.Literal(p))
return pytd_utils.JoinTypes(literal_parameters)
elif any(isinstance(p, (int, str)) for p in parameters):
parameters = ", ".join(
str(p) if isinstance(p, (int, str)) else "_" for p in parameters)
raise ParseError(
"%s[%s] not supported" % (pytd_utils.Print(base_type), parameters))
elif self._is_any(base_type):
return pytd.AnythingType()
elif len(parameters) == 2 and parameters[-1] is self.ELLIPSIS and (
not self._is_callable_base_type(base_type)):
element_type = parameters[0]
if element_type is self.ELLIPSIS:
raise ParseError("[..., ...] not supported")
return pytd.GenericType(base_type=base_type, parameters=(element_type,))
else:
parameters = tuple(pytd.AnythingType() if p is self.ELLIPSIS else p
for p in parameters)
if self._is_tuple_base_type(base_type):
return self._heterogeneous_tuple(base_type, parameters)
elif (self._is_callable_base_type(base_type) and
self._is_heterogeneous_tuple(parameters[0])):
if len(parameters) > 2:
raise ParseError(
"Expected 2 parameters to Callable, got %d" % len(parameters))
if len(parameters) == 1:
# We're usually happy to treat omitted parameters as "Any", but we
# need a return type for CallableType, or we wouldn't know whether the
# last parameter is an argument or return type.
parameters += (pytd.AnythingType(),)
if self._is_empty_tuple(parameters[0]):
parameters = parameters[1:]
else:
parameters = parameters[0].parameters + parameters[1:]
return pytd.CallableType(base_type=base_type, parameters=parameters)
else:
assert parameters
if (self._is_callable_base_type(base_type) and
not self._is_any(parameters[0])):
raise ParseError(
"First argument to Callable must be a list of argument types")
return pytd.GenericType(base_type=base_type, parameters=parameters)
def new_union_type(self, types):
"""Return a new UnionType composed of the specified types."""
# UnionType flattens any contained UnionType's.
return pytd.UnionType(tuple(types))
def new_intersection_type(self, types):
"""Return a new IntersectionType composed of the specified types."""
# IntersectionType flattens any contained IntersectionType's.
return pytd.IntersectionType(tuple(types))
def new_function(
self, decorators, is_async, name, param_list, return_type, body):
"""Return a _NameAndSig object for the function.
Args:
decorators: List of decorator names.
is_async: Whether this is an async function.
name: Name of function.
param_list: List of parameters, where a paremeter is either a tuple
(name, type, default) or the ELLIPSIS special object. See
_validate_params for a more detailed description of allowed parameters.
return_type: A pytd type object.
body: ?
Returns:
A _NameAndSig object.
Raises:
ParseError: if any validity checks fail.
"""
if name == "__init__" and isinstance(return_type, pytd.AnythingType):
ret = pytd.NamedType("NoneType")
elif is_async:
base = pytd.NamedType("typing.Coroutine")
params = (pytd.NamedType("typing.Any"),
pytd.NamedType("typing.Any"),
return_type)
ret = pytd.GenericType(base, params)
else:
ret = return_type
params = _validate_params(param_list)
exceptions = []
mutators = []
for stmt in body:
if isinstance(stmt, pytd.Type):
exceptions.append(stmt) # raise stmt
continue
assert isinstance(stmt, tuple) and len(stmt) == 2, stmt
mutators.append(_Mutator(stmt[0], stmt[1]))
signature = pytd.Signature(params=tuple(params.required), return_type=ret,
starargs=params.starargs,
starstarargs=params.starstarargs,
exceptions=tuple(exceptions), template=())
for mutator in mutators:
try:
signature = signature.Visit(mutator)
except NotImplementedError as e:
raise ParseError(utils.message(e))
if not mutator.successful:
raise ParseError("No parameter named %s" % mutator.name)
# Remove ignored decorators, raise ParseError for invalid decorators.
decorators = {d for d in decorators if _keep_decorator(d)}
# Extract out abstractmethod and coroutine decorators, there should be at
# most one remaining decorator.
def _check_decorator(decorators, decorator_set):
exists = any(x in decorators for x in decorator_set)
if exists:
decorators -= decorator_set
return exists
is_abstract = _check_decorator(
decorators, {"abstractmethod", "abc.abstractmethod"})
is_coroutine = _check_decorator(
decorators, {"coroutine", "asyncio.coroutine", "coroutines.coroutine"})
if len(decorators) > 1:
raise ParseError("Too many decorators for %s" % name)
decorator, = decorators if decorators else (None,)
return _NameAndSig(name=name, signature=signature,
decorator=decorator,
is_abstract=is_abstract,
is_coroutine=is_coroutine)