This repository was archived by the owner on Jan 3, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathtest_parser.py
More file actions
2094 lines (1825 loc) · 75.8 KB
/
test_parser.py
File metadata and controls
2094 lines (1825 loc) · 75.8 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
# coding:utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
from . import test_utils
from .. import source, lexer, diagnostic, ast, coverage
from ..coverage import parser
import unittest, sys, re, ast as pyast
BytesOnly = test_utils.BytesOnly
UnicodeOnly = test_utils.UnicodeOnly
if sys.version_info >= (3,):
def unicode(x): return x
def tearDownModule():
coverage.report(parser)
class ParserTestCase(unittest.TestCase):
maxDiff = None
versions = [(2, 6), (2, 7), (3, 0), (3, 1), (3, 2), (3, 3), (3, 4), (3, 5)]
def parser_for(self, code, version, interactive=False):
code = code.replace("·", "\n")
self.source_buffer = source.Buffer(code, str(version))
self.engine = diagnostic.Engine()
self.engine.render_diagnostic = lambda diag: None
self.lexer = lexer.Lexer(self.source_buffer, version, self.engine,
interactive=interactive)
old_next = self.lexer.next
def lexer_next(**args):
token = old_next(**args)
# print(repr(token))
return token
self.lexer.next = lexer_next
self.parser = parser.Parser(self.lexer, version, self.engine)
return self.parser
def flatten_ast(self, node):
if node is None:
return None
# Validate locs and fields
for attr in node.__dict__:
if attr.endswith("loc") or attr.endswith("_locs"):
self.assertTrue(attr in node._locs,
"%s not in %s._locs" % (attr, repr(node)))
else:
self.assertTrue(attr in node._fields,
"%s not in %s._fields" % (attr, repr(node)))
for loc in node._locs:
self.assertTrue(loc in node.__dict__,
"loc %s not in %s" % (loc, repr(node)))
for field in node._fields:
self.assertTrue(field in node.__dict__,
"field %s not in %s" % (field, repr(node)))
flat_node = { "ty": unicode(type(node).__name__) }
for field in node._fields:
value = getattr(node, field)
if isinstance(value, ast.AST):
value = self.flatten_ast(value)
if isinstance(value, list) and len(value) > 0 and \
any([isinstance(x, ast.AST) for x in value]):
value = list(map(self.flatten_ast, value))
flat_node[unicode(field)] = value
return flat_node
def flatten_python_ast(self, node):
if node is None:
return None
flat_node = { "ty": unicode(type(node).__name__) }
for field in node._fields:
if field == "ctx":
flat_node["ctx"] = None
continue
value = getattr(node, field)
if isinstance(value, pyast.AST):
value = self.flatten_python_ast(value)
if isinstance(value, list) and len(value) > 0 and \
any([isinstance(x, pyast.AST) for x in value]):
value = list(map(self.flatten_python_ast, value))
flat_node[unicode(field)] = value
return flat_node
_loc_re = re.compile(r"\s*([~^]*)<?\s+([a-z_0-9.]+)")
_path_re = re.compile(r"(([a-z_]+)|([0-9]+))(\.)?")
def match_loc(self, ast, matcher, root=lambda x: (0, x)):
offset, ast = root(ast)
matcher_pos = 0
while matcher_pos < len(matcher):
matcher_match = self._loc_re.match(matcher, matcher_pos)
if matcher_match is None:
raise Exception("invalid location matcher %s" % matcher[matcher_pos:])
range = source.Range(self.source_buffer,
matcher_match.start(1) - matcher_pos + offset,
matcher_match.end(1) - matcher_pos + offset)
path = matcher_match.group(2)
path_pos = 0
obj = ast
while path_pos < len(path):
path_match = self._path_re.match(path, path_pos)
if path_match is None:
raise Exception("invalid location matcher path %s" % path)
path_field = path_match.group(2)
path_index = path_match.group(3)
path_last = not path_match.group(4)
if path_field is not None:
obj = getattr(obj, path_field)
elif path_index is not None:
obj = obj[int(path_index)]
if path_last:
self.assertEqual(obj, range)
path_pos = path_match.end(0)
matcher_pos = matcher_match.end(0)
def assertParsesGen(self, expected_flat_ast, code,
loc_matcher="", ast_slicer=lambda x: (0, x),
only_if=lambda ver: True, validate_if=lambda: True):
for version in self.versions:
if not only_if(version):
continue
ast = self.parser_for(code, version).file_input()
flat_ast = self.flatten_ast(ast)
self.assertEqual({"ty": "Module", "body": expected_flat_ast},
flat_ast)
self.match_loc(ast, loc_matcher, ast_slicer)
compatible_pyast_version = \
(sys.version_info[0:2] == (2, 7) or
sys.version_info[0:2] == (3, 4))
if compatible_pyast_version and version == sys.version_info[0:2] and validate_if():
python_ast = pyast.parse(code.replace("·", "\n"))
flat_python_ast = self.flatten_python_ast(python_ast)
self.assertEqual({"ty": "Module", "body": expected_flat_ast},
flat_python_ast)
def assertParsesSuite(self, expected_flat_ast, code, loc_matcher="", **kwargs):
self.assertParsesGen(expected_flat_ast, code,
loc_matcher, lambda x: (0, x.body),
**kwargs)
def assertParsesExpr(self, expected_flat_ast, code, loc_matcher="", **kwargs):
self.assertParsesGen([{"ty": "Expr", "value": expected_flat_ast}], code,
loc_matcher, lambda x: (0, x.body[0].value),
**kwargs)
def assertParsesArgs(self, expected_flat_ast, code, loc_matcher="", **kwargs):
self.assertParsesGen([{"ty": "Expr", "value": {"ty": "Lambda", "body": self.ast_1,
"args": expected_flat_ast}}],
"lambda %s: 1" % code,
loc_matcher, lambda x: (7, x.body[0].value.args),
**kwargs)
def assertParsesToplevel(self, expected_flat_ast, code,
mode="file_input", interactive=False):
for version in self.versions:
ast = getattr(self.parser_for(code, version=version, interactive=interactive), mode)()
self.assertEqual(expected_flat_ast, self.flatten_ast(ast))
def assertDiagnoses(self, code, level, reason, args={}, loc_matcher="",
only_if=lambda ver: True):
for version in self.versions:
if not only_if(version):
continue
try:
self.parser_for(code, version).file_input()
self.fail("Expected a diagnostic")
except diagnostic.Error as e:
self.assertEqual(level, e.diagnostic.level)
self.assertEqual(reason, e.diagnostic.reason)
for key in args:
self.assertEqual(args[key], e.diagnostic.arguments[key],
"{{%s}}: \"%s\" != \"%s\"" %
(key, args[key], e.diagnostic.arguments[key]))
self.match_loc([e.diagnostic.location] + e.diagnostic.highlights,
loc_matcher)
def assertDiagnosesUnexpected(self, code, err_token, loc_matcher="",
only_if=lambda ver: True):
self.assertDiagnoses(code,
"fatal", "unexpected {actual}: expected {expected}",
{"actual": err_token}, loc_matcher="")
# Fixtures
ast_1 = {"ty": "Num", "n": 1}
ast_2 = {"ty": "Num", "n": 2}
ast_3 = {"ty": "Num", "n": 3}
ast_expr_1 = {"ty": "Expr", "value": {"ty": "Num", "n": 1}}
ast_expr_2 = {"ty": "Expr", "value": {"ty": "Num", "n": 2}}
ast_expr_3 = {"ty": "Expr", "value": {"ty": "Num", "n": 3}}
ast_expr_4 = {"ty": "Expr", "value": {"ty": "Num", "n": 4}}
ast_x = {"ty": "Name", "id": "x", "ctx": None}
ast_y = {"ty": "Name", "id": "y", "ctx": None}
ast_z = {"ty": "Name", "id": "z", "ctx": None}
ast_t = {"ty": "Name", "id": "t", "ctx": None}
ast_arg_x = {"ty": "arg", "arg": "x", "annotation": None}
ast_arg_y = {"ty": "arg", "arg": "y", "annotation": None}
ast_arg_z = {"ty": "arg", "arg": "z", "annotation": None}
ast_arg_t = {"ty": "arg", "arg": "t", "annotation": None}
#
# LITERALS
#
def test_int(self):
self.assertParsesExpr(
{"ty": "Num", "n": 1},
"1",
"^ loc")
def test_float(self):
self.assertParsesExpr(
{"ty": "Num", "n": 1.0},
"1.0",
"~~~ loc")
def test_complex(self):
self.assertParsesExpr(
{"ty": "Num", "n": 1j},
"1j",
"~~ loc")
def test_long(self):
self.assertParsesExpr(
{"ty": "Num", "n": test_utils.LongOnly(1)},
"1L",
"~~ loc",
only_if=lambda ver: ver < (3,))
def test_string(self):
self.assertParsesExpr(
{"ty": "Str", "s": "foo"},
"'foo'",
"~~~~~ loc"
"^ begin_loc"
" ^ end_loc",
only_if=lambda ver: ver >= (3,))
self.assertParsesExpr(
{"ty": "Str", "s": BytesOnly("foo")}, "'foo'",
only_if=lambda ver: ver < (3,))
self.assertParsesExpr(
{"ty": "Str", "s": BytesOnly(b"foo")},
"b'foo'",
"~~~~~~ loc"
"~~ begin_loc"
" ^ end_loc",
# Python 3.4 for some reason produces a Bytes node where all other
# known versions produce Str.
validate_if=lambda: sys.version_info[:2] != (3, 4))
self.assertParsesExpr(
{"ty": "Str", "s": BytesOnly(b"foo")},
"'foo'",
"~~~~~ loc"
"^ begin_loc"
" ^ end_loc",
only_if=lambda ver: ver < (3,))
self.assertParsesExpr(
{"ty": "Str", "s": "foobar"},
"'foo' 'bar'",
"~~~~~~~~~~~ loc"
"^ begin_loc"
" ^ end_loc",
only_if=lambda ver: ver >= (3,))
self.assertParsesExpr(
{"ty": "Str", "s": BytesOnly("foobar")}, "'foo' 'bar'",
only_if=lambda ver: ver < (3,))
def test_ident(self):
self.assertParsesExpr(
{"ty": "Name", "id": "foo", "ctx": None},
"foo",
"~~~ loc")
def test_named(self):
self.assertParsesExpr(
{"ty": "NameConstant", "value": None},
"None",
"~~~~ loc",
only_if=lambda ver: ver >= (3, 0))
self.assertParsesExpr(
{"ty": "NameConstant", "value": True},
"True",
"~~~~ loc",
only_if=lambda ver: ver >= (3, 0))
self.assertParsesExpr(
{"ty": "NameConstant", "value": False},
"False",
"~~~~~ loc",
only_if=lambda ver: ver >= (3, 0))
#
# OPERATORS
#
def test_unary(self):
self.assertParsesExpr(
{"ty": "UnaryOp", "op": {"ty": "UAdd"}, "operand": self.ast_1},
"+1",
"~~ loc"
"~ op.loc")
self.assertParsesExpr(
{"ty": "UnaryOp", "op": {"ty": "USub"}, "operand": self.ast_x},
"-x",
"~~ loc"
"~ op.loc")
self.assertParsesExpr(
{"ty": "UnaryOp", "op": {"ty": "Invert"}, "operand": self.ast_1},
"~1",
"~~ loc"
"~ op.loc")
def test_binary(self):
self.assertParsesExpr(
{"ty": "BinOp", "op": {"ty": "Pow"}, "left": self.ast_1, "right": self.ast_1},
"1 ** 1",
"~~~~~~ loc"
" ~~ op.loc")
self.assertParsesExpr(
{"ty": "BinOp", "op": {"ty": "Mult"}, "left": self.ast_1, "right": self.ast_1},
"1 * 1",
"~~~~~ loc"
" ^ op.loc")
self.assertParsesExpr(
{"ty": "BinOp", "op": {"ty": "MatMult"}, "left": self.ast_x, "right": self.ast_x},
"x @ x",
"~~~~~ loc"
" ^ op.loc",
only_if=lambda ver: ver >= (3, 5))
self.assertParsesExpr(
{"ty": "BinOp", "op": {"ty": "Div"}, "left": self.ast_1, "right": self.ast_1},
"1 / 1",
"~~~~~ loc"
" ^ op.loc")
self.assertParsesExpr(
{"ty": "BinOp", "op": {"ty": "Mod"}, "left": self.ast_1, "right": self.ast_1},
"1 % 1",
"~~~~~ loc"
" ^ op.loc")
self.assertParsesExpr(
{"ty": "BinOp", "op": {"ty": "FloorDiv"}, "left": self.ast_1, "right": self.ast_1},
"1 // 1",
"~~~~~~ loc"
" ~~ op.loc")
self.assertParsesExpr(
{"ty": "BinOp", "op": {"ty": "Add"}, "left": self.ast_1, "right": self.ast_1},
"1 + 1",
"~~~~~ loc"
" ^ op.loc")
self.assertParsesExpr(
{"ty": "BinOp", "op": {"ty": "Sub"}, "left": self.ast_1, "right": self.ast_1},
"1 - 1",
"~~~~~ loc"
" ^ op.loc")
def test_bitwise(self):
self.assertParsesExpr(
{"ty": "BinOp", "op": {"ty": "LShift"}, "left": self.ast_1, "right": self.ast_1},
"1 << 1",
"~~~~~~ loc"
" ~~ op.loc")
self.assertParsesExpr(
{"ty": "BinOp", "op": {"ty": "RShift"}, "left": self.ast_1, "right": self.ast_1},
"1 >> 1",
"~~~~~~ loc"
" ~~ op.loc")
self.assertParsesExpr(
{"ty": "BinOp", "op": {"ty": "BitAnd"}, "left": self.ast_1, "right": self.ast_1},
"1 & 1",
"~~~~~ loc"
" ^ op.loc")
self.assertParsesExpr(
{"ty": "BinOp", "op": {"ty": "BitOr"}, "left": self.ast_1, "right": self.ast_1},
"1 | 1",
"~~~~~ loc"
" ^ op.loc")
self.assertParsesExpr(
{"ty": "BinOp", "op": {"ty": "BitXor"}, "left": self.ast_1, "right": self.ast_1},
"1 ^ 1",
"~~~~~ loc"
" ^ op.loc")
def test_compare(self):
self.assertParsesExpr(
{"ty": "Compare", "ops": [{"ty": "Lt"}],
"left": self.ast_1, "comparators": [self.ast_1]},
"1 < 1",
"~~~~~ loc"
" ^ ops.0.loc")
self.assertParsesExpr(
{"ty": "Compare", "ops": [{"ty": "LtE"}],
"left": self.ast_1, "comparators": [self.ast_1]},
"1 <= 1",
"~~~~~~ loc"
" ~~ ops.0.loc")
self.assertParsesExpr(
{"ty": "Compare", "ops": [{"ty": "Gt"}],
"left": self.ast_1, "comparators": [self.ast_1]},
"1 > 1",
"~~~~~ loc"
" ^ ops.0.loc")
self.assertParsesExpr(
{"ty": "Compare", "ops": [{"ty": "GtE"}],
"left": self.ast_1, "comparators": [self.ast_1]},
"1 >= 1",
"~~~~~~ loc"
" ~~ ops.0.loc")
self.assertParsesExpr(
{"ty": "Compare", "ops": [{"ty": "Eq"}],
"left": self.ast_1, "comparators": [self.ast_1]},
"1 == 1",
"~~~~~~ loc"
" ~~ ops.0.loc")
self.assertParsesExpr(
{"ty": "Compare", "ops": [{"ty": "NotEq"}],
"left": self.ast_1, "comparators": [self.ast_1]},
"1 != 1",
"~~~~~~ loc"
" ~~ ops.0.loc")
self.assertParsesExpr(
{"ty": "Compare", "ops": [{"ty": "NotEq"}],
"left": self.ast_1, "comparators": [self.ast_1]},
"1 <> 1",
"~~~~~~ loc"
" ~~ ops.0.loc",
only_if=lambda ver: ver < (3, 0))
self.assertParsesExpr(
{"ty": "Compare", "ops": [{"ty": "In"}],
"left": self.ast_1, "comparators": [self.ast_1]},
"1 in 1",
"~~~~~~ loc"
" ~~ ops.0.loc")
self.assertParsesExpr(
{"ty": "Compare", "ops": [{"ty": "NotIn"}],
"left": self.ast_1, "comparators": [self.ast_1]},
"1 not in 1",
"~~~~~~~~~~ loc"
" ~~~~~~ ops.0.loc")
self.assertParsesExpr(
{"ty": "Compare", "ops": [{"ty": "Is"}],
"left": self.ast_1, "comparators": [self.ast_1]},
"1 is 1",
"~~~~~~ loc"
" ~~ ops.0.loc")
self.assertParsesExpr(
{"ty": "Compare", "ops": [{"ty": "IsNot"}],
"left": self.ast_1, "comparators": [self.ast_1]},
"1 is not 1",
"~~~~~~~~~~ loc"
" ~~~~~~ ops.0.loc")
def test_compare_multi(self):
self.assertParsesExpr(
{"ty": "Compare", "ops": [{"ty": "Lt"}, {"ty": "LtE"}],
"left": self.ast_1,
"comparators": [{"ty": "Num", "n": 2}, {"ty": "Num", "n": 3}]},
"1 < 2 <= 3",
"~~~~~~~~~~ loc"
" ^ ops.0.loc"
" ~~ ops.1.loc")
def test_boolop(self):
self.assertParsesExpr(
{"ty": "BoolOp", "op": {"ty": "And"}, "values": [self.ast_1, self.ast_1]},
"1 and 1",
"~~~~~~~ loc"
" ~~~ op_locs.0")
self.assertParsesExpr(
{"ty": "BoolOp", "op": {"ty": "Or"}, "values": [self.ast_1, self.ast_1]},
"1 or 1",
"~~~~~~ loc"
" ~~ op_locs.0")
self.assertParsesExpr(
{"ty": "UnaryOp", "op": {"ty": "Not"}, "operand": self.ast_1},
"not 1",
"~~~~~ loc"
"~~~ op.loc")
def test_boolop_multi(self):
self.assertParsesExpr(
{"ty": "BoolOp", "op": {"ty": "Or"}, "values": [self.ast_1, self.ast_1, self.ast_1]},
"1 or 1 or 1",
"~~~~~~~~~~~ loc"
" ~~ op_locs.0"
" ~~ op_locs.1")
#
# COMPOUND LITERALS
#
def test_tuple(self):
self.assertParsesExpr(
{"ty": "Tuple", "elts": [], "ctx": None},
"()",
"^ begin_loc"
" ^ end_loc"
"~~ loc")
self.assertParsesExpr(
{"ty": "Tuple", "elts": [self.ast_1], "ctx": None},
"(1,)",
"~~~~ loc")
self.assertParsesExpr(
{"ty": "Tuple", "elts": [self.ast_1, self.ast_1], "ctx": None},
"(1,1)",
"~~~~~ loc")
self.assertParsesExpr(
self.ast_1,
"(1)",
" ~ loc")
def test_list(self):
self.assertParsesExpr(
{"ty": "List", "elts": [], "ctx": None},
"[]",
"^ begin_loc"
" ^ end_loc"
"~~ loc")
self.assertParsesExpr(
{"ty": "List", "elts": [self.ast_1], "ctx": None},
"[1]",
"~~~ loc")
self.assertParsesExpr(
{"ty": "List", "elts": [self.ast_1, self.ast_1], "ctx": None},
"[1,1]",
"~~~~~ loc")
def test_dict(self):
self.assertParsesExpr(
{"ty": "Dict", "keys": [], "values": []},
"{}",
"^ begin_loc"
" ^ end_loc"
"~~ loc")
self.assertParsesExpr(
{"ty": "Dict", "keys": [self.ast_x], "values": [self.ast_1]},
"{x: 1}",
"^ begin_loc"
" ^ end_loc"
" ^ colon_locs.0"
"~~~~~~ loc")
def test_set(self):
self.assertParsesExpr(
{"ty": "Set", "elts": [self.ast_1]},
"{1}",
"^ begin_loc"
" ^ end_loc"
"~~~ loc",
only_if=lambda ver: ver >= (2, 7))
self.assertParsesExpr(
{"ty": "Set", "elts": [self.ast_1, self.ast_2]},
"{1, 2}",
"~~~~~~ loc",
only_if=lambda ver: ver >= (2, 7))
def test_repr(self):
self.assertParsesExpr(
{"ty": "Repr", "value": self.ast_1},
"`1`",
"^ begin_loc"
" ^ end_loc"
"~~~ loc",
only_if=lambda ver: ver < (3, 0))
#
# GENERATOR AND CONDITIONAL EXPRESSIONS
#
def test_list_comp(self):
self.assertParsesExpr(
{"ty": "ListComp", "elt": self.ast_x, "generators": [
{"ty": "comprehension", "iter": self.ast_z, "target": self.ast_y, "ifs": []}
]},
"[x for y in z]",
"^ begin_loc"
" ~~~ generators.0.for_loc"
" ~~ generators.0.in_loc"
" ~~~~~~~~~~ generators.0.loc"
" ^ end_loc"
"~~~~~~~~~~~~~~ loc")
self.assertParsesExpr(
{"ty": "ListComp", "elt": self.ast_x, "generators": [
{"ty": "comprehension", "iter": self.ast_z, "target": self.ast_y,
"ifs": [self.ast_t]}
]},
"[x for y in z if t]",
" ~~ generators.0.if_locs.0"
" ~~~~~~~~~~~~~~~ generators.0.loc"
"~~~~~~~~~~~~~~~~~~~ loc")
self.assertParsesExpr(
{"ty": "ListComp", "elt": self.ast_x, "generators": [
{"ty": "comprehension", "iter": self.ast_z, "target": self.ast_y,
"ifs": [self.ast_x]},
{"ty": "comprehension", "iter": self.ast_z, "target": self.ast_t, "ifs": []}
]},
"[x for y in z if x for t in z]",
"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ loc")
def test_dict_comp(self):
self.assertParsesExpr(
{"ty": "DictComp", "key": self.ast_x, "value": self.ast_y,
"generators": [{"ty": "comprehension", "target": self.ast_z,
"iter": self.ast_t, "ifs": []}]},
"{x: y for z in t}",
"^ begin_loc"
" ^ end_loc"
" ^ colon_loc"
"~~~~~~~~~~~~~~~~~ loc",
only_if=lambda ver: ver >= (2, 7))
def test_set_comp(self):
self.assertParsesExpr(
{"ty": "SetComp", "elt": self.ast_x,
"generators": [{"ty": "comprehension", "target": self.ast_y,
"iter": self.ast_z, "ifs": []}]},
"{x for y in z}",
"^ begin_loc"
" ^ end_loc"
"~~~~~~~~~~~~~~ loc",
only_if=lambda ver: ver >= (2, 7))
def test_gen_comp(self):
self.assertParsesExpr(
{"ty": "GeneratorExp", "elt": self.ast_x, "generators": [
{"ty": "comprehension", "iter": self.ast_z, "target": self.ast_y, "ifs": []}
]},
"(x for y in z)",
"^ begin_loc"
" ~~~ generators.0.for_loc"
" ~~ generators.0.in_loc"
" ~~~~~~~~~~ generators.0.loc"
" ^ end_loc"
"~~~~~~~~~~~~~~ loc")
self.assertParsesExpr(
{"ty": "GeneratorExp", "elt": self.ast_x, "generators": [
{"ty": "comprehension", "iter": self.ast_z, "target": self.ast_y,
"ifs": [self.ast_t]}
]},
"(x for y in z if t)",
" ~~ generators.0.if_locs.0"
" ~~~~~~~~~~~~~~~ generators.0.loc"
"~~~~~~~~~~~~~~~~~~~ loc")
self.assertParsesExpr(
{"ty": "GeneratorExp", "elt": self.ast_x, "generators": [
{"ty": "comprehension", "iter": self.ast_z, "target": self.ast_y,
"ifs": [self.ast_x]},
{"ty": "comprehension", "iter": self.ast_z, "target": self.ast_t, "ifs": []}
]},
"(x for y in z if x for t in z)",
"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ loc")
def test_list_comp_starred(self):
self.assertParsesExpr(
{"ty": "GeneratorExp", "elt": {"ty": "Starred", "value": self.ast_x, "ctx": None},
"generators": [
{"ty": "comprehension", "iter": self.ast_z, "target": self.ast_y, "ifs": []}
]},
"(*x for y in z)",
only_if=lambda ver: ver >= (3, 2))
self.assertParsesExpr(
{"ty": "ListComp", "elt": {"ty": "Starred", "value": self.ast_x, "ctx": None},
"generators": [
{"ty": "comprehension", "iter": self.ast_z, "target": self.ast_y, "ifs": []}
]},
"[*x for y in z]",
only_if=lambda ver: ver >= (3, 2))
def test_yield_expr(self):
self.assertParsesExpr(
{"ty": "Yield", "value": self.ast_1},
"(yield 1)",
" ~~~~~ yield_loc"
" ~~~~~~~ loc")
def test_if_expr(self):
self.assertParsesExpr(
{"ty": "IfExp", "body": self.ast_x, "test": self.ast_y, "orelse": self.ast_z},
"x if y else z",
" ~~ if_loc"
" ~~~~ else_loc"
"~~~~~~~~~~~~~ loc")
def test_lambda(self):
self.assertParsesExpr(
{"ty": "Lambda",
"args": {"ty": "arguments", "args": [], "defaults": [],
"kwonlyargs": [], "kw_defaults": [],
"kwarg": None, "vararg": None},
"body": self.ast_x},
"lambda: x",
"~~~~~~ lambda_loc"
" < args.loc"
" ^ colon_loc"
"~~~~~~~~~ loc",
validate_if=lambda: sys.version_info >= (3, 2))
def test_lambda_nocond(self):
self.assertParsesExpr(
{"ty": "GeneratorExp", "elt": self.ast_x, "generators": [
{"ty": "comprehension", "iter": self.ast_z, "target": self.ast_y,
"ifs": [{"ty": "Lambda",
"args": {"ty": "arguments", "args": [], "defaults": [],
"kwonlyargs": [], "kw_defaults": [],
"kwarg": None, "vararg": None},
"body": self.ast_t}
]}
]},
"(x for y in z if lambda: t)",
" ~~~~~~ generators.0.ifs.0.lambda_loc"
" < generators.0.ifs.0.args.loc"
" ^ generators.0.ifs.0.colon_loc"
" ~~~~~~~~~ generators.0.ifs.0.loc",
validate_if=lambda: sys.version_info >= (3, 2))
self.assertParsesExpr(
{"ty": "GeneratorExp", "elt": self.ast_x, "generators": [
{"ty": "comprehension", "iter": self.ast_z, "target": self.ast_y,
"ifs": [{"ty": "Lambda",
"args": {"ty": "arguments", "args": [self.ast_arg_t], "defaults": [],
"kwonlyargs": [], "kw_defaults": [],
"kwarg": None, "vararg": None},
"body": self.ast_t}
]}
]},
"(x for y in z if lambda t: t)",
validate_if=lambda: sys.version_info >= (3, 2))
#
# CALLS, ATTRIBUTES AND SUBSCRIPTS
#
def test_call(self):
self.assertParsesExpr(
{"ty": "Call", "func": self.ast_x, "starargs": None, "kwargs": None,
"args": [], "keywords": []},
"x()",
" ^ begin_loc"
" ^ end_loc"
"~~~ loc")
self.assertParsesExpr(
{"ty": "Call", "func": self.ast_x, "starargs": None, "kwargs": None,
"args": [self.ast_y, self.ast_z], "keywords": []},
"x(y, z)",
"~~~~~~~ loc")
self.assertParsesExpr(
{"ty": "Call", "func": self.ast_x, "starargs": None, "kwargs": None,
"args": [self.ast_y], "keywords": [
{ "ty": "keyword", "arg": "z", "value": self.ast_z}
]},
"x(y, z=z)",
" ^ keywords.0.arg_loc"
" ^ keywords.0.equals_loc"
" ~~~ keywords.0.loc"
"~~~~~~~~~ loc")
self.assertParsesExpr(
{"ty": "Call", "func": self.ast_x, "starargs": None, "kwargs": None,
"args": [self.ast_y], "keywords": []},
"x(y,)",
"~~~~~ loc")
self.assertParsesExpr(
{"ty": "Call", "func": self.ast_x, "starargs": self.ast_y, "kwargs": None,
"args": [], "keywords": []},
"x(*y)",
" ^ star_loc"
"~~~~~ loc",
# This and following tests fail because of a grammar bug (conflict)
# in upstream Python. We get different results because our parsers
# are different, and upstream works more or less by accident.
# Upstream "fixed" it with a gross workaround in a minor version
# (at least 3.1.5).
# Not really worth fixing for us, so skip.
only_if=lambda ver: ver not in ((3, 0), (3, 1)))
self.assertParsesExpr(
{"ty": "Call", "func": self.ast_x, "starargs": self.ast_y, "kwargs": self.ast_z,
"args": [], "keywords": []},
"x(*y, **z)",
" ^ star_loc"
" ^^ dstar_loc"
"~~~~~~~~~~ loc",
only_if=lambda ver: ver not in ((3, 0), (3, 1)))
self.assertParsesExpr(
{"ty": "Call", "func": self.ast_x, "starargs": self.ast_y, "kwargs": self.ast_z,
"args": [], "keywords": [{"ty": "keyword", "arg": "t", "value": self.ast_t}]},
"x(*y, t=t, **z)",
" ^ star_loc"
" ^^ dstar_loc"
"~~~~~~~~~~~~~~~ loc",
only_if=lambda ver: ver not in ((3, 0), (3, 1)))
self.assertParsesExpr(
{"ty": "Call", "func": self.ast_x, "starargs": self.ast_z, "kwargs": self.ast_t,
"args": [self.ast_y], "keywords": []},
"x(y, *z, **t)",
" ^ star_loc"
" ^^ dstar_loc"
"~~~~~~~~~~~~~ loc",
only_if=lambda ver: ver not in ((3, 0), (3, 1)))
self.assertParsesExpr(
{"ty": "Call", "func": self.ast_x, "starargs": None, "kwargs": self.ast_z,
"args": [], "keywords": []},
"x(**z)",
" ^^ dstar_loc"
"~~~~~~ loc")
self.assertParsesExpr(
{"ty": "Call", "func": self.ast_x, "starargs": None, "kwargs": self.ast_z,
"args": [self.ast_1], "keywords": []},
"x(1, **z)")
self.assertParsesExpr(
{"ty": "Call", "func": self.ast_x, "starargs": None, "kwargs": None,
"args": [self.ast_1, self.ast_2], "keywords": []},
"x(1, 2,)")
self.assertParsesExpr(
{"ty": "Call", "func": self.ast_x, "starargs": None, "kwargs": None,
"keywords": [], "args": [
{"ty": "GeneratorExp", "elt": self.ast_y, "generators": [
{"ty": "comprehension", "iter": self.ast_z, "target": self.ast_y, "ifs": []}
]}
]},
"x(y for y in z)")
def test_subscript(self):
self.assertParsesExpr(
{"ty": "Subscript", "value": self.ast_x, "ctx": None,
"slice": {"ty": "Index", "value": self.ast_1}},
"x[1]",
" ^ begin_loc"
" ^ slice.loc"
" ^ end_loc"
"~~~~ loc")
self.assertParsesExpr(
{"ty": "Subscript", "value": self.ast_x, "ctx": None,
"slice": {"ty": "Index", "value": {"ty": "Tuple", "ctx": None, "elts": [
self.ast_1, self.ast_2
]}}},
"x[1, 2]",
" ~~~~ slice.loc"
"~~~~~~~ loc")
self.assertParsesExpr(
{"ty": "Subscript", "value": self.ast_x, "ctx": None,
"slice": {"ty": "Slice", "lower": self.ast_1, "upper": None, "step": None}},
"x[1:]",
" ^ slice.bound_colon_loc"
" ~~ slice.loc"
"~~~~~ loc")
self.assertParsesExpr(
{"ty": "Subscript", "value": self.ast_x, "ctx": None,
"slice": {"ty": "Slice", "lower": None, "upper": self.ast_1, "step": None}},
"x[:1]",
" ^ slice.bound_colon_loc"
" ~~ slice.loc"
"~~~~~ loc")
self.assertParsesExpr(
{"ty": "Subscript", "value": self.ast_x, "ctx": None,
"slice": {"ty": "Slice", "lower": self.ast_1, "upper": self.ast_2, "step": None}},
"x[1:2]",
" ^ slice.bound_colon_loc"
" ~~~ slice.loc"
"~~~~~~ loc")
self.assertParsesExpr(
{"ty": "Subscript", "value": self.ast_x, "ctx": None,
"slice": {"ty": "ExtSlice", "dims": [
{"ty": "Slice", "lower": self.ast_1, "upper": self.ast_2, "step": None},
{"ty": "Index", "value": self.ast_2},
]}},
"x[1:2, 2]",
" ~~~~~~ slice.loc"
"~~~~~~~~~ loc")
self.assertParsesExpr(
{"ty": "Subscript", "value": self.ast_x, "ctx": None,
"slice": {"ty": "Slice", "lower": self.ast_1, "upper": self.ast_2, "step": None}},
"x[1:2:]",
" ^ slice.bound_colon_loc"
" ^ slice.step_colon_loc"
" ~~~~ slice.loc"
"~~~~~~~ loc",
# A Python bug places ast.Name(id='None') instead of None in step on <3.0
validate_if=lambda: sys.version_info >= (3, 0))
self.assertParsesExpr(
{"ty": "Subscript", "value": self.ast_x, "ctx": None,
"slice": {"ty": "Slice", "lower": self.ast_1, "upper": self.ast_2, "step": self.ast_3}},
"x[1:2:3]",
" ^ slice.bound_colon_loc"
" ^ slice.step_colon_loc"
" ~~~~~ slice.loc"
"~~~~~~~~ loc")
self.assertParsesExpr(
{"ty": "Subscript", "value": self.ast_x, "ctx": None,
"slice": {"ty": "Ellipsis"}},
"x[...]",
" ~~~ slice.loc"
"~~~~~~ loc",
only_if=lambda ver: ver < (3, 0))
self.assertParsesExpr(
{"ty": "Subscript", "value": self.ast_x, "ctx": None,
"slice": {"ty": "Index", "value": {"ty": "Ellipsis"}}},
"x[...]",
" ~~~ slice.loc"
"~~~~~~ loc",
only_if=lambda ver: ver >= (3, 0))
def test_attribute(self):
self.assertParsesExpr(
{"ty": "Attribute", "value": self.ast_x, "attr": "zz", "ctx": None},
"x.zz",
" ^ dot_loc"
" ~~ attr_loc"
"~~~~ loc")
#
# SIMPLE STATEMENTS
#
def test_assign(self):
self.assertParsesSuite(
[{"ty": "Assign", "targets": [self.ast_x], "value": self.ast_1}],
"x = 1",
"~~~~~ 0.loc"
" ^ 0.op_locs.0")