Debian Codegraph @

rpython/annotator/argument.py

raw symbols SCIP
1 """
2 Arguments objects.
3 """
4 from rpython.annotator.model import SomeTuple
5 from rpython.flowspace.argument import CallSpec
6
7 class ArgumentsForTranslation(CallSpec):
8 @property
9 def positional_args(self):
10 if self.w_stararg is not None:
11 args_w = self.unpackiterable(self.w_stararg)
12 return self.arguments_w + args_w
13 else:
14 return self.arguments_w
15
16 def newtuple(self, items_s):
17 return SomeTuple(items_s)
18
19 def unpackiterable(self, s_obj):
20 assert isinstance(s_obj, SomeTuple)
21 return list(s_obj.items)
22
23 def fixedunpack(self, argcount):
24 """The simplest argument parsing: get the 'argcount' arguments,
25 or raise a real ValueError if the length is wrong."""
26 if self.keywords:
27 raise ValueError("no keyword arguments expected")
28 if len(self.arguments_w) > argcount:
29 raise ValueError("too many arguments (%d expected)" % argcount)
30 elif len(self.arguments_w) < argcount:
31 raise ValueError("not enough arguments (%d expected)" % argcount)
32 return self.arguments_w
33
34 def prepend(self, w_firstarg): # used often
35 "Return a new Arguments with a new argument inserted first."
36 return ArgumentsForTranslation([w_firstarg] + self.arguments_w,
37 self.keywords, self.w_stararg)
38
39 def copy(self):
40 return ArgumentsForTranslation(self.arguments_w, self.keywords,
41 self.w_stararg)
42
43 def _match_signature(self, scope_w, signature, defaults_w=None):
44 """Parse args and kwargs according to the signature of a code object,
45 or raise an ArgErr in case of failure.
46 """
47 # args_w = list of the normal actual parameters, wrapped
48 # scope_w = resulting list of wrapped values
49 #
50 co_argcount = signature.num_argnames() # expected formal arguments, without */**
51
52 args_w = self.positional_args
53 num_args = len(args_w)
54 keywords = self.keywords
55 num_kwds = len(keywords)
56
57 # put as many positional input arguments into place as available
58 take = min(num_args, co_argcount)
59 scope_w[:take] = args_w[:take]
60 input_argcount = take
61
62 # collect extra positional arguments into the *vararg
63 if signature.has_vararg():
64 if num_args > co_argcount:
65 starargs_w = args_w[co_argcount:]
66 else:
67 starargs_w = []
68 scope_w[co_argcount] = self.newtuple(starargs_w)
69 elif num_args > co_argcount:
70 raise ArgErrCount(num_args, num_kwds, signature, defaults_w, 0)
71
72 assert not signature.has_kwarg() # XXX should not happen?
73
74 # handle keyword arguments
75 num_remainingkwds = 0
76 kwds_mapping = None
77 if num_kwds:
78 # kwds_mapping maps target indexes in the scope (minus input_argcount)
79 # to keyword names
80 kwds_mapping = []
81 # match the keywords given at the call site to the argument names
82 # the called function takes
83 # this function must not take a scope_w, to make the scope not
84 # escape
85 num_remainingkwds = len(keywords)
86 for name in keywords:
87 j = signature.find_argname(name)
88 # if j == -1 nothing happens
89 if j < input_argcount:
90 # check that no keyword argument conflicts with these.
91 if j >= 0:
92 raise ArgErrMultipleValues(name)
93 else:
94 kwds_mapping.append(name)
95 num_remainingkwds -= 1
96
97 if num_remainingkwds:
98 if co_argcount == 0:
99 raise ArgErrCount(num_args, num_kwds, signature, defaults_w, 0)
100 raise ArgErrUnknownKwds(num_remainingkwds, keywords,
101 kwds_mapping)
102
103 # check for missing arguments and fill them from the kwds,
104 # or with defaults, if available
105 missing = 0
106 if input_argcount < co_argcount:
107 def_first = co_argcount - (0 if defaults_w is None else len(defaults_w))
108 j = 0
109 for i in range(input_argcount, co_argcount):
110 name = signature.argnames[i]
111 if name in keywords:
112 scope_w[i] = keywords[name]
113 continue
114 defnum = i - def_first
115 if defnum >= 0:
116 scope_w[i] = defaults_w[defnum]
117 else:
118 missing += 1
119 if missing:
120 raise ArgErrCount(num_args, num_kwds, signature, defaults_w, missing)
121
122 def unpack(self):
123 "Return a ([w1,w2...], {'kw':w3...}) pair."
124 return self.positional_args, self.keywords
125
126 def match_signature(self, signature, defaults_w):
127 """Parse args and kwargs according to the signature of a code object,
128 or raise an ArgErr in case of failure.
129 """
130 scopelen = signature.scope_length()
131 scope_w = [None] * scopelen
132 self._match_signature(scope_w, signature, defaults_w)
133 return scope_w
134
135 def unmatch_signature(self, signature, data_w):
136 """kind of inverse of match_signature"""
137 argnames, varargname, kwargname = signature
138 assert kwargname is None
139 cnt = len(argnames)
140 need_cnt = len(self.positional_args)
141 if varargname:
142 assert len(data_w) == cnt + 1
143 stararg_w = self.unpackiterable(data_w[cnt])
144 if stararg_w:
145 args_w = data_w[:cnt] + stararg_w
146 assert len(args_w) == need_cnt
147 assert not self.keywords
148 return ArgumentsForTranslation(args_w, {})
149 else:
150 data_w = data_w[:-1]
151 assert len(data_w) == cnt
152 assert len(data_w) >= need_cnt
153 args_w = data_w[:need_cnt]
154 _kwds_w = dict(zip(argnames[need_cnt:], data_w[need_cnt:]))
155 keywords_w = [_kwds_w[key] for key in self.keywords]
156 return ArgumentsForTranslation(args_w, dict(zip(self.keywords, keywords_w)))
157
158
159 def rawshape(args):
160 return args._rawshape()
161
162 def simple_args(args_s):
163 return ArgumentsForTranslation(list(args_s))
164
165 def complex_args(args_s):
166 return ArgumentsForTranslation.fromshape(args_s[0].const,
167 list(args_s[1:]))
168
169 #
170 # ArgErr family of exceptions raised in case of argument mismatch.
171 # We try to give error messages following CPython's, which are very informative.
172 #
173
174 class ArgErr(Exception):
175 def getmsg(self):
176 raise NotImplementedError
177
178
179 class ArgErrCount(ArgErr):
180 def __init__(self, got_nargs, nkwds, signature,
181 defaults_w, missing_args):
182 self.signature = signature
183
184 self.num_defaults = 0 if defaults_w is None else len(defaults_w)
185 self.missing_args = missing_args
186 self.num_args = got_nargs
187 self.num_kwds = nkwds
188
189 def getmsg(self):
190 n = self.signature.num_argnames()
191 if n == 0:
192 msg = "takes no arguments (%d given)" % (
193 self.num_args + self.num_kwds)
194 else:
195 defcount = self.num_defaults
196 has_kwarg = self.signature.has_kwarg()
197 num_args = self.num_args
198 num_kwds = self.num_kwds
199 if defcount == 0 and not self.signature.has_vararg():
200 msg1 = "exactly"
201 if not has_kwarg:
202 num_args += num_kwds
203 num_kwds = 0
204 elif not self.missing_args:
205 msg1 = "at most"
206 else:
207 msg1 = "at least"
208 has_kwarg = False
209 n -= defcount
210 if n == 1:
211 plural = ""
212 else:
213 plural = "s"
214 if has_kwarg or num_kwds > 0:
215 msg2 = " non-keyword"
216 else:
217 msg2 = ""
218 msg = "takes %s %d%s argument%s (%d given)" % (
219 msg1,
220 n,
221 msg2,
222 plural,
223 num_args)
224 return msg
225
226
227 class ArgErrMultipleValues(ArgErr):
228 def __init__(self, argname):
229 self.argname = argname
230
231 def getmsg(self):
232 msg = "got multiple values for keyword argument '%s'" % (
233 self.argname)
234 return msg
235
236
237 class ArgErrUnknownKwds(ArgErr):
238 def __init__(self, num_remainingkwds, keywords, kwds_mapping):
239 name = ''
240 self.num_kwds = num_remainingkwds
241 if num_remainingkwds == 1:
242 for name in keywords:
243 if name not in kwds_mapping:
244 break
245 self.kwd_name = name
246
247 def getmsg(self):
248 if self.num_kwds == 1:
249 msg = "got an unexpected keyword argument '%s'" % (
250 self.kwd_name)
251 else:
252 msg = "got %d unexpected keyword arguments" % (
253 self.num_kwds)
254 return msg