run-functions.test 29 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258
  1. # Test cases for functions and calls (compile and run)
  2. [case testCallTrivialFunction]
  3. def f(x: int) -> int:
  4. return x
  5. [file driver.py]
  6. from native import f
  7. print(f(3))
  8. print(f(-157))
  9. print(f(10**20))
  10. print(f(-10**20))
  11. [out]
  12. 3
  13. -157
  14. 100000000000000000000
  15. -100000000000000000000
  16. [case testRecursiveFibonacci]
  17. def fib(n: int) -> int:
  18. if n <= 1:
  19. return 1
  20. else:
  21. return fib(n - 1) + fib(n - 2)
  22. [file driver.py]
  23. from native import fib
  24. print(fib(0))
  25. print(fib(1))
  26. print(fib(2))
  27. print(fib(6))
  28. [out]
  29. 1
  30. 1
  31. 2
  32. 13
  33. [case testNestedFunctions]
  34. from typing import Callable, List
  35. def a() -> Callable[[], object]:
  36. def inner() -> object:
  37. return None
  38. return inner
  39. def b() -> Callable[[], Callable[[], str]]:
  40. def first() -> Callable[[], str]:
  41. def second() -> str:
  42. return 'b.first.second: nested function'
  43. return second
  44. return first
  45. def c(num: float) -> Callable[[str], str]:
  46. def inner(s: str) -> str:
  47. return s + '!'
  48. return inner
  49. def d(num: float) -> str:
  50. def inner(s: str) -> str:
  51. return s + '?'
  52. a = inner('one')
  53. b = inner('two')
  54. return a
  55. def e() -> int:
  56. return 0
  57. def f() -> int:
  58. def inner() -> int:
  59. return e()
  60. return inner()
  61. def g() -> Callable[[], Callable[[], int]]:
  62. def inner() -> Callable[[], int]:
  63. return e
  64. return inner
  65. def h(num: int) -> int:
  66. def inner() -> int:
  67. return num
  68. return inner()
  69. def i() -> int:
  70. num = 3
  71. def inner() -> int:
  72. return num
  73. return inner()
  74. def j(num: int) -> int:
  75. x = 1
  76. y = 2
  77. def inner() -> int:
  78. nonlocal x
  79. x = 3
  80. return num + x + y
  81. return inner()
  82. def k() -> int:
  83. num = 3
  84. def inner() -> int:
  85. nonlocal num
  86. num = 5
  87. return num
  88. return inner() + num
  89. def l() -> int:
  90. num = 3
  91. def inner() -> int:
  92. num = 5
  93. return num
  94. return inner() + num
  95. def m() -> Callable[[], int]:
  96. num = 1
  97. def inner() -> int:
  98. num += 1
  99. return num
  100. num += 1
  101. return inner
  102. def n() -> int:
  103. x = 1
  104. def add_one() -> None:
  105. x += 1
  106. def add_two() -> None:
  107. x += 2
  108. add_one()
  109. add_two()
  110. return x
  111. def triple(a: int) -> Callable[[], Callable[[int], int]]:
  112. x = 1
  113. def outer() -> Callable[[int], int]:
  114. nonlocal x
  115. x += 1
  116. x += a
  117. a += 1
  118. def inner(b: int) -> int:
  119. x += b
  120. return x
  121. return inner
  122. return outer
  123. def if_else(flag: int) -> str:
  124. def dummy_funtion() -> str:
  125. return 'if_else.dummy_function'
  126. if flag < 0:
  127. def inner() -> str:
  128. return 'if_else.inner: first definition'
  129. elif flag > 0:
  130. def inner() -> str:
  131. return 'if_else.inner: second definition'
  132. else:
  133. def inner() -> str:
  134. return 'if_else.inner: third definition'
  135. return inner()
  136. def for_loop() -> int:
  137. def dummy_funtion() -> str:
  138. return 'for_loop.dummy_function'
  139. for i in range(5):
  140. def inner(i: int) -> int:
  141. return i
  142. if i == 3:
  143. return inner(i)
  144. return 0
  145. def while_loop() -> int:
  146. def dummy_funtion() -> str:
  147. return 'while_loop.dummy_function'
  148. i = 0
  149. while i < 5:
  150. def inner(i: int) -> int:
  151. return i
  152. if i == 3:
  153. return inner(i)
  154. i += 1
  155. return 0
  156. def free_vars(foo: int, bar: int) -> int:
  157. x = 1
  158. y = 2
  159. def g(): # type: ignore # missing type annotation for testing
  160. nonlocal y
  161. y = 3
  162. nonlocal bar
  163. bar += y
  164. z = 3
  165. g()
  166. return bar
  167. def lambdas(x: int, y: int) -> int:
  168. s = lambda a, b: a + b + x + y
  169. return s(1, 2)
  170. def outer() -> str:
  171. return 'outer: normal function'
  172. def inner() -> str:
  173. return 'inner: normal function'
  174. class A:
  175. def __init__(self, x: int) -> None:
  176. self.x = x
  177. def outer(self, num: int) -> int:
  178. y = 5
  179. def inner() -> int:
  180. return self.x + y + num
  181. return inner()
  182. def o() -> int:
  183. a = [0, 0]
  184. b = 0
  185. def b_incr() -> List[int]:
  186. b += 10
  187. return a
  188. c = 0
  189. def c_incr() -> int:
  190. c += 1
  191. return c
  192. # x = 1, y = 1
  193. x = y = c_incr()
  194. # a = [2, 2], b = 20
  195. b_incr()[0] = b_incr()[1] = c_incr()
  196. # Should return 26.
  197. return x + y + a[0] + a[1] + b
  198. global_upvar = 20
  199. toplevel_lambda = lambda x: 10 + global_upvar + x
  200. [file driver.py]
  201. from native import (
  202. a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, triple, if_else, for_loop, while_loop,
  203. free_vars, lambdas, outer, inner, A, toplevel_lambda
  204. )
  205. assert a()() == None
  206. assert b()()() == 'b.first.second: nested function'
  207. assert c(5.0)('c') == 'c!'
  208. assert d(4.0) == 'one?'
  209. assert e() == 0
  210. assert f() == 0
  211. assert g()()() == 0
  212. assert h(3) == 3
  213. assert i() == 3
  214. assert j(3) == 8
  215. assert k() == 10
  216. assert l() == 8
  217. assert m()() == 3
  218. assert n() == 4
  219. assert o() == 26
  220. triple_outer = triple(2)
  221. triple_inner = triple_outer()
  222. assert triple_inner(4) == 8
  223. assert triple_inner(4) == 12
  224. assert triple_outer()(4) == 20
  225. assert if_else(-1) == 'if_else.inner: first definition'
  226. assert if_else(1) == 'if_else.inner: second definition'
  227. assert if_else(0) == 'if_else.inner: third definition'
  228. assert for_loop() == 3
  229. assert while_loop() == 3
  230. assert free_vars(1, 2) == 5
  231. assert lambdas(3, 4) == 10
  232. assert outer() == 'outer: normal function'
  233. assert inner() == 'inner: normal function'
  234. assert A(3).outer(4) == 12
  235. assert toplevel_lambda(5) == 35
  236. [case testNestedFunctions2]
  237. from typing import Callable
  238. def outer() -> Callable[[], object]:
  239. def inner() -> object:
  240. return None
  241. return inner
  242. def first() -> Callable[[], Callable[[], str]]:
  243. def second() -> Callable[[], str]:
  244. def third() -> str:
  245. return 'third: nested function'
  246. return third
  247. return second
  248. def f1() -> int:
  249. x = 1
  250. def f2() -> int:
  251. y = 2
  252. def f3() -> int:
  253. z = 3
  254. return y
  255. return f3()
  256. return f2()
  257. def outer_func() -> int:
  258. def inner_func() -> int:
  259. return x
  260. x = 1
  261. return inner_func()
  262. def mutual_recursion(start : int) -> int:
  263. def f1(k : int) -> int:
  264. if k <= 0:
  265. return 0
  266. k -= 1
  267. return f2(k)
  268. def f2(k : int) -> int:
  269. if k <= 0:
  270. return 0
  271. k -= 1
  272. return f1(k)
  273. return f1(start)
  274. def topLayer() -> int:
  275. def middleLayer() -> int:
  276. def bottomLayer() -> int:
  277. return x
  278. return bottomLayer()
  279. x = 1
  280. return middleLayer()
  281. def nest1() -> str:
  282. def nest2() -> str:
  283. def nest3() -> str:
  284. def mut1(val: int) -> str:
  285. if val <= 0:
  286. return "bottomed"
  287. val -= 1
  288. return mut2(val)
  289. def mut2(val: int) -> str:
  290. if val <= 0:
  291. return "bottomed"
  292. val -= 1
  293. return mut1(val)
  294. return mut1(start)
  295. return nest3()
  296. start = 3
  297. return nest2()
  298. def uno(num: float) -> Callable[[str], str]:
  299. def dos(s: str) -> str:
  300. return s + '!'
  301. return dos
  302. def eins(num: float) -> str:
  303. def zwei(s: str) -> str:
  304. return s + '?'
  305. a = zwei('eins')
  306. b = zwei('zwei')
  307. return a
  308. def call_other_inner_func(a: int) -> int:
  309. def foo() -> int:
  310. return a + 1
  311. def bar() -> int:
  312. return foo()
  313. def baz(n: int) -> int:
  314. if n == 0:
  315. return 0
  316. return n + baz(n - 1)
  317. return bar() + baz(a)
  318. def inner() -> str:
  319. return 'inner: normal function'
  320. def second() -> str:
  321. return 'second: normal function'
  322. def third() -> str:
  323. return 'third: normal function'
  324. [file driver.py]
  325. from native import (outer, inner, first, uno, eins, call_other_inner_func,
  326. second, third, f1, outer_func, mutual_recursion, topLayer, nest1)
  327. assert outer()() == None
  328. assert inner() == 'inner: normal function'
  329. assert first()()() == 'third: nested function'
  330. assert uno(5.0)('uno') == 'uno!'
  331. assert eins(4.0) == 'eins?'
  332. assert call_other_inner_func(5) == 21
  333. assert second() == 'second: normal function'
  334. assert third() == 'third: normal function'
  335. assert f1() == 2
  336. assert outer_func() == 1
  337. assert mutual_recursion(5) == 0
  338. assert topLayer() == 1
  339. assert nest1() == "bottomed"
  340. [case testFunctionCallWithDefaultArgs]
  341. from typing import Tuple, List, Optional, Callable, Any
  342. def f(x: int, y: int = 3, s: str = "test", z: object = 5) -> Tuple[int, str]:
  343. def inner() -> int:
  344. return x + y
  345. return inner(), s
  346. def g() -> None:
  347. assert f(2) == (5, "test")
  348. assert f(s = "123", x = -2) == (1, "123")
  349. def h(a: Optional[object] = None, b: Optional[str] = None) -> Tuple[object, Optional[str]]:
  350. return (a, b)
  351. def same(x: object = object()) -> object:
  352. return x
  353. a_lambda: Callable[..., Any] = lambda n=20: n
  354. def nested_funcs(n: int) -> List[Callable[..., Any]]:
  355. ls: List[Callable[..., Any]] = []
  356. for i in range(n):
  357. def f(i: int = i) -> int:
  358. return i
  359. ls.append(f)
  360. return ls
  361. def bool_default(x: bool = False, y: bool = True) -> str:
  362. return str(x) + '-' + str(y)
  363. [file driver.py]
  364. from native import f, g, h, same, nested_funcs, a_lambda, bool_default
  365. g()
  366. assert f(2) == (5, "test")
  367. assert f(s = "123", x = -2) == (1, "123")
  368. assert h() == (None, None)
  369. assert h(10) == (10, None)
  370. assert h(b='a') == (None, 'a')
  371. assert h(10, 'a') == (10, 'a')
  372. assert same() == same()
  373. assert [f() for f in nested_funcs(10)] == list(range(10))
  374. assert a_lambda(10) == 10
  375. assert a_lambda() == 20
  376. assert bool_default() == 'False-True'
  377. assert bool_default(True) == 'True-True'
  378. assert bool_default(True, False) == 'True-False'
  379. [case testMethodCallWithDefaultArgs]
  380. from typing import Tuple, List
  381. class A:
  382. def f(self, x: int, y: int = 3, s: str = "test") -> Tuple[int, str]:
  383. def inner() -> int:
  384. return x + y
  385. return inner(), s
  386. def g() -> None:
  387. a = A()
  388. assert a.f(2) == (5, "test")
  389. assert a.f(s = "123", x = -2) == (1, "123")
  390. [file driver.py]
  391. from native import A, g
  392. g()
  393. a = A()
  394. assert a.f(2) == (5, "test")
  395. assert a.f(s = "123", x = -2) == (1, "123")
  396. [case testMethodCallOrdering]
  397. class A:
  398. def __init__(self, s: str) -> None:
  399. print(s)
  400. def f(self, x: 'A', y: 'A') -> None:
  401. pass
  402. def g() -> None:
  403. A('A!').f(A('hello'), A('world'))
  404. [file driver.py]
  405. from native import g
  406. g()
  407. [out]
  408. A!
  409. hello
  410. world
  411. [case testPyMethodCall]
  412. from typing import List
  413. def f(x: List[int]) -> int:
  414. return x.pop()
  415. def g(x: List[int], y: List[int]) -> None:
  416. x.extend(y)
  417. [file driver.py]
  418. from native import f, g
  419. l = [1, 2]
  420. assert f(l) == 2
  421. g(l, [10])
  422. assert l == [1, 10]
  423. assert f(l) == 10
  424. assert f(l) == 1
  425. g(l, [11, 12])
  426. assert l == [11, 12]
  427. [case testMethodCallWithKeywordArgs]
  428. from typing import Tuple
  429. import testmodule
  430. class A:
  431. def echo(self, a: int, b: int, c: int) -> Tuple[int, int, int]:
  432. return a, b, c
  433. def test_native_method_call_with_kwargs() -> None:
  434. a = A()
  435. assert a.echo(1, c=3, b=2) == (1, 2, 3)
  436. assert a.echo(c = 3, a = 1, b = 2) == (1, 2, 3)
  437. def test_module_method_call_with_kwargs() -> None:
  438. a = testmodule.A()
  439. assert a.echo(1, c=3, b=2) == (1, 2, 3)
  440. assert a.echo(c = 3, a = 1, b = 2) == (1, 2, 3)
  441. [file testmodule.py]
  442. from typing import Tuple
  443. class A:
  444. def echo(self, a: int, b: int, c: int) -> Tuple[int, int, int]:
  445. return a, b, c
  446. [file driver.py]
  447. import native
  448. native.test_native_method_call_with_kwargs()
  449. native.test_module_method_call_with_kwargs()
  450. [case testAnyCall]
  451. from typing import Any
  452. def call(f: Any) -> Any:
  453. return f(1, 'x')
  454. [file driver.py]
  455. from native import call
  456. def f(x, y):
  457. return (x, y)
  458. def g(x): pass
  459. assert call(f) == (1, 'x')
  460. for bad in g, 1:
  461. try:
  462. call(bad)
  463. except TypeError:
  464. pass
  465. else:
  466. assert False, bad
  467. [case testCallableTypes]
  468. from typing import Callable
  469. def absolute_value(x: int) -> int:
  470. return x if x > 0 else -x
  471. def call_native_function(x: int) -> int:
  472. return absolute_value(x)
  473. def call_python_function(x: int) -> int:
  474. return int(x)
  475. def return_float() -> float:
  476. return 5.0
  477. def return_callable_type() -> Callable[[], float]:
  478. return return_float
  479. def call_callable_type() -> float:
  480. f = return_callable_type()
  481. return f()
  482. def return_passed_in_callable_type(f: Callable[[], float]) -> Callable[[], float]:
  483. return f
  484. def call_passed_in_callable_type(f: Callable[[], float]) -> float:
  485. return f()
  486. [file driver.py]
  487. from native import call_native_function, call_python_function, return_float, return_callable_type, call_callable_type, return_passed_in_callable_type, call_passed_in_callable_type
  488. a = call_native_function(1)
  489. b = call_python_function(1)
  490. c = return_callable_type()
  491. d = call_callable_type()
  492. e = return_passed_in_callable_type(return_float)
  493. f = call_passed_in_callable_type(return_float)
  494. assert a == 1
  495. assert b == 1
  496. assert c() == 5.0
  497. assert d == 5.0
  498. assert e() == 5.0
  499. assert f == 5.0
  500. [case testKeywordArgs]
  501. from typing import Tuple
  502. import testmodule
  503. def g(a: int, b: int, c: int) -> Tuple[int, int, int]:
  504. return a, b, c
  505. def test_call_native_function_with_keyword_args() -> None:
  506. assert g(1, c = 3, b = 2) == (1, 2, 3)
  507. assert g(c = 3, a = 1, b = 2) == (1, 2, 3)
  508. def test_call_module_function_with_keyword_args() -> None:
  509. assert testmodule.g(1, c = 3, b = 2) == (1, 2, 3)
  510. assert testmodule.g(c = 3, a = 1, b = 2) == (1, 2, 3)
  511. def test_call_python_function_with_keyword_args() -> None:
  512. assert int("11", base=2) == 3
  513. def test_call_lambda_function_with_keyword_args() -> None:
  514. g = testmodule.get_lambda_function()
  515. assert g(1, c = 3, b = 2) == (1, 2, 3)
  516. assert g(c = 3, a = 1, b = 2) == (1, 2, 3)
  517. [file testmodule.py]
  518. from typing import Tuple
  519. def g(a: int, b: int, c: int) -> Tuple[int, int, int]:
  520. return a, b, c
  521. def get_lambda_function():
  522. return (lambda a, b, c: (a, b, c))
  523. [file driver.py]
  524. import native
  525. native.test_call_native_function_with_keyword_args()
  526. native.test_call_module_function_with_keyword_args()
  527. native.test_call_python_function_with_keyword_args()
  528. native.test_call_lambda_function_with_keyword_args()
  529. [case testStarArgs]
  530. from typing import Tuple
  531. def g(a: int, b: int, c: int) -> Tuple[int, int, int]:
  532. return a, b, c
  533. def test_star_args() -> None:
  534. assert g(*[1, 2, 3]) == (1, 2, 3)
  535. assert g(*(1, 2, 3)) == (1, 2, 3)
  536. assert g(*(1,), *[2, 3]) == (1, 2, 3)
  537. assert g(*(), *(1,), *(), *(2,), *(3,), *()) == (1, 2, 3)
  538. assert g(*range(3)) == (0, 1, 2)
  539. [file driver.py]
  540. import native
  541. native.test_star_args()
  542. [case testStar2Args]
  543. from typing import Tuple
  544. def g(a: int, b: int, c: int) -> Tuple[int, int, int]:
  545. return a, b, c
  546. def test_star2_args() -> None:
  547. assert g(**{'a': 1, 'b': 2, 'c': 3}) == (1, 2, 3)
  548. assert g(**{'c': 3, 'a': 1, 'b': 2}) == (1, 2, 3)
  549. assert g(b=2, **{'a': 1, 'c': 3}) == (1, 2, 3)
  550. def test_star2_args_bad(v: dict) -> bool:
  551. return g(a=1, b=2, **v) == (1, 2, 3)
  552. [file driver.py]
  553. import native
  554. native.test_star2_args()
  555. # this should raise TypeError due to duplicate kwarg, but currently it doesn't
  556. assert native.test_star2_args_bad({'b': 2, 'c': 3})
  557. [case testStarAndStar2Args]
  558. from typing import Tuple
  559. def g(a: int, b: int, c: int) -> Tuple[int, int, int]:
  560. return a, b, c
  561. class C:
  562. def g(self, a: int, b: int, c: int) -> Tuple[int, int, int]:
  563. return a, b, c
  564. def test_star_and_star2_args() -> None:
  565. assert g(1, *(2,), **{'c': 3}) == (1, 2, 3)
  566. assert g(*[1], **{'b': 2, 'c': 3}) == (1, 2, 3)
  567. c = C()
  568. assert c.g(1, *(2,), **{'c': 3}) == (1, 2, 3)
  569. assert c.g(*[1], **{'b': 2, 'c': 3}) == (1, 2, 3)
  570. [file driver.py]
  571. import native
  572. native.test_star_and_star2_args()
  573. [case testAllTheArgCombinations]
  574. from typing import Tuple
  575. def g(a: int, b: int, c: int, d: int = -1) -> Tuple[int, int, int, int]:
  576. return a, b, c, d
  577. class C:
  578. def g(self, a: int, b: int, c: int, d: int = -1) -> Tuple[int, int, int, int]:
  579. return a, b, c, d
  580. def test_all_the_arg_combinations() -> None:
  581. assert g(1, *(2,), **{'c': 3}) == (1, 2, 3, -1)
  582. assert g(*[1], **{'b': 2, 'c': 3, 'd': 4}) == (1, 2, 3, 4)
  583. c = C()
  584. assert c.g(1, *(2,), **{'c': 3}) == (1, 2, 3, -1)
  585. assert c.g(*[1], **{'b': 2, 'c': 3, 'd': 4}) == (1, 2, 3, 4)
  586. [file driver.py]
  587. import native
  588. native.test_all_the_arg_combinations()
  589. [case testOverloads]
  590. from typing import overload, Union, Tuple
  591. @overload
  592. def foo(x: int) -> int: ...
  593. @overload
  594. def foo(x: str) -> str: ...
  595. def foo(x: Union[int, str]) -> Union[int, str]:
  596. return x
  597. class A:
  598. @overload
  599. def foo(self, x: int) -> int: ...
  600. @overload
  601. def foo(self, x: str) -> str: ...
  602. def foo(self, x: Union[int, str]) -> Union[int, str]:
  603. return x
  604. def call1() -> Tuple[int, str]:
  605. return (foo(10), foo('10'))
  606. def call2() -> Tuple[int, str]:
  607. x = A()
  608. return (x.foo(10), x.foo('10'))
  609. [file driver.py]
  610. from native import *
  611. assert call1() == (10, '10')
  612. assert call2() == (10, '10')
  613. [case testDecorators1]
  614. from typing import Generator, Callable, Iterator
  615. from contextlib import contextmanager
  616. def a(f: Callable[[], None]) -> Callable[[], None]:
  617. def g() -> None:
  618. print('Entering')
  619. f()
  620. print('Exited')
  621. return g
  622. def b(f: Callable[[], None]) -> Callable[[], None]:
  623. def g() -> None:
  624. print('***')
  625. f()
  626. print('***')
  627. return g
  628. @contextmanager
  629. def foo() -> Iterator[int]:
  630. try:
  631. print('started')
  632. yield 0
  633. finally:
  634. print('finished')
  635. @contextmanager
  636. def catch() -> Iterator[None]:
  637. try:
  638. print('started')
  639. yield
  640. except IndexError:
  641. print('index')
  642. raise
  643. except Exception:
  644. print('lol')
  645. def thing() -> None:
  646. c()
  647. @a
  648. @b
  649. def c() -> None:
  650. @a
  651. @b
  652. def d() -> None:
  653. print('d')
  654. print('c')
  655. d()
  656. def hm() -> None:
  657. x = [1]
  658. with catch():
  659. x[2]
  660. [file driver.py]
  661. from native import foo, c, thing, hm
  662. with foo() as f:
  663. print('hello')
  664. c()
  665. thing()
  666. print('==')
  667. try:
  668. hm()
  669. except IndexError:
  670. pass
  671. else:
  672. assert False
  673. [out]
  674. started
  675. hello
  676. finished
  677. Entering
  678. ***
  679. c
  680. Entering
  681. ***
  682. d
  683. ***
  684. Exited
  685. ***
  686. Exited
  687. Entering
  688. ***
  689. c
  690. Entering
  691. ***
  692. d
  693. ***
  694. Exited
  695. ***
  696. Exited
  697. ==
  698. started
  699. index
  700. [case testDecoratorsMethods]
  701. from typing import Any, Callable, Iterator, TypeVar
  702. from contextlib import contextmanager
  703. T = TypeVar('T')
  704. def dec(f: T) -> T:
  705. return f
  706. def a(f: Callable[[Any], None]) -> Callable[[Any], None]:
  707. def g(a: Any) -> None:
  708. print('Entering')
  709. f(a)
  710. print('Exited')
  711. return g
  712. class A:
  713. @a
  714. def foo(self) -> None:
  715. print('foo')
  716. @contextmanager
  717. def generator(self) -> Iterator[int]:
  718. try:
  719. print('contextmanager: entering')
  720. yield 0
  721. finally:
  722. print('contextmanager: exited')
  723. class Lol:
  724. @staticmethod
  725. def foo() -> None:
  726. Lol.bar()
  727. Lol.baz()
  728. @staticmethod
  729. @dec
  730. def bar() -> None:
  731. pass
  732. @classmethod
  733. @dec
  734. def baz(cls) -> None:
  735. pass
  736. def inside() -> None:
  737. with A().generator() as g:
  738. print('hello!')
  739. with A().generator() as g:
  740. print('hello!')
  741. def lol() -> None:
  742. with A().generator() as g:
  743. raise Exception
  744. [file driver.py]
  745. from native import A, lol
  746. A.foo(A())
  747. A().foo()
  748. with A().generator() as g:
  749. print('hello!')
  750. try:
  751. lol()
  752. except:
  753. pass
  754. else:
  755. assert False
  756. [out]
  757. contextmanager: entering
  758. hello!
  759. contextmanager: exited
  760. Entering
  761. foo
  762. Exited
  763. Entering
  764. foo
  765. Exited
  766. contextmanager: entering
  767. hello!
  768. contextmanager: exited
  769. contextmanager: entering
  770. contextmanager: exited
  771. [case testUnannotatedFunction]
  772. def g(x: int) -> int:
  773. return x * 2
  774. def f(x):
  775. return g(x)
  776. [file driver.py]
  777. from native import f
  778. assert f(3) == 6
  779. [case testUnannotatedModuleLevelInitFunction]
  780. # Ensure that adding an implicit `-> None` annotation only applies to `__init__`
  781. # _methods_ specifically (not module-level `__init__` functions).
  782. def __init__():
  783. return 42
  784. [file driver.py]
  785. from native import __init__
  786. assert __init__() == 42
  787. [case testDifferentArgCountsFromInterpreted]
  788. # Test various signatures from interpreted code.
  789. def noargs() -> int:
  790. return 5
  791. def onearg(x: int) -> int:
  792. return x + 1
  793. def twoargs(x: int, y: str) -> int:
  794. return x + len(y)
  795. def one_or_two(x: int, y: str = 'a') -> int:
  796. return x + len(y)
  797. [file driver.py]
  798. from native import noargs, onearg, twoargs, one_or_two
  799. from testutil import assertRaises
  800. assert noargs() == 5
  801. t = ()
  802. assert noargs(*t) == 5
  803. d = {}
  804. assert noargs(**d) == 5
  805. assert noargs(*t, **d) == 5
  806. assert onearg(12) == 13
  807. assert onearg(x=8) == 9
  808. t = (1,)
  809. assert onearg(*t) == 2
  810. d = {'x': 5}
  811. assert onearg(**d) == 6
  812. # Test a bogus call to twoargs before any correct calls are made
  813. with assertRaises(TypeError, "twoargs() missing required argument 'x' (pos 1)"):
  814. twoargs()
  815. assert twoargs(5, 'foo') == 8
  816. assert twoargs(4, y='foo') == 7
  817. assert twoargs(y='foo', x=7) == 10
  818. t = (1, 'xy')
  819. assert twoargs(*t) == 3
  820. d = {'y': 'xy'}
  821. assert twoargs(2, **d) == 4
  822. assert one_or_two(5) == 6
  823. assert one_or_two(x=3) == 4
  824. assert one_or_two(6, 'xy') == 8
  825. assert one_or_two(7, y='xy') == 9
  826. assert one_or_two(y='xy', x=2) == 4
  827. assert one_or_two(*t) == 3
  828. d = {'x': 5}
  829. assert one_or_two(**d) == 6
  830. assert one_or_two(y='xx', **d) == 7
  831. d = {'y': 'abc'}
  832. assert one_or_two(1, **d) == 4
  833. with assertRaises(TypeError, 'noargs() takes at most 0 arguments (1 given)'):
  834. noargs(1)
  835. with assertRaises(TypeError, 'noargs() takes at most 0 keyword arguments (1 given)'):
  836. noargs(x=1)
  837. with assertRaises(TypeError, "onearg() missing required argument 'x' (pos 1)"):
  838. onearg()
  839. with assertRaises(TypeError, 'onearg() takes at most 1 argument (2 given)'):
  840. onearg(1, 2)
  841. with assertRaises(TypeError, "onearg() missing required argument 'x' (pos 1)"):
  842. onearg(y=1)
  843. with assertRaises(TypeError, "onearg() takes at most 1 argument (2 given)"):
  844. onearg(1, y=1)
  845. with assertRaises(TypeError, "twoargs() missing required argument 'x' (pos 1)"):
  846. twoargs()
  847. with assertRaises(TypeError, "twoargs() missing required argument 'y' (pos 2)"):
  848. twoargs(1)
  849. with assertRaises(TypeError, 'twoargs() takes at most 2 arguments (3 given)'):
  850. twoargs(1, 'x', 2)
  851. with assertRaises(TypeError, 'twoargs() takes at most 2 arguments (3 given)'):
  852. twoargs(1, 'x', y=2)
  853. with assertRaises(TypeError, "one_or_two() missing required argument 'x' (pos 1)"):
  854. one_or_two()
  855. with assertRaises(TypeError, 'one_or_two() takes at most 2 arguments (3 given)'):
  856. one_or_two(1, 'x', 2)
  857. with assertRaises(TypeError, 'one_or_two() takes at most 2 arguments (3 given)'):
  858. one_or_two(1, 'x', y=2)
  859. [case testComplicatedArgs]
  860. from typing import Tuple, Dict
  861. def kwonly1(x: int = 0, *, y: int) -> Tuple[int, int]:
  862. return x, y
  863. def kwonly2(*, x: int = 0, y: int) -> Tuple[int, int]:
  864. return x, y
  865. def kwonly3(a: int, b: int = 0, *, y: int, x: int = 1) -> Tuple[int, int, int, int]:
  866. return a, b, x, y
  867. def kwonly4(*, x: int, y: int) -> Tuple[int, int]:
  868. return x, y
  869. def varargs1(*args: int) -> Tuple[int, ...]:
  870. return args
  871. def varargs2(*args: int, **kwargs: int) -> Tuple[Tuple[int, ...], Dict[str, int]]:
  872. return args, kwargs
  873. def varargs3(**kwargs: int) -> Dict[str, int]:
  874. return kwargs
  875. def varargs4(a: int, b: int = 0,
  876. *args: int, y: int, x: int = 1,
  877. **kwargs: int) -> Tuple[Tuple[int, ...], Dict[str, int]]:
  878. return (a, b, *args), {'x': x, 'y': y, **kwargs}
  879. class A:
  880. def f(self, x: int) -> Tuple[int, ...]:
  881. return (x,)
  882. def g(self, x: int) -> Tuple[Tuple[int, ...], Dict[str, int]]:
  883. return (x,), {}
  884. class B(A):
  885. def f(self, *args: int) -> Tuple[int, ...]:
  886. return args
  887. def g(self, *args: int, **kwargs: int) -> Tuple[Tuple[int, ...], Dict[str, int]]:
  888. return args, kwargs
  889. [file other.py]
  890. # This file is imported in both compiled and interpreted mode in order to
  891. # test both native calls and calls via the C API.
  892. from native import (
  893. kwonly1, kwonly2, kwonly3, kwonly4,
  894. varargs1, varargs2, varargs3, varargs4,
  895. A, B
  896. )
  897. # kwonly arg tests
  898. assert kwonly1(10, y=20) == (10, 20)
  899. assert kwonly1(y=20) == (0, 20)
  900. assert kwonly2(x=10, y=20) == (10, 20)
  901. assert kwonly2(y=20) == (0, 20)
  902. assert kwonly3(10, y=20) == (10, 0, 1, 20)
  903. assert kwonly3(a=10, y=20) == (10, 0, 1, 20)
  904. assert kwonly3(10, 30, y=20) == (10, 30, 1, 20)
  905. assert kwonly3(10, b=30, y=20) == (10, 30, 1, 20)
  906. assert kwonly3(a=10, b=30, y=20) == (10, 30, 1, 20)
  907. assert kwonly3(10, x=40, y=20) == (10, 0, 40, 20)
  908. assert kwonly3(a=10, x=40, y=20) == (10, 0, 40, 20)
  909. assert kwonly3(10, 30, x=40, y=20) == (10, 30, 40, 20)
  910. assert kwonly3(10, b=30, x=40, y=20) == (10, 30, 40, 20)
  911. assert kwonly3(a=10, b=30, x=40, y=20) == (10, 30, 40, 20)
  912. assert kwonly4(x=1, y=2) == (1, 2)
  913. assert kwonly4(y=2, x=1) == (1, 2)
  914. # varargs tests
  915. assert varargs1() == ()
  916. assert varargs1(1, 2, 3) == (1, 2, 3)
  917. assert varargs1(1, *[2, 3, 4], 5, *[6, 7, 8], 9) == (1, 2, 3, 4, 5, 6, 7, 8, 9)
  918. assert varargs2(1, 2, 3) == ((1, 2, 3), {})
  919. assert varargs2(1, 2, 3, x=4) == ((1, 2, 3), {'x': 4})
  920. assert varargs2(x=4) == ((), {'x': 4})
  921. assert varargs3() == {}
  922. assert varargs3(x=4) == {'x': 4}
  923. assert varargs3(x=4, y=5) == {'x': 4, 'y': 5}
  924. assert varargs4(-1, y=2) == ((-1, 0), {'x': 1, 'y': 2})
  925. assert varargs4(-1, 2, y=2) == ((-1, 2), {'x': 1, 'y': 2})
  926. assert varargs4(-1, 2, 3, y=2) == ((-1, 2, 3), {'x': 1, 'y': 2})
  927. assert varargs4(-1, 2, 3, x=10, y=2) == ((-1, 2, 3), {'x': 10, 'y': 2})
  928. assert varargs4(-1, x=10, y=2) == ((-1, 0), {'x': 10, 'y': 2})
  929. assert varargs4(-1, y=2, z=20) == ((-1, 0), {'x': 1, 'y': 2, 'z': 20})
  930. assert varargs4(-1, 2, y=2, z=20) == ((-1, 2), {'x': 1, 'y': 2, 'z': 20})
  931. assert varargs4(-1, 2, 3, y=2, z=20) == ((-1, 2, 3), {'x': 1, 'y': 2, 'z': 20})
  932. assert varargs4(-1, 2, 3, x=10, y=2, z=20) == ((-1, 2, 3), {'x': 10, 'y': 2, 'z': 20})
  933. assert varargs4(-1, x=10, y=2, z=20) == ((-1, 0), {'x': 10, 'y': 2, 'z': 20})
  934. x = B() # type: A
  935. assert x.f(1) == (1,)
  936. assert x.g(1) == ((1,), {})
  937. # This one is really funny! When we make native calls we lose
  938. # track of which arguments are positional or keyword, so the glue
  939. # calls them all positional unless they are keyword only...
  940. # It would be possible to fix this by dynamically tracking which
  941. # arguments were passed by keyword (for example, by passing a bitmask
  942. # to functions indicating this), but paying a speed, size, and complexity
  943. # cost for something so deeply marginal seems like a bad choice.
  944. # assert x.g(x=1) == ((), {'x': 1})
  945. [file driver.py]
  946. from testutil import assertRaises
  947. from native import (
  948. kwonly1, kwonly2, kwonly3, kwonly4,
  949. varargs1, varargs2, varargs3, varargs4,
  950. )
  951. # Run the non-exceptional tests in both interpreted and compiled mode
  952. import other
  953. import other_interpreted
  954. # And the tests for errors at the interfaces in interpreted only
  955. with assertRaises(TypeError, "missing required keyword-only argument 'y'"):
  956. kwonly1()
  957. with assertRaises(TypeError, "takes at most 1 positional argument (2 given)"):
  958. kwonly1(10, 20)
  959. with assertRaises(TypeError, "missing required keyword-only argument 'y'"):
  960. kwonly2()
  961. with assertRaises(TypeError, "takes no positional arguments"):
  962. kwonly2(10, 20)
  963. with assertRaises(TypeError, "missing required argument 'a'"):
  964. kwonly3(b=30, x=40, y=20)
  965. with assertRaises(TypeError, "missing required keyword-only argument 'y'"):
  966. kwonly3(10)
  967. with assertRaises(TypeError, "missing required keyword-only argument 'y'"):
  968. kwonly4(x=1)
  969. with assertRaises(TypeError, "missing required keyword-only argument 'x'"):
  970. kwonly4(y=1)
  971. with assertRaises(TypeError, "missing required keyword-only argument 'x'"):
  972. kwonly4()
  973. with assertRaises(TypeError, "'x' is an invalid keyword argument for varargs1()"):
  974. varargs1(x=10)
  975. with assertRaises(TypeError, "'x' is an invalid keyword argument for varargs1()"):
  976. varargs1(1, x=10)
  977. with assertRaises(TypeError, "varargs3() takes no positional arguments"):
  978. varargs3(10)
  979. with assertRaises(TypeError, "varargs3() takes no positional arguments"):
  980. varargs3(10, x=10)
  981. with assertRaises(TypeError, "varargs4() missing required argument 'a' (pos 1)"):
  982. varargs4()
  983. with assertRaises(TypeError, "varargs4() missing required keyword-only argument 'y'"):
  984. varargs4(1, 2)
  985. with assertRaises(TypeError, "varargs4() missing required keyword-only argument 'y'"):
  986. varargs4(1, 2, x=1)
  987. with assertRaises(TypeError, "varargs4() missing required keyword-only argument 'y'"):
  988. varargs4(1, 2, 3)
  989. with assertRaises(TypeError, "varargs4() missing required argument 'a' (pos 1)"):
  990. varargs4(y=20)
  991. [case testDecoratorName]
  992. def dec(f): return f
  993. @dec
  994. def foo(): pass
  995. def test_decorator_name():
  996. assert foo.__name__ == "foo"
  997. [case testLambdaArgToOverloaded]
  998. from lib import sub
  999. def test_str_overload() -> None:
  1000. assert sub('x', lambda m: m) == 'x'
  1001. def test_bytes_overload() -> None:
  1002. assert sub(b'x', lambda m: m) == b'x'
  1003. [file lib.py]
  1004. from typing import overload, Callable, TypeVar, Generic
  1005. T = TypeVar("T")
  1006. class Match(Generic[T]):
  1007. def __init__(self, x: T) -> None:
  1008. self.x = x
  1009. def group(self, n: int) -> T:
  1010. return self.x
  1011. @overload
  1012. def sub(s: str, f: Callable[[str], str]) -> str: ...
  1013. @overload
  1014. def sub(s: bytes, f: Callable[[bytes], bytes]) -> bytes: ...
  1015. def sub(s, f):
  1016. return f(s)
  1017. [case testContextManagerSpecialCase]
  1018. from typing import Generator, Callable, Iterator
  1019. from contextlib import contextmanager
  1020. @contextmanager
  1021. def f() -> Iterator[None]:
  1022. yield
  1023. def g() -> None:
  1024. a = ['']
  1025. with f():
  1026. a.pop()
  1027. g()
  1028. [case testUnpackKwargsCompiled]
  1029. from typing_extensions import Unpack, TypedDict
  1030. class Person(TypedDict):
  1031. name: str
  1032. age: int
  1033. def foo(**kwargs: Unpack[Person]) -> None:
  1034. print(kwargs["name"])
  1035. # This is not really supported yet, just test that we behave reasonably.
  1036. foo(name='Jennifer', age=38)
  1037. [out]
  1038. Jennifer