/
ExpressionBases.py
1301 lines (968 loc) · 44.5 KB
/
ExpressionBases.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 2019, Kay Hayen, mailto:kay.hayen@gmail.com
#
# Part of "Nuitka", an optimizing Python compiler that is compatible and
# integrates with CPython, but also works on its own.
#
# 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.
#
""" Expression base classes.
These classes provide the generic base classes available for
expressions. They have a richer interface, mostly related to
abstract execution, and different from statements.
"""
from abc import abstractmethod
from nuitka.__past__ import long # pylint: disable=I0021,redefined-builtin
from nuitka.Constants import isCompileTimeConstantValue
from nuitka.Options import isFullCompat
from nuitka.PythonVersions import python_version
from .NodeBases import ChildrenHavingMixin, NodeBase
from .NodeMakingHelpers import (
getComputationResult,
makeConstantReplacementNode,
makeRaiseTypeErrorExceptionReplacementFromTemplateAndValue,
wrapExpressionWithNodeSideEffects,
wrapExpressionWithSideEffects,
)
from .shapes.BuiltinTypeShapes import ShapeTypeDict, ShapeTypeStr, ShapeTypeUnicode
from .shapes.StandardShapes import ShapeUnknown
class ExpressionBase(NodeBase):
# TODO: Maybe we can do this only for debug mode.
__slots__ = ("code_generated",)
def getTypeShape(self):
# Virtual method, pylint: disable=no-self-use
return ShapeUnknown
def getValueShape(self):
return self
def isCompileTimeConstant(self):
""" Has a value that we can use at compile time.
Yes or no. If it has such a value, simulations can be applied at
compile time and e.g. operations or conditions, or even calls may
be executed against it.
"""
# Virtual method, pylint: disable=no-self-use
return False
def getTruthValue(self):
""" Return known truth value. The "None" value indicates unknown. """
if self.isCompileTimeConstant():
return bool(self.getCompileTimeConstant())
else:
return None
def isKnownToBeIterable(self, count):
""" Can be iterated at all (count is None) or exactly count times.
Yes or no. If it can be iterated a known number of times, it may
be asked to unpack itself.
"""
# Virtual method, pylint: disable=no-self-use,unused-argument
return False
def isKnownToBeIterableAtMin(self, count):
# Virtual method, pylint: disable=no-self-use,unused-argument
return False
def isKnownToBeIterableAtMax(self, count):
# Virtual method, pylint: disable=no-self-use,unused-argument
return False
def getIterationLength(self):
""" Value that "len" or "PyObject_Size" would give, if known.
Otherwise it is "None" to indicate unknown.
"""
# Virtual method, pylint: disable=no-self-use
return None
def getIterationMinLength(self):
""" Value that "len" or "PyObject_Size" would give at minimum, if known.
Otherwise it is "None" to indicate unknown.
"""
return self.getIterationLength()
def getIterationMaxLength(self):
""" Value that "len" or "PyObject_Size" would give at maximum, if known.
Otherwise it is "None" to indicate unknown.
"""
return self.getIterationLength()
def getStringValue(self):
""" Node as string value, if possible."""
# Virtual method, pylint: disable=no-self-use
return None
def getStrValue(self):
""" Value that "str" or "PyObject_Str" would give, if known.
Otherwise it is "None" to indicate unknown. Users must not
forget to take side effects into account, when replacing a
node with its string value.
"""
string_value = self.getStringValue()
if string_value is not None:
return makeConstantReplacementNode(node=self, constant=string_value)
return None
def getTypeValue(self):
""" Type of the node.
"""
from .TypeNodes import ExpressionBuiltinType1
return ExpressionBuiltinType1(
value=self.makeClone(), source_ref=self.getSourceReference()
)
def getIterationHandle(self):
# Virtual method, pylint: disable=no-self-use
return None
def isKnownToBeHashable(self):
""" Is the value hashable, i.e. suitable for dictionary/set keying."""
# Virtual method, pylint: disable=no-self-use
# Unknown by default.
return None
def extractUnhashableNode(self):
# Virtual method, pylint: disable=no-self-use
# Not available by default.
return None
def onRelease(self, trace_collection):
# print "onRelease", self
pass
def isKnownToHaveAttribute(self, attribute_name):
# Virtual method, pylint: disable=no-self-use,unused-argument
return None
@abstractmethod
def computeExpressionRaw(self, trace_collection):
""" Returns a tuple(node, tags, description).
Replace this node with computation result. """
def computeExpressionAttribute(self, lookup_node, attribute_name, trace_collection):
# By default, an attribute lookup may change everything about the lookup
# source.
trace_collection.removeKnowledge(self)
# Any code could be run, note that.
trace_collection.onControlFlowEscape(self)
if not self.isKnownToHaveAttribute(attribute_name):
trace_collection.onExceptionRaiseExit(BaseException)
return lookup_node, None, None
def computeExpressionAttributeSpecial(
self, lookup_node, attribute_name, trace_collection
):
# By default, an attribute lookup may change everything about the lookup
# source. Virtual method, pylint: disable=unused-argument
trace_collection.removeKnowledge(lookup_node)
# Any code could be run, note that.
trace_collection.onControlFlowEscape(self)
trace_collection.onExceptionRaiseExit(BaseException)
return lookup_node, None, None
def computeExpressionImportName(self, import_node, import_name, trace_collection):
if self.mayRaiseExceptionImportName(BaseException, import_name):
trace_collection.onExceptionRaiseExit(BaseException)
# Any code could be run, note that.
trace_collection.onControlFlowEscape(self)
return import_node, None, None
def computeExpressionSetAttribute(
self, set_node, attribute_name, value_node, trace_collection
):
# By default, an attribute lookup may change everything about the lookup
# source. Virtual method, pylint: disable=unused-argument
trace_collection.removeKnowledge(self)
trace_collection.removeKnowledge(value_node)
# Any code could be run, note that.
trace_collection.onControlFlowEscape(self)
trace_collection.onExceptionRaiseExit(BaseException)
# Better mechanics?
return set_node, None, None
def computeExpressionDelAttribute(self, set_node, attribute_name, trace_collection):
# By default, an attribute lookup may change everything about the lookup
# source. Virtual method, pylint: disable=unused-argument
trace_collection.removeKnowledge(self)
# Any code could be run, note that.
trace_collection.onControlFlowEscape(self)
trace_collection.onExceptionRaiseExit(BaseException)
# Better mechanics?
return set_node, None, None
def computeExpressionSubscript(self, lookup_node, subscript, trace_collection):
# By default, an subscript can execute any code and change all values
# that escaped. This is a virtual method that may consider the subscript
# but generally we don't know what to do. pylint: disable=unused-argument
trace_collection.onControlFlowEscape(self)
# Any exception may be raised.
trace_collection.onExceptionRaiseExit(BaseException)
return lookup_node, None, None
def computeExpressionSetSubscript(
self, set_node, subscript, value_node, trace_collection
):
# By default, an subscript can execute any code and change all values
# that escaped. This is a virtual method that may consider the subscript
# but generally we don't know what to do. pylint: disable=unused-argument
trace_collection.onControlFlowEscape(self)
# Any exception may be raised.
trace_collection.onExceptionRaiseExit(BaseException)
return set_node, None, None
def computeExpressionDelSubscript(self, del_node, subscript, trace_collection):
# By default, an subscript can execute any code and change all values
# that escaped. This is a virtual method that may consider the subscript
# but generally we don't know what to do. pylint: disable=unused-argument
trace_collection.onControlFlowEscape(self)
# Any exception may be raised.
trace_collection.onExceptionRaiseExit(BaseException)
return del_node, None, None
def computeExpressionSlice(self, lookup_node, lower, upper, trace_collection):
# By default, a slicing may change everything about the lookup source.
trace_collection.removeKnowledge(self)
trace_collection.removeKnowledge(lower)
trace_collection.removeKnowledge(upper)
# Any exception may be raised.
trace_collection.onExceptionRaiseExit(BaseException)
return lookup_node, None, None
def computeExpressionSetSlice(
self, set_node, lower, upper, value_node, trace_collection
):
# By default, an subscript may change everything about the lookup
# source.
trace_collection.removeKnowledge(self)
trace_collection.removeKnowledge(lower)
trace_collection.removeKnowledge(upper)
trace_collection.removeKnowledge(value_node)
# Any code could be run, note that.
trace_collection.onControlFlowEscape(self)
# Any exception may be raised.
trace_collection.onExceptionRaiseExit(BaseException)
return set_node, None, None
def computeExpressionDelSlice(self, set_node, lower, upper, trace_collection):
# By default, an subscript may change everything about the lookup
# source.
trace_collection.removeKnowledge(self)
trace_collection.removeKnowledge(lower)
trace_collection.removeKnowledge(upper)
# Any code could be run, note that.
trace_collection.onControlFlowEscape(self)
# Any exception may be raised.
trace_collection.onExceptionRaiseExit(BaseException)
return set_node, None, None
def computeExpressionCall(self, call_node, call_args, call_kw, trace_collection):
# The called and the arguments escape for good.
self.onContentEscapes(trace_collection)
if call_args is not None:
call_args.onContentEscapes(trace_collection)
if call_kw is not None:
call_kw.onContentEscapes(trace_collection)
# Any code could be run, note that.
trace_collection.onControlFlowEscape(self)
# Any exception may be raised.
trace_collection.onExceptionRaiseExit(BaseException)
return call_node, None, None
def computeExpressionLen(self, len_node, trace_collection):
shape = self.getValueShape()
has_len = shape.hasShapeSlotLen()
if has_len is False:
return makeRaiseTypeErrorExceptionReplacementFromTemplateAndValue(
template="object of type '%s' has no len()",
operation="len",
original_node=len_node,
value_node=self,
)
elif has_len is True:
iter_length = self.getIterationLength()
if iter_length is not None:
from .ConstantRefNodes import makeConstantRefNode
result = makeConstantRefNode(
constant=int(iter_length), # make sure to downcast long
source_ref=len_node.getSourceReference(),
)
result = wrapExpressionWithNodeSideEffects(
new_node=result, old_node=self
)
return (
result,
"new_constant",
"Predicted 'len' result from value shape.",
)
self.onContentEscapes(trace_collection)
# Any code could be run, note that.
trace_collection.onControlFlowEscape(self)
# Any exception may be raised.
trace_collection.onExceptionRaiseExit(BaseException)
return len_node, None, None
def computeExpressionAbs(self, abs_node, trace_collection):
shape = self.getTypeShape()
if shape.hasShapeSlotAbs() is False:
return makeRaiseTypeErrorExceptionReplacementFromTemplateAndValue(
template="bad operand type for abs(): '%s'",
operation="abs",
original_node=abs_node,
value_node=self,
)
self.onContentEscapes(trace_collection)
# Any code could be run, note that.
trace_collection.onControlFlowEscape(self)
# Any exception may be raised.
trace_collection.onExceptionRaiseExit(BaseException)
return abs_node, None, None
def computeExpressionInt(self, int_node, trace_collection):
shape = self.getTypeShape()
if shape.hasShapeSlotInt() is False:
return makeRaiseTypeErrorExceptionReplacementFromTemplateAndValue(
template="int() argument must be a string or a number, not '%s'"
if python_version < 300
else "int() argument must be a string, a bytes-like object or a number, not '%s'",
operation="int",
original_node=int_node,
value_node=self,
)
self.onContentEscapes(trace_collection)
# Any code could be run, note that.
trace_collection.onControlFlowEscape(self)
# Any exception may be raised.
trace_collection.onExceptionRaiseExit(BaseException)
return int_node, None, None
def computeExpressionLong(self, long_node, trace_collection):
shape = self.getTypeShape()
if shape.hasShapeSlotLong() is False:
return makeRaiseTypeErrorExceptionReplacementFromTemplateAndValue(
template="long() argument must be a string or a number, not '%s'",
operation="long",
original_node=long_node,
value_node=self,
)
self.onContentEscapes(trace_collection)
# Any code could be run, note that.
trace_collection.onControlFlowEscape(self)
# Any exception may be raised.
trace_collection.onExceptionRaiseExit(BaseException)
return long_node, None, None
def computeExpressionFloat(self, float_node, trace_collection):
shape = self.getTypeShape()
if shape.hasShapeSlotFloat() is False:
return makeRaiseTypeErrorExceptionReplacementFromTemplateAndValue(
"float() argument must be a string or a number"
if isFullCompat() and python_version < 300
else "float() argument must be a string or a number, not '%s'",
operation="long",
original_node=float_node,
value_node=self,
)
self.onContentEscapes(trace_collection)
# Any code could be run, note that.
trace_collection.onControlFlowEscape(self)
# Any exception may be raised.
trace_collection.onExceptionRaiseExit(BaseException)
return float_node, None, None
def computeExpressionBytes(self, bytes_node, trace_collection):
shape = self.getTypeShape()
if (
shape.hasShapeSlotBytes() is False
and shape.hasShapeSlotInt() is False
and shape.hasShapeSlotIter() is False
):
return makeRaiseTypeErrorExceptionReplacementFromTemplateAndValue(
"'%s' object is not iterable",
operation="bytes",
original_node=bytes_node,
value_node=self,
)
self.onContentEscapes(trace_collection)
# Any code could be run, note that.
trace_collection.onControlFlowEscape(self)
# Any exception may be raised.
trace_collection.onExceptionRaiseExit(BaseException)
return bytes_node, None, None
def computeExpressionComplex(self, complex_node, trace_collection):
shape = self.getTypeShape()
if shape.hasShapeSlotComplex() is False:
return makeRaiseTypeErrorExceptionReplacementFromTemplateAndValue(
"complex() argument must be a string or a number"
if isFullCompat() and python_version < 300
else "complex() argument must be a string or a number, not '%s'",
operation="complex",
original_node=complex_node,
value_node=self,
)
self.onContentEscapes(trace_collection)
# Any code could be run, note that.
trace_collection.onControlFlowEscape(self)
# Any exception may be raised.
trace_collection.onExceptionRaiseExit(BaseException)
return complex_node, None, None
def computeExpressionIter1(self, iter_node, trace_collection):
shape = self.getTypeShape()
if shape.hasShapeSlotIter() is False:
# Any exception TypeError will be raised.
trace_collection.onExceptionRaiseExit(BaseException)
return makeRaiseTypeErrorExceptionReplacementFromTemplateAndValue(
template="'%s' object is not iterable",
operation="iter",
original_node=iter_node,
value_node=self,
)
self.onContentEscapes(trace_collection)
# Any code could be run, note that.
trace_collection.onControlFlowEscape(self)
# Any exception may be raised.
trace_collection.onExceptionRaiseExit(BaseException)
return iter_node, None, None
def computeExpressionNext1(self, next_node, trace_collection):
self.onContentEscapes(trace_collection)
# Any code could be run, note that.
trace_collection.onControlFlowEscape(self)
# Any exception may be raised.
trace_collection.onExceptionRaiseExit(BaseException)
return next_node, None, None
def computeExpressionAsyncIter(self, iter_node, trace_collection):
self.onContentEscapes(trace_collection)
# Any code could be run, note that.
trace_collection.onControlFlowEscape(self)
# Any exception may be raised.
trace_collection.onExceptionRaiseExit(BaseException)
return iter_node, None, None
def computeExpressionOperationNot(self, not_node, trace_collection):
# Virtual method, pylint: disable=no-self-use
# The value of that node escapes and could change its contents.
trace_collection.removeKnowledge(not_node)
# Any code could be run, note that.
trace_collection.onControlFlowEscape(not_node)
# Any exception may be raised.
trace_collection.onExceptionRaiseExit(BaseException)
return not_node, None, None
def computeExpressionComparisonIn(self, in_node, value_node, trace_collection):
# Virtual method, pylint: disable=unused-argument
shape = self.getTypeShape()
assert shape is not None, self
if shape.hasShapeSlotContains() is False:
return makeRaiseTypeErrorExceptionReplacementFromTemplateAndValue(
template="argument of type '%s' object is not iterable",
operation="in",
original_node=in_node,
value_node=self,
)
# Any code could be run, note that.
trace_collection.onControlFlowEscape(in_node)
# Any exception may be raised.
trace_collection.onExceptionRaiseExit(BaseException)
return in_node, None, None
def computeExpressionDrop(self, statement, trace_collection):
if not self.mayHaveSideEffects():
return (
None,
"new_statements",
lambda: "Removed %s without effect." % self.getDescription(),
)
return statement, None, None
def computeExpressionBool(self, trace_collection):
if not self.mayRaiseException(BaseException) and self.mayRaiseExceptionBool(
BaseException
):
trace_collection.onExceptionRaiseExit(BaseException)
def onContentEscapes(self, trace_collection):
pass
def mayRaiseExceptionBool(self, exception_type):
""" Unless we are told otherwise, everything may raise being checked. """
# Virtual method, pylint: disable=no-self-use,unused-argument
return True
def mayRaiseExceptionAbs(self, exception_type):
""" Unless we are told otherwise, everything may raise in 'abs'. """
# Virtual method, pylint: disable=no-self-use,unused-argument
return True
def mayRaiseExceptionInt(self, exception_type):
""" Unless we are told otherwise, everything may raise in __int__. """
# Virtual method, pylint: disable=no-self-use,unused-argument
return True
def mayRaiseExceptionLong(self, exception_type):
""" Unless we are told otherwise, everything may raise in __long__. """
# Virtual method, pylint: disable=no-self-use,unused-argument
return True
def mayRaiseExceptionFloat(self, exception_type):
""" Unless we are told otherwise, everything may raise in __float__. """
# Virtual method, pylint: disable=no-self-use,unused-argument
return True
def mayRaiseExceptionBytes(self, exception_type):
""" Unless we are told otherwise, everything may raise in __bytes__. """
# Virtual method, pylint: disable=no-self-use,unused-argument
return True
def mayRaiseExceptionIn(self, exception_type, checked_value):
""" Unless we are told otherwise, everything may raise being iterated. """
# Virtual method, pylint: disable=no-self-use,unused-argument
return True
def mayRaiseExceptionAttributeLookup(self, exception_type, attribute_name):
""" Unless we are told otherwise, everything may raise for attribute access. """
# Virtual method, pylint: disable=no-self-use,unused-argument
return True
def mayRaiseExceptionAttributeLookupSpecial(self, exception_type, attribute_name):
""" Unless we are told otherwise, everything may raise for attribute access. """
# Virtual method, pylint: disable=no-self-use,unused-argument
return True
def mayRaiseExceptionAttributeLookupObject(self, exception_type, attribute):
""" Unless we are told otherwise, everything may raise for attribute access. """
# Virtual method, pylint: disable=no-self-use,unused-argument
return True
def mayRaiseExceptionAttributeCheck(self, exception_type, attribute_name):
""" Unless we are told otherwise, everything may raise for attribute check. """
# Virtual method, pylint: disable=no-self-use,unused-argument
return True
def mayRaiseExceptionAttributeCheckObject(self, exception_type, attribute):
""" Unless we are told otherwise, everything may raise for attribute check. """
# Virtual method, pylint: disable=no-self-use,unused-argument
return True
def mayRaiseExceptionImportName(self, exception_type, import_name):
""" Unless we are told otherwise, everything may raise for name import. """
# Virtual method, pylint: disable=no-self-use,unused-argument
return True
def mayHaveSideEffectsBool(self):
""" Unless we are told otherwise, everything may have a side effect for bool check. """
# Virtual method, pylint: disable=no-self-use
return True
def mayHaveSideEffectsAbs(self):
""" Unless we are told otherwise, everything may have a side effect for abs check. """
# Virtual method, pylint: disable=no-self-use
# TODO: Bonus points for check type shapes that will be good
# for abs, i.e. number shapes like Int, Long, Float, Complex.
return True
def hasShapeSlotLen(self):
""" The type shape tells us, if "len" is available.
"""
return self.getTypeShape().hasShapeSlotLen()
def hasShapeSlotIter(self):
""" The type shape tells us, if "iter" is available.
"""
return self.getTypeShape().hasShapeSlotIter()
def hasShapeSlotNext(self):
""" The type shape tells us, if "next" is available.
"""
return self.getTypeShape().hasShapeSlotNext()
# TODO: Maybe this is a shape slot thing.
def isIndexable(self):
""" Unless we are told otherwise, it's not indexable. """
# Virtual method, pylint: disable=no-self-use
return False
# TODO: The ought to be a type shape check for that too.
def getIntegerValue(self):
""" Node as integer value, if possible."""
# Virtual method, pylint: disable=no-self-use
return None
def getIntValue(self):
""" Value that "int" or "PyNumber_Int" (sp) would give, if known.
Otherwise it is "None" to indicate unknown. Users must not
forget to take side effects into account, when replacing a
node with its string value.
"""
# Virtual method, pylint: disable=no-self-use
return None
def hasShapeDictionaryExact(self):
""" Does a node have exactly a dictionary shape.
"""
return self.getTypeShape() is ShapeTypeDict
def hasShapeStrExact(self):
""" Does an expression have exactly a string shape.
"""
return self.getTypeShape() is ShapeTypeStr
def hasShapeUnicodeExact(self):
""" Does an expression have exactly a unicode shape.
"""
return self.getTypeShape() is ShapeTypeUnicode
class CompileTimeConstantExpressionBase(ExpressionBase):
# Base classes can be abstract, pylint: disable=abstract-method
# TODO: Do this for all computations, do this in the base class of all
# nodes.
__slots__ = ("computed_attribute",)
def __init__(self, source_ref):
ExpressionBase.__init__(self, source_ref=source_ref)
self.computed_attribute = None
def isCompileTimeConstant(self):
""" Has a value that we can use at compile time.
Yes or no. If it has such a value, simulations can be applied at
compile time and e.g. operations or conditions, or even calls may
be executed against it.
"""
return True
def isMutable(self):
# Virtual method, pylint: disable=no-self-use
return False
def mayHaveSideEffects(self):
# Virtual method overload
return False
def mayHaveSideEffectsBool(self):
# Virtual method overload
return False
def mayRaiseException(self, exception_type):
# Virtual method overload
return False
def mayRaiseExceptionBool(self, exception_type):
# Virtual method overload
return False
def mayRaiseExceptionAttributeLookup(self, exception_type, attribute_name):
# Virtual method overload
# We remember it from our computation.
return not self.computed_attribute
def mayRaiseExceptionAttributeLookupSpecial(self, exception_type, attribute_name):
# Virtual method overload
# We remember it from our computation.
return not self.computed_attribute
def mayRaiseExceptionAttributeCheck(self, exception_type, attribute_name):
# Virtual method overload
# Checking attributes of compile time constants never raises.
return False
def computeExpressionOperationNot(self, not_node, trace_collection):
return trace_collection.getCompileTimeComputationResult(
node=not_node,
computation=lambda: not self.getCompileTimeConstant(),
description="""\
Compile time constant negation truth value pre-computed.""",
)
def computeExpressionLen(self, len_node, trace_collection):
return trace_collection.getCompileTimeComputationResult(
node=len_node,
computation=lambda: len(self.getCompileTimeConstant()),
description="""\
Compile time constant len value pre-computed.""",
)
def computeExpressionAbs(self, abs_node, trace_collection):
return trace_collection.getCompileTimeComputationResult(
node=abs_node,
computation=lambda: abs(self.getCompileTimeConstant()),
description="""\
Compile time constant abs value pre-computed.""",
)
def computeExpressionInt(self, int_node, trace_collection):
return trace_collection.getCompileTimeComputationResult(
node=int_node,
computation=lambda: int(self.getCompileTimeConstant()),
description="""\
Compile time constant int value pre-computed.""",
)
def computeExpressionLong(self, long_node, trace_collection):
return trace_collection.getCompileTimeComputationResult(
node=long_node,
computation=lambda: long(self.getCompileTimeConstant()),
description="""\
Compile time constant long value pre-computed.""",
)
def computeExpressionFloat(self, float_node, trace_collection):
return trace_collection.getCompileTimeComputationResult(
node=float_node,
computation=lambda: float(self.getCompileTimeConstant()),
description="""\
Compile time constant float value pre-computed.""",
)
def computeExpressionBytes(self, bytes_node, trace_collection):
constant_value = self.getCompileTimeConstant()
if type(constant_value) in (int, long):
if constant_value > 1000:
return bytes_node, None, None
return trace_collection.getCompileTimeComputationResult(
node=bytes_node,
computation=lambda: bytes(constant_value),
description="""\
Compile time constant bytes value pre-computed.""",
)
def isKnownToHaveAttribute(self, attribute_name):
if self.computed_attribute is None:
self.computed_attribute = hasattr(
self.getCompileTimeConstant(), attribute_name
)
return self.computed_attribute
def computeExpressionAttribute(self, lookup_node, attribute_name, trace_collection):
value = self.getCompileTimeConstant()
if self.computed_attribute is None:
self.computed_attribute = hasattr(value, attribute_name)
# If it raises, or the attribute itself is a compile time constant,
# then do execute it.
if not self.computed_attribute or isCompileTimeConstantValue(
getattr(value, attribute_name)
):
return trace_collection.getCompileTimeComputationResult(
node=lookup_node,
computation=lambda: getattr(value, attribute_name),
description="Attribute '%s' pre-computed." % (attribute_name),
)
return lookup_node, None, None
def computeExpressionSubscript(self, lookup_node, subscript, trace_collection):
if subscript.isCompileTimeConstant():
return trace_collection.getCompileTimeComputationResult(
node=lookup_node,
computation=lambda: self.getCompileTimeConstant()[
subscript.getCompileTimeConstant()
],
description="Subscript of constant with constant value.",
)
# TODO: Look-up of subscript to index may happen.
# Any code could be run due to that, note that.
trace_collection.onControlFlowEscape(self)
trace_collection.onExceptionRaiseExit(BaseException)
return lookup_node, None, None
def computeExpressionSlice(self, lookup_node, lower, upper, trace_collection):
# TODO: Could be happy with predictable index values and not require
# constants.
if lower is not None:
if upper is not None:
if lower.isCompileTimeConstant() and upper.isCompileTimeConstant():
return getComputationResult(
node=lookup_node,
computation=lambda: self.getCompileTimeConstant()[
lower.getCompileTimeConstant() : upper.getCompileTimeConstant()
],
description="""\
Slicing of constant with constant indexes.""",
)
else:
if lower.isCompileTimeConstant():
return getComputationResult(
node=lookup_node,
computation=lambda: self.getCompileTimeConstant()[
lower.getCompileTimeConstant() :
],
description="""\
Slicing of constant with constant lower index only.""",
)
else:
if upper is not None:
if upper.isCompileTimeConstant():
return getComputationResult(
node=lookup_node,
computation=lambda: self.getCompileTimeConstant()[
: upper.getCompileTimeConstant()
],
description="""\
Slicing of constant with constant upper index only.""",
)
else:
return getComputationResult(
node=lookup_node,
computation=lambda: self.getCompileTimeConstant()[:],
description="Slicing of constant with no indexes.",
)
return lookup_node, None, None
def computeExpressionComparisonIn(self, in_node, value_node, trace_collection):
if value_node.isCompileTimeConstant():
return getComputationResult(
node=in_node,
computation=lambda: in_node.getSimulator()(
value_node.getCompileTimeConstant(), self.getCompileTimeConstant()
),
description="""\
Predicted '%s' on compiled time constant values."""
% in_node.comparator,
)
# Look-up of __contains__ on compile time constants does mostly nothing.
trace_collection.onExceptionRaiseExit(BaseException)
return in_node, None, None