Debian Codegraph @

resolve/resolve.go

raw
1 // Copyright 2017 The Bazel Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package resolve defines a name-resolution pass for Starlark abstract
6 // syntax trees.
7 //
8 // The resolver sets the Locals and FreeVars arrays of each DefStmt and
9 // the LocalIndex field of each syntax.Ident that refers to a local or
10 // free variable. It also sets the Locals array of a File for locals
11 // bound by top-level comprehensions and load statements.
12 // Identifiers for global variables do not get an index.
13 package resolve // import "go.starlark.net/resolve"
14
15 // All references to names are statically resolved. Names may be
16 // predeclared, global, or local to a function or file.
17 // File-local variables include those bound by top-level comprehensions
18 // and by load statements. ("Top-level" means "outside of any function".)
19 // The resolver maps each global name to a small integer and each local
20 // name to a small integer; these integers enable a fast and compact
21 // representation of globals and locals in the evaluator.
22 //
23 // As an optimization, the resolver classifies each predeclared name as
24 // either universal (e.g. None, len) or per-module (e.g. glob in Bazel's
25 // build language), enabling the evaluator to share the representation
26 // of the universal environment across all modules.
27 //
28 // The lexical environment is a tree of blocks with the file block at
29 // its root. The file's child blocks may be of two kinds: functions
30 // and comprehensions, and these may have further children of either
31 // kind.
32 //
33 // Python-style resolution requires multiple passes because a name is
34 // determined to be local to a function only if the function contains a
35 // "binding" use of it; similarly, a name is determined to be global (as
36 // opposed to predeclared) if the module contains a top-level binding use.
37 // Unlike ordinary top-level assignments, the bindings created by load
38 // statements are local to the file block.
39 // A non-binding use may lexically precede the binding to which it is resolved.
40 // In the first pass, we inspect each function, recording in
41 // 'uses' each identifier and the environment block in which it occurs.
42 // If a use of a name is binding, such as a function parameter or
43 // assignment, we add the name to the block's bindings mapping and add a
44 // local variable to the enclosing function.
45 //
46 // As we finish resolving each function, we inspect all the uses within
47 // that function and discard ones that were found to be function-local. The
48 // remaining ones must be either free (local to some lexically enclosing
49 // function), or top-level (global, predeclared, or file-local), but we cannot tell
50 // which until we have finished inspecting the outermost enclosing
51 // function. At that point, we can distinguish local from top-level names
52 // (and this is when Python would compute free variables).
53 //
54 // However, Starlark additionally requires that all references to global
55 // names are satisfied by some declaration in the current module;
56 // Starlark permits a function to forward-reference a global or file-local
57 // that has not
58 // been declared yet so long as it is declared before the end of the
59 // module. So, instead of re-resolving the unresolved references after
60 // each top-level function, we defer this until the end of the module
61 // and ensure that all such references are satisfied by some definition.
62 //
63 // At the end of the module, we visit each of the nested function blocks
64 // in bottom-up order, doing a recursive lexical lookup for each
65 // unresolved name. If the name is found to be local to some enclosing
66 // function, we must create a DefStmt.FreeVar (capture) parameter for
67 // each intervening function. We enter these synthetic bindings into
68 // the bindings map so that we create at most one freevar per name. If
69 // the name was not local, we check that it was defined at module level.
70 //
71 // We resolve all uses of locals in the module (due to load statements
72 // and comprehensions) in a similar way and compute the file's set of
73 // local variables.
74 //
75 // Starlark enforces that all global names are assigned at most once on
76 // all control flow paths by forbidding if/else statements and loops at
77 // top level. A global may be used before it is defined, leading to a
78 // dynamic error. However, the AllowGlobalReassign flag (really: allow
79 // top-level reassign) makes the resolver allow multiple to a variable
80 // at top-level. It also allows if-, for-, and while-loops at top-level,
81 // which in turn may make the evaluator dynamically assign multiple
82 // values to a variable at top-level. (These two roles should be separated.)
83
84 import (
85 "fmt"
86 "log"
87 "sort"
88 "strings"
89
90 "go.starlark.net/internal/spell"
91 "go.starlark.net/syntax"
92 )
93
94 const debug = false
95 const doesnt = "this Starlark dialect does not "
96
97 // Global options: these features are either not standard Starlark
98 // (yet), or deprecated features of the BUILD language, so we put them
99 // behind flags.
100 //
101 // Deprecated: use an explicit [syntax.FileOptions] argument instead,
102 // as it avoids all the usual problems of global variables,
103 // and permits finer control.
104 //
105 // For example The legacy AllowGlobalReassign flag controls three
106 // FileOptions: the availability of 'while' loops at all; the use of
107 // if/for/while constructs at top level; and the ability to reassign
108 // a global variable.
109 var (
110 AllowGlobalReassign = false // allow reassignment to top-level names; while loops; and if/for/while at top-level
111 AllowRecursion = false // allow recursive functions
112 LoadBindsGlobally = false // load creates global not file-local bindings (deprecated)
113
114 // obsolete flags for features that are now standard. No effect.
115 AllowBitwise = true
116 AllowFloat = true
117 AllowLambda = true
118 AllowNestedDef = true
119 AllowSet = true
120 )
121
122 // File resolves the specified file and records information about the
123 // module in file.Module.
124 //
125 // The isPredeclared and isUniversal predicates report whether a name is
126 // a pre-declared identifier (visible in the current module) or a
127 // universal identifier (visible in every module).
128 // Clients should typically pass predeclared.Has for the first and
129 // starlark.Universe.Has for the second, where predeclared is the
130 // module's StringDict of predeclared names and starlark.Universe is the
131 // standard set of built-ins.
132 // The isUniverse predicate is supplied a parameter to avoid a cyclic
133 // dependency upon starlark.Universe, not because users should ever need
134 // to redefine it.
135 func File(file *syntax.File, isPredeclared, isUniversal func(name string) bool) error {
136 return REPLChunk(file, nil, isPredeclared, isUniversal)
137 }
138
139 // REPLChunk is a generalization of the File function that supports a
140 // non-empty initial global block, as occurs in a REPL.
141 func REPLChunk(file *syntax.File, isGlobal, isPredeclared, isUniversal func(name string) bool) error {
142 r := newResolver(file.Options, isGlobal, isPredeclared, isUniversal)
143 r.stmts(file.Stmts)
144
145 r.env.resolveLocalUses()
146
147 // At the end of the module, resolve all non-local variable references,
148 // computing closures.
149 // Function bodies may contain forward references to later global declarations.
150 r.resolveNonLocalUses(r.env)
151
152 file.Module = &Module{
153 Locals: r.moduleLocals,
154 Globals: r.moduleGlobals,
155 }
156
157 if len(r.errors) > 0 {
158 return r.errors
159 }
160 return nil
161 }
162
163 // Expr calls [ExprOptions] using [syntax.LegacyFileOptions].
164 //
165 // Deprecated: use [ExprOptions] with [syntax.FileOptions] instead,
166 // because this function relies on legacy global variables.
167 func Expr(expr syntax.Expr, isPredeclared, isUniversal func(name string) bool) ([]*Binding, error) {
168 return ExprOptions(syntax.LegacyFileOptions(), expr, isPredeclared, isUniversal)
169 }
170
171 // ExprOptions resolves the specified expression.
172 // It returns the local variables bound within the expression.
173 //
174 // The isPredeclared and isUniversal predicates behave as for the File function
175 func ExprOptions(opts *syntax.FileOptions, expr syntax.Expr, isPredeclared, isUniversal func(name string) bool) ([]*Binding, error) {
176 r := newResolver(opts, nil, isPredeclared, isUniversal)
177 r.expr(expr)
178 r.env.resolveLocalUses()
179 r.resolveNonLocalUses(r.env) // globals & universals
180 if len(r.errors) > 0 {
181 return nil, r.errors
182 }
183 return r.moduleLocals, nil
184 }
185
186 // An ErrorList is a non-empty list of resolver error messages.
187 type ErrorList []Error // len > 0
188
189 func (e ErrorList) Error() string { return e[0].Error() }
190
191 // An Error describes the nature and position of a resolver error.
192 type Error struct {
193 Pos syntax.Position
194 Msg string
195 }
196
197 func (e Error) Error() string { return e.Pos.String() + ": " + e.Msg }
198
199 func newResolver(options *syntax.FileOptions, isGlobal, isPredeclared, isUniversal func(name string) bool) *resolver {
200 file := new(block)
201 return &resolver{
202 options: options,
203 file: file,
204 env: file,
205 isGlobal: isGlobal,
206 isPredeclared: isPredeclared,
207 isUniversal: isUniversal,
208 globals: make(map[string]*Binding),
209 predeclared: make(map[string]*Binding),
210 }
211 }
212
213 type resolver struct {
214 options *syntax.FileOptions
215
216 // env is the current local environment:
217 // a linked list of blocks, innermost first.
218 // The tail of the list is the file block.
219 env *block
220 file *block // file block (contains load bindings)
221
222 // moduleLocals contains the local variables of the module
223 // (due to load statements and comprehensions outside any function).
224 // moduleGlobals contains the global variables of the module.
225 moduleLocals []*Binding
226 moduleGlobals []*Binding
227
228 // globals maps each global name in the module to its binding.
229 // predeclared does the same for predeclared and universal names.
230 globals map[string]*Binding
231 predeclared map[string]*Binding
232
233 // These predicates report whether a name is
234 // pre-declared, either in this module or universally,
235 // or already declared in the module globals (as in a REPL).
236 // isGlobal may be nil.
237 isGlobal, isPredeclared, isUniversal func(name string) bool
238
239 loops int // number of enclosing for/while loops in current function (or file, if top-level)
240 ifstmts int // number of enclosing if statements loops
241
242 errors ErrorList
243 }
244
245 // container returns the innermost enclosing "container" block:
246 // a function (function != nil) or file (function == nil).
247 // Container blocks accumulate local variable bindings.
248 func (r *resolver) container() *block {
249 for b := r.env; ; b = b.parent {
250 if b.function != nil || b == r.file {
251 return b
252 }
253 }
254 }
255
256 func (r *resolver) push(b *block) {
257 r.env.children = append(r.env.children, b)
258 b.parent = r.env
259 r.env = b
260 }
261
262 func (r *resolver) pop() { r.env = r.env.parent }
263
264 type block struct {
265 parent *block // nil for file block
266
267 // In the file (root) block, both these fields are nil.
268 function *Function // only for function blocks
269 comp *syntax.Comprehension // only for comprehension blocks
270
271 // bindings maps a name to its binding.
272 // A local binding has an index into its innermost enclosing container's locals array.
273 // A free binding has an index into its innermost enclosing function's freevars array.
274 bindings map[string]*Binding
275
276 // children records the child blocks of the current one.
277 children []*block
278
279 // uses records all identifiers seen in this container (function or file),
280 // and a reference to the environment in which they appear.
281 // As we leave each container block, we resolve them,
282 // so that only free and global ones remain.
283 // At the end of each top-level function we compute closures.
284 uses []use
285 }
286
287 func (b *block) bind(name string, bind *Binding) {
288 if b.bindings == nil {
289 b.bindings = make(map[string]*Binding)
290 }
291 b.bindings[name] = bind
292 }
293
294 func (b *block) String() string {
295 if b.function != nil {
296 return "function block at " + fmt.Sprint(b.function.Pos)
297 }
298 if b.comp != nil {
299 return "comprehension block at " + fmt.Sprint(b.comp.Span())
300 }
301 return "file block"
302 }
303
304 func (r *resolver) errorf(posn syntax.Position, format string, args ...any) {
305 r.errors = append(r.errors, Error{posn, fmt.Sprintf(format, args...)})
306 }
307
308 // A use records an identifier and the environment in which it appears.
309 type use struct {
310 id *syntax.Ident
311 env *block
312 }
313
314 // bind creates a binding for id: a global (not file-local)
315 // binding at top-level, a local binding otherwise.
316 // At top-level, it reports an error if a global or file-local
317 // binding already exists, unless AllowGlobalReassign.
318 // It sets id.Binding to the binding (whether old or new),
319 // and returns whether a binding already existed.
320 func (r *resolver) bind(id *syntax.Ident) bool {
321 // Binding outside any local (comprehension/function) block?
322 if r.env == r.file {
323 bind, ok := r.file.bindings[id.Name]
324 if !ok {
325 bind, ok = r.globals[id.Name]
326 if !ok {
327 // first global binding of this name
328 bind = &Binding{
329 First: id,
330 Scope: Global,
331 Index: len(r.moduleGlobals),
332 }
333 r.globals[id.Name] = bind
334 r.moduleGlobals = append(r.moduleGlobals, bind)
335 }
336 }
337 if ok && !r.options.GlobalReassign {
338 r.errorf(id.NamePos, "cannot reassign %s %s declared at %s",
339 bind.Scope, id.Name, bind.First.NamePos)
340 }
341 id.Binding = bind
342 return ok
343 }
344
345 return r.bindLocal(id)
346 }
347
348 func (r *resolver) bindLocal(id *syntax.Ident) bool {
349 // Mark this name as local to current block.
350 // Assign it a new local (positive) index in the current container.
351 _, ok := r.env.bindings[id.Name]
352 if !ok {
353 var locals *[]*Binding
354 if fn := r.container().function; fn != nil {
355 locals = &fn.Locals
356 } else {
357 locals = &r.moduleLocals
358 }
359 bind := &Binding{
360 First: id,
361 Scope: Local,
362 Index: len(*locals),
363 }
364 r.env.bind(id.Name, bind)
365 *locals = append(*locals, bind)
366 }
367
368 r.use(id)
369 return ok
370 }
371
372 func (r *resolver) use(id *syntax.Ident) {
373 use := use{id, r.env}
374
375 // The spec says that if there is a global binding of a name
376 // then all references to that name in that block refer to the
377 // global, even if the use precedes the def---just as for locals.
378 // For example, in this code,
379 //
380 // print(len); len=1; print(len)
381 //
382 // both occurrences of len refer to the len=1 binding, which
383 // completely shadows the predeclared len function.
384 //
385 // The rationale for these semantics, which differ from Python,
386 // is that the static meaning of len (a reference to a global)
387 // does not change depending on where it appears in the file.
388 // Of course, its dynamic meaning does change, from an error
389 // into a valid reference, so it's not clear these semantics
390 // have any practical advantage.
391 //
392 // In any case, the Bazel implementation lags behind the spec
393 // and follows Python behavior, so the first use of len refers
394 // to the predeclared function. This typically used in a BUILD
395 // file that redefines a predeclared name half way through,
396 // for example:
397 //
398 // proto_library(...) # built-in rule
399 // load("myproto.bzl", "proto_library")
400 // proto_library(...) # user-defined rule
401 //
402 // We will piggyback support for the legacy semantics on the
403 // AllowGlobalReassign flag, which is loosely related and also
404 // required for Bazel.
405 if r.options.GlobalReassign && r.env == r.file {
406 r.useToplevel(use)
407 return
408 }
409
410 b := r.container()
411 b.uses = append(b.uses, use)
412 }
413
414 // useToplevel resolves use.id as a reference to a name visible at top-level.
415 // The use.env field captures the original environment for error reporting.
416 func (r *resolver) useToplevel(use use) (bind *Binding) {
417 id := use.id
418
419 if prev, ok := r.file.bindings[id.Name]; ok {
420 // use of load-defined name in file block
421 bind = prev
422 } else if prev, ok := r.globals[id.Name]; ok {
423 // use of global declared by module
424 bind = prev
425 } else if r.isGlobal != nil && r.isGlobal(id.Name) {
426 // use of global defined in a previous REPL chunk
427 bind = &Binding{
428 First: id, // wrong: this is not even a binding use
429 Scope: Global,
430 Index: len(r.moduleGlobals),
431 }
432 r.globals[id.Name] = bind
433 r.moduleGlobals = append(r.moduleGlobals, bind)
434 } else if prev, ok := r.predeclared[id.Name]; ok {
435 // repeated use of predeclared or universal
436 bind = prev
437 } else if r.isPredeclared(id.Name) {
438 // use of pre-declared name
439 bind = &Binding{Scope: Predeclared}
440 r.predeclared[id.Name] = bind // save it
441 } else if r.isUniversal(id.Name) {
442 // use of universal name
443 if !r.options.Set && id.Name == "set" {
444 r.errorf(id.NamePos, doesnt+"support sets")
445 }
446 bind = &Binding{Scope: Universal}
447 r.predeclared[id.Name] = bind // save it
448 } else {
449 bind = &Binding{Scope: Undefined}
450 var hint string
451 if n := r.spellcheck(use); n != "" {
452 hint = fmt.Sprintf(" (did you mean %s?)", n)
453 }
454 r.errorf(id.NamePos, "undefined: %s%s", id.Name, hint)
455 }
456 id.Binding = bind
457 return bind
458 }
459
460 // spellcheck returns the most likely misspelling of
461 // the name use.id in the environment use.env.
462 func (r *resolver) spellcheck(use use) string {
463 var names []string
464
465 // locals
466 for b := use.env; b != nil; b = b.parent {
467 for name := range b.bindings {
468 names = append(names, name)
469 }
470 }
471
472 // globals
473 //
474 // We have no way to enumerate the sets whose membership
475 // tests are isPredeclared, isUniverse, and isGlobal,
476 // which includes prior names in the REPL session.
477 for _, bind := range r.moduleGlobals {
478 names = append(names, bind.First.Name)
479 }
480
481 sort.Strings(names)
482 return spell.Nearest(use.id.Name, names)
483 }
484
485 // resolveLocalUses is called when leaving a container (function/module)
486 // block. It resolves all uses of locals/cells within that block.
487 func (b *block) resolveLocalUses() {
488 unresolved := b.uses[:0]
489 for _, use := range b.uses {
490 if bind := lookupLocal(use); bind != nil && (bind.Scope == Local || bind.Scope == Cell) {
491 use.id.Binding = bind
492 } else {
493 unresolved = append(unresolved, use)
494 }
495 }
496 b.uses = unresolved
497 }
498
499 func (r *resolver) stmts(stmts []syntax.Stmt) {
500 for _, stmt := range stmts {
501 r.stmt(stmt)
502 }
503 }
504
505 func (r *resolver) stmt(stmt syntax.Stmt) {
506 switch stmt := stmt.(type) {
507 case *syntax.ExprStmt:
508 r.expr(stmt.X)
509
510 case *syntax.BranchStmt:
511 if r.loops == 0 && (stmt.Token == syntax.BREAK || stmt.Token == syntax.CONTINUE) {
512 r.errorf(stmt.TokenPos, "%s not in a loop", stmt.Token)
513 }
514
515 case *syntax.IfStmt:
516 if !r.options.TopLevelControl && r.container().function == nil {
517 r.errorf(stmt.If, "if statement not within a function")
518 }
519 r.expr(stmt.Cond)
520 r.ifstmts++
521 r.stmts(stmt.True)
522 r.stmts(stmt.False)
523 r.ifstmts--
524
525 case *syntax.AssignStmt:
526 r.expr(stmt.RHS)
527 isAugmented := stmt.Op != syntax.EQ
528 r.assign(stmt.LHS, isAugmented)
529
530 case *syntax.DefStmt:
531 r.bind(stmt.Name)
532 fn := &Function{
533 Name: stmt.Name.Name,
534 Pos: stmt.Def,
535 Params: stmt.Params,
536 Body: stmt.Body,
537 }
538 stmt.Function = fn
539 r.function(fn, stmt.Def)
540
541 case *syntax.ForStmt:
542 if !r.options.TopLevelControl && r.container().function == nil {
543 r.errorf(stmt.For, "for loop not within a function")
544 }
545 r.expr(stmt.X)
546 const isAugmented = false
547 r.assign(stmt.Vars, isAugmented)
548 r.loops++
549 r.stmts(stmt.Body)
550 r.loops--
551
552 case *syntax.WhileStmt:
553 if !r.options.While {
554 r.errorf(stmt.While, doesnt+"support while loops")
555 }
556 if !r.options.TopLevelControl && r.container().function == nil {
557 r.errorf(stmt.While, "while loop not within a function")
558 }
559 r.expr(stmt.Cond)
560 r.loops++
561 r.stmts(stmt.Body)
562 r.loops--
563
564 case *syntax.ReturnStmt:
565 if r.container().function == nil {
566 r.errorf(stmt.Return, "return statement not within a function")
567 }
568 if stmt.Result != nil {
569 r.expr(stmt.Result)
570 }
571
572 case *syntax.LoadStmt:
573 // A load statement may not be nested in any other statement.
574 if r.container().function != nil {
575 r.errorf(stmt.Load, "load statement within a function")
576 } else if r.loops > 0 {
577 r.errorf(stmt.Load, "load statement within a loop")
578 } else if r.ifstmts > 0 {
579 r.errorf(stmt.Load, "load statement within a conditional")
580 }
581
582 for i, from := range stmt.From {
583 if from.Name == "" {
584 r.errorf(from.NamePos, "load: empty identifier")
585 continue
586 }
587 if from.Name[0] == '_' {
588 r.errorf(from.NamePos, "load: names with leading underscores are not exported: %s", from.Name)
589 }
590
591 id := stmt.To[i]
592 if r.options.LoadBindsGlobally {
593 r.bind(id)
594 } else if r.bindLocal(id) && !r.options.GlobalReassign {
595 // "Global" in AllowGlobalReassign is a misnomer for "toplevel".
596 // Sadly we can't report the previous declaration
597 // as id.Binding may not be set yet.
598 r.errorf(id.NamePos, "cannot reassign top-level %s", id.Name)
599 }
600 }
601
602 default:
603 log.Panicf("unexpected stmt %T", stmt)
604 }
605 }
606
607 func (r *resolver) assign(lhs syntax.Expr, isAugmented bool) {
608 switch lhs := lhs.(type) {
609 case *syntax.Ident:
610 // x = ...
611 r.bind(lhs)
612
613 case *syntax.IndexExpr:
614 // x[i] = ...
615 r.expr(lhs.X)
616 r.expr(lhs.Y)
617
618 case *syntax.DotExpr:
619 // x.f = ...
620 r.expr(lhs.X)
621
622 case *syntax.TupleExpr:
623 // (x, y) = ...
624 if isAugmented {
625 r.errorf(syntax.Start(lhs), "can't use tuple expression in augmented assignment")
626 }
627 for _, elem := range lhs.List {
628 r.assign(elem, isAugmented)
629 }
630
631 case *syntax.ListExpr:
632 // [x, y, z] = ...
633 if isAugmented {
634 r.errorf(syntax.Start(lhs), "can't use list expression in augmented assignment")
635 }
636 for _, elem := range lhs.List {
637 r.assign(elem, isAugmented)
638 }
639
640 case *syntax.ParenExpr:
641 r.assign(lhs.X, isAugmented)
642
643 default:
644 name := strings.ToLower(strings.TrimPrefix(fmt.Sprintf("%T", lhs), "*syntax."))
645 r.errorf(syntax.Start(lhs), "can't assign to %s", name)
646 }
647 }
648
649 func (r *resolver) expr(e syntax.Expr) {
650 switch e := e.(type) {
651 case *syntax.Ident:
652 r.use(e)
653
654 case *syntax.Literal:
655
656 case *syntax.ListExpr:
657 for _, x := range e.List {
658 r.expr(x)
659 }
660
661 case *syntax.CondExpr:
662 r.expr(e.Cond)
663 r.expr(e.True)
664 r.expr(e.False)
665
666 case *syntax.IndexExpr:
667 r.expr(e.X)
668 r.expr(e.Y)
669
670 case *syntax.DictEntry:
671 r.expr(e.Key)
672 r.expr(e.Value)
673
674 case *syntax.SliceExpr:
675 r.expr(e.X)
676 if e.Lo != nil {
677 r.expr(e.Lo)
678 }
679 if e.Hi != nil {
680 r.expr(e.Hi)
681 }
682 if e.Step != nil {
683 r.expr(e.Step)
684 }
685
686 case *syntax.Comprehension:
687 // The 'in' operand of the first clause (always a ForClause)
688 // is resolved in the outer block; consider: [x for x in x].
689 clause := e.Clauses[0].(*syntax.ForClause)
690 r.expr(clause.X)
691
692 // A list/dict comprehension defines a new lexical block.
693 // Locals defined within the block will be allotted
694 // distinct slots in the locals array of the innermost
695 // enclosing container (function/module) block.
696 r.push(&block{comp: e})
697
698 const isAugmented = false
699 r.assign(clause.Vars, isAugmented)
700
701 for _, clause := range e.Clauses[1:] {
702 switch clause := clause.(type) {
703 case *syntax.IfClause:
704 r.expr(clause.Cond)
705 case *syntax.ForClause:
706 r.assign(clause.Vars, isAugmented)
707 r.expr(clause.X)
708 }
709 }
710 r.expr(e.Body) // body may be *DictEntry
711 r.pop()
712
713 case *syntax.TupleExpr:
714 for _, x := range e.List {
715 r.expr(x)
716 }
717
718 case *syntax.DictExpr:
719 for _, entry := range e.List {
720 entry := entry.(*syntax.DictEntry)
721 r.expr(entry.Key)
722 r.expr(entry.Value)
723 }
724
725 case *syntax.UnaryExpr:
726 r.expr(e.X)
727
728 case *syntax.BinaryExpr:
729 r.expr(e.X)
730 r.expr(e.Y)
731
732 case *syntax.DotExpr:
733 r.expr(e.X)
734 // ignore e.Name
735
736 case *syntax.CallExpr:
737 r.expr(e.Fn)
738 var seenVarargs, seenKwargs bool
739 var seenName map[string]bool
740 var n, p int
741 for _, arg := range e.Args {
742 pos, _ := arg.Span()
743 if unop, ok := arg.(*syntax.UnaryExpr); ok && unop.Op == syntax.STARSTAR {
744 // **kwargs
745 if seenKwargs {
746 r.errorf(pos, "multiple **kwargs not allowed")
747 }
748 seenKwargs = true
749 r.expr(arg)
750 } else if ok && unop.Op == syntax.STAR {
751 // *args
752 if seenKwargs {
753 r.errorf(pos, "*args may not follow **kwargs")
754 } else if seenVarargs {
755 r.errorf(pos, "multiple *args not allowed")
756 }
757 seenVarargs = true
758 r.expr(arg)
759 } else if binop, ok := arg.(*syntax.BinaryExpr); ok && binop.Op == syntax.EQ {
760 // k=v
761 n++
762 if seenKwargs {
763 r.errorf(pos, "keyword argument may not follow **kwargs")
764 } else if seenVarargs {
765 r.errorf(pos, "keyword argument may not follow *args")
766 }
767 x := binop.X.(*syntax.Ident)
768 if seenName[x.Name] {
769 r.errorf(x.NamePos, "keyword argument %q is repeated", x.Name)
770 } else {
771 if seenName == nil {
772 seenName = make(map[string]bool)
773 }
774 seenName[x.Name] = true
775 }
776 r.expr(binop.Y)
777 } else {
778 // positional argument
779 p++
780 if seenVarargs {
781 r.errorf(pos, "positional argument may not follow *args")
782 } else if seenKwargs {
783 r.errorf(pos, "positional argument may not follow **kwargs")
784 } else if len(seenName) > 0 {
785 r.errorf(pos, "positional argument may not follow named")
786 }
787 r.expr(arg)
788 }
789 }
790
791 // Fail gracefully if compiler-imposed limit is exceeded.
792 if p >= 256 {
793 pos, _ := e.Span()
794 r.errorf(pos, "%v positional arguments in call, limit is 255", p)
795 }
796 if n >= 256 {
797 pos, _ := e.Span()
798 r.errorf(pos, "%v keyword arguments in call, limit is 255", n)
799 }
800
801 case *syntax.LambdaExpr:
802 fn := &Function{
803 Name: "lambda",
804 Pos: e.Lambda,
805 Params: e.Params,
806 Body: []syntax.Stmt{&syntax.ReturnStmt{Result: e.Body}},
807 }
808 e.Function = fn
809 r.function(fn, e.Lambda)
810
811 case *syntax.ParenExpr:
812 r.expr(e.X)
813
814 default:
815 log.Panicf("unexpected expr %T", e)
816 }
817 }
818
819 func (r *resolver) function(function *Function, pos syntax.Position) {
820 // Resolve defaults in enclosing environment.
821 for _, param := range function.Params {
822 if binary, ok := param.(*syntax.BinaryExpr); ok {
823 r.expr(binary.Y)
824 }
825 }
826
827 // Enter function block.
828 b := &block{function: function}
829 r.push(b)
830
831 // Save the current loop count and reset it for the new function
832 outerLoops := r.loops
833 r.loops = 0
834
835 var seenOptional bool
836 var star *syntax.UnaryExpr // * or *args param
837 var starStar *syntax.Ident // **kwargs ident
838 var numKwonlyParams int
839 for _, param := range function.Params {
840 switch param := param.(type) {
841 case *syntax.Ident:
842 // e.g. x
843 if starStar != nil {
844 r.errorf(param.NamePos, "required parameter may not follow **%s", starStar.Name)
845 } else if star != nil {
846 numKwonlyParams++
847 } else if seenOptional {
848 r.errorf(param.NamePos, "required parameter may not follow optional")
849 }
850 if r.bind(param) {
851 r.errorf(param.NamePos, "duplicate parameter: %s", param.Name)
852 }
853
854 case *syntax.BinaryExpr:
855 // e.g. y=dflt
856 if starStar != nil {
857 r.errorf(param.OpPos, "optional parameter may not follow **%s", starStar.Name)
858 } else if star != nil {
859 numKwonlyParams++
860 }
861 if id := param.X.(*syntax.Ident); r.bind(id) {
862 r.errorf(param.OpPos, "duplicate parameter: %s", id.Name)
863 }
864 seenOptional = true
865
866 case *syntax.UnaryExpr:
867 // * or *args or **kwargs
868 if param.Op == syntax.STAR {
869 if starStar != nil {
870 r.errorf(param.OpPos, "* parameter may not follow **%s", starStar.Name)
871 } else if star != nil {
872 r.errorf(param.OpPos, "multiple * parameters not allowed")
873 } else {
874 star = param
875 }
876 } else {
877 if starStar != nil {
878 r.errorf(param.OpPos, "multiple ** parameters not allowed")
879 }
880 starStar = param.X.(*syntax.Ident)
881 }
882 }
883 }
884
885 // Bind the *args and **kwargs parameters at the end,
886 // so that regular parameters a/b/c are contiguous and
887 // there is no hole for the "*":
888 // def f(a, b, *args, c=0, **kwargs)
889 // def f(a, b, *, c=0, **kwargs)
890 if star != nil {
891 if id, _ := star.X.(*syntax.Ident); id != nil {
892 // *args
893 if r.bind(id) {
894 r.errorf(id.NamePos, "duplicate parameter: %s", id.Name)
895 }
896 function.HasVarargs = true
897 } else if numKwonlyParams == 0 {
898 r.errorf(star.OpPos, "bare * must be followed by keyword-only parameters")
899 }
900 }
901 if starStar != nil {
902 if r.bind(starStar) {
903 r.errorf(starStar.NamePos, "duplicate parameter: %s", starStar.Name)
904 }
905 function.HasKwargs = true
906 }
907
908 function.NumKwonlyParams = numKwonlyParams
909 r.stmts(function.Body)
910
911 // Resolve all uses of this function's local vars,
912 // and keep just the remaining uses of free/global vars.
913 b.resolveLocalUses()
914
915 // Leave function block.
916 r.pop()
917
918 // Restore the outer loop count
919 r.loops = outerLoops
920
921 // References within the function body to globals are not
922 // resolved until the end of the module.
923 }
924
925 func (r *resolver) resolveNonLocalUses(b *block) {
926 // First resolve inner blocks.
927 for _, child := range b.children {
928 r.resolveNonLocalUses(child)
929 }
930 for _, use := range b.uses {
931 use.id.Binding = r.lookupLexical(use, use.env)
932 }
933 }
934
935 // lookupLocal looks up an identifier within its immediately enclosing function.
936 func lookupLocal(use use) *Binding {
937 for env := use.env; env != nil; env = env.parent {
938 if bind, ok := env.bindings[use.id.Name]; ok {
939 if bind.Scope == Free {
940 // shouldn't exist till later
941 log.Panicf("%s: internal error: %s, %v", use.id.NamePos, use.id.Name, bind)
942 }
943 return bind // found
944 }
945 if env.function != nil {
946 break
947 }
948 }
949 return nil // not found in this function
950 }
951
952 // lookupLexical looks up an identifier use.id within its lexically enclosing environment.
953 // The use.env field captures the original environment for error reporting.
954 func (r *resolver) lookupLexical(use use, env *block) (bind *Binding) {
955 if debug {
956 fmt.Printf("lookupLexical %s in %s = ...\n", use.id.Name, env)
957 defer func() { fmt.Printf("= %v\n", bind) }()
958 }
959
960 // Is this the file block?
961 if env == r.file {
962 return r.useToplevel(use) // file-local, global, predeclared, or not found
963 }
964
965 // Defined in this block?
966 bind, ok := env.bindings[use.id.Name]
967 if !ok {
968 // Defined in parent block?
969 bind = r.lookupLexical(use, env.parent)
970 if env.function != nil && (bind.Scope == Local || bind.Scope == Free || bind.Scope == Cell) {
971 // Found in parent block, which belongs to enclosing function.
972 // Add the parent's binding to the function's freevars,
973 // and add a new 'free' binding to the inner function's block,
974 // and turn the parent's local into cell.
975 if bind.Scope == Local {
976 bind.Scope = Cell
977 }
978 index := len(env.function.FreeVars)
979 env.function.FreeVars = append(env.function.FreeVars, bind)
980 bind = &Binding{
981 First: bind.First,
982 Scope: Free,
983 Index: index,
984 }
985 if debug {
986 fmt.Printf("creating freevar %v in function at %s: %s\n",
987 len(env.function.FreeVars), env.function.Pos, use.id.Name)
988 }
989 }
990
991 // Memoize, to avoid duplicate free vars
992 // and redundant global (failing) lookups.
993 env.bind(use.id.Name, bind)
994 }
995 return bind
996 }