This repository was archived by the owner on Mar 18, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathtest_fatoptimizer.py
More file actions
3274 lines (2743 loc) · 93.5 KB
/
test_fatoptimizer.py
File metadata and controls
3274 lines (2743 loc) · 93.5 KB
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
# Disable the AST optimizer on this module
__fatoptimizer__ = {'enabled': False}
import ast
import fatoptimizer.convert_const
import fatoptimizer.namespace
import fatoptimizer.optimizer
import fatoptimizer.tools
import io
import re
import sys
from fatoptimizer.tools import UNSET
import textwrap
import unittest
from unittest import mock
if sys.version_info < (3, 5):
# RecursionError was introduced in Python 3.5
fatoptimizer.tools.RecursionError = RuntimeError
need_python35 = unittest.skipIf(sys.version_info < (3, 5), "need python 3.5")
if not hasattr(ast, 'Constant'):
# backport ast.Constant of the PEP 511
class Constant(ast.AST):
_attributes = ('lineno', 'col_offset')
_fields = ('value',)
def __init__(self, value):
self.value = value
ast.Constant = Constant
def format_code(code):
return textwrap.dedent(code).strip()
def compile_ast(source):
source = format_code(source)
return ast.parse(source, '<string>', 'exec')
def compile_ast_expr(source):
module = ast.parse(source, '<string>', 'exec')
assert isinstance(module, ast.Module)
body = module.body
assert len(body) == 1
expr = body[0]
assert isinstance(expr, ast.Expr)
return expr.value
def specialize_constant(node, value):
if value is None or isinstance(value, bool):
new_node = ast.NameConstant(value=value)
elif isinstance(value, (int, float, complex)):
new_node = ast.Num(n=value)
elif isinstance(value, str):
new_node = ast.Str(s=value)
elif isinstance(value, bytes):
new_node = ast.Bytes(s=value)
elif isinstance(value, tuple):
elts = [specialize_constant(node, elt) for elt in value]
new_node = ast.Tuple(elts=elts, ctx=ast.Load())
else:
raise ValueError("unknown constant: %r" % value)
fatoptimizer.tools.copy_lineno(node, new_node)
return new_node
def builtin_guards(*names):
args = ', '.join(map(repr, sorted(names)))
return '[__fat__.GuardBuiltins(%s)]' % (args,)
class SpecializeConstant(ast.NodeTransformer):
def visit_Constant(self, node):
if isinstance(node.value, frozenset):
return node
return specialize_constant(node, node.value)
class AstToolsTests(unittest.TestCase):
def test_get_starargs(self):
tree = compile_ast('func()')
node = fatoptimizer.tools.get_starargs(tree.body[0].value)
self.assertIsNone(node)
tree = compile_ast('func(arg, *varargs)')
node = fatoptimizer.tools.get_starargs(tree.body[0].value)
self.assertIsInstance(node, ast.Name)
self.assertEqual(node.id, 'varargs')
tree = compile_ast('func()')
with self.assertRaises(ValueError):
fatoptimizer.tools.get_starargs(tree)
def test_get_keywords(self):
tree = compile_ast('func()')
keywords = fatoptimizer.tools.get_keywords(tree.body[0].value)
self.assertFalse(keywords)
tree = compile_ast('func(x=1, y=2)')
keywords = fatoptimizer.tools.get_keywords(tree.body[0].value)
self.assertEqual(len(keywords), 2)
self.assertIsInstance(keywords[0], ast.keyword)
self.assertEqual(keywords[0].arg, 'x')
self.assertIsInstance(keywords[1], ast.keyword)
self.assertEqual(keywords[1].arg, 'y')
tree = compile_ast('func(arg, *varargs, **kwargs)')
keywords = fatoptimizer.tools.get_keywords(tree.body[0].value)
self.assertEqual(len(keywords), 1)
self.assertIsInstance(keywords[0], ast.keyword)
self.assertIsNone(keywords[0].arg)
tree = compile_ast('func()')
with self.assertRaises(ValueError):
fatoptimizer.tools.get_keywords(tree)
def test_get_varkeywords(self):
tree = compile_ast('func()')
keywords = fatoptimizer.tools.get_varkeywords(tree.body[0].value)
self.assertFalse(keywords)
tree = compile_ast('func(x=1, y=2)')
keywords = fatoptimizer.tools.get_varkeywords(tree.body[0].value)
self.assertFalse(keywords)
tree = compile_ast('func(arg, *varargs, **kwargs)')
varkwds = fatoptimizer.tools.get_varkeywords(tree.body[0].value)
self.assertIsInstance(varkwds, ast.Name)
self.assertEqual(varkwds.id, 'kwargs')
tree = compile_ast('func()')
with self.assertRaises(ValueError):
fatoptimizer.tools.get_varkeywords(tree)
class VariableVisitorTests(unittest.TestCase):
def check_vars(self, code, local_variables, global_variables=None,
nonlocal_variables=None,
get_node=None):
tree = compile_ast(code)
self.assertIsInstance(tree, ast.Module)
if get_node:
node = get_node(tree)
else:
node = tree.body[0]
visitor = fatoptimizer.namespace.VariableVisitor("<string>")
visitor.find_variables(node)
self.assertEqual(visitor.local_variables, local_variables)
if global_variables is not None:
self.assertEqual(visitor.global_variables, global_variables)
else:
self.assertEqual(visitor.global_variables, set())
if nonlocal_variables is not None:
self.assertEqual(visitor.nonlocal_variables, nonlocal_variables)
else:
self.assertEqual(visitor.nonlocal_variables, set())
def test_module(self):
code = """
global x
y = 1
"""
self.check_vars(code, {'y'}, {'x'}, get_node=lambda tree: tree)
def test_for(self):
code = """
def func(arg):
for x in arg:
pass
for y, z in arg:
pass
"""
self.check_vars(code, {'arg', 'x', 'y', 'z'})
def test_local(self):
code = """
x = 1
def func():
x = 2
"""
self.check_vars(code, {'x'}, get_node=lambda tree: tree.body[1])
def test_func_args(self):
code = """
def func(arg1, arg2, *varargs, **kwargs):
pass
"""
self.check_vars(code, {'arg1', 'arg2', 'varargs', 'kwargs'})
code = """
def func(*varargs):
pass
"""
self.check_vars(code, {'varargs'})
code = """
def func(**kw):
pass
"""
self.check_vars(code, {'kw'})
@need_python35
def test_nested(self):
code = """
def func(arg):
def func2(arg2):
var2 = arg2
async def afunc3(arg3):
var3 = arg3
var = [None for listcomp in range(3)]
var = {None: None for dictcomp in range(3)}
var = {None for setcomp in range(3)}
var = (None for genexp in range(3))
"""
self.check_vars(code, {'arg', 'func2', 'afunc3', 'var'})
def test_assign(self):
code = """
def func():
a, b = 1, 2
*c, d = (3, 4)
e.f = 5
g[:2] = [6, 7]
"""
self.check_vars(code, {'a', 'b', 'c', 'd'}, {'e', 'g'})
def test_assign_complex(self):
code = """
def func(arg):
first, *obj.attr[0], last = arg
obj.attr[0].attr2[1] = arg
"""
self.check_vars(code, {'arg', 'first', 'last'}, {'obj'})
code = """
def func(arg):
obj.meth().y = arg
"""
self.check_vars(code, {'arg'}, {'obj'})
def test_modify_globals(self):
code = """
def set_global(key, arg):
globals()[key] = arg
"""
with self.assertRaises(fatoptimizer.namespace.ComplexAssignment):
self.check_vars(code, set())
code = """
def assign(checksig):
type(mock)._mock_check_sig = checksig
"""
with self.assertRaises(fatoptimizer.namespace.ComplexAssignment):
self.check_vars(code, set())
def test_global(self):
code = """
x = 1
def func1():
global x
x = 2
"""
self.check_vars(code, set(), {'x'}, get_node=lambda tree: tree.body[1])
def test_nonlocal(self):
code = """
def func1():
nonlocal x
x = 2
"""
self.check_vars(code, set(), nonlocal_variables={'x'})
def test_late_global(self):
code = """
def func1():
x = 6
global x
"""
self.check_vars(code, set(), {'x'})
def test_function_def(self):
code = """
def func():
x = 1
def nested():
pass
"""
self.check_vars(code, {'x', 'nested'})
def test_import(self):
code = """
def func():
from sys import flags
from sys import ps1 as PS1
import os
import subprocess, email
"""
self.check_vars(code, {'flags', 'PS1', 'os', 'subprocess', 'email'})
def test_with(self):
code = """
def func():
with open(name1) as fp1, open(name2) as fp2, open(name3):
pass
with cm() as (a, b):
pass
with cm() as self.attr:
pass
"""
self.check_vars(code, {'fp1', 'fp2', 'a', 'b'}, {'self'})
code = """
obj = object()
def func():
global obj
with cm() as obj.attr:
pass
"""
self.check_vars(code, set(), {'obj'}, get_node=lambda tree: tree.body[1])
def test_augassign(self):
code = """
def func():
# artificial example, it raises UnboundLocalError
x += 1
"""
self.check_vars(code, {'x'})
def test_nested_func(self):
code = """
def func(self):
def func2():
self.attr = 1
"""
self.check_vars(code, set(), {'self'},
get_node=lambda tree: tree.body[0].body[0])
class BaseAstTests(unittest.TestCase):
maxDiff = 15000
def setUp(self):
if hasattr(sys, 'ast_transformers'):
# Disable the AST hook (if any)
old_transformers = sys.ast_transformers
self.addCleanup(setattr, sys, 'ast_transformers', old_transformers )
sys.ast_transformers = []
# Disable all optimizations by default
self.config = fatoptimizer.Config()
self.config.disable_all()
def assertAstEqual(self, tree1, tree2):
# ast objects don't support comparison,
# so compare their text representation
tree1 = SpecializeConstant().visit(tree1)
text1 = fatoptimizer.pretty_dump(tree1)
text2 = fatoptimizer.pretty_dump(tree2)
self.assertEqual(text1, text2)
def optimize(self, source):
tree = compile_ast(source)
return fatoptimizer.optimize(tree, "<string>", self.config)
def check_optimize(self, source1, source2):
tree1 = self.optimize(source1)
if isinstance(source2, ast.AST):
tree2 = ast.Module(body=[source2])
else:
tree2 = compile_ast(source2)
self.assertAstEqual(tree1, tree2)
def check_optimize_func(self, expr, result):
before = "def func(): return (%s)" % expr
tree1 = self.optimize(before)
if isinstance(result, ast.AST):
after = "def func(): return 0"
tree2 = compile_ast(after)
tree2.body[0].body[0].value = result
else:
after = "def func(): return (%s)" % result
tree2 = compile_ast(after)
self.assertAstEqual(tree1, tree2)
def check_dont_optimize(self, source, result=None):
if result is None:
result = source
self.check_optimize(source, result)
def check_dont_optimize_func(self, expr, result=None):
if result is None:
result = expr
self.check_optimize_func(expr, result)
def indent(self, source, level=1):
source = format_code(source)
indent = ' ' * level
return '\n'.join(indent + line for line in source.splitlines())
def format_specialize(self, before, specialized, guards,
template=None):
before = textwrap.dedent(before).strip()
specialized = textwrap.dedent(specialized).strip()
if not template:
template = """
{import_fat}
{code}
"""
template = format_code(template)
code1 = before
code2 = textwrap.dedent("""
import fat as __fat__
{before}
_ast_optimized = func
{specialized}
__fat__.specialize(_ast_optimized, func.__code__, {guards})
func = _ast_optimized
del _ast_optimized
""").strip()
code2 = code2.format(before=before,
specialized=specialized,
guards=guards)
return (code1, code2)
def check_specialize(self, *args, **kw):
code1, code2 = self.format_specialize(*args, **kw)
self.check_optimize(code1, code2)
def check_func_specialize(self, source, specialized, guards,
replace_consts='', template=None):
source = self.indent(source)
before = textwrap.dedent("""
def func():
{source}
""").strip()
before = before.format(source=source)
if isinstance(specialized, ast.AST):
specialized_ast = specialized
specialized = 'def func(): return 8421028141204'
else:
specialized_ast = None
specialized = self.indent(specialized)
specialized = "def func():\n" + specialized
if replace_consts:
specialized += ('\nfunc.__code__ = __fat__.replace_consts(func.__code__, %s)'
% replace_consts)
code1, code2 = self.format_specialize(before, specialized, guards, template=template)
tree1 = self.optimize(code1)
tree2 = compile_ast(code2)
if specialized_ast:
# import, def func, _ast_optimized = func, [def func]
node = tree2.body[3]
assert node.body[0].value.n == 8421028141204
node.body[:] = [specialized_ast]
self.assertAstEqual(tree1, tree2)
def check_builtin_func(self, func, source, specialized):
self.check_func_specialize(source, specialized,
guards=builtin_guards(func))
class FunctionsTests(BaseAstTests):
def test_get_constant(self):
def get_constant(source):
filename = "test"
tree = compile_ast_expr(source)
tree = fatoptimizer.convert_const.ConvertConstant(filename).visit(tree)
return fatoptimizer.tools.get_constant(tree)
self.assertEqual(get_constant('True'), True)
self.assertEqual(get_constant('False'), False)
self.assertEqual(get_constant('None'), None)
self.assertEqual(get_constant('1'), 1)
self.assertEqual(get_constant(r'"unicode \u20ac"'), "unicode \u20ac")
self.assertEqual(get_constant(r'b"bytes \xff"'), b"bytes \xff")
self.assertEqual(get_constant('(1, 2, 3)'), (1, 2, 3))
# unsupported types
self.assertIs(get_constant('[1, 2]'), UNSET)
self.assertIs(get_constant('{1, 2}'), UNSET)
self.assertIs(get_constant('{"key": "value"}'), UNSET)
def new_constant(self, value):
node = ast.Num(n=1, lineno=1, col_offset=1)
return fatoptimizer.tools._new_constant(node, value)
def test_new_constant_primitive(self):
self.assertAstEqual(self.new_constant(None),
compile_ast_expr('None'))
self.assertAstEqual(self.new_constant(False),
compile_ast_expr('False'))
self.assertAstEqual(self.new_constant(True),
compile_ast_expr('True'))
self.assertAstEqual(self.new_constant(2),
compile_ast_expr('2'))
self.assertAstEqual(self.new_constant(4.0),
compile_ast_expr('4.0'))
self.assertAstEqual(self.new_constant(4.0j),
compile_ast_expr('4.0j'))
self.assertAstEqual(self.new_constant("unicode \u20ac"),
compile_ast_expr(r'"unicode \u20ac"'))
self.assertAstEqual(self.new_constant(b"bytes \xff"),
compile_ast_expr(r'b"bytes \xff"'))
def test_new_constant_containers(self):
self.assertAstEqual(self.new_constant((1, 2)),
compile_ast_expr('(1, 2)'))
self.assertAstEqual(self.new_constant([1, 2]),
compile_ast_expr('[1, 2]'))
self.assertAstEqual(self.new_constant({"key": "value"}),
compile_ast_expr('{"key": "value"}'))
self.assertAstEqual(self.new_constant({"a": 1, "b": 2, "c": 3, "d": 4}),
compile_ast_expr(repr({"a": 1, "b": 2, "c": 3, "d": 4})))
class CallPureBuiltinTests(BaseAstTests):
def setUp(self):
super().setUp()
from fatoptimizer.builtins import add_pure_builtins
add_pure_builtins(self.config)
def test_builtin_abs(self):
self.check_builtin_func('abs',
'return abs(-3)',
'return 3')
def test_builtin_ascii(self):
self.check_builtin_func('ascii',
'return ascii(3)',
'return "3"')
def test_builtin_bool(self):
self.check_builtin_func('bool',
'return bool("x")',
'return True')
def test_builtin_bin(self):
self.check_builtin_func('bin',
'return bin(15)',
'return "0b1111"')
def test_builtin_bytes(self):
self.check_builtin_func('bytes',
"return bytes(b'abc')",
"return b'abc'")
self.check_builtin_func('bytes',
"return bytes((65, 66, 67))",
"return b'ABC'")
self.check_dont_optimize_func("bytes('unicode')")
self.check_dont_optimize_func("bytes((-1,))")
self.check_dont_optimize_func("bytes((256,))")
def test_builtin_chr(self):
self.check_builtin_func('chr',
'return chr(65)',
'return "A"')
self.check_dont_optimize_func('chr(-1)')
self.check_dont_optimize_func('chr(0x110000)')
def test_builtin_complex(self):
self.check_builtin_func('complex',
'return complex("1.0j")',
'return 1.0j')
self.check_builtin_func('complex',
'return complex(3j)',
'return 3j')
self.check_builtin_func('complex',
'return complex(0, 2)',
'return 2j')
self.check_dont_optimize_func("complex('xyz')")
self.check_dont_optimize_func("complex('1.0', 2)")
def test_builtin_dict(self):
self.check_builtin_func('dict',
"return dict(((1, 2), (3, 4)))",
"return {1: 2, 3: 4}")
self.check_builtin_func('dict',
"return dict({1: 2, 3: 4})",
"return {1: 2, 3: 4}")
self.check_builtin_func('dict',
"return dict()",
"return {}")
self.check_dont_optimize_func("dict({['list']: 'value'})")
def test_builtin_divmod(self):
self.check_builtin_func('divmod',
'return divmod(100, 3)',
'return (33, 1)')
# division by zero
self.check_dont_optimize_func("divmod(1, 0)")
self.check_dont_optimize_func("divmod(2.0, 0.0)")
def test_builtin_float(self):
self.check_builtin_func('float',
'return float("1.0")',
'return 1.0')
self.check_builtin_func('float',
'return float(2)',
'return 2.0')
self.check_builtin_func('float',
'return float(3.0)',
'return 3.0')
self.check_dont_optimize_func("float('xyz')")
def test_builtin_frozenset(self):
self.check_builtin_func('frozenset',
"return frozenset(('abc',))",
ast.Return(ast.Constant(value=frozenset(('abc',)))))
self.check_builtin_func('frozenset',
"return frozenset()",
ast.Return(ast.Constant(value=frozenset())))
self.check_dont_optimize_func('frozenset(([],))')
def test_builtin_hex(self):
self.check_builtin_func('hex',
'return hex(16)',
'return "0x10"')
def test_builtin_int(self):
self.check_builtin_func('int',
'return int(123)',
'return 123')
self.check_builtin_func('int',
'return int(123.0)',
'return 123')
self.check_builtin_func('int',
'return int("123")',
'return 123')
self.check_dont_optimize_func("int(1j)")
self.check_dont_optimize_func("int('xyz')")
def test_builtin_len(self):
self.check_builtin_func('len', 'return len("abc")', 'return 3')
def test_builtin_list(self):
self.check_builtin_func('list',
'return list("abc")',
'return ["a", "b", "c"]')
def test_builtin_oct(self):
self.check_builtin_func('oct',
'return oct(83)',
'return "0o123"')
def test_builtin_ord(self):
self.check_builtin_func('ord', 'return ord("A")', 'return 65')
self.check_builtin_func('ord', 'return ord(b"A")', 'return 65')
self.check_dont_optimize_func("ord(123)")
self.check_dont_optimize_func("ord('')")
self.check_dont_optimize_func("ord('xyz')")
def test_builtin_max(self):
self.check_builtin_func('max', 'return max(4, 6)', 'return 6')
self.check_dont_optimize_func("max(b'bytes', 'unicode')")
def test_builtin_min(self):
self.check_builtin_func('min', 'return min(4, 6)', 'return 4')
self.check_dont_optimize_func("min(b'bytes', 'unicode')")
def test_builtin_repr(self):
self.check_builtin_func('repr',
'return repr("abc")',
'return "\'abc\'"')
def test_builtin_pow(self):
# int
self.check_builtin_func('pow',
'return pow(2, 8)',
'return 256')
# float
self.check_builtin_func('pow',
'return pow(16.0, 0.5)',
'return 4.0')
# int modulo
self.check_builtin_func('pow',
'return pow(10, 3, 7)',
'return 6')
def test_builtin_round(self):
self.check_builtin_func('round',
'return round(1.5)',
'return 2')
def test_builtin_set(self):
self.check_builtin_func('set',
"return set(('abc',))",
"return {'abc'}")
self.check_dont_optimize_func('set(([],))')
def test_builtin_str(self):
self.check_builtin_func('str',
'return str(123)',
'return "123"')
self.check_builtin_func('str',
'return str("hello")',
'return "hello"')
def test_builtin_sum(self):
self.check_builtin_func('sum',
'return sum((1, 2, 3))',
'return 6')
self.check_dont_optimize_func('sum(([],))')
def test_builtin_tuple(self):
self.check_builtin_func('tuple',
'return tuple("abc")',
'return ("a", "b", "c")')
def test_config_argtype(self):
self.check_builtin_func('str',
'return str(123)',
'return "123"')
self.config._pure_builtins['str'].arg_types = (str,)
self.check_dont_optimize("""
def func():
return str(123)
""")
def test_pow_max_bits(self):
self.config.max_int_bits = 16
self.check_builtin_func('pow',
'return pow(2, 15)',
'return 32768')
self.check_dont_optimize("""
def func():
return pow(2, 16)
""")
self.config.max_int_bits = 17
self.check_builtin_func('pow',
'return pow(2, 16)',
'return 65536')
def test_config_pure_builtins(self):
self.check_builtin_func('str',
'return str(123)',
'return "123"')
del self.config._pure_builtins['str']
self.check_dont_optimize("""
def func():
return str(123)
""")
class ConfigTests(BaseAstTests):
def setUp(self):
super().setUp()
self.config.constant_folding = True
def test_config_max_int_bits(self):
self.config.max_int_bits = 16
self.check_optimize("""
def func():
return 1 << 15
""", """
def func():
return 32768
""")
self.check_dont_optimize("""
def func():
return 1 << 16
""")
def test_config_max_bytes_len(self):
self.config.max_bytes_len = 3
self.check_optimize("""
def func():
return b'x' * 3
""", """
def func():
return b'xxx'
""")
self.check_dont_optimize("""
def func():
return b'x' * 4
""")
def test_config_max_str_len(self):
self.config.max_str_len = 3
self.check_optimize("""
def func():
return 'x' * 3
""", """
def func():
return 'xxx'
""")
self.check_dont_optimize("""
def func():
return 'x' * 4
""")
# FIXME: fix this test
#def test_config_max_constant_size(self):
# size = fatoptimizer.tools.get_constant_size('abc')
# self.config.max_constant_size = size
# self.check_builtin_func('str',
# 'return str(123)',
# 'return "123"')
# self.config.max_constant_size = size - 1
# self.check_dont_optimize("""
# def func():
# return str(1234)
# """)
class OptimizerTests(BaseAstTests):
def setUp(self):
super().setUp()
from fatoptimizer.builtins import add_pure_builtins
add_pure_builtins(self.config)
def check_add_import(self, before='', after=''):
template = ("""
%s
{import_fat}
%s
{code}
""" % (after, before))
code1 = textwrap.dedent("""
def func():
print(chr(65))
""")
code2 = """
def func():
print("A")
"""
self.check_specialize(code1, code2,
guards=builtin_guards('chr'),
template=template)
def test_add_import_after_docstring(self):
self.check_add_import(after='"docstring"')
def test_add_import_after_import_future(self):
self.check_add_import(after='from __future__ import print_function')
def test_add_import_before_import_sys(self):
self.check_add_import(before='import sys')
def test_builtin_chr(self):
self.check_func_specialize(
"return chr(65)",
'return "A"',
guards=builtin_guards('chr'))
def test_reentrant_functiondef(self):
# Test reentrant call to visit_FunctionDef() (func2()) when we already
# decided to specialized the function func()
self.check_func_specialize("""
res = chr(65)
def func2():
return 2
return res
""", """
res = "A"
def func2():
return 2
return res
""",
guards=builtin_guards('chr'))
def test_generic_visitor(self):
# Test that visitor visits ast.Call arguments
self.check_func_specialize("""
print(chr(65))
""", """
print("A")
""", guards=builtin_guards('chr'))
def test_combined_called(self):
# optimize str(obj) where obj is not a constant, but a call
# which will be optimized to a constant
self.check_func_specialize(
'return str(ord("A"))',
"return '65'",
guards=builtin_guards('ord', 'str'))
def test_duplicate_guards(self):
# check that duplicated guards are removed
self.check_func_specialize(
"return ord('A') + ord('B')",
"return 65 + 66",
guards=builtin_guards('ord'))
def test_decorator(self):
# FIXME: support decorators
self.check_dont_optimize("""
@decorator
def func():
return ord('A')
""")
def test_method(self):
template = format_code("""
{import_fat}
class MyClass:
{code}
""")
self.check_specialize("""
def func(self):
return chr(65)
""", """
def func(self):
return "A"
""", guards=builtin_guards('chr'), template=template)
def test_nested_functiondef(self):
template = format_code("""
{import_fat}
def create_func():
{code}
return func
""")
self.check_specialize("""
def func():
return chr(65)
""", """
def func():
return "A"
""", guards=builtin_guards('chr'), template=template)