• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1"""This module tests SyntaxErrors.
2
3Here's an example of the sort of thing that is tested.
4
5>>> def f(x):
6...     global x
7Traceback (most recent call last):
8SyntaxError: name 'x' is parameter and global
9
10The tests are all raise SyntaxErrors.  They were created by checking
11each C call that raises SyntaxError.  There are several modules that
12raise these exceptions-- ast.c, compile.c, future.c, pythonrun.c, and
13symtable.c.
14
15The parser itself outlaws a lot of invalid syntax.  None of these
16errors are tested here at the moment.  We should add some tests; since
17there are infinitely many programs with invalid syntax, we would need
18to be judicious in selecting some.
19
20The compiler generates a synthetic module name for code executed by
21doctest.  Since all the code comes from the same module, a suffix like
22[1] is appended to the module name, As a consequence, changing the
23order of tests in this module means renumbering all the errors after
24it.  (Maybe we should enable the ellipsis option for these tests.)
25
26In ast.c, syntax errors are raised by calling ast_error().
27
28Errors from set_context():
29
30>>> obj.None = 1
31Traceback (most recent call last):
32SyntaxError: invalid syntax
33
34>>> None = 1
35Traceback (most recent call last):
36SyntaxError: cannot assign to None
37
38>>> obj.True = 1
39Traceback (most recent call last):
40SyntaxError: invalid syntax
41
42>>> True = 1
43Traceback (most recent call last):
44SyntaxError: cannot assign to True
45
46>>> (True := 1)
47Traceback (most recent call last):
48SyntaxError: cannot use assignment expressions with True
49
50>>> obj.__debug__ = 1
51Traceback (most recent call last):
52SyntaxError: cannot assign to __debug__
53
54>>> __debug__ = 1
55Traceback (most recent call last):
56SyntaxError: cannot assign to __debug__
57
58>>> (__debug__ := 1)
59Traceback (most recent call last):
60SyntaxError: cannot assign to __debug__
61
62>>> f() = 1
63Traceback (most recent call last):
64SyntaxError: cannot assign to function call
65
66>>> del f()
67Traceback (most recent call last):
68SyntaxError: cannot delete function call
69
70>>> a + 1 = 2
71Traceback (most recent call last):
72SyntaxError: cannot assign to operator
73
74>>> (x for x in x) = 1
75Traceback (most recent call last):
76SyntaxError: cannot assign to generator expression
77
78>>> 1 = 1
79Traceback (most recent call last):
80SyntaxError: cannot assign to literal
81
82>>> "abc" = 1
83Traceback (most recent call last):
84SyntaxError: cannot assign to literal
85
86>>> b"" = 1
87Traceback (most recent call last):
88SyntaxError: cannot assign to literal
89
90>>> ... = 1
91Traceback (most recent call last):
92SyntaxError: cannot assign to Ellipsis
93
94>>> `1` = 1
95Traceback (most recent call last):
96SyntaxError: invalid syntax
97
98If the left-hand side of an assignment is a list or tuple, an illegal
99expression inside that contain should still cause a syntax error.
100This test just checks a couple of cases rather than enumerating all of
101them.
102
103>>> (a, "b", c) = (1, 2, 3)
104Traceback (most recent call last):
105SyntaxError: cannot assign to literal
106
107>>> (a, True, c) = (1, 2, 3)
108Traceback (most recent call last):
109SyntaxError: cannot assign to True
110
111>>> (a, __debug__, c) = (1, 2, 3)
112Traceback (most recent call last):
113SyntaxError: cannot assign to __debug__
114
115>>> (a, *True, c) = (1, 2, 3)
116Traceback (most recent call last):
117SyntaxError: cannot assign to True
118
119>>> (a, *__debug__, c) = (1, 2, 3)
120Traceback (most recent call last):
121SyntaxError: cannot assign to __debug__
122
123>>> [a, b, c + 1] = [1, 2, 3]
124Traceback (most recent call last):
125SyntaxError: cannot assign to operator
126
127>>> [a, b[1], c + 1] = [1, 2, 3]
128Traceback (most recent call last):
129SyntaxError: cannot assign to operator
130
131>>> [a, b.c.d, c + 1] = [1, 2, 3]
132Traceback (most recent call last):
133SyntaxError: cannot assign to operator
134
135>>> a if 1 else b = 1
136Traceback (most recent call last):
137SyntaxError: cannot assign to conditional expression
138
139>>> True = True = 3
140Traceback (most recent call last):
141SyntaxError: cannot assign to True
142
143>>> x = y = True = z = 3
144Traceback (most recent call last):
145SyntaxError: cannot assign to True
146
147>>> x = y = yield = 1
148Traceback (most recent call last):
149SyntaxError: assignment to yield expression not possible
150
151>>> a, b += 1, 2
152Traceback (most recent call last):
153SyntaxError: 'tuple' is an illegal expression for augmented assignment
154
155>>> (a, b) += 1, 2
156Traceback (most recent call last):
157SyntaxError: 'tuple' is an illegal expression for augmented assignment
158
159>>> [a, b] += 1, 2
160Traceback (most recent call last):
161SyntaxError: 'list' is an illegal expression for augmented assignment
162
163Invalid targets in `for` loops and `with` statements should also
164produce a specialized error message
165
166>>> for a() in b: pass
167Traceback (most recent call last):
168SyntaxError: cannot assign to function call
169
170>>> for (a, b()) in b: pass
171Traceback (most recent call last):
172SyntaxError: cannot assign to function call
173
174>>> for [a, b()] in b: pass
175Traceback (most recent call last):
176SyntaxError: cannot assign to function call
177
178>>> for (*a, b, c+1) in b: pass
179Traceback (most recent call last):
180SyntaxError: cannot assign to operator
181
182>>> for (x, *(y, z.d())) in b: pass
183Traceback (most recent call last):
184SyntaxError: cannot assign to function call
185
186>>> for a, b() in c: pass
187Traceback (most recent call last):
188SyntaxError: cannot assign to function call
189
190>>> for i < (): pass
191Traceback (most recent call last):
192SyntaxError: invalid syntax
193
194>>> for a, b
195Traceback (most recent call last):
196SyntaxError: invalid syntax
197
198>>> with a as b(): pass
199Traceback (most recent call last):
200SyntaxError: cannot assign to function call
201
202>>> with a as (b, c()): pass
203Traceback (most recent call last):
204SyntaxError: cannot assign to function call
205
206>>> with a as [b, c()]: pass
207Traceback (most recent call last):
208SyntaxError: cannot assign to function call
209
210>>> with a as (*b, c, d+1): pass
211Traceback (most recent call last):
212SyntaxError: cannot assign to operator
213
214>>> with a as (x, *(y, z.d())): pass
215Traceback (most recent call last):
216SyntaxError: cannot assign to function call
217
218>>> with a as b, c as d(): pass
219Traceback (most recent call last):
220SyntaxError: cannot assign to function call
221
222>>> with a as b
223Traceback (most recent call last):
224SyntaxError: invalid syntax
225
226>>> p = p =
227Traceback (most recent call last):
228SyntaxError: invalid syntax
229
230From compiler_complex_args():
231
232>>> def f(None=1):
233...     pass
234Traceback (most recent call last):
235SyntaxError: invalid syntax
236
237From ast_for_arguments():
238
239>>> def f(x, y=1, z):
240...     pass
241Traceback (most recent call last):
242SyntaxError: non-default argument follows default argument
243
244>>> def f(x, None):
245...     pass
246Traceback (most recent call last):
247SyntaxError: invalid syntax
248
249>>> def f(*None):
250...     pass
251Traceback (most recent call last):
252SyntaxError: invalid syntax
253
254>>> def f(**None):
255...     pass
256Traceback (most recent call last):
257SyntaxError: invalid syntax
258
259>>> import ast; ast.parse('''
260... def f(
261...     *, # type: int
262...     a, # type: int
263... ):
264...     pass
265... ''', type_comments=True)
266Traceback (most recent call last):
267SyntaxError: bare * has associated type comment
268
269
270From ast_for_funcdef():
271
272>>> def None(x):
273...     pass
274Traceback (most recent call last):
275SyntaxError: invalid syntax
276
277
278From ast_for_call():
279
280>>> def f(it, *varargs, **kwargs):
281...     return list(it)
282>>> L = range(10)
283>>> f(x for x in L)
284[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
285>>> f(x for x in L, 1)
286Traceback (most recent call last):
287SyntaxError: Generator expression must be parenthesized
288>>> f(x for x in L, y=1)
289Traceback (most recent call last):
290SyntaxError: Generator expression must be parenthesized
291>>> f(x for x in L, *[])
292Traceback (most recent call last):
293SyntaxError: Generator expression must be parenthesized
294>>> f(x for x in L, **{})
295Traceback (most recent call last):
296SyntaxError: Generator expression must be parenthesized
297>>> f(L, x for x in L)
298Traceback (most recent call last):
299SyntaxError: Generator expression must be parenthesized
300>>> f(x for x in L, y for y in L)
301Traceback (most recent call last):
302SyntaxError: Generator expression must be parenthesized
303>>> f(x for x in L,)
304Traceback (most recent call last):
305SyntaxError: Generator expression must be parenthesized
306>>> f((x for x in L), 1)
307[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
308>>> class C(x for x in L):
309...     pass
310Traceback (most recent call last):
311SyntaxError: invalid syntax
312
313>>> def g(*args, **kwargs):
314...     print(args, sorted(kwargs.items()))
315>>> g(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
316...   20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
317...   38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
318...   56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73,
319...   74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91,
320...   92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107,
321...   108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
322...   122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135,
323...   136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
324...   150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163,
325...   164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177,
326...   178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191,
327...   192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205,
328...   206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219,
329...   220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233,
330...   234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247,
331...   248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261,
332...   262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275,
333...   276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289,
334...   290, 291, 292, 293, 294, 295, 296, 297, 298, 299)  # doctest: +ELLIPSIS
335(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ..., 297, 298, 299) []
336
337>>> g(a000=0, a001=1, a002=2, a003=3, a004=4, a005=5, a006=6, a007=7, a008=8,
338...   a009=9, a010=10, a011=11, a012=12, a013=13, a014=14, a015=15, a016=16,
339...   a017=17, a018=18, a019=19, a020=20, a021=21, a022=22, a023=23, a024=24,
340...   a025=25, a026=26, a027=27, a028=28, a029=29, a030=30, a031=31, a032=32,
341...   a033=33, a034=34, a035=35, a036=36, a037=37, a038=38, a039=39, a040=40,
342...   a041=41, a042=42, a043=43, a044=44, a045=45, a046=46, a047=47, a048=48,
343...   a049=49, a050=50, a051=51, a052=52, a053=53, a054=54, a055=55, a056=56,
344...   a057=57, a058=58, a059=59, a060=60, a061=61, a062=62, a063=63, a064=64,
345...   a065=65, a066=66, a067=67, a068=68, a069=69, a070=70, a071=71, a072=72,
346...   a073=73, a074=74, a075=75, a076=76, a077=77, a078=78, a079=79, a080=80,
347...   a081=81, a082=82, a083=83, a084=84, a085=85, a086=86, a087=87, a088=88,
348...   a089=89, a090=90, a091=91, a092=92, a093=93, a094=94, a095=95, a096=96,
349...   a097=97, a098=98, a099=99, a100=100, a101=101, a102=102, a103=103,
350...   a104=104, a105=105, a106=106, a107=107, a108=108, a109=109, a110=110,
351...   a111=111, a112=112, a113=113, a114=114, a115=115, a116=116, a117=117,
352...   a118=118, a119=119, a120=120, a121=121, a122=122, a123=123, a124=124,
353...   a125=125, a126=126, a127=127, a128=128, a129=129, a130=130, a131=131,
354...   a132=132, a133=133, a134=134, a135=135, a136=136, a137=137, a138=138,
355...   a139=139, a140=140, a141=141, a142=142, a143=143, a144=144, a145=145,
356...   a146=146, a147=147, a148=148, a149=149, a150=150, a151=151, a152=152,
357...   a153=153, a154=154, a155=155, a156=156, a157=157, a158=158, a159=159,
358...   a160=160, a161=161, a162=162, a163=163, a164=164, a165=165, a166=166,
359...   a167=167, a168=168, a169=169, a170=170, a171=171, a172=172, a173=173,
360...   a174=174, a175=175, a176=176, a177=177, a178=178, a179=179, a180=180,
361...   a181=181, a182=182, a183=183, a184=184, a185=185, a186=186, a187=187,
362...   a188=188, a189=189, a190=190, a191=191, a192=192, a193=193, a194=194,
363...   a195=195, a196=196, a197=197, a198=198, a199=199, a200=200, a201=201,
364...   a202=202, a203=203, a204=204, a205=205, a206=206, a207=207, a208=208,
365...   a209=209, a210=210, a211=211, a212=212, a213=213, a214=214, a215=215,
366...   a216=216, a217=217, a218=218, a219=219, a220=220, a221=221, a222=222,
367...   a223=223, a224=224, a225=225, a226=226, a227=227, a228=228, a229=229,
368...   a230=230, a231=231, a232=232, a233=233, a234=234, a235=235, a236=236,
369...   a237=237, a238=238, a239=239, a240=240, a241=241, a242=242, a243=243,
370...   a244=244, a245=245, a246=246, a247=247, a248=248, a249=249, a250=250,
371...   a251=251, a252=252, a253=253, a254=254, a255=255, a256=256, a257=257,
372...   a258=258, a259=259, a260=260, a261=261, a262=262, a263=263, a264=264,
373...   a265=265, a266=266, a267=267, a268=268, a269=269, a270=270, a271=271,
374...   a272=272, a273=273, a274=274, a275=275, a276=276, a277=277, a278=278,
375...   a279=279, a280=280, a281=281, a282=282, a283=283, a284=284, a285=285,
376...   a286=286, a287=287, a288=288, a289=289, a290=290, a291=291, a292=292,
377...   a293=293, a294=294, a295=295, a296=296, a297=297, a298=298, a299=299)
378...  # doctest: +ELLIPSIS
379() [('a000', 0), ('a001', 1), ('a002', 2), ..., ('a298', 298), ('a299', 299)]
380
381>>> class C:
382...     def meth(self, *args):
383...         return args
384>>> obj = C()
385>>> obj.meth(
386...   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
387...   20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
388...   38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
389...   56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73,
390...   74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91,
391...   92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107,
392...   108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
393...   122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135,
394...   136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
395...   150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163,
396...   164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177,
397...   178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191,
398...   192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205,
399...   206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219,
400...   220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233,
401...   234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247,
402...   248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261,
403...   262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275,
404...   276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289,
405...   290, 291, 292, 293, 294, 295, 296, 297, 298, 299)  # doctest: +ELLIPSIS
406(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ..., 297, 298, 299)
407
408# >>> f(lambda x: x[0] = 3)
409# Traceback (most recent call last):
410# SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
411
412The grammar accepts any test (basically, any expression) in the
413keyword slot of a call site.  Test a few different options.
414
415# >>> f(x()=2)
416# Traceback (most recent call last):
417# SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
418# >>> f(a or b=1)
419# Traceback (most recent call last):
420# SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
421# >>> f(x.y=1)
422# Traceback (most recent call last):
423# SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
424# >>> f((x)=2)
425# Traceback (most recent call last):
426# SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
427# >>> f(True=2)
428# Traceback (most recent call last):
429# SyntaxError: cannot assign to True
430>>> f(__debug__=1)
431Traceback (most recent call last):
432SyntaxError: cannot assign to __debug__
433>>> __debug__: int
434Traceback (most recent call last):
435SyntaxError: cannot assign to __debug__
436
437
438More set_context():
439
440>>> (x for x in x) += 1
441Traceback (most recent call last):
442SyntaxError: 'generator expression' is an illegal expression for augmented assignment
443>>> None += 1
444Traceback (most recent call last):
445SyntaxError: 'None' is an illegal expression for augmented assignment
446>>> __debug__ += 1
447Traceback (most recent call last):
448SyntaxError: cannot assign to __debug__
449>>> f() += 1
450Traceback (most recent call last):
451SyntaxError: 'function call' is an illegal expression for augmented assignment
452
453
454Test continue in finally in weird combinations.
455
456continue in for loop under finally should be ok.
457
458    >>> def test():
459    ...     try:
460    ...         pass
461    ...     finally:
462    ...         for abc in range(10):
463    ...             continue
464    ...     print(abc)
465    >>> test()
466    9
467
468continue in a finally should be ok.
469
470    >>> def test():
471    ...    for abc in range(10):
472    ...        try:
473    ...            pass
474    ...        finally:
475    ...            continue
476    ...    print(abc)
477    >>> test()
478    9
479
480    >>> def test():
481    ...    for abc in range(10):
482    ...        try:
483    ...            pass
484    ...        finally:
485    ...            try:
486    ...                continue
487    ...            except:
488    ...                pass
489    ...    print(abc)
490    >>> test()
491    9
492
493    >>> def test():
494    ...    for abc in range(10):
495    ...        try:
496    ...            pass
497    ...        finally:
498    ...            try:
499    ...                pass
500    ...            except:
501    ...                continue
502    ...    print(abc)
503    >>> test()
504    9
505
506A continue outside loop should not be allowed.
507
508    >>> def foo():
509    ...     try:
510    ...         pass
511    ...     finally:
512    ...         continue
513    Traceback (most recent call last):
514      ...
515    SyntaxError: 'continue' not properly in loop
516
517There is one test for a break that is not in a loop.  The compiler
518uses a single data structure to keep track of try-finally and loops,
519so we need to be sure that a break is actually inside a loop.  If it
520isn't, there should be a syntax error.
521
522   >>> try:
523   ...     print(1)
524   ...     break
525   ...     print(2)
526   ... finally:
527   ...     print(3)
528   Traceback (most recent call last):
529     ...
530   SyntaxError: 'break' outside loop
531
532This raises a SyntaxError, it used to raise a SystemError.
533Context for this change can be found on issue #27514
534
535In 2.5 there was a missing exception and an assert was triggered in a debug
536build.  The number of blocks must be greater than CO_MAXBLOCKS.  SF #1565514
537
538   >>> while 1:
539   ...  while 2:
540   ...   while 3:
541   ...    while 4:
542   ...     while 5:
543   ...      while 6:
544   ...       while 8:
545   ...        while 9:
546   ...         while 10:
547   ...          while 11:
548   ...           while 12:
549   ...            while 13:
550   ...             while 14:
551   ...              while 15:
552   ...               while 16:
553   ...                while 17:
554   ...                 while 18:
555   ...                  while 19:
556   ...                   while 20:
557   ...                    while 21:
558   ...                     while 22:
559   ...                      break
560   Traceback (most recent call last):
561     ...
562   SyntaxError: too many statically nested blocks
563
564Misuse of the nonlocal and global statement can lead to a few unique syntax errors.
565
566   >>> def f():
567   ...     print(x)
568   ...     global x
569   Traceback (most recent call last):
570     ...
571   SyntaxError: name 'x' is used prior to global declaration
572
573   >>> def f():
574   ...     x = 1
575   ...     global x
576   Traceback (most recent call last):
577     ...
578   SyntaxError: name 'x' is assigned to before global declaration
579
580   >>> def f(x):
581   ...     global x
582   Traceback (most recent call last):
583     ...
584   SyntaxError: name 'x' is parameter and global
585
586   >>> def f():
587   ...     x = 1
588   ...     def g():
589   ...         print(x)
590   ...         nonlocal x
591   Traceback (most recent call last):
592     ...
593   SyntaxError: name 'x' is used prior to nonlocal declaration
594
595   >>> def f():
596   ...     x = 1
597   ...     def g():
598   ...         x = 2
599   ...         nonlocal x
600   Traceback (most recent call last):
601     ...
602   SyntaxError: name 'x' is assigned to before nonlocal declaration
603
604   >>> def f(x):
605   ...     nonlocal x
606   Traceback (most recent call last):
607     ...
608   SyntaxError: name 'x' is parameter and nonlocal
609
610   >>> def f():
611   ...     global x
612   ...     nonlocal x
613   Traceback (most recent call last):
614     ...
615   SyntaxError: name 'x' is nonlocal and global
616
617   >>> def f():
618   ...     nonlocal x
619   Traceback (most recent call last):
620     ...
621   SyntaxError: no binding for nonlocal 'x' found
622
623From SF bug #1705365
624   >>> nonlocal x
625   Traceback (most recent call last):
626     ...
627   SyntaxError: nonlocal declaration not allowed at module level
628
629From https://bugs.python.org/issue25973
630   >>> class A:
631   ...     def f(self):
632   ...         nonlocal __x
633   Traceback (most recent call last):
634     ...
635   SyntaxError: no binding for nonlocal '_A__x' found
636
637
638This tests assignment-context; there was a bug in Python 2.5 where compiling
639a complex 'if' (one with 'elif') would fail to notice an invalid suite,
640leading to spurious errors.
641
642   >>> if 1:
643   ...   x() = 1
644   ... elif 1:
645   ...   pass
646   Traceback (most recent call last):
647     ...
648   SyntaxError: cannot assign to function call
649
650   >>> if 1:
651   ...   pass
652   ... elif 1:
653   ...   x() = 1
654   Traceback (most recent call last):
655     ...
656   SyntaxError: cannot assign to function call
657
658   >>> if 1:
659   ...   x() = 1
660   ... elif 1:
661   ...   pass
662   ... else:
663   ...   pass
664   Traceback (most recent call last):
665     ...
666   SyntaxError: cannot assign to function call
667
668   >>> if 1:
669   ...   pass
670   ... elif 1:
671   ...   x() = 1
672   ... else:
673   ...   pass
674   Traceback (most recent call last):
675     ...
676   SyntaxError: cannot assign to function call
677
678   >>> if 1:
679   ...   pass
680   ... elif 1:
681   ...   pass
682   ... else:
683   ...   x() = 1
684   Traceback (most recent call last):
685     ...
686   SyntaxError: cannot assign to function call
687
688Make sure that the old "raise X, Y[, Z]" form is gone:
689   >>> raise X, Y
690   Traceback (most recent call last):
691     ...
692   SyntaxError: invalid syntax
693   >>> raise X, Y, Z
694   Traceback (most recent call last):
695     ...
696   SyntaxError: invalid syntax
697
698
699>>> f(a=23, a=234)
700Traceback (most recent call last):
701   ...
702SyntaxError: keyword argument repeated: a
703
704>>> {1, 2, 3} = 42
705Traceback (most recent call last):
706SyntaxError: cannot assign to set display
707
708>>> {1: 2, 3: 4} = 42
709Traceback (most recent call last):
710SyntaxError: cannot assign to dict display
711
712>>> f'{x}' = 42
713Traceback (most recent call last):
714SyntaxError: cannot assign to f-string expression
715
716>>> f'{x}-{y}' = 42
717Traceback (most recent call last):
718SyntaxError: cannot assign to f-string expression
719
720>>> from t import x,
721Traceback (most recent call last):
722SyntaxError: trailing comma not allowed without surrounding parentheses
723
724>>> from t import x,y,
725Traceback (most recent call last):
726SyntaxError: trailing comma not allowed without surrounding parentheses
727
728>>> (): int
729Traceback (most recent call last):
730SyntaxError: only single target (not tuple) can be annotated
731>>> []: int
732Traceback (most recent call last):
733SyntaxError: only single target (not list) can be annotated
734>>> (()): int
735Traceback (most recent call last):
736SyntaxError: only single target (not tuple) can be annotated
737>>> ([]): int
738Traceback (most recent call last):
739SyntaxError: only single target (not list) can be annotated
740
741Corner-cases that used to fail to raise the correct error:
742
743    >>> def f(*, x=lambda __debug__:0): pass
744    Traceback (most recent call last):
745    SyntaxError: cannot assign to __debug__
746
747    >>> def f(*args:(lambda __debug__:0)): pass
748    Traceback (most recent call last):
749    SyntaxError: cannot assign to __debug__
750
751    >>> def f(**kwargs:(lambda __debug__:0)): pass
752    Traceback (most recent call last):
753    SyntaxError: cannot assign to __debug__
754
755    >>> with (lambda *:0): pass
756    Traceback (most recent call last):
757    SyntaxError: named arguments must follow bare *
758
759Corner-cases that used to crash:
760
761    >>> def f(**__debug__): pass
762    Traceback (most recent call last):
763    SyntaxError: cannot assign to __debug__
764
765    >>> def f(*xx, __debug__): pass
766    Traceback (most recent call last):
767    SyntaxError: cannot assign to __debug__
768
769    >>> import ä £
770    Traceback (most recent call last):
771    SyntaxError: invalid character '£' (U+00A3)
772"""
773
774import re
775import unittest
776
777from test import support
778
779class SyntaxTestCase(unittest.TestCase):
780
781    def _check_error(self, code, errtext,
782                     filename="<testcase>", mode="exec", subclass=None, lineno=None, offset=None):
783        """Check that compiling code raises SyntaxError with errtext.
784
785        errtest is a regular expression that must be present in the
786        test of the exception raised.  If subclass is specified it
787        is the expected subclass of SyntaxError (e.g. IndentationError).
788        """
789        try:
790            compile(code, filename, mode)
791        except SyntaxError as err:
792            if subclass and not isinstance(err, subclass):
793                self.fail("SyntaxError is not a %s" % subclass.__name__)
794            mo = re.search(errtext, str(err))
795            if mo is None:
796                self.fail("SyntaxError did not contain %r" % (errtext,))
797            self.assertEqual(err.filename, filename)
798            if lineno is not None:
799                self.assertEqual(err.lineno, lineno)
800            if offset is not None:
801                self.assertEqual(err.offset, offset)
802        else:
803            self.fail("compile() did not raise SyntaxError")
804
805    def test_curly_brace_after_primary_raises_immediately(self):
806        self._check_error("f{", "invalid syntax", mode="single")
807
808    def test_assign_call(self):
809        self._check_error("f() = 1", "assign")
810
811    @unittest.skipIf(support.use_old_parser(), "The old parser cannot generate these error messages")
812    def test_assign_del(self):
813        self._check_error("del (,)", "invalid syntax")
814        self._check_error("del 1", "delete literal")
815        self._check_error("del (1, 2)", "delete literal")
816        self._check_error("del None", "delete None")
817        self._check_error("del *x", "delete starred")
818        self._check_error("del (*x)", "use starred expression")
819        self._check_error("del (*x,)", "delete starred")
820        self._check_error("del [*x,]", "delete starred")
821        self._check_error("del f()", "delete function call")
822        self._check_error("del f(a, b)", "delete function call")
823        self._check_error("del o.f()", "delete function call")
824        self._check_error("del a[0]()", "delete function call")
825        self._check_error("del x, f()", "delete function call")
826        self._check_error("del f(), x", "delete function call")
827        self._check_error("del [a, b, ((c), (d,), e.f())]", "delete function call")
828        self._check_error("del (a if True else b)", "delete conditional")
829        self._check_error("del +a", "delete operator")
830        self._check_error("del a, +b", "delete operator")
831        self._check_error("del a + b", "delete operator")
832        self._check_error("del (a + b, c)", "delete operator")
833        self._check_error("del (c[0], a + b)", "delete operator")
834        self._check_error("del a.b.c + 2", "delete operator")
835        self._check_error("del a.b.c[0] + 2", "delete operator")
836        self._check_error("del (a, b, (c, d.e.f + 2))", "delete operator")
837        self._check_error("del [a, b, (c, d.e.f[0] + 2)]", "delete operator")
838        self._check_error("del (a := 5)", "delete named expression")
839        # We don't have a special message for this, but make sure we don't
840        # report "cannot delete name"
841        self._check_error("del a += b", "invalid syntax")
842
843    def test_global_param_err_first(self):
844        source = """if 1:
845            def error(a):
846                global a  # SyntaxError
847            def error2():
848                b = 1
849                global b  # SyntaxError
850            """
851        self._check_error(source, "parameter and global", lineno=3)
852
853    def test_nonlocal_param_err_first(self):
854        source = """if 1:
855            def error(a):
856                nonlocal a  # SyntaxError
857            def error2():
858                b = 1
859                global b  # SyntaxError
860            """
861        self._check_error(source, "parameter and nonlocal", lineno=3)
862
863    def test_break_outside_loop(self):
864        self._check_error("break", "outside loop")
865
866    def test_yield_outside_function(self):
867        self._check_error("if 0: yield",                "outside function")
868        self._check_error("if 0: yield\nelse:  x=1",    "outside function")
869        self._check_error("if 1: pass\nelse: yield",    "outside function")
870        self._check_error("while 0: yield",             "outside function")
871        self._check_error("while 0: yield\nelse:  x=1", "outside function")
872        self._check_error("class C:\n  if 0: yield",    "outside function")
873        self._check_error("class C:\n  if 1: pass\n  else: yield",
874                          "outside function")
875        self._check_error("class C:\n  while 0: yield", "outside function")
876        self._check_error("class C:\n  while 0: yield\n  else:  x = 1",
877                          "outside function")
878
879    def test_return_outside_function(self):
880        self._check_error("if 0: return",                "outside function")
881        self._check_error("if 0: return\nelse:  x=1",    "outside function")
882        self._check_error("if 1: pass\nelse: return",    "outside function")
883        self._check_error("while 0: return",             "outside function")
884        self._check_error("class C:\n  if 0: return",    "outside function")
885        self._check_error("class C:\n  while 0: return", "outside function")
886        self._check_error("class C:\n  while 0: return\n  else:  x=1",
887                          "outside function")
888        self._check_error("class C:\n  if 0: return\n  else: x= 1",
889                          "outside function")
890        self._check_error("class C:\n  if 1: pass\n  else: return",
891                          "outside function")
892
893    def test_break_outside_loop(self):
894        self._check_error("if 0: break",             "outside loop")
895        self._check_error("if 0: break\nelse:  x=1",  "outside loop")
896        self._check_error("if 1: pass\nelse: break", "outside loop")
897        self._check_error("class C:\n  if 0: break", "outside loop")
898        self._check_error("class C:\n  if 1: pass\n  else: break",
899                          "outside loop")
900
901    def test_continue_outside_loop(self):
902        self._check_error("if 0: continue",             "not properly in loop")
903        self._check_error("if 0: continue\nelse:  x=1", "not properly in loop")
904        self._check_error("if 1: pass\nelse: continue", "not properly in loop")
905        self._check_error("class C:\n  if 0: continue", "not properly in loop")
906        self._check_error("class C:\n  if 1: pass\n  else: continue",
907                          "not properly in loop")
908
909    def test_unexpected_indent(self):
910        self._check_error("foo()\n bar()\n", "unexpected indent",
911                          subclass=IndentationError)
912
913    def test_no_indent(self):
914        self._check_error("if 1:\nfoo()", "expected an indented block",
915                          subclass=IndentationError)
916
917    def test_bad_outdent(self):
918        self._check_error("if 1:\n  foo()\n bar()",
919                          "unindent does not match .* level",
920                          subclass=IndentationError)
921
922    def test_kwargs_last(self):
923        self._check_error("int(base=10, '2')",
924                          "positional argument follows keyword argument")
925
926    def test_kwargs_last2(self):
927        self._check_error("int(**{'base': 10}, '2')",
928                          "positional argument follows "
929                          "keyword argument unpacking")
930
931    def test_kwargs_last3(self):
932        self._check_error("int(**{'base': 10}, *['2'])",
933                          "iterable argument unpacking follows "
934                          "keyword argument unpacking")
935
936    def test_empty_line_after_linecont(self):
937        # See issue-40847
938        s = r"""\
939pass
940        \
941
942pass
943"""
944        try:
945            compile(s, '<string>', 'exec')
946        except SyntaxError:
947            self.fail("Empty line after a line continuation character is valid.")
948
949    @support.cpython_only
950    def test_nested_named_except_blocks(self):
951        code = ""
952        for i in range(12):
953            code += f"{'    '*i}try:\n"
954            code += f"{'    '*(i+1)}raise Exception\n"
955            code += f"{'    '*i}except Exception as e:\n"
956        code += f"{' '*4*12}pass"
957        self._check_error(code, "too many statically nested blocks")
958
959    def test_barry_as_flufl_with_syntax_errors(self):
960        # The "barry_as_flufl" rule can produce some "bugs-at-a-distance" if
961        # is reading the wrong token in the presence of syntax errors later
962        # in the file. See bpo-42214 for more information.
963        code = """
964def func1():
965    if a != b:
966        raise ValueError
967
968def func2():
969    try
970        return 1
971    finally:
972        pass
973"""
974        self._check_error(code, "invalid syntax")
975
976    def test_invalid_line_continuation_left_recursive(self):
977        # Check bpo-42218: SyntaxErrors following left-recursive rules
978        # (t_primary_raw in this case) need to be tested explicitly
979        self._check_error("A.\u018a\\ ",
980                          "unexpected character after line continuation character")
981        self._check_error("A.\u03bc\\\n",
982                          "unexpected EOF while parsing")
983
984def test_main():
985    support.run_unittest(SyntaxTestCase)
986    from test import test_syntax
987    support.run_doctest(test_syntax, verbosity=True)
988
989if __name__ == "__main__":
990    test_main()
991