Debian Codegraph @

rpython/annotator/builtin.py

raw symbols SCIP
1 """
2 Built-in functions.
3 """
4 import sys
5 from collections import OrderedDict, defaultdict
6
7 from rpython.annotator.model import (
8 SomeInteger, SomeChar, SomeBool, SomeString, SomeTuple,
9 SomeUnicodeCodePoint, SomeFloat, union, SomeUnicodeString,
10 SomePBC, SomeInstance, SomeDict, SomeList, SomeWeakRef, SomeIterator,
11 SomeOrderedDict, SomeByteArray, add_knowntypedata, s_ImpossibleValue,)
12 from rpython.annotator.bookkeeper import (
13 getbookkeeper, immutablevalue, BUILTIN_ANALYZERS, analyzer_for)
14 from rpython.annotator import description
15 from rpython.annotator.classdesc import ClassDef
16 from rpython.flowspace.model import Constant
17 import rpython.rlib.rarithmetic
18 import rpython.rlib.objectmodel
19 from rpython.annotator.model import AnnotatorError
20
21
22 def constpropagate(func, args_s, s_result):
23 """Returns s_result unless all args are constants, in which case the
24 func() is called and a constant result is returned (it must be contained
25 in s_result).
26 """
27 args = []
28 for s in args_s:
29 if not s.is_immutable_constant():
30 return s_result
31 args.append(s.const)
32 try:
33 realresult = func(*args)
34 except (ValueError, OverflowError):
35 # no possible answer for this precise input. Be conservative
36 # and keep the computation non-constant. Example:
37 # unichr(constant-that-doesn't-fit-16-bits) on platforms where
38 # the underlying Python has sys.maxunicode == 0xffff.
39 return s_result
40 s_realresult = immutablevalue(realresult)
41 if not s_result.contains(s_realresult):
42 raise AnnotatorError(
43 "%s%r returned %r, which is not contained in %s" % (
44 func, args, realresult, s_result))
45 return s_realresult
46
47 # ____________________________________________________________
48
49 def builtin_range(*args):
50 s_step = immutablevalue(1)
51 if len(args) == 1:
52 s_start = immutablevalue(0)
53 s_stop = args[0]
54 elif len(args) == 2:
55 s_start, s_stop = args
56 elif len(args) == 3:
57 s_start, s_stop = args[:2]
58 s_step = args[2]
59 else:
60 raise AnnotatorError("range() takes 1 to 3 arguments")
61 empty = False # so far
62 if not s_step.is_constant():
63 step = 0 # this case signals a variable step
64 else:
65 step = s_step.const
66 if step == 0:
67 raise AnnotatorError("range() with step zero")
68 if s_start.is_constant() and s_stop.is_constant():
69 try:
70 if len(xrange(s_start.const, s_stop.const, step)) == 0:
71 empty = True
72 except TypeError: # if one of the .const is a Symbolic
73 pass
74 if empty:
75 s_item = s_ImpossibleValue
76 else:
77 nonneg = False # so far
78 if step > 0 or s_step.nonneg:
79 nonneg = s_start.nonneg
80 elif step < 0:
81 nonneg = s_stop.nonneg or (s_stop.is_constant() and
82 s_stop.const >= -1)
83 s_item = SomeInteger(nonneg=nonneg)
84 return getbookkeeper().newlist(s_item, range_step=step)
85
86 builtin_xrange = builtin_range # xxx for now allow it
87
88
89 def builtin_enumerate(s_obj, s_start=None):
90 const = None
91 if s_start is not None:
92 if not s_start.is_constant():
93 raise AnnotatorError("second argument to enumerate must be constant")
94 const = s_start.const
95 return SomeIterator(s_obj, "enumerate", const)
96
97
98 def builtin_reversed(s_obj):
99 return SomeIterator(s_obj, "reversed")
100
101
102 def builtin_bool(s_obj):
103 return s_obj.bool()
104
105 def builtin_int(s_obj, s_base=None):
106 if isinstance(s_obj, SomeInteger):
107 assert not s_obj.unsigned, "instead of int(r_uint(x)), use intmask(r_uint(x))"
108 assert (s_base is None or isinstance(s_base, SomeInteger)
109 and s_obj.knowntype == str), "only int(v|string) or int(string,int) expected"
110 if s_base is not None:
111 args_s = [s_obj, s_base]
112 else:
113 args_s = [s_obj]
114 nonneg = isinstance(s_obj, SomeInteger) and s_obj.nonneg
115 return constpropagate(int, args_s, SomeInteger(nonneg=nonneg))
116
117 def builtin_float(s_obj):
118 return constpropagate(float, [s_obj], SomeFloat())
119
120 def builtin_chr(s_int):
121 return constpropagate(chr, [s_int], SomeChar())
122
123 def builtin_unichr(s_int):
124 return constpropagate(unichr, [s_int], SomeUnicodeCodePoint())
125
126 def builtin_unicode(s_unicode):
127 return constpropagate(unicode, [s_unicode], SomeUnicodeString())
128
129 def builtin_bytearray(s_str):
130 return SomeByteArray()
131
132 # note that this one either needs to be constant, or we will create SomeObject
133 def builtin_hasattr(s_obj, s_attr):
134 if not s_attr.is_constant() or not isinstance(s_attr.const, str):
135 getbookkeeper().warning('hasattr(%r, %r) is not RPythonic enough' %
136 (s_obj, s_attr))
137 r = SomeBool()
138 if s_obj.is_immutable_constant():
139 r.const = hasattr(s_obj.const, s_attr.const)
140 elif (isinstance(s_obj, SomePBC)
141 and s_obj.getKind() is description.FrozenDesc):
142 answers = {}
143 for d in s_obj.descriptions:
144 answer = (d.s_read_attribute(s_attr.const) != s_ImpossibleValue)
145 answers[answer] = True
146 if len(answers) == 1:
147 r.const, = answers
148 return r
149
150
151 def builtin_tuple(s_iterable):
152 if isinstance(s_iterable, SomeTuple):
153 return s_iterable
154 raise AnnotatorError("tuple(): argument must be another tuple")
155
156 def builtin_list(s_iterable):
157 bk = getbookkeeper()
158 if isinstance(s_iterable, SomeList):
159 return s_iterable.listdef.offspring(bk)
160 s_iter = s_iterable.iter()
161 return bk.newlist(s_iter.next())
162
163 def builtin_zip(s_iterable1, s_iterable2): # xxx not actually implemented
164 s_iter1 = s_iterable1.iter()
165 s_iter2 = s_iterable2.iter()
166 s_tup = SomeTuple((s_iter1.next(),s_iter2.next()))
167 return getbookkeeper().newlist(s_tup)
168
169 def builtin_min(*s_values):
170 if len(s_values) == 1: # xxx do we support this?
171 s_iter = s_values[0].iter()
172 return s_iter.next()
173 else:
174 return union(*s_values)
175
176 def builtin_max(*s_values):
177 if len(s_values) == 1: # xxx do we support this?
178 s_iter = s_values[0].iter()
179 return s_iter.next()
180 else:
181 s = union(*s_values)
182 if type(s) is SomeInteger and not s.nonneg:
183 nonneg = False
184 for s1 in s_values:
185 nonneg |= s1.nonneg
186 if nonneg:
187 s = SomeInteger(nonneg=True, knowntype=s.knowntype)
188 return s
189
190 # collect all functions
191 import __builtin__
192 for name, value in globals().items():
193 if name.startswith('builtin_'):
194 original = getattr(__builtin__, name[8:])
195 BUILTIN_ANALYZERS[original] = value
196
197
198 @analyzer_for(getattr(object.__init__, 'im_func', object.__init__))
199 def object_init(s_self, *args):
200 # ignore - mostly used for abstract classes initialization
201 pass
202
203 @analyzer_for(getattr(EnvironmentError.__init__, 'im_func', EnvironmentError.__init__))
204 def EnvironmentError_init(s_self, *args):
205 pass
206
207 try:
208 WindowsError
209 except NameError:
210 pass
211 else:
212 @analyzer_for(getattr(WindowsError.__init__, 'im_func', WindowsError.__init__))
213 def WindowsError_init(s_self, *args):
214 pass
215
216
217 @analyzer_for(sys.getdefaultencoding)
218 def conf():
219 return SomeString()
220
221 @analyzer_for(rpython.rlib.rarithmetic.intmask)
222 def rarith_intmask(s_obj):
223 return SomeInteger()
224
225 @analyzer_for(rpython.rlib.rarithmetic.longlongmask)
226 def rarith_longlongmask(s_obj):
227 return SomeInteger(knowntype=rpython.rlib.rarithmetic.r_longlong)
228
229 @analyzer_for(rpython.rlib.objectmodel.instantiate)
230 def robjmodel_instantiate(s_clspbc, s_nonmovable=None):
231 assert isinstance(s_clspbc, SomePBC)
232 clsdef = None
233 more_than_one = len(s_clspbc.descriptions) > 1
234 for desc in s_clspbc.descriptions:
235 cdef = desc.getuniqueclassdef()
236 if more_than_one:
237 getbookkeeper().needs_generic_instantiate[cdef] = True
238 if not clsdef:
239 clsdef = cdef
240 else:
241 clsdef = clsdef.commonbase(cdef)
242 return SomeInstance(clsdef)
243
244 @analyzer_for(rpython.rlib.objectmodel.r_dict)
245 def robjmodel_r_dict(s_eqfn, s_hashfn, s_force_non_null=None, s_simple_hash_eq=None):
246 return _r_dict_helper(SomeDict, s_eqfn, s_hashfn, s_force_non_null, s_simple_hash_eq)
247
248 @analyzer_for(rpython.rlib.objectmodel.r_ordereddict)
249 def robjmodel_r_ordereddict(s_eqfn, s_hashfn, s_force_non_null=None, s_simple_hash_eq=None):
250 return _r_dict_helper(SomeOrderedDict, s_eqfn, s_hashfn,
251 s_force_non_null, s_simple_hash_eq)
252
253 def _r_dict_helper(cls, s_eqfn, s_hashfn, s_force_non_null, s_simple_hash_eq):
254 if s_force_non_null is None:
255 force_non_null = False
256 else:
257 assert s_force_non_null.is_constant()
258 force_non_null = s_force_non_null.const
259 if s_simple_hash_eq is None:
260 simple_hash_eq = False
261 else:
262 assert s_simple_hash_eq.is_constant()
263 simple_hash_eq = s_simple_hash_eq.const
264 dictdef = getbookkeeper().getdictdef(is_r_dict=True,
265 force_non_null=force_non_null,
266 simple_hash_eq=simple_hash_eq)
267 dictdef.dictkey.update_rdict_annotations(s_eqfn, s_hashfn)
268 return cls(dictdef)
269
270 @analyzer_for(rpython.rlib.objectmodel.hlinvoke)
271 def robjmodel_hlinvoke(s_repr, s_llcallable, *args_s):
272 from rpython.rtyper.llannotation import lltype_to_annotation
273 from rpython.rtyper import rmodel
274 from rpython.rtyper.error import TyperError
275
276 assert s_repr.is_constant() and isinstance(s_repr.const, rmodel.Repr), "hlinvoke expects a constant repr as first argument"
277 r_func, nimplicitarg = s_repr.const.get_r_implfunc()
278
279 nbargs = len(args_s) + nimplicitarg
280 s_sigs = r_func.get_s_signatures((nbargs, (), False))
281 if len(s_sigs) != 1:
282 raise TyperError("cannot hlinvoke callable %r with not uniform"
283 "annotations: %r" % (s_repr.const,
284 s_sigs))
285 _, s_ret = s_sigs[0]
286 rresult = r_func.rtyper.getrepr(s_ret)
287
288 return lltype_to_annotation(rresult.lowleveltype)
289
290
291 @analyzer_for(rpython.rlib.objectmodel.keepalive_until_here)
292 def robjmodel_keepalive_until_here(*args_s):
293 return immutablevalue(None)
294
295 try:
296 import unicodedata
297 except ImportError:
298 pass
299 else:
300 @analyzer_for(unicodedata.decimal)
301 def unicodedata_decimal(s_uchr):
302 raise AnnotatorError(
303 "unicodedate.decimal() calls should not happen at interp-level")
304
305 @analyzer_for(OrderedDict)
306 def analyze():
307 return SomeOrderedDict(getbookkeeper().getdictdef())
308
309 #________________________________
310 # weakrefs
311
312 import weakref
313
314 @analyzer_for(weakref.ref)
315 def weakref_ref(s_obj):
316 if not isinstance(s_obj, SomeInstance):
317 raise AnnotatorError("cannot take a weakref to %r" % (s_obj,))
318 if s_obj.can_be_None:
319 raise AnnotatorError("should assert that the instance we take "
320 "a weakref to cannot be None")
321 return SomeWeakRef(s_obj.classdef)
322
323 #________________________________
324 # non-gc objects
325
326 @analyzer_for(rpython.rlib.objectmodel.free_non_gc_object)
327 def robjmodel_free_non_gc_object(obj):
328 pass
329
330 #________________________________
331 # pdb
332
333 import pdb
334
335 @analyzer_for(pdb.set_trace)
336 def pdb_set_trace(*args_s):
337 raise AnnotatorError(
338 "you left pdb.set_trace() in your interpreter! "
339 "If you want to attach a gdb instead, call rlib.debug.attach_gdb()")