PageRenderTime 67ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/rpython/annotator/test/test_annrpython.py

https://bitbucket.org/pypy/pypy/
Python | 4652 lines | 4237 code | 333 blank | 82 comment | 134 complexity | 110d1c09fbd137bc641194cbba8997c5 MD5 | raw file
Possible License(s): AGPL-3.0, BSD-3-Clause, Apache-2.0

Large files files are truncated, but you can click here to view the full file

  1. from __future__ import with_statement
  2. import py.test
  3. import sys
  4. from collections import OrderedDict
  5. from rpython.conftest import option
  6. from rpython.annotator import model as annmodel
  7. from rpython.annotator.model import AnnotatorError, UnionError
  8. from rpython.annotator.annrpython import RPythonAnnotator as _RPythonAnnotator
  9. from rpython.annotator.classdesc import NoSuchAttrError
  10. from rpython.translator.translator import graphof as tgraphof
  11. from rpython.annotator.policy import AnnotatorPolicy
  12. from rpython.annotator.signature import Sig, SignatureError
  13. from rpython.annotator.listdef import ListDef, ListChangeUnallowed
  14. from rpython.annotator.dictdef import DictDef
  15. from rpython.flowspace.model import *
  16. from rpython.rlib.rarithmetic import r_uint, base_int, r_longlong, r_ulonglong
  17. from rpython.rlib.rarithmetic import r_singlefloat
  18. from rpython.rlib import objectmodel
  19. from rpython.flowspace.flowcontext import FlowingError
  20. from rpython.flowspace.operation import op
  21. from rpython.translator.test import snippet
  22. def graphof(a, func):
  23. return tgraphof(a.translator, func)
  24. def listitem(s_list):
  25. assert isinstance(s_list, annmodel.SomeList)
  26. return s_list.listdef.listitem.s_value
  27. def somelist(s_type):
  28. return annmodel.SomeList(ListDef(None, s_type))
  29. def dictkey(s_dict):
  30. assert isinstance(s_dict, annmodel.SomeDict)
  31. return s_dict.dictdef.dictkey.s_value
  32. def dictvalue(s_dict):
  33. assert isinstance(s_dict, annmodel.SomeDict)
  34. return s_dict.dictdef.dictvalue.s_value
  35. def somedict(annotator, s_key, s_value):
  36. return annmodel.SomeDict(DictDef(annotator.bookkeeper, s_key, s_value))
  37. class TestAnnotateTestCase:
  38. def teardown_method(self, meth):
  39. assert annmodel.s_Bool == annmodel.SomeBool()
  40. class RPythonAnnotator(_RPythonAnnotator):
  41. def build_types(self, *args):
  42. s = _RPythonAnnotator.build_types(self, *args)
  43. self.validate()
  44. if option.view:
  45. self.translator.view()
  46. return s
  47. def test_simple_func(self):
  48. """
  49. one test source:
  50. def f(x):
  51. return x+1
  52. """
  53. x = Variable("x")
  54. oper = op.add(x, Constant(1))
  55. block = Block([x])
  56. fun = FunctionGraph("f", block)
  57. block.operations.append(oper)
  58. block.closeblock(Link([oper.result], fun.returnblock))
  59. a = self.RPythonAnnotator()
  60. a.addpendingblock(fun, fun.startblock, [annmodel.SomeInteger()])
  61. a.complete()
  62. assert a.gettype(fun.getreturnvar()) == int
  63. def test_while(self):
  64. """
  65. one test source:
  66. def f(i):
  67. while i > 0:
  68. i = i - 1
  69. return i
  70. """
  71. i1 = Variable("i1")
  72. i2 = Variable("i2")
  73. conditionop = op.gt(i1, Constant(0))
  74. decop = op.add(i2, Constant(-1))
  75. headerblock = Block([i1])
  76. whileblock = Block([i2])
  77. fun = FunctionGraph("f", headerblock)
  78. headerblock.operations.append(conditionop)
  79. headerblock.exitswitch = conditionop.result
  80. headerblock.closeblock(Link([i1], fun.returnblock, False),
  81. Link([i1], whileblock, True))
  82. whileblock.operations.append(decop)
  83. whileblock.closeblock(Link([decop.result], headerblock))
  84. a = self.RPythonAnnotator()
  85. a.addpendingblock(fun, fun.startblock, [annmodel.SomeInteger()])
  86. a.complete()
  87. assert a.gettype(fun.getreturnvar()) == int
  88. def test_while_sum(self):
  89. """
  90. one test source:
  91. def f(i):
  92. sum = 0
  93. while i > 0:
  94. sum = sum + i
  95. i = i - 1
  96. return sum
  97. """
  98. i1 = Variable("i1")
  99. i2 = Variable("i2")
  100. i3 = Variable("i3")
  101. sum2 = Variable("sum2")
  102. sum3 = Variable("sum3")
  103. conditionop = op.gt(i2, Constant(0))
  104. decop = op.add(i3, Constant(-1))
  105. addop = op.add(i3, sum3)
  106. startblock = Block([i1])
  107. headerblock = Block([i2, sum2])
  108. whileblock = Block([i3, sum3])
  109. fun = FunctionGraph("f", startblock)
  110. startblock.closeblock(Link([i1, Constant(0)], headerblock))
  111. headerblock.operations.append(conditionop)
  112. headerblock.exitswitch = conditionop.result
  113. headerblock.closeblock(Link([sum2], fun.returnblock, False),
  114. Link([i2, sum2], whileblock, True))
  115. whileblock.operations.append(addop)
  116. whileblock.operations.append(decop)
  117. whileblock.closeblock(Link([decop.result, addop.result], headerblock))
  118. a = self.RPythonAnnotator()
  119. a.addpendingblock(fun, fun.startblock, [annmodel.SomeInteger()])
  120. a.complete()
  121. assert a.gettype(fun.getreturnvar()) == int
  122. def test_f_calls_g(self):
  123. a = self.RPythonAnnotator()
  124. s = a.build_types(f_calls_g, [int])
  125. # result should be an integer
  126. assert s.knowntype == int
  127. def test_lists(self):
  128. a = self.RPythonAnnotator()
  129. end_cell = a.build_types(snippet.poor_man_rev_range, [int])
  130. # result should be a list of integers
  131. assert listitem(end_cell).knowntype == int
  132. def test_factorial(self):
  133. a = self.RPythonAnnotator()
  134. s = a.build_types(snippet.factorial, [int])
  135. # result should be an integer
  136. assert s.knowntype == int
  137. def test_factorial2(self):
  138. a = self.RPythonAnnotator()
  139. s = a.build_types(snippet.factorial2, [int])
  140. # result should be an integer
  141. assert s.knowntype == int
  142. def test_build_instance(self):
  143. a = self.RPythonAnnotator()
  144. s = a.build_types(snippet.build_instance, [])
  145. # result should be a snippet.C instance
  146. assert isinstance(s, annmodel.SomeInstance)
  147. assert s.classdef == a.bookkeeper.getuniqueclassdef(snippet.C)
  148. def test_set_attr(self):
  149. a = self.RPythonAnnotator()
  150. s = a.build_types(snippet.set_attr, [])
  151. # result should be an integer
  152. assert s.knowntype == int
  153. def test_merge_setattr(self):
  154. a = self.RPythonAnnotator()
  155. s = a.build_types(snippet.merge_setattr, [int])
  156. # result should be an integer
  157. assert s.knowntype == int
  158. def test_inheritance1(self):
  159. a = self.RPythonAnnotator()
  160. s = a.build_types(snippet.inheritance1, [])
  161. # result should be exactly:
  162. assert s == annmodel.SomeTuple([
  163. a.bookkeeper.immutablevalue(()),
  164. annmodel.SomeInteger()
  165. ])
  166. def test_poor_man_range(self):
  167. a = self.RPythonAnnotator()
  168. s = a.build_types(snippet.poor_man_range, [int])
  169. # result should be a list of integers
  170. assert listitem(s).knowntype == int
  171. def test_staticmethod(self):
  172. class X(object):
  173. @staticmethod
  174. def stat(value):
  175. return value + 4
  176. def f(v):
  177. return X().stat(v)
  178. a = self.RPythonAnnotator()
  179. s = a.build_types(f, [int])
  180. assert isinstance(s, annmodel.SomeInteger)
  181. def test_classmethod(self):
  182. class X(object):
  183. @classmethod
  184. def meth(cls):
  185. return None
  186. def f():
  187. return X().meth()
  188. a = self.RPythonAnnotator()
  189. py.test.raises(AnnotatorError, a.build_types, f, [])
  190. def test_methodcall1(self):
  191. a = self.RPythonAnnotator()
  192. s = a.build_types(snippet._methodcall1, [int])
  193. # result should be a tuple of (C, positive_int)
  194. assert s.knowntype == tuple
  195. assert len(s.items) == 2
  196. s0 = s.items[0]
  197. assert isinstance(s0, annmodel.SomeInstance)
  198. assert s0.classdef == a.bookkeeper.getuniqueclassdef(snippet.C)
  199. assert s.items[1].knowntype == int
  200. assert s.items[1].nonneg == True
  201. def test_classes_methodcall1(self):
  202. a = self.RPythonAnnotator()
  203. a.build_types(snippet._methodcall1, [int])
  204. # the user classes should have the following attributes:
  205. getcdef = a.bookkeeper.getuniqueclassdef
  206. assert getcdef(snippet.F).attrs.keys() == ['m']
  207. assert getcdef(snippet.G).attrs.keys() == ['m2']
  208. assert getcdef(snippet.H).attrs.keys() == ['attr']
  209. assert getcdef(snippet.H).about_attribute('attr') == (
  210. a.bookkeeper.immutablevalue(1))
  211. def test_generaldict(self):
  212. a = self.RPythonAnnotator()
  213. s = a.build_types(snippet.generaldict, [str, int, str, int])
  214. # result should be an integer
  215. assert s.knowntype == int
  216. def test_somebug1(self):
  217. a = self.RPythonAnnotator()
  218. s = a.build_types(snippet._somebug1, [int])
  219. # result should be a built-in method
  220. assert isinstance(s, annmodel.SomeBuiltin)
  221. def test_with_init(self):
  222. a = self.RPythonAnnotator()
  223. s = a.build_types(snippet.with_init, [int])
  224. # result should be an integer
  225. assert s.knowntype == int
  226. def test_with_more_init(self):
  227. a = self.RPythonAnnotator()
  228. s = a.build_types(snippet.with_more_init, [int, bool])
  229. # the user classes should have the following attributes:
  230. getcdef = a.bookkeeper.getuniqueclassdef
  231. # XXX on which class should the attribute 'a' appear? We only
  232. # ever flow WithInit.__init__ with a self which is an instance
  233. # of WithMoreInit, so currently it appears on WithMoreInit.
  234. assert getcdef(snippet.WithMoreInit).about_attribute('a') == (
  235. annmodel.SomeInteger())
  236. assert getcdef(snippet.WithMoreInit).about_attribute('b') == (
  237. annmodel.SomeBool())
  238. def test_global_instance(self):
  239. a = self.RPythonAnnotator()
  240. s = a.build_types(snippet.global_instance, [])
  241. # currently this returns the constant 42.
  242. # XXX not sure this is the best behavior...
  243. assert s == a.bookkeeper.immutablevalue(42)
  244. def test_call_five(self):
  245. a = self.RPythonAnnotator()
  246. s = a.build_types(snippet.call_five, [])
  247. # returns should be a list of constants (= 5)
  248. assert listitem(s) == a.bookkeeper.immutablevalue(5)
  249. def test_call_five_six(self):
  250. a = self.RPythonAnnotator()
  251. s = a.build_types(snippet.call_five_six, [])
  252. # returns should be a list of positive integers
  253. assert listitem(s) == annmodel.SomeInteger(nonneg=True)
  254. def test_constant_result(self):
  255. a = self.RPythonAnnotator()
  256. s = a.build_types(snippet.constant_result, [])
  257. #a.translator.simplify()
  258. # must return "yadda"
  259. assert s == a.bookkeeper.immutablevalue("yadda")
  260. graphs = a.translator.graphs
  261. assert len(graphs) == 2
  262. assert graphs[0].func is snippet.constant_result
  263. assert graphs[1].func is snippet.forty_two
  264. a.simplify()
  265. #a.translator.view()
  266. def test_flow_type_info(self):
  267. a = self.RPythonAnnotator()
  268. s = a.build_types(snippet.flow_type_info, [int])
  269. a.simplify()
  270. assert s.knowntype == int
  271. a = self.RPythonAnnotator()
  272. s = a.build_types(snippet.flow_type_info, [str])
  273. a.simplify()
  274. assert s.knowntype == int
  275. def test_flow_type_info_2(self):
  276. a = self.RPythonAnnotator()
  277. s = a.build_types(snippet.flow_type_info,
  278. [annmodel.SomeInteger(nonneg=True)])
  279. # this checks that isinstance(i, int) didn't lose the
  280. # actually more precise information that i is non-negative
  281. assert s == annmodel.SomeInteger(nonneg=True)
  282. def test_flow_usertype_info(self):
  283. a = self.RPythonAnnotator()
  284. s = a.build_types(snippet.flow_usertype_info, [snippet.WithInit])
  285. #a.translator.view()
  286. assert isinstance(s, annmodel.SomeInstance)
  287. assert s.classdef == a.bookkeeper.getuniqueclassdef(snippet.WithInit)
  288. def test_flow_usertype_info2(self):
  289. a = self.RPythonAnnotator()
  290. s = a.build_types(snippet.flow_usertype_info, [snippet.WithMoreInit])
  291. #a.translator.view()
  292. assert isinstance(s, annmodel.SomeInstance)
  293. assert s.classdef == a.bookkeeper.getuniqueclassdef(snippet.WithMoreInit)
  294. def test_mergefunctions(self):
  295. a = self.RPythonAnnotator()
  296. s = a.build_types(snippet.mergefunctions, [int])
  297. # the test is mostly that the above line hasn't blown up
  298. # but let's at least check *something*
  299. assert isinstance(s, annmodel.SomePBC)
  300. def test_func_calls_func_which_just_raises(self):
  301. a = self.RPythonAnnotator()
  302. s = a.build_types(snippet.funccallsex, [])
  303. # the test is mostly that the above line hasn't blown up
  304. # but let's at least check *something*
  305. #self.assert_(isinstance(s, SomeCallable))
  306. def test_tuple_unpack_from_const_tuple_with_different_types(self):
  307. a = self.RPythonAnnotator()
  308. s = a.build_types(snippet.func_arg_unpack, [])
  309. assert isinstance(s, annmodel.SomeInteger)
  310. assert s.const == 3
  311. def test_star_unpack_list(self):
  312. def g():
  313. pass
  314. def f(l):
  315. return g(*l)
  316. a = self.RPythonAnnotator()
  317. with py.test.raises(AnnotatorError):
  318. a.build_types(f, [[int]])
  319. def test_star_unpack_and_keywords(self):
  320. def g(a, b, c=0, d=0):
  321. return a + b + c + d
  322. def f(a, b):
  323. return g(a, *(b,), d=5)
  324. a = self.RPythonAnnotator()
  325. s_result = a.build_types(f, [int, int])
  326. assert isinstance(s_result, annmodel.SomeInteger)
  327. def test_pbc_attr_preserved_on_instance(self):
  328. a = self.RPythonAnnotator()
  329. s = a.build_types(snippet.preserve_pbc_attr_on_instance, [bool])
  330. #a.simplify()
  331. #a.translator.view()
  332. assert s == annmodel.SomeInteger(nonneg=True)
  333. #self.assertEquals(s.__class__, annmodel.SomeInteger)
  334. def test_pbc_attr_preserved_on_instance_with_slots(self):
  335. a = self.RPythonAnnotator()
  336. s = a.build_types(snippet.preserve_pbc_attr_on_instance_with_slots,
  337. [bool])
  338. assert s == annmodel.SomeInteger(nonneg=True)
  339. def test_is_and_knowntype_data(self):
  340. a = self.RPythonAnnotator()
  341. s = a.build_types(snippet.is_and_knowntype, [str])
  342. #a.simplify()
  343. #a.translator.view()
  344. assert s == a.bookkeeper.immutablevalue(None)
  345. def test_isinstance_and_knowntype_data(self):
  346. a = self.RPythonAnnotator()
  347. x = a.bookkeeper.immutablevalue(snippet.apbc)
  348. s = a.build_types(snippet.isinstance_and_knowntype, [x])
  349. #a.simplify()
  350. #a.translator.view()
  351. assert s == x
  352. def test_somepbc_simplify(self):
  353. a = self.RPythonAnnotator()
  354. # this example used to trigger an AssertionError
  355. a.build_types(snippet.somepbc_simplify, [])
  356. def test_builtin_methods(self):
  357. a = self.RPythonAnnotator()
  358. iv = a.bookkeeper.immutablevalue
  359. # this checks that some built-in methods are really supported by
  360. # the annotator (it doesn't check that they operate property, though)
  361. for example, methname, s_example in [
  362. ('', 'join', annmodel.SomeString()),
  363. ([], 'append', somelist(annmodel.s_Int)),
  364. ([], 'extend', somelist(annmodel.s_Int)),
  365. ([], 'reverse', somelist(annmodel.s_Int)),
  366. ([], 'insert', somelist(annmodel.s_Int)),
  367. ([], 'pop', somelist(annmodel.s_Int)),
  368. ]:
  369. constmeth = getattr(example, methname)
  370. s_constmeth = iv(constmeth)
  371. assert isinstance(s_constmeth, annmodel.SomeBuiltin)
  372. s_meth = s_example.getattr(iv(methname))
  373. assert isinstance(s_constmeth, annmodel.SomeBuiltin)
  374. def test_str_join(self):
  375. a = self.RPythonAnnotator()
  376. def g(n):
  377. if n:
  378. return ["foo", "bar"]
  379. def f(n):
  380. g(0)
  381. return ''.join(g(n))
  382. s = a.build_types(f, [int])
  383. assert s.knowntype == str
  384. assert s.no_nul
  385. def test_unicode_join(self):
  386. a = self.RPythonAnnotator()
  387. def g(n):
  388. if n:
  389. return [u"foo", u"bar"]
  390. def f(n):
  391. g(0)
  392. return u''.join(g(n))
  393. s = a.build_types(f, [int])
  394. assert s.knowntype == unicode
  395. assert s.no_nul
  396. def test_str_split(self):
  397. a = self.RPythonAnnotator()
  398. def g(n):
  399. if n:
  400. return "test string"
  401. def f(n):
  402. if n:
  403. return g(n).split(' ')
  404. s = a.build_types(f, [int])
  405. assert isinstance(s, annmodel.SomeList)
  406. s_item = s.listdef.listitem.s_value
  407. assert s_item.no_nul
  408. def test_unicode_split(self):
  409. a = self.RPythonAnnotator()
  410. def g(n):
  411. if n:
  412. return u"test string"
  413. def f(n):
  414. if n:
  415. return g(n).split(u' ')
  416. s = a.build_types(f, [int])
  417. assert isinstance(s, annmodel.SomeList)
  418. s_item = s.listdef.listitem.s_value
  419. assert s_item.no_nul
  420. def test_str_split_nul(self):
  421. def f(n):
  422. return n.split('\0')[0]
  423. a = self.RPythonAnnotator()
  424. a.translator.config.translation.check_str_without_nul = True
  425. s = a.build_types(f, [annmodel.SomeString(no_nul=False, can_be_None=False)])
  426. assert isinstance(s, annmodel.SomeString)
  427. assert not s.can_be_None
  428. assert s.no_nul
  429. def g(n):
  430. return n.split('\0', 1)[0]
  431. a = self.RPythonAnnotator()
  432. a.translator.config.translation.check_str_without_nul = True
  433. s = a.build_types(g, [annmodel.SomeString(no_nul=False, can_be_None=False)])
  434. assert isinstance(s, annmodel.SomeString)
  435. assert not s.can_be_None
  436. assert not s.no_nul
  437. def test_unicode_split_nul(self):
  438. def f(n):
  439. return n.split(u'\0')[0]
  440. a = self.RPythonAnnotator()
  441. a.translator.config.translation.check_str_without_nul = True
  442. s = a.build_types(f, [annmodel.SomeUnicodeString(
  443. no_nul=False, can_be_None=False)])
  444. assert isinstance(s, annmodel.SomeUnicodeString)
  445. assert not s.can_be_None
  446. assert s.no_nul
  447. def g(n):
  448. return n.split(u'\0', 1)[0]
  449. a = self.RPythonAnnotator()
  450. a.translator.config.translation.check_str_without_nul = True
  451. s = a.build_types(g, [annmodel.SomeUnicodeString(
  452. no_nul=False, can_be_None=False)])
  453. assert isinstance(s, annmodel.SomeUnicodeString)
  454. assert not s.can_be_None
  455. assert not s.no_nul
  456. def test_str_splitlines(self):
  457. a = self.RPythonAnnotator()
  458. def f(a_str):
  459. return a_str.splitlines()
  460. s = a.build_types(f, [str])
  461. assert isinstance(s, annmodel.SomeList)
  462. assert s.listdef.listitem.resized
  463. def test_str_strip(self):
  464. a = self.RPythonAnnotator()
  465. def f(n, a_str):
  466. if n == 0:
  467. return a_str.strip(' ')
  468. elif n == 1:
  469. return a_str.rstrip(' ')
  470. else:
  471. return a_str.lstrip(' ')
  472. s = a.build_types(f, [int, annmodel.SomeString(no_nul=True)])
  473. assert s.no_nul
  474. def test_unicode_strip(self):
  475. a = self.RPythonAnnotator()
  476. def f(n, a_str):
  477. if n == 0:
  478. return a_str.strip(u' ')
  479. elif n == 1:
  480. return a_str.rstrip(u' ')
  481. else:
  482. return a_str.lstrip(u' ')
  483. s = a.build_types(f, [int, annmodel.SomeUnicodeString(no_nul=True)])
  484. assert s.no_nul
  485. def test_str_mul(self):
  486. a = self.RPythonAnnotator()
  487. def f(a_str):
  488. return a_str * 3
  489. s = a.build_types(f, [str])
  490. assert isinstance(s, annmodel.SomeString)
  491. def test_str_isalpha(self):
  492. def f(s):
  493. return s.isalpha()
  494. a = self.RPythonAnnotator()
  495. s = a.build_types(f, [str])
  496. assert isinstance(s, annmodel.SomeBool)
  497. def test_simple_slicing(self):
  498. a = self.RPythonAnnotator()
  499. s = a.build_types(snippet.simple_slice, [somelist(annmodel.s_Int)])
  500. assert isinstance(s, annmodel.SomeList)
  501. def test_simple_iter_list(self):
  502. a = self.RPythonAnnotator()
  503. s = a.build_types(snippet.simple_iter, [somelist(annmodel.s_Int)])
  504. assert isinstance(s, annmodel.SomeIterator)
  505. def test_simple_iter_next(self):
  506. def f(x):
  507. i = iter(range(x))
  508. return i.next()
  509. a = self.RPythonAnnotator()
  510. s = a.build_types(f, [int])
  511. assert isinstance(s, annmodel.SomeInteger)
  512. def test_simple_iter_dict(self):
  513. a = self.RPythonAnnotator()
  514. t = somedict(a, annmodel.SomeInteger(), annmodel.SomeInteger())
  515. s = a.build_types(snippet.simple_iter, [t])
  516. assert isinstance(s, annmodel.SomeIterator)
  517. def test_simple_zip(self):
  518. a = self.RPythonAnnotator()
  519. x = somelist(annmodel.SomeInteger())
  520. y = somelist(annmodel.SomeString())
  521. s = a.build_types(snippet.simple_zip, [x,y])
  522. assert s.knowntype == list
  523. assert listitem(s).knowntype == tuple
  524. assert listitem(s).items[0].knowntype == int
  525. assert listitem(s).items[1].knowntype == str
  526. def test_dict_copy(self):
  527. a = self.RPythonAnnotator()
  528. t = somedict(a, annmodel.SomeInteger(), annmodel.SomeInteger())
  529. s = a.build_types(snippet.dict_copy, [t])
  530. assert isinstance(dictkey(s), annmodel.SomeInteger)
  531. assert isinstance(dictvalue(s), annmodel.SomeInteger)
  532. def test_dict_update(self):
  533. a = self.RPythonAnnotator()
  534. s = a.build_types(snippet.dict_update, [int])
  535. assert isinstance(dictkey(s), annmodel.SomeInteger)
  536. assert isinstance(dictvalue(s), annmodel.SomeInteger)
  537. def test_dict_update_2(self):
  538. a = self.RPythonAnnotator()
  539. def g(n):
  540. if n:
  541. return {3: 4}
  542. def f(n):
  543. g(0)
  544. d = {}
  545. d.update(g(n))
  546. return d
  547. s = a.build_types(f, [int])
  548. assert dictkey(s).knowntype == int
  549. def test_dict_keys(self):
  550. a = self.RPythonAnnotator()
  551. s = a.build_types(snippet.dict_keys, [])
  552. assert isinstance(listitem(s), annmodel.SomeString)
  553. def test_dict_keys2(self):
  554. a = self.RPythonAnnotator()
  555. s = a.build_types(snippet.dict_keys2, [])
  556. assert type(listitem(s)) is annmodel.SomeString
  557. def test_dict_values(self):
  558. a = self.RPythonAnnotator()
  559. s = a.build_types(snippet.dict_values, [])
  560. assert isinstance(listitem(s), annmodel.SomeString)
  561. def test_dict_values2(self):
  562. a = self.RPythonAnnotator()
  563. s = a.build_types(snippet.dict_values2, [])
  564. assert type(listitem(s)) is annmodel.SomeString
  565. def test_dict_items(self):
  566. a = self.RPythonAnnotator()
  567. s = a.build_types(snippet.dict_items, [])
  568. assert isinstance(listitem(s), annmodel.SomeTuple)
  569. s_key, s_value = listitem(s).items
  570. assert isinstance(s_key, annmodel.SomeString)
  571. assert isinstance(s_value, annmodel.SomeInteger)
  572. def test_dict_setdefault(self):
  573. a = self.RPythonAnnotator()
  574. def f():
  575. d = {}
  576. d.setdefault('a', 2)
  577. d.setdefault('a', -3)
  578. return d
  579. s = a.build_types(f, [])
  580. assert isinstance(s, annmodel.SomeDict)
  581. assert isinstance(dictkey(s), annmodel.SomeString)
  582. assert isinstance(dictvalue(s), annmodel.SomeInteger)
  583. assert not dictvalue(s).nonneg
  584. def test_exception_deduction(self):
  585. a = self.RPythonAnnotator()
  586. s = a.build_types(snippet.exception_deduction, [])
  587. assert isinstance(s, annmodel.SomeInstance)
  588. assert s.classdef is a.bookkeeper.getuniqueclassdef(snippet.Exc)
  589. def test_exception_deduction_we_are_dumb(self):
  590. a = self.RPythonAnnotator()
  591. s = a.build_types(snippet.exception_deduction_we_are_dumb, [])
  592. assert isinstance(s, annmodel.SomeInstance)
  593. assert s.classdef is a.bookkeeper.getuniqueclassdef(snippet.Exc)
  594. def test_nested_exception_deduction(self):
  595. a = self.RPythonAnnotator()
  596. s = a.build_types(snippet.nested_exception_deduction, [])
  597. assert isinstance(s, annmodel.SomeTuple)
  598. assert isinstance(s.items[0], annmodel.SomeInstance)
  599. assert isinstance(s.items[1], annmodel.SomeInstance)
  600. assert s.items[0].classdef is a.bookkeeper.getuniqueclassdef(snippet.Exc)
  601. assert s.items[1].classdef is a.bookkeeper.getuniqueclassdef(snippet.Exc2)
  602. def test_exc_deduction_our_exc_plus_others(self):
  603. a = self.RPythonAnnotator()
  604. s = a.build_types(snippet.exc_deduction_our_exc_plus_others, [])
  605. assert isinstance(s, annmodel.SomeInteger)
  606. def test_exc_deduction_our_excs_plus_others(self):
  607. a = self.RPythonAnnotator()
  608. s = a.build_types(snippet.exc_deduction_our_excs_plus_others, [])
  609. assert isinstance(s, annmodel.SomeInteger)
  610. def test_complex_exception_deduction(self):
  611. class InternalError(Exception):
  612. def __init__(self, msg):
  613. self.msg = msg
  614. class AppError(Exception):
  615. def __init__(self, msg):
  616. self.msg = msg
  617. def apperror(msg):
  618. return AppError(msg)
  619. def f(string):
  620. if not string:
  621. raise InternalError('Empty string')
  622. return string, None
  623. def cleanup():
  624. pass
  625. def g(string):
  626. try:
  627. try:
  628. string, _ = f(string)
  629. except ZeroDivisionError:
  630. raise apperror('ZeroDivisionError')
  631. try:
  632. result, _ = f(string)
  633. finally:
  634. cleanup()
  635. except InternalError as e:
  636. raise apperror(e.msg)
  637. return result
  638. a = self.RPythonAnnotator()
  639. s_result = a.build_types(g, [str])
  640. assert isinstance(s_result, annmodel.SomeString)
  641. def test_method_exception_specialization(self):
  642. def f(l):
  643. try:
  644. return l.pop()
  645. except Exception:
  646. raise
  647. a = self.RPythonAnnotator()
  648. s = a.build_types(f, [[int]])
  649. graph = graphof(a, f)
  650. etype, evalue = graph.exceptblock.inputargs
  651. assert evalue.annotation.classdefs == {
  652. a.bookkeeper.getuniqueclassdef(IndexError)}
  653. assert etype.annotation.const == IndexError
  654. def test_operation_always_raising(self):
  655. def operation_always_raising(n):
  656. lst = []
  657. try:
  658. return lst[n]
  659. except IndexError:
  660. return 24
  661. a = self.RPythonAnnotator()
  662. s = a.build_types(operation_always_raising, [int])
  663. assert s == a.bookkeeper.immutablevalue(24)
  664. def test_propagation_of_fresh_instances_through_attrs(self):
  665. a = self.RPythonAnnotator()
  666. s = a.build_types(snippet.propagation_of_fresh_instances_through_attrs, [int])
  667. assert s is not None
  668. def test_propagation_of_fresh_instances_through_attrs_rec_0(self):
  669. a = self.RPythonAnnotator()
  670. s = a.build_types(snippet.make_r, [int])
  671. Rdef = a.bookkeeper.getuniqueclassdef(snippet.R)
  672. assert s.classdef == Rdef
  673. assert Rdef.attrs['r'].s_value.classdef == Rdef
  674. assert Rdef.attrs['n'].s_value.knowntype == int
  675. assert Rdef.attrs['m'].s_value.knowntype == int
  676. def test_propagation_of_fresh_instances_through_attrs_rec_eo(self):
  677. a = self.RPythonAnnotator()
  678. s = a.build_types(snippet.make_eo, [int])
  679. assert s.classdef == a.bookkeeper.getuniqueclassdef(snippet.B)
  680. Even_def = a.bookkeeper.getuniqueclassdef(snippet.Even)
  681. Odd_def = a.bookkeeper.getuniqueclassdef(snippet.Odd)
  682. assert listitem(Even_def.attrs['x'].s_value).classdef == Odd_def
  683. assert listitem(Even_def.attrs['y'].s_value).classdef == Even_def
  684. assert listitem(Odd_def.attrs['x'].s_value).classdef == Even_def
  685. assert listitem(Odd_def.attrs['y'].s_value).classdef == Odd_def
  686. def test_flow_rev_numbers(self):
  687. a = self.RPythonAnnotator()
  688. s = a.build_types(snippet.flow_rev_numbers, [int])
  689. assert s.knowntype == int
  690. assert not s.is_constant() # !
  691. def test_methodcall_is_precise(self):
  692. a = self.RPythonAnnotator()
  693. s = a.build_types(snippet.methodcall_is_precise, [bool])
  694. getcdef = a.bookkeeper.getuniqueclassdef
  695. assert 'x' not in getcdef(snippet.CBase).attrs
  696. assert (getcdef(snippet.CSub1).attrs['x'].s_value ==
  697. a.bookkeeper.immutablevalue(42))
  698. assert (getcdef(snippet.CSub2).attrs['x'].s_value ==
  699. a.bookkeeper.immutablevalue('world'))
  700. assert s == a.bookkeeper.immutablevalue(42)
  701. def test_call_star_args(self):
  702. a = self.RPythonAnnotator(policy=AnnotatorPolicy())
  703. s = a.build_types(snippet.call_star_args, [int])
  704. assert s.knowntype == int
  705. def test_call_star_args_multiple(self):
  706. a = self.RPythonAnnotator(policy=AnnotatorPolicy())
  707. s = a.build_types(snippet.call_star_args_multiple, [int])
  708. assert s.knowntype == int
  709. def test_exception_deduction_with_raise1(self):
  710. a = self.RPythonAnnotator()
  711. s = a.build_types(snippet.exception_deduction_with_raise1, [bool])
  712. assert isinstance(s, annmodel.SomeInstance)
  713. assert s.classdef is a.bookkeeper.getuniqueclassdef(snippet.Exc)
  714. def test_exception_deduction_with_raise2(self):
  715. a = self.RPythonAnnotator()
  716. s = a.build_types(snippet.exception_deduction_with_raise2, [bool])
  717. assert isinstance(s, annmodel.SomeInstance)
  718. assert s.classdef is a.bookkeeper.getuniqueclassdef(snippet.Exc)
  719. def test_exception_deduction_with_raise3(self):
  720. a = self.RPythonAnnotator()
  721. s = a.build_types(snippet.exception_deduction_with_raise3, [bool])
  722. assert isinstance(s, annmodel.SomeInstance)
  723. assert s.classdef is a.bookkeeper.getuniqueclassdef(snippet.Exc)
  724. def test_type_is(self):
  725. class B(object):
  726. pass
  727. class C(B):
  728. pass
  729. def f(x):
  730. assert type(x) is C
  731. return x
  732. a = self.RPythonAnnotator()
  733. s = a.build_types(f, [B])
  734. assert s.classdef is a.bookkeeper.getuniqueclassdef(C)
  735. @py.test.mark.xfail
  736. def test_union_type_some_pbc(self):
  737. class A(object):
  738. name = "A"
  739. def f(self):
  740. return type(self)
  741. class B(A):
  742. name = "B"
  743. def f(tp):
  744. return tp
  745. def main(n):
  746. if n:
  747. if n == 1:
  748. inst = A()
  749. else:
  750. inst = B()
  751. arg = inst.f()
  752. else:
  753. arg = B
  754. return f(arg).name
  755. a = self.RPythonAnnotator()
  756. s = a.build_types(main, [int])
  757. assert isinstance(s, annmodel.SomeString)
  758. def test_ann_assert(self):
  759. def assert_(x):
  760. assert x,"XXX"
  761. a = self.RPythonAnnotator()
  762. s = a.build_types(assert_, [int])
  763. assert s.const is None
  764. def test_string_and_none(self):
  765. def f(n):
  766. if n:
  767. return 'y'
  768. else:
  769. return 'n'
  770. def g(n):
  771. if n:
  772. return 'y'
  773. else:
  774. return None
  775. a = self.RPythonAnnotator()
  776. s = a.build_types(f, [bool])
  777. assert s.knowntype == str
  778. assert not s.can_be_None
  779. s = a.build_types(g, [bool])
  780. assert s.knowntype == str
  781. assert s.can_be_None
  782. def test_implicit_exc(self):
  783. def f(l):
  784. try:
  785. l[0]
  786. except (KeyError, IndexError) as e:
  787. return e
  788. return None
  789. a = self.RPythonAnnotator()
  790. s = a.build_types(f, [somelist(annmodel.s_Int)])
  791. assert s.classdef is a.bookkeeper.getuniqueclassdef(IndexError) # KeyError ignored because l is a list
  792. def test_freeze_protocol(self):
  793. class Stuff:
  794. def __init__(self):
  795. self.called = False
  796. def _freeze_(self):
  797. self.called = True
  798. return True
  799. myobj = Stuff()
  800. a = self.RPythonAnnotator()
  801. s = a.build_types(lambda: myobj, [])
  802. assert myobj.called
  803. assert isinstance(s, annmodel.SomePBC)
  804. assert s.const == myobj
  805. def test_cleanup_protocol(self):
  806. class Stuff:
  807. def __init__(self):
  808. self.called = False
  809. def _cleanup_(self):
  810. self.called = True
  811. myobj = Stuff()
  812. a = self.RPythonAnnotator()
  813. s = a.build_types(lambda: myobj, [])
  814. assert myobj.called
  815. assert isinstance(s, annmodel.SomeInstance)
  816. assert s.classdef is a.bookkeeper.getuniqueclassdef(Stuff)
  817. def test_circular_mutable_getattr(self):
  818. class C:
  819. pass
  820. c = C()
  821. c.x = c
  822. def f():
  823. return c.x
  824. a = self.RPythonAnnotator()
  825. s = a.build_types(f, [])
  826. assert isinstance(s, annmodel.SomeInstance)
  827. assert s.classdef == a.bookkeeper.getuniqueclassdef(C)
  828. def test_circular_list_type(self):
  829. def f(n):
  830. lst = []
  831. for i in range(n):
  832. lst = [lst]
  833. return lst
  834. a = self.RPythonAnnotator()
  835. s = a.build_types(f, [int])
  836. assert listitem(s) == s
  837. def test_harmonic(self):
  838. a = self.RPythonAnnotator()
  839. s = a.build_types(snippet.harmonic, [int])
  840. assert s.knowntype == float
  841. # check that the list produced by range() is not mutated or resized
  842. graph = graphof(a, snippet.harmonic)
  843. all_vars = set().union(*[block.getvariables() for block in graph.iterblocks()])
  844. print all_vars
  845. for var in all_vars:
  846. s_value = var.annotation
  847. if isinstance(s_value, annmodel.SomeList):
  848. assert not s_value.listdef.listitem.resized
  849. assert not s_value.listdef.listitem.mutated
  850. assert s_value.listdef.listitem.range_step
  851. def test_bool(self):
  852. def f(a,b):
  853. return bool(a) or bool(b)
  854. a = self.RPythonAnnotator()
  855. s = a.build_types(f, [int, somelist(annmodel.s_Int)])
  856. assert s.knowntype == bool
  857. def test_float(self):
  858. def f(n):
  859. return float(n)
  860. a = self.RPythonAnnotator()
  861. s = a.build_types(f, [int])
  862. assert s.knowntype == float
  863. def test_r_uint(self):
  864. def f(n):
  865. return n + constant_unsigned_five
  866. a = self.RPythonAnnotator()
  867. s = a.build_types(f, [r_uint])
  868. assert s == annmodel.SomeInteger(nonneg = True, unsigned = True)
  869. def test_large_unsigned(self):
  870. large_constant = sys.maxint * 2 + 1 # 0xFFFFFFFF on 32-bit platforms
  871. def f():
  872. return large_constant
  873. a = self.RPythonAnnotator()
  874. with py.test.raises(ValueError):
  875. a.build_types(f, [])
  876. # if you want to get a r_uint, you have to be explicit about it
  877. def test_add_different_ints(self):
  878. def f(a, b):
  879. return a + b
  880. a = self.RPythonAnnotator()
  881. with py.test.raises(UnionError):
  882. a.build_types(f, [r_uint, int])
  883. def test_merge_different_ints(self):
  884. def f(a, b):
  885. if a:
  886. c = a
  887. else:
  888. c = b
  889. return c
  890. a = self.RPythonAnnotator()
  891. with py.test.raises(UnionError):
  892. a.build_types(f, [r_uint, int])
  893. def test_merge_ruint_zero(self):
  894. def f(a):
  895. if a:
  896. c = a
  897. else:
  898. c = 0
  899. return c
  900. a = self.RPythonAnnotator()
  901. s = a.build_types(f, [r_uint])
  902. assert s == annmodel.SomeInteger(nonneg = True, unsigned = True)
  903. def test_merge_ruint_nonneg_signed(self):
  904. def f(a, b):
  905. if a:
  906. c = a
  907. else:
  908. assert b >= 0
  909. c = b
  910. return c
  911. a = self.RPythonAnnotator()
  912. s = a.build_types(f, [r_uint, int])
  913. assert s == annmodel.SomeInteger(nonneg = True, unsigned = True)
  914. def test_prebuilt_long_that_is_not_too_long(self):
  915. small_constant = 12L
  916. def f():
  917. return small_constant
  918. a = self.RPythonAnnotator()
  919. s = a.build_types(f, [])
  920. assert s.const == 12
  921. assert s.nonneg
  922. assert not s.unsigned
  923. #
  924. small_constant = -23L
  925. def f():
  926. return small_constant
  927. a = self.RPythonAnnotator()
  928. s = a.build_types(f, [])
  929. assert s.const == -23
  930. assert not s.nonneg
  931. assert not s.unsigned
  932. def test_pbc_getattr(self):
  933. class C:
  934. def __init__(self, v1, v2):
  935. self.v2 = v2
  936. self.v1 = v1
  937. def _freeze_(self):
  938. return True
  939. c1 = C(1,'a')
  940. c2 = C(2,'b')
  941. c3 = C(3,'c')
  942. def f1(l, c):
  943. l.append(c.v1)
  944. def f2(l, c):
  945. l.append(c.v2)
  946. def g():
  947. l1 = []
  948. l2 = []
  949. f1(l1, c1)
  950. f1(l1, c2)
  951. f2(l2, c2)
  952. f2(l2, c3)
  953. return l1,l2
  954. a = self.RPythonAnnotator()
  955. s = a.build_types(g,[])
  956. l1, l2 = s.items
  957. assert listitem(l1).knowntype == int
  958. assert listitem(l2).knowntype == str
  959. acc1 = a.bookkeeper.getdesc(c1).getattrfamily()
  960. acc2 = a.bookkeeper.getdesc(c2).getattrfamily()
  961. acc3 = a.bookkeeper.getdesc(c3).getattrfamily()
  962. assert acc1 is acc2 is acc3
  963. assert len(acc1.descs) == 3
  964. assert dict.fromkeys(acc1.attrs) == {'v1': None, 'v2': None}
  965. def test_single_pbc_getattr(self):
  966. class C:
  967. def __init__(self, v1, v2):
  968. self.v1 = v1
  969. self.v2 = v2
  970. def _freeze_(self):
  971. return True
  972. c1 = C(11, "hello")
  973. c2 = C(22, 623)
  974. def f1(l, c):
  975. l.append(c.v1)
  976. def f2(c):
  977. return c.v2
  978. def f3(c):
  979. return c.v2
  980. def g():
  981. l = []
  982. f1(l, c1)
  983. f1(l, c2)
  984. return l, f2(c1), f3(c2)
  985. a = self.RPythonAnnotator()
  986. s = a.build_types(g,[])
  987. s_l, s_c1v2, s_c2v2 = s.items
  988. assert listitem(s_l).knowntype == int
  989. assert s_c1v2.const == "hello"
  990. assert s_c2v2.const == 623
  991. acc1 = a.bookkeeper.getdesc(c1).getattrfamily()
  992. acc2 = a.bookkeeper.getdesc(c2).getattrfamily()
  993. assert acc1 is acc2
  994. assert acc1.attrs.keys() == ['v1']
  995. def test_isinstance_unsigned_1(self):
  996. def f(x):
  997. return isinstance(x, r_uint)
  998. def g():
  999. v = r_uint(1)
  1000. return f(v)
  1001. a = self.RPythonAnnotator()
  1002. s = a.build_types(g, [])
  1003. assert s.const == True
  1004. def test_isinstance_unsigned_2(self):
  1005. class Foo:
  1006. pass
  1007. def f(x):
  1008. return isinstance(x, r_uint)
  1009. def g():
  1010. v = Foo()
  1011. return f(v)
  1012. a = self.RPythonAnnotator()
  1013. s = a.build_types(g, [])
  1014. assert s.const == False
  1015. def test_isinstance_base_int(self):
  1016. def f(x):
  1017. return isinstance(x, base_int)
  1018. def g(n):
  1019. v = r_uint(n)
  1020. return f(v)
  1021. a = self.RPythonAnnotator()
  1022. s = a.build_types(g, [int])
  1023. assert s.const == True
  1024. def test_isinstance_basic(self):
  1025. def f():
  1026. return isinstance(IndexError(), type)
  1027. a = self.RPythonAnnotator()
  1028. s = a.build_types(f, [])
  1029. assert s.const == False
  1030. def test_alloc_like(self):
  1031. class Base(object):
  1032. pass
  1033. class C1(Base):
  1034. pass
  1035. class C2(Base):
  1036. pass
  1037. def inst(cls):
  1038. return cls()
  1039. def alloc(cls):
  1040. i = inst(cls)
  1041. assert isinstance(i, cls)
  1042. return i
  1043. alloc._annspecialcase_ = "specialize:arg(0)"
  1044. def f():
  1045. c1 = alloc(C1)
  1046. c2 = alloc(C2)
  1047. return c1,c2
  1048. a = self.RPythonAnnotator()
  1049. s = a.build_types(f, [])
  1050. C1df = a.bookkeeper.getuniqueclassdef(C1)
  1051. C2df = a.bookkeeper.getuniqueclassdef(C2)
  1052. assert s.items[0].classdef == C1df
  1053. assert s.items[1].classdef == C2df
  1054. allocdesc = a.bookkeeper.getdesc(alloc)
  1055. s_C1 = a.bookkeeper.immutablevalue(C1)
  1056. s_C2 = a.bookkeeper.immutablevalue(C2)
  1057. graph1 = allocdesc.specialize([s_C1], None)
  1058. graph2 = allocdesc.specialize([s_C2], None)
  1059. assert a.binding(graph1.getreturnvar()).classdef == C1df
  1060. assert a.binding(graph2.getreturnvar()).classdef == C2df
  1061. assert graph1 in a.translator.graphs
  1062. assert graph2 in a.translator.graphs
  1063. def test_specialcase_args(self):
  1064. class C1(object):
  1065. pass
  1066. class C2(object):
  1067. pass
  1068. def alloc(cls, cls2):
  1069. i = cls()
  1070. assert isinstance(i, cls)
  1071. j = cls2()
  1072. assert isinstance(j, cls2)
  1073. return i
  1074. def f():
  1075. alloc(C1, C1)
  1076. alloc(C1, C2)
  1077. alloc(C2, C1)
  1078. alloc(C2, C2)
  1079. alloc._annspecialcase_ = "specialize:arg(0,1)"
  1080. a = self.RPythonAnnotator()
  1081. C1df = a.bookkeeper.getuniqueclassdef(C1)
  1082. C2df = a.bookkeeper.getuniqueclassdef(C2)
  1083. s = a.build_types(f, [])
  1084. allocdesc = a.bookkeeper.getdesc(alloc)
  1085. s_C1 = a.bookkeeper.immutablevalue(C1)
  1086. s_C2 = a.bookkeeper.immutablevalue(C2)
  1087. graph1 = allocdesc.specialize([s_C1, s_C2], None)
  1088. graph2 = allocdesc.specialize([s_C2, s_C2], None)
  1089. assert a.binding(graph1.getreturnvar()).classdef == C1df
  1090. assert a.binding(graph2.getreturnvar()).classdef == C2df
  1091. assert graph1 in a.translator.graphs
  1092. assert graph2 in a.translator.graphs
  1093. def test_specialize_arg_bound_method(self):
  1094. class GC(object):
  1095. def trace(self, callback, *args):
  1096. return callback(*args)
  1097. trace._annspecialcase_ = "specialize:arg(1)"
  1098. def callback1(self, arg1):
  1099. self.x = arg1
  1100. return "hello"
  1101. def callback2(self, arg2, arg3):
  1102. self.y = arg2
  1103. self.z = arg3
  1104. return 6
  1105. def f():
  1106. gc = GC()
  1107. s1 = gc.trace(gc.callback1, "foo")
  1108. n2 = gc.trace(gc.callback2, 7, 2)
  1109. return (s1, n2, gc.x, gc.y, gc.z)
  1110. a = self.RPythonAnnotator()
  1111. s = a.build_types(f, [])
  1112. assert s.items[0].const == "hello"
  1113. assert s.items[1].const == 6
  1114. assert s.items[2].const == "foo"
  1115. assert s.items[3].const == 7
  1116. assert s.items[4].const == 2
  1117. def test_specialize_and_star_args(self):
  1118. class I(object):
  1119. def execute(self, op, *args):
  1120. if op == 0:
  1121. return args[0]+args[1]
  1122. if op == 1:
  1123. return args[0] * args[1] + args[2]
  1124. execute._annspecialcase_ = "specialize:arg(1)"
  1125. def f(x, y):
  1126. i = I()
  1127. a = i.execute(0, x, y)
  1128. b = i.execute(1, y, y, 5)
  1129. return a+b
  1130. a = self.RPythonAnnotator()
  1131. s = a.build_types(f, [int, int])
  1132. executedesc = a.bookkeeper.getdesc(I.execute.im_func)
  1133. assert len(executedesc._cache) == 2
  1134. assert len(executedesc._cache[(0, 'star', 2)].startblock.inputargs) == 4
  1135. assert len(executedesc._cache[(1, 'star', 3)].startblock.inputargs) == 5
  1136. def test_specialize_arg_or_var(self):
  1137. def f(a):
  1138. return 1
  1139. f._annspecialcase_ = 'specialize:arg_or_var(0)'
  1140. def fn(a):
  1141. return f(3) + f(a)
  1142. a = self.RPythonAnnotator()
  1143. a.build_types(fn, [int])
  1144. executedesc = a.bookkeeper.getdesc(f)
  1145. assert sorted(executedesc._cache.keys()) == [None, (3,)]
  1146. # we got two different special
  1147. def test_specialize_call_location(self):
  1148. def g(a):
  1149. return a
  1150. g._annspecialcase_ = "specialize:call_location"
  1151. def f(x):
  1152. return g(x)
  1153. f._annspecialcase_ = "specialize:argtype(0)"
  1154. def h(y):
  1155. w = f(y)
  1156. return int(f(str(y))) + w
  1157. a = self.RPythonAnnotator()
  1158. assert a.build_types(h, [int]) == annmodel.SomeInteger()
  1159. def test_assert_list_doesnt_lose_info(self):
  1160. class T(object):
  1161. pass
  1162. def g(l):
  1163. assert isinstance(l, list)
  1164. return l
  1165. def f():
  1166. l = [T()]
  1167. return g(l)
  1168. a = self.RPythonAnnotator()
  1169. s = a.build_types(f, [])
  1170. s_item = listitem(s)
  1171. assert isinstance(s_item, annmodel.SomeInstance)
  1172. assert s_item.classdef is a.bookkeeper.getuniqueclassdef(T)
  1173. def test_int_str_mul(self):
  1174. def f(x,a,b):
  1175. return a*x+x*b
  1176. a = self.RPythonAnnotator()
  1177. s = a.build_types(f, [str,int,int])
  1178. assert s.knowntype == str
  1179. def test_list_tuple(self):
  1180. def g0(x):
  1181. return list(x)
  1182. def g1(x):
  1183. return list(x)
  1184. def f(n):
  1185. l1 = g0(())
  1186. l2 = g1((1,))
  1187. if n:
  1188. t = (1,)
  1189. else:
  1190. t = (2,)
  1191. l3 = g1(t)
  1192. return l1, l2, l3
  1193. a = self.RPythonAnnotator()
  1194. s = a.build_types(f, [bool])
  1195. assert listitem(s.items[0]) == annmodel.SomeImpossibleValue()
  1196. assert listitem(s.items[1]).knowntype == int
  1197. assert listitem(s.items[2]).knowntype == int
  1198. def test_empty_list(self):
  1199. def f():
  1200. l = []
  1201. return bool(l)
  1202. def g():
  1203. l = []
  1204. x = bool(l)
  1205. l.append(1)
  1206. return x, bool(l)
  1207. a = self.RPythonAnnotator()
  1208. s = a.build_types(f, [])
  1209. assert s.const == False
  1210. a = self.RPythonAnnotator()
  1211. s = a.build_types(g, [])
  1212. assert s.items[0].knowntype == bool and not s.items[0].is_constant()
  1213. assert s.items[1].knowntype == bool and not s.items[1].is_constant()
  1214. def test_empty_dict(self):
  1215. def f():
  1216. d = {}
  1217. return bool(d)
  1218. def g():
  1219. d = {}
  1220. x = bool(d)
  1221. d['a'] = 1
  1222. return x, bool(d)
  1223. a = self.RPythonAnnotator()
  1224. s = a.build_types(f, [])
  1225. assert s.const == False
  1226. a = self.RPythonAnnotator()
  1227. s = a.build_types(g, [])
  1228. assert s.items[0].knowntype == bool and not s.items[0].is_constant()
  1229. assert s.items[1].knowntype == bool and not s.items[1].is_constant()
  1230. def test_call_two_funcs_but_one_can_only_raise(self):
  1231. a = self.RPythonAnnotator()
  1232. s = a.build_types(snippet.call_two_funcs_but_one_can_only_raise,
  1233. [int])
  1234. assert s == a.bookkeeper.immutablevalue(None)
  1235. def test_reraiseKeyError(self):
  1236. def f(dic):
  1237. try:
  1238. dic[5]
  1239. except KeyError:
  1240. raise
  1241. a = self.RPythonAnnotator()
  1242. a.build_types(f, [somedict(a, annmodel.s_Int, annmodel.s_Int)])
  1243. fg = graphof(a, f)
  1244. et, ev = fg.exceptblock.inputargs
  1245. t = annmodel.SomeTypeOf([ev])
  1246. t.const = KeyError
  1247. assert et.annotation == t
  1248. s_ev = ev.annotation
  1249. assert s_ev == a.bookkeeper.new_exception([KeyError])
  1250. def test_reraiseAnything(self):
  1251. def f(dic):
  1252. try:
  1253. dic[5]
  1254. except:
  1255. raise
  1256. a = self.RPythonAnnotator()
  1257. a.build_types(f, [somedict(a, annmodel.s_Int, annmodel.s_Int)])
  1258. fg = graphof(a, f)
  1259. et, ev = fg.exceptblock.inputargs
  1260. t = annmodel.SomeTypeOf([ev])
  1261. t.const = KeyError # IndexError ignored because 'dic' is a dict
  1262. assert et.annotation == t
  1263. s_ev = ev.annotation
  1264. assert s_ev == a.bookkeeper.new_exception([KeyError])
  1265. def test_exception_mixing(self):
  1266. def h():
  1267. pass
  1268. def g():
  1269. pass
  1270. class X(Exception):
  1271. def __init__(self, x=0):
  1272. self.x = x
  1273. def f(a, l):
  1274. if a==1:
  1275. raise X
  1276. elif a==2:
  1277. raise X(1)
  1278. elif a==3:
  1279. raise X(4)
  1280. else:
  1281. try:
  1282. l[0]
  1283. x,y = l
  1284. g()
  1285. finally:
  1286. h()
  1287. a = self.RPythonAnnotator()
  1288. a.build_types(f, [int, somelist(annmodel.s_Int)])
  1289. fg = graphof(a, f)
  1290. et, ev = fg.exceptblock.inputargs
  1291. t = annmodel.SomeTypeOf([ev])
  1292. assert et.annotation == t
  1293. s_ev = ev.annotation
  1294. assert (isinstance(s_ev, annmodel.SomeInstance) and
  1295. s_ev.classdef == a.bookkeeper.getuniqueclassdef(Exception))
  1296. def test_try_except_raise_finally1(self):
  1297. def h(): pass
  1298. def g(): pass
  1299. class

Large files files are truncated, but you can click here to view the full file