Debian Codegraph @

pypy/objspace/fake/objspace.py

raw symbols SCIP
1 from rpython.annotator.model import SomeInstance, s_None
2 from rpython.annotator.listdef import s_list_of_strings
3 from rpython.rlib.objectmodel import (instantiate, we_are_translated, specialize,
4 not_rpython)
5 from rpython.rlib.nonconst import NonConstant
6 from rpython.rlib.rarithmetic import r_uint, r_singlefloat
7 from rpython.rlib.debug import make_sure_not_resized
8 from rpython.rtyper.extregistry import ExtRegistryEntry
9 from rpython.rtyper.lltypesystem import lltype
10 from rpython.tool.sourcetools import compile2, func_with_new_name
11 from rpython.translator.translator import TranslationContext
12 from rpython.translator.c.genc import CStandaloneBuilder
13
14 from pypy.tool.option import make_config
15 from pypy.interpreter import argument, gateway
16 from pypy.interpreter.baseobjspace import W_Root, ObjSpace, SpaceCache
17 from pypy.interpreter.buffer import StringBuffer, SimpleView
18 from pypy.interpreter.mixedmodule import MixedModule
19 from pypy.interpreter.typedef import TypeDef, GetSetProperty
20 from pypy.objspace.std.sliceobject import W_SliceObject
21
22
23 class W_MyObject(W_Root):
24 typedef = None
25
26 def getdict(self, space):
27 return w_obj_or_none()
28
29 def getdictvalue(self, space, attr):
30 attr + "xx" # check that it's a string
31 return w_obj_or_none()
32
33 def setdictvalue(self, space, attr, w_value):
34 attr + "xx" # check that it's a string
35 is_root(w_value)
36 return NonConstant(True)
37
38 def deldictvalue(self, space, attr):
39 attr + "xx" # check that it's a string
40 return NonConstant(True)
41
42 def setdict(self, space, w_dict):
43 is_root(w_dict)
44
45 def setclass(self, space, w_subtype):
46 is_root(w_subtype)
47
48 def buffer_w(self, space, flags):
49 return SimpleView(StringBuffer("foobar"), w_obj=self)
50
51 def text_w(self, space):
52 return NonConstant("foobar")
53 bytes_w = text_w
54
55 def utf8_w(self, space):
56 return NonConstant("foobar")
57
58 def int_w(self, space, allow_conversion=True):
59 return NonConstant(-42)
60
61 def uint_w(self, space):
62 return r_uint(NonConstant(42))
63
64 def bigint_w(self, space, allow_conversion=True):
65 from rpython.rlib.rbigint import rbigint
66 x = 42
67 if we_are_translated():
68 x = NonConstant(x)
69 return rbigint.fromint(x)
70
71 class W_MyListObj(W_MyObject):
72 def append(self, w_other):
73 pass
74
75 class W_UnicodeObject(W_MyObject):
76 _length = 21
77 _utf8 = 'foobar'
78
79 def _index_to_byte(self, at):
80 return NonConstant(42)
81
82 def _len(self):
83 return self._length
84
85 def eq_w(self, w_other):
86 return NonConstant(True)
87
88
89 class W_MyType(W_MyObject):
90 name = "foobar"
91 flag_map_or_seq = '?'
92 hasuserdel = False
93
94 def __init__(self):
95 self.mro_w = [w_some_obj(), w_some_obj()]
96 self.dict_w = {'__str__': w_some_obj()}
97 self.hasuserdel = True
98
99 def get_module(self):
100 return w_some_obj()
101
102 def getname(self, space):
103 return self.name
104
105 def w_some_obj():
106 if NonConstant(False):
107 return W_Root()
108 return W_MyObject()
109
110 def w_obj_or_none():
111 if NonConstant(False):
112 return None
113 return w_some_obj()
114
115 def w_some_type():
116 return W_MyType()
117
118 def is_root(w_obj):
119 assert isinstance(w_obj, W_Root)
120 is_root.expecting = W_Root
121
122 def is_arguments(arg):
123 assert isinstance(arg, argument.Arguments)
124 is_arguments.expecting = argument.Arguments
125
126
127 class Entry(ExtRegistryEntry):
128 _about_ = is_root, is_arguments
129
130 def compute_result_annotation(self, s_w_obj):
131 cls = self.instance.expecting
132 s_inst = SomeInstance(self.bookkeeper.getuniqueclassdef(cls),
133 can_be_None=True)
134 assert s_inst.contains(s_w_obj)
135 return s_None
136
137 def specialize_call(self, hop):
138 hop.exception_cannot_occur()
139 return hop.inputconst(lltype.Void, None)
140
141 # ____________________________________________________________
142
143
144 BUILTIN_TYPES = ['int', 'float', 'tuple', 'list', 'dict', 'bytes',
145 'unicode', 'complex', 'slice', 'bool', 'text', 'object',
146 'set', 'frozenset', 'bytearray', 'memoryview']
147
148 INTERP_TYPES = ['function', 'builtin_function', 'module', 'getset_descriptor',
149 'instance', 'classobj']
150
151 class FakeObjSpace(ObjSpace):
152 is_fake_objspace = True
153
154 def __init__(self, config=None):
155 self._seen_extras = []
156 ObjSpace.__init__(self, config=config)
157 self.setup()
158
159 # Be sure to annotate W_SliceObject constructor.
160 # In Python2, this is triggered by W_InstanceObject.__getslice__.
161 def build_slice():
162 self.newslice(self.w_None, self.w_None, self.w_None)
163 def attach_list_strategy():
164 # this is needed for modules which interacts directly with
165 # std.listobject.W_ListObject, e.g. after an isinstance check. For
166 # example, _hpy_universal. We need to attach a couple of attributes
167 # so that the annotator annotates them with the correct types
168 from pypy.objspace.std.listobject import W_ListObject, ObjectListStrategy
169 space = self
170 w_obj = w_some_obj()
171 if isinstance(w_obj, W_ListObject):
172 w_obj.space = space
173 w_obj.strategy = ObjectListStrategy(space)
174 list_w = [w_some_obj(), w_some_obj()]
175 w_obj.lstorage = w_obj.strategy.erase(list_w)
176
177 self._seen_extras.append(build_slice)
178 self._seen_extras.append(attach_list_strategy)
179
180 def _freeze_(self):
181 return True
182
183 def view_as_kwargs(self, w_obj):
184 return [W_UnicodeObject()] * 3, [W_UnicodeObject()] * 3
185
186 UnicodeObjectCls = W_UnicodeObject
187
188 def float_w(self, w_obj, allow_conversion=True):
189 is_root(w_obj)
190 return NonConstant(42.5)
191
192 def is_true(self, w_obj):
193 is_root(w_obj)
194 return NonConstant(False)
195
196 def hash_w(self, w_obj):
197 return NonConstant(32)
198
199 def len_w(self, w_obj):
200 return NonConstant(37)
201
202 def utf8_len_w(self, space):
203 return NonConstant((NonConstant("utf8len_foobar"), NonConstant(14)))
204
205 @not_rpython
206 def unwrap(self, w_obj):
207 raise NotImplementedError
208
209 def newdict(self, module=False, instance=False, kwargs=False,
210 strdict=False):
211 return w_some_obj()
212
213 def newtuple(self, list_w):
214 make_sure_not_resized(list_w)
215 for w_x in list_w:
216 is_root(w_x)
217 return w_some_obj()
218
219 def newtuple2(self, w_a, w_b):
220 return w_some_obj()
221
222 def newset(self, list_w=None):
223 if list_w is not None:
224 for w_x in list_w:
225 is_root(w_x)
226 return w_some_obj()
227 newfrozenset = newset
228
229 def newlist(self, list_w):
230 # make sure that the annotator thinks that the list is resized
231 list_w.append(W_Root())
232 #
233 for w_x in list_w:
234 is_root(w_x)
235 return W_MyListObj()
236
237 def newslice(self, w_start, w_end, w_step):
238 is_root(w_start)
239 is_root(w_end)
240 is_root(w_step)
241 W_SliceObject(w_start, w_end, w_step)
242 return w_some_obj()
243
244 @specialize.argtype(1)
245 def newint(self, x):
246 return w_some_obj()
247
248 def newlong(self, x):
249 return w_some_obj()
250
251 @specialize.argtype(1)
252 def newlong_from_rarith_int(self, x):
253 return w_some_obj()
254
255 def newfloat(self, x):
256 return w_some_obj()
257
258 def newcomplex(self, x, y):
259 return w_some_obj()
260
261 def newlong_from_rbigint(self, x):
262 return w_some_obj()
263
264 def newseqiter(self, x):
265 return w_some_obj()
266
267 def newmemoryview(self, x):
268 return w_some_obj()
269
270 @not_rpython
271 def marshal_w(self, w_obj):
272 raise NotImplementedError
273
274 def newbytes(self, x):
275 return w_some_obj()
276
277 def newutf8(self, x, l):
278 return W_UnicodeObject()
279
280 def eq_w(self, obj1, obj2):
281 return NonConstant(True)
282
283 @specialize.argtype(1)
284 def newtext(self, x, lgt=-1):
285 return W_UnicodeObject()
286 newtext_or_none = newtext
287 newfilename = newtext
288
289 @not_rpython
290 def wrap(self, x):
291 if not we_are_translated():
292 if isinstance(x, W_Root):
293 x.spacebind(self)
294 if isinstance(x, r_singlefloat):
295 self._wrap_not_rpython(x)
296 if isinstance(x, list):
297 if x == []: # special case: it is used e.g. in sys/__init__.py
298 return w_some_obj()
299 raise NotImplementedError
300 return w_some_obj()
301
302 @not_rpython
303 def _see_interp2app(self, interp2app):
304 """Called by GatewayCache.build()"""
305 activation = interp2app._code.activation
306 def check():
307 scope_w = [w_some_obj()] * NonConstant(42)
308 w_result = activation._run(self, scope_w)
309 is_root(w_result)
310 check = func_with_new_name(check, 'check__' + interp2app.name)
311 self._seen_extras.append(check)
312
313 @not_rpython
314 def _see_getsetproperty(self, getsetproperty):
315 """Called by GetSetProperty.spacebind()"""
316 space = self
317 def checkprop():
318 getsetproperty.fget(getsetproperty, space, w_some_obj())
319 if getsetproperty.fset is not None:
320 getsetproperty.fset(getsetproperty, space, w_some_obj(),
321 w_some_obj())
322 if getsetproperty.fdel is not None:
323 getsetproperty.fdel(getsetproperty, space, w_some_obj())
324 if not getsetproperty.name.startswith('<'):
325 checkprop = func_with_new_name(checkprop,
326 'checkprop__' + getsetproperty.name)
327 self._seen_extras.append(checkprop)
328
329 def call_obj_args(self, w_callable, w_obj, args):
330 is_root(w_callable)
331 is_root(w_obj)
332 is_arguments(args)
333 return w_some_obj()
334
335 def call(self, w_callable, w_args, w_kwds=None):
336 is_root(w_callable)
337 is_root(w_args)
338 is_root(w_kwds)
339 return w_some_obj()
340
341 def call_function(self, w_func, *args_w):
342 is_root(w_func)
343 for w_arg in list(args_w):
344 is_root(w_arg)
345 return w_some_obj()
346
347 def call_args(self, w_func, args):
348 is_root(w_func)
349 is_arguments(args)
350 return w_some_obj()
351
352 def get_and_call_function(space, w_descr, w_obj, *args_w):
353 args = argument.Arguments(space, list(args_w))
354 w_impl = space.get(w_descr, w_obj)
355 return space.call_args(w_impl, args)
356
357 def gettypefor(self, cls):
358 return self.gettypeobject(cls.typedef)
359
360 def gettypeobject(self, typedef):
361 assert typedef is not None
362 see_typedef(self, typedef)
363 return w_some_type()
364
365 def getitem(self, w_obj, w_name):
366 is_root(w_obj)
367 is_root(w_name)
368 if isinstance(w_obj, FakeModules):
369 # For reset_lazy_initial_values,
370 # need to pretend we return a MixedModule object
371 return FakeMixedModule()
372 return w_some_type()
373
374 def type(self, w_obj):
375 return w_some_type()
376
377 def lookup_in_type_where(self, w_type, key):
378 return w_some_obj(), w_some_obj()
379
380 def issubtype_w(self, w_sub, w_type):
381 is_root(w_sub)
382 is_root(w_type)
383 return NonConstant(True)
384
385 def isinstance_w(self, w_inst, w_type):
386 is_root(w_inst)
387 is_root(w_type)
388 return NonConstant(True)
389
390 def unpackiterable(self, w_iterable, expected_length=-1):
391 is_root(w_iterable)
392 if expected_length < 0:
393 expected_length = 3
394 return [w_some_obj()] * expected_length
395
396 def unpackcomplex(self, w_complex):
397 is_root(w_complex)
398 return 1.1, 2.2
399
400 @specialize.arg(1)
401 def allocate_instance(self, cls, w_subtype):
402 is_root(w_subtype)
403 return instantiate(cls)
404
405 def decode_index4(self, w_index_or_slice, w_obj):
406 is_root(w_index_or_slice)
407 return (NonConstant(42), NonConstant(42),
408 NonConstant(42), NonConstant(42))
409
410 def exec_(self, *args, **kwds):
411 pass
412
413 def createexecutioncontext(self):
414 ec = ObjSpace.createexecutioncontext(self)
415 ec._py_repr = None
416 return ec
417
418 def unicode_from_object(self, w_obj):
419 return w_some_obj()
420
421 def encode_unicode_object(self, w_unicode, encoding, errors):
422 return w_some_obj()
423
424 def _try_fetch_pycode(self, w_func):
425 return None
426
427 def is_generator(self, w_obj):
428 return NonConstant(False)
429
430 def is_iterable(self, w_obj):
431 return NonConstant(False)
432
433 def lookup_in_type(self, w_type, name):
434 return w_some_obj()
435
436 def warn(self, w_msg, w_warningcls, stacklevel=2):
437 pass
438
439 def _try_buffer_w(self, w_obj, flags):
440 return w_obj.buffer_w(self, flags)
441
442 # ----------
443
444 def translates(self, func=None, argtypes=None, seeobj_w=[],
445 extra_func=None, c_compile=False,
446 **kwds):
447 config = make_config(None, **kwds)
448 if func is not None:
449 if argtypes is None:
450 nb_args = func.func_code.co_argcount
451 argtypes = [W_Root] * nb_args
452 #
453 t = TranslationContext(config=config)
454 self.t = t # for debugging
455 ann = t.buildannotator()
456
457 def entry_point(argv):
458 self.threadlocals.enter_thread(self)
459 W_SliceObject(w_some_obj(), w_some_obj(), w_some_obj())
460 if extra_func:
461 extra_func(self)
462 return 0
463 ann.build_types(entry_point, [s_list_of_strings], complete_now=False)
464 if func is not None:
465 ann.build_types(func, argtypes, complete_now=False)
466 if seeobj_w:
467 def seeme(n):
468 return seeobj_w[n]
469 ann.build_types(seeme, [int], complete_now=False)
470 #
471 # annotate all _seen_extras, knowing that annotating some may
472 # grow the list
473 done = 0
474 while done < len(self._seen_extras):
475 #print self._seen_extras
476 ann.build_types(self._seen_extras[done], [],
477 complete_now=False)
478 ann.complete_pending_blocks()
479 done += 1
480 ann.complete()
481 assert done == len(self._seen_extras)
482 #t.viewcg()
483 t.buildrtyper().specialize()
484 t.checkgraphs()
485 from rpython.translator.backendopt.all import backend_optimizations
486 backend_optimizations(t, replace_we_are_jitted=True)
487 if c_compile:
488 cbuilder = CStandaloneBuilder(t, entry_point, t.config)
489 cbuilder.generate_source(defines=cbuilder.DEBUG_DEFINES)
490 cbuilder.compile()
491 return t, cbuilder
492
493
494 def setup(space):
495 from pypy.module.exceptions import interp_exceptions
496 obj_space_exceptions = ObjSpace.ExceptionTable
497 # Add subclasses of the ExceptionTable errors
498 for name, exc in interp_exceptions.__dict__.items():
499 if (isinstance(exc, type) and
500 issubclass(exc, interp_exceptions.W_BaseException)):
501 name = name.replace("W_", "")
502 if name not in obj_space_exceptions:
503 obj_space_exceptions.append(name)
504
505 for name in (ObjSpace.ConstantTable +
506 obj_space_exceptions +
507 BUILTIN_TYPES):
508 if name != "str":
509 setattr(space, 'w_' + name, w_some_obj())
510 space.w_bytes = w_some_obj()
511 space.w_text = w_some_obj()
512 space.w_type = w_some_type()
513 #
514 for (name, _, arity, _) in ObjSpace.MethodTable:
515 if name in ('type', 'getitem'):
516 continue
517 args = ['w_%d' % i for i in range(arity)]
518 params = args[:]
519 d = {'is_root': is_root,
520 'w_some_obj': w_some_obj}
521 if name in ('get',):
522 params[-1] += '=None'
523 exec compile2("""\
524 def meth(%s):
525 %s
526 return w_some_obj()
527 """ % (', '.join(params),
528 '; '.join(['is_root(%s)' % arg for arg in args]))) in d
529 meth = func_with_new_name(d['meth'], name)
530 setattr(space, name, meth)
531 #
532 for name in ObjSpace.IrregularOpTable:
533 assert hasattr(space, name) # missing?
534
535
536 # ____________________________________________________________
537
538 @specialize.memo()
539 def see_typedef(space, typedef):
540 assert isinstance(typedef, TypeDef)
541 if typedef.name not in BUILTIN_TYPES and typedef.name not in INTERP_TYPES:
542 print
543 print '------ seeing typedef %r ------' % (typedef.name,)
544 for name, value in typedef.rawdict.items():
545 space.wrap(value)
546
547 class FakeCompiler(object):
548 def compile(self, code, name, mode, flags, optimize=-1):
549 return FakePyCode()
550 FakeObjSpace.default_compiler = FakeCompiler()
551
552 class FakePyCode(W_Root):
553 def exec_code(self, space, w_globals, w_locals):
554 return W_Root()
555
556 class FakeMixedModule(MixedModule):
557 def __init__(self):
558 pass
559
560 class FakeModules(W_Root):
561 pass
562
563 class FakeModule(W_Root):
564 def __init__(self):
565 self.w_dict = w_some_obj()
566 def get(self, name):
567 name + "xx" # check that it's a string
568 return FakeModules()
569 def setmodule(self, w_mod):
570 is_root(w_mod)
571 FakeObjSpace.sys = FakeModule()
572 FakeObjSpace.sys.filesystemencoding = 'foobar'
573 FakeObjSpace.sys.defaultencoding = 'ascii'
574 FakeObjSpace.sys.dlopenflags = 123
575 FakeObjSpace.builtin = FakeModule()