• 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>>> del __debug__
63Traceback (most recent call last):
64SyntaxError: cannot delete __debug__
65
66>>> f() = 1
67Traceback (most recent call last):
68SyntaxError: cannot assign to function call here. Maybe you meant '==' instead of '='?
69
70>>> yield = 1
71Traceback (most recent call last):
72SyntaxError: assignment to yield expression not possible
73
74>>> del f()
75Traceback (most recent call last):
76SyntaxError: cannot delete function call
77
78>>> a + 1 = 2
79Traceback (most recent call last):
80SyntaxError: cannot assign to expression here. Maybe you meant '==' instead of '='?
81
82>>> (x for x in x) = 1
83Traceback (most recent call last):
84SyntaxError: cannot assign to generator expression
85
86>>> 1 = 1
87Traceback (most recent call last):
88SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?
89
90>>> "abc" = 1
91Traceback (most recent call last):
92SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?
93
94>>> b"" = 1
95Traceback (most recent call last):
96SyntaxError: cannot assign to literal here. Maybe you meant '==' instead of '='?
97
98>>> ... = 1
99Traceback (most recent call last):
100SyntaxError: cannot assign to ellipsis here. Maybe you meant '==' instead of '='?
101
102>>> `1` = 1
103Traceback (most recent call last):
104SyntaxError: invalid syntax
105
106If the left-hand side of an assignment is a list or tuple, an illegal
107expression inside that contain should still cause a syntax error.
108This test just checks a couple of cases rather than enumerating all of
109them.
110
111>>> (a, "b", c) = (1, 2, 3)
112Traceback (most recent call last):
113SyntaxError: cannot assign to literal
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, *True, c) = (1, 2, 3)
124Traceback (most recent call last):
125SyntaxError: cannot assign to True
126
127>>> (a, *__debug__, c) = (1, 2, 3)
128Traceback (most recent call last):
129SyntaxError: cannot assign to __debug__
130
131>>> [a, b, c + 1] = [1, 2, 3]
132Traceback (most recent call last):
133SyntaxError: cannot assign to expression
134
135>>> [a, b[1], c + 1] = [1, 2, 3]
136Traceback (most recent call last):
137SyntaxError: cannot assign to expression
138
139>>> [a, b.c.d, c + 1] = [1, 2, 3]
140Traceback (most recent call last):
141SyntaxError: cannot assign to expression
142
143>>> a if 1 else b = 1
144Traceback (most recent call last):
145SyntaxError: cannot assign to conditional expression
146
147>>> a = 42 if True
148Traceback (most recent call last):
149SyntaxError: expected 'else' after 'if' expression
150
151>>> a = (42 if True)
152Traceback (most recent call last):
153SyntaxError: expected 'else' after 'if' expression
154
155>>> a = [1, 42 if True, 4]
156Traceback (most recent call last):
157SyntaxError: expected 'else' after 'if' expression
158
159>>> if True:
160...     print("Hello"
161...
162... if 2:
163...    print(123))
164Traceback (most recent call last):
165SyntaxError: invalid syntax
166
167>>> True = True = 3
168Traceback (most recent call last):
169SyntaxError: cannot assign to True
170
171>>> x = y = True = z = 3
172Traceback (most recent call last):
173SyntaxError: cannot assign to True
174
175>>> x = y = yield = 1
176Traceback (most recent call last):
177SyntaxError: assignment to yield expression not possible
178
179>>> a, b += 1, 2
180Traceback (most recent call last):
181SyntaxError: 'tuple' is an illegal expression for augmented assignment
182
183>>> (a, b) += 1, 2
184Traceback (most recent call last):
185SyntaxError: 'tuple' is an illegal expression for augmented assignment
186
187>>> [a, b] += 1, 2
188Traceback (most recent call last):
189SyntaxError: 'list' is an illegal expression for augmented assignment
190
191Invalid targets in `for` loops and `with` statements should also
192produce a specialized error message
193
194>>> for a() in b: pass
195Traceback (most recent call last):
196SyntaxError: cannot assign to function call
197
198>>> for (a, b()) in b: pass
199Traceback (most recent call last):
200SyntaxError: cannot assign to function call
201
202>>> for [a, b()] in b: pass
203Traceback (most recent call last):
204SyntaxError: cannot assign to function call
205
206>>> for (*a, b, c+1) in b: pass
207Traceback (most recent call last):
208SyntaxError: cannot assign to expression
209
210>>> for (x, *(y, z.d())) in b: pass
211Traceback (most recent call last):
212SyntaxError: cannot assign to function call
213
214>>> for a, b() in c: pass
215Traceback (most recent call last):
216SyntaxError: cannot assign to function call
217
218>>> for a, b, (c + 1, d()): pass
219Traceback (most recent call last):
220SyntaxError: cannot assign to expression
221
222>>> for i < (): pass
223Traceback (most recent call last):
224SyntaxError: invalid syntax
225
226>>> for a, b
227Traceback (most recent call last):
228SyntaxError: invalid syntax
229
230>>> with a as b(): pass
231Traceback (most recent call last):
232SyntaxError: cannot assign to function call
233
234>>> with a as (b, c()): pass
235Traceback (most recent call last):
236SyntaxError: cannot assign to function call
237
238>>> with a as [b, c()]: pass
239Traceback (most recent call last):
240SyntaxError: cannot assign to function call
241
242>>> with a as (*b, c, d+1): pass
243Traceback (most recent call last):
244SyntaxError: cannot assign to expression
245
246>>> with a as (x, *(y, z.d())): pass
247Traceback (most recent call last):
248SyntaxError: cannot assign to function call
249
250>>> with a as b, c as d(): pass
251Traceback (most recent call last):
252SyntaxError: cannot assign to function call
253
254>>> with a as b
255Traceback (most recent call last):
256SyntaxError: expected ':'
257
258>>> p = p =
259Traceback (most recent call last):
260SyntaxError: invalid syntax
261
262Comprehensions creating tuples without parentheses
263should produce a specialized error message:
264
265>>> [x,y for x,y in range(100)]
266Traceback (most recent call last):
267SyntaxError: did you forget parentheses around the comprehension target?
268
269>>> {x,y for x,y in range(100)}
270Traceback (most recent call last):
271SyntaxError: did you forget parentheses around the comprehension target?
272
273# Missing commas in literals collections should not
274# produce special error messages regarding missing
275# parentheses, but about missing commas instead
276
277>>> [1, 2 3]
278Traceback (most recent call last):
279SyntaxError: invalid syntax. Perhaps you forgot a comma?
280
281>>> {1, 2 3}
282Traceback (most recent call last):
283SyntaxError: invalid syntax. Perhaps you forgot a comma?
284
285>>> {1:2, 2:5 3:12}
286Traceback (most recent call last):
287SyntaxError: invalid syntax. Perhaps you forgot a comma?
288
289>>> (1, 2 3)
290Traceback (most recent call last):
291SyntaxError: invalid syntax. Perhaps you forgot a comma?
292
293# Make sure soft keywords constructs don't raise specialized
294# errors regarding missing commas or other spezialiced errors
295
296>>> match x:
297...     y = 3
298Traceback (most recent call last):
299SyntaxError: invalid syntax
300
301>>> match x:
302...     case y:
303...        3 $ 3
304Traceback (most recent call last):
305SyntaxError: invalid syntax
306
307>>> match x:
308...     case $:
309...        ...
310Traceback (most recent call last):
311SyntaxError: invalid syntax
312
313>>> match ...:
314...     case {**rest, "key": value}:
315...        ...
316Traceback (most recent call last):
317SyntaxError: invalid syntax
318
319>>> match ...:
320...     case {**_}:
321...        ...
322Traceback (most recent call last):
323SyntaxError: invalid syntax
324
325From compiler_complex_args():
326
327>>> def f(None=1):
328...     pass
329Traceback (most recent call last):
330SyntaxError: invalid syntax
331
332From ast_for_arguments():
333
334>>> def f(x, y=1, z):
335...     pass
336Traceback (most recent call last):
337SyntaxError: non-default argument follows default argument
338
339>>> def f(x, None):
340...     pass
341Traceback (most recent call last):
342SyntaxError: invalid syntax
343
344>>> def f(*None):
345...     pass
346Traceback (most recent call last):
347SyntaxError: invalid syntax
348
349>>> def f(**None):
350...     pass
351Traceback (most recent call last):
352SyntaxError: invalid syntax
353
354>>> import ast; ast.parse('''
355... def f(
356...     *, # type: int
357...     a, # type: int
358... ):
359...     pass
360... ''', type_comments=True)
361Traceback (most recent call last):
362SyntaxError: bare * has associated type comment
363
364
365From ast_for_funcdef():
366
367>>> def None(x):
368...     pass
369Traceback (most recent call last):
370SyntaxError: invalid syntax
371
372
373From ast_for_call():
374
375>>> def f(it, *varargs, **kwargs):
376...     return list(it)
377>>> L = range(10)
378>>> f(x for x in L)
379[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
380>>> f(x for x in L, 1)
381Traceback (most recent call last):
382SyntaxError: Generator expression must be parenthesized
383>>> f(x for x in L, y=1)
384Traceback (most recent call last):
385SyntaxError: Generator expression must be parenthesized
386>>> f(x for x in L, *[])
387Traceback (most recent call last):
388SyntaxError: Generator expression must be parenthesized
389>>> f(x for x in L, **{})
390Traceback (most recent call last):
391SyntaxError: Generator expression must be parenthesized
392>>> f(L, x for x in L)
393Traceback (most recent call last):
394SyntaxError: Generator expression must be parenthesized
395>>> f(x for x in L, y for y in L)
396Traceback (most recent call last):
397SyntaxError: Generator expression must be parenthesized
398>>> f(x for x in L,)
399Traceback (most recent call last):
400SyntaxError: Generator expression must be parenthesized
401>>> f((x for x in L), 1)
402[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
403>>> class C(x for x in L):
404...     pass
405Traceback (most recent call last):
406SyntaxError: expected ':'
407
408>>> def g(*args, **kwargs):
409...     print(args, sorted(kwargs.items()))
410>>> g(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
411...   20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
412...   38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
413...   56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73,
414...   74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91,
415...   92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107,
416...   108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
417...   122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135,
418...   136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
419...   150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163,
420...   164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177,
421...   178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191,
422...   192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205,
423...   206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219,
424...   220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233,
425...   234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247,
426...   248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261,
427...   262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275,
428...   276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289,
429...   290, 291, 292, 293, 294, 295, 296, 297, 298, 299)  # doctest: +ELLIPSIS
430(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ..., 297, 298, 299) []
431
432>>> g(a000=0, a001=1, a002=2, a003=3, a004=4, a005=5, a006=6, a007=7, a008=8,
433...   a009=9, a010=10, a011=11, a012=12, a013=13, a014=14, a015=15, a016=16,
434...   a017=17, a018=18, a019=19, a020=20, a021=21, a022=22, a023=23, a024=24,
435...   a025=25, a026=26, a027=27, a028=28, a029=29, a030=30, a031=31, a032=32,
436...   a033=33, a034=34, a035=35, a036=36, a037=37, a038=38, a039=39, a040=40,
437...   a041=41, a042=42, a043=43, a044=44, a045=45, a046=46, a047=47, a048=48,
438...   a049=49, a050=50, a051=51, a052=52, a053=53, a054=54, a055=55, a056=56,
439...   a057=57, a058=58, a059=59, a060=60, a061=61, a062=62, a063=63, a064=64,
440...   a065=65, a066=66, a067=67, a068=68, a069=69, a070=70, a071=71, a072=72,
441...   a073=73, a074=74, a075=75, a076=76, a077=77, a078=78, a079=79, a080=80,
442...   a081=81, a082=82, a083=83, a084=84, a085=85, a086=86, a087=87, a088=88,
443...   a089=89, a090=90, a091=91, a092=92, a093=93, a094=94, a095=95, a096=96,
444...   a097=97, a098=98, a099=99, a100=100, a101=101, a102=102, a103=103,
445...   a104=104, a105=105, a106=106, a107=107, a108=108, a109=109, a110=110,
446...   a111=111, a112=112, a113=113, a114=114, a115=115, a116=116, a117=117,
447...   a118=118, a119=119, a120=120, a121=121, a122=122, a123=123, a124=124,
448...   a125=125, a126=126, a127=127, a128=128, a129=129, a130=130, a131=131,
449...   a132=132, a133=133, a134=134, a135=135, a136=136, a137=137, a138=138,
450...   a139=139, a140=140, a141=141, a142=142, a143=143, a144=144, a145=145,
451...   a146=146, a147=147, a148=148, a149=149, a150=150, a151=151, a152=152,
452...   a153=153, a154=154, a155=155, a156=156, a157=157, a158=158, a159=159,
453...   a160=160, a161=161, a162=162, a163=163, a164=164, a165=165, a166=166,
454...   a167=167, a168=168, a169=169, a170=170, a171=171, a172=172, a173=173,
455...   a174=174, a175=175, a176=176, a177=177, a178=178, a179=179, a180=180,
456...   a181=181, a182=182, a183=183, a184=184, a185=185, a186=186, a187=187,
457...   a188=188, a189=189, a190=190, a191=191, a192=192, a193=193, a194=194,
458...   a195=195, a196=196, a197=197, a198=198, a199=199, a200=200, a201=201,
459...   a202=202, a203=203, a204=204, a205=205, a206=206, a207=207, a208=208,
460...   a209=209, a210=210, a211=211, a212=212, a213=213, a214=214, a215=215,
461...   a216=216, a217=217, a218=218, a219=219, a220=220, a221=221, a222=222,
462...   a223=223, a224=224, a225=225, a226=226, a227=227, a228=228, a229=229,
463...   a230=230, a231=231, a232=232, a233=233, a234=234, a235=235, a236=236,
464...   a237=237, a238=238, a239=239, a240=240, a241=241, a242=242, a243=243,
465...   a244=244, a245=245, a246=246, a247=247, a248=248, a249=249, a250=250,
466...   a251=251, a252=252, a253=253, a254=254, a255=255, a256=256, a257=257,
467...   a258=258, a259=259, a260=260, a261=261, a262=262, a263=263, a264=264,
468...   a265=265, a266=266, a267=267, a268=268, a269=269, a270=270, a271=271,
469...   a272=272, a273=273, a274=274, a275=275, a276=276, a277=277, a278=278,
470...   a279=279, a280=280, a281=281, a282=282, a283=283, a284=284, a285=285,
471...   a286=286, a287=287, a288=288, a289=289, a290=290, a291=291, a292=292,
472...   a293=293, a294=294, a295=295, a296=296, a297=297, a298=298, a299=299)
473...  # doctest: +ELLIPSIS
474() [('a000', 0), ('a001', 1), ('a002', 2), ..., ('a298', 298), ('a299', 299)]
475
476>>> class C:
477...     def meth(self, *args):
478...         return args
479>>> obj = C()
480>>> obj.meth(
481...   0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
482...   20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
483...   38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
484...   56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73,
485...   74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91,
486...   92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107,
487...   108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
488...   122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135,
489...   136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149,
490...   150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163,
491...   164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177,
492...   178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191,
493...   192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205,
494...   206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219,
495...   220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233,
496...   234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247,
497...   248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261,
498...   262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275,
499...   276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289,
500...   290, 291, 292, 293, 294, 295, 296, 297, 298, 299)  # doctest: +ELLIPSIS
501(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ..., 297, 298, 299)
502
503>>> f(lambda x: x[0] = 3)
504Traceback (most recent call last):
505SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
506
507# Check that this error doesn't trigger for names:
508>>> f(a={x: for x in {}})
509Traceback (most recent call last):
510SyntaxError: invalid syntax
511
512The grammar accepts any test (basically, any expression) in the
513keyword slot of a call site.  Test a few different options.
514
515>>> f(x()=2)
516Traceback (most recent call last):
517SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
518>>> f(a or b=1)
519Traceback (most recent call last):
520SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
521>>> f(x.y=1)
522Traceback (most recent call last):
523SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
524>>> f((x)=2)
525Traceback (most recent call last):
526SyntaxError: expression cannot contain assignment, perhaps you meant "=="?
527>>> f(True=1)
528Traceback (most recent call last):
529SyntaxError: cannot assign to True
530>>> f(False=1)
531Traceback (most recent call last):
532SyntaxError: cannot assign to False
533>>> f(None=1)
534Traceback (most recent call last):
535SyntaxError: cannot assign to None
536>>> f(__debug__=1)
537Traceback (most recent call last):
538SyntaxError: cannot assign to __debug__
539>>> __debug__: int
540Traceback (most recent call last):
541SyntaxError: cannot assign to __debug__
542
543
544More set_context():
545
546>>> (x for x in x) += 1
547Traceback (most recent call last):
548SyntaxError: 'generator expression' is an illegal expression for augmented assignment
549>>> None += 1
550Traceback (most recent call last):
551SyntaxError: 'None' is an illegal expression for augmented assignment
552>>> __debug__ += 1
553Traceback (most recent call last):
554SyntaxError: cannot assign to __debug__
555>>> f() += 1
556Traceback (most recent call last):
557SyntaxError: 'function call' is an illegal expression for augmented assignment
558
559
560Test continue in finally in weird combinations.
561
562continue in for loop under finally should be ok.
563
564    >>> def test():
565    ...     try:
566    ...         pass
567    ...     finally:
568    ...         for abc in range(10):
569    ...             continue
570    ...     print(abc)
571    >>> test()
572    9
573
574continue in a finally should be ok.
575
576    >>> def test():
577    ...    for abc in range(10):
578    ...        try:
579    ...            pass
580    ...        finally:
581    ...            continue
582    ...    print(abc)
583    >>> test()
584    9
585
586    >>> def test():
587    ...    for abc in range(10):
588    ...        try:
589    ...            pass
590    ...        finally:
591    ...            try:
592    ...                continue
593    ...            except:
594    ...                pass
595    ...    print(abc)
596    >>> test()
597    9
598
599    >>> def test():
600    ...    for abc in range(10):
601    ...        try:
602    ...            pass
603    ...        finally:
604    ...            try:
605    ...                pass
606    ...            except:
607    ...                continue
608    ...    print(abc)
609    >>> test()
610    9
611
612A continue outside loop should not be allowed.
613
614    >>> def foo():
615    ...     try:
616    ...         pass
617    ...     finally:
618    ...         continue
619    Traceback (most recent call last):
620      ...
621    SyntaxError: 'continue' not properly in loop
622
623There is one test for a break that is not in a loop.  The compiler
624uses a single data structure to keep track of try-finally and loops,
625so we need to be sure that a break is actually inside a loop.  If it
626isn't, there should be a syntax error.
627
628   >>> try:
629   ...     print(1)
630   ...     break
631   ...     print(2)
632   ... finally:
633   ...     print(3)
634   Traceback (most recent call last):
635     ...
636   SyntaxError: 'break' outside loop
637
638Misuse of the nonlocal and global statement can lead to a few unique syntax errors.
639
640   >>> def f():
641   ...     print(x)
642   ...     global x
643   Traceback (most recent call last):
644     ...
645   SyntaxError: name 'x' is used prior to global declaration
646
647   >>> def f():
648   ...     x = 1
649   ...     global x
650   Traceback (most recent call last):
651     ...
652   SyntaxError: name 'x' is assigned to before global declaration
653
654   >>> def f(x):
655   ...     global x
656   Traceback (most recent call last):
657     ...
658   SyntaxError: name 'x' is parameter and global
659
660   >>> def f():
661   ...     x = 1
662   ...     def g():
663   ...         print(x)
664   ...         nonlocal x
665   Traceback (most recent call last):
666     ...
667   SyntaxError: name 'x' is used prior to nonlocal declaration
668
669   >>> def f():
670   ...     x = 1
671   ...     def g():
672   ...         x = 2
673   ...         nonlocal x
674   Traceback (most recent call last):
675     ...
676   SyntaxError: name 'x' is assigned to before nonlocal declaration
677
678   >>> def f(x):
679   ...     nonlocal x
680   Traceback (most recent call last):
681     ...
682   SyntaxError: name 'x' is parameter and nonlocal
683
684   >>> def f():
685   ...     global x
686   ...     nonlocal x
687   Traceback (most recent call last):
688     ...
689   SyntaxError: name 'x' is nonlocal and global
690
691   >>> def f():
692   ...     nonlocal x
693   Traceback (most recent call last):
694     ...
695   SyntaxError: no binding for nonlocal 'x' found
696
697From SF bug #1705365
698   >>> nonlocal x
699   Traceback (most recent call last):
700     ...
701   SyntaxError: nonlocal declaration not allowed at module level
702
703From https://bugs.python.org/issue25973
704   >>> class A:
705   ...     def f(self):
706   ...         nonlocal __x
707   Traceback (most recent call last):
708     ...
709   SyntaxError: no binding for nonlocal '_A__x' found
710
711
712This tests assignment-context; there was a bug in Python 2.5 where compiling
713a complex 'if' (one with 'elif') would fail to notice an invalid suite,
714leading to spurious errors.
715
716   >>> if 1:
717   ...   x() = 1
718   ... elif 1:
719   ...   pass
720   Traceback (most recent call last):
721     ...
722   SyntaxError: cannot assign to function call here. Maybe you meant '==' instead of '='?
723
724   >>> if 1:
725   ...   pass
726   ... elif 1:
727   ...   x() = 1
728   Traceback (most recent call last):
729     ...
730   SyntaxError: cannot assign to function call here. Maybe you meant '==' instead of '='?
731
732   >>> if 1:
733   ...   x() = 1
734   ... elif 1:
735   ...   pass
736   ... else:
737   ...   pass
738   Traceback (most recent call last):
739     ...
740   SyntaxError: cannot assign to function call here. Maybe you meant '==' instead of '='?
741
742   >>> if 1:
743   ...   pass
744   ... elif 1:
745   ...   x() = 1
746   ... else:
747   ...   pass
748   Traceback (most recent call last):
749     ...
750   SyntaxError: cannot assign to function call here. Maybe you meant '==' instead of '='?
751
752   >>> if 1:
753   ...   pass
754   ... elif 1:
755   ...   pass
756   ... else:
757   ...   x() = 1
758   Traceback (most recent call last):
759     ...
760   SyntaxError: cannot assign to function call here. Maybe you meant '==' instead of '='?
761
762    Missing ':' before suites:
763
764    >>> def f()
765    ...     pass
766    Traceback (most recent call last):
767    SyntaxError: expected ':'
768
769    >>> class A
770    ...     pass
771    Traceback (most recent call last):
772    SyntaxError: expected ':'
773
774   >>> if 1
775   ...   pass
776   ... elif 1:
777   ...   pass
778   ... else:
779   ...   x() = 1
780   Traceback (most recent call last):
781   SyntaxError: expected ':'
782
783   >>> if 1:
784   ...   pass
785   ... elif 1
786   ...   pass
787   ... else:
788   ...   x() = 1
789   Traceback (most recent call last):
790   SyntaxError: expected ':'
791
792   >>> if 1:
793   ...   pass
794   ... elif 1:
795   ...   pass
796   ... else
797   ...   x() = 1
798   Traceback (most recent call last):
799   SyntaxError: expected ':'
800
801   >>> for x in range(10)
802   ...   pass
803   Traceback (most recent call last):
804   SyntaxError: expected ':'
805
806   >>> while True
807   ...   pass
808   Traceback (most recent call last):
809   SyntaxError: expected ':'
810
811   >>> with blech as something
812   ...   pass
813   Traceback (most recent call last):
814   SyntaxError: expected ':'
815
816   >>> with blech
817   ...   pass
818   Traceback (most recent call last):
819   SyntaxError: expected ':'
820
821   >>> with blech, block as something
822   ...   pass
823   Traceback (most recent call last):
824   SyntaxError: expected ':'
825
826   >>> with blech, block as something, bluch
827   ...   pass
828   Traceback (most recent call last):
829   SyntaxError: expected ':'
830
831   >>> with (blech as something)
832   ...   pass
833   Traceback (most recent call last):
834   SyntaxError: expected ':'
835
836   >>> with (blech)
837   ...   pass
838   Traceback (most recent call last):
839   SyntaxError: expected ':'
840
841   >>> with (blech, block as something)
842   ...   pass
843   Traceback (most recent call last):
844   SyntaxError: expected ':'
845
846   >>> with (blech, block as something, bluch)
847   ...   pass
848   Traceback (most recent call last):
849   SyntaxError: expected ':'
850
851   >>> try
852   ...   pass
853   Traceback (most recent call last):
854   SyntaxError: expected ':'
855
856   >>> try:
857   ...   pass
858   ... except
859   ...   pass
860   Traceback (most recent call last):
861   SyntaxError: expected ':'
862
863   >>> match x
864   ...   case list():
865   ...       pass
866   Traceback (most recent call last):
867   SyntaxError: expected ':'
868
869   >>> match x:
870   ...   case list()
871   ...       pass
872   Traceback (most recent call last):
873   SyntaxError: expected ':'
874
875   >>> match x:
876   ...   case [y] if y > 0
877   ...       pass
878   Traceback (most recent call last):
879   SyntaxError: expected ':'
880
881   >>> if x = 3:
882   ...    pass
883   Traceback (most recent call last):
884   SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
885
886   >>> while x = 3:
887   ...    pass
888   Traceback (most recent call last):
889   SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
890
891   >>> if x.a = 3:
892   ...    pass
893   Traceback (most recent call last):
894   SyntaxError: cannot assign to attribute here. Maybe you meant '==' instead of '='?
895
896   >>> while x.a = 3:
897   ...    pass
898   Traceback (most recent call last):
899   SyntaxError: cannot assign to attribute here. Maybe you meant '==' instead of '='?
900
901Custom error messages for try blocks that are not followed by except/finally
902
903   >>> try:
904   ...    x = 34
905   ...
906   Traceback (most recent call last):
907   SyntaxError: expected 'except' or 'finally' block
908
909Ensure that early = are not matched by the parser as invalid comparisons
910   >>> f(2, 4, x=34); 1 $ 2
911   Traceback (most recent call last):
912   SyntaxError: invalid syntax
913
914   >>> dict(x=34); x $ y
915   Traceback (most recent call last):
916   SyntaxError: invalid syntax
917
918   >>> dict(x=34, (x for x in range 10), 1); x $ y
919   Traceback (most recent call last):
920   SyntaxError: invalid syntax
921
922   >>> dict(x=34, x=1, y=2); x $ y
923   Traceback (most recent call last):
924   SyntaxError: invalid syntax
925
926Incomplete dictionary literals
927
928   >>> {1:2, 3:4, 5}
929   Traceback (most recent call last):
930   SyntaxError: ':' expected after dictionary key
931
932   >>> {1:2, 3:4, 5:}
933   Traceback (most recent call last):
934   SyntaxError: expression expected after dictionary key and ':'
935
936   >>> {1: *12+1, 23: 1}
937   Traceback (most recent call last):
938   SyntaxError: cannot use a starred expression in a dictionary value
939
940   >>> {1: *12+1}
941   Traceback (most recent call last):
942   SyntaxError: cannot use a starred expression in a dictionary value
943
944   >>> {1: 23, 1: *12+1}
945   Traceback (most recent call last):
946   SyntaxError: cannot use a starred expression in a dictionary value
947
948   >>> {1:}
949   Traceback (most recent call last):
950   SyntaxError: expression expected after dictionary key and ':'
951
952   # Ensure that the error is not raise for syntax errors that happen after sets
953
954   >>> {1} $
955   Traceback (most recent call last):
956   SyntaxError: invalid syntax
957
958Specialized indentation errors:
959
960   >>> while condition:
961   ... pass
962   Traceback (most recent call last):
963   IndentationError: expected an indented block after 'while' statement on line 1
964
965   >>> for x in range(10):
966   ... pass
967   Traceback (most recent call last):
968   IndentationError: expected an indented block after 'for' statement on line 1
969
970   >>> for x in range(10):
971   ...     pass
972   ... else:
973   ... pass
974   Traceback (most recent call last):
975   IndentationError: expected an indented block after 'else' statement on line 3
976
977   >>> async for x in range(10):
978   ... pass
979   Traceback (most recent call last):
980   IndentationError: expected an indented block after 'for' statement on line 1
981
982   >>> async for x in range(10):
983   ...     pass
984   ... else:
985   ... pass
986   Traceback (most recent call last):
987   IndentationError: expected an indented block after 'else' statement on line 3
988
989   >>> if something:
990   ... pass
991   Traceback (most recent call last):
992   IndentationError: expected an indented block after 'if' statement on line 1
993
994   >>> if something:
995   ...     pass
996   ... elif something_else:
997   ... pass
998   Traceback (most recent call last):
999   IndentationError: expected an indented block after 'elif' statement on line 3
1000
1001   >>> if something:
1002   ...     pass
1003   ... elif something_else:
1004   ...     pass
1005   ... else:
1006   ... pass
1007   Traceback (most recent call last):
1008   IndentationError: expected an indented block after 'else' statement on line 5
1009
1010   >>> try:
1011   ... pass
1012   Traceback (most recent call last):
1013   IndentationError: expected an indented block after 'try' statement on line 1
1014
1015   >>> try:
1016   ...     something()
1017   ... except A:
1018   ... pass
1019   Traceback (most recent call last):
1020   IndentationError: expected an indented block after 'except' statement on line 3
1021
1022   >>> try:
1023   ...     something()
1024   ... except A:
1025   ...     pass
1026   ... finally:
1027   ... pass
1028   Traceback (most recent call last):
1029   IndentationError: expected an indented block after 'finally' statement on line 5
1030
1031   >>> with A:
1032   ... pass
1033   Traceback (most recent call last):
1034   IndentationError: expected an indented block after 'with' statement on line 1
1035
1036   >>> with A as a, B as b:
1037   ... pass
1038   Traceback (most recent call last):
1039   IndentationError: expected an indented block after 'with' statement on line 1
1040
1041   >>> with (A as a, B as b):
1042   ... pass
1043   Traceback (most recent call last):
1044   IndentationError: expected an indented block after 'with' statement on line 1
1045
1046   >>> async with A:
1047   ... pass
1048   Traceback (most recent call last):
1049   IndentationError: expected an indented block after 'with' statement on line 1
1050
1051   >>> async with A as a, B as b:
1052   ... pass
1053   Traceback (most recent call last):
1054   IndentationError: expected an indented block after 'with' statement on line 1
1055
1056   >>> async with (A as a, B as b):
1057   ... pass
1058   Traceback (most recent call last):
1059   IndentationError: expected an indented block after 'with' statement on line 1
1060
1061   >>> def foo(x, /, y, *, z=2):
1062   ... pass
1063   Traceback (most recent call last):
1064   IndentationError: expected an indented block after function definition on line 1
1065
1066   >>> class Blech(A):
1067   ... pass
1068   Traceback (most recent call last):
1069   IndentationError: expected an indented block after class definition on line 1
1070
1071   >>> match something:
1072   ... pass
1073   Traceback (most recent call last):
1074   IndentationError: expected an indented block after 'match' statement on line 1
1075
1076   >>> match something:
1077   ...     case []:
1078   ... pass
1079   Traceback (most recent call last):
1080   IndentationError: expected an indented block after 'case' statement on line 2
1081
1082   >>> match something:
1083   ...     case []:
1084   ...         ...
1085   ...     case {}:
1086   ... pass
1087   Traceback (most recent call last):
1088   IndentationError: expected an indented block after 'case' statement on line 4
1089
1090Make sure that the old "raise X, Y[, Z]" form is gone:
1091   >>> raise X, Y
1092   Traceback (most recent call last):
1093     ...
1094   SyntaxError: invalid syntax
1095   >>> raise X, Y, Z
1096   Traceback (most recent call last):
1097     ...
1098   SyntaxError: invalid syntax
1099
1100Check that an multiple exception types with missing parentheses
1101raise a custom exception
1102
1103   >>> try:
1104   ...   pass
1105   ... except A, B:
1106   ...   pass
1107   Traceback (most recent call last):
1108   SyntaxError: multiple exception types must be parenthesized
1109
1110   >>> try:
1111   ...   pass
1112   ... except A, B, C:
1113   ...   pass
1114   Traceback (most recent call last):
1115   SyntaxError: multiple exception types must be parenthesized
1116
1117   >>> try:
1118   ...   pass
1119   ... except A, B, C as blech:
1120   ...   pass
1121   Traceback (most recent call last):
1122   SyntaxError: multiple exception types must be parenthesized
1123
1124   >>> try:
1125   ...   pass
1126   ... except A, B, C as blech:
1127   ...   pass
1128   ... finally:
1129   ...   pass
1130   Traceback (most recent call last):
1131   SyntaxError: multiple exception types must be parenthesized
1132
1133
1134>>> f(a=23, a=234)
1135Traceback (most recent call last):
1136   ...
1137SyntaxError: keyword argument repeated: a
1138
1139>>> {1, 2, 3} = 42
1140Traceback (most recent call last):
1141SyntaxError: cannot assign to set display here. Maybe you meant '==' instead of '='?
1142
1143>>> {1: 2, 3: 4} = 42
1144Traceback (most recent call last):
1145SyntaxError: cannot assign to dict literal here. Maybe you meant '==' instead of '='?
1146
1147>>> f'{x}' = 42
1148Traceback (most recent call last):
1149SyntaxError: cannot assign to f-string expression here. Maybe you meant '==' instead of '='?
1150
1151>>> f'{x}-{y}' = 42
1152Traceback (most recent call last):
1153SyntaxError: cannot assign to f-string expression here. Maybe you meant '==' instead of '='?
1154
1155>>> (x, y, z=3, d, e)
1156Traceback (most recent call last):
1157SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
1158
1159>>> [x, y, z=3, d, e]
1160Traceback (most recent call last):
1161SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
1162
1163>>> [z=3]
1164Traceback (most recent call last):
1165SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
1166
1167>>> {x, y, z=3, d, e}
1168Traceback (most recent call last):
1169SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
1170
1171>>> {z=3}
1172Traceback (most recent call last):
1173SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?
1174
1175>>> from t import x,
1176Traceback (most recent call last):
1177SyntaxError: trailing comma not allowed without surrounding parentheses
1178
1179>>> from t import x,y,
1180Traceback (most recent call last):
1181SyntaxError: trailing comma not allowed without surrounding parentheses
1182
1183# Check that we dont raise the "trailing comma" error if there is more
1184# input to the left of the valid part that we parsed.
1185
1186>>> from t import x,y, and 3
1187Traceback (most recent call last):
1188SyntaxError: invalid syntax
1189
1190>>> (): int
1191Traceback (most recent call last):
1192SyntaxError: only single target (not tuple) can be annotated
1193>>> []: int
1194Traceback (most recent call last):
1195SyntaxError: only single target (not list) can be annotated
1196>>> (()): int
1197Traceback (most recent call last):
1198SyntaxError: only single target (not tuple) can be annotated
1199>>> ([]): int
1200Traceback (most recent call last):
1201SyntaxError: only single target (not list) can be annotated
1202
1203Corner-cases that used to fail to raise the correct error:
1204
1205    >>> def f(*, x=lambda __debug__:0): pass
1206    Traceback (most recent call last):
1207    SyntaxError: cannot assign to __debug__
1208
1209    >>> def f(*args:(lambda __debug__:0)): pass
1210    Traceback (most recent call last):
1211    SyntaxError: cannot assign to __debug__
1212
1213    >>> def f(**kwargs:(lambda __debug__:0)): pass
1214    Traceback (most recent call last):
1215    SyntaxError: cannot assign to __debug__
1216
1217    >>> with (lambda *:0): pass
1218    Traceback (most recent call last):
1219    SyntaxError: named arguments must follow bare *
1220
1221Corner-cases that used to crash:
1222
1223    >>> def f(**__debug__): pass
1224    Traceback (most recent call last):
1225    SyntaxError: cannot assign to __debug__
1226
1227    >>> def f(*xx, __debug__): pass
1228    Traceback (most recent call last):
1229    SyntaxError: cannot assign to __debug__
1230
1231    >>> import ä £
1232    Traceback (most recent call last):
1233    SyntaxError: invalid character '£' (U+00A3)
1234
1235  Invalid pattern matching constructs:
1236
1237    >>> match ...:
1238    ...   case 42 as _:
1239    ...     ...
1240    Traceback (most recent call last):
1241    SyntaxError: cannot use '_' as a target
1242
1243    >>> match ...:
1244    ...   case 42 as 1+2+4:
1245    ...     ...
1246    Traceback (most recent call last):
1247    SyntaxError: invalid pattern target
1248
1249    >>> match ...:
1250    ...   case Foo(z=1, y=2, x):
1251    ...     ...
1252    Traceback (most recent call last):
1253    SyntaxError: positional patterns follow keyword patterns
1254
1255    >>> match ...:
1256    ...   case Foo(a, z=1, y=2, x):
1257    ...     ...
1258    Traceback (most recent call last):
1259    SyntaxError: positional patterns follow keyword patterns
1260
1261    >>> match ...:
1262    ...   case Foo(z=1, x, y=2):
1263    ...     ...
1264    Traceback (most recent call last):
1265    SyntaxError: positional patterns follow keyword patterns
1266
1267    >>> match ...:
1268    ...   case C(a=b, c, d=e, f, g=h, i, j=k, ...):
1269    ...     ...
1270    Traceback (most recent call last):
1271    SyntaxError: positional patterns follow keyword patterns
1272"""
1273
1274import re
1275import unittest
1276
1277from test import support
1278
1279class SyntaxTestCase(unittest.TestCase):
1280
1281    def _check_error(self, code, errtext,
1282                     filename="<testcase>", mode="exec", subclass=None,
1283                     lineno=None, offset=None, end_lineno=None, end_offset=None):
1284        """Check that compiling code raises SyntaxError with errtext.
1285
1286        errtest is a regular expression that must be present in the
1287        test of the exception raised.  If subclass is specified it
1288        is the expected subclass of SyntaxError (e.g. IndentationError).
1289        """
1290        try:
1291            compile(code, filename, mode)
1292        except SyntaxError as err:
1293            if subclass and not isinstance(err, subclass):
1294                self.fail("SyntaxError is not a %s" % subclass.__name__)
1295            mo = re.search(errtext, str(err))
1296            if mo is None:
1297                self.fail("SyntaxError did not contain %r" % (errtext,))
1298            self.assertEqual(err.filename, filename)
1299            if lineno is not None:
1300                self.assertEqual(err.lineno, lineno)
1301            if offset is not None:
1302                self.assertEqual(err.offset, offset)
1303            if end_lineno is not None:
1304                self.assertEqual(err.end_lineno, end_lineno)
1305            if end_offset is not None:
1306                self.assertEqual(err.end_offset, end_offset)
1307
1308        else:
1309            self.fail("compile() did not raise SyntaxError")
1310
1311    def test_expression_with_assignment(self):
1312        self._check_error(
1313            "print(end1 + end2 = ' ')",
1314            'expression cannot contain assignment, perhaps you meant "=="?',
1315            offset=7
1316        )
1317
1318    def test_curly_brace_after_primary_raises_immediately(self):
1319        self._check_error("f{}", "invalid syntax", mode="single")
1320
1321    def test_assign_call(self):
1322        self._check_error("f() = 1", "assign")
1323
1324    def test_assign_del(self):
1325        self._check_error("del (,)", "invalid syntax")
1326        self._check_error("del 1", "cannot delete literal")
1327        self._check_error("del (1, 2)", "cannot delete literal")
1328        self._check_error("del None", "cannot delete None")
1329        self._check_error("del *x", "cannot delete starred")
1330        self._check_error("del (*x)", "cannot use starred expression")
1331        self._check_error("del (*x,)", "cannot delete starred")
1332        self._check_error("del [*x,]", "cannot delete starred")
1333        self._check_error("del f()", "cannot delete function call")
1334        self._check_error("del f(a, b)", "cannot delete function call")
1335        self._check_error("del o.f()", "cannot delete function call")
1336        self._check_error("del a[0]()", "cannot delete function call")
1337        self._check_error("del x, f()", "cannot delete function call")
1338        self._check_error("del f(), x", "cannot delete function call")
1339        self._check_error("del [a, b, ((c), (d,), e.f())]", "cannot delete function call")
1340        self._check_error("del (a if True else b)", "cannot delete conditional")
1341        self._check_error("del +a", "cannot delete expression")
1342        self._check_error("del a, +b", "cannot delete expression")
1343        self._check_error("del a + b", "cannot delete expression")
1344        self._check_error("del (a + b, c)", "cannot delete expression")
1345        self._check_error("del (c[0], a + b)", "cannot delete expression")
1346        self._check_error("del a.b.c + 2", "cannot delete expression")
1347        self._check_error("del a.b.c[0] + 2", "cannot delete expression")
1348        self._check_error("del (a, b, (c, d.e.f + 2))", "cannot delete expression")
1349        self._check_error("del [a, b, (c, d.e.f[0] + 2)]", "cannot delete expression")
1350        self._check_error("del (a := 5)", "cannot delete named expression")
1351        # We don't have a special message for this, but make sure we don't
1352        # report "cannot delete name"
1353        self._check_error("del a += b", "invalid syntax")
1354
1355    def test_global_param_err_first(self):
1356        source = """if 1:
1357            def error(a):
1358                global a  # SyntaxError
1359            def error2():
1360                b = 1
1361                global b  # SyntaxError
1362            """
1363        self._check_error(source, "parameter and global", lineno=3)
1364
1365    def test_nonlocal_param_err_first(self):
1366        source = """if 1:
1367            def error(a):
1368                nonlocal a  # SyntaxError
1369            def error2():
1370                b = 1
1371                global b  # SyntaxError
1372            """
1373        self._check_error(source, "parameter and nonlocal", lineno=3)
1374
1375    def test_break_outside_loop(self):
1376        self._check_error("break", "outside loop")
1377
1378    def test_yield_outside_function(self):
1379        self._check_error("if 0: yield",                "outside function")
1380        self._check_error("if 0: yield\nelse:  x=1",    "outside function")
1381        self._check_error("if 1: pass\nelse: yield",    "outside function")
1382        self._check_error("while 0: yield",             "outside function")
1383        self._check_error("while 0: yield\nelse:  x=1", "outside function")
1384        self._check_error("class C:\n  if 0: yield",    "outside function")
1385        self._check_error("class C:\n  if 1: pass\n  else: yield",
1386                          "outside function")
1387        self._check_error("class C:\n  while 0: yield", "outside function")
1388        self._check_error("class C:\n  while 0: yield\n  else:  x = 1",
1389                          "outside function")
1390
1391    def test_return_outside_function(self):
1392        self._check_error("if 0: return",                "outside function")
1393        self._check_error("if 0: return\nelse:  x=1",    "outside function")
1394        self._check_error("if 1: pass\nelse: return",    "outside function")
1395        self._check_error("while 0: return",             "outside function")
1396        self._check_error("class C:\n  if 0: return",    "outside function")
1397        self._check_error("class C:\n  while 0: return", "outside function")
1398        self._check_error("class C:\n  while 0: return\n  else:  x=1",
1399                          "outside function")
1400        self._check_error("class C:\n  if 0: return\n  else: x= 1",
1401                          "outside function")
1402        self._check_error("class C:\n  if 1: pass\n  else: return",
1403                          "outside function")
1404
1405    def test_break_outside_loop(self):
1406        self._check_error("if 0: break",             "outside loop")
1407        self._check_error("if 0: break\nelse:  x=1",  "outside loop")
1408        self._check_error("if 1: pass\nelse: break", "outside loop")
1409        self._check_error("class C:\n  if 0: break", "outside loop")
1410        self._check_error("class C:\n  if 1: pass\n  else: break",
1411                          "outside loop")
1412
1413    def test_continue_outside_loop(self):
1414        self._check_error("if 0: continue",             "not properly in loop")
1415        self._check_error("if 0: continue\nelse:  x=1", "not properly in loop")
1416        self._check_error("if 1: pass\nelse: continue", "not properly in loop")
1417        self._check_error("class C:\n  if 0: continue", "not properly in loop")
1418        self._check_error("class C:\n  if 1: pass\n  else: continue",
1419                          "not properly in loop")
1420
1421    def test_unexpected_indent(self):
1422        self._check_error("foo()\n bar()\n", "unexpected indent",
1423                          subclass=IndentationError)
1424
1425    def test_no_indent(self):
1426        self._check_error("if 1:\nfoo()", "expected an indented block",
1427                          subclass=IndentationError)
1428
1429    def test_bad_outdent(self):
1430        self._check_error("if 1:\n  foo()\n bar()",
1431                          "unindent does not match .* level",
1432                          subclass=IndentationError)
1433
1434    def test_kwargs_last(self):
1435        self._check_error("int(base=10, '2')",
1436                          "positional argument follows keyword argument")
1437
1438    def test_kwargs_last2(self):
1439        self._check_error("int(**{'base': 10}, '2')",
1440                          "positional argument follows "
1441                          "keyword argument unpacking")
1442
1443    def test_kwargs_last3(self):
1444        self._check_error("int(**{'base': 10}, *['2'])",
1445                          "iterable argument unpacking follows "
1446                          "keyword argument unpacking")
1447
1448    def test_generator_in_function_call(self):
1449        self._check_error("foo(x,    y for y in range(3) for z in range(2) if z    , p)",
1450                          "Generator expression must be parenthesized",
1451                          lineno=1, end_lineno=1, offset=11, end_offset=53)
1452
1453    def test_empty_line_after_linecont(self):
1454        # See issue-40847
1455        s = r"""\
1456pass
1457        \
1458
1459pass
1460"""
1461        try:
1462            compile(s, '<string>', 'exec')
1463        except SyntaxError:
1464            self.fail("Empty line after a line continuation character is valid.")
1465
1466    @support.cpython_only
1467    def test_nested_named_except_blocks(self):
1468        code = ""
1469        for i in range(12):
1470            code += f"{'    '*i}try:\n"
1471            code += f"{'    '*(i+1)}raise Exception\n"
1472            code += f"{'    '*i}except Exception as e:\n"
1473        code += f"{' '*4*12}pass"
1474        self._check_error(code, "too many statically nested blocks")
1475
1476    def test_barry_as_flufl_with_syntax_errors(self):
1477        # The "barry_as_flufl" rule can produce some "bugs-at-a-distance" if
1478        # is reading the wrong token in the presence of syntax errors later
1479        # in the file. See bpo-42214 for more information.
1480        code = """
1481def func1():
1482    if a != b:
1483        raise ValueError
1484
1485def func2():
1486    try
1487        return 1
1488    finally:
1489        pass
1490"""
1491        self._check_error(code, "expected ':'")
1492
1493    def test_invalid_line_continuation_error_position(self):
1494        self._check_error(r"a = 3 \ 4",
1495                          "unexpected character after line continuation character",
1496                          lineno=1, offset=8)
1497        self._check_error('1,\\#\n2',
1498                          "unexpected character after line continuation character",
1499                          lineno=1, offset=4)
1500        self._check_error('\nfgdfgf\n1,\\#\n2\n',
1501                          "unexpected character after line continuation character",
1502                          lineno=3, offset=4)
1503
1504    def test_invalid_line_continuation_left_recursive(self):
1505        # Check bpo-42218: SyntaxErrors following left-recursive rules
1506        # (t_primary_raw in this case) need to be tested explicitly
1507        self._check_error("A.\u018a\\ ",
1508                          "unexpected character after line continuation character")
1509        self._check_error("A.\u03bc\\\n",
1510                          "unexpected EOF while parsing")
1511
1512    def test_error_parenthesis(self):
1513        for paren in "([{":
1514            self._check_error(paren + "1 + 2", f"\\{paren}' was never closed")
1515
1516        for paren in ")]}":
1517            self._check_error(paren + "1 + 2", f"unmatched '\\{paren}'")
1518
1519    def test_match_call_does_not_raise_syntax_error(self):
1520        code = """
1521def match(x):
1522    return 1+1
1523
1524match(34)
1525"""
1526        compile(code, "<string>", "exec")
1527
1528    def test_case_call_does_not_raise_syntax_error(self):
1529        code = """
1530def case(x):
1531    return 1+1
1532
1533case(34)
1534"""
1535        compile(code, "<string>", "exec")
1536
1537    def test_multiline_compiler_error_points_to_the_end(self):
1538        self._check_error(
1539            "call(\na=1,\na=1\n)",
1540            "keyword argument repeated",
1541            lineno=3
1542        )
1543
1544    @support.cpython_only
1545    def test_syntax_error_on_deeply_nested_blocks(self):
1546        # This raises a SyntaxError, it used to raise a SystemError. Context
1547        # for this change can be found on issue #27514
1548
1549        # In 2.5 there was a missing exception and an assert was triggered in a
1550        # debug build.  The number of blocks must be greater than CO_MAXBLOCKS.
1551        # SF #1565514
1552
1553        source = """
1554while 1:
1555 while 2:
1556  while 3:
1557   while 4:
1558    while 5:
1559     while 6:
1560      while 8:
1561       while 9:
1562        while 10:
1563         while 11:
1564          while 12:
1565           while 13:
1566            while 14:
1567             while 15:
1568              while 16:
1569               while 17:
1570                while 18:
1571                 while 19:
1572                  while 20:
1573                   while 21:
1574                    while 22:
1575                     break
1576"""
1577        self._check_error(source, "too many statically nested blocks")
1578
1579    @support.cpython_only
1580    def test_error_on_parser_stack_overflow(self):
1581        source = "-" * 100000 + "4"
1582        for mode in ["exec", "eval", "single"]:
1583            with self.subTest(mode=mode):
1584                with self.assertRaises(MemoryError):
1585                    compile(source, "<string>", mode)
1586
1587
1588def test_main():
1589    support.run_unittest(SyntaxTestCase)
1590    from test import test_syntax
1591    support.run_doctest(test_syntax, verbosity=True)
1592
1593if __name__ == "__main__":
1594    test_main()
1595