]> Cypherpunks.ru repositories - gostls13.git/blob - src/cmd/compile/internal/noder/noder.go
[dev.regabi] cmd/compile: add Name.Canonical and move Byval
[gostls13.git] / src / cmd / compile / internal / noder / noder.go
1 // Copyright 2016 The Go 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 noder
6
7 import (
8         "fmt"
9         "go/constant"
10         "go/token"
11         "os"
12         "path/filepath"
13         "runtime"
14         "strconv"
15         "strings"
16         "unicode"
17         "unicode/utf8"
18
19         "cmd/compile/internal/base"
20         "cmd/compile/internal/ir"
21         "cmd/compile/internal/syntax"
22         "cmd/compile/internal/typecheck"
23         "cmd/compile/internal/types"
24         "cmd/internal/objabi"
25         "cmd/internal/src"
26 )
27
28 func LoadPackage(filenames []string) {
29         base.Timer.Start("fe", "parse")
30         lines := ParseFiles(filenames)
31         base.Timer.Stop()
32         base.Timer.AddEvent(int64(lines), "lines")
33
34         // Typecheck.
35         Package()
36
37         // With all user code typechecked, it's now safe to verify unused dot imports.
38         CheckDotImports()
39         base.ExitIfErrors()
40 }
41
42 // ParseFiles concurrently parses files into *syntax.File structures.
43 // Each declaration in every *syntax.File is converted to a syntax tree
44 // and its root represented by *Node is appended to Target.Decls.
45 // Returns the total count of parsed lines.
46 func ParseFiles(filenames []string) uint {
47         noders := make([]*noder, 0, len(filenames))
48         // Limit the number of simultaneously open files.
49         sem := make(chan struct{}, runtime.GOMAXPROCS(0)+10)
50
51         for _, filename := range filenames {
52                 p := &noder{
53                         basemap:     make(map[*syntax.PosBase]*src.PosBase),
54                         err:         make(chan syntax.Error),
55                         trackScopes: base.Flag.Dwarf,
56                 }
57                 noders = append(noders, p)
58
59                 go func(filename string) {
60                         sem <- struct{}{}
61                         defer func() { <-sem }()
62                         defer close(p.err)
63                         base := syntax.NewFileBase(filename)
64
65                         f, err := os.Open(filename)
66                         if err != nil {
67                                 p.error(syntax.Error{Msg: err.Error()})
68                                 return
69                         }
70                         defer f.Close()
71
72                         p.file, _ = syntax.Parse(base, f, p.error, p.pragma, syntax.CheckBranches) // errors are tracked via p.error
73                 }(filename)
74         }
75
76         var lines uint
77         for _, p := range noders {
78                 for e := range p.err {
79                         p.errorAt(e.Pos, "%s", e.Msg)
80                 }
81
82                 p.node()
83                 lines += p.file.Lines
84                 p.file = nil // release memory
85
86                 if base.SyntaxErrors() != 0 {
87                         base.ErrorExit()
88                 }
89                 // Always run testdclstack here, even when debug_dclstack is not set, as a sanity measure.
90                 types.CheckDclstack()
91         }
92
93         for _, p := range noders {
94                 p.processPragmas()
95         }
96
97         types.LocalPkg.Height = myheight
98
99         return lines
100 }
101
102 func Package() {
103         typecheck.DeclareUniverse()
104
105         typecheck.TypecheckAllowed = true
106
107         // Process top-level declarations in phases.
108
109         // Phase 1: const, type, and names and types of funcs.
110         //   This will gather all the information about types
111         //   and methods but doesn't depend on any of it.
112         //
113         //   We also defer type alias declarations until phase 2
114         //   to avoid cycles like #18640.
115         //   TODO(gri) Remove this again once we have a fix for #25838.
116
117         // Don't use range--typecheck can add closures to Target.Decls.
118         base.Timer.Start("fe", "typecheck", "top1")
119         for i := 0; i < len(typecheck.Target.Decls); i++ {
120                 n := typecheck.Target.Decls[i]
121                 if op := n.Op(); op != ir.ODCL && op != ir.OAS && op != ir.OAS2 && (op != ir.ODCLTYPE || !n.(*ir.Decl).X.Alias()) {
122                         typecheck.Target.Decls[i] = typecheck.Stmt(n)
123                 }
124         }
125
126         // Phase 2: Variable assignments.
127         //   To check interface assignments, depends on phase 1.
128
129         // Don't use range--typecheck can add closures to Target.Decls.
130         base.Timer.Start("fe", "typecheck", "top2")
131         for i := 0; i < len(typecheck.Target.Decls); i++ {
132                 n := typecheck.Target.Decls[i]
133                 if op := n.Op(); op == ir.ODCL || op == ir.OAS || op == ir.OAS2 || op == ir.ODCLTYPE && n.(*ir.Decl).X.Alias() {
134                         typecheck.Target.Decls[i] = typecheck.Stmt(n)
135                 }
136         }
137
138         // Phase 3: Type check function bodies.
139         // Don't use range--typecheck can add closures to Target.Decls.
140         base.Timer.Start("fe", "typecheck", "func")
141         var fcount int64
142         for i := 0; i < len(typecheck.Target.Decls); i++ {
143                 n := typecheck.Target.Decls[i]
144                 if n.Op() == ir.ODCLFUNC {
145                         typecheck.FuncBody(n.(*ir.Func))
146                         fcount++
147                 }
148         }
149
150         // Phase 4: Check external declarations.
151         // TODO(mdempsky): This should be handled when type checking their
152         // corresponding ODCL nodes.
153         base.Timer.Start("fe", "typecheck", "externdcls")
154         for i, n := range typecheck.Target.Externs {
155                 if n.Op() == ir.ONAME {
156                         typecheck.Target.Externs[i] = typecheck.Expr(typecheck.Target.Externs[i])
157                 }
158         }
159
160         // Phase 5: With all user code type-checked, it's now safe to verify map keys.
161         typecheck.CheckMapKeys()
162
163 }
164
165 // makeSrcPosBase translates from a *syntax.PosBase to a *src.PosBase.
166 func (p *noder) makeSrcPosBase(b0 *syntax.PosBase) *src.PosBase {
167         // fast path: most likely PosBase hasn't changed
168         if p.basecache.last == b0 {
169                 return p.basecache.base
170         }
171
172         b1, ok := p.basemap[b0]
173         if !ok {
174                 fn := b0.Filename()
175                 if b0.IsFileBase() {
176                         b1 = src.NewFileBase(fn, absFilename(fn))
177                 } else {
178                         // line directive base
179                         p0 := b0.Pos()
180                         p0b := p0.Base()
181                         if p0b == b0 {
182                                 panic("infinite recursion in makeSrcPosBase")
183                         }
184                         p1 := src.MakePos(p.makeSrcPosBase(p0b), p0.Line(), p0.Col())
185                         b1 = src.NewLinePragmaBase(p1, fn, fileh(fn), b0.Line(), b0.Col())
186                 }
187                 p.basemap[b0] = b1
188         }
189
190         // update cache
191         p.basecache.last = b0
192         p.basecache.base = b1
193
194         return b1
195 }
196
197 func (p *noder) makeXPos(pos syntax.Pos) (_ src.XPos) {
198         return base.Ctxt.PosTable.XPos(src.MakePos(p.makeSrcPosBase(pos.Base()), pos.Line(), pos.Col()))
199 }
200
201 func (p *noder) errorAt(pos syntax.Pos, format string, args ...interface{}) {
202         base.ErrorfAt(p.makeXPos(pos), format, args...)
203 }
204
205 // TODO(gri) Can we eliminate fileh in favor of absFilename?
206 func fileh(name string) string {
207         return objabi.AbsFile("", name, base.Flag.TrimPath)
208 }
209
210 func absFilename(name string) string {
211         return objabi.AbsFile(base.Ctxt.Pathname, name, base.Flag.TrimPath)
212 }
213
214 // noder transforms package syntax's AST into a Node tree.
215 type noder struct {
216         basemap   map[*syntax.PosBase]*src.PosBase
217         basecache struct {
218                 last *syntax.PosBase
219                 base *src.PosBase
220         }
221
222         file           *syntax.File
223         linknames      []linkname
224         pragcgobuf     [][]string
225         err            chan syntax.Error
226         scope          ir.ScopeID
227         importedUnsafe bool
228         importedEmbed  bool
229
230         // scopeVars is a stack tracking the number of variables declared in the
231         // current function at the moment each open scope was opened.
232         trackScopes bool
233         scopeVars   []int
234
235         lastCloseScopePos syntax.Pos
236 }
237
238 func (p *noder) funcBody(fn *ir.Func, block *syntax.BlockStmt) {
239         oldScope := p.scope
240         p.scope = 0
241         typecheck.StartFuncBody(fn)
242
243         if block != nil {
244                 body := p.stmts(block.List)
245                 if body == nil {
246                         body = []ir.Node{ir.NewBlockStmt(base.Pos, nil)}
247                 }
248                 fn.Body = body
249
250                 base.Pos = p.makeXPos(block.Rbrace)
251                 fn.Endlineno = base.Pos
252         }
253
254         typecheck.FinishFuncBody()
255         p.scope = oldScope
256 }
257
258 func (p *noder) openScope(pos syntax.Pos) {
259         types.Markdcl()
260
261         if p.trackScopes {
262                 ir.CurFunc.Parents = append(ir.CurFunc.Parents, p.scope)
263                 p.scopeVars = append(p.scopeVars, len(ir.CurFunc.Dcl))
264                 p.scope = ir.ScopeID(len(ir.CurFunc.Parents))
265
266                 p.markScope(pos)
267         }
268 }
269
270 func (p *noder) closeScope(pos syntax.Pos) {
271         p.lastCloseScopePos = pos
272         types.Popdcl()
273
274         if p.trackScopes {
275                 scopeVars := p.scopeVars[len(p.scopeVars)-1]
276                 p.scopeVars = p.scopeVars[:len(p.scopeVars)-1]
277                 if scopeVars == len(ir.CurFunc.Dcl) {
278                         // no variables were declared in this scope, so we can retract it.
279
280                         if int(p.scope) != len(ir.CurFunc.Parents) {
281                                 base.Fatalf("scope tracking inconsistency, no variables declared but scopes were not retracted")
282                         }
283
284                         p.scope = ir.CurFunc.Parents[p.scope-1]
285                         ir.CurFunc.Parents = ir.CurFunc.Parents[:len(ir.CurFunc.Parents)-1]
286
287                         nmarks := len(ir.CurFunc.Marks)
288                         ir.CurFunc.Marks[nmarks-1].Scope = p.scope
289                         prevScope := ir.ScopeID(0)
290                         if nmarks >= 2 {
291                                 prevScope = ir.CurFunc.Marks[nmarks-2].Scope
292                         }
293                         if ir.CurFunc.Marks[nmarks-1].Scope == prevScope {
294                                 ir.CurFunc.Marks = ir.CurFunc.Marks[:nmarks-1]
295                         }
296                         return
297                 }
298
299                 p.scope = ir.CurFunc.Parents[p.scope-1]
300
301                 p.markScope(pos)
302         }
303 }
304
305 func (p *noder) markScope(pos syntax.Pos) {
306         xpos := p.makeXPos(pos)
307         if i := len(ir.CurFunc.Marks); i > 0 && ir.CurFunc.Marks[i-1].Pos == xpos {
308                 ir.CurFunc.Marks[i-1].Scope = p.scope
309         } else {
310                 ir.CurFunc.Marks = append(ir.CurFunc.Marks, ir.Mark{Pos: xpos, Scope: p.scope})
311         }
312 }
313
314 // closeAnotherScope is like closeScope, but it reuses the same mark
315 // position as the last closeScope call. This is useful for "for" and
316 // "if" statements, as their implicit blocks always end at the same
317 // position as an explicit block.
318 func (p *noder) closeAnotherScope() {
319         p.closeScope(p.lastCloseScopePos)
320 }
321
322 // linkname records a //go:linkname directive.
323 type linkname struct {
324         pos    syntax.Pos
325         local  string
326         remote string
327 }
328
329 func (p *noder) node() {
330         types.Block = 1
331         p.importedUnsafe = false
332         p.importedEmbed = false
333
334         p.setlineno(p.file.PkgName)
335         mkpackage(p.file.PkgName.Value)
336
337         if pragma, ok := p.file.Pragma.(*pragmas); ok {
338                 pragma.Flag &^= ir.GoBuildPragma
339                 p.checkUnused(pragma)
340         }
341
342         typecheck.Target.Decls = append(typecheck.Target.Decls, p.decls(p.file.DeclList)...)
343
344         base.Pos = src.NoXPos
345         clearImports()
346 }
347
348 func (p *noder) processPragmas() {
349         for _, l := range p.linknames {
350                 if !p.importedUnsafe {
351                         p.errorAt(l.pos, "//go:linkname only allowed in Go files that import \"unsafe\"")
352                         continue
353                 }
354                 n := ir.AsNode(typecheck.Lookup(l.local).Def)
355                 if n == nil || n.Op() != ir.ONAME {
356                         // TODO(mdempsky): Change to p.errorAt before Go 1.17 release.
357                         // base.WarnfAt(p.makeXPos(l.pos), "//go:linkname must refer to declared function or variable (will be an error in Go 1.17)")
358                         continue
359                 }
360                 if n.Sym().Linkname != "" {
361                         p.errorAt(l.pos, "duplicate //go:linkname for %s", l.local)
362                         continue
363                 }
364                 n.Sym().Linkname = l.remote
365         }
366         typecheck.Target.CgoPragmas = append(typecheck.Target.CgoPragmas, p.pragcgobuf...)
367 }
368
369 func (p *noder) decls(decls []syntax.Decl) (l []ir.Node) {
370         var cs constState
371
372         for _, decl := range decls {
373                 p.setlineno(decl)
374                 switch decl := decl.(type) {
375                 case *syntax.ImportDecl:
376                         p.importDecl(decl)
377
378                 case *syntax.VarDecl:
379                         l = append(l, p.varDecl(decl)...)
380
381                 case *syntax.ConstDecl:
382                         l = append(l, p.constDecl(decl, &cs)...)
383
384                 case *syntax.TypeDecl:
385                         l = append(l, p.typeDecl(decl))
386
387                 case *syntax.FuncDecl:
388                         l = append(l, p.funcDecl(decl))
389
390                 default:
391                         panic("unhandled Decl")
392                 }
393         }
394
395         return
396 }
397
398 func (p *noder) importDecl(imp *syntax.ImportDecl) {
399         if imp.Path.Bad {
400                 return // avoid follow-on errors if there was a syntax error
401         }
402
403         if pragma, ok := imp.Pragma.(*pragmas); ok {
404                 p.checkUnused(pragma)
405         }
406
407         ipkg := importfile(p.basicLit(imp.Path))
408         if ipkg == nil {
409                 if base.Errors() == 0 {
410                         base.Fatalf("phase error in import")
411                 }
412                 return
413         }
414
415         if ipkg == ir.Pkgs.Unsafe {
416                 p.importedUnsafe = true
417         }
418         if ipkg.Path == "embed" {
419                 p.importedEmbed = true
420         }
421
422         if !ipkg.Direct {
423                 typecheck.Target.Imports = append(typecheck.Target.Imports, ipkg)
424         }
425         ipkg.Direct = true
426
427         var my *types.Sym
428         if imp.LocalPkgName != nil {
429                 my = p.name(imp.LocalPkgName)
430         } else {
431                 my = typecheck.Lookup(ipkg.Name)
432         }
433
434         pack := ir.NewPkgName(p.pos(imp), my, ipkg)
435
436         switch my.Name {
437         case ".":
438                 importDot(pack)
439                 return
440         case "init":
441                 base.ErrorfAt(pack.Pos(), "cannot import package as init - init must be a func")
442                 return
443         case "_":
444                 return
445         }
446         if my.Def != nil {
447                 typecheck.Redeclared(pack.Pos(), my, "as imported package name")
448         }
449         my.Def = pack
450         my.Lastlineno = pack.Pos()
451         my.Block = 1 // at top level
452 }
453
454 func (p *noder) varDecl(decl *syntax.VarDecl) []ir.Node {
455         names := p.declNames(ir.ONAME, decl.NameList)
456         typ := p.typeExprOrNil(decl.Type)
457         exprs := p.exprList(decl.Values)
458
459         if pragma, ok := decl.Pragma.(*pragmas); ok {
460                 if len(pragma.Embeds) > 0 {
461                         if !p.importedEmbed {
462                                 // This check can't be done when building the list pragma.Embeds
463                                 // because that list is created before the noder starts walking over the file,
464                                 // so at that point it hasn't seen the imports.
465                                 // We're left to check now, just before applying the //go:embed lines.
466                                 for _, e := range pragma.Embeds {
467                                         p.errorAt(e.Pos, "//go:embed only allowed in Go files that import \"embed\"")
468                                 }
469                         } else {
470                                 exprs = varEmbed(p, names, typ, exprs, pragma.Embeds)
471                         }
472                         pragma.Embeds = nil
473                 }
474                 p.checkUnused(pragma)
475         }
476
477         var init []ir.Node
478         p.setlineno(decl)
479
480         if len(names) > 1 && len(exprs) == 1 {
481                 as2 := ir.NewAssignListStmt(base.Pos, ir.OAS2, nil, exprs)
482                 for _, v := range names {
483                         as2.Lhs.Append(v)
484                         typecheck.Declare(v, typecheck.DeclContext)
485                         v.Ntype = typ
486                         v.Defn = as2
487                         if ir.CurFunc != nil {
488                                 init = append(init, ir.NewDecl(base.Pos, ir.ODCL, v))
489                         }
490                 }
491
492                 return append(init, as2)
493         }
494
495         for i, v := range names {
496                 var e ir.Node
497                 if i < len(exprs) {
498                         e = exprs[i]
499                 }
500
501                 typecheck.Declare(v, typecheck.DeclContext)
502                 v.Ntype = typ
503
504                 if ir.CurFunc != nil {
505                         init = append(init, ir.NewDecl(base.Pos, ir.ODCL, v))
506                 }
507                 as := ir.NewAssignStmt(base.Pos, v, e)
508                 init = append(init, as)
509                 if e != nil || ir.CurFunc == nil {
510                         v.Defn = as
511                 }
512         }
513
514         if len(exprs) != 0 && len(names) != len(exprs) {
515                 base.Errorf("assignment mismatch: %d variables but %d values", len(names), len(exprs))
516         }
517
518         return init
519 }
520
521 // constState tracks state between constant specifiers within a
522 // declaration group. This state is kept separate from noder so nested
523 // constant declarations are handled correctly (e.g., issue 15550).
524 type constState struct {
525         group  *syntax.Group
526         typ    ir.Ntype
527         values []ir.Node
528         iota   int64
529 }
530
531 func (p *noder) constDecl(decl *syntax.ConstDecl, cs *constState) []ir.Node {
532         if decl.Group == nil || decl.Group != cs.group {
533                 *cs = constState{
534                         group: decl.Group,
535                 }
536         }
537
538         if pragma, ok := decl.Pragma.(*pragmas); ok {
539                 p.checkUnused(pragma)
540         }
541
542         names := p.declNames(ir.OLITERAL, decl.NameList)
543         typ := p.typeExprOrNil(decl.Type)
544
545         var values []ir.Node
546         if decl.Values != nil {
547                 values = p.exprList(decl.Values)
548                 cs.typ, cs.values = typ, values
549         } else {
550                 if typ != nil {
551                         base.Errorf("const declaration cannot have type without expression")
552                 }
553                 typ, values = cs.typ, cs.values
554         }
555
556         nn := make([]ir.Node, 0, len(names))
557         for i, n := range names {
558                 if i >= len(values) {
559                         base.Errorf("missing value in const declaration")
560                         break
561                 }
562                 v := values[i]
563                 if decl.Values == nil {
564                         v = ir.DeepCopy(n.Pos(), v)
565                 }
566                 typecheck.Declare(n, typecheck.DeclContext)
567
568                 n.Ntype = typ
569                 n.Defn = v
570                 n.SetIota(cs.iota)
571
572                 nn = append(nn, ir.NewDecl(p.pos(decl), ir.ODCLCONST, n))
573         }
574
575         if len(values) > len(names) {
576                 base.Errorf("extra expression in const declaration")
577         }
578
579         cs.iota++
580
581         return nn
582 }
583
584 func (p *noder) typeDecl(decl *syntax.TypeDecl) ir.Node {
585         n := p.declName(ir.OTYPE, decl.Name)
586         typecheck.Declare(n, typecheck.DeclContext)
587
588         // decl.Type may be nil but in that case we got a syntax error during parsing
589         typ := p.typeExprOrNil(decl.Type)
590
591         n.Ntype = typ
592         n.SetAlias(decl.Alias)
593         if pragma, ok := decl.Pragma.(*pragmas); ok {
594                 if !decl.Alias {
595                         n.SetPragma(pragma.Flag & typePragmas)
596                         pragma.Flag &^= typePragmas
597                 }
598                 p.checkUnused(pragma)
599         }
600
601         nod := ir.NewDecl(p.pos(decl), ir.ODCLTYPE, n)
602         if n.Alias() && !types.AllowsGoVersion(types.LocalPkg, 1, 9) {
603                 base.ErrorfAt(nod.Pos(), "type aliases only supported as of -lang=go1.9")
604         }
605         return nod
606 }
607
608 func (p *noder) declNames(op ir.Op, names []*syntax.Name) []*ir.Name {
609         nodes := make([]*ir.Name, 0, len(names))
610         for _, name := range names {
611                 nodes = append(nodes, p.declName(op, name))
612         }
613         return nodes
614 }
615
616 func (p *noder) declName(op ir.Op, name *syntax.Name) *ir.Name {
617         return ir.NewDeclNameAt(p.pos(name), op, p.name(name))
618 }
619
620 func (p *noder) funcDecl(fun *syntax.FuncDecl) ir.Node {
621         name := p.name(fun.Name)
622         t := p.signature(fun.Recv, fun.Type)
623         f := ir.NewFunc(p.pos(fun))
624
625         if fun.Recv == nil {
626                 if name.Name == "init" {
627                         name = renameinit()
628                         if len(t.Params) > 0 || len(t.Results) > 0 {
629                                 base.ErrorfAt(f.Pos(), "func init must have no arguments and no return values")
630                         }
631                         typecheck.Target.Inits = append(typecheck.Target.Inits, f)
632                 }
633
634                 if types.LocalPkg.Name == "main" && name.Name == "main" {
635                         if len(t.Params) > 0 || len(t.Results) > 0 {
636                                 base.ErrorfAt(f.Pos(), "func main must have no arguments and no return values")
637                         }
638                 }
639         } else {
640                 f.Shortname = name
641                 name = ir.BlankNode.Sym() // filled in by typecheckfunc
642         }
643
644         f.Nname = ir.NewNameAt(p.pos(fun.Name), name)
645         f.Nname.Func = f
646         f.Nname.Defn = f
647         f.Nname.Ntype = t
648
649         if pragma, ok := fun.Pragma.(*pragmas); ok {
650                 f.Pragma = pragma.Flag & funcPragmas
651                 if pragma.Flag&ir.Systemstack != 0 && pragma.Flag&ir.Nosplit != 0 {
652                         base.ErrorfAt(f.Pos(), "go:nosplit and go:systemstack cannot be combined")
653                 }
654                 pragma.Flag &^= funcPragmas
655                 p.checkUnused(pragma)
656         }
657
658         if fun.Recv == nil {
659                 typecheck.Declare(f.Nname, ir.PFUNC)
660         }
661
662         p.funcBody(f, fun.Body)
663
664         if fun.Body != nil {
665                 if f.Pragma&ir.Noescape != 0 {
666                         base.ErrorfAt(f.Pos(), "can only use //go:noescape with external func implementations")
667                 }
668         } else {
669                 if base.Flag.Complete || strings.HasPrefix(ir.FuncName(f), "init.") {
670                         // Linknamed functions are allowed to have no body. Hopefully
671                         // the linkname target has a body. See issue 23311.
672                         isLinknamed := false
673                         for _, n := range p.linknames {
674                                 if ir.FuncName(f) == n.local {
675                                         isLinknamed = true
676                                         break
677                                 }
678                         }
679                         if !isLinknamed {
680                                 base.ErrorfAt(f.Pos(), "missing function body")
681                         }
682                 }
683         }
684
685         return f
686 }
687
688 func (p *noder) signature(recv *syntax.Field, typ *syntax.FuncType) *ir.FuncType {
689         var rcvr *ir.Field
690         if recv != nil {
691                 rcvr = p.param(recv, false, false)
692         }
693         return ir.NewFuncType(p.pos(typ), rcvr,
694                 p.params(typ.ParamList, true),
695                 p.params(typ.ResultList, false))
696 }
697
698 func (p *noder) params(params []*syntax.Field, dddOk bool) []*ir.Field {
699         nodes := make([]*ir.Field, 0, len(params))
700         for i, param := range params {
701                 p.setlineno(param)
702                 nodes = append(nodes, p.param(param, dddOk, i+1 == len(params)))
703         }
704         return nodes
705 }
706
707 func (p *noder) param(param *syntax.Field, dddOk, final bool) *ir.Field {
708         var name *types.Sym
709         if param.Name != nil {
710                 name = p.name(param.Name)
711         }
712
713         typ := p.typeExpr(param.Type)
714         n := ir.NewField(p.pos(param), name, typ, nil)
715
716         // rewrite ...T parameter
717         if typ, ok := typ.(*ir.SliceType); ok && typ.DDD {
718                 if !dddOk {
719                         // We mark these as syntax errors to get automatic elimination
720                         // of multiple such errors per line (see ErrorfAt in subr.go).
721                         base.Errorf("syntax error: cannot use ... in receiver or result parameter list")
722                 } else if !final {
723                         if param.Name == nil {
724                                 base.Errorf("syntax error: cannot use ... with non-final parameter")
725                         } else {
726                                 p.errorAt(param.Name.Pos(), "syntax error: cannot use ... with non-final parameter %s", param.Name.Value)
727                         }
728                 }
729                 typ.DDD = false
730                 n.IsDDD = true
731         }
732
733         return n
734 }
735
736 func (p *noder) exprList(expr syntax.Expr) []ir.Node {
737         switch expr := expr.(type) {
738         case nil:
739                 return nil
740         case *syntax.ListExpr:
741                 return p.exprs(expr.ElemList)
742         default:
743                 return []ir.Node{p.expr(expr)}
744         }
745 }
746
747 func (p *noder) exprs(exprs []syntax.Expr) []ir.Node {
748         nodes := make([]ir.Node, 0, len(exprs))
749         for _, expr := range exprs {
750                 nodes = append(nodes, p.expr(expr))
751         }
752         return nodes
753 }
754
755 func (p *noder) expr(expr syntax.Expr) ir.Node {
756         p.setlineno(expr)
757         switch expr := expr.(type) {
758         case nil, *syntax.BadExpr:
759                 return nil
760         case *syntax.Name:
761                 return p.mkname(expr)
762         case *syntax.BasicLit:
763                 n := ir.NewBasicLit(p.pos(expr), p.basicLit(expr))
764                 if expr.Kind == syntax.RuneLit {
765                         n.SetType(types.UntypedRune)
766                 }
767                 n.SetDiag(expr.Bad) // avoid follow-on errors if there was a syntax error
768                 return n
769         case *syntax.CompositeLit:
770                 n := ir.NewCompLitExpr(p.pos(expr), ir.OCOMPLIT, p.typeExpr(expr.Type), nil)
771                 l := p.exprs(expr.ElemList)
772                 for i, e := range l {
773                         l[i] = p.wrapname(expr.ElemList[i], e)
774                 }
775                 n.List = l
776                 base.Pos = p.makeXPos(expr.Rbrace)
777                 return n
778         case *syntax.KeyValueExpr:
779                 // use position of expr.Key rather than of expr (which has position of ':')
780                 return ir.NewKeyExpr(p.pos(expr.Key), p.expr(expr.Key), p.wrapname(expr.Value, p.expr(expr.Value)))
781         case *syntax.FuncLit:
782                 return p.funcLit(expr)
783         case *syntax.ParenExpr:
784                 return ir.NewParenExpr(p.pos(expr), p.expr(expr.X))
785         case *syntax.SelectorExpr:
786                 // parser.new_dotname
787                 obj := p.expr(expr.X)
788                 if obj.Op() == ir.OPACK {
789                         pack := obj.(*ir.PkgName)
790                         pack.Used = true
791                         return importName(pack.Pkg.Lookup(expr.Sel.Value))
792                 }
793                 n := ir.NewSelectorExpr(base.Pos, ir.OXDOT, obj, p.name(expr.Sel))
794                 n.SetPos(p.pos(expr)) // lineno may have been changed by p.expr(expr.X)
795                 return n
796         case *syntax.IndexExpr:
797                 return ir.NewIndexExpr(p.pos(expr), p.expr(expr.X), p.expr(expr.Index))
798         case *syntax.SliceExpr:
799                 op := ir.OSLICE
800                 if expr.Full {
801                         op = ir.OSLICE3
802                 }
803                 x := p.expr(expr.X)
804                 var index [3]ir.Node
805                 for i, n := range &expr.Index {
806                         if n != nil {
807                                 index[i] = p.expr(n)
808                         }
809                 }
810                 return ir.NewSliceExpr(p.pos(expr), op, x, index[0], index[1], index[2])
811         case *syntax.AssertExpr:
812                 return ir.NewTypeAssertExpr(p.pos(expr), p.expr(expr.X), p.typeExpr(expr.Type))
813         case *syntax.Operation:
814                 if expr.Op == syntax.Add && expr.Y != nil {
815                         return p.sum(expr)
816                 }
817                 x := p.expr(expr.X)
818                 if expr.Y == nil {
819                         pos, op := p.pos(expr), p.unOp(expr.Op)
820                         switch op {
821                         case ir.OADDR:
822                                 return typecheck.NodAddrAt(pos, x)
823                         case ir.ODEREF:
824                                 return ir.NewStarExpr(pos, x)
825                         }
826                         return ir.NewUnaryExpr(pos, op, x)
827                 }
828
829                 pos, op, y := p.pos(expr), p.binOp(expr.Op), p.expr(expr.Y)
830                 switch op {
831                 case ir.OANDAND, ir.OOROR:
832                         return ir.NewLogicalExpr(pos, op, x, y)
833                 }
834                 return ir.NewBinaryExpr(pos, op, x, y)
835         case *syntax.CallExpr:
836                 n := ir.NewCallExpr(p.pos(expr), ir.OCALL, p.expr(expr.Fun), p.exprs(expr.ArgList))
837                 n.IsDDD = expr.HasDots
838                 return n
839
840         case *syntax.ArrayType:
841                 var len ir.Node
842                 if expr.Len != nil {
843                         len = p.expr(expr.Len)
844                 }
845                 return ir.NewArrayType(p.pos(expr), len, p.typeExpr(expr.Elem))
846         case *syntax.SliceType:
847                 return ir.NewSliceType(p.pos(expr), p.typeExpr(expr.Elem))
848         case *syntax.DotsType:
849                 t := ir.NewSliceType(p.pos(expr), p.typeExpr(expr.Elem))
850                 t.DDD = true
851                 return t
852         case *syntax.StructType:
853                 return p.structType(expr)
854         case *syntax.InterfaceType:
855                 return p.interfaceType(expr)
856         case *syntax.FuncType:
857                 return p.signature(nil, expr)
858         case *syntax.MapType:
859                 return ir.NewMapType(p.pos(expr),
860                         p.typeExpr(expr.Key), p.typeExpr(expr.Value))
861         case *syntax.ChanType:
862                 return ir.NewChanType(p.pos(expr),
863                         p.typeExpr(expr.Elem), p.chanDir(expr.Dir))
864
865         case *syntax.TypeSwitchGuard:
866                 var tag *ir.Ident
867                 if expr.Lhs != nil {
868                         tag = ir.NewIdent(p.pos(expr.Lhs), p.name(expr.Lhs))
869                         if ir.IsBlank(tag) {
870                                 base.Errorf("invalid variable name %v in type switch", tag)
871                         }
872                 }
873                 return ir.NewTypeSwitchGuard(p.pos(expr), tag, p.expr(expr.X))
874         }
875         panic("unhandled Expr")
876 }
877
878 // sum efficiently handles very large summation expressions (such as
879 // in issue #16394). In particular, it avoids left recursion and
880 // collapses string literals.
881 func (p *noder) sum(x syntax.Expr) ir.Node {
882         // While we need to handle long sums with asymptotic
883         // efficiency, the vast majority of sums are very small: ~95%
884         // have only 2 or 3 operands, and ~99% of string literals are
885         // never concatenated.
886
887         adds := make([]*syntax.Operation, 0, 2)
888         for {
889                 add, ok := x.(*syntax.Operation)
890                 if !ok || add.Op != syntax.Add || add.Y == nil {
891                         break
892                 }
893                 adds = append(adds, add)
894                 x = add.X
895         }
896
897         // nstr is the current rightmost string literal in the
898         // summation (if any), and chunks holds its accumulated
899         // substrings.
900         //
901         // Consider the expression x + "a" + "b" + "c" + y. When we
902         // reach the string literal "a", we assign nstr to point to
903         // its corresponding Node and initialize chunks to {"a"}.
904         // Visiting the subsequent string literals "b" and "c", we
905         // simply append their values to chunks. Finally, when we
906         // reach the non-constant operand y, we'll join chunks to form
907         // "abc" and reassign the "a" string literal's value.
908         //
909         // N.B., we need to be careful about named string constants
910         // (indicated by Sym != nil) because 1) we can't modify their
911         // value, as doing so would affect other uses of the string
912         // constant, and 2) they may have types, which we need to
913         // handle correctly. For now, we avoid these problems by
914         // treating named string constants the same as non-constant
915         // operands.
916         var nstr ir.Node
917         chunks := make([]string, 0, 1)
918
919         n := p.expr(x)
920         if ir.IsConst(n, constant.String) && n.Sym() == nil {
921                 nstr = n
922                 chunks = append(chunks, ir.StringVal(nstr))
923         }
924
925         for i := len(adds) - 1; i >= 0; i-- {
926                 add := adds[i]
927
928                 r := p.expr(add.Y)
929                 if ir.IsConst(r, constant.String) && r.Sym() == nil {
930                         if nstr != nil {
931                                 // Collapse r into nstr instead of adding to n.
932                                 chunks = append(chunks, ir.StringVal(r))
933                                 continue
934                         }
935
936                         nstr = r
937                         chunks = append(chunks, ir.StringVal(nstr))
938                 } else {
939                         if len(chunks) > 1 {
940                                 nstr.SetVal(constant.MakeString(strings.Join(chunks, "")))
941                         }
942                         nstr = nil
943                         chunks = chunks[:0]
944                 }
945                 n = ir.NewBinaryExpr(p.pos(add), ir.OADD, n, r)
946         }
947         if len(chunks) > 1 {
948                 nstr.SetVal(constant.MakeString(strings.Join(chunks, "")))
949         }
950
951         return n
952 }
953
954 func (p *noder) typeExpr(typ syntax.Expr) ir.Ntype {
955         // TODO(mdempsky): Be stricter? typecheck should handle errors anyway.
956         n := p.expr(typ)
957         if n == nil {
958                 return nil
959         }
960         if _, ok := n.(ir.Ntype); !ok {
961                 ir.Dump("NOT NTYPE", n)
962         }
963         return n.(ir.Ntype)
964 }
965
966 func (p *noder) typeExprOrNil(typ syntax.Expr) ir.Ntype {
967         if typ != nil {
968                 return p.typeExpr(typ)
969         }
970         return nil
971 }
972
973 func (p *noder) chanDir(dir syntax.ChanDir) types.ChanDir {
974         switch dir {
975         case 0:
976                 return types.Cboth
977         case syntax.SendOnly:
978                 return types.Csend
979         case syntax.RecvOnly:
980                 return types.Crecv
981         }
982         panic("unhandled ChanDir")
983 }
984
985 func (p *noder) structType(expr *syntax.StructType) ir.Node {
986         l := make([]*ir.Field, 0, len(expr.FieldList))
987         for i, field := range expr.FieldList {
988                 p.setlineno(field)
989                 var n *ir.Field
990                 if field.Name == nil {
991                         n = p.embedded(field.Type)
992                 } else {
993                         n = ir.NewField(p.pos(field), p.name(field.Name), p.typeExpr(field.Type), nil)
994                 }
995                 if i < len(expr.TagList) && expr.TagList[i] != nil {
996                         n.Note = constant.StringVal(p.basicLit(expr.TagList[i]))
997                 }
998                 l = append(l, n)
999         }
1000
1001         p.setlineno(expr)
1002         return ir.NewStructType(p.pos(expr), l)
1003 }
1004
1005 func (p *noder) interfaceType(expr *syntax.InterfaceType) ir.Node {
1006         l := make([]*ir.Field, 0, len(expr.MethodList))
1007         for _, method := range expr.MethodList {
1008                 p.setlineno(method)
1009                 var n *ir.Field
1010                 if method.Name == nil {
1011                         n = ir.NewField(p.pos(method), nil, importName(p.packname(method.Type)).(ir.Ntype), nil)
1012                 } else {
1013                         mname := p.name(method.Name)
1014                         if mname.IsBlank() {
1015                                 base.Errorf("methods must have a unique non-blank name")
1016                                 continue
1017                         }
1018                         sig := p.typeExpr(method.Type).(*ir.FuncType)
1019                         sig.Recv = fakeRecv()
1020                         n = ir.NewField(p.pos(method), mname, sig, nil)
1021                 }
1022                 l = append(l, n)
1023         }
1024
1025         return ir.NewInterfaceType(p.pos(expr), l)
1026 }
1027
1028 func (p *noder) packname(expr syntax.Expr) *types.Sym {
1029         switch expr := expr.(type) {
1030         case *syntax.Name:
1031                 name := p.name(expr)
1032                 if n := oldname(name); n.Name() != nil && n.Name().PkgName != nil {
1033                         n.Name().PkgName.Used = true
1034                 }
1035                 return name
1036         case *syntax.SelectorExpr:
1037                 name := p.name(expr.X.(*syntax.Name))
1038                 def := ir.AsNode(name.Def)
1039                 if def == nil {
1040                         base.Errorf("undefined: %v", name)
1041                         return name
1042                 }
1043                 var pkg *types.Pkg
1044                 if def.Op() != ir.OPACK {
1045                         base.Errorf("%v is not a package", name)
1046                         pkg = types.LocalPkg
1047                 } else {
1048                         def := def.(*ir.PkgName)
1049                         def.Used = true
1050                         pkg = def.Pkg
1051                 }
1052                 return pkg.Lookup(expr.Sel.Value)
1053         }
1054         panic(fmt.Sprintf("unexpected packname: %#v", expr))
1055 }
1056
1057 func (p *noder) embedded(typ syntax.Expr) *ir.Field {
1058         op, isStar := typ.(*syntax.Operation)
1059         if isStar {
1060                 if op.Op != syntax.Mul || op.Y != nil {
1061                         panic("unexpected Operation")
1062                 }
1063                 typ = op.X
1064         }
1065
1066         sym := p.packname(typ)
1067         n := ir.NewField(p.pos(typ), typecheck.Lookup(sym.Name), importName(sym).(ir.Ntype), nil)
1068         n.Embedded = true
1069
1070         if isStar {
1071                 n.Ntype = ir.NewStarExpr(p.pos(op), n.Ntype)
1072         }
1073         return n
1074 }
1075
1076 func (p *noder) stmts(stmts []syntax.Stmt) []ir.Node {
1077         return p.stmtsFall(stmts, false)
1078 }
1079
1080 func (p *noder) stmtsFall(stmts []syntax.Stmt, fallOK bool) []ir.Node {
1081         var nodes []ir.Node
1082         for i, stmt := range stmts {
1083                 s := p.stmtFall(stmt, fallOK && i+1 == len(stmts))
1084                 if s == nil {
1085                 } else if s.Op() == ir.OBLOCK && len(s.(*ir.BlockStmt).List) > 0 {
1086                         // Inline non-empty block.
1087                         // Empty blocks must be preserved for checkreturn.
1088                         nodes = append(nodes, s.(*ir.BlockStmt).List...)
1089                 } else {
1090                         nodes = append(nodes, s)
1091                 }
1092         }
1093         return nodes
1094 }
1095
1096 func (p *noder) stmt(stmt syntax.Stmt) ir.Node {
1097         return p.stmtFall(stmt, false)
1098 }
1099
1100 func (p *noder) stmtFall(stmt syntax.Stmt, fallOK bool) ir.Node {
1101         p.setlineno(stmt)
1102         switch stmt := stmt.(type) {
1103         case nil, *syntax.EmptyStmt:
1104                 return nil
1105         case *syntax.LabeledStmt:
1106                 return p.labeledStmt(stmt, fallOK)
1107         case *syntax.BlockStmt:
1108                 l := p.blockStmt(stmt)
1109                 if len(l) == 0 {
1110                         // TODO(mdempsky): Line number?
1111                         return ir.NewBlockStmt(base.Pos, nil)
1112                 }
1113                 return ir.NewBlockStmt(src.NoXPos, l)
1114         case *syntax.ExprStmt:
1115                 return p.wrapname(stmt, p.expr(stmt.X))
1116         case *syntax.SendStmt:
1117                 return ir.NewSendStmt(p.pos(stmt), p.expr(stmt.Chan), p.expr(stmt.Value))
1118         case *syntax.DeclStmt:
1119                 return ir.NewBlockStmt(src.NoXPos, p.decls(stmt.DeclList))
1120         case *syntax.AssignStmt:
1121                 if stmt.Op != 0 && stmt.Op != syntax.Def {
1122                         n := ir.NewAssignOpStmt(p.pos(stmt), p.binOp(stmt.Op), p.expr(stmt.Lhs), p.expr(stmt.Rhs))
1123                         n.IncDec = stmt.Rhs == syntax.ImplicitOne
1124                         return n
1125                 }
1126
1127                 rhs := p.exprList(stmt.Rhs)
1128                 if list, ok := stmt.Lhs.(*syntax.ListExpr); ok && len(list.ElemList) != 1 || len(rhs) != 1 {
1129                         n := ir.NewAssignListStmt(p.pos(stmt), ir.OAS2, nil, nil)
1130                         n.Def = stmt.Op == syntax.Def
1131                         n.Lhs = p.assignList(stmt.Lhs, n, n.Def)
1132                         n.Rhs = rhs
1133                         return n
1134                 }
1135
1136                 n := ir.NewAssignStmt(p.pos(stmt), nil, nil)
1137                 n.Def = stmt.Op == syntax.Def
1138                 n.X = p.assignList(stmt.Lhs, n, n.Def)[0]
1139                 n.Y = rhs[0]
1140                 return n
1141
1142         case *syntax.BranchStmt:
1143                 var op ir.Op
1144                 switch stmt.Tok {
1145                 case syntax.Break:
1146                         op = ir.OBREAK
1147                 case syntax.Continue:
1148                         op = ir.OCONTINUE
1149                 case syntax.Fallthrough:
1150                         if !fallOK {
1151                                 base.Errorf("fallthrough statement out of place")
1152                         }
1153                         op = ir.OFALL
1154                 case syntax.Goto:
1155                         op = ir.OGOTO
1156                 default:
1157                         panic("unhandled BranchStmt")
1158                 }
1159                 var sym *types.Sym
1160                 if stmt.Label != nil {
1161                         sym = p.name(stmt.Label)
1162                 }
1163                 return ir.NewBranchStmt(p.pos(stmt), op, sym)
1164         case *syntax.CallStmt:
1165                 var op ir.Op
1166                 switch stmt.Tok {
1167                 case syntax.Defer:
1168                         op = ir.ODEFER
1169                 case syntax.Go:
1170                         op = ir.OGO
1171                 default:
1172                         panic("unhandled CallStmt")
1173                 }
1174                 return ir.NewGoDeferStmt(p.pos(stmt), op, p.expr(stmt.Call))
1175         case *syntax.ReturnStmt:
1176                 n := ir.NewReturnStmt(p.pos(stmt), p.exprList(stmt.Results))
1177                 if len(n.Results) == 0 && ir.CurFunc != nil {
1178                         for _, ln := range ir.CurFunc.Dcl {
1179                                 if ln.Class == ir.PPARAM {
1180                                         continue
1181                                 }
1182                                 if ln.Class != ir.PPARAMOUT {
1183                                         break
1184                                 }
1185                                 if ln.Sym().Def != ln {
1186                                         base.Errorf("%s is shadowed during return", ln.Sym().Name)
1187                                 }
1188                         }
1189                 }
1190                 return n
1191         case *syntax.IfStmt:
1192                 return p.ifStmt(stmt)
1193         case *syntax.ForStmt:
1194                 return p.forStmt(stmt)
1195         case *syntax.SwitchStmt:
1196                 return p.switchStmt(stmt)
1197         case *syntax.SelectStmt:
1198                 return p.selectStmt(stmt)
1199         }
1200         panic("unhandled Stmt")
1201 }
1202
1203 func (p *noder) assignList(expr syntax.Expr, defn ir.InitNode, colas bool) []ir.Node {
1204         if !colas {
1205                 return p.exprList(expr)
1206         }
1207
1208         var exprs []syntax.Expr
1209         if list, ok := expr.(*syntax.ListExpr); ok {
1210                 exprs = list.ElemList
1211         } else {
1212                 exprs = []syntax.Expr{expr}
1213         }
1214
1215         res := make([]ir.Node, len(exprs))
1216         seen := make(map[*types.Sym]bool, len(exprs))
1217
1218         newOrErr := false
1219         for i, expr := range exprs {
1220                 p.setlineno(expr)
1221                 res[i] = ir.BlankNode
1222
1223                 name, ok := expr.(*syntax.Name)
1224                 if !ok {
1225                         p.errorAt(expr.Pos(), "non-name %v on left side of :=", p.expr(expr))
1226                         newOrErr = true
1227                         continue
1228                 }
1229
1230                 sym := p.name(name)
1231                 if sym.IsBlank() {
1232                         continue
1233                 }
1234
1235                 if seen[sym] {
1236                         p.errorAt(expr.Pos(), "%v repeated on left side of :=", sym)
1237                         newOrErr = true
1238                         continue
1239                 }
1240                 seen[sym] = true
1241
1242                 if sym.Block == types.Block {
1243                         res[i] = oldname(sym)
1244                         continue
1245                 }
1246
1247                 newOrErr = true
1248                 n := typecheck.NewName(sym)
1249                 typecheck.Declare(n, typecheck.DeclContext)
1250                 n.Defn = defn
1251                 defn.PtrInit().Append(ir.NewDecl(base.Pos, ir.ODCL, n))
1252                 res[i] = n
1253         }
1254
1255         if !newOrErr {
1256                 base.ErrorfAt(defn.Pos(), "no new variables on left side of :=")
1257         }
1258         return res
1259 }
1260
1261 func (p *noder) blockStmt(stmt *syntax.BlockStmt) []ir.Node {
1262         p.openScope(stmt.Pos())
1263         nodes := p.stmts(stmt.List)
1264         p.closeScope(stmt.Rbrace)
1265         return nodes
1266 }
1267
1268 func (p *noder) ifStmt(stmt *syntax.IfStmt) ir.Node {
1269         p.openScope(stmt.Pos())
1270         init := p.stmt(stmt.Init)
1271         n := ir.NewIfStmt(p.pos(stmt), p.expr(stmt.Cond), p.blockStmt(stmt.Then), nil)
1272         if init != nil {
1273                 *n.PtrInit() = []ir.Node{init}
1274         }
1275         if stmt.Else != nil {
1276                 e := p.stmt(stmt.Else)
1277                 if e.Op() == ir.OBLOCK {
1278                         e := e.(*ir.BlockStmt)
1279                         n.Else = e.List
1280                 } else {
1281                         n.Else = []ir.Node{e}
1282                 }
1283         }
1284         p.closeAnotherScope()
1285         return n
1286 }
1287
1288 func (p *noder) forStmt(stmt *syntax.ForStmt) ir.Node {
1289         p.openScope(stmt.Pos())
1290         if r, ok := stmt.Init.(*syntax.RangeClause); ok {
1291                 if stmt.Cond != nil || stmt.Post != nil {
1292                         panic("unexpected RangeClause")
1293                 }
1294
1295                 n := ir.NewRangeStmt(p.pos(r), nil, nil, p.expr(r.X), nil)
1296                 if r.Lhs != nil {
1297                         n.Def = r.Def
1298                         lhs := p.assignList(r.Lhs, n, n.Def)
1299                         n.Key = lhs[0]
1300                         if len(lhs) > 1 {
1301                                 n.Value = lhs[1]
1302                         }
1303                 }
1304                 n.Body = p.blockStmt(stmt.Body)
1305                 p.closeAnotherScope()
1306                 return n
1307         }
1308
1309         n := ir.NewForStmt(p.pos(stmt), p.stmt(stmt.Init), p.expr(stmt.Cond), p.stmt(stmt.Post), p.blockStmt(stmt.Body))
1310         p.closeAnotherScope()
1311         return n
1312 }
1313
1314 func (p *noder) switchStmt(stmt *syntax.SwitchStmt) ir.Node {
1315         p.openScope(stmt.Pos())
1316
1317         init := p.stmt(stmt.Init)
1318         n := ir.NewSwitchStmt(p.pos(stmt), p.expr(stmt.Tag), nil)
1319         if init != nil {
1320                 *n.PtrInit() = []ir.Node{init}
1321         }
1322
1323         var tswitch *ir.TypeSwitchGuard
1324         if l := n.Tag; l != nil && l.Op() == ir.OTYPESW {
1325                 tswitch = l.(*ir.TypeSwitchGuard)
1326         }
1327         n.Cases = p.caseClauses(stmt.Body, tswitch, stmt.Rbrace)
1328
1329         p.closeScope(stmt.Rbrace)
1330         return n
1331 }
1332
1333 func (p *noder) caseClauses(clauses []*syntax.CaseClause, tswitch *ir.TypeSwitchGuard, rbrace syntax.Pos) []*ir.CaseClause {
1334         nodes := make([]*ir.CaseClause, 0, len(clauses))
1335         for i, clause := range clauses {
1336                 p.setlineno(clause)
1337                 if i > 0 {
1338                         p.closeScope(clause.Pos())
1339                 }
1340                 p.openScope(clause.Pos())
1341
1342                 n := ir.NewCaseStmt(p.pos(clause), p.exprList(clause.Cases), nil)
1343                 if tswitch != nil && tswitch.Tag != nil {
1344                         nn := typecheck.NewName(tswitch.Tag.Sym())
1345                         typecheck.Declare(nn, typecheck.DeclContext)
1346                         n.Var = nn
1347                         // keep track of the instances for reporting unused
1348                         nn.Defn = tswitch
1349                 }
1350
1351                 // Trim trailing empty statements. We omit them from
1352                 // the Node AST anyway, and it's easier to identify
1353                 // out-of-place fallthrough statements without them.
1354                 body := clause.Body
1355                 for len(body) > 0 {
1356                         if _, ok := body[len(body)-1].(*syntax.EmptyStmt); !ok {
1357                                 break
1358                         }
1359                         body = body[:len(body)-1]
1360                 }
1361
1362                 n.Body = p.stmtsFall(body, true)
1363                 if l := len(n.Body); l > 0 && n.Body[l-1].Op() == ir.OFALL {
1364                         if tswitch != nil {
1365                                 base.Errorf("cannot fallthrough in type switch")
1366                         }
1367                         if i+1 == len(clauses) {
1368                                 base.Errorf("cannot fallthrough final case in switch")
1369                         }
1370                 }
1371
1372                 nodes = append(nodes, n)
1373         }
1374         if len(clauses) > 0 {
1375                 p.closeScope(rbrace)
1376         }
1377         return nodes
1378 }
1379
1380 func (p *noder) selectStmt(stmt *syntax.SelectStmt) ir.Node {
1381         return ir.NewSelectStmt(p.pos(stmt), p.commClauses(stmt.Body, stmt.Rbrace))
1382 }
1383
1384 func (p *noder) commClauses(clauses []*syntax.CommClause, rbrace syntax.Pos) []*ir.CommClause {
1385         nodes := make([]*ir.CommClause, len(clauses))
1386         for i, clause := range clauses {
1387                 p.setlineno(clause)
1388                 if i > 0 {
1389                         p.closeScope(clause.Pos())
1390                 }
1391                 p.openScope(clause.Pos())
1392
1393                 nodes[i] = ir.NewCommStmt(p.pos(clause), p.stmt(clause.Comm), p.stmts(clause.Body))
1394         }
1395         if len(clauses) > 0 {
1396                 p.closeScope(rbrace)
1397         }
1398         return nodes
1399 }
1400
1401 func (p *noder) labeledStmt(label *syntax.LabeledStmt, fallOK bool) ir.Node {
1402         sym := p.name(label.Label)
1403         lhs := ir.NewLabelStmt(p.pos(label), sym)
1404
1405         var ls ir.Node
1406         if label.Stmt != nil { // TODO(mdempsky): Should always be present.
1407                 ls = p.stmtFall(label.Stmt, fallOK)
1408                 // Attach label directly to control statement too.
1409                 if ls != nil {
1410                         switch ls.Op() {
1411                         case ir.OFOR:
1412                                 ls := ls.(*ir.ForStmt)
1413                                 ls.Label = sym
1414                         case ir.ORANGE:
1415                                 ls := ls.(*ir.RangeStmt)
1416                                 ls.Label = sym
1417                         case ir.OSWITCH:
1418                                 ls := ls.(*ir.SwitchStmt)
1419                                 ls.Label = sym
1420                         case ir.OSELECT:
1421                                 ls := ls.(*ir.SelectStmt)
1422                                 ls.Label = sym
1423                         }
1424                 }
1425         }
1426
1427         l := []ir.Node{lhs}
1428         if ls != nil {
1429                 if ls.Op() == ir.OBLOCK {
1430                         ls := ls.(*ir.BlockStmt)
1431                         l = append(l, ls.List...)
1432                 } else {
1433                         l = append(l, ls)
1434                 }
1435         }
1436         return ir.NewBlockStmt(src.NoXPos, l)
1437 }
1438
1439 var unOps = [...]ir.Op{
1440         syntax.Recv: ir.ORECV,
1441         syntax.Mul:  ir.ODEREF,
1442         syntax.And:  ir.OADDR,
1443
1444         syntax.Not: ir.ONOT,
1445         syntax.Xor: ir.OBITNOT,
1446         syntax.Add: ir.OPLUS,
1447         syntax.Sub: ir.ONEG,
1448 }
1449
1450 func (p *noder) unOp(op syntax.Operator) ir.Op {
1451         if uint64(op) >= uint64(len(unOps)) || unOps[op] == 0 {
1452                 panic("invalid Operator")
1453         }
1454         return unOps[op]
1455 }
1456
1457 var binOps = [...]ir.Op{
1458         syntax.OrOr:   ir.OOROR,
1459         syntax.AndAnd: ir.OANDAND,
1460
1461         syntax.Eql: ir.OEQ,
1462         syntax.Neq: ir.ONE,
1463         syntax.Lss: ir.OLT,
1464         syntax.Leq: ir.OLE,
1465         syntax.Gtr: ir.OGT,
1466         syntax.Geq: ir.OGE,
1467
1468         syntax.Add: ir.OADD,
1469         syntax.Sub: ir.OSUB,
1470         syntax.Or:  ir.OOR,
1471         syntax.Xor: ir.OXOR,
1472
1473         syntax.Mul:    ir.OMUL,
1474         syntax.Div:    ir.ODIV,
1475         syntax.Rem:    ir.OMOD,
1476         syntax.And:    ir.OAND,
1477         syntax.AndNot: ir.OANDNOT,
1478         syntax.Shl:    ir.OLSH,
1479         syntax.Shr:    ir.ORSH,
1480 }
1481
1482 func (p *noder) binOp(op syntax.Operator) ir.Op {
1483         if uint64(op) >= uint64(len(binOps)) || binOps[op] == 0 {
1484                 panic("invalid Operator")
1485         }
1486         return binOps[op]
1487 }
1488
1489 // checkLangCompat reports an error if the representation of a numeric
1490 // literal is not compatible with the current language version.
1491 func checkLangCompat(lit *syntax.BasicLit) {
1492         s := lit.Value
1493         if len(s) <= 2 || types.AllowsGoVersion(types.LocalPkg, 1, 13) {
1494                 return
1495         }
1496         // len(s) > 2
1497         if strings.Contains(s, "_") {
1498                 base.ErrorfVers("go1.13", "underscores in numeric literals")
1499                 return
1500         }
1501         if s[0] != '0' {
1502                 return
1503         }
1504         radix := s[1]
1505         if radix == 'b' || radix == 'B' {
1506                 base.ErrorfVers("go1.13", "binary literals")
1507                 return
1508         }
1509         if radix == 'o' || radix == 'O' {
1510                 base.ErrorfVers("go1.13", "0o/0O-style octal literals")
1511                 return
1512         }
1513         if lit.Kind != syntax.IntLit && (radix == 'x' || radix == 'X') {
1514                 base.ErrorfVers("go1.13", "hexadecimal floating-point literals")
1515         }
1516 }
1517
1518 func (p *noder) basicLit(lit *syntax.BasicLit) constant.Value {
1519         // We don't use the errors of the conversion routines to determine
1520         // if a literal string is valid because the conversion routines may
1521         // accept a wider syntax than the language permits. Rely on lit.Bad
1522         // instead.
1523         if lit.Bad {
1524                 return constant.MakeUnknown()
1525         }
1526
1527         switch lit.Kind {
1528         case syntax.IntLit, syntax.FloatLit, syntax.ImagLit:
1529                 checkLangCompat(lit)
1530         }
1531
1532         v := constant.MakeFromLiteral(lit.Value, tokenForLitKind[lit.Kind], 0)
1533         if v.Kind() == constant.Unknown {
1534                 // TODO(mdempsky): Better error message?
1535                 p.errorAt(lit.Pos(), "malformed constant: %s", lit.Value)
1536         }
1537
1538         // go/constant uses big.Rat by default, which is more precise, but
1539         // causes toolstash -cmp and some tests to fail. For now, convert
1540         // to big.Float to match cmd/compile's historical precision.
1541         // TODO(mdempsky): Remove.
1542         if v.Kind() == constant.Float {
1543                 v = constant.Make(ir.BigFloat(v))
1544         }
1545
1546         return v
1547 }
1548
1549 var tokenForLitKind = [...]token.Token{
1550         syntax.IntLit:    token.INT,
1551         syntax.RuneLit:   token.CHAR,
1552         syntax.FloatLit:  token.FLOAT,
1553         syntax.ImagLit:   token.IMAG,
1554         syntax.StringLit: token.STRING,
1555 }
1556
1557 func (p *noder) name(name *syntax.Name) *types.Sym {
1558         return typecheck.Lookup(name.Value)
1559 }
1560
1561 func (p *noder) mkname(name *syntax.Name) ir.Node {
1562         // TODO(mdempsky): Set line number?
1563         return mkname(p.name(name))
1564 }
1565
1566 func (p *noder) wrapname(n syntax.Node, x ir.Node) ir.Node {
1567         // These nodes do not carry line numbers.
1568         // Introduce a wrapper node to give them the correct line.
1569         switch x.Op() {
1570         case ir.OTYPE, ir.OLITERAL:
1571                 if x.Sym() == nil {
1572                         break
1573                 }
1574                 fallthrough
1575         case ir.ONAME, ir.ONONAME, ir.OPACK:
1576                 p := ir.NewParenExpr(p.pos(n), x)
1577                 p.SetImplicit(true)
1578                 return p
1579         }
1580         return x
1581 }
1582
1583 func (p *noder) pos(n syntax.Node) src.XPos {
1584         // TODO(gri): orig.Pos() should always be known - fix package syntax
1585         xpos := base.Pos
1586         if pos := n.Pos(); pos.IsKnown() {
1587                 xpos = p.makeXPos(pos)
1588         }
1589         return xpos
1590 }
1591
1592 func (p *noder) setlineno(n syntax.Node) {
1593         if n != nil {
1594                 base.Pos = p.pos(n)
1595         }
1596 }
1597
1598 // error is called concurrently if files are parsed concurrently.
1599 func (p *noder) error(err error) {
1600         p.err <- err.(syntax.Error)
1601 }
1602
1603 // pragmas that are allowed in the std lib, but don't have
1604 // a syntax.Pragma value (see lex.go) associated with them.
1605 var allowedStdPragmas = map[string]bool{
1606         "go:cgo_export_static":  true,
1607         "go:cgo_export_dynamic": true,
1608         "go:cgo_import_static":  true,
1609         "go:cgo_import_dynamic": true,
1610         "go:cgo_ldflag":         true,
1611         "go:cgo_dynamic_linker": true,
1612         "go:embed":              true,
1613         "go:generate":           true,
1614 }
1615
1616 // *pragmas is the value stored in a syntax.pragmas during parsing.
1617 type pragmas struct {
1618         Flag   ir.PragmaFlag // collected bits
1619         Pos    []pragmaPos   // position of each individual flag
1620         Embeds []pragmaEmbed
1621 }
1622
1623 type pragmaPos struct {
1624         Flag ir.PragmaFlag
1625         Pos  syntax.Pos
1626 }
1627
1628 type pragmaEmbed struct {
1629         Pos      syntax.Pos
1630         Patterns []string
1631 }
1632
1633 func (p *noder) checkUnused(pragma *pragmas) {
1634         for _, pos := range pragma.Pos {
1635                 if pos.Flag&pragma.Flag != 0 {
1636                         p.errorAt(pos.Pos, "misplaced compiler directive")
1637                 }
1638         }
1639         if len(pragma.Embeds) > 0 {
1640                 for _, e := range pragma.Embeds {
1641                         p.errorAt(e.Pos, "misplaced go:embed directive")
1642                 }
1643         }
1644 }
1645
1646 func (p *noder) checkUnusedDuringParse(pragma *pragmas) {
1647         for _, pos := range pragma.Pos {
1648                 if pos.Flag&pragma.Flag != 0 {
1649                         p.error(syntax.Error{Pos: pos.Pos, Msg: "misplaced compiler directive"})
1650                 }
1651         }
1652         if len(pragma.Embeds) > 0 {
1653                 for _, e := range pragma.Embeds {
1654                         p.error(syntax.Error{Pos: e.Pos, Msg: "misplaced go:embed directive"})
1655                 }
1656         }
1657 }
1658
1659 // pragma is called concurrently if files are parsed concurrently.
1660 func (p *noder) pragma(pos syntax.Pos, blankLine bool, text string, old syntax.Pragma) syntax.Pragma {
1661         pragma, _ := old.(*pragmas)
1662         if pragma == nil {
1663                 pragma = new(pragmas)
1664         }
1665
1666         if text == "" {
1667                 // unused pragma; only called with old != nil.
1668                 p.checkUnusedDuringParse(pragma)
1669                 return nil
1670         }
1671
1672         if strings.HasPrefix(text, "line ") {
1673                 // line directives are handled by syntax package
1674                 panic("unreachable")
1675         }
1676
1677         if !blankLine {
1678                 // directive must be on line by itself
1679                 p.error(syntax.Error{Pos: pos, Msg: "misplaced compiler directive"})
1680                 return pragma
1681         }
1682
1683         switch {
1684         case strings.HasPrefix(text, "go:linkname "):
1685                 f := strings.Fields(text)
1686                 if !(2 <= len(f) && len(f) <= 3) {
1687                         p.error(syntax.Error{Pos: pos, Msg: "usage: //go:linkname localname [linkname]"})
1688                         break
1689                 }
1690                 // The second argument is optional. If omitted, we use
1691                 // the default object symbol name for this and
1692                 // linkname only serves to mark this symbol as
1693                 // something that may be referenced via the object
1694                 // symbol name from another package.
1695                 var target string
1696                 if len(f) == 3 {
1697                         target = f[2]
1698                 } else if base.Ctxt.Pkgpath != "" {
1699                         // Use the default object symbol name if the
1700                         // user didn't provide one.
1701                         target = objabi.PathToPrefix(base.Ctxt.Pkgpath) + "." + f[1]
1702                 } else {
1703                         p.error(syntax.Error{Pos: pos, Msg: "//go:linkname requires linkname argument or -p compiler flag"})
1704                         break
1705                 }
1706                 p.linknames = append(p.linknames, linkname{pos, f[1], target})
1707
1708         case text == "go:embed", strings.HasPrefix(text, "go:embed "):
1709                 args, err := parseGoEmbed(text[len("go:embed"):])
1710                 if err != nil {
1711                         p.error(syntax.Error{Pos: pos, Msg: err.Error()})
1712                 }
1713                 if len(args) == 0 {
1714                         p.error(syntax.Error{Pos: pos, Msg: "usage: //go:embed pattern..."})
1715                         break
1716                 }
1717                 pragma.Embeds = append(pragma.Embeds, pragmaEmbed{pos, args})
1718
1719         case strings.HasPrefix(text, "go:cgo_import_dynamic "):
1720                 // This is permitted for general use because Solaris
1721                 // code relies on it in golang.org/x/sys/unix and others.
1722                 fields := pragmaFields(text)
1723                 if len(fields) >= 4 {
1724                         lib := strings.Trim(fields[3], `"`)
1725                         if lib != "" && !safeArg(lib) && !isCgoGeneratedFile(pos) {
1726                                 p.error(syntax.Error{Pos: pos, Msg: fmt.Sprintf("invalid library name %q in cgo_import_dynamic directive", lib)})
1727                         }
1728                         p.pragcgo(pos, text)
1729                         pragma.Flag |= pragmaFlag("go:cgo_import_dynamic")
1730                         break
1731                 }
1732                 fallthrough
1733         case strings.HasPrefix(text, "go:cgo_"):
1734                 // For security, we disallow //go:cgo_* directives other
1735                 // than cgo_import_dynamic outside cgo-generated files.
1736                 // Exception: they are allowed in the standard library, for runtime and syscall.
1737                 if !isCgoGeneratedFile(pos) && !base.Flag.Std {
1738                         p.error(syntax.Error{Pos: pos, Msg: fmt.Sprintf("//%s only allowed in cgo-generated code", text)})
1739                 }
1740                 p.pragcgo(pos, text)
1741                 fallthrough // because of //go:cgo_unsafe_args
1742         default:
1743                 verb := text
1744                 if i := strings.Index(text, " "); i >= 0 {
1745                         verb = verb[:i]
1746                 }
1747                 flag := pragmaFlag(verb)
1748                 const runtimePragmas = ir.Systemstack | ir.Nowritebarrier | ir.Nowritebarrierrec | ir.Yeswritebarrierrec
1749                 if !base.Flag.CompilingRuntime && flag&runtimePragmas != 0 {
1750                         p.error(syntax.Error{Pos: pos, Msg: fmt.Sprintf("//%s only allowed in runtime", verb)})
1751                 }
1752                 if flag == 0 && !allowedStdPragmas[verb] && base.Flag.Std {
1753                         p.error(syntax.Error{Pos: pos, Msg: fmt.Sprintf("//%s is not allowed in the standard library", verb)})
1754                 }
1755                 pragma.Flag |= flag
1756                 pragma.Pos = append(pragma.Pos, pragmaPos{flag, pos})
1757         }
1758
1759         return pragma
1760 }
1761
1762 // isCgoGeneratedFile reports whether pos is in a file
1763 // generated by cgo, which is to say a file with name
1764 // beginning with "_cgo_". Such files are allowed to
1765 // contain cgo directives, and for security reasons
1766 // (primarily misuse of linker flags), other files are not.
1767 // See golang.org/issue/23672.
1768 func isCgoGeneratedFile(pos syntax.Pos) bool {
1769         return strings.HasPrefix(filepath.Base(filepath.Clean(fileh(pos.Base().Filename()))), "_cgo_")
1770 }
1771
1772 // safeArg reports whether arg is a "safe" command-line argument,
1773 // meaning that when it appears in a command-line, it probably
1774 // doesn't have some special meaning other than its own name.
1775 // This is copied from SafeArg in cmd/go/internal/load/pkg.go.
1776 func safeArg(name string) bool {
1777         if name == "" {
1778                 return false
1779         }
1780         c := name[0]
1781         return '0' <= c && c <= '9' || 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || c == '.' || c == '_' || c == '/' || c >= utf8.RuneSelf
1782 }
1783
1784 func mkname(sym *types.Sym) ir.Node {
1785         n := oldname(sym)
1786         if n.Name() != nil && n.Name().PkgName != nil {
1787                 n.Name().PkgName.Used = true
1788         }
1789         return n
1790 }
1791
1792 // parseGoEmbed parses the text following "//go:embed" to extract the glob patterns.
1793 // It accepts unquoted space-separated patterns as well as double-quoted and back-quoted Go strings.
1794 // go/build/read.go also processes these strings and contains similar logic.
1795 func parseGoEmbed(args string) ([]string, error) {
1796         var list []string
1797         for args = strings.TrimSpace(args); args != ""; args = strings.TrimSpace(args) {
1798                 var path string
1799         Switch:
1800                 switch args[0] {
1801                 default:
1802                         i := len(args)
1803                         for j, c := range args {
1804                                 if unicode.IsSpace(c) {
1805                                         i = j
1806                                         break
1807                                 }
1808                         }
1809                         path = args[:i]
1810                         args = args[i:]
1811
1812                 case '`':
1813                         i := strings.Index(args[1:], "`")
1814                         if i < 0 {
1815                                 return nil, fmt.Errorf("invalid quoted string in //go:embed: %s", args)
1816                         }
1817                         path = args[1 : 1+i]
1818                         args = args[1+i+1:]
1819
1820                 case '"':
1821                         i := 1
1822                         for ; i < len(args); i++ {
1823                                 if args[i] == '\\' {
1824                                         i++
1825                                         continue
1826                                 }
1827                                 if args[i] == '"' {
1828                                         q, err := strconv.Unquote(args[:i+1])
1829                                         if err != nil {
1830                                                 return nil, fmt.Errorf("invalid quoted string in //go:embed: %s", args[:i+1])
1831                                         }
1832                                         path = q
1833                                         args = args[i+1:]
1834                                         break Switch
1835                                 }
1836                         }
1837                         if i >= len(args) {
1838                                 return nil, fmt.Errorf("invalid quoted string in //go:embed: %s", args)
1839                         }
1840                 }
1841
1842                 if args != "" {
1843                         r, _ := utf8.DecodeRuneInString(args)
1844                         if !unicode.IsSpace(r) {
1845                                 return nil, fmt.Errorf("invalid quoted string in //go:embed: %s", args)
1846                         }
1847                 }
1848                 list = append(list, path)
1849         }
1850         return list, nil
1851 }
1852
1853 func fakeRecv() *ir.Field {
1854         return ir.NewField(base.Pos, nil, nil, types.FakeRecvType())
1855 }
1856
1857 func (p *noder) funcLit(expr *syntax.FuncLit) ir.Node {
1858         xtype := p.typeExpr(expr.Type)
1859         ntype := p.typeExpr(expr.Type)
1860
1861         fn := ir.NewFunc(p.pos(expr))
1862         fn.SetIsHiddenClosure(ir.CurFunc != nil)
1863
1864         fn.Nname = ir.NewNameAt(p.pos(expr), ir.BlankNode.Sym()) // filled in by typecheckclosure
1865         fn.Nname.Func = fn
1866         fn.Nname.Ntype = xtype
1867         fn.Nname.Defn = fn
1868
1869         clo := ir.NewClosureExpr(p.pos(expr), fn)
1870         fn.ClosureType = ntype
1871         fn.OClosure = clo
1872
1873         p.funcBody(fn, expr.Body)
1874
1875         // closure-specific variables are hanging off the
1876         // ordinary ones in the symbol table; see oldname.
1877         // unhook them.
1878         // make the list of pointers for the closure call.
1879         for _, v := range fn.ClosureVars {
1880                 // Unlink from v1; see comment in syntax.go type Param for these fields.
1881                 v1 := v.Defn
1882                 v1.Name().Innermost = v.Outer
1883
1884                 // If the closure usage of v is not dense,
1885                 // we need to make it dense; now that we're out
1886                 // of the function in which v appeared,
1887                 // look up v.Sym in the enclosing function
1888                 // and keep it around for use in the compiled code.
1889                 //
1890                 // That is, suppose we just finished parsing the innermost
1891                 // closure f4 in this code:
1892                 //
1893                 //      func f() {
1894                 //              v := 1
1895                 //              func() { // f2
1896                 //                      use(v)
1897                 //                      func() { // f3
1898                 //                              func() { // f4
1899                 //                                      use(v)
1900                 //                              }()
1901                 //                      }()
1902                 //              }()
1903                 //      }
1904                 //
1905                 // At this point v.Outer is f2's v; there is no f3's v.
1906                 // To construct the closure f4 from within f3,
1907                 // we need to use f3's v and in this case we need to create f3's v.
1908                 // We are now in the context of f3, so calling oldname(v.Sym)
1909                 // obtains f3's v, creating it if necessary (as it is in the example).
1910                 //
1911                 // capturevars will decide whether to use v directly or &v.
1912                 v.Outer = oldname(v.Sym()).(*ir.Name)
1913         }
1914
1915         return clo
1916 }
1917
1918 // A function named init is a special case.
1919 // It is called by the initialization before main is run.
1920 // To make it unique within a package and also uncallable,
1921 // the name, normally "pkg.init", is altered to "pkg.init.0".
1922 var renameinitgen int
1923
1924 func renameinit() *types.Sym {
1925         s := typecheck.LookupNum("init.", renameinitgen)
1926         renameinitgen++
1927         return s
1928 }
1929
1930 // oldname returns the Node that declares symbol s in the current scope.
1931 // If no such Node currently exists, an ONONAME Node is returned instead.
1932 // Automatically creates a new closure variable if the referenced symbol was
1933 // declared in a different (containing) function.
1934 func oldname(s *types.Sym) ir.Node {
1935         if s.Pkg != types.LocalPkg {
1936                 return ir.NewIdent(base.Pos, s)
1937         }
1938
1939         n := ir.AsNode(s.Def)
1940         if n == nil {
1941                 // Maybe a top-level declaration will come along later to
1942                 // define s. resolve will check s.Def again once all input
1943                 // source has been processed.
1944                 return ir.NewIdent(base.Pos, s)
1945         }
1946
1947         if ir.CurFunc != nil && n.Op() == ir.ONAME && n.Name().Curfn != nil && n.Name().Curfn != ir.CurFunc {
1948                 // Inner func is referring to var in outer func.
1949                 //
1950                 // TODO(rsc): If there is an outer variable x and we
1951                 // are parsing x := 5 inside the closure, until we get to
1952                 // the := it looks like a reference to the outer x so we'll
1953                 // make x a closure variable unnecessarily.
1954                 n := n.(*ir.Name)
1955                 c := n.Innermost
1956                 if c == nil || c.Curfn != ir.CurFunc {
1957                         // Do not have a closure var for the active closure yet; make one.
1958                         c = typecheck.NewName(s)
1959                         c.Class = ir.PAUTOHEAP
1960                         c.SetIsClosureVar(true)
1961                         c.Defn = n
1962
1963                         // Link into list of active closure variables.
1964                         // Popped from list in func funcLit.
1965                         c.Outer = n.Innermost
1966                         n.Innermost = c
1967
1968                         ir.CurFunc.ClosureVars = append(ir.CurFunc.ClosureVars, c)
1969                 }
1970
1971                 // return ref to closure var, not original
1972                 return c
1973         }
1974
1975         return n
1976 }
1977
1978 func varEmbed(p *noder, names []*ir.Name, typ ir.Ntype, exprs []ir.Node, embeds []pragmaEmbed) (newExprs []ir.Node) {
1979         haveEmbed := false
1980         for _, decl := range p.file.DeclList {
1981                 imp, ok := decl.(*syntax.ImportDecl)
1982                 if !ok {
1983                         // imports always come first
1984                         break
1985                 }
1986                 path, _ := strconv.Unquote(imp.Path.Value)
1987                 if path == "embed" {
1988                         haveEmbed = true
1989                         break
1990                 }
1991         }
1992
1993         pos := embeds[0].Pos
1994         if !haveEmbed {
1995                 p.errorAt(pos, "invalid go:embed: missing import \"embed\"")
1996                 return exprs
1997         }
1998         if base.Flag.Cfg.Embed.Patterns == nil {
1999                 p.errorAt(pos, "invalid go:embed: build system did not supply embed configuration")
2000                 return exprs
2001         }
2002         if len(names) > 1 {
2003                 p.errorAt(pos, "go:embed cannot apply to multiple vars")
2004                 return exprs
2005         }
2006         if len(exprs) > 0 {
2007                 p.errorAt(pos, "go:embed cannot apply to var with initializer")
2008                 return exprs
2009         }
2010         if typ == nil {
2011                 // Should not happen, since len(exprs) == 0 now.
2012                 p.errorAt(pos, "go:embed cannot apply to var without type")
2013                 return exprs
2014         }
2015         if typecheck.DeclContext != ir.PEXTERN {
2016                 p.errorAt(pos, "go:embed cannot apply to var inside func")
2017                 return exprs
2018         }
2019
2020         v := names[0]
2021         typecheck.Target.Embeds = append(typecheck.Target.Embeds, v)
2022         v.Embed = new([]ir.Embed)
2023         for _, e := range embeds {
2024                 *v.Embed = append(*v.Embed, ir.Embed{Pos: p.makeXPos(e.Pos), Patterns: e.Patterns})
2025         }
2026         return exprs
2027 }