Apparently the code to forestall Tk eating events was too aggressive (Tk user input...
[python/dscho.git] / Lib / test / test_grammar.py
blob04b14318fd2189cfd8805121f55dfbe7fc3ffb94
1 # Python test set -- part 1, grammar.
2 # This just tests whether the parser accepts them all.
4 from test_support import *
6 print '1. Parser'
8 print '1.1 Tokens'
10 print '1.1.1 Backslashes'
12 # Backslash means line continuation:
13 x = 1 \
14 + 1
15 if x != 2: raise TestFailed, 'backslash for line continuation'
17 # Backslash does not means continuation in comments :\
18 x = 0
19 if x != 0: raise TestFailed, 'backslash ending comment'
21 print '1.1.2 Numeric literals'
23 print '1.1.2.1 Plain integers'
24 if 0xff != 255: raise TestFailed, 'hex int'
25 if 0377 != 255: raise TestFailed, 'octal int'
26 if 2147483647 != 017777777777: raise TestFailed, 'large positive int'
27 try:
28 from sys import maxint
29 except ImportError:
30 maxint = 2147483647
31 if maxint == 2147483647:
32 if -2147483647-1 != 020000000000: raise TestFailed, 'max negative int'
33 # XXX -2147483648
34 if 037777777777 != -1: raise TestFailed, 'oct -1'
35 if 0xffffffff != -1: raise TestFailed, 'hex -1'
36 for s in '2147483648', '040000000000', '0x100000000':
37 try:
38 x = eval(s)
39 except OverflowError:
40 continue
41 ## raise TestFailed, \
42 print \
43 'No OverflowError on huge integer literal ' + `s`
44 elif eval('maxint == 9223372036854775807'):
45 if eval('-9223372036854775807-1 != 01000000000000000000000'):
46 raise TestFailed, 'max negative int'
47 if eval('01777777777777777777777') != -1: raise TestFailed, 'oct -1'
48 if eval('0xffffffffffffffff') != -1: raise TestFailed, 'hex -1'
49 for s in '9223372036854775808', '02000000000000000000000', \
50 '0x10000000000000000':
51 try:
52 x = eval(s)
53 except OverflowError:
54 continue
55 raise TestFailed, \
56 'No OverflowError on huge integer literal ' + `s`
57 else:
58 print 'Weird maxint value', maxint
60 print '1.1.2.2 Long integers'
61 x = 0L
62 x = 0l
63 x = 0xffffffffffffffffL
64 x = 0xffffffffffffffffl
65 x = 077777777777777777L
66 x = 077777777777777777l
67 x = 123456789012345678901234567890L
68 x = 123456789012345678901234567890l
70 print '1.1.2.3 Floating point'
71 x = 3.14
72 x = 314.
73 x = 0.314
74 # XXX x = 000.314
75 x = .314
76 x = 3e14
77 x = 3E14
78 x = 3e-14
79 x = 3e+14
80 x = 3.e14
81 x = .3e14
82 x = 3.1e4
84 print '1.1.3 String literals'
86 x = ''; y = ""; verify(len(x) == 0 and x == y)
87 x = '\''; y = "'"; verify(len(x) == 1 and x == y and ord(x) == 39)
88 x = '"'; y = "\""; verify(len(x) == 1 and x == y and ord(x) == 34)
89 x = "doesn't \"shrink\" does it"
90 y = 'doesn\'t "shrink" does it'
91 verify(len(x) == 24 and x == y)
92 x = "does \"shrink\" doesn't it"
93 y = 'does "shrink" doesn\'t it'
94 verify(len(x) == 24 and x == y)
95 x = """
96 The "quick"
97 brown fox
98 jumps over
99 the 'lazy' dog.
101 y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n'
102 verify(x == y)
103 y = '''
104 The "quick"
105 brown fox
106 jumps over
107 the 'lazy' dog.
108 '''; verify(x == y)
109 y = "\n\
110 The \"quick\"\n\
111 brown fox\n\
112 jumps over\n\
113 the 'lazy' dog.\n\
114 "; verify(x == y)
115 y = '\n\
116 The \"quick\"\n\
117 brown fox\n\
118 jumps over\n\
119 the \'lazy\' dog.\n\
120 '; verify(x == y)
123 print '1.2 Grammar'
125 print 'single_input' # NEWLINE | simple_stmt | compound_stmt NEWLINE
126 # XXX can't test in a script -- this rule is only used when interactive
128 print 'file_input' # (NEWLINE | stmt)* ENDMARKER
129 # Being tested as this very moment this very module
131 print 'expr_input' # testlist NEWLINE
132 # XXX Hard to test -- used only in calls to input()
134 print 'eval_input' # testlist ENDMARKER
135 x = eval('1, 0 or 1')
137 print 'funcdef'
138 ### 'def' NAME parameters ':' suite
139 ### parameters: '(' [varargslist] ')'
140 ### varargslist: (fpdef ['=' test] ',')* ('*' NAME [',' ('**'|'*' '*') NAME]
141 ### | ('**'|'*' '*') NAME)
142 ### | fpdef ['=' test] (',' fpdef ['=' test])* [',']
143 ### fpdef: NAME | '(' fplist ')'
144 ### fplist: fpdef (',' fpdef)* [',']
145 ### arglist: (argument ',')* (argument | *' test [',' '**' test] | '**' test)
146 ### argument: [test '='] test # Really [keyword '='] test
147 def f1(): pass
148 f1()
149 f1(*())
150 f1(*(), **{})
151 def f2(one_argument): pass
152 def f3(two, arguments): pass
153 def f4(two, (compound, (argument, list))): pass
154 def f5((compound, first), two): pass
155 verify(f2.func_code.co_varnames == ('one_argument',))
156 verify(f3.func_code.co_varnames == ('two', 'arguments'))
157 verify(f4.func_code.co_varnames == ('two', '.2', 'compound', 'argument',
158 'list'))
159 verify(f5.func_code.co_varnames == ('.0', 'two', 'compound', 'first'))
160 def a1(one_arg,): pass
161 def a2(two, args,): pass
162 def v0(*rest): pass
163 def v1(a, *rest): pass
164 def v2(a, b, *rest): pass
165 def v3(a, (b, c), *rest): return a, b, c, rest
166 verify(v3.func_code.co_varnames == ('a', '.2', 'rest', 'b', 'c'))
167 verify(v3(1, (2, 3), 4) == (1, 2, 3, (4,)))
168 def d01(a=1): pass
169 d01()
170 d01(1)
171 d01(*(1,))
172 d01(**{'a':2})
173 def d11(a, b=1): pass
174 d11(1)
175 d11(1, 2)
176 d11(1, **{'b':2})
177 def d21(a, b, c=1): pass
178 d21(1, 2)
179 d21(1, 2, 3)
180 d21(*(1, 2, 3))
181 d21(1, *(2, 3))
182 d21(1, 2, *(3,))
183 d21(1, 2, **{'c':3})
184 def d02(a=1, b=2): pass
185 d02()
186 d02(1)
187 d02(1, 2)
188 d02(*(1, 2))
189 d02(1, *(2,))
190 d02(1, **{'b':2})
191 d02(**{'a': 1, 'b': 2})
192 def d12(a, b=1, c=2): pass
193 d12(1)
194 d12(1, 2)
195 d12(1, 2, 3)
196 def d22(a, b, c=1, d=2): pass
197 d22(1, 2)
198 d22(1, 2, 3)
199 d22(1, 2, 3, 4)
200 def d01v(a=1, *rest): pass
201 d01v()
202 d01v(1)
203 d01v(1, 2)
204 d01v(*(1, 2, 3, 4))
205 d01v(*(1,))
206 d01v(**{'a':2})
207 def d11v(a, b=1, *rest): pass
208 d11v(1)
209 d11v(1, 2)
210 d11v(1, 2, 3)
211 def d21v(a, b, c=1, *rest): pass
212 d21v(1, 2)
213 d21v(1, 2, 3)
214 d21v(1, 2, 3, 4)
215 d21v(*(1, 2, 3, 4))
216 d21v(1, 2, **{'c': 3})
217 def d02v(a=1, b=2, *rest): pass
218 d02v()
219 d02v(1)
220 d02v(1, 2)
221 d02v(1, 2, 3)
222 d02v(1, *(2, 3, 4))
223 d02v(**{'a': 1, 'b': 2})
224 def d12v(a, b=1, c=2, *rest): pass
225 d12v(1)
226 d12v(1, 2)
227 d12v(1, 2, 3)
228 d12v(1, 2, 3, 4)
229 d12v(*(1, 2, 3, 4))
230 d12v(1, 2, *(3, 4, 5))
231 d12v(1, *(2,), **{'c': 3})
232 def d22v(a, b, c=1, d=2, *rest): pass
233 d22v(1, 2)
234 d22v(1, 2, 3)
235 d22v(1, 2, 3, 4)
236 d22v(1, 2, 3, 4, 5)
237 d22v(*(1, 2, 3, 4))
238 d22v(1, 2, *(3, 4, 5))
239 d22v(1, *(2, 3), **{'d': 4})
241 ### lambdef: 'lambda' [varargslist] ':' test
242 print 'lambdef'
243 l1 = lambda : 0
244 verify(l1() == 0)
245 l2 = lambda : a[d] # XXX just testing the expression
246 l3 = lambda : [2 < x for x in [-1, 3, 0L]]
247 verify(l3() == [0, 1, 0])
248 l4 = lambda x = lambda y = lambda z=1 : z : y() : x()
249 verify(l4() == 1)
250 l5 = lambda x, y, z=2: x + y + z
251 verify(l5(1, 2) == 5)
252 verify(l5(1, 2, 3) == 6)
253 check_syntax("lambda x: x = 2")
255 ### stmt: simple_stmt | compound_stmt
256 # Tested below
258 ### simple_stmt: small_stmt (';' small_stmt)* [';']
259 print 'simple_stmt'
260 x = 1; pass; del x
262 ### small_stmt: expr_stmt | print_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt | exec_stmt
263 # Tested below
265 print 'expr_stmt' # (exprlist '=')* exprlist
267 1, 2, 3
268 x = 1
269 x = 1, 2, 3
270 x = y = z = 1, 2, 3
271 x, y, z = 1, 2, 3
272 abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4)
273 # NB these variables are deleted below
275 check_syntax("x + 1 = 1")
276 check_syntax("a + 1 = b + 2")
278 print 'print_stmt' # 'print' (test ',')* [test]
279 print 1, 2, 3
280 print 1, 2, 3,
281 print
282 print 0 or 1, 0 or 1,
283 print 0 or 1
285 print 'extended print_stmt' # 'print' '>>' test ','
286 import sys
287 print >> sys.stdout, 1, 2, 3
288 print >> sys.stdout, 1, 2, 3,
289 print >> sys.stdout
290 print >> sys.stdout, 0 or 1, 0 or 1,
291 print >> sys.stdout, 0 or 1
293 # test printing to an instance
294 class Gulp:
295 def write(self, msg): pass
297 gulp = Gulp()
298 print >> gulp, 1, 2, 3
299 print >> gulp, 1, 2, 3,
300 print >> gulp
301 print >> gulp, 0 or 1, 0 or 1,
302 print >> gulp, 0 or 1
304 # test print >> None
305 def driver():
306 oldstdout = sys.stdout
307 sys.stdout = Gulp()
308 try:
309 tellme(Gulp())
310 tellme()
311 finally:
312 sys.stdout = oldstdout
314 # we should see this once
315 def tellme(file=sys.stdout):
316 print >> file, 'hello world'
318 driver()
320 # we should not see this at all
321 def tellme(file=None):
322 print >> file, 'goodbye universe'
324 driver()
326 # syntax errors
327 check_syntax('print ,')
328 check_syntax('print >> x,')
330 print 'del_stmt' # 'del' exprlist
331 del abc
332 del x, y, (z, xyz)
334 print 'pass_stmt' # 'pass'
335 pass
337 print 'flow_stmt' # break_stmt | continue_stmt | return_stmt | raise_stmt
338 # Tested below
340 print 'break_stmt' # 'break'
341 while 1: break
343 print 'continue_stmt' # 'continue'
344 i = 1
345 while i: i = 0; continue
347 msg = ""
348 while not msg:
349 msg = "continue + try/except ok"
350 try:
351 continue
352 msg = "continue failed to continue inside try"
353 except:
354 msg = "continue inside try called except block"
355 print msg
357 msg = ""
358 while not msg:
359 msg = "finally block not called"
360 try:
361 continue
362 finally:
363 msg = "continue + try/finally ok"
364 print msg
366 print 'return_stmt' # 'return' [testlist]
367 def g1(): return
368 def g2(): return 1
369 g1()
370 x = g2()
372 print 'raise_stmt' # 'raise' test [',' test]
373 try: raise RuntimeError, 'just testing'
374 except RuntimeError: pass
375 try: raise KeyboardInterrupt
376 except KeyboardInterrupt: pass
378 print 'import_stmt' # 'import' NAME (',' NAME)* | 'from' NAME 'import' ('*' | NAME (',' NAME)*)
379 import sys
380 import time, sys
381 from time import time
382 from sys import *
383 from sys import path, argv
385 print 'global_stmt' # 'global' NAME (',' NAME)*
386 def f():
387 global a
388 global a, b
389 global one, two, three, four, five, six, seven, eight, nine, ten
391 print 'exec_stmt' # 'exec' expr ['in' expr [',' expr]]
392 def f():
393 z = None
394 del z
395 exec 'z=1+1\n'
396 if z != 2: raise TestFailed, 'exec \'z=1+1\'\\n'
397 del z
398 exec 'z=1+1'
399 if z != 2: raise TestFailed, 'exec \'z=1+1\''
400 z = None
401 del z
402 exec u'z=1+1\n'
403 if z != 2: raise TestFailed, 'exec u\'z=1+1\'\\n'
404 del z
405 exec u'z=1+1'
406 if z != 2: raise TestFailed, 'exec u\'z=1+1\''
408 g = {}
409 exec 'z = 1' in g
410 if g.has_key('__builtins__'): del g['__builtins__']
411 if g != {'z': 1}: raise TestFailed, 'exec \'z = 1\' in g'
412 g = {}
413 l = {}
415 import warnings
416 warnings.filterwarnings("ignore", "global statement", module="<string>")
417 exec 'global a; a = 1; b = 2' in g, l
418 if g.has_key('__builtins__'): del g['__builtins__']
419 if l.has_key('__builtins__'): del l['__builtins__']
420 if (g, l) != ({'a':1}, {'b':2}): raise TestFailed, 'exec ... in g (%s), l (%s)' %(g,l)
423 print "assert_stmt" # assert_stmt: 'assert' test [',' test]
424 assert 1
425 assert 1, 1
426 assert lambda x:x
427 assert 1, lambda x:x+1
429 ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
430 # Tested below
432 print 'if_stmt' # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
433 if 1: pass
434 if 1: pass
435 else: pass
436 if 0: pass
437 elif 0: pass
438 if 0: pass
439 elif 0: pass
440 elif 0: pass
441 elif 0: pass
442 else: pass
444 print 'while_stmt' # 'while' test ':' suite ['else' ':' suite]
445 while 0: pass
446 while 0: pass
447 else: pass
449 print 'for_stmt' # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
450 for i in 1, 2, 3: pass
451 for i, j, k in (): pass
452 else: pass
453 class Squares:
454 def __init__(self, max):
455 self.max = max
456 self.sofar = []
457 def __len__(self): return len(self.sofar)
458 def __getitem__(self, i):
459 if not 0 <= i < self.max: raise IndexError
460 n = len(self.sofar)
461 while n <= i:
462 self.sofar.append(n*n)
463 n = n+1
464 return self.sofar[i]
465 n = 0
466 for x in Squares(10): n = n+x
467 if n != 285: raise TestFailed, 'for over growing sequence'
469 print 'try_stmt'
470 ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
471 ### | 'try' ':' suite 'finally' ':' suite
472 ### except_clause: 'except' [expr [',' expr]]
473 try:
475 except ZeroDivisionError:
476 pass
477 else:
478 pass
479 try: 1/0
480 except EOFError: pass
481 except TypeError, msg: pass
482 except RuntimeError, msg: pass
483 except: pass
484 else: pass
485 try: 1/0
486 except (EOFError, TypeError, ZeroDivisionError): pass
487 try: 1/0
488 except (EOFError, TypeError, ZeroDivisionError), msg: pass
489 try: pass
490 finally: pass
492 print 'suite' # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
493 if 1: pass
494 if 1:
495 pass
496 if 1:
500 pass
501 pass
503 pass
506 print 'test'
507 ### and_test ('or' and_test)*
508 ### and_test: not_test ('and' not_test)*
509 ### not_test: 'not' not_test | comparison
510 if not 1: pass
511 if 1 and 1: pass
512 if 1 or 1: pass
513 if not not not 1: pass
514 if not 1 and 1 and 1: pass
515 if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass
517 print 'comparison'
518 ### comparison: expr (comp_op expr)*
519 ### comp_op: '<'|'>'|'=='|'>='|'<='|'<>'|'!='|'in'|'not' 'in'|'is'|'is' 'not'
520 if 1: pass
521 x = (1 == 1)
522 if 1 == 1: pass
523 if 1 != 1: pass
524 if 1 <> 1: pass
525 if 1 < 1: pass
526 if 1 > 1: pass
527 if 1 <= 1: pass
528 if 1 >= 1: pass
529 if 1 is 1: pass
530 if 1 is not 1: pass
531 if 1 in (): pass
532 if 1 not in (): pass
533 if 1 < 1 > 1 == 1 >= 1 <= 1 <> 1 != 1 in 1 not in 1 is 1 is not 1: pass
535 print 'binary mask ops'
536 x = 1 & 1
537 x = 1 ^ 1
538 x = 1 | 1
540 print 'shift ops'
541 x = 1 << 1
542 x = 1 >> 1
543 x = 1 << 1 >> 1
545 print 'additive ops'
546 x = 1
547 x = 1 + 1
548 x = 1 - 1 - 1
549 x = 1 - 1 + 1 - 1 + 1
551 print 'multiplicative ops'
552 x = 1 * 1
553 x = 1 / 1
554 x = 1 % 1
555 x = 1 / 1 * 1 % 1
557 print 'unary ops'
558 x = +1
559 x = -1
560 x = ~1
561 x = ~1 ^ 1 & 1 | 1 & 1 ^ -1
562 x = -1*1/1 + 1*1 - ---1*1
564 print 'selectors'
565 ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
566 ### subscript: expr | [expr] ':' [expr]
567 f1()
568 f2(1)
569 f2(1,)
570 f3(1, 2)
571 f3(1, 2,)
572 f4(1, (2, (3, 4)))
573 v0()
574 v0(1)
575 v0(1,)
576 v0(1,2)
577 v0(1,2,3,4,5,6,7,8,9,0)
578 v1(1)
579 v1(1,)
580 v1(1,2)
581 v1(1,2,3)
582 v1(1,2,3,4,5,6,7,8,9,0)
583 v2(1,2)
584 v2(1,2,3)
585 v2(1,2,3,4)
586 v2(1,2,3,4,5,6,7,8,9,0)
587 v3(1,(2,3))
588 v3(1,(2,3),4)
589 v3(1,(2,3),4,5,6,7,8,9,0)
590 print
591 import sys, time
592 c = sys.path[0]
593 x = time.time()
594 x = sys.modules['time'].time()
595 a = '01234'
596 c = a[0]
597 c = a[-1]
598 s = a[0:5]
599 s = a[:5]
600 s = a[0:]
601 s = a[:]
602 s = a[-5:]
603 s = a[:-1]
604 s = a[-4:-3]
606 print 'atoms'
607 ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictmaker] '}' | '`' testlist '`' | NAME | NUMBER | STRING
608 ### dictmaker: test ':' test (',' test ':' test)* [',']
610 x = (1)
611 x = (1 or 2 or 3)
612 x = (1 or 2 or 3, 2, 3)
614 x = []
615 x = [1]
616 x = [1 or 2 or 3]
617 x = [1 or 2 or 3, 2, 3]
618 x = []
620 x = {}
621 x = {'one': 1}
622 x = {'one': 1,}
623 x = {'one' or 'two': 1 or 2}
624 x = {'one': 1, 'two': 2}
625 x = {'one': 1, 'two': 2,}
626 x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6}
628 x = `x`
629 x = `1 or 2 or 3`
630 x = x
631 x = 'x'
632 x = 123
634 ### exprlist: expr (',' expr)* [',']
635 ### testlist: test (',' test)* [',']
636 # These have been exercised enough above
638 print 'classdef' # 'class' NAME ['(' testlist ')'] ':' suite
639 class B: pass
640 class C1(B): pass
641 class C2(B): pass
642 class D(C1, C2, B): pass
643 class C:
644 def meth1(self): pass
645 def meth2(self, arg): pass
646 def meth3(self, a1, a2): pass
648 # list comprehension tests
649 nums = [1, 2, 3, 4, 5]
650 strs = ["Apple", "Banana", "Coconut"]
651 spcs = [" Apple", " Banana ", "Coco nut "]
653 print [s.strip() for s in spcs]
654 print [3 * x for x in nums]
655 print [x for x in nums if x > 2]
656 print [(i, s) for i in nums for s in strs]
657 print [(i, s) for i in nums for s in [f for f in strs if "n" in f]]
659 def test_in_func(l):
660 return [None < x < 3 for x in l if x > 2]
662 print test_in_func(nums)
664 def test_nested_front():
665 print [[y for y in [x, x + 1]] for x in [1,3,5]]
667 test_nested_front()
669 check_syntax("[i, s for i in nums for s in strs]")
670 check_syntax("[x if y]")
672 suppliers = [
673 (1, "Boeing"),
674 (2, "Ford"),
675 (3, "Macdonalds")
678 parts = [
679 (10, "Airliner"),
680 (20, "Engine"),
681 (30, "Cheeseburger")
684 suppart = [
685 (1, 10), (1, 20), (2, 20), (3, 30)
688 print [
689 (sname, pname)
690 for (sno, sname) in suppliers
691 for (pno, pname) in parts
692 for (sp_sno, sp_pno) in suppart
693 if sno == sp_sno and pno == sp_pno