Debian Codegraph @

pypy/interpreter/argument.py

raw symbols SCIP
1 """
2 Arguments objects.
3 """
4 from rpython.rlib.debug import make_sure_not_resized
5 from rpython.rlib.objectmodel import not_rpython, specialize
6 from rpython.rlib import jit
7 from rpython.rlib.objectmodel import enforceargs
8 from rpython.rlib.rstring import StringBuilder
9
10 from pypy.interpreter.error import OperationError, oefmt
11
12 @specialize.arg(2)
13 def raise_type_error(space, w_function, msg, *args):
14 if w_function is None:
15 raise oefmt(space.w_TypeError, msg, *args)
16 msg = "%s " + msg
17 raise oefmt(space.w_TypeError, msg, space.object_functionstr(w_function), *args)
18
19
20 class Arguments(object):
21 """
22 Collects the arguments of a function call.
23
24 Instances should be considered immutable.
25
26 Some parts of this class are written in a slightly convoluted style to help
27 the JIT. It is really crucial to get this right, because Python's argument
28 semantics are complex, but calls occur everywhere.
29 """
30
31 def __init__(self, space, args_w, keyword_names_w=None, keywords_w=None,
32 w_stararg=None, w_starstararg=None,
33 methodcall=False, w_function=None):
34 self.space = space
35 assert isinstance(args_w, list)
36 self.arguments_w = args_w
37 # keyword_names_w and keywords_w are two parallel lists
38 self.keyword_names_w = keyword_names_w
39 self.keywords_w = keywords_w
40 if keyword_names_w is not None:
41 assert keywords_w is not None
42 assert len(keywords_w) == len(keyword_names_w)
43 make_sure_not_resized(self.keyword_names_w)
44 make_sure_not_resized(self.keywords_w)
45
46 make_sure_not_resized(self.arguments_w)
47 self._combine_wrapped(w_stararg, w_starstararg, w_function)
48 # a flag that specifies whether the JIT can unroll loops that operate
49 # on the keywords
50 self._jit_few_keywords = self.keyword_names_w is None or jit.isconstant(len(self.keyword_names_w))
51 # a flag whether this is likely a method call, which doesn't change the
52 # behaviour but produces better error messages
53 self.methodcall = methodcall
54
55 @not_rpython
56 def __repr__(self):
57 name = self.__class__.__name__
58 if not self.keyword_names_w:
59 return '%s(%s)' % (name, self.arguments_w,)
60 else:
61 return '%s(%s, %s, %s)' % (name, self.arguments_w,
62 [self.space.text_w(w_name) for w_name in self.keyword_names_w],
63 self.keywords_w)
64
65
66 ### Manipulation ###
67
68 @jit.look_inside_iff(lambda self: self._jit_few_keywords)
69 def unpack(self): # slowish
70 "Return a ([w1,w2...], {'kw':w3...}) pair."
71 kwds_w = {}
72 if self.keyword_names_w:
73 for i in range(len(self.keyword_names_w)):
74 kwds_w[self.space.text_w(self.keyword_names_w[i])] = self.keywords_w[i]
75 return self.arguments_w, kwds_w
76
77 def replace_arguments(self, args_w):
78 "Return a new Arguments with a args_w as positional arguments."
79 return Arguments(self.space, args_w, self.keyword_names_w, self.keywords_w)
80
81 def prepend(self, w_firstarg):
82 "Return a new Arguments with a new argument inserted first."
83 return self.replace_arguments([w_firstarg] + self.arguments_w)
84
85 def _combine_wrapped(self, w_stararg, w_starstararg, w_function=None):
86 "unpack the *arg and **kwd into arguments_w and keywords_w"
87 if w_stararg is not None:
88 self._combine_starargs_wrapped(w_stararg, w_function)
89 if w_starstararg is not None:
90 self._combine_starstarargs_wrapped(w_starstararg, w_function)
91
92 def _combine_starargs_wrapped(self, w_stararg, w_function=None):
93 # unpack the * arguments
94 space = self.space
95 try:
96 args_w = space.fixedview(w_stararg)
97 except OperationError as e:
98 if (e.match(space, space.w_TypeError) and
99 not space.is_iterable(w_stararg)):
100 raise_type_error(space, w_function,
101 "argument after * must be an iterable, not %T",
102 w_stararg)
103 raise
104 self.arguments_w = self.arguments_w + args_w
105
106 def _combine_starstarargs_wrapped(self, w_starstararg, w_function=None):
107 # unpack the ** arguments
108 space = self.space
109 keyword_names_w, values_w = space.view_as_kwargs(w_starstararg)
110 if keyword_names_w is not None: # this path also taken for empty dicts
111 if self.keyword_names_w is None:
112 self.keyword_names_w = keyword_names_w
113 self.keywords_w = values_w
114 else:
115 _check_not_duplicate_kwargs(
116 self.space, self.keyword_names_w, keyword_names_w, values_w,
117 w_function)
118 self.keyword_names_w = self.keyword_names_w + keyword_names_w
119 self.keywords_w = self.keywords_w + values_w
120 return
121 is_dict = False
122 if space.isinstance_w(w_starstararg, space.w_dict):
123 w_st_iter = space.newtext("__iter__")
124 # bug-to-bug compatibility: CPython ignores __getitem__ overrides
125 # in dict subclasses if there is no __iter__
126 is_dict = space.is_w(
127 space.findattr(space.type(w_starstararg), w_st_iter),
128 space.findattr(space.w_dict, w_st_iter))
129 keys_w = space.unpackiterable(w_starstararg)
130 else:
131 try:
132 w_keys = space.call_method(w_starstararg, "keys")
133 except OperationError as e:
134 if e.match(space, space.w_AttributeError):
135 raise_type_error(space, w_function,
136 "argument after ** must be a mapping, not %T",
137 w_starstararg)
138 raise
139 keys_w = space.unpackiterable(w_keys)
140 keywords_w = [None] * len(keys_w)
141 keyword_names_w = [None] * len(keys_w)
142 _do_combine_starstarargs_wrapped(
143 space, keys_w, w_starstararg, keyword_names_w, keywords_w, self.keyword_names_w,
144 is_dict, w_function)
145 if self.keyword_names_w is None:
146 self.keyword_names_w = keyword_names_w
147 self.keywords_w = keywords_w
148 else:
149 self.keyword_names_w = self.keyword_names_w + keyword_names_w
150 self.keywords_w = self.keywords_w + keywords_w
151
152
153 def fixedunpack(self, argcount):
154 """The simplest argument parsing: get the 'argcount' arguments,
155 or raise a real ValueError if the length is wrong."""
156 if self.keyword_names_w:
157 raise ValueError("no keyword arguments expected")
158 if len(self.arguments_w) > argcount:
159 raise ValueError("too many arguments (%d expected)" % argcount)
160 elif len(self.arguments_w) < argcount:
161 raise ValueError("not enough arguments (%d expected)" % argcount)
162 return self.arguments_w
163
164 def firstarg(self):
165 "Return the first argument for inspection."
166 if self.arguments_w:
167 return self.arguments_w[0]
168 return None
169
170 ### Parsing for function calls ###
171
172 @jit.unroll_safe
173 def _match_signature(self, w_firstarg, scope_w, signature, defaults_w=None,
174 w_kw_defs=None, blindargs=0):
175 """Parse args and kwargs according to the signature of a code object,
176 or raise an ArgErr in case of failure.
177 """
178 # w_firstarg = a first argument to be inserted (e.g. self) or None
179 # args_w = list of the normal actual parameters, wrapped
180 # scope_w = resulting list of wrapped values
181 #
182
183 # some comments about the JIT: it assumes that signature is a constant,
184 # so all values coming from there can be assumed constant. It assumes
185 # that the length of the defaults_w does not vary too much.
186 co_posonlyargcount = signature.posonlyargcount
187 co_argcount = signature.num_argnames()
188 co_kwonlyargcount = signature.num_kwonlyargnames()
189 too_many_args = False
190
191 # put the special w_firstarg into the scope, if it exists
192 upfront = 0
193 args_w = self.arguments_w
194 if w_firstarg is not None:
195 if co_argcount > 0:
196 scope_w[0] = w_firstarg
197 upfront = 1
198 else:
199 # ugh, this is a call to a method 'def meth(*args)', maybe
200 # (see test_issue2996_*). Fall-back solution...
201 args_w = [w_firstarg] + args_w
202
203 num_args = len(args_w)
204 avail = num_args + upfront
205
206 keyword_names_w = self.keyword_names_w
207 num_kwds = 0
208 if keyword_names_w is not None:
209 num_kwds = len(keyword_names_w)
210
211 # put as many positional input arguments into place as available
212 input_argcount = upfront
213 if input_argcount < co_argcount:
214 take = min(num_args, co_argcount - upfront)
215
216 # letting the JIT unroll this loop is safe, because take is always
217 # smaller than co_argcount
218 for i in range(take):
219 scope_w[i + input_argcount] = args_w[i]
220 input_argcount += take
221
222 # collect extra positional arguments into the *vararg
223 if signature.has_vararg():
224 args_left = co_argcount - upfront
225 assert args_left >= 0 # check required by rpython
226 if num_args > args_left:
227 if args_left == 0:
228 starargs_w = args_w # don't need to copy if its the whole list
229 else:
230 starargs_w = args_w[args_left:]
231 else:
232 starargs_w = []
233 loc = co_argcount + co_kwonlyargcount
234 scope_w[loc] = self.space.newtuple(starargs_w)
235 elif avail > co_argcount:
236 too_many_args = True
237
238 # if a **kwargs argument is needed, create the dict
239 w_kwds = None
240 if signature.has_kwarg():
241 w_kwds = self.space.newdict(kwargs=True)
242 scope_w[co_argcount + co_kwonlyargcount + signature.has_vararg()] = w_kwds
243
244 # handle keyword arguments
245 num_remainingkwds = 0
246 keywords_w = self.keywords_w
247 kwds_mapping = None
248 if num_kwds:
249 # kwds_mapping maps target indexes in the scope (minus input_argcount)
250 # to positions in the keywords_w list
251 kwds_mapping = [0] * (co_argcount + co_kwonlyargcount - input_argcount)
252 # initialize manually, for the JIT :-(
253 for i in range(len(kwds_mapping)):
254 kwds_mapping[i] = -1
255 # match the keywords given at the call site to the argument names
256 # the called function takes
257 # this function must not take a scope_w, to make the scope not
258 # escape
259 num_remainingkwds = _match_keywords(
260 self.space,
261 signature, blindargs, co_posonlyargcount, input_argcount,
262 keyword_names_w, kwds_mapping, self._jit_few_keywords)
263 if num_remainingkwds:
264 if w_kwds is not None:
265 # collect extra keyword arguments into the **kwarg
266 _collect_keyword_args(
267 self.space, keyword_names_w, keywords_w, w_kwds,
268 kwds_mapping, self._jit_few_keywords)
269 else:
270 raise ArgErrUnknownKwds(self.space, num_remainingkwds,
271 keyword_names_w, kwds_mapping)
272
273 # check for missing arguments and fill them from the kwds,
274 # or with defaults, if available
275 more_filling = (input_argcount < co_argcount + co_kwonlyargcount)
276 def_first = 0
277 if more_filling:
278 def_first = co_argcount - (0 if defaults_w is None else len(defaults_w))
279 j = 0
280 kwds_index = -1
281 # first, fill the arguments from the kwds
282 for i in range(input_argcount, co_argcount + co_kwonlyargcount):
283 if kwds_mapping is not None:
284 kwds_index = kwds_mapping[j]
285 j += 1
286 if kwds_index >= 0:
287 scope_w[i] = keywords_w[kwds_index]
288
289 if too_many_args:
290 kwonly_given = 0
291 for i in range(co_argcount, co_argcount + co_kwonlyargcount):
292 if scope_w[i] is not None:
293 kwonly_given += 1
294 if self.methodcall:
295 cls = ArgErrTooManyMethod
296 else:
297 cls = ArgErrTooMany
298 raise cls(signature,
299 0 if defaults_w is None else len(defaults_w),
300 avail, kwonly_given)
301
302 if more_filling:
303 missing_positional = None
304 missing_kwonly = None
305 # then, fill the posonly arguments with defaults_w (if needed)
306 for i in range(input_argcount, co_argcount):
307 if scope_w[i] is not None:
308 continue
309 defnum = i - def_first
310 if defnum >= 0:
311 scope_w[i] = defaults_w[defnum]
312 else:
313 if missing_positional is None:
314 missing_positional = []
315 missing_positional.append(signature.argnames[i])
316
317 # finally, fill kwonly arguments with w_kw_defs (if needed)
318 for i in range(co_argcount, co_argcount + co_kwonlyargcount):
319 if scope_w[i] is not None:
320 continue
321 name = signature.argnames[i]
322 if w_kw_defs is None:
323 if missing_kwonly is None:
324 missing_kwonly = []
325 missing_kwonly.append(name)
326 continue
327 w_def = self.space.finditem_str(w_kw_defs, name)
328 if w_def is not None:
329 scope_w[i] = w_def
330 else:
331 if missing_kwonly is None:
332 missing_kwonly = []
333 missing_kwonly.append(name)
334
335 if missing_positional:
336 raise ArgErrMissing(missing_positional, True)
337 if missing_kwonly:
338 raise ArgErrMissing(missing_kwonly, False)
339
340
341 def parse_into_scope(self, w_firstarg,
342 scope_w, fnname, signature, defaults_w=None,
343 w_kw_defs=None):
344 """Parse args and kwargs to initialize a frame
345 according to the signature of code object.
346 Store the argumentvalues into scope_w.
347 scope_w must be big enough for signature.
348 """
349 try:
350 self._match_signature(w_firstarg,
351 scope_w, signature, defaults_w,
352 w_kw_defs, 0)
353 except ArgErr as e:
354 raise oefmt(self.space.w_TypeError, "%s() %8", fnname, e.getmsg())
355 return signature.scope_length()
356
357 def _parse(self, w_firstarg, signature, defaults_w, w_kw_defs, blindargs=0):
358 """Parse args and kwargs according to the signature of a code object,
359 or raise an ArgErr in case of failure.
360 """
361 scopelen = signature.scope_length()
362 scope_w = [None] * scopelen
363 self._match_signature(w_firstarg, scope_w, signature, defaults_w,
364 w_kw_defs, blindargs)
365 return scope_w
366
367
368 def parse_obj(self, w_firstarg,
369 fnname, signature, defaults_w=None, w_kw_defs=None,
370 blindargs=0):
371 """Parse args and kwargs into a list according to the signature of a
372 code object.
373 """
374 try:
375 return self._parse(w_firstarg, signature, defaults_w, w_kw_defs,
376 blindargs)
377 except ArgErrUnknownKwds as e:
378 if not signature.has_kwarg() and signature.kwonlyargcount == 0:
379 raise oefmt(self.space.w_TypeError,
380 "%s() takes no keyword arguments", fnname)
381 raise oefmt(self.space.w_TypeError, "%s() %8", fnname, e.getmsg())
382 except ArgErr as e:
383 raise oefmt(self.space.w_TypeError, "%s() %8", fnname, e.getmsg())
384
385 @staticmethod
386 def frompacked(space, w_args=None, w_kwds=None):
387 """Convenience static method to build an Arguments
388 from a wrapped sequence and a wrapped dictionary."""
389 return Arguments(space, [], w_stararg=w_args, w_starstararg=w_kwds)
390
391 def topacked(self):
392 """Express the Argument object as a pair of wrapped w_args, w_kwds."""
393 space = self.space
394 w_args = space.newtuple(self.arguments_w)
395 w_kwds = space.newdict()
396 if self.keyword_names_w is not None:
397 for i in range(len(self.keyword_names_w)):
398 w_key = self.keyword_names_w[i]
399 space.setitem(w_kwds, w_key, self.keywords_w[i])
400 return w_args, w_kwds
401
402 # JIT helper functions
403 # these functions contain functionality that the JIT is not always supposed to
404 # look at. They should not get a self arguments, which makes the amount of
405 # arguments annoying :-(
406
407 @jit.look_inside_iff(lambda space, existingkeywords_w, keyword_names_w, keywords_w, w_function:
408 jit.isconstant(len(keyword_names_w) and
409 jit.isconstant(existingkeywords_w)))
410 def _check_not_duplicate_kwargs(space, existingkeywords_w, keyword_names_w, keywords_w, w_function):
411 # looks quadratic, but the JIT should remove all of it nicely.
412 # Also, all the lists should be small
413 for w_key in keyword_names_w:
414 if contains_w_names(w_key, existingkeywords_w):
415 raise_type_error(space, w_function,
416 "got multiple values for keyword argument '%S'",
417 w_key)
418
419 def contains_w_names(w_key, keys_w):
420 for w_other in keys_w:
421 if w_other.eq_w(w_key):
422 return True
423 return False
424
425 def _do_combine_starstarargs_wrapped(space, keys_w, w_starstararg, keyword_names_w,
426 keywords_w, existingkeywords_w, is_dict, w_function):
427 i = 0
428 seen = {}
429 for w_key in keys_w:
430 try:
431 key = space.text_w(w_key)
432 except OperationError as e:
433 if e.match(space, space.w_TypeError):
434 raise_type_error(space, w_function,
435 "keywords must be strings, not '%T'",
436 w_key)
437 raise
438 else:
439 if ((existingkeywords_w and
440 contains_w_names(w_key, existingkeywords_w)) or
441 key in seen
442 ):
443 raise_type_error(space, w_function,
444 "got multiple values for keyword argument '%S'",
445 w_key)
446 seen[key] = None
447 assert isinstance(w_key, space.UnicodeObjectCls)
448 keyword_names_w[i] = w_key
449 if is_dict:
450 # issue 2435: bug-to-bug compatibility with cpython. for a subclass of
451 # dict, just ignore the __getitem__ and access the underlying dict
452 # directly
453 from pypy.objspace.descroperation import dict_getitem
454 w_descr = dict_getitem(space)
455 w_value = space.get_and_call_function(w_descr, w_starstararg, w_key)
456 else:
457 w_value = space.getitem(w_starstararg, w_key)
458 keywords_w[i] = w_value
459 i += 1
460
461 @jit.look_inside_iff(
462 lambda space, signature, blindargs, co_posonlyargcount, input_argcount,
463 keyword_names_w, kwds_mapping, jiton: jiton)
464 def _match_keywords(space, signature, blindargs, co_posonlyargcount,
465 input_argcount, keyword_names_w, kwds_mapping, _):
466 # letting JIT unroll the loop is *only* safe if the callsite didn't
467 # use **args because num_kwds can be arbitrarily large otherwise.
468 num_kwds = num_remainingkwds = len(keyword_names_w)
469 wrong_posonly = None
470 for i in range(num_kwds):
471 w_name = keyword_names_w[i]
472 assert w_name is not None
473 j = signature.find_w_argname(w_name)
474 if 0 <= j < co_posonlyargcount:
475 # we complain about a forbidden positional only keyword argument
476 # only if there is no **kwargs. otherwise, the keyword goes into
477 # the kwargs dict.
478 if signature.has_kwarg():
479 j = -1
480 else:
481 if wrong_posonly is None:
482 wrong_posonly = []
483 wrong_posonly.append(signature.argnames[j])
484 continue
485 if j < input_argcount:
486 # if j == -1 nothing happens, because j < input_argcount and
487 # blindargs > j
488
489 # check that no keyword argument conflicts with these. note
490 # that for this purpose we ignore the first blindargs,
491 # which were put into place by prepend(). This way,
492 # keywords do not conflict with the hidden extra argument
493 # bound by methods.
494 if blindargs <= j:
495 raise ArgErrMultipleValues(space.text_w(w_name))
496 else:
497 kwds_mapping[j - input_argcount] = i # map to the right index
498 num_remainingkwds -= 1
499 if wrong_posonly:
500 raise ArgErrPosonlyAsKwds(wrong_posonly)
501 return num_remainingkwds
502
503 @jit.look_inside_iff(
504 lambda space, keyword_names_w, keywords_w, w_kwds, kwds_mapping,
505 jiton: jiton)
506 def _collect_keyword_args(space, keyword_names_w, keywords_w, w_kwds,
507 kwds_mapping, _):
508 for i in range(len(keyword_names_w)):
509 # again a dangerous-looking loop that either the JIT unrolls
510 # or that is not too bad, because len(kwds_mapping) is small
511 for j in kwds_mapping:
512 if i == j:
513 break
514 else:
515 w_key = keyword_names_w[i]
516 space.setitem(w_kwds, w_key, keywords_w[i])
517
518 #
519 # ArgErr family of exceptions raised in case of argument mismatch.
520 # We try to give error messages following CPython's, which are very informative.
521 #
522
523 class ArgErr(Exception):
524
525 def getmsg(self):
526 raise NotImplementedError
527
528
529 class ArgErrMissing(ArgErr):
530 def __init__(self, missing, positional):
531 self.missing = missing
532 self.positional = positional # keyword-only otherwise
533
534 def getmsg(self):
535 arguments_str = StringBuilder()
536 for i, arg in enumerate(self.missing):
537 if i == 0:
538 pass
539 elif i == len(self.missing) - 1:
540 if len(self.missing) == 2:
541 arguments_str.append(" and ")
542 else:
543 arguments_str.append(", and ")
544 else:
545 arguments_str.append(", ")
546 arguments_str.append("'%s'" % arg)
547 msg = "missing %s required %s argument%s: %s" % (
548 len(self.missing),
549 "positional" if self.positional else "keyword-only",
550 "s" if len(self.missing) != 1 else "",
551 arguments_str.build())
552 return msg
553
554
555 class ArgErrTooMany(ArgErr):
556 def __init__(self, signature, num_defaults, given, kwonly_given):
557 self.signature = signature
558 self.num_defaults = num_defaults
559 self.given = given
560 self.kwonly_given = kwonly_given
561
562 def getmsg(self):
563 num_args = self.signature.num_argnames()
564 num_defaults = self.num_defaults
565 if num_defaults:
566 takes_str = "from %d to %d positional arguments" % (
567 num_args - num_defaults, num_args)
568 else:
569 takes_str = "%d positional argument%s" % (
570 num_args, "s" if num_args != 1 else "")
571 if self.kwonly_given:
572 given_str = ("%s positional argument%s "
573 "(and %s keyword-only argument%s) were") % (
574 self.given, "s" if self.given != 1 else "",
575 self.kwonly_given, "s" if self.kwonly_given != 1 else "")
576 else:
577 given_str = "%s %s" % (
578 self.given, "were" if self.given != 1 else "was")
579 msg = "takes %s but %s given" % (takes_str, given_str)
580 return msg
581
582 class ArgErrTooManyMethod(ArgErrTooMany):
583 """ A subclass of ArgErrCount that is used if the argument matching is done
584 as part of a method call, in which case more information is added to the
585 error message, if the cause of the error is likely a forgotten `self`
586 argument.
587 """
588
589 def getmsg(self):
590 msg = ArgErrTooMany.getmsg(self)
591 n = self.signature.num_argnames()
592 if (self.given == n + 1 and
593 (n == 0 or self.signature.argnames[0] != "self")):
594 msg += ". Did you forget 'self' in the function definition?"
595 return msg
596
597
598 class ArgErrMultipleValues(ArgErr):
599
600 def __init__(self, argname):
601 self.argname = argname
602
603 def getmsg(self):
604 msg = "got multiple values for argument '%s'" % self.argname
605 return msg
606
607 class ArgErrUnknownKwds(ArgErr):
608
609 def __init__(self, space, num_remainingkwds, keyword_names_w,
610 kwds_mapping):
611 name = ''
612 self.num_kwds = num_remainingkwds
613 if num_remainingkwds == 1:
614 for i in range(len(keyword_names_w)):
615 if i not in kwds_mapping:
616 name = space.text_w(keyword_names_w[i])
617 break
618 self.kwd_name = name
619
620 def getmsg(self):
621 if self.num_kwds == 1:
622 msg = "got an unexpected keyword argument '%s'" % (
623 self.kwd_name)
624 else:
625 msg = "got %d unexpected keyword arguments" % (
626 self.num_kwds)
627 return msg
628
629
630 class ArgErrPosonlyAsKwds(ArgErr):
631
632 def __init__(self, posonly_kwds):
633 self.posonly_kwds = posonly_kwds
634
635 def getmsg(self):
636 msg = ("got some positional-only arguments passed as keyword arguments: '%s'" % ", ".join(self.posonly_kwds))
637 return msg