forked from localchart/mini-pysonar
/
pysonar.py
executable file
·1353 lines (1100 loc) · 41.3 KB
/
pysonar.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
# pysonar.py - a Python version of PySonar static analyzer for Python
# Copyright (C) 2011 Yin Wang (yinwang0@gmail.com)
import sys
import re
import ast
from ast import *
from lists import lookup, nil, ext, first, rest, assq, reverse, maplist,\
SimplePair, append
from collections import defaultdict
import os
import logging
from functools import partial
logging.basicConfig(filename="_pysonar.log", level=logging.DEBUG)
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.WARN)
def _log(fn, *args):
fn(' '.join(map(str, args)))
debug = partial(_log, logger.debug)
warn = partial(_log, logger.warn)
error = partial(_log, logger.error)
####################################################################
## global parameters
####################################################################
IS = isinstance
# dict[str, list]
# class/type name -> list[tuple[
# list[list[initializator arguments]],
# list[list[call arguments]],
# ENV
# ]]
MYDICT = defaultdict(list)
PYTHONPATH = []
####################################################################
## utilities
####################################################################
def iter_fields(node):
"""Iterate over all existing fields, excluding 'ctx'."""
for field in node._fields:
try:
if field != 'ctx':
yield field, getattr(node, field)
except AttributeError:
pass
# for debugging
def dp(s):
return map(dump, parse(s).body)
def pf(file_):
import cProfile
cProfile.run("sonar(" + file_ + ")", sort="cumulative")
####################################################################
## test on AST nodes
####################################################################
def isAtom(x):
return type(x) in [int, str, bool, float]
def isDef(node):
return IS(node, FunctionDef) or IS(node, ClassDef)
##################################################################
# per-node information store
##################################################################
history = {}
def putInfo(exp, item):
if exp in history:
seen = history[exp]
else:
seen = []
history[exp] = union([seen, item])
def getInfo(exp):
return history[exp]
##################################################################
# types used by pysonar
##################################################################
class Type:
pass
nUnknown = 0
class UnknownType(Type):
def __init__(self, obj):
assert obj is not None
self.obj = obj
global nUnknown
nUnknown += 1
def __repr__(self):
return "Unknown(%r)" % self.obj
def __hash__(self):
return hash(self.obj.lineno)
def __eq__(self, other):
if IS(other, UnknownType):
return self.obj.lineno == other.obj.lineno
return False
def __ne__(self, other):
return not self.__eq__(other)
class PrimType(Type):
def __init__(self, name):
self.name = name
def __repr__(self):
return str(self.name)
def __eq__(self, other):
if IS(other, PrimType):
return self.name == other.name
else:
return False
def __ne__(self, other):
return not self.__eq__(other)
class ClassType(Type):
def __init__(self, name, bases, body, env, ast_def_class):
'@types: str, list[ast.AST], list[ast.AST], LinkedList'
assert IS(name, str)
self.name = name
self.env = env
self.attrs = {}
self.ast = ast_def_class
for base in bases:
if IS(base, Attribute) or base.id == 'object':
continue
baseClasses = lookup(base.id, env)
if (baseClasses and len(baseClasses) == 1
and IS(baseClasses[0], ClassType)):
# limit to one possible type
baseClass = baseClasses[0]
for key, val in baseClass.attrs.iteritems():
self.attrs[key] = val
else:
logger.error('Can\'t infer base of %s: %s %s'
% (name, baseClasses, base.id))
self.__saveClassAttrs(body)
def __saveClassAttrs(self, body):
env = close(body, nil) # {Name.id -> (Closure | ClassType)}
for pair in env:
# Closure's env will be updated, when invoking AttrType
self.attrs[pair.fst] = pair.snd
def __repr__(self):
return "ClassType:" + str(self.ast)
def __eq__(self, other):
if IS(other, ClassType):
return self.name == other.name
else:
return False
def __hash__(self):
return hash(self.ast)
def __ne__(self, other):
return not self.__eq__(other)
class ObjType(Type):
def __init__(self, classtype, ctorargs, env, ast):
'@types: ClassType, list[Type], LinkedList, ast'
self.classtype = classtype
self.attrs = {}
# copy class attributes over to instance
for name, attr in self.classtype.attrs.iteritems():
self.attrs[name] = attr
self.ctorargs = ctorargs
self.ast = ast
def __repr__(self):
return ("'" + str(self.classtype.name) + "' instance" # +", ctor:" +
#str(self.ctorargs) + ", attrs:" + str(self.attrs)
)
def __eq__(self, other):
if IS(other, ObjType):
return ((self.classtype == other.classtype) and
self.attrs == other.attrs)
else:
return False
def __ne__(self, other):
return not self.__eq__(other)
def __hash__(self):
return hash(self.ast)
class FuncType(Type):
def __init__(self, fromtype, totype):
self.fromtype = fromtype
self.totype = totype
def __repr__(self):
return str(self.fromtype) + " -> " + str(self.totype)
def __eq__(self, other):
return (IS(other, FuncType)
and (self.fromtype == other.fromtype)
and self.totype == other.totype)
def __ne__(self, other):
return not self.__eq__(other)
class AttrType(Type):
'''
This is an analog to Name, just for object attributes
Reference on object attribute value, so binds object with this value while
name is determined in the context (or environment)
'''
def __init__(self, closures, o, objT):
'''@types: list[Closure], ObjType, ast.AST
@param: objT is a value of ast.Attribute
'''
# self.env = closure.env
assert IS(closures, list)
self.clo = closures
self.obj = o
self.objT = objT
def __repr__(self):
clo_repr = ','.join(map(str, self.clo))
return '(attr "%s", "%s")' % (self.obj, clo_repr)
def __eq__(self, other):
if IS(other, FuncType):
return (self.clo == other.clo)
else:
return False
def __ne__(self, other):
return not self.__eq__(other)
def __hash__(self):
return hash(tuple(self.clo)) + hash(self.objT)
class Closure(Type):
def __init__(self, func, env):
'@types: ast.FunctionDef, LinkedList'
self.func = func
self.env = env
self.defaults = []
def __repr__(self):
return str(self.func)
class TupleType(Type):
def __init__(self, elts):
self.elts = elts
def __repr__(self):
return "tup:" + str(self.elts)
def __eq__(self, other):
if IS(other, TupleType):
if len(self.elts) != len(other.elts):
return False
else:
for i in xrange(len(self.elts)):
if self.elts[i] != other.elts[i]:
return False
return True
else:
return False
def __ne__(self, other):
return not self.__eq__(other)
class ListType(Type):
def __init__(self, elts):
'@types: tuple'
self.elts = elts
def __repr__(self):
return "list:" + str(self.elts)
def __eq__(self, other):
return (IS(other, ListType)
and self.elts == other.elts)
def __hash__(self):
return hash(self.elts)
def __iter__(self):
return iter(self.elts)
def __ne__(self, other):
return not self.__eq__(other)
def flatten(list_of_lists):
# TODO: handle __iter__ and next()
flattened = []
for sublist in list_of_lists:
if not isinstance(sublist, TypeError):
try:
flattened.extend([i for i in sublist])
except TypeError:
flattened.append(sublist)
else:
flattened.append(sublist)
return flattened
class DictType(Type):
def __init__(self, dict_):
'@types: LinkedList'
self.dict = dict_
self.attrs = {'keys': [self.get_keys],
'iterkeys': [self.get_keys],
'values': [self.get_values],
'itervalues': [self.get_values],
'items': [self.get_items],
'iteritems': [self.get_items],
'get': [self.get_key]}
self.iter_operations = (self.get_keys, self.get_values, self.get_items)
# Since we are not infering body's,
# these functions should always return a list:
@staticmethod
def get_key(dict_, key, default=None):
'@types: LinkedList, ? -> list'
# potentially, any value can be returned
value = flatten([key_value_pair.snd for key_value_pair in dict_])
if default:
value.extend(default)
return value
@staticmethod
def get_keys(dict_):
'@types: LinkedList -> list'
return [[key_value_pair.fst for key_value_pair in dict_]]
@staticmethod
def get_values(dict_):
'@types: LinkedList -> list'
return [[key_value_pair.snd for key_value_pair in dict_]]
@staticmethod
def get_items(dict_):
'@types: LinkedList -> list'
return [[TupleType([[pair.fst], pair.snd]) for pair in dict_]]
def __repr__(self):
return "dict:" + str(self.dict)
# any hashable value can be used as keys
# any object can be used as values
# so we can know almost nothing about the dictionaries
def __eq__(self, other):
return IS(other, DictType)
def __ne__(self, other):
return not self.__eq__(other)
class UnionType(Type):
def __init__(self, elts):
self.elts = elts
def __repr__(self):
return "U:" + str(self.elts)
# singleton primtive types
contType = PrimType('cont') # continuation type
bottomType = PrimType('_|_') # non-terminating recursion
# need to rewrite this when we have recursive types
def typeEqual(t1, t2):
if IS(t1, list) and IS(t2, list):
for bd1 in t1:
if bd1 not in t2:
return False
return True
else:
return t1 == t2
def subtypeBindings(rec1, rec2):
def find(a, rec2):
for b in rec2:
if (first(a) == first(b)) and typeEqual(rest(a), rest(b)):
return True
return False
for a in rec1:
if not find(a, rec2):
return False
return True
def union(ts):
u = []
for t in ts:
if IS(t, list): # already a union (list)
for b in t:
if b not in u:
u.append(b)
else:
if t not in u:
u.append(t)
return u
####################################################################
## type inferencer
####################################################################
class Bind:
def __init__(self, typ, loc):
self.typ = typ
self.loc = loc
def __repr__(self):
return "(" + str(self.typ) + " <~~ " + str(self.loc) + ")"
def __iter__(self):
return BindIterator(self)
def __eq__(self, other):
return (IS(other, Bind) and
self.typ == other.typ and
self.loc == other.loc)
class BindIterator:
def __init__(self, p):
self.p = p
self.cur = 0
def next(self):
if self.cur == 2:
raise StopIteration
elif self.cur == 0:
self.cur += 1
return self.p.typ
else:
self.cur += 1
return self.p.loc
def typeOnly(bs):
return union(bs)
# test whether a type is in a union
def inUnion(t, u):
for t2 in u:
if t == t2:
return True
return False
def removeType(t, u):
return [x for x in u if x != t]
# combine two environments, make unions when necessary
# only assocs appear in both envs are preserved
# use a variable bound in only one branch will cause type error
def mergeEnv(env1, env2):
ret = nil
for p1 in env1:
p2 = assq(first(p1), env2)
if p2 != None:
ret = ext(first(p1), union([rest(p1), rest(p2)]), ret)
return ret
# compare both str's and Name's for equivalence, because
# keywords are str's (bad design of the ast)
def getId(x):
if IS(x, Name):
return x.id
else:
return x
def getName(x, lineno):
return Name(id=x, lineno=lineno)
def bind(target, infered_value, env):
if IS(target, Name) or IS(target, str):
u = infered_value
putInfo(target, u)
return ext(getId(target), u, env)
elif IS(target, Attribute):
ast_name = target.value
infered_targets = infer(ast_name, env, nil)
for obj in infered_targets:
if IS(obj, (ClassType, ObjType)):
obj.attrs[target.attr] = infered_value
elif IS(obj, AttrType):
obj.obj.attrs[target.attr] = infered_value
else:
error("Syntax error: wrong target type in assignment: ",
obj, type(obj))
return env
elif IS(target, Tuple) or IS(target, List):
infered_values = infered_value
target_to_value = defaultdict(list)
for infered_value in infered_values:
if IS(infered_value, TupleType) or IS(infered_value, List):
debug('infered key, value:', infered_value)
if len(target.elts) == len(infered_value.elts):
for i in xrange(len(infered_value.elts)):
target_to_value[target.elts[i]].extend(infered_value.elts[i])
elif len(target.elts) < len(infered_value.elts):
putInfo(target, ValueError('too many values to unpack'))
else:
putInfo(target, ValueError('too few values to unpack'))
else:
putInfo(target, TypeError('non-iterable object'))
for key, value in target_to_value.iteritems():
debug('binding %s to %s:' % (key, value))
env = bind(key, value, env)
return env
elif IS(target, ast.Subscript):
error("Syntax error: Subscript type is not supported in assignment: ",
target)
return env
else:
putInfo(target, SyntaxError("not assignable"))
return env
def onStack(call, args, stk):
for p1 in stk:
call2 = first(p1)
args2 = rest(p1)
if call == call2 and subtypeBindings(args, args2):
return True
return False
def saveMethodInvocationInfo(call, clo, env, stk):
'''
@types: ast.Call, ObjType, LinkedList, LinkedList -> None
'''
if call.args:
ctorargs = [a for a in clo.obj.ctorargs]
callargs = [infer(arg, env, stk) for arg in call.args]
# TODO save keywords
MYDICT[clo.obj.classtype.name].append((ctorargs, callargs, env))
def getMethodInvocationInfo():
return MYDICT
# invoke one closure
def invoke1(call, clo, env, stk):
'''@types: ast.Call, Callable, LinkedList, LinkedList -> ast.AST or Type
'''
if (clo == bottomType):
return [bottomType]
# Even if operator is not a closure, resolve the
# arguments for partial information.
if not IS(clo, (Closure, ClassType, AttrType)):
# infer arguments even if it is not callable
# (we don't know which method it is)
debug('Unknown function or method, infering arguments', call.args)
for a in call.args:
infer(a, env, stk)
for k in call.keywords:
infer(k.value, env, stk)
err = TypeError('calling non-callable', clo)
putInfo(call, err)
return [err]
if IS(clo, ClassType):
debug('creating instance of', clo)
ctorargs = [infer(arg, env, stk) for arg in call.args]
new_obj = ObjType(clo, ctorargs, clo.env, call)
init_closures = new_obj.attrs.get('__init__', [])
if len(init_closures):
# we don't really care about this name,
# we just don't want to collide with method's global symbols
# TODO: generate a special name,
# that would represent a temporary object
self_arg = get_self_arg_name(init_closures[0].func)
ref_to_init = AttrType(init_closures, new_obj, self_arg)
init_env = ext(self_arg.id, [new_obj], env)
invoke1(call, ref_to_init, init_env, stk)
return [new_obj]
if IS(clo, AttrType):
attr = clo
if IS(attr.obj, ObjType):
# add self to function call args
actualParams = list(call.args)
classtype = attr.obj.classtype
saveMethodInvocationInfo(call, attr, env, stk)
# TODO: @staticmethod, @classmethod
if classtype.name != 'module':
actualParams.insert(0, attr.objT)
types = []
for closure in attr.clo:
if IS(closure, Closure):
# Create new env for method
# On each call ClassType.env might be different
new_closure = Closure(closure.func, classtype.env)
debug('invoking method', closure.func.name,
'with args', call.args)
types.extend(invokeClosure(call, actualParams, new_closure,
env, stk))
elif IS(closure, ClassType):
types.extend(invoke1(call, closure, env, stk))
else:
types.append(TypeError("Callable type %s is not supported"
% closure))
return types
elif IS(attr.obj, DictType):
types = []
for closure in attr.clo:
if closure in attr.obj.iter_operations:
types.extend(closure(attr.obj.dict))
else:
# we take the first version of infered arguments
# but ideally all must be processed
infered_args = [infer(arg, env, stk) for arg in call.args]
types.extend(closure(attr.obj.dict, *infered_args))
return types
else:
err = TypeError('AttrType object is not supported for the invoke',
attr)
putInfo(call, err)
return [err]
return invokeClosure(call, call.args, clo, env, stk)
def get_self_arg_name(fn_def):
''' Expecting to get ast.Name with id, for instance, self
@types: ast.FunctionDef -> ast.Name
'''
if not fn_def.args.args:
raise ValueError("Bound method has at least one parameter - self")
arg = fn_def.args.args[0]
if IS(arg, ast.Name):
return arg
msg = "Method definition %s doesn't have self as first argument"
raise ValueError(msg % fn_def.name)
def invokeClosure(call, actualParams, clo, env, stk):
'''
@types: ast.Call, list[ast.AST], Closure, LinkedList, LinkedList -> list[Type]
'''
debug('invoking closure', clo.func, 'with args', actualParams)
debug(clo.func.body)
func = clo.func
fenv = clo.env
pos = nil
kwarg = nil
# bind positionals first
poslen = min(len(func.args.args), len(actualParams))
for i in xrange(poslen):
t = infer(actualParams[i], env, stk)
pos = bind(func.args.args[i], t, pos)
# put extra positionals into vararg if provided
# report error and go on otherwise
if len(actualParams) > len(func.args.args):
if func.args.vararg == None:
err = TypeError('excess arguments to function')
putInfo(call, err)
return [err]
else:
ts = []
for i in xrange(len(func.args.args), len(actualParams)):
t = infer(actualParams[i], env, stk)
ts = ts + t
pos = bind(func.args.vararg, ts, pos)
# bind keywords, collect kwarg
ids = map(getId, func.args.args)
for k in call.keywords:
ts = infer(k.value, env, stk)
tloc1 = lookup(k.arg, pos)
if tloc1 != None:
putInfo(call, TypeError('multiple values for keyword argument',
k.arg, tloc1))
elif k.arg not in ids:
kwarg = bind(k.arg, ts, kwarg)
else:
pos = bind(k.arg, ts, pos)
# put extras in kwarg or report them
# bind call.keywords to func.args.kwarg
if kwarg != nil:
if func.args.kwarg != None:
pos = bind(func.args.kwarg, [DictType(reverse(kwarg))], pos)
else:
putInfo(call, TypeError("unexpected keyword arguements", kwarg))
elif func.args.kwarg != None:
pos = bind(func.args.kwarg, [DictType(nil)], pos)
# bind defaults, avoid overwriting bound vars
# types for defaults are already inferred when the function was defined
i = len(func.args.args) - len(func.args.defaults)
_ = len(func.args.args)
for j in xrange(len(clo.defaults)):
tloc = lookup(getId(func.args.args[i]), pos)
if tloc == None:
pos = bind(func.args.args[i], clo.defaults[j], pos)
i += 1
# finish building the input type
fromtype = maplist(lambda p: SimplePair(first(p), typeOnly(rest(p))), pos)
# check whether the same call site is on stack with same input types
# if so, we are back to a loop, terminate
if onStack(call, fromtype, stk):
return [bottomType]
# push the call site onto the stack and analyze the function body
stk = ext(call, fromtype, stk)
fenv = append(pos, fenv)
to = infer(func.body, fenv, stk)
# record the function type
putInfo(func, FuncType(reverse(fromtype), to))
return to
# invoke a union of closures. call invoke1 on each of them and collect
# their return types into a union
def invoke(call, env, stk):
clos = infer(call.func, env, stk)
totypes = []
for clo in clos:
t = invoke1(call, clo, env, stk)
totypes = totypes + t
return totypes
# pre-bind names to functions in sequences
def close(code_block, env):
'''@types: list[ast.AST], LinkedList -> LinkedList'''
for e in code_block:
if IS(e, FunctionDef):
c = Closure(e, nil)
env = ext(e.name, [c], env)
elif IS(e, ClassDef):
c = ClassType(e.name, e.bases, e.body, nil, e)
env = ext(e.name, [c], env)
# here we also need Import and Assign
# Assign is complicated
return env
def isTerminating(t):
return not inUnion(contType, t)
def finalize(t):
return removeType(contType, t)
# infer a sequence of statements
def inferSeq(exp, env, stk):
debug('Infering sequence', exp)
if exp == []: # reached end without return
return ([contType], env)
e = exp[0]
if IS(e, If):
_ = infer(e.test, env, stk)
(t1, env1) = inferSeq(e.body, close(e.body, env), stk)
(t2, env2) = inferSeq(e.orelse, close(e.orelse, env), stk)
if isTerminating(t1) and isTerminating(t2): # both terminates
for e2 in exp[1:]:
putInfo(e2, TypeError('unreachable code'))
return (union([t1, t2]), env)
elif isTerminating(t1) and not isTerminating(t2): # t1 terminates
(t3, env3) = inferSeq(exp[1:], env2, stk)
t2 = finalize(t2)
return (union([t1, t2, t3]), env3)
elif not isTerminating(t1) and isTerminating(t2): # t2 terminates
(t3, env3) = inferSeq(exp[1:], env1, stk)
t1 = finalize(t1)
return (union([t1, t2, t3]), env3)
else: # both non-terminating
(t3, env3) = inferSeq(exp[1:], mergeEnv(env1, env2), stk)
t1 = finalize(t1)
t2 = finalize(t2)
return (union([t1, t2, t3]), env3)
elif IS(e, While):
# todo evaluate test
(t1, env1) = inferSeq(e.body, close(e.body, env), stk)
(t2, env2) = inferSeq(e.orelse, close(e.orelse, env), stk)
if isTerminating(t1) and isTerminating(t2): # both terminates
for e2 in exp[1:]:
putInfo(e2, TypeError('unreachable code'))
return (union([t1, t2]), env)
elif isTerminating(t1) and not isTerminating(t2): # t1 terminates
(t3, env3) = inferSeq(exp[1:], env2, stk)
t2 = finalize(t2)
return (union([t1, t2, t3]), env3)
elif not isTerminating(t1) and isTerminating(t2): # t2 terminates
(t3, env3) = inferSeq(exp[1:], env1, stk)
t1 = finalize(t1)
return (union([t1, t2, t3]), env3)
else: # both non-terminating
(t3, env3) = inferSeq(exp[1:], mergeEnv(env1, env2), stk)
t1 = finalize(t1)
t2 = finalize(t2)
return (union([t1, t2, t3]), env3)
elif IS(e, For):
values = infer(e.iter, env, stk)
value = flatten(values)
env = bind(e.target, value, env)
(t1, env1) = inferSeq(e.body, close(e.body, env), stk)
(t2, env2) = inferSeq(e.orelse, close(e.orelse, env), stk)
if isTerminating(t1) and isTerminating(t2): # both terminates
for e2 in exp[1:]:
putInfo(e2, TypeError('unreachable code'))
return (union([t1, t2]), env)
elif isTerminating(t1) and not isTerminating(t2): # t1 terminates
(t3, env3) = inferSeq(exp[1:], env2, stk)
t2 = finalize(t2)
return (union([t1, t2, t3]), env3)
elif not isTerminating(t1) and isTerminating(t2): # t2 terminates
(t3, env3) = inferSeq(exp[1:], env1, stk)
t1 = finalize(t1)
return (union([t1, t2, t3]), env3)
else: # both non-terminating
(t3, env3) = inferSeq(exp[1:], mergeEnv(env1, env2), stk)
t1 = finalize(t1)
t2 = finalize(t2)
return (union([t1, t2, t3]), env3)
elif IS(e, Assign):
t = infer(e.value, env, stk)
for x in e.targets:
env = bind(x, t, env)
return inferSeq(exp[1:], env, stk)
elif IS(e, AugAssign):
t = infer(e.value, env, stk)
env = bind(e.target, t, env)
return inferSeq(exp[1:], env, stk)
elif IS(e, FunctionDef):
cs = lookup(e.name, env)
if not cs:
debug('Function %s not found in scope %s' % (e.name, env))
for c in cs:
c.env = env # create circular env to support recursion
for d in e.args.defaults: # infer types for default arguments
dt = infer(d, env, stk)
c.defaults.append(dt)
return inferSeq(exp[1:], env, stk)
elif IS(e, Return):
if e.value is None:
t1 = [PrimType(None)]
else:
t1 = infer(e.value, env, stk)
(t2, env2) = inferSeq(exp[1:], env, stk)
for e2 in exp[1:]:
putInfo(e2, TypeError('unreachable code'))
return (t1, env)
elif IS(e, Expr):
t1 = infer(e.value, env, stk)
return inferSeq(exp[1:], env, stk)
elif IS(e, ImportFrom):
_, module_symbols = get_module_symbols(e.module)
for module_name in e.names:
name_to_import = module_name.name
name_import_as = module_name.asname or name_to_import
module_symbol = lookup(name_to_import, module_symbols)
env = bind(getName(name_import_as, e.lineno), module_symbol, env)
return inferSeq(exp[1:], env, stk)
elif IS(e, Import):
for module_name in e.names:
name_to_import = module_name.name
module, module_env = get_module_symbols(name_to_import)
name_import_as = module_name.asname or module_name.name
module_class = ClassType('module', [], module.body, module_env, e)
module_obj = [ObjType(module_class, [], nil, e)]
env = bind(getName(name_import_as, e.lineno), module_obj, env)
return inferSeq(exp[1:], env, stk)
elif IS(e, ClassDef):
cs = lookup(e.name, env)
if not cs:
debug('Class def %s not found in scope %s' % (e.name, env))
for c in cs:
c.env = env
(t2, env2) = inferSeq(exp[1:], env, stk)
return (t2, env2)
elif IS(e, Break):
return inferSeq(exp[1:], env, stk)
elif IS(e, Continue):
return inferSeq(exp[1:], env, stk)
elif IS(e, TryExcept):
(t1, env1) = inferSeq(e.body, close(e.body, env), stk)
(t2, env2) = inferSeq(e.orelse, close(e.orelse, env), stk)
(_, _) = inferSeq(e.handlers, close(e.handlers, env), stk)
if isTerminating(t1) and isTerminating(t2): # both terminates
for e2 in exp[1:]:
putInfo(e2, TypeError('unreachable code'))
return (union([t1, t2]), env)
elif isTerminating(t1) and not isTerminating(t2): # t1 terminates
(t3, env3) = inferSeq(exp[1:], env2, stk)
t2 = finalize(t2)
return (union([t1, t2, t3]), env3)
elif not isTerminating(t1) and isTerminating(t2): # t2 terminates
(t3, env3) = inferSeq(exp[1:], env1, stk)
t1 = finalize(t1)
return (union([t1, t2, t3]), env3)
else: # both non-terminating
(t3, env3) = inferSeq(exp[1:], mergeEnv(env1, env2), stk)
t1 = finalize(t1)
t2 = finalize(t2)
return (union([t1, t2, t3]), env3)
elif IS(e, TryFinally):
(t1, env1) = inferSeq(e.body, close(e.body, env), stk)
(t2, env2) = inferSeq(e.finalbody, close(e.finalbody, env), stk)
if isTerminating(t1) and isTerminating(t2): # both terminates
for e2 in exp[1:]:
putInfo(e2, TypeError('unreachable code'))
return (union([t1, t2]), env)
elif isTerminating(t1) and not isTerminating(t2): # t1 terminates
(t3, env3) = inferSeq(exp[1:], env2, stk)
t2 = finalize(t2)
return (union([t1, t2, t3]), env3)
elif not isTerminating(t1) and isTerminating(t2): # t2 terminates
(t3, env3) = inferSeq(exp[1:], env1, stk)
t1 = finalize(t1)