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.
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"
28 func LoadPackage(filenames []string) {
29 base.Timer.Start("fe", "parse")
30 lines := ParseFiles(filenames)
32 base.Timer.AddEvent(int64(lines), "lines")
37 // With all user code typechecked, it's now safe to verify unused dot imports.
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)
51 for _, filename := range filenames {
53 basemap: make(map[*syntax.PosBase]*src.PosBase),
54 err: make(chan syntax.Error),
55 trackScopes: base.Flag.Dwarf,
57 noders = append(noders, p)
59 go func(filename string) {
61 defer func() { <-sem }()
63 base := syntax.NewFileBase(filename)
65 f, err := os.Open(filename)
67 p.error(syntax.Error{Msg: err.Error()})
72 p.file, _ = syntax.Parse(base, f, p.error, p.pragma, syntax.CheckBranches) // errors are tracked via p.error
77 for _, p := range noders {
78 for e := range p.err {
79 p.errorAt(e.Pos, "%s", e.Msg)
84 p.file = nil // release memory
86 if base.SyntaxErrors() != 0 {
89 // Always run testdclstack here, even when debug_dclstack is not set, as a sanity measure.
93 for _, p := range noders {
97 types.LocalPkg.Height = myheight
103 typecheck.DeclareUniverse()
105 typecheck.TypecheckAllowed = true
107 // Process top-level declarations in phases.
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.
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.
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)
126 // Phase 2: Variable assignments.
127 // To check interface assignments, depends on phase 1.
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)
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")
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))
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])
160 // Phase 5: With all user code type-checked, it's now safe to verify map keys.
161 typecheck.CheckMapKeys()
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
172 b1, ok := p.basemap[b0]
176 b1 = src.NewFileBase(fn, absFilename(fn))
178 // line directive base
182 panic("infinite recursion in makeSrcPosBase")
184 p1 := src.MakePos(p.makeSrcPosBase(p0b), p0.Line(), p0.Col())
185 b1 = src.NewLinePragmaBase(p1, fn, fileh(fn), b0.Line(), b0.Col())
191 p.basecache.last = b0
192 p.basecache.base = b1
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()))
201 func (p *noder) errorAt(pos syntax.Pos, format string, args ...interface{}) {
202 base.ErrorfAt(p.makeXPos(pos), format, args...)
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)
210 func absFilename(name string) string {
211 return objabi.AbsFile(base.Ctxt.Pathname, name, base.Flag.TrimPath)
214 // noder transforms package syntax's AST into a Node tree.
216 basemap map[*syntax.PosBase]*src.PosBase
224 pragcgobuf [][]string
225 err chan syntax.Error
230 // scopeVars is a stack tracking the number of variables declared in the
231 // current function at the moment each open scope was opened.
235 lastCloseScopePos syntax.Pos
238 func (p *noder) funcBody(fn *ir.Func, block *syntax.BlockStmt) {
241 typecheck.StartFuncBody(fn)
244 body := p.stmts(block.List)
246 body = []ir.Node{ir.NewBlockStmt(base.Pos, nil)}
250 base.Pos = p.makeXPos(block.Rbrace)
251 fn.Endlineno = base.Pos
254 typecheck.FinishFuncBody()
258 func (p *noder) openScope(pos syntax.Pos) {
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))
270 func (p *noder) closeScope(pos syntax.Pos) {
271 p.lastCloseScopePos = pos
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.
280 if int(p.scope) != len(ir.CurFunc.Parents) {
281 base.Fatalf("scope tracking inconsistency, no variables declared but scopes were not retracted")
284 p.scope = ir.CurFunc.Parents[p.scope-1]
285 ir.CurFunc.Parents = ir.CurFunc.Parents[:len(ir.CurFunc.Parents)-1]
287 nmarks := len(ir.CurFunc.Marks)
288 ir.CurFunc.Marks[nmarks-1].Scope = p.scope
289 prevScope := ir.ScopeID(0)
291 prevScope = ir.CurFunc.Marks[nmarks-2].Scope
293 if ir.CurFunc.Marks[nmarks-1].Scope == prevScope {
294 ir.CurFunc.Marks = ir.CurFunc.Marks[:nmarks-1]
299 p.scope = ir.CurFunc.Parents[p.scope-1]
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
310 ir.CurFunc.Marks = append(ir.CurFunc.Marks, ir.Mark{Pos: xpos, Scope: p.scope})
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)
322 // linkname records a //go:linkname directive.
323 type linkname struct {
329 func (p *noder) node() {
331 p.importedUnsafe = false
332 p.importedEmbed = false
334 p.setlineno(p.file.PkgName)
335 mkpackage(p.file.PkgName.Value)
337 if pragma, ok := p.file.Pragma.(*pragmas); ok {
338 pragma.Flag &^= ir.GoBuildPragma
339 p.checkUnused(pragma)
342 typecheck.Target.Decls = append(typecheck.Target.Decls, p.decls(p.file.DeclList)...)
344 base.Pos = src.NoXPos
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\"")
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)")
360 if n.Sym().Linkname != "" {
361 p.errorAt(l.pos, "duplicate //go:linkname for %s", l.local)
364 n.Sym().Linkname = l.remote
366 typecheck.Target.CgoPragmas = append(typecheck.Target.CgoPragmas, p.pragcgobuf...)
369 func (p *noder) decls(decls []syntax.Decl) (l []ir.Node) {
372 for _, decl := range decls {
374 switch decl := decl.(type) {
375 case *syntax.ImportDecl:
378 case *syntax.VarDecl:
379 l = append(l, p.varDecl(decl)...)
381 case *syntax.ConstDecl:
382 l = append(l, p.constDecl(decl, &cs)...)
384 case *syntax.TypeDecl:
385 l = append(l, p.typeDecl(decl))
387 case *syntax.FuncDecl:
388 l = append(l, p.funcDecl(decl))
391 panic("unhandled Decl")
398 func (p *noder) importDecl(imp *syntax.ImportDecl) {
400 return // avoid follow-on errors if there was a syntax error
403 if pragma, ok := imp.Pragma.(*pragmas); ok {
404 p.checkUnused(pragma)
407 ipkg := importfile(p.basicLit(imp.Path))
409 if base.Errors() == 0 {
410 base.Fatalf("phase error in import")
415 if ipkg == ir.Pkgs.Unsafe {
416 p.importedUnsafe = true
418 if ipkg.Path == "embed" {
419 p.importedEmbed = true
423 typecheck.Target.Imports = append(typecheck.Target.Imports, ipkg)
428 if imp.LocalPkgName != nil {
429 my = p.name(imp.LocalPkgName)
431 my = typecheck.Lookup(ipkg.Name)
434 pack := ir.NewPkgName(p.pos(imp), my, ipkg)
441 base.ErrorfAt(pack.Pos(), "cannot import package as init - init must be a func")
447 typecheck.Redeclared(pack.Pos(), my, "as imported package name")
450 my.Lastlineno = pack.Pos()
451 my.Block = 1 // at top level
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)
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\"")
470 exprs = varEmbed(p, names, typ, exprs, pragma.Embeds)
474 p.checkUnused(pragma)
480 if len(names) > 1 && len(exprs) == 1 {
481 as2 := ir.NewAssignListStmt(base.Pos, ir.OAS2, nil, exprs)
482 for _, v := range names {
484 typecheck.Declare(v, typecheck.DeclContext)
487 if ir.CurFunc != nil {
488 init = append(init, ir.NewDecl(base.Pos, ir.ODCL, v))
492 return append(init, as2)
495 for i, v := range names {
501 typecheck.Declare(v, typecheck.DeclContext)
504 if ir.CurFunc != nil {
505 init = append(init, ir.NewDecl(base.Pos, ir.ODCL, v))
507 as := ir.NewAssignStmt(base.Pos, v, e)
508 init = append(init, as)
509 if e != nil || ir.CurFunc == nil {
514 if len(exprs) != 0 && len(names) != len(exprs) {
515 base.Errorf("assignment mismatch: %d variables but %d values", len(names), len(exprs))
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 {
531 func (p *noder) constDecl(decl *syntax.ConstDecl, cs *constState) []ir.Node {
532 if decl.Group == nil || decl.Group != cs.group {
538 if pragma, ok := decl.Pragma.(*pragmas); ok {
539 p.checkUnused(pragma)
542 names := p.declNames(ir.OLITERAL, decl.NameList)
543 typ := p.typeExprOrNil(decl.Type)
546 if decl.Values != nil {
547 values = p.exprList(decl.Values)
548 cs.typ, cs.values = typ, values
551 base.Errorf("const declaration cannot have type without expression")
553 typ, values = cs.typ, cs.values
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")
563 if decl.Values == nil {
564 v = ir.DeepCopy(n.Pos(), v)
566 typecheck.Declare(n, typecheck.DeclContext)
572 nn = append(nn, ir.NewDecl(p.pos(decl), ir.ODCLCONST, n))
575 if len(values) > len(names) {
576 base.Errorf("extra expression in const declaration")
584 func (p *noder) typeDecl(decl *syntax.TypeDecl) ir.Node {
585 n := p.declName(ir.OTYPE, decl.Name)
586 typecheck.Declare(n, typecheck.DeclContext)
588 // decl.Type may be nil but in that case we got a syntax error during parsing
589 typ := p.typeExprOrNil(decl.Type)
592 n.SetAlias(decl.Alias)
593 if pragma, ok := decl.Pragma.(*pragmas); ok {
595 n.SetPragma(pragma.Flag & typePragmas)
596 pragma.Flag &^= typePragmas
598 p.checkUnused(pragma)
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")
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))
616 func (p *noder) declName(op ir.Op, name *syntax.Name) *ir.Name {
617 return ir.NewDeclNameAt(p.pos(name), op, p.name(name))
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))
626 if name.Name == "init" {
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")
631 typecheck.Target.Inits = append(typecheck.Target.Inits, f)
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")
641 name = ir.BlankNode.Sym() // filled in by typecheckfunc
644 f.Nname = ir.NewNameAt(p.pos(fun.Name), name)
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")
654 pragma.Flag &^= funcPragmas
655 p.checkUnused(pragma)
659 typecheck.Declare(f.Nname, ir.PFUNC)
662 p.funcBody(f, fun.Body)
665 if f.Pragma&ir.Noescape != 0 {
666 base.ErrorfAt(f.Pos(), "can only use //go:noescape with external func implementations")
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.
673 for _, n := range p.linknames {
674 if ir.FuncName(f) == n.local {
680 base.ErrorfAt(f.Pos(), "missing function body")
688 func (p *noder) signature(recv *syntax.Field, typ *syntax.FuncType) *ir.FuncType {
691 rcvr = p.param(recv, false, false)
693 return ir.NewFuncType(p.pos(typ), rcvr,
694 p.params(typ.ParamList, true),
695 p.params(typ.ResultList, false))
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 {
702 nodes = append(nodes, p.param(param, dddOk, i+1 == len(params)))
707 func (p *noder) param(param *syntax.Field, dddOk, final bool) *ir.Field {
709 if param.Name != nil {
710 name = p.name(param.Name)
713 typ := p.typeExpr(param.Type)
714 n := ir.NewField(p.pos(param), name, typ, nil)
716 // rewrite ...T parameter
717 if typ, ok := typ.(*ir.SliceType); ok && typ.DDD {
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")
723 if param.Name == nil {
724 base.Errorf("syntax error: cannot use ... with non-final parameter")
726 p.errorAt(param.Name.Pos(), "syntax error: cannot use ... with non-final parameter %s", param.Name.Value)
736 func (p *noder) exprList(expr syntax.Expr) []ir.Node {
737 switch expr := expr.(type) {
740 case *syntax.ListExpr:
741 return p.exprs(expr.ElemList)
743 return []ir.Node{p.expr(expr)}
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))
755 func (p *noder) expr(expr syntax.Expr) ir.Node {
757 switch expr := expr.(type) {
758 case nil, *syntax.BadExpr:
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)
767 n.SetDiag(expr.Bad) // avoid follow-on errors if there was a syntax error
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)
776 base.Pos = p.makeXPos(expr.Rbrace)
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)
791 return importName(pack.Pkg.Lookup(expr.Sel.Value))
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)
796 case *syntax.IndexExpr:
797 return ir.NewIndexExpr(p.pos(expr), p.expr(expr.X), p.expr(expr.Index))
798 case *syntax.SliceExpr:
805 for i, n := range &expr.Index {
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 {
819 pos, op := p.pos(expr), p.unOp(expr.Op)
822 return typecheck.NodAddrAt(pos, x)
824 return ir.NewStarExpr(pos, x)
826 return ir.NewUnaryExpr(pos, op, x)
829 pos, op, y := p.pos(expr), p.binOp(expr.Op), p.expr(expr.Y)
831 case ir.OANDAND, ir.OOROR:
832 return ir.NewLogicalExpr(pos, op, x, y)
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
840 case *syntax.ArrayType:
843 len = p.expr(expr.Len)
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))
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))
865 case *syntax.TypeSwitchGuard:
868 tag = ir.NewIdent(p.pos(expr.Lhs), p.name(expr.Lhs))
870 base.Errorf("invalid variable name %v in type switch", tag)
873 return ir.NewTypeSwitchGuard(p.pos(expr), tag, p.expr(expr.X))
875 panic("unhandled Expr")
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.
887 adds := make([]*syntax.Operation, 0, 2)
889 add, ok := x.(*syntax.Operation)
890 if !ok || add.Op != syntax.Add || add.Y == nil {
893 adds = append(adds, add)
897 // nstr is the current rightmost string literal in the
898 // summation (if any), and chunks holds its accumulated
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.
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
917 chunks := make([]string, 0, 1)
920 if ir.IsConst(n, constant.String) && n.Sym() == nil {
922 chunks = append(chunks, ir.StringVal(nstr))
925 for i := len(adds) - 1; i >= 0; i-- {
929 if ir.IsConst(r, constant.String) && r.Sym() == nil {
931 // Collapse r into nstr instead of adding to n.
932 chunks = append(chunks, ir.StringVal(r))
937 chunks = append(chunks, ir.StringVal(nstr))
940 nstr.SetVal(constant.MakeString(strings.Join(chunks, "")))
945 n = ir.NewBinaryExpr(p.pos(add), ir.OADD, n, r)
948 nstr.SetVal(constant.MakeString(strings.Join(chunks, "")))
954 func (p *noder) typeExpr(typ syntax.Expr) ir.Ntype {
955 // TODO(mdempsky): Be stricter? typecheck should handle errors anyway.
960 if _, ok := n.(ir.Ntype); !ok {
961 ir.Dump("NOT NTYPE", n)
966 func (p *noder) typeExprOrNil(typ syntax.Expr) ir.Ntype {
968 return p.typeExpr(typ)
973 func (p *noder) chanDir(dir syntax.ChanDir) types.ChanDir {
977 case syntax.SendOnly:
979 case syntax.RecvOnly:
982 panic("unhandled ChanDir")
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 {
990 if field.Name == nil {
991 n = p.embedded(field.Type)
993 n = ir.NewField(p.pos(field), p.name(field.Name), p.typeExpr(field.Type), nil)
995 if i < len(expr.TagList) && expr.TagList[i] != nil {
996 n.Note = constant.StringVal(p.basicLit(expr.TagList[i]))
1002 return ir.NewStructType(p.pos(expr), l)
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 {
1010 if method.Name == nil {
1011 n = ir.NewField(p.pos(method), nil, importName(p.packname(method.Type)).(ir.Ntype), nil)
1013 mname := p.name(method.Name)
1014 if mname.IsBlank() {
1015 base.Errorf("methods must have a unique non-blank name")
1018 sig := p.typeExpr(method.Type).(*ir.FuncType)
1019 sig.Recv = fakeRecv()
1020 n = ir.NewField(p.pos(method), mname, sig, nil)
1025 return ir.NewInterfaceType(p.pos(expr), l)
1028 func (p *noder) packname(expr syntax.Expr) *types.Sym {
1029 switch expr := expr.(type) {
1031 name := p.name(expr)
1032 if n := oldname(name); n.Name() != nil && n.Name().PkgName != nil {
1033 n.Name().PkgName.Used = true
1036 case *syntax.SelectorExpr:
1037 name := p.name(expr.X.(*syntax.Name))
1038 def := ir.AsNode(name.Def)
1040 base.Errorf("undefined: %v", name)
1044 if def.Op() != ir.OPACK {
1045 base.Errorf("%v is not a package", name)
1046 pkg = types.LocalPkg
1048 def := def.(*ir.PkgName)
1052 return pkg.Lookup(expr.Sel.Value)
1054 panic(fmt.Sprintf("unexpected packname: %#v", expr))
1057 func (p *noder) embedded(typ syntax.Expr) *ir.Field {
1058 op, isStar := typ.(*syntax.Operation)
1060 if op.Op != syntax.Mul || op.Y != nil {
1061 panic("unexpected Operation")
1066 sym := p.packname(typ)
1067 n := ir.NewField(p.pos(typ), typecheck.Lookup(sym.Name), importName(sym).(ir.Ntype), nil)
1071 n.Ntype = ir.NewStarExpr(p.pos(op), n.Ntype)
1076 func (p *noder) stmts(stmts []syntax.Stmt) []ir.Node {
1077 return p.stmtsFall(stmts, false)
1080 func (p *noder) stmtsFall(stmts []syntax.Stmt, fallOK bool) []ir.Node {
1082 for i, stmt := range stmts {
1083 s := p.stmtFall(stmt, fallOK && i+1 == len(stmts))
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...)
1090 nodes = append(nodes, s)
1096 func (p *noder) stmt(stmt syntax.Stmt) ir.Node {
1097 return p.stmtFall(stmt, false)
1100 func (p *noder) stmtFall(stmt syntax.Stmt, fallOK bool) ir.Node {
1102 switch stmt := stmt.(type) {
1103 case nil, *syntax.EmptyStmt:
1105 case *syntax.LabeledStmt:
1106 return p.labeledStmt(stmt, fallOK)
1107 case *syntax.BlockStmt:
1108 l := p.blockStmt(stmt)
1110 // TODO(mdempsky): Line number?
1111 return ir.NewBlockStmt(base.Pos, nil)
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
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)
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]
1142 case *syntax.BranchStmt:
1147 case syntax.Continue:
1149 case syntax.Fallthrough:
1151 base.Errorf("fallthrough statement out of place")
1157 panic("unhandled BranchStmt")
1160 if stmt.Label != nil {
1161 sym = p.name(stmt.Label)
1163 return ir.NewBranchStmt(p.pos(stmt), op, sym)
1164 case *syntax.CallStmt:
1172 panic("unhandled CallStmt")
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 {
1182 if ln.Class != ir.PPARAMOUT {
1185 if ln.Sym().Def != ln {
1186 base.Errorf("%s is shadowed during return", ln.Sym().Name)
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)
1200 panic("unhandled Stmt")
1203 func (p *noder) assignList(expr syntax.Expr, defn ir.InitNode, colas bool) []ir.Node {
1205 return p.exprList(expr)
1208 var exprs []syntax.Expr
1209 if list, ok := expr.(*syntax.ListExpr); ok {
1210 exprs = list.ElemList
1212 exprs = []syntax.Expr{expr}
1215 res := make([]ir.Node, len(exprs))
1216 seen := make(map[*types.Sym]bool, len(exprs))
1219 for i, expr := range exprs {
1221 res[i] = ir.BlankNode
1223 name, ok := expr.(*syntax.Name)
1225 p.errorAt(expr.Pos(), "non-name %v on left side of :=", p.expr(expr))
1236 p.errorAt(expr.Pos(), "%v repeated on left side of :=", sym)
1242 if sym.Block == types.Block {
1243 res[i] = oldname(sym)
1248 n := typecheck.NewName(sym)
1249 typecheck.Declare(n, typecheck.DeclContext)
1251 defn.PtrInit().Append(ir.NewDecl(base.Pos, ir.ODCL, n))
1256 base.ErrorfAt(defn.Pos(), "no new variables on left side of :=")
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)
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)
1273 *n.PtrInit() = []ir.Node{init}
1275 if stmt.Else != nil {
1276 e := p.stmt(stmt.Else)
1277 if e.Op() == ir.OBLOCK {
1278 e := e.(*ir.BlockStmt)
1281 n.Else = []ir.Node{e}
1284 p.closeAnotherScope()
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")
1295 n := ir.NewRangeStmt(p.pos(r), nil, nil, p.expr(r.X), nil)
1298 lhs := p.assignList(r.Lhs, n, n.Def)
1304 n.Body = p.blockStmt(stmt.Body)
1305 p.closeAnotherScope()
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()
1314 func (p *noder) switchStmt(stmt *syntax.SwitchStmt) ir.Node {
1315 p.openScope(stmt.Pos())
1317 init := p.stmt(stmt.Init)
1318 n := ir.NewSwitchStmt(p.pos(stmt), p.expr(stmt.Tag), nil)
1320 *n.PtrInit() = []ir.Node{init}
1323 var tswitch *ir.TypeSwitchGuard
1324 if l := n.Tag; l != nil && l.Op() == ir.OTYPESW {
1325 tswitch = l.(*ir.TypeSwitchGuard)
1327 n.Cases = p.caseClauses(stmt.Body, tswitch, stmt.Rbrace)
1329 p.closeScope(stmt.Rbrace)
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 {
1338 p.closeScope(clause.Pos())
1340 p.openScope(clause.Pos())
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)
1347 // keep track of the instances for reporting unused
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.
1356 if _, ok := body[len(body)-1].(*syntax.EmptyStmt); !ok {
1359 body = body[:len(body)-1]
1362 n.Body = p.stmtsFall(body, true)
1363 if l := len(n.Body); l > 0 && n.Body[l-1].Op() == ir.OFALL {
1365 base.Errorf("cannot fallthrough in type switch")
1367 if i+1 == len(clauses) {
1368 base.Errorf("cannot fallthrough final case in switch")
1372 nodes = append(nodes, n)
1374 if len(clauses) > 0 {
1375 p.closeScope(rbrace)
1380 func (p *noder) selectStmt(stmt *syntax.SelectStmt) ir.Node {
1381 return ir.NewSelectStmt(p.pos(stmt), p.commClauses(stmt.Body, stmt.Rbrace))
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 {
1389 p.closeScope(clause.Pos())
1391 p.openScope(clause.Pos())
1393 nodes[i] = ir.NewCommStmt(p.pos(clause), p.stmt(clause.Comm), p.stmts(clause.Body))
1395 if len(clauses) > 0 {
1396 p.closeScope(rbrace)
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)
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.
1412 ls := ls.(*ir.ForStmt)
1415 ls := ls.(*ir.RangeStmt)
1418 ls := ls.(*ir.SwitchStmt)
1421 ls := ls.(*ir.SelectStmt)
1429 if ls.Op() == ir.OBLOCK {
1430 ls := ls.(*ir.BlockStmt)
1431 l = append(l, ls.List...)
1436 return ir.NewBlockStmt(src.NoXPos, l)
1439 var unOps = [...]ir.Op{
1440 syntax.Recv: ir.ORECV,
1441 syntax.Mul: ir.ODEREF,
1442 syntax.And: ir.OADDR,
1444 syntax.Not: ir.ONOT,
1445 syntax.Xor: ir.OBITNOT,
1446 syntax.Add: ir.OPLUS,
1447 syntax.Sub: ir.ONEG,
1450 func (p *noder) unOp(op syntax.Operator) ir.Op {
1451 if uint64(op) >= uint64(len(unOps)) || unOps[op] == 0 {
1452 panic("invalid Operator")
1457 var binOps = [...]ir.Op{
1458 syntax.OrOr: ir.OOROR,
1459 syntax.AndAnd: ir.OANDAND,
1468 syntax.Add: ir.OADD,
1469 syntax.Sub: ir.OSUB,
1471 syntax.Xor: ir.OXOR,
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,
1482 func (p *noder) binOp(op syntax.Operator) ir.Op {
1483 if uint64(op) >= uint64(len(binOps)) || binOps[op] == 0 {
1484 panic("invalid Operator")
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) {
1493 if len(s) <= 2 || types.AllowsGoVersion(types.LocalPkg, 1, 13) {
1497 if strings.Contains(s, "_") {
1498 base.ErrorfVers("go1.13", "underscores in numeric literals")
1505 if radix == 'b' || radix == 'B' {
1506 base.ErrorfVers("go1.13", "binary literals")
1509 if radix == 'o' || radix == 'O' {
1510 base.ErrorfVers("go1.13", "0o/0O-style octal literals")
1513 if lit.Kind != syntax.IntLit && (radix == 'x' || radix == 'X') {
1514 base.ErrorfVers("go1.13", "hexadecimal floating-point literals")
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
1524 return constant.MakeUnknown()
1528 case syntax.IntLit, syntax.FloatLit, syntax.ImagLit:
1529 checkLangCompat(lit)
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)
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))
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,
1557 func (p *noder) name(name *syntax.Name) *types.Sym {
1558 return typecheck.Lookup(name.Value)
1561 func (p *noder) mkname(name *syntax.Name) ir.Node {
1562 // TODO(mdempsky): Set line number?
1563 return mkname(p.name(name))
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.
1570 case ir.OTYPE, ir.OLITERAL:
1575 case ir.ONAME, ir.ONONAME, ir.OPACK:
1576 p := ir.NewParenExpr(p.pos(n), x)
1583 func (p *noder) pos(n syntax.Node) src.XPos {
1584 // TODO(gri): orig.Pos() should always be known - fix package syntax
1586 if pos := n.Pos(); pos.IsKnown() {
1587 xpos = p.makeXPos(pos)
1592 func (p *noder) setlineno(n syntax.Node) {
1598 // error is called concurrently if files are parsed concurrently.
1599 func (p *noder) error(err error) {
1600 p.err <- err.(syntax.Error)
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,
1613 "go:generate": true,
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
1623 type pragmaPos struct {
1628 type pragmaEmbed struct {
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")
1639 if len(pragma.Embeds) > 0 {
1640 for _, e := range pragma.Embeds {
1641 p.errorAt(e.Pos, "misplaced go:embed directive")
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"})
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"})
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)
1663 pragma = new(pragmas)
1667 // unused pragma; only called with old != nil.
1668 p.checkUnusedDuringParse(pragma)
1672 if strings.HasPrefix(text, "line ") {
1673 // line directives are handled by syntax package
1674 panic("unreachable")
1678 // directive must be on line by itself
1679 p.error(syntax.Error{Pos: pos, Msg: "misplaced compiler directive"})
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]"})
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.
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]
1703 p.error(syntax.Error{Pos: pos, Msg: "//go:linkname requires linkname argument or -p compiler flag"})
1706 p.linknames = append(p.linknames, linkname{pos, f[1], target})
1708 case text == "go:embed", strings.HasPrefix(text, "go:embed "):
1709 args, err := parseGoEmbed(text[len("go:embed"):])
1711 p.error(syntax.Error{Pos: pos, Msg: err.Error()})
1714 p.error(syntax.Error{Pos: pos, Msg: "usage: //go:embed pattern..."})
1717 pragma.Embeds = append(pragma.Embeds, pragmaEmbed{pos, args})
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)})
1728 p.pragcgo(pos, text)
1729 pragma.Flag |= pragmaFlag("go:cgo_import_dynamic")
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)})
1740 p.pragcgo(pos, text)
1741 fallthrough // because of //go:cgo_unsafe_args
1744 if i := strings.Index(text, " "); i >= 0 {
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)})
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)})
1756 pragma.Pos = append(pragma.Pos, pragmaPos{flag, pos})
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_")
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 {
1781 return '0' <= c && c <= '9' || 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || c == '.' || c == '_' || c == '/' || c >= utf8.RuneSelf
1784 func mkname(sym *types.Sym) ir.Node {
1786 if n.Name() != nil && n.Name().PkgName != nil {
1787 n.Name().PkgName.Used = true
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) {
1797 for args = strings.TrimSpace(args); args != ""; args = strings.TrimSpace(args) {
1803 for j, c := range args {
1804 if unicode.IsSpace(c) {
1813 i := strings.Index(args[1:], "`")
1815 return nil, fmt.Errorf("invalid quoted string in //go:embed: %s", args)
1817 path = args[1 : 1+i]
1822 for ; i < len(args); i++ {
1823 if args[i] == '\\' {
1828 q, err := strconv.Unquote(args[:i+1])
1830 return nil, fmt.Errorf("invalid quoted string in //go:embed: %s", args[:i+1])
1838 return nil, fmt.Errorf("invalid quoted string in //go:embed: %s", args)
1843 r, _ := utf8.DecodeRuneInString(args)
1844 if !unicode.IsSpace(r) {
1845 return nil, fmt.Errorf("invalid quoted string in //go:embed: %s", args)
1848 list = append(list, path)
1853 func fakeRecv() *ir.Field {
1854 return ir.NewField(base.Pos, nil, nil, types.FakeRecvType())
1857 func (p *noder) funcLit(expr *syntax.FuncLit) ir.Node {
1858 xtype := p.typeExpr(expr.Type)
1859 ntype := p.typeExpr(expr.Type)
1861 fn := ir.NewFunc(p.pos(expr))
1862 fn.SetIsHiddenClosure(ir.CurFunc != nil)
1864 fn.Nname = ir.NewNameAt(p.pos(expr), ir.BlankNode.Sym()) // filled in by typecheckclosure
1866 fn.Nname.Ntype = xtype
1869 clo := ir.NewClosureExpr(p.pos(expr), fn)
1870 fn.ClosureType = ntype
1873 p.funcBody(fn, expr.Body)
1875 // closure-specific variables are hanging off the
1876 // ordinary ones in the symbol table; see oldname.
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.
1882 v1.Name().Innermost = v.Outer
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.
1890 // That is, suppose we just finished parsing the innermost
1891 // closure f4 in this code:
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).
1911 // capturevars will decide whether to use v directly or &v.
1912 v.Outer = oldname(v.Sym()).(*ir.Name)
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
1924 func renameinit() *types.Sym {
1925 s := typecheck.LookupNum("init.", renameinitgen)
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)
1939 n := ir.AsNode(s.Def)
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)
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.
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.
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)
1963 // Link into list of active closure variables.
1964 // Popped from list in func funcLit.
1965 c.Outer = n.Innermost
1968 ir.CurFunc.ClosureVars = append(ir.CurFunc.ClosureVars, c)
1971 // return ref to closure var, not original
1978 func varEmbed(p *noder, names []*ir.Name, typ ir.Ntype, exprs []ir.Node, embeds []pragmaEmbed) (newExprs []ir.Node) {
1980 for _, decl := range p.file.DeclList {
1981 imp, ok := decl.(*syntax.ImportDecl)
1983 // imports always come first
1986 path, _ := strconv.Unquote(imp.Path.Value)
1987 if path == "embed" {
1993 pos := embeds[0].Pos
1995 p.errorAt(pos, "invalid go:embed: missing import \"embed\"")
1998 if base.Flag.Cfg.Embed.Patterns == nil {
1999 p.errorAt(pos, "invalid go:embed: build system did not supply embed configuration")
2003 p.errorAt(pos, "go:embed cannot apply to multiple vars")
2007 p.errorAt(pos, "go:embed cannot apply to var with initializer")
2011 // Should not happen, since len(exprs) == 0 now.
2012 p.errorAt(pos, "go:embed cannot apply to var without type")
2015 if typecheck.DeclContext != ir.PEXTERN {
2016 p.errorAt(pos, "go:embed cannot apply to var inside func")
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})