Debian Codegraph @

starlark/unpack.go

raw
1 package starlark
2
3 // This file defines the Unpack helper functions used by
4 // built-in functions to interpret their call arguments.
5
6 import (
7 "fmt"
8 "log"
9 "reflect"
10 "strings"
11 "unsafe"
12
13 "go.starlark.net/internal/spell"
14 )
15
16 // An Unpacker defines custom argument unpacking behavior.
17 // See UnpackArgs.
18 type Unpacker interface {
19 Unpack(v Value) error
20 }
21
22 // UnpackArgs unpacks the positional and keyword arguments into the
23 // supplied parameter variables. pairs is an alternating list of names
24 // and pointers to variables.
25 //
26 // If the variable is a bool, integer, string, *List, *Dict, Callable,
27 // Iterable, or user-defined implementation of Value,
28 // UnpackArgs performs the appropriate type check.
29 // Predeclared Go integer types use the AsInt check.
30 //
31 // If the parameter name ends with "?", it is optional.
32 //
33 // If the parameter name ends with "??", it is optional and treats the None value
34 // as if the argument was absent.
35 //
36 // If a parameter is marked optional, then all following parameters are
37 // implicitly optional whether or not they are marked.
38 //
39 // If the variable implements Unpacker, its Unpack argument
40 // is called with the argument value, allowing an application
41 // to define its own argument validation and conversion.
42 //
43 // If the variable implements Value, UnpackArgs may call
44 // its Type() method while constructing the error message.
45 //
46 // Examples:
47 //
48 // var (
49 // a Value
50 // b = MakeInt(42)
51 // c Value = starlark.None
52 // )
53 //
54 // // 1. mixed parameters, like def f(a, b=42, c=None).
55 // err := UnpackArgs("f", args, kwargs, "a", &a, "b?", &b, "c?", &c)
56 //
57 // // 2. keyword parameters only, like def f(*, a, b, c=None).
58 // if len(args) > 0 {
59 // return fmt.Errorf("f: unexpected positional arguments")
60 // }
61 // err := UnpackArgs("f", args, kwargs, "a", &a, "b?", &b, "c?", &c)
62 //
63 // // 3. positional parameters only, like def f(a, b=42, c=None, /) in Python 3.8.
64 // err := UnpackPositionalArgs("f", args, kwargs, 1, &a, &b, &c)
65 //
66 // More complex forms such as def f(a, b=42, *args, c, d=123, **kwargs)
67 // require additional logic, but their need in built-ins is exceedingly rare.
68 //
69 // In the examples above, the declaration of b with type Int causes UnpackArgs
70 // to require that b's argument value, if provided, is also an int.
71 // To allow arguments of any type, while retaining the default value of 42,
72 // declare b as a Value:
73 //
74 // var b Value = MakeInt(42)
75 //
76 // The zero value of a variable of type Value, such as 'a' in the
77 // examples above, is not a valid Starlark value, so if the parameter is
78 // optional, the caller must explicitly handle the default case by
79 // interpreting nil as None or some computed default. The same is true
80 // for the zero values of variables of type *List, *Dict, Callable, or
81 // Iterable. For example:
82 //
83 // // def myfunc(d=None, e=[], f={})
84 // var (
85 // d Value
86 // e *List
87 // f *Dict
88 // )
89 // err := UnpackArgs("myfunc", args, kwargs, "d?", &d, "e?", &e, "f?", &f)
90 // if d == nil { d = None; }
91 // if e == nil { e = new(List); }
92 // if f == nil { f = new(Dict); }
93 func UnpackArgs(fnname string, args Tuple, kwargs []Tuple, pairs ...any) error {
94 nparams := len(pairs) / 2
95 var defined intset
96 defined.init(nparams)
97
98 paramName := func(x any) (name string, skipNone bool) { // (no free variables)
99 name = x.(string)
100 if before, ok := strings.CutSuffix(name, "??"); ok {
101 name = before
102 skipNone = true
103 } else if name[len(name)-1] == '?' {
104 name = name[:len(name)-1]
105 }
106
107 return name, skipNone
108 }
109
110 // positional arguments
111 if len(args) > nparams {
112 return fmt.Errorf("%s: got %d arguments, want at most %d",
113 fnname, len(args), nparams)
114 }
115 for i, arg := range args {
116 defined.set(i)
117 name, skipNone := paramName(pairs[2*i])
118 if skipNone {
119 if _, isNone := arg.(NoneType); isNone {
120 continue
121 }
122 }
123 if err := UnpackArg(arg, pairs[2*i+1]); err != nil {
124 return fmt.Errorf("%s: for parameter %s: %s", fnname, name, err)
125 }
126 }
127
128 // keyword arguments
129 kwloop:
130 for _, item := range kwargs {
131 name, arg := item[0].(String), item[1]
132 for i := range nparams {
133 pName, skipNone := paramName(pairs[2*i])
134 if pName == string(name) {
135 // found it
136 if defined.set(i) {
137 return fmt.Errorf("%s: got multiple values for keyword argument %s",
138 fnname, name)
139 }
140
141 if skipNone {
142 if _, isNone := arg.(NoneType); isNone {
143 continue kwloop
144 }
145 }
146
147 ptr := pairs[2*i+1]
148 if err := UnpackArg(arg, ptr); err != nil {
149 return fmt.Errorf("%s: for parameter %s: %s", fnname, name, err)
150 }
151 continue kwloop
152 }
153 }
154 err := fmt.Errorf("%s: unexpected keyword argument %s", fnname, name)
155 names := make([]string, 0, nparams)
156 for i := 0; i < nparams; i += 2 {
157 param, _ := paramName(pairs[i])
158 names = append(names, param)
159 }
160 if n := spell.Nearest(string(name), names); n != "" {
161 err = fmt.Errorf("%s (did you mean %s?)", err.Error(), n)
162 }
163 return err
164 }
165
166 // Check that all non-optional parameters are defined.
167 for i := range nparams {
168 name := pairs[2*i].(string)
169 if strings.HasSuffix(name, "?") {
170 break // optional
171 }
172 // (We needn't check the first len(args).)
173 if i < len(args) {
174 continue
175 }
176 if !defined.get(i) {
177 return fmt.Errorf("%s: missing argument for %s", fnname, name)
178 }
179 }
180
181 return nil
182 }
183
184 // UnpackPositionalArgs unpacks the positional arguments into
185 // corresponding variables. Each element of vars is a pointer; see
186 // UnpackArgs for allowed types and conversions.
187 //
188 // UnpackPositionalArgs reports an error if the number of arguments is
189 // less than min or greater than len(vars), if kwargs is nonempty, or if
190 // any conversion fails.
191 //
192 // See UnpackArgs for general comments.
193 func UnpackPositionalArgs(fnname string, args Tuple, kwargs []Tuple, min int, vars ...any) error {
194 if err := checkPositionalArgs(fnname, args, kwargs, min, len(vars)); err != nil {
195 return err
196 }
197 for i, arg := range args {
198 if err := UnpackArg(arg, vars[i]); err != nil {
199 return fmt.Errorf("%s: for parameter %d: %s", fnname, i+1, err)
200 }
201 }
202 return nil
203 }
204
205 // unpackPositionalArgsNoEscape is an optimized version of [UnpackPositionalArgs].
206 // However, it panics if any vars[i] pointer value implements Unpacker.
207 func unpackPositionalArgsNoEscape(fnname string, args Tuple, kwargs []Tuple, min int, vars ...any) error {
208 if err := checkPositionalArgs(fnname, args, kwargs, min, len(vars)); err != nil {
209 return err
210 }
211 for i, arg := range args {
212 if err := unpackArgNoEscape(arg, vars[i]); err != nil {
213 return fmt.Errorf("%s: for parameter %d: %s", fnname, i+1, err)
214 }
215 }
216 return nil
217 }
218
219 func checkPositionalArgs(fnname string, args Tuple, kwargs []Tuple, min, max int) error {
220 if len(kwargs) > 0 {
221 return fmt.Errorf("%s: unexpected keyword arguments", fnname)
222 }
223 if len(args) < min {
224 var atleast string
225 if min < max {
226 atleast = "at least "
227 }
228 return fmt.Errorf("%s: got %d arguments, want %s%d", fnname, len(args), atleast, min)
229 }
230 if len(args) > max {
231 var atmost string
232 if max > min {
233 atmost = "at most "
234 }
235 return fmt.Errorf("%s: got %d arguments, want %s%d", fnname, len(args), atmost, max)
236 }
237 return nil
238 }
239
240 // UnpackArg unpacks a Value v into the variable pointed to by ptr.
241 // See [UnpackArgs] for details, including which types of variable are supported.
242 //
243 // This function defines the unpack operation for a single value.
244 // The implementations of most built-in functions use [UnpackArgs] and
245 // [UnpackPositionalArgs] to unpack a sequence of positional and/or
246 // keyword arguments.
247 func UnpackArg(v Value, ptr any) error {
248 if ptr, ok := ptr.(Unpacker); ok {
249 return ptr.Unpack(v) // (causes *ptr to escape)
250 }
251 return unpackArgNoEscape(v, ptr)
252 }
253
254 // unpackArgNoEscape is an optimized version of [UnpackArg].
255 // However, it panics if ptr implements Unpacker.
256 func unpackArgNoEscape(v Value, ptr any) error {
257 // Caution: do not let *ptr escape,
258 // e.g. via reflection or dynamic calls.
259 // There is a test of this invariant.
260
261 // On failure, don't clobber *ptr.
262 switch ptr := ptr.(type) {
263 case *Value:
264 *ptr = v
265 case *string:
266 s, ok := AsString(v)
267 if !ok {
268 return fmt.Errorf("got %s, want string", v.Type())
269 }
270 *ptr = s
271 case *bool:
272 b, ok := v.(Bool)
273 if !ok {
274 return fmt.Errorf("got %s, want bool", v.Type())
275 }
276 *ptr = bool(b)
277 case *int, *int8, *int16, *int32, *int64,
278 *uint, *uint8, *uint16, *uint32, *uint64, *uintptr:
279 return AsInt(v, ptr)
280 case *float64:
281 f, ok := v.(Float)
282 if !ok {
283 return fmt.Errorf("got %s, want float", v.Type())
284 }
285 *ptr = float64(f)
286 case **List:
287 list, ok := v.(*List)
288 if !ok {
289 return fmt.Errorf("got %s, want list", v.Type())
290 }
291 *ptr = list
292 case **Dict:
293 dict, ok := v.(*Dict)
294 if !ok {
295 return fmt.Errorf("got %s, want dict", v.Type())
296 }
297 *ptr = dict
298 case *Callable:
299 f, ok := v.(Callable)
300 if !ok {
301 return fmt.Errorf("got %s, want callable", v.Type())
302 }
303 *ptr = f
304 case *Iterable:
305 it, ok := v.(Iterable)
306 if !ok {
307 return fmt.Errorf("got %s, want iterable", v.Type())
308 }
309 *ptr = it
310 default:
311 // v must have type *V, where V is some subtype of starlark.Value.
312 ptrt := reflect.TypeOf(ptr)
313 if _, ok := ptr.(Unpacker); ok {
314 log.Panicf("unpackArgNoEscape does not support %s (Unpacker); use UnpackArg instead", ptrt)
315 }
316 if ptrt.Kind() != reflect.Pointer {
317 log.Panicf("internal error: not a pointer: %s", ptrt)
318 }
319 paramVarType := ptrt.Elem()
320 if !reflect.TypeOf(v).AssignableTo(paramVarType) {
321 // The value is not assignable to the variable.
322
323 // Detect a possible bug in the Go program that called Unpack:
324 // If the variable *ptr is not a subtype of Value,
325 // no value of v can possibly work.
326 if !paramVarType.AssignableTo(reflect.TypeFor[Value]()) {
327 log.Panicf("pointer element type does not implement Value: %s", ptrt)
328 }
329
330 // Report Starlark dynamic type error.
331 //
332 // We prefer the Starlark Value.Type name over
333 // its Go reflect.Type name, but calling the
334 // Value.Type method on the variable is not safe
335 // in general. If the variable is an interface,
336 // the call will fail. Even if the variable has
337 // a concrete type, it might not be safe to call
338 // Type() on a zero instance. Thus we must use
339 // recover.
340
341 // Default to Go reflect.Type name
342 paramType := paramVarType.String()
343
344 // Attempt to call Value.Type method on the zero
345 // value of the variable.
346 func() {
347 defer func() { recover() }()
348
349 if v, _ := reflect.Zero(paramVarType).Interface().(Value); v != nil {
350 paramType = v.Type()
351 }
352 }()
353 return fmt.Errorf("got %s, want %s", v.Type(), paramType)
354 }
355
356 // assign *ptr = v
357 reflectSetElem(ptr, reflect.ValueOf(v))
358 }
359 return nil
360 }
361
362 type intset struct {
363 small uint64 // bitset, used if n < 64
364 large map[int]bool // set, used if n >= 64
365 }
366
367 func (is *intset) init(n int) {
368 if n >= 64 {
369 is.large = make(map[int]bool)
370 }
371 }
372
373 func (is *intset) set(i int) (prev bool) {
374 if is.large == nil {
375 prev = is.small&(1<<uint(i)) != 0
376 is.small |= 1 << uint(i)
377 } else {
378 prev = is.large[i]
379 is.large[i] = true
380 }
381 return
382 }
383
384 func (is *intset) get(i int) bool {
385 if is.large == nil {
386 return is.small&(1<<uint(i)) != 0
387 }
388 return is.large[i]
389 }
390
391 func (is *intset) len() int {
392 if is.large == nil {
393 // Suboptimal, but used only for error reporting.
394 len := 0
395 for i := range 64 {
396 if is.small&(1<<uint(i)) != 0 {
397 len++
398 }
399 }
400 return len
401 }
402 return len(is.large)
403 }
404
405 // reflectSetElem is equivalent to reflect.ValueOf(ptr).Elem().Set(v)
406 // but does not let *ptr escape.
407 //
408 // ptr must be a non-nil pointer to a variable to which v may be assigned.
409 func reflectSetElem(ptr any, v reflect.Value) {
410 typ := reflect.TypeOf(ptr)
411 if typ.Kind() != reflect.Pointer {
412 panic("reflect: call of SetElem on non-pointer")
413 }
414 type eface struct{ typ, data unsafe.Pointer }
415 p := noescape((*eface)(unsafe.Pointer(&ptr)).data)
416 reflect.NewAt(typ.Elem(), p).Elem().Set(v)
417 }
418
419 // -- copied verbatim from abi.NoEscape --
420
421 // noescape hides the pointer p from escape analysis, preventing it
422 // from escaping to the heap. It compiles down to nothing.
423 //
424 // WARNING: This is very subtle to use correctly. The caller must
425 // ensure that it's truly safe for p to not escape to the heap by
426 // maintaining runtime pointer invariants (for example, that globals
427 // and the heap may not generally point into a stack).
428 //
429 //go:nosplit
430 //go:nocheckptr
431 func noescape(p unsafe.Pointer) unsafe.Pointer {
432 x := uintptr(p)
433 return unsafe.Pointer(x ^ 0)
434 }