python3-grammar.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945
  1. # Python test set -- part 1, grammar.
  2. # This just tests whether the parser accepts them all.
  3. # NOTE: When you run this test as a script from the command line, you
  4. # get warnings about certain hex/oct constants. Since those are
  5. # issued by the parser, you can't suppress them by adding a
  6. # filterwarnings() call to this module. Therefore, to shut up the
  7. # regression test, the filterwarnings() call has been added to
  8. # regrtest.py.
  9. from test.support import run_unittest, check_syntax_error
  10. import unittest
  11. import sys
  12. # testing import *
  13. from sys import *
  14. class TokenTests(unittest.TestCase):
  15. def testBackslash(self):
  16. # Backslash means line continuation:
  17. x = 1 \
  18. + 1
  19. self.assertEquals(x, 2, 'backslash for line continuation')
  20. # Backslash does not means continuation in comments :\
  21. x = 0
  22. self.assertEquals(x, 0, 'backslash ending comment')
  23. def testPlainIntegers(self):
  24. self.assertEquals(type(000), type(0))
  25. self.assertEquals(0xff, 255)
  26. self.assertEquals(0o377, 255)
  27. self.assertEquals(2147483647, 0o17777777777)
  28. self.assertEquals(0b1001, 9)
  29. # "0x" is not a valid literal
  30. self.assertRaises(SyntaxError, eval, "0x")
  31. from sys import maxsize
  32. if maxsize == 2147483647:
  33. self.assertEquals(-2147483647-1, -0o20000000000)
  34. # XXX -2147483648
  35. self.assert_(0o37777777777 > 0)
  36. self.assert_(0xffffffff > 0)
  37. self.assert_(0b1111111111111111111111111111111 > 0)
  38. for s in ('2147483648', '0o40000000000', '0x100000000',
  39. '0b10000000000000000000000000000000'):
  40. try:
  41. x = eval(s)
  42. except OverflowError:
  43. self.fail("OverflowError on huge integer literal %r" % s)
  44. elif maxsize == 9223372036854775807:
  45. self.assertEquals(-9223372036854775807-1, -0o1000000000000000000000)
  46. self.assert_(0o1777777777777777777777 > 0)
  47. self.assert_(0xffffffffffffffff > 0)
  48. self.assert_(0b11111111111111111111111111111111111111111111111111111111111111 > 0)
  49. for s in '9223372036854775808', '0o2000000000000000000000', \
  50. '0x10000000000000000', \
  51. '0b100000000000000000000000000000000000000000000000000000000000000':
  52. try:
  53. x = eval(s)
  54. except OverflowError:
  55. self.fail("OverflowError on huge integer literal %r" % s)
  56. else:
  57. self.fail('Weird maxsize value %r' % maxsize)
  58. def testLongIntegers(self):
  59. x = 0
  60. x = 0xffffffffffffffff
  61. x = 0Xffffffffffffffff
  62. x = 0o77777777777777777
  63. x = 0O77777777777777777
  64. x = 123456789012345678901234567890
  65. x = 0b100000000000000000000000000000000000000000000000000000000000000000000
  66. x = 0B111111111111111111111111111111111111111111111111111111111111111111111
  67. def testUnderscoresInNumbers(self):
  68. # Integers
  69. x = 1_0
  70. x = 123_456_7_89
  71. x = 0xabc_123_4_5
  72. x = 0X_abc_123
  73. x = 0B11_01
  74. x = 0b_11_01
  75. x = 0o45_67
  76. x = 0O_45_67
  77. # Floats
  78. x = 3_1.4
  79. x = 03_1.4
  80. x = 3_1.
  81. x = .3_1
  82. x = 3.1_4
  83. x = 0_3.1_4
  84. x = 3e1_4
  85. x = 3_1e+4_1
  86. x = 3_1E-4_1
  87. def testFloats(self):
  88. x = 3.14
  89. x = 314.
  90. x = 0.314
  91. # XXX x = 000.314
  92. x = .314
  93. x = 3e14
  94. x = 3E14
  95. x = 3e-14
  96. x = 3e+14
  97. x = 3.e14
  98. x = .3e14
  99. x = 3.1e4
  100. def testEllipsis(self):
  101. x = ...
  102. self.assert_(x is Ellipsis)
  103. self.assertRaises(SyntaxError, eval, ".. .")
  104. class GrammarTests(unittest.TestCase):
  105. # single_input: NEWLINE | simple_stmt | compound_stmt NEWLINE
  106. # XXX can't test in a script -- this rule is only used when interactive
  107. # file_input: (NEWLINE | stmt)* ENDMARKER
  108. # Being tested as this very moment this very module
  109. # expr_input: testlist NEWLINE
  110. # XXX Hard to test -- used only in calls to input()
  111. def testEvalInput(self):
  112. # testlist ENDMARKER
  113. x = eval('1, 0 or 1')
  114. def testFuncdef(self):
  115. ### [decorators] 'def' NAME parameters ['->' test] ':' suite
  116. ### decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
  117. ### decorators: decorator+
  118. ### parameters: '(' [typedargslist] ')'
  119. ### typedargslist: ((tfpdef ['=' test] ',')*
  120. ### ('*' [tfpdef] (',' tfpdef ['=' test])* [',' '**' tfpdef] | '**' tfpdef)
  121. ### | tfpdef ['=' test] (',' tfpdef ['=' test])* [','])
  122. ### tfpdef: NAME [':' test]
  123. ### varargslist: ((vfpdef ['=' test] ',')*
  124. ### ('*' [vfpdef] (',' vfpdef ['=' test])* [',' '**' vfpdef] | '**' vfpdef)
  125. ### | vfpdef ['=' test] (',' vfpdef ['=' test])* [','])
  126. ### vfpdef: NAME
  127. def f1(): pass
  128. f1()
  129. f1(*())
  130. f1(*(), **{})
  131. def f2(one_argument): pass
  132. def f3(two, arguments): pass
  133. self.assertEquals(f2.__code__.co_varnames, ('one_argument',))
  134. self.assertEquals(f3.__code__.co_varnames, ('two', 'arguments'))
  135. def a1(one_arg,): pass
  136. def a2(two, args,): pass
  137. def v0(*rest): pass
  138. def v1(a, *rest): pass
  139. def v2(a, b, *rest): pass
  140. f1()
  141. f2(1)
  142. f2(1,)
  143. f3(1, 2)
  144. f3(1, 2,)
  145. v0()
  146. v0(1)
  147. v0(1,)
  148. v0(1,2)
  149. v0(1,2,3,4,5,6,7,8,9,0)
  150. v1(1)
  151. v1(1,)
  152. v1(1,2)
  153. v1(1,2,3)
  154. v1(1,2,3,4,5,6,7,8,9,0)
  155. v2(1,2)
  156. v2(1,2,3)
  157. v2(1,2,3,4)
  158. v2(1,2,3,4,5,6,7,8,9,0)
  159. def d01(a=1): pass
  160. d01()
  161. d01(1)
  162. d01(*(1,))
  163. d01(**{'a':2})
  164. def d11(a, b=1): pass
  165. d11(1)
  166. d11(1, 2)
  167. d11(1, **{'b':2})
  168. def d21(a, b, c=1): pass
  169. d21(1, 2)
  170. d21(1, 2, 3)
  171. d21(*(1, 2, 3))
  172. d21(1, *(2, 3))
  173. d21(1, 2, *(3,))
  174. d21(1, 2, **{'c':3})
  175. def d02(a=1, b=2): pass
  176. d02()
  177. d02(1)
  178. d02(1, 2)
  179. d02(*(1, 2))
  180. d02(1, *(2,))
  181. d02(1, **{'b':2})
  182. d02(**{'a': 1, 'b': 2})
  183. def d12(a, b=1, c=2): pass
  184. d12(1)
  185. d12(1, 2)
  186. d12(1, 2, 3)
  187. def d22(a, b, c=1, d=2): pass
  188. d22(1, 2)
  189. d22(1, 2, 3)
  190. d22(1, 2, 3, 4)
  191. def d01v(a=1, *rest): pass
  192. d01v()
  193. d01v(1)
  194. d01v(1, 2)
  195. d01v(*(1, 2, 3, 4))
  196. d01v(*(1,))
  197. d01v(**{'a':2})
  198. def d11v(a, b=1, *rest): pass
  199. d11v(1)
  200. d11v(1, 2)
  201. d11v(1, 2, 3)
  202. def d21v(a, b, c=1, *rest): pass
  203. d21v(1, 2)
  204. d21v(1, 2, 3)
  205. d21v(1, 2, 3, 4)
  206. d21v(*(1, 2, 3, 4))
  207. d21v(1, 2, **{'c': 3})
  208. def d02v(a=1, b=2, *rest): pass
  209. d02v()
  210. d02v(1)
  211. d02v(1, 2)
  212. d02v(1, 2, 3)
  213. d02v(1, *(2, 3, 4))
  214. d02v(**{'a': 1, 'b': 2})
  215. def d12v(a, b=1, c=2, *rest): pass
  216. d12v(1)
  217. d12v(1, 2)
  218. d12v(1, 2, 3)
  219. d12v(1, 2, 3, 4)
  220. d12v(*(1, 2, 3, 4))
  221. d12v(1, 2, *(3, 4, 5))
  222. d12v(1, *(2,), **{'c': 3})
  223. def d22v(a, b, c=1, d=2, *rest): pass
  224. d22v(1, 2)
  225. d22v(1, 2, 3)
  226. d22v(1, 2, 3, 4)
  227. d22v(1, 2, 3, 4, 5)
  228. d22v(*(1, 2, 3, 4))
  229. d22v(1, 2, *(3, 4, 5))
  230. d22v(1, *(2, 3), **{'d': 4})
  231. # keyword argument type tests
  232. try:
  233. str('x', **{b'foo':1 })
  234. except TypeError:
  235. pass
  236. else:
  237. self.fail('Bytes should not work as keyword argument names')
  238. # keyword only argument tests
  239. def pos0key1(*, key): return key
  240. pos0key1(key=100)
  241. def pos2key2(p1, p2, *, k1, k2=100): return p1,p2,k1,k2
  242. pos2key2(1, 2, k1=100)
  243. pos2key2(1, 2, k1=100, k2=200)
  244. pos2key2(1, 2, k2=100, k1=200)
  245. def pos2key2dict(p1, p2, *, k1=100, k2, **kwarg): return p1,p2,k1,k2,kwarg
  246. pos2key2dict(1,2,k2=100,tokwarg1=100,tokwarg2=200)
  247. pos2key2dict(1,2,tokwarg1=100,tokwarg2=200, k2=100)
  248. # keyword arguments after *arglist
  249. def f(*args, **kwargs):
  250. return args, kwargs
  251. self.assertEquals(f(1, x=2, *[3, 4], y=5), ((1, 3, 4),
  252. {'x':2, 'y':5}))
  253. self.assertRaises(SyntaxError, eval, "f(1, *(2,3), 4)")
  254. self.assertRaises(SyntaxError, eval, "f(1, x=2, *(3,4), x=5)")
  255. # argument annotation tests
  256. def f(x) -> list: pass
  257. self.assertEquals(f.__annotations__, {'return': list})
  258. def f(x:int): pass
  259. self.assertEquals(f.__annotations__, {'x': int})
  260. def f(*x:str): pass
  261. self.assertEquals(f.__annotations__, {'x': str})
  262. def f(**x:float): pass
  263. self.assertEquals(f.__annotations__, {'x': float})
  264. def f(x, y:1+2): pass
  265. self.assertEquals(f.__annotations__, {'y': 3})
  266. def f(a, b:1, c:2, d): pass
  267. self.assertEquals(f.__annotations__, {'b': 1, 'c': 2})
  268. def f(a, b:1, c:2, d, e:3=4, f=5, *g:6): pass
  269. self.assertEquals(f.__annotations__,
  270. {'b': 1, 'c': 2, 'e': 3, 'g': 6})
  271. def f(a, b:1, c:2, d, e:3=4, f=5, *g:6, h:7, i=8, j:9=10,
  272. **k:11) -> 12: pass
  273. self.assertEquals(f.__annotations__,
  274. {'b': 1, 'c': 2, 'e': 3, 'g': 6, 'h': 7, 'j': 9,
  275. 'k': 11, 'return': 12})
  276. # Check for SF Bug #1697248 - mixing decorators and a return annotation
  277. def null(x): return x
  278. @null
  279. def f(x) -> list: pass
  280. self.assertEquals(f.__annotations__, {'return': list})
  281. # test closures with a variety of oparg's
  282. closure = 1
  283. def f(): return closure
  284. def f(x=1): return closure
  285. def f(*, k=1): return closure
  286. def f() -> int: return closure
  287. # Check ast errors in *args and *kwargs
  288. check_syntax_error(self, "f(*g(1=2))")
  289. check_syntax_error(self, "f(**g(1=2))")
  290. def testLambdef(self):
  291. ### lambdef: 'lambda' [varargslist] ':' test
  292. l1 = lambda : 0
  293. self.assertEquals(l1(), 0)
  294. l2 = lambda : a[d] # XXX just testing the expression
  295. l3 = lambda : [2 < x for x in [-1, 3, 0]]
  296. self.assertEquals(l3(), [0, 1, 0])
  297. l4 = lambda x = lambda y = lambda z=1 : z : y() : x()
  298. self.assertEquals(l4(), 1)
  299. l5 = lambda x, y, z=2: x + y + z
  300. self.assertEquals(l5(1, 2), 5)
  301. self.assertEquals(l5(1, 2, 3), 6)
  302. check_syntax_error(self, "lambda x: x = 2")
  303. check_syntax_error(self, "lambda (None,): None")
  304. l6 = lambda x, y, *, k=20: x+y+k
  305. self.assertEquals(l6(1,2), 1+2+20)
  306. self.assertEquals(l6(1,2,k=10), 1+2+10)
  307. ### stmt: simple_stmt | compound_stmt
  308. # Tested below
  309. def testSimpleStmt(self):
  310. ### simple_stmt: small_stmt (';' small_stmt)* [';']
  311. x = 1; pass; del x
  312. def foo():
  313. # verify statements that end with semi-colons
  314. x = 1; pass; del x;
  315. foo()
  316. ### small_stmt: expr_stmt | pass_stmt | del_stmt | flow_stmt | import_stmt | global_stmt | access_stmt
  317. # Tested below
  318. def testExprStmt(self):
  319. # (exprlist '=')* exprlist
  320. 1
  321. 1, 2, 3
  322. x = 1
  323. x = 1, 2, 3
  324. x = y = z = 1, 2, 3
  325. x, y, z = 1, 2, 3
  326. abc = a, b, c = x, y, z = xyz = 1, 2, (3, 4)
  327. check_syntax_error(self, "x + 1 = 1")
  328. check_syntax_error(self, "a + 1 = b + 2")
  329. def testDelStmt(self):
  330. # 'del' exprlist
  331. abc = [1,2,3]
  332. x, y, z = abc
  333. xyz = x, y, z
  334. del abc
  335. del x, y, (z, xyz)
  336. def testPassStmt(self):
  337. # 'pass'
  338. pass
  339. # flow_stmt: break_stmt | continue_stmt | return_stmt | raise_stmt
  340. # Tested below
  341. def testBreakStmt(self):
  342. # 'break'
  343. while 1: break
  344. def testContinueStmt(self):
  345. # 'continue'
  346. i = 1
  347. while i: i = 0; continue
  348. msg = ""
  349. while not msg:
  350. msg = "ok"
  351. try:
  352. continue
  353. msg = "continue failed to continue inside try"
  354. except:
  355. msg = "continue inside try called except block"
  356. if msg != "ok":
  357. self.fail(msg)
  358. msg = ""
  359. while not msg:
  360. msg = "finally block not called"
  361. try:
  362. continue
  363. finally:
  364. msg = "ok"
  365. if msg != "ok":
  366. self.fail(msg)
  367. def test_break_continue_loop(self):
  368. # This test warrants an explanation. It is a test specifically for SF bugs
  369. # #463359 and #462937. The bug is that a 'break' statement executed or
  370. # exception raised inside a try/except inside a loop, *after* a continue
  371. # statement has been executed in that loop, will cause the wrong number of
  372. # arguments to be popped off the stack and the instruction pointer reset to
  373. # a very small number (usually 0.) Because of this, the following test
  374. # *must* written as a function, and the tracking vars *must* be function
  375. # arguments with default values. Otherwise, the test will loop and loop.
  376. def test_inner(extra_burning_oil = 1, count=0):
  377. big_hippo = 2
  378. while big_hippo:
  379. count += 1
  380. try:
  381. if extra_burning_oil and big_hippo == 1:
  382. extra_burning_oil -= 1
  383. break
  384. big_hippo -= 1
  385. continue
  386. except:
  387. raise
  388. if count > 2 or big_hippo != 1:
  389. self.fail("continue then break in try/except in loop broken!")
  390. test_inner()
  391. def testReturn(self):
  392. # 'return' [testlist]
  393. def g1(): return
  394. def g2(): return 1
  395. g1()
  396. x = g2()
  397. check_syntax_error(self, "class foo:return 1")
  398. def testYield(self):
  399. check_syntax_error(self, "class foo:yield 1")
  400. def testRaise(self):
  401. # 'raise' test [',' test]
  402. try: raise RuntimeError('just testing')
  403. except RuntimeError: pass
  404. try: raise KeyboardInterrupt
  405. except KeyboardInterrupt: pass
  406. def testImport(self):
  407. # 'import' dotted_as_names
  408. import sys
  409. import time, sys
  410. # 'from' dotted_name 'import' ('*' | '(' import_as_names ')' | import_as_names)
  411. from time import time
  412. from time import (time)
  413. # not testable inside a function, but already done at top of the module
  414. # from sys import *
  415. from sys import path, argv
  416. from sys import (path, argv)
  417. from sys import (path, argv,)
  418. def testGlobal(self):
  419. # 'global' NAME (',' NAME)*
  420. global a
  421. global a, b
  422. global one, two, three, four, five, six, seven, eight, nine, ten
  423. def testNonlocal(self):
  424. # 'nonlocal' NAME (',' NAME)*
  425. x = 0
  426. y = 0
  427. def f():
  428. nonlocal x
  429. nonlocal x, y
  430. def testAssert(self):
  431. # assert_stmt: 'assert' test [',' test]
  432. assert 1
  433. assert 1, 1
  434. assert lambda x:x
  435. assert 1, lambda x:x+1
  436. try:
  437. assert 0, "msg"
  438. except AssertionError as e:
  439. self.assertEquals(e.args[0], "msg")
  440. else:
  441. if __debug__:
  442. self.fail("AssertionError not raised by assert 0")
  443. ### compound_stmt: if_stmt | while_stmt | for_stmt | try_stmt | funcdef | classdef
  444. # Tested below
  445. def testIf(self):
  446. # 'if' test ':' suite ('elif' test ':' suite)* ['else' ':' suite]
  447. if 1: pass
  448. if 1: pass
  449. else: pass
  450. if 0: pass
  451. elif 0: pass
  452. if 0: pass
  453. elif 0: pass
  454. elif 0: pass
  455. elif 0: pass
  456. else: pass
  457. def testWhile(self):
  458. # 'while' test ':' suite ['else' ':' suite]
  459. while 0: pass
  460. while 0: pass
  461. else: pass
  462. # Issue1920: "while 0" is optimized away,
  463. # ensure that the "else" clause is still present.
  464. x = 0
  465. while 0:
  466. x = 1
  467. else:
  468. x = 2
  469. self.assertEquals(x, 2)
  470. def testFor(self):
  471. # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
  472. for i in 1, 2, 3: pass
  473. for i, j, k in (): pass
  474. else: pass
  475. class Squares:
  476. def __init__(self, max):
  477. self.max = max
  478. self.sofar = []
  479. def __len__(self): return len(self.sofar)
  480. def __getitem__(self, i):
  481. if not 0 <= i < self.max: raise IndexError
  482. n = len(self.sofar)
  483. while n <= i:
  484. self.sofar.append(n*n)
  485. n = n+1
  486. return self.sofar[i]
  487. n = 0
  488. for x in Squares(10): n = n+x
  489. if n != 285:
  490. self.fail('for over growing sequence')
  491. result = []
  492. for x, in [(1,), (2,), (3,)]:
  493. result.append(x)
  494. self.assertEqual(result, [1, 2, 3])
  495. def testTry(self):
  496. ### try_stmt: 'try' ':' suite (except_clause ':' suite)+ ['else' ':' suite]
  497. ### | 'try' ':' suite 'finally' ':' suite
  498. ### except_clause: 'except' [expr ['as' expr]]
  499. try:
  500. 1/0
  501. except ZeroDivisionError:
  502. pass
  503. else:
  504. pass
  505. try: 1/0
  506. except EOFError: pass
  507. except TypeError as msg: pass
  508. except RuntimeError as msg: pass
  509. except: pass
  510. else: pass
  511. try: 1/0
  512. except (EOFError, TypeError, ZeroDivisionError): pass
  513. try: 1/0
  514. except (EOFError, TypeError, ZeroDivisionError) as msg: pass
  515. try: pass
  516. finally: pass
  517. def testSuite(self):
  518. # simple_stmt | NEWLINE INDENT NEWLINE* (stmt NEWLINE*)+ DEDENT
  519. if 1: pass
  520. if 1:
  521. pass
  522. if 1:
  523. #
  524. #
  525. #
  526. pass
  527. pass
  528. #
  529. pass
  530. #
  531. def testTest(self):
  532. ### and_test ('or' and_test)*
  533. ### and_test: not_test ('and' not_test)*
  534. ### not_test: 'not' not_test | comparison
  535. if not 1: pass
  536. if 1 and 1: pass
  537. if 1 or 1: pass
  538. if not not not 1: pass
  539. if not 1 and 1 and 1: pass
  540. if 1 and 1 or 1 and 1 and 1 or not 1 and 1: pass
  541. def testComparison(self):
  542. ### comparison: expr (comp_op expr)*
  543. ### comp_op: '<'|'>'|'=='|'>='|'<='|'!='|'in'|'not' 'in'|'is'|'is' 'not'
  544. if 1: pass
  545. x = (1 == 1)
  546. if 1 == 1: pass
  547. if 1 != 1: pass
  548. if 1 < 1: pass
  549. if 1 > 1: pass
  550. if 1 <= 1: pass
  551. if 1 >= 1: pass
  552. if 1 is 1: pass
  553. if 1 is not 1: pass
  554. if 1 in (): pass
  555. if 1 not in (): pass
  556. if 1 < 1 > 1 == 1 >= 1 <= 1 != 1 in 1 not in 1 is 1 is not 1: pass
  557. def testBinaryMaskOps(self):
  558. x = 1 & 1
  559. x = 1 ^ 1
  560. x = 1 | 1
  561. def testShiftOps(self):
  562. x = 1 << 1
  563. x = 1 >> 1
  564. x = 1 << 1 >> 1
  565. def testAdditiveOps(self):
  566. x = 1
  567. x = 1 + 1
  568. x = 1 - 1 - 1
  569. x = 1 - 1 + 1 - 1 + 1
  570. def testMultiplicativeOps(self):
  571. x = 1 * 1
  572. x = 1 / 1
  573. x = 1 % 1
  574. x = 1 / 1 * 1 % 1
  575. def testUnaryOps(self):
  576. x = +1
  577. x = -1
  578. x = ~1
  579. x = ~1 ^ 1 & 1 | 1 & 1 ^ -1
  580. x = -1*1/1 + 1*1 - ---1*1
  581. def testSelectors(self):
  582. ### trailer: '(' [testlist] ')' | '[' subscript ']' | '.' NAME
  583. ### subscript: expr | [expr] ':' [expr]
  584. import sys, time
  585. c = sys.path[0]
  586. x = time.time()
  587. x = sys.modules['time'].time()
  588. a = '01234'
  589. c = a[0]
  590. c = a[-1]
  591. s = a[0:5]
  592. s = a[:5]
  593. s = a[0:]
  594. s = a[:]
  595. s = a[-5:]
  596. s = a[:-1]
  597. s = a[-4:-3]
  598. # A rough test of SF bug 1333982. http://python.org/sf/1333982
  599. # The testing here is fairly incomplete.
  600. # Test cases should include: commas with 1 and 2 colons
  601. d = {}
  602. d[1] = 1
  603. d[1,] = 2
  604. d[1,2] = 3
  605. d[1,2,3] = 4
  606. L = list(d)
  607. L.sort(key=lambda x: x if isinstance(x, tuple) else ())
  608. self.assertEquals(str(L), '[1, (1,), (1, 2), (1, 2, 3)]')
  609. def testAtoms(self):
  610. ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictsetmaker] '}' | NAME | NUMBER | STRING
  611. ### dictsetmaker: (test ':' test (',' test ':' test)* [',']) | (test (',' test)* [','])
  612. x = (1)
  613. x = (1 or 2 or 3)
  614. x = (1 or 2 or 3, 2, 3)
  615. x = []
  616. x = [1]
  617. x = [1 or 2 or 3]
  618. x = [1 or 2 or 3, 2, 3]
  619. 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}
  627. x = {'one'}
  628. x = {'one', 1,}
  629. x = {'one', 'two', 'three'}
  630. x = {2, 3, 4,}
  631. x = x
  632. x = 'x'
  633. x = 123
  634. ### exprlist: expr (',' expr)* [',']
  635. ### testlist: test (',' test)* [',']
  636. # These have been exercised enough above
  637. def testClassdef(self):
  638. # 'class' NAME ['(' [testlist] ')'] ':' suite
  639. class B: pass
  640. class B2(): pass
  641. class C1(B): pass
  642. class C2(B): pass
  643. class D(C1, C2, B): pass
  644. class C:
  645. def meth1(self): pass
  646. def meth2(self, arg): pass
  647. def meth3(self, a1, a2): pass
  648. # decorator: '@' dotted_name [ '(' [arglist] ')' ] NEWLINE
  649. # decorators: decorator+
  650. # decorated: decorators (classdef | funcdef)
  651. def class_decorator(x): return x
  652. @class_decorator
  653. class G: pass
  654. def testDictcomps(self):
  655. # dictorsetmaker: ( (test ':' test (comp_for |
  656. # (',' test ':' test)* [','])) |
  657. # (test (comp_for | (',' test)* [','])) )
  658. nums = [1, 2, 3]
  659. self.assertEqual({i:i+1 for i in nums}, {1: 2, 2: 3, 3: 4})
  660. def testListcomps(self):
  661. # list comprehension tests
  662. nums = [1, 2, 3, 4, 5]
  663. strs = ["Apple", "Banana", "Coconut"]
  664. spcs = [" Apple", " Banana ", "Coco nut "]
  665. self.assertEqual([s.strip() for s in spcs], ['Apple', 'Banana', 'Coco nut'])
  666. self.assertEqual([3 * x for x in nums], [3, 6, 9, 12, 15])
  667. self.assertEqual([x for x in nums if x > 2], [3, 4, 5])
  668. self.assertEqual([(i, s) for i in nums for s in strs],
  669. [(1, 'Apple'), (1, 'Banana'), (1, 'Coconut'),
  670. (2, 'Apple'), (2, 'Banana'), (2, 'Coconut'),
  671. (3, 'Apple'), (3, 'Banana'), (3, 'Coconut'),
  672. (4, 'Apple'), (4, 'Banana'), (4, 'Coconut'),
  673. (5, 'Apple'), (5, 'Banana'), (5, 'Coconut')])
  674. self.assertEqual([(i, s) for i in nums for s in [f for f in strs if "n" in f]],
  675. [(1, 'Banana'), (1, 'Coconut'), (2, 'Banana'), (2, 'Coconut'),
  676. (3, 'Banana'), (3, 'Coconut'), (4, 'Banana'), (4, 'Coconut'),
  677. (5, 'Banana'), (5, 'Coconut')])
  678. self.assertEqual([(lambda a:[a**i for i in range(a+1)])(j) for j in range(5)],
  679. [[1], [1, 1], [1, 2, 4], [1, 3, 9, 27], [1, 4, 16, 64, 256]])
  680. def test_in_func(l):
  681. return [0 < x < 3 for x in l if x > 2]
  682. self.assertEqual(test_in_func(nums), [False, False, False])
  683. def test_nested_front():
  684. self.assertEqual([[y for y in [x, x + 1]] for x in [1,3,5]],
  685. [[1, 2], [3, 4], [5, 6]])
  686. test_nested_front()
  687. check_syntax_error(self, "[i, s for i in nums for s in strs]")
  688. check_syntax_error(self, "[x if y]")
  689. suppliers = [
  690. (1, "Boeing"),
  691. (2, "Ford"),
  692. (3, "Macdonalds")
  693. ]
  694. parts = [
  695. (10, "Airliner"),
  696. (20, "Engine"),
  697. (30, "Cheeseburger")
  698. ]
  699. suppart = [
  700. (1, 10), (1, 20), (2, 20), (3, 30)
  701. ]
  702. x = [
  703. (sname, pname)
  704. for (sno, sname) in suppliers
  705. for (pno, pname) in parts
  706. for (sp_sno, sp_pno) in suppart
  707. if sno == sp_sno and pno == sp_pno
  708. ]
  709. self.assertEqual(x, [('Boeing', 'Airliner'), ('Boeing', 'Engine'), ('Ford', 'Engine'),
  710. ('Macdonalds', 'Cheeseburger')])
  711. def testGenexps(self):
  712. # generator expression tests
  713. g = ([x for x in range(10)] for x in range(1))
  714. self.assertEqual(next(g), [x for x in range(10)])
  715. try:
  716. next(g)
  717. self.fail('should produce StopIteration exception')
  718. except StopIteration:
  719. pass
  720. a = 1
  721. try:
  722. g = (a for d in a)
  723. next(g)
  724. self.fail('should produce TypeError')
  725. except TypeError:
  726. pass
  727. self.assertEqual(list((x, y) for x in 'abcd' for y in 'abcd'), [(x, y) for x in 'abcd' for y in 'abcd'])
  728. self.assertEqual(list((x, y) for x in 'ab' for y in 'xy'), [(x, y) for x in 'ab' for y in 'xy'])
  729. a = [x for x in range(10)]
  730. b = (x for x in (y for y in a))
  731. self.assertEqual(sum(b), sum([x for x in range(10)]))
  732. self.assertEqual(sum(x**2 for x in range(10)), sum([x**2 for x in range(10)]))
  733. self.assertEqual(sum(x*x for x in range(10) if x%2), sum([x*x for x in range(10) if x%2]))
  734. self.assertEqual(sum(x for x in (y for y in range(10))), sum([x for x in range(10)]))
  735. self.assertEqual(sum(x for x in (y for y in (z for z in range(10)))), sum([x for x in range(10)]))
  736. self.assertEqual(sum(x for x in [y for y in (z for z in range(10))]), sum([x for x in range(10)]))
  737. self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True)) if True), sum([x for x in range(10)]))
  738. self.assertEqual(sum(x for x in (y for y in (z for z in range(10) if True) if False) if True), 0)
  739. check_syntax_error(self, "foo(x for x in range(10), 100)")
  740. check_syntax_error(self, "foo(100, x for x in range(10))")
  741. def testComprehensionSpecials(self):
  742. # test for outmost iterable precomputation
  743. x = 10; g = (i for i in range(x)); x = 5
  744. self.assertEqual(len(list(g)), 10)
  745. # This should hold, since we're only precomputing outmost iterable.
  746. x = 10; t = False; g = ((i,j) for i in range(x) if t for j in range(x))
  747. x = 5; t = True;
  748. self.assertEqual([(i,j) for i in range(10) for j in range(5)], list(g))
  749. # Grammar allows multiple adjacent 'if's in listcomps and genexps,
  750. # even though it's silly. Make sure it works (ifelse broke this.)
  751. self.assertEqual([ x for x in range(10) if x % 2 if x % 3 ], [1, 5, 7])
  752. self.assertEqual(list(x for x in range(10) if x % 2 if x % 3), [1, 5, 7])
  753. # verify unpacking single element tuples in listcomp/genexp.
  754. self.assertEqual([x for x, in [(4,), (5,), (6,)]], [4, 5, 6])
  755. self.assertEqual(list(x for x, in [(7,), (8,), (9,)]), [7, 8, 9])
  756. def test_with_statement(self):
  757. class manager(object):
  758. def __enter__(self):
  759. return (1, 2)
  760. def __exit__(self, *args):
  761. pass
  762. with manager():
  763. pass
  764. with manager() as x:
  765. pass
  766. with manager() as (x, y):
  767. pass
  768. with manager(), manager():
  769. pass
  770. with manager() as x, manager() as y:
  771. pass
  772. with manager() as x, manager():
  773. pass
  774. def testIfElseExpr(self):
  775. # Test ifelse expressions in various cases
  776. def _checkeval(msg, ret):
  777. "helper to check that evaluation of expressions is done correctly"
  778. print(x)
  779. return ret
  780. # the next line is not allowed anymore
  781. #self.assertEqual([ x() for x in lambda: True, lambda: False if x() ], [True])
  782. self.assertEqual([ x() for x in (lambda: True, lambda: False) if x() ], [True])
  783. self.assertEqual([ x(False) for x in (lambda x: False if x else True, lambda x: True if x else False) if x(False) ], [True])
  784. self.assertEqual((5 if 1 else _checkeval("check 1", 0)), 5)
  785. self.assertEqual((_checkeval("check 2", 0) if 0 else 5), 5)
  786. self.assertEqual((5 and 6 if 0 else 1), 1)
  787. self.assertEqual(((5 and 6) if 0 else 1), 1)
  788. self.assertEqual((5 and (6 if 1 else 1)), 6)
  789. self.assertEqual((0 or _checkeval("check 3", 2) if 0 else 3), 3)
  790. self.assertEqual((1 or _checkeval("check 4", 2) if 1 else _checkeval("check 5", 3)), 1)
  791. self.assertEqual((0 or 5 if 1 else _checkeval("check 6", 3)), 5)
  792. self.assertEqual((not 5 if 1 else 1), False)
  793. self.assertEqual((not 5 if 0 else 1), 1)
  794. self.assertEqual((6 + 1 if 1 else 2), 7)
  795. self.assertEqual((6 - 1 if 1 else 2), 5)
  796. self.assertEqual((6 * 2 if 1 else 4), 12)
  797. self.assertEqual((6 / 2 if 1 else 3), 3)
  798. self.assertEqual((6 < 4 if 0 else 2), 2)
  799. def testStringLiterals(self):
  800. x = ''; y = ""; self.assert_(len(x) == 0 and x == y)
  801. x = '\''; y = "'"; self.assert_(len(x) == 1 and x == y and ord(x) == 39)
  802. x = '"'; y = "\""; self.assert_(len(x) == 1 and x == y and ord(x) == 34)
  803. x = "doesn't \"shrink\" does it"
  804. y = 'doesn\'t "shrink" does it'
  805. self.assert_(len(x) == 24 and x == y)
  806. x = "does \"shrink\" doesn't it"
  807. y = 'does "shrink" doesn\'t it'
  808. self.assert_(len(x) == 24 and x == y)
  809. x = f"""
  810. The "quick"
  811. brown fo{ok()}x
  812. jumps over
  813. the 'lazy' dog.
  814. """
  815. y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n'
  816. self.assertEquals(x, y)
  817. y = '''
  818. The "quick"
  819. brown fox
  820. jumps over
  821. the 'lazy' dog.
  822. '''
  823. self.assertEquals(x, y)
  824. y = "\n\
  825. The \"quick\"\n\
  826. brown fox\n\
  827. jumps over\n\
  828. the 'lazy' dog.\n\
  829. "
  830. self.assertEquals(x, y)
  831. y = '\n\
  832. The \"quick\"\n\
  833. brown fox\n\
  834. jumps over\n\
  835. the \'lazy\' dog.\n\
  836. '
  837. self.assertEquals(x, y)
  838. def test_main():
  839. run_unittest(TokenTests, GrammarTests)
  840. if __name__ == '__main__':
  841. test_main()