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