PageRenderTime 49ms CodeModel.GetById 11ms RepoModel.GetById 0ms app.codeStats 0ms

/pypy/objspace/fake/objspace.py

https://bitbucket.org/pypy/pypy/
Python | 432 lines | 344 code | 79 blank | 9 comment | 27 complexity | 816653870faaf3b5a5f03d11d6322089 MD5 | raw file
Possible License(s): AGPL-3.0, BSD-3-Clause, Apache-2.0
  1. from rpython.annotator.model import SomeInstance, s_None
  2. from pypy.interpreter import argument, gateway
  3. from pypy.interpreter.baseobjspace import W_Root, ObjSpace, SpaceCache
  4. from pypy.interpreter.typedef import TypeDef, GetSetProperty
  5. from pypy.objspace.std.sliceobject import W_SliceObject
  6. from rpython.rlib.buffer import StringBuffer
  7. from rpython.rlib.objectmodel import instantiate, we_are_translated, specialize
  8. from rpython.rlib.nonconst import NonConstant
  9. from rpython.rlib.rarithmetic import r_uint, r_singlefloat
  10. from rpython.rtyper.extregistry import ExtRegistryEntry
  11. from rpython.rtyper.lltypesystem import lltype
  12. from pypy.tool.option import make_config
  13. from rpython.tool.sourcetools import compile2, func_with_new_name
  14. from rpython.translator.translator import TranslationContext
  15. class W_MyObject(W_Root):
  16. typedef = None
  17. def getdict(self, space):
  18. return w_obj_or_none()
  19. def getdictvalue(self, space, attr):
  20. attr + "xx" # check that it's a string
  21. return w_obj_or_none()
  22. def setdictvalue(self, space, attr, w_value):
  23. attr + "xx" # check that it's a string
  24. is_root(w_value)
  25. return NonConstant(True)
  26. def deldictvalue(self, space, attr):
  27. attr + "xx" # check that it's a string
  28. return NonConstant(True)
  29. def setdict(self, space, w_dict):
  30. is_root(w_dict)
  31. def setclass(self, space, w_subtype):
  32. is_root(w_subtype)
  33. def buffer_w(self, space, flags):
  34. return StringBuffer("foobar")
  35. def str_w(self, space):
  36. return NonConstant("foobar")
  37. identifier_w = bytes_w = str_w
  38. def unicode_w(self, space):
  39. return NonConstant(u"foobar")
  40. def int_w(self, space, allow_conversion=True):
  41. return NonConstant(-42)
  42. def uint_w(self, space):
  43. return r_uint(NonConstant(42))
  44. def bigint_w(self, space, allow_conversion=True):
  45. from rpython.rlib.rbigint import rbigint
  46. return rbigint.fromint(NonConstant(42))
  47. class W_MyListObj(W_MyObject):
  48. def append(self, w_other):
  49. pass
  50. class W_MyType(W_MyObject):
  51. name = "foobar"
  52. flag_map_or_seq = '?'
  53. def __init__(self):
  54. self.mro_w = [w_some_obj(), w_some_obj()]
  55. self.dict_w = {'__str__': w_some_obj()}
  56. def get_module(self):
  57. return w_some_obj()
  58. def getname(self, space):
  59. return self.name
  60. def w_some_obj():
  61. if NonConstant(False):
  62. return W_Root()
  63. return W_MyObject()
  64. def w_obj_or_none():
  65. if NonConstant(False):
  66. return None
  67. return w_some_obj()
  68. def w_some_type():
  69. return W_MyType()
  70. def is_root(w_obj):
  71. assert isinstance(w_obj, W_Root)
  72. is_root.expecting = W_Root
  73. def is_arguments(arg):
  74. assert isinstance(arg, argument.Arguments)
  75. is_arguments.expecting = argument.Arguments
  76. class Entry(ExtRegistryEntry):
  77. _about_ = is_root, is_arguments
  78. def compute_result_annotation(self, s_w_obj):
  79. cls = self.instance.expecting
  80. s_inst = SomeInstance(self.bookkeeper.getuniqueclassdef(cls),
  81. can_be_None=True)
  82. assert s_inst.contains(s_w_obj)
  83. return s_None
  84. def specialize_call(self, hop):
  85. hop.exception_cannot_occur()
  86. return hop.inputconst(lltype.Void, None)
  87. # ____________________________________________________________
  88. BUILTIN_TYPES = ['int', 'str', 'float', 'long', 'tuple', 'list', 'dict',
  89. 'unicode', 'complex', 'slice', 'bool', 'basestring', 'object',
  90. 'bytearray', 'buffer', 'set', 'frozenset']
  91. class FakeObjSpace(ObjSpace):
  92. is_fake_objspace = True
  93. def __init__(self, config=None):
  94. self._seen_extras = []
  95. ObjSpace.__init__(self, config=config)
  96. self.setup()
  97. def _freeze_(self):
  98. return True
  99. def float_w(self, w_obj, allow_conversion=True):
  100. is_root(w_obj)
  101. return NonConstant(42.5)
  102. def is_true(self, w_obj):
  103. is_root(w_obj)
  104. return NonConstant(False)
  105. def unwrap(self, w_obj):
  106. "NOT_RPYTHON"
  107. raise NotImplementedError
  108. def newdict(self, module=False, instance=False, kwargs=False,
  109. strdict=False):
  110. return w_some_obj()
  111. def newtuple(self, list_w):
  112. for w_x in list_w:
  113. is_root(w_x)
  114. return w_some_obj()
  115. def newset(self, list_w=None):
  116. if list_w is not None:
  117. for w_x in list_w:
  118. is_root(w_x)
  119. return w_some_obj()
  120. def newlist(self, list_w):
  121. for w_x in list_w:
  122. is_root(w_x)
  123. return W_MyListObj()
  124. def newslice(self, w_start, w_end, w_step):
  125. is_root(w_start)
  126. is_root(w_end)
  127. is_root(w_step)
  128. W_SliceObject(w_start, w_end, w_step)
  129. return w_some_obj()
  130. def newint(self, x):
  131. return w_some_obj()
  132. def newlong(self, x):
  133. return w_some_obj()
  134. def newfloat(self, x):
  135. return w_some_obj()
  136. def newcomplex(self, x, y):
  137. return w_some_obj()
  138. def newlong_from_rbigint(self, x):
  139. return w_some_obj()
  140. def newseqiter(self, x):
  141. return w_some_obj()
  142. def newbuffer(self, x):
  143. return w_some_obj()
  144. def marshal_w(self, w_obj):
  145. "NOT_RPYTHON"
  146. raise NotImplementedError
  147. def newbytes(self, x):
  148. return w_some_obj()
  149. def newunicode(self, x):
  150. return w_some_obj()
  151. def wrap(self, x):
  152. if not we_are_translated():
  153. if isinstance(x, gateway.interp2app):
  154. self._see_interp2app(x)
  155. if isinstance(x, GetSetProperty):
  156. self._see_getsetproperty(x)
  157. if isinstance(x, r_singlefloat):
  158. self._wrap_not_rpython(x)
  159. if isinstance(x, list):
  160. if x == []: # special case: it is used e.g. in sys/__init__.py
  161. return w_some_obj()
  162. self._wrap_not_rpython(x)
  163. return w_some_obj()
  164. wrap._annspecialcase_ = "specialize:argtype(1)"
  165. def _wrap_not_rpython(self, x):
  166. "NOT_RPYTHON"
  167. raise NotImplementedError
  168. def _see_interp2app(self, interp2app):
  169. "NOT_RPYTHON"
  170. activation = interp2app._code.activation
  171. def check():
  172. scope_w = [w_some_obj()] * NonConstant(42)
  173. w_result = activation._run(self, scope_w)
  174. is_root(w_result)
  175. check = func_with_new_name(check, 'check__' + interp2app.name)
  176. self._seen_extras.append(check)
  177. def _see_getsetproperty(self, getsetproperty):
  178. "NOT_RPYTHON"
  179. space = self
  180. def checkprop():
  181. getsetproperty.fget(getsetproperty, space, w_some_obj())
  182. if getsetproperty.fset is not None:
  183. getsetproperty.fset(getsetproperty, space, w_some_obj(),
  184. w_some_obj())
  185. if getsetproperty.fdel is not None:
  186. getsetproperty.fdel(getsetproperty, space, w_some_obj())
  187. if not getsetproperty.name.startswith('<'):
  188. checkprop = func_with_new_name(checkprop,
  189. 'checkprop__' + getsetproperty.name)
  190. self._seen_extras.append(checkprop)
  191. def call_obj_args(self, w_callable, w_obj, args):
  192. is_root(w_callable)
  193. is_root(w_obj)
  194. is_arguments(args)
  195. return w_some_obj()
  196. def call(self, w_callable, w_args, w_kwds=None):
  197. is_root(w_callable)
  198. is_root(w_args)
  199. is_root(w_kwds)
  200. return w_some_obj()
  201. def call_function(self, w_func, *args_w):
  202. is_root(w_func)
  203. for w_arg in list(args_w):
  204. is_root(w_arg)
  205. return w_some_obj()
  206. def call_args(self, w_func, args):
  207. is_root(w_func)
  208. is_arguments(args)
  209. return w_some_obj()
  210. def get_and_call_function(space, w_descr, w_obj, *args_w):
  211. args = argument.Arguments(space, list(args_w))
  212. w_impl = space.get(w_descr, w_obj)
  213. return space.call_args(w_impl, args)
  214. def gettypefor(self, cls):
  215. return self.gettypeobject(cls.typedef)
  216. def gettypeobject(self, typedef):
  217. assert typedef is not None
  218. see_typedef(self, typedef)
  219. return w_some_type()
  220. def type(self, w_obj):
  221. return w_some_type()
  222. def issubtype_w(self, w_sub, w_type):
  223. is_root(w_sub)
  224. is_root(w_type)
  225. return NonConstant(True)
  226. def isinstance_w(self, w_inst, w_type):
  227. is_root(w_inst)
  228. is_root(w_type)
  229. return NonConstant(True)
  230. def unpackiterable(self, w_iterable, expected_length=-1):
  231. is_root(w_iterable)
  232. if expected_length < 0:
  233. expected_length = 3
  234. return [w_some_obj()] * expected_length
  235. def unpackcomplex(self, w_complex):
  236. is_root(w_complex)
  237. return 1.1, 2.2
  238. def allocate_instance(self, cls, w_subtype):
  239. is_root(w_subtype)
  240. return instantiate(cls)
  241. allocate_instance._annspecialcase_ = "specialize:arg(1)"
  242. def decode_index(self, w_index_or_slice, seqlength):
  243. is_root(w_index_or_slice)
  244. return (NonConstant(42), NonConstant(42), NonConstant(42))
  245. def decode_index4(self, w_index_or_slice, seqlength):
  246. is_root(w_index_or_slice)
  247. return (NonConstant(42), NonConstant(42),
  248. NonConstant(42), NonConstant(42))
  249. def exec_(self, *args, **kwds):
  250. pass
  251. def createexecutioncontext(self):
  252. ec = ObjSpace.createexecutioncontext(self)
  253. ec._py_repr = None
  254. return ec
  255. def unicode_from_object(self, w_obj):
  256. return w_some_obj()
  257. def _try_fetch_pycode(self, w_func):
  258. return None
  259. # ----------
  260. def translates(self, func=None, argtypes=None, seeobj_w=[], **kwds):
  261. config = make_config(None, **kwds)
  262. if func is not None:
  263. if argtypes is None:
  264. nb_args = func.func_code.co_argcount
  265. argtypes = [W_Root] * nb_args
  266. #
  267. t = TranslationContext(config=config)
  268. self.t = t # for debugging
  269. ann = t.buildannotator()
  270. def _do_startup():
  271. self.threadlocals.enter_thread(self)
  272. ann.build_types(_do_startup, [], complete_now=False)
  273. if func is not None:
  274. ann.build_types(func, argtypes, complete_now=False)
  275. if seeobj_w:
  276. def seeme(n):
  277. return seeobj_w[n]
  278. ann.build_types(seeme, [int], complete_now=False)
  279. #
  280. # annotate all _seen_extras, knowing that annotating some may
  281. # grow the list
  282. done = 0
  283. while done < len(self._seen_extras):
  284. #print self._seen_extras
  285. ann.build_types(self._seen_extras[done], [],
  286. complete_now=False)
  287. ann.complete_pending_blocks()
  288. done += 1
  289. ann.complete()
  290. assert done == len(self._seen_extras)
  291. #t.viewcg()
  292. t.buildrtyper().specialize()
  293. t.checkgraphs()
  294. def setup(space):
  295. for name in (ObjSpace.ConstantTable +
  296. ObjSpace.ExceptionTable +
  297. BUILTIN_TYPES):
  298. setattr(space, 'w_' + name, w_some_obj())
  299. space.w_type = w_some_type()
  300. #
  301. for (name, _, arity, _) in ObjSpace.MethodTable:
  302. if name == 'type':
  303. continue
  304. args = ['w_%d' % i for i in range(arity)]
  305. params = args[:]
  306. d = {'is_root': is_root,
  307. 'w_some_obj': w_some_obj}
  308. if name in ('get',):
  309. params[-1] += '=None'
  310. exec compile2("""\
  311. def meth(%s):
  312. %s
  313. return w_some_obj()
  314. """ % (', '.join(params),
  315. '; '.join(['is_root(%s)' % arg for arg in args]))) in d
  316. meth = func_with_new_name(d['meth'], name)
  317. setattr(space, name, meth)
  318. #
  319. for name in ObjSpace.IrregularOpTable:
  320. assert hasattr(space, name) # missing?
  321. # ____________________________________________________________
  322. @specialize.memo()
  323. def see_typedef(space, typedef):
  324. assert isinstance(typedef, TypeDef)
  325. if typedef.name not in BUILTIN_TYPES:
  326. for name, value in typedef.rawdict.items():
  327. space.wrap(value)
  328. class FakeCompiler(object):
  329. def compile(self, code, name, mode, flags):
  330. return FakePyCode()
  331. FakeObjSpace.default_compiler = FakeCompiler()
  332. class FakePyCode(W_Root):
  333. def exec_code(self, space, w_globals, w_locals):
  334. return W_Root()
  335. class FakeModule(W_Root):
  336. def __init__(self):
  337. self.w_dict = w_some_obj()
  338. def get(self, name):
  339. name + "xx" # check that it's a string
  340. return w_some_obj()
  341. FakeObjSpace.sys = FakeModule()
  342. FakeObjSpace.sys.filesystemencoding = 'foobar'
  343. FakeObjSpace.sys.defaultencoding = 'ascii'
  344. FakeObjSpace.sys.dlopenflags = 123
  345. FakeObjSpace.sys.track_resources = False
  346. FakeObjSpace.builtin = FakeModule()