-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
Copy pathir.py
1702 lines (1401 loc) · 51 KB
/
ir.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
from collections import defaultdict
import copy
import itertools
import os
import linecache
import pprint
import re
import sys
import operator
from types import FunctionType, BuiltinFunctionType
from functools import total_ordering
from io import StringIO
from numba.core import errors, config
from numba.core.utils import (BINOPS_TO_OPERATORS, INPLACE_BINOPS_TO_OPERATORS,
UNARY_BUITINS_TO_OPERATORS, OPERATORS_TO_BUILTINS)
from numba.core.errors import (NotDefinedError, RedefinedError,
VerificationError, ConstantInferenceError)
from numba.core import consts
# terminal color markup
_termcolor = errors.termcolor()
class Loc(object):
"""Source location
"""
_defmatcher = re.compile(r'def\s+(\w+)')
def __init__(self, filename, line, col=None, maybe_decorator=False):
""" Arguments:
filename - name of the file
line - line in file
col - column
maybe_decorator - Set to True if location is likely a jit decorator
"""
self.filename = filename
self.line = line
self.col = col
self.lines = None # the source lines from the linecache
self.maybe_decorator = maybe_decorator
def __eq__(self, other):
# equivalence is solely based on filename, line and col
if type(self) is not type(other): return False
if self.filename != other.filename: return False
if self.line != other.line: return False
if self.col != other.col: return False
return True
def __ne__(self, other):
return not self.__eq__(other)
@classmethod
def from_function_id(cls, func_id):
return cls(func_id.filename, func_id.firstlineno, maybe_decorator=True)
def __repr__(self):
return "Loc(filename=%s, line=%s, col=%s)" % (self.filename,
self.line, self.col)
def __str__(self):
if self.col is not None:
return "%s (%s:%s)" % (self.filename, self.line, self.col)
else:
return "%s (%s)" % (self.filename, self.line)
def _find_definition(self):
# try and find a def, go backwards from error line
fn_name = None
lines = self.get_lines()
for x in reversed(lines[:self.line - 1]):
# the strip and startswith is to handle user code with commented out
# 'def' or use of 'def' in a docstring.
if x.strip().startswith('def '):
fn_name = x
break
return fn_name
def _raw_function_name(self):
defn = self._find_definition()
if defn:
m = self._defmatcher.match(defn.strip())
if m:
return m.groups()[0]
# Probably exec(<string>) or REPL.
return None
def get_lines(self):
if self.lines is None:
path = self._get_path()
# Avoid reading from dynamic string. They are most likely
# overridden. Problem started with Python 3.13. "<string>" seems
# to be something from multiprocessing.
lns = [] if path == "<string>" else linecache.getlines(path)
self.lines = lns
return self.lines
def _get_path(self):
path = None
try:
# Try to get a relative path
# ipython/jupyter input just returns as self.filename
path = os.path.relpath(self.filename)
except ValueError:
# Fallback to absolute path if error occurred in getting the
# relative path.
# This may happen on windows if the drive is different
path = os.path.abspath(self.filename)
return path
def strformat(self, nlines_up=2):
lines = self.get_lines()
use_line = self.line
if self.maybe_decorator:
# try and sort out a better `loc`, if it's suspected that this loc
# points at a jit decorator by virtue of
# `__code__.co_firstlineno`
# get lines, add a dummy entry at the start as lines count from
# 1 but list index counts from 0
tmplines = [''] + lines
if lines and use_line and 'def ' not in tmplines[use_line]:
# look forward 10 lines, unlikely anyone managed to stretch
# a jit call declaration over >10 lines?!
min_line = max(0, use_line)
max_line = use_line + 10
selected = tmplines[min_line : max_line]
index = 0
for idx, x in enumerate(selected):
if 'def ' in x:
index = idx
break
use_line = use_line + index
ret = [] # accumulates output
if lines and use_line > 0:
def count_spaces(string):
spaces = 0
for x in itertools.takewhile(str.isspace, str(string)):
spaces += 1
return spaces
# A few places in the code still use no `loc` or default to line 1
# this is often in places where exceptions are used for the purposes
# of flow control. As a result max is in use to prevent slice from
# `[negative: positive]`
selected = lines[max(0, use_line - nlines_up):use_line]
# see if selected contains a definition
def_found = False
for x in selected:
if 'def ' in x:
def_found = True
# no definition found, try and find one
if not def_found:
# try and find a def, go backwards from error line
fn_name = None
for x in reversed(lines[:use_line - 1]):
if 'def ' in x:
fn_name = x
break
if fn_name:
ret.append(fn_name)
spaces = count_spaces(x)
ret.append(' '*(4 + spaces) + '<source elided>\n')
if selected:
ret.extend(selected[:-1])
ret.append(_termcolor.highlight(selected[-1]))
# point at the problem with a caret
spaces = count_spaces(selected[-1])
ret.append(' '*(spaces) + _termcolor.indicate("^"))
# if in the REPL source may not be available
if not ret:
if not lines:
ret = "<source missing, REPL/exec in use?>"
elif use_line <= 0:
ret = "<source line number missing>"
err = _termcolor.filename('\nFile "%s", line %d:')+'\n%s'
tmp = err % (self._get_path(), use_line, _termcolor.code(''.join(ret)))
return tmp
def with_lineno(self, line, col=None):
"""
Return a new Loc with this line number.
"""
return type(self)(self.filename, line, col)
def short(self):
"""
Returns a short string
"""
shortfilename = os.path.basename(self.filename)
return "%s:%s" % (shortfilename, self.line)
# Used for annotating errors when source location is unknown.
unknown_loc = Loc("unknown location", 0, 0)
@total_ordering
class SlotEqualityCheckMixin(object):
# some ir nodes are __dict__ free using __slots__ instead, this mixin
# should not trigger the unintended creation of __dict__.
__slots__ = tuple()
def __eq__(self, other):
if type(self) is type(other):
for name in self.__slots__:
if getattr(self, name) != getattr(other, name):
return False
else:
return True
return False
def __le__(self, other):
return str(self) <= str(other)
def __hash__(self):
return id(self)
@total_ordering
class EqualityCheckMixin(object):
""" Mixin for basic equality checking """
def __eq__(self, other):
if type(self) is type(other):
def fixup(adict):
bad = ('loc', 'scope')
d = dict(adict)
for x in bad:
d.pop(x, None)
return d
d1 = fixup(self.__dict__)
d2 = fixup(other.__dict__)
if d1 == d2:
return True
return False
def __le__(self, other):
return str(self) < str(other)
def __hash__(self):
return id(self)
class VarMap(object):
def __init__(self):
self._con = {}
def define(self, name, var):
if name in self._con:
raise RedefinedError(name)
else:
self._con[name] = var
def get(self, name):
try:
return self._con[name]
except KeyError:
raise NotDefinedError(name)
def __contains__(self, name):
return name in self._con
def __len__(self):
return len(self._con)
def __repr__(self):
return pprint.pformat(self._con)
def __hash__(self):
return hash(self.name)
def __iter__(self):
return self._con.iterkeys()
def __eq__(self, other):
if type(self) is type(other):
# check keys only, else __eq__ ref cycles, scope -> varmap -> var
return self._con.keys() == other._con.keys()
return False
def __ne__(self, other):
return not self.__eq__(other)
class AbstractRHS(object):
"""Abstract base class for anything that can be the RHS of an assignment.
This class **does not** define any methods.
"""
class Inst(EqualityCheckMixin, AbstractRHS):
"""
Base class for all IR instructions.
"""
def list_vars(self):
"""
List the variables used (read or written) by the instruction.
"""
raise NotImplementedError
def _rec_list_vars(self, val):
"""
A recursive helper used to implement list_vars() in subclasses.
"""
if isinstance(val, Var):
return [val]
elif isinstance(val, Inst):
return val.list_vars()
elif isinstance(val, (list, tuple)):
lst = []
for v in val:
lst.extend(self._rec_list_vars(v))
return lst
elif isinstance(val, dict):
lst = []
for v in val.values():
lst.extend(self._rec_list_vars(v))
return lst
else:
return []
class Stmt(Inst):
"""
Base class for IR statements (instructions which can appear on their
own in a Block).
"""
# Whether this statement ends its basic block (i.e. it will either jump
# to another block or exit the function).
is_terminator = False
# Whether this statement exits the function.
is_exit = False
def list_vars(self):
return self._rec_list_vars(self.__dict__)
class Terminator(Stmt):
"""
IR statements that are terminators: the last statement in a block.
A terminator must either:
- exit the function
- jump to a block
All subclass of Terminator must override `.get_targets()` to return a list
of jump targets.
"""
is_terminator = True
def get_targets(self):
raise NotImplementedError(type(self))
class Expr(Inst):
"""
An IR expression (an instruction which can only be part of a larger
statement).
"""
def __init__(self, op, loc, **kws):
assert isinstance(op, str)
assert isinstance(loc, Loc)
self.op = op
self.loc = loc
self._kws = kws
def __getattr__(self, name):
if name.startswith('_'):
return Inst.__getattr__(self, name)
return self._kws[name]
def __setattr__(self, name, value):
if name in ('op', 'loc', '_kws'):
self.__dict__[name] = value
else:
self._kws[name] = value
@classmethod
def binop(cls, fn, lhs, rhs, loc):
assert isinstance(fn, BuiltinFunctionType)
assert isinstance(lhs, Var)
assert isinstance(rhs, Var)
assert isinstance(loc, Loc)
op = 'binop'
return cls(op=op, loc=loc, fn=fn, lhs=lhs, rhs=rhs,
static_lhs=UNDEFINED, static_rhs=UNDEFINED)
@classmethod
def inplace_binop(cls, fn, immutable_fn, lhs, rhs, loc):
assert isinstance(fn, BuiltinFunctionType)
assert isinstance(immutable_fn, BuiltinFunctionType)
assert isinstance(lhs, Var)
assert isinstance(rhs, Var)
assert isinstance(loc, Loc)
op = 'inplace_binop'
return cls(op=op, loc=loc, fn=fn, immutable_fn=immutable_fn,
lhs=lhs, rhs=rhs,
static_lhs=UNDEFINED, static_rhs=UNDEFINED)
@classmethod
def unary(cls, fn, value, loc):
assert isinstance(value, (str, Var, FunctionType))
assert isinstance(loc, Loc)
op = 'unary'
fn = UNARY_BUITINS_TO_OPERATORS.get(fn, fn)
return cls(op=op, loc=loc, fn=fn, value=value)
@classmethod
def call(cls, func, args, kws, loc, vararg=None, varkwarg=None, target=None):
assert isinstance(func, Var)
assert isinstance(loc, Loc)
op = 'call'
return cls(op=op, loc=loc, func=func, args=args, kws=kws,
vararg=vararg, varkwarg=varkwarg, target=target)
@classmethod
def build_tuple(cls, items, loc):
assert isinstance(loc, Loc)
op = 'build_tuple'
return cls(op=op, loc=loc, items=items)
@classmethod
def build_list(cls, items, loc):
assert isinstance(loc, Loc)
op = 'build_list'
return cls(op=op, loc=loc, items=items)
@classmethod
def build_set(cls, items, loc):
assert isinstance(loc, Loc)
op = 'build_set'
return cls(op=op, loc=loc, items=items)
@classmethod
def build_map(cls, items, size, literal_value, value_indexes, loc):
assert isinstance(loc, Loc)
op = 'build_map'
return cls(op=op, loc=loc, items=items, size=size,
literal_value=literal_value, value_indexes=value_indexes)
@classmethod
def pair_first(cls, value, loc):
assert isinstance(value, Var)
op = 'pair_first'
return cls(op=op, loc=loc, value=value)
@classmethod
def pair_second(cls, value, loc):
assert isinstance(value, Var)
assert isinstance(loc, Loc)
op = 'pair_second'
return cls(op=op, loc=loc, value=value)
@classmethod
def getiter(cls, value, loc):
assert isinstance(value, Var)
assert isinstance(loc, Loc)
op = 'getiter'
return cls(op=op, loc=loc, value=value)
@classmethod
def iternext(cls, value, loc):
assert isinstance(value, Var)
assert isinstance(loc, Loc)
op = 'iternext'
return cls(op=op, loc=loc, value=value)
@classmethod
def exhaust_iter(cls, value, count, loc):
assert isinstance(value, Var)
assert isinstance(count, int)
assert isinstance(loc, Loc)
op = 'exhaust_iter'
return cls(op=op, loc=loc, value=value, count=count)
@classmethod
def getattr(cls, value, attr, loc):
assert isinstance(value, Var)
assert isinstance(attr, str)
assert isinstance(loc, Loc)
op = 'getattr'
return cls(op=op, loc=loc, value=value, attr=attr)
@classmethod
def getitem(cls, value, index, loc):
assert isinstance(value, Var)
assert isinstance(index, Var)
assert isinstance(loc, Loc)
op = 'getitem'
fn = operator.getitem
return cls(op=op, loc=loc, value=value, index=index, fn=fn)
@classmethod
def typed_getitem(cls, value, dtype, index, loc):
assert isinstance(value, Var)
assert isinstance(loc, Loc)
op = 'typed_getitem'
return cls(op=op, loc=loc, value=value, dtype=dtype,
index=index)
@classmethod
def static_getitem(cls, value, index, index_var, loc):
assert isinstance(value, Var)
assert index_var is None or isinstance(index_var, Var)
assert isinstance(loc, Loc)
op = 'static_getitem'
fn = operator.getitem
return cls(op=op, loc=loc, value=value, index=index,
index_var=index_var, fn=fn)
@classmethod
def cast(cls, value, loc):
"""
A node for implicit casting at the return statement
"""
assert isinstance(value, Var)
assert isinstance(loc, Loc)
op = 'cast'
return cls(op=op, value=value, loc=loc)
@classmethod
def phi(cls, loc):
"""Phi node
"""
assert isinstance(loc, Loc)
return cls(op='phi', incoming_values=[], incoming_blocks=[], loc=loc)
@classmethod
def make_function(cls, name, code, closure, defaults, loc):
"""
A node for making a function object.
"""
assert isinstance(loc, Loc)
op = 'make_function'
return cls(op=op, name=name, code=code, closure=closure, defaults=defaults, loc=loc)
@classmethod
def null(cls, loc):
"""
A node for null value.
This node is not handled by type inference. It is only added by
post-typing passes.
"""
assert isinstance(loc, Loc)
op = 'null'
return cls(op=op, loc=loc)
@classmethod
def undef(cls, loc):
"""
A node for undefined value specifically from LOAD_FAST_AND_CLEAR opcode.
"""
assert isinstance(loc, Loc)
op = 'undef'
return cls(op=op, loc=loc)
@classmethod
def dummy(cls, op, info, loc):
"""
A node for a dummy value.
This node is a place holder for carrying information through to a point
where it is rewritten into something valid. This node is not handled
by type inference or lowering. It's presence outside of the interpreter
renders IR as illegal.
"""
assert isinstance(loc, Loc)
assert isinstance(op, str)
return cls(op=op, info=info, loc=loc)
def __repr__(self):
if self.op == 'call':
args = ', '.join(str(a) for a in self.args)
pres_order = self._kws.items() if config.DIFF_IR == 0 else sorted(self._kws.items())
kws = ', '.join('%s=%s' % (k, v) for k, v in pres_order)
vararg = '*%s' % (self.vararg,) if self.vararg is not None else ''
arglist = ', '.join(filter(None, [args, vararg, kws]))
return 'call %s(%s)' % (self.func, arglist)
elif self.op == 'binop':
lhs, rhs = self.lhs, self.rhs
if self.fn == operator.contains:
lhs, rhs = rhs, lhs
fn = OPERATORS_TO_BUILTINS.get(self.fn, self.fn)
return '%s %s %s' % (lhs, fn, rhs)
else:
pres_order = self._kws.items() if config.DIFF_IR == 0 else sorted(self._kws.items())
args = ('%s=%s' % (k, v) for k, v in pres_order)
return '%s(%s)' % (self.op, ', '.join(args))
def list_vars(self):
return self._rec_list_vars(self._kws)
def infer_constant(self):
raise ConstantInferenceError('%s' % self, loc=self.loc)
class SetItem(Stmt):
"""
target[index] = value
"""
def __init__(self, target, index, value, loc):
assert isinstance(target, Var)
assert isinstance(index, Var)
assert isinstance(value, Var)
assert isinstance(loc, Loc)
self.target = target
self.index = index
self.value = value
self.loc = loc
def __repr__(self):
return '%s[%s] = %s' % (self.target, self.index, self.value)
class StaticSetItem(Stmt):
"""
target[constant index] = value
"""
def __init__(self, target, index, index_var, value, loc):
assert isinstance(target, Var)
assert not isinstance(index, Var)
assert isinstance(index_var, Var)
assert isinstance(value, Var)
assert isinstance(loc, Loc)
self.target = target
self.index = index
self.index_var = index_var
self.value = value
self.loc = loc
def __repr__(self):
return '%s[%r] = %s' % (self.target, self.index, self.value)
class DelItem(Stmt):
"""
del target[index]
"""
def __init__(self, target, index, loc):
assert isinstance(target, Var)
assert isinstance(index, Var)
assert isinstance(loc, Loc)
self.target = target
self.index = index
self.loc = loc
def __repr__(self):
return 'del %s[%s]' % (self.target, self.index)
class SetAttr(Stmt):
def __init__(self, target, attr, value, loc):
assert isinstance(target, Var)
assert isinstance(attr, str)
assert isinstance(value, Var)
assert isinstance(loc, Loc)
self.target = target
self.attr = attr
self.value = value
self.loc = loc
def __repr__(self):
return '(%s).%s = %s' % (self.target, self.attr, self.value)
class DelAttr(Stmt):
def __init__(self, target, attr, loc):
assert isinstance(target, Var)
assert isinstance(attr, str)
assert isinstance(loc, Loc)
self.target = target
self.attr = attr
self.loc = loc
def __repr__(self):
return 'del (%s).%s' % (self.target, self.attr)
class StoreMap(Stmt):
def __init__(self, dct, key, value, loc):
assert isinstance(dct, Var)
assert isinstance(key, Var)
assert isinstance(value, Var)
assert isinstance(loc, Loc)
self.dct = dct
self.key = key
self.value = value
self.loc = loc
def __repr__(self):
return '%s[%s] = %s' % (self.dct, self.key, self.value)
class Del(Stmt):
def __init__(self, value, loc):
assert isinstance(value, str)
assert isinstance(loc, Loc)
self.value = value
self.loc = loc
def __str__(self):
return "del %s" % self.value
class Raise(Terminator):
is_exit = True
def __init__(self, exception, loc):
assert exception is None or isinstance(exception, Var)
assert isinstance(loc, Loc)
self.exception = exception
self.loc = loc
def __str__(self):
return "raise %s" % self.exception
def get_targets(self):
return []
class StaticRaise(Terminator):
"""
Raise an exception class and arguments known at compile-time.
Note that if *exc_class* is None, a bare "raise" statement is implied
(i.e. re-raise the current exception).
"""
is_exit = True
def __init__(self, exc_class, exc_args, loc):
assert exc_class is None or isinstance(exc_class, type)
assert isinstance(loc, Loc)
assert exc_args is None or isinstance(exc_args, tuple)
self.exc_class = exc_class
self.exc_args = exc_args
self.loc = loc
def __str__(self):
if self.exc_class is None:
return "<static> raise"
elif self.exc_args is None:
return "<static> raise %s" % (self.exc_class,)
else:
return "<static> raise %s(%s)" % (self.exc_class,
", ".join(map(repr, self.exc_args)))
def get_targets(self):
return []
class DynamicRaise(Terminator):
"""
Raise an exception class and some argument *values* unknown at compile-time.
Note that if *exc_class* is None, a bare "raise" statement is implied
(i.e. re-raise the current exception).
"""
is_exit = True
def __init__(self, exc_class, exc_args, loc):
assert exc_class is None or isinstance(exc_class, type)
assert isinstance(loc, Loc)
assert exc_args is None or isinstance(exc_args, tuple)
self.exc_class = exc_class
self.exc_args = exc_args
self.loc = loc
def __str__(self):
if self.exc_class is None:
return "<dynamic> raise"
elif self.exc_args is None:
return "<dynamic> raise %s" % (self.exc_class,)
else:
return "<dynamic> raise %s(%s)" % (self.exc_class,
", ".join(map(repr, self.exc_args)))
def get_targets(self):
return []
class TryRaise(Stmt):
"""A raise statement inside a try-block
Similar to ``Raise`` but does not terminate.
"""
def __init__(self, exception, loc):
assert exception is None or isinstance(exception, Var)
assert isinstance(loc, Loc)
self.exception = exception
self.loc = loc
def __str__(self):
return "try_raise %s" % self.exception
class StaticTryRaise(Stmt):
"""A raise statement inside a try-block.
Similar to ``StaticRaise`` but does not terminate.
"""
def __init__(self, exc_class, exc_args, loc):
assert exc_class is None or isinstance(exc_class, type)
assert isinstance(loc, Loc)
assert exc_args is None or isinstance(exc_args, tuple)
self.exc_class = exc_class
self.exc_args = exc_args
self.loc = loc
def __str__(self):
if self.exc_class is None:
return f"static_try_raise"
elif self.exc_args is None:
return f"static_try_raise {self.exc_class}"
else:
args = ", ".join(map(repr, self.exc_args))
return f"static_try_raise {self.exc_class}({args})"
class DynamicTryRaise(Stmt):
"""A raise statement inside a try-block.
Similar to ``DynamicRaise`` but does not terminate.
"""
def __init__(self, exc_class, exc_args, loc):
assert exc_class is None or isinstance(exc_class, type)
assert isinstance(loc, Loc)
assert exc_args is None or isinstance(exc_args, tuple)
self.exc_class = exc_class
self.exc_args = exc_args
self.loc = loc
def __str__(self):
if self.exc_class is None:
return f"dynamic_try_raise"
elif self.exc_args is None:
return f"dynamic_try_raise {self.exc_class}"
else:
args = ", ".join(map(repr, self.exc_args))
return f"dynamic_try_raise {self.exc_class}({args})"
class Return(Terminator):
"""
Return to caller.
"""
is_exit = True
def __init__(self, value, loc):
assert isinstance(value, Var), type(value)
assert isinstance(loc, Loc)
self.value = value
self.loc = loc
def __str__(self):
return 'return %s' % self.value
def get_targets(self):
return []
class Jump(Terminator):
"""
Unconditional branch.
"""
def __init__(self, target, loc):
assert isinstance(loc, Loc)
self.target = target
self.loc = loc
def __str__(self):
return 'jump %s' % self.target
def get_targets(self):
return [self.target]
class Branch(Terminator):
"""
Conditional branch.
"""
def __init__(self, cond, truebr, falsebr, loc):
assert isinstance(cond, Var)
assert isinstance(loc, Loc)
self.cond = cond
self.truebr = truebr
self.falsebr = falsebr
self.loc = loc
def __str__(self):
return 'branch %s, %s, %s' % (self.cond, self.truebr, self.falsebr)
def get_targets(self):
return [self.truebr, self.falsebr]
class Assign(Stmt):
"""
Assign to a variable.
"""
def __init__(self, value, target, loc):
assert isinstance(value, AbstractRHS)
assert isinstance(target, Var)
assert isinstance(loc, Loc)
self.value = value
self.target = target
self.loc = loc
def __str__(self):
return '%s = %s' % (self.target, self.value)
class Print(Stmt):
"""
Print some values.
"""
def __init__(self, args, vararg, loc):
assert all(isinstance(x, Var) for x in args)
assert vararg is None or isinstance(vararg, Var)
assert isinstance(loc, Loc)
self.args = tuple(args)
self.vararg = vararg
# Constant-inferred arguments
self.consts = {}
self.loc = loc
def __str__(self):
return 'print(%s)' % ', '.join(str(v) for v in self.args)
class Yield(Inst):
def __init__(self, value, loc, index):
assert isinstance(value, Var)
assert isinstance(loc, Loc)
self.value = value
self.loc = loc
self.index = index
def __str__(self):
return 'yield %s' % (self.value,)
def list_vars(self):
return [self.value]
class EnterWith(Stmt):
"""Enter a "with" context
"""
def __init__(self, contextmanager, begin, end, loc):
"""
Parameters
----------
contextmanager : IR value
begin, end : int
The beginning and the ending offset of the with-body.
loc : ir.Loc instance
Source location
"""
assert isinstance(contextmanager, Var)
assert isinstance(loc, Loc)
self.contextmanager = contextmanager
self.begin = begin
self.end = end
self.loc = loc
def __str__(self):
return 'enter_with {}'.format(self.contextmanager)
def list_vars(self):
return [self.contextmanager]
class PopBlock(Stmt):
"""Marker statement for a pop block op code"""
def __init__(self, loc):
assert isinstance(loc, Loc)
self.loc = loc
def __str__(self):
return 'pop_block'