github.com/epfl-dcsl/gotee@v0.0.0-20200909122901-014b35f5e5e9/src/cmd/compile/internal/gc/noder.go (about) 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 gc 6 7 import ( 8 "fmt" 9 "os" 10 "path/filepath" 11 "runtime" 12 "strconv" 13 "strings" 14 "unicode/utf8" 15 16 "cmd/compile/internal/syntax" 17 "cmd/compile/internal/types" 18 "cmd/internal/objabi" 19 "cmd/internal/src" 20 ) 21 22 func parseFiles(filenames []string) uint { 23 var noders []*noder 24 // Limit the number of simultaneously open files. 25 sem := make(chan struct{}, runtime.GOMAXPROCS(0)+10) 26 27 for _, filename := range filenames { 28 p := &noder{err: make(chan syntax.Error)} 29 noders = append(noders, p) 30 31 go func(filename string) { 32 sem <- struct{}{} 33 defer func() { <-sem }() 34 defer close(p.err) 35 base := src.NewFileBase(filename, absFilename(filename)) 36 37 f, err := os.Open(filename) 38 if err != nil { 39 p.error(syntax.Error{Pos: src.MakePos(base, 0, 0), Msg: err.Error()}) 40 return 41 } 42 defer f.Close() 43 44 p.file, _ = syntax.Parse(base, f, p.error, p.pragma, fileh, syntax.CheckBranches) // errors are tracked via p.error 45 }(filename) 46 } 47 48 var lines uint 49 for _, p := range noders { 50 for e := range p.err { 51 yyerrorpos(e.Pos, "%s", e.Msg) 52 } 53 54 p.node() 55 lines += p.file.Lines 56 p.file = nil // release memory 57 58 if nsyntaxerrors != 0 { 59 errorexit() 60 } 61 // Always run testdclstack here, even when debug_dclstack is not set, as a sanity measure. 62 testdclstack() 63 } 64 65 return lines 66 } 67 68 func yyerrorpos(pos src.Pos, format string, args ...interface{}) { 69 yyerrorl(Ctxt.PosTable.XPos(pos), format, args...) 70 } 71 72 var pathPrefix string 73 74 func fileh(name string) string { 75 return objabi.AbsFile("", name, pathPrefix) 76 } 77 78 func absFilename(name string) string { 79 return objabi.AbsFile(Ctxt.Pathname, name, pathPrefix) 80 } 81 82 // noder transforms package syntax's AST into a Node tree. 83 type noder struct { 84 file *syntax.File 85 linknames []linkname 86 pragcgobuf string 87 err chan syntax.Error 88 scope ScopeID 89 } 90 91 func (p *noder) funchdr(n *Node) ScopeID { 92 old := p.scope 93 p.scope = 0 94 funchdr(n) 95 return old 96 } 97 98 func (p *noder) funcbody(old ScopeID) { 99 funcbody() 100 p.scope = old 101 } 102 103 func (p *noder) openScope(pos src.Pos) { 104 types.Markdcl() 105 106 if trackScopes { 107 Curfn.Func.Parents = append(Curfn.Func.Parents, p.scope) 108 p.scope = ScopeID(len(Curfn.Func.Parents)) 109 110 p.markScope(pos) 111 } 112 } 113 114 func (p *noder) closeScope(pos src.Pos) { 115 types.Popdcl() 116 117 if trackScopes { 118 p.scope = Curfn.Func.Parents[p.scope-1] 119 120 p.markScope(pos) 121 } 122 } 123 124 func (p *noder) markScope(pos src.Pos) { 125 xpos := Ctxt.PosTable.XPos(pos) 126 if i := len(Curfn.Func.Marks); i > 0 && Curfn.Func.Marks[i-1].Pos == xpos { 127 Curfn.Func.Marks[i-1].Scope = p.scope 128 } else { 129 Curfn.Func.Marks = append(Curfn.Func.Marks, Mark{xpos, p.scope}) 130 } 131 } 132 133 // closeAnotherScope is like closeScope, but it reuses the same mark 134 // position as the last closeScope call. This is useful for "for" and 135 // "if" statements, as their implicit blocks always end at the same 136 // position as an explicit block. 137 func (p *noder) closeAnotherScope() { 138 types.Popdcl() 139 140 if trackScopes { 141 p.scope = Curfn.Func.Parents[p.scope-1] 142 Curfn.Func.Marks[len(Curfn.Func.Marks)-1].Scope = p.scope 143 } 144 } 145 146 // linkname records a //go:linkname directive. 147 type linkname struct { 148 pos src.Pos 149 local string 150 remote string 151 } 152 153 func (p *noder) node() { 154 types.Block = 1 155 imported_unsafe = false 156 157 p.lineno(p.file.PkgName) 158 mkpackage(p.file.PkgName.Value) 159 160 xtop = append(xtop, p.decls(p.file.DeclList)...) 161 162 for _, n := range p.linknames { 163 if imported_unsafe { 164 lookup(n.local).Linkname = n.remote 165 } else { 166 yyerrorpos(n.pos, "//go:linkname only allowed in Go files that import \"unsafe\"") 167 } 168 } 169 170 pragcgobuf += p.pragcgobuf 171 lineno = src.NoXPos 172 clearImports() 173 } 174 175 func (p *noder) decls(decls []syntax.Decl) (l []*Node) { 176 var cs constState 177 178 for _, decl := range decls { 179 p.lineno(decl) 180 switch decl := decl.(type) { 181 case *syntax.ImportDecl: 182 p.importDecl(decl) 183 184 case *syntax.VarDecl: 185 l = append(l, p.varDecl(decl)...) 186 187 case *syntax.ConstDecl: 188 l = append(l, p.constDecl(decl, &cs)...) 189 190 case *syntax.TypeDecl: 191 l = append(l, p.typeDecl(decl)) 192 193 case *syntax.FuncDecl: 194 l = append(l, p.funcDecl(decl)) 195 196 default: 197 panic("unhandled Decl") 198 } 199 } 200 201 return 202 } 203 204 func (p *noder) importDecl(imp *syntax.ImportDecl) { 205 val := p.basicLit(imp.Path) 206 ipkg := importfile(&val) 207 208 if ipkg == nil { 209 if nerrors == 0 { 210 Fatalf("phase error in import") 211 } 212 return 213 } 214 215 ipkg.Direct = true 216 217 var my *types.Sym 218 if imp.LocalPkgName != nil { 219 my = p.name(imp.LocalPkgName) 220 } else { 221 my = lookup(ipkg.Name) 222 } 223 224 pack := p.nod(imp, OPACK, nil, nil) 225 pack.Sym = my 226 pack.Name.Pkg = ipkg 227 228 switch my.Name { 229 case ".": 230 importdot(ipkg, pack) 231 return 232 case "init": 233 yyerrorl(pack.Pos, "cannot import package as init - init must be a func") 234 return 235 case "_": 236 return 237 } 238 if my.Def != nil { 239 lineno = pack.Pos 240 redeclare(my, "as imported package name") 241 } 242 my.Def = asTypesNode(pack) 243 my.Lastlineno = pack.Pos 244 my.Block = 1 // at top level 245 } 246 247 func (p *noder) varDecl(decl *syntax.VarDecl) []*Node { 248 names := p.declNames(decl.NameList) 249 typ := p.typeExprOrNil(decl.Type) 250 251 var exprs []*Node 252 if decl.Values != nil { 253 exprs = p.exprList(decl.Values) 254 } 255 256 p.lineno(decl) 257 return variter(names, typ, exprs) 258 } 259 260 // constState tracks state between constant specifiers within a 261 // declaration group. This state is kept separate from noder so nested 262 // constant declarations are handled correctly (e.g., issue 15550). 263 type constState struct { 264 group *syntax.Group 265 typ *Node 266 values []*Node 267 iota int64 268 } 269 270 func (p *noder) constDecl(decl *syntax.ConstDecl, cs *constState) []*Node { 271 if decl.Group == nil || decl.Group != cs.group { 272 *cs = constState{ 273 group: decl.Group, 274 } 275 } 276 277 names := p.declNames(decl.NameList) 278 typ := p.typeExprOrNil(decl.Type) 279 280 var values []*Node 281 if decl.Values != nil { 282 values = p.exprList(decl.Values) 283 cs.typ, cs.values = typ, values 284 } else { 285 if typ != nil { 286 yyerror("const declaration cannot have type without expression") 287 } 288 typ, values = cs.typ, cs.values 289 } 290 291 var nn []*Node 292 for i, n := range names { 293 if i >= len(values) { 294 yyerror("missing value in const declaration") 295 break 296 } 297 v := values[i] 298 if decl.Values == nil { 299 v = treecopy(v, n.Pos) 300 } 301 302 n.Op = OLITERAL 303 declare(n, dclcontext) 304 305 n.Name.Param.Ntype = typ 306 n.Name.Defn = v 307 n.SetIota(cs.iota) 308 309 nn = append(nn, p.nod(decl, ODCLCONST, n, nil)) 310 } 311 312 if len(values) > len(names) { 313 yyerror("extra expression in const declaration") 314 } 315 316 cs.iota++ 317 318 return nn 319 } 320 321 func (p *noder) typeDecl(decl *syntax.TypeDecl) *Node { 322 n := p.declName(decl.Name) 323 n.Op = OTYPE 324 declare(n, dclcontext) 325 326 // decl.Type may be nil but in that case we got a syntax error during parsing 327 typ := p.typeExprOrNil(decl.Type) 328 329 param := n.Name.Param 330 param.Ntype = typ 331 param.Pragma = decl.Pragma 332 param.Alias = decl.Alias 333 if param.Alias && param.Pragma != 0 { 334 yyerror("cannot specify directive with type alias") 335 param.Pragma = 0 336 } 337 338 return p.nod(decl, ODCLTYPE, n, nil) 339 340 } 341 342 func (p *noder) declNames(names []*syntax.Name) []*Node { 343 var nodes []*Node 344 for _, name := range names { 345 nodes = append(nodes, p.declName(name)) 346 } 347 return nodes 348 } 349 350 func (p *noder) declName(name *syntax.Name) *Node { 351 // TODO(mdempsky): Set lineno? 352 return dclname(p.name(name)) 353 } 354 355 func (p *noder) funcDecl(fun *syntax.FuncDecl) *Node { 356 name := p.name(fun.Name) 357 t := p.signature(fun.Recv, fun.Type) 358 f := p.nod(fun, ODCLFUNC, nil, nil) 359 360 if fun.Recv == nil { 361 if name.Name == "init" { 362 name = renameinit() 363 if t.List.Len() > 0 || t.Rlist.Len() > 0 { 364 yyerrorl(f.Pos, "func init must have no arguments and no return values") 365 } 366 } 367 368 if localpkg.Name == "main" && name.Name == "main" { 369 if t.List.Len() > 0 || t.Rlist.Len() > 0 { 370 yyerrorl(f.Pos, "func main must have no arguments and no return values") 371 } 372 } 373 } else { 374 f.Func.Shortname = name 375 name = nblank.Sym // filled in by typecheckfunc 376 } 377 378 f.Func.Nname = newfuncname(name) 379 f.Func.Nname.Name.Defn = f 380 f.Func.Nname.Name.Param.Ntype = t 381 382 pragma := fun.Pragma 383 f.Func.Pragma = fun.Pragma 384 f.SetNoescape(pragma&Noescape != 0) 385 if pragma&Systemstack != 0 && pragma&Nosplit != 0 { 386 yyerrorl(f.Pos, "go:nosplit and go:systemstack cannot be combined") 387 } 388 389 if fun.Recv == nil { 390 declare(f.Func.Nname, PFUNC) 391 } 392 393 oldScope := p.funchdr(f) 394 395 if fun.Body != nil { 396 if f.Noescape() { 397 yyerrorl(f.Pos, "can only use //go:noescape with external func implementations") 398 } 399 400 body := p.stmts(fun.Body.List) 401 if body == nil { 402 body = []*Node{p.nod(fun, OEMPTY, nil, nil)} 403 } 404 f.Nbody.Set(body) 405 406 lineno = Ctxt.PosTable.XPos(fun.Body.Rbrace) 407 f.Func.Endlineno = lineno 408 } else { 409 if pure_go || strings.HasPrefix(f.funcname(), "init.") { 410 yyerrorl(f.Pos, "missing function body") 411 } 412 } 413 414 p.funcbody(oldScope) 415 return f 416 } 417 418 func (p *noder) signature(recv *syntax.Field, typ *syntax.FuncType) *Node { 419 n := p.nod(typ, OTFUNC, nil, nil) 420 if recv != nil { 421 n.Left = p.param(recv, false, false) 422 } 423 n.List.Set(p.params(typ.ParamList, true)) 424 n.Rlist.Set(p.params(typ.ResultList, false)) 425 return n 426 } 427 428 func (p *noder) params(params []*syntax.Field, dddOk bool) []*Node { 429 var nodes []*Node 430 for i, param := range params { 431 p.lineno(param) 432 nodes = append(nodes, p.param(param, dddOk, i+1 == len(params))) 433 } 434 return nodes 435 } 436 437 func (p *noder) param(param *syntax.Field, dddOk, final bool) *Node { 438 var name *Node 439 if param.Name != nil { 440 name = p.newname(param.Name) 441 } 442 443 typ := p.typeExpr(param.Type) 444 n := p.nod(param, ODCLFIELD, name, typ) 445 446 // rewrite ...T parameter 447 if typ.Op == ODDD { 448 if !dddOk { 449 yyerror("cannot use ... in receiver or result parameter list") 450 } else if !final { 451 yyerror("can only use ... with final parameter in list") 452 } 453 typ.Op = OTARRAY 454 typ.Right = typ.Left 455 typ.Left = nil 456 n.SetIsddd(true) 457 if n.Left != nil { 458 n.Left.SetIsddd(true) 459 } 460 } 461 462 return n 463 } 464 465 func (p *noder) exprList(expr syntax.Expr) []*Node { 466 if list, ok := expr.(*syntax.ListExpr); ok { 467 return p.exprs(list.ElemList) 468 } 469 return []*Node{p.expr(expr)} 470 } 471 472 func (p *noder) exprs(exprs []syntax.Expr) []*Node { 473 var nodes []*Node 474 for _, expr := range exprs { 475 nodes = append(nodes, p.expr(expr)) 476 } 477 return nodes 478 } 479 480 func (p *noder) expr(expr syntax.Expr) *Node { 481 p.lineno(expr) 482 switch expr := expr.(type) { 483 case nil, *syntax.BadExpr: 484 return nil 485 case *syntax.Name: 486 return p.mkname(expr) 487 case *syntax.BasicLit: 488 return p.setlineno(expr, nodlit(p.basicLit(expr))) 489 490 case *syntax.CompositeLit: 491 n := p.nod(expr, OCOMPLIT, nil, nil) 492 if expr.Type != nil { 493 n.Right = p.expr(expr.Type) 494 } 495 l := p.exprs(expr.ElemList) 496 for i, e := range l { 497 l[i] = p.wrapname(expr.ElemList[i], e) 498 } 499 n.List.Set(l) 500 lineno = Ctxt.PosTable.XPos(expr.Rbrace) 501 return n 502 case *syntax.KeyValueExpr: 503 return p.nod(expr, OKEY, p.expr(expr.Key), p.wrapname(expr.Value, p.expr(expr.Value))) 504 case *syntax.FuncLit: 505 return p.funcLit(expr) 506 case *syntax.ParenExpr: 507 return p.nod(expr, OPAREN, p.expr(expr.X), nil) 508 case *syntax.SelectorExpr: 509 // parser.new_dotname 510 obj := p.expr(expr.X) 511 if obj.Op == OPACK { 512 obj.Name.SetUsed(true) 513 return oldname(restrictlookup(expr.Sel.Value, obj.Name.Pkg)) 514 } 515 return p.setlineno(expr, nodSym(OXDOT, obj, p.name(expr.Sel))) 516 case *syntax.IndexExpr: 517 return p.nod(expr, OINDEX, p.expr(expr.X), p.expr(expr.Index)) 518 case *syntax.SliceExpr: 519 op := OSLICE 520 if expr.Full { 521 op = OSLICE3 522 } 523 n := p.nod(expr, op, p.expr(expr.X), nil) 524 var index [3]*Node 525 for i, x := range expr.Index { 526 if x != nil { 527 index[i] = p.expr(x) 528 } 529 } 530 n.SetSliceBounds(index[0], index[1], index[2]) 531 return n 532 case *syntax.AssertExpr: 533 if expr.Type == nil { 534 panic("unexpected AssertExpr") 535 } 536 // TODO(mdempsky): parser.pexpr uses p.expr(), but 537 // seems like the type field should be parsed with 538 // ntype? Shrug, doesn't matter here. 539 return p.nod(expr, ODOTTYPE, p.expr(expr.X), p.expr(expr.Type)) 540 case *syntax.Operation: 541 if expr.Op == syntax.Add && expr.Y != nil { 542 return p.sum(expr) 543 } 544 x := p.expr(expr.X) 545 if expr.Y == nil { 546 if expr.Op == syntax.And { 547 x = unparen(x) // TODO(mdempsky): Needed? 548 if x.Op == OCOMPLIT { 549 // Special case for &T{...}: turn into (*T){...}. 550 // TODO(mdempsky): Switch back to p.nod after we 551 // get rid of gcCompat. 552 x.Right = nod(OIND, x.Right, nil) 553 x.Right.SetImplicit(true) 554 return x 555 } 556 } 557 return p.nod(expr, p.unOp(expr.Op), x, nil) 558 } 559 return p.nod(expr, p.binOp(expr.Op), x, p.expr(expr.Y)) 560 case *syntax.CallExpr: 561 n := p.nod(expr, OCALL, p.expr(expr.Fun), nil) 562 n.List.Set(p.exprs(expr.ArgList)) 563 n.SetIsddd(expr.HasDots) 564 return n 565 566 case *syntax.ArrayType: 567 var len *Node 568 if expr.Len != nil { 569 len = p.expr(expr.Len) 570 } else { 571 len = p.nod(expr, ODDD, nil, nil) 572 } 573 return p.nod(expr, OTARRAY, len, p.typeExpr(expr.Elem)) 574 case *syntax.SliceType: 575 return p.nod(expr, OTARRAY, nil, p.typeExpr(expr.Elem)) 576 case *syntax.DotsType: 577 return p.nod(expr, ODDD, p.typeExpr(expr.Elem), nil) 578 case *syntax.StructType: 579 return p.structType(expr) 580 case *syntax.InterfaceType: 581 return p.interfaceType(expr) 582 case *syntax.FuncType: 583 return p.signature(nil, expr) 584 case *syntax.MapType: 585 return p.nod(expr, OTMAP, p.typeExpr(expr.Key), p.typeExpr(expr.Value)) 586 case *syntax.ChanType: 587 n := p.nod(expr, OTCHAN, p.typeExpr(expr.Elem), nil) 588 n.Etype = types.EType(p.chanDir(expr.Dir)) 589 return n 590 591 case *syntax.TypeSwitchGuard: 592 n := p.nod(expr, OTYPESW, nil, p.expr(expr.X)) 593 if expr.Lhs != nil { 594 n.Left = p.declName(expr.Lhs) 595 if isblank(n.Left) { 596 yyerror("invalid variable name %v in type switch", n.Left) 597 } 598 } 599 return n 600 } 601 panic("unhandled Expr") 602 } 603 604 // sum efficiently handles very large summation expressions (such as 605 // in issue #16394). In particular, it avoids left recursion and 606 // collapses string literals. 607 func (p *noder) sum(x syntax.Expr) *Node { 608 // While we need to handle long sums with asymptotic 609 // efficiency, the vast majority of sums are very small: ~95% 610 // have only 2 or 3 operands, and ~99% of string literals are 611 // never concatenated. 612 613 adds := make([]*syntax.Operation, 0, 2) 614 for { 615 add, ok := x.(*syntax.Operation) 616 if !ok || add.Op != syntax.Add || add.Y == nil { 617 break 618 } 619 adds = append(adds, add) 620 x = add.X 621 } 622 623 // nstr is the current rightmost string literal in the 624 // summation (if any), and chunks holds its accumulated 625 // substrings. 626 // 627 // Consider the expression x + "a" + "b" + "c" + y. When we 628 // reach the string literal "a", we assign nstr to point to 629 // its corresponding Node and initialize chunks to {"a"}. 630 // Visiting the subsequent string literals "b" and "c", we 631 // simply append their values to chunks. Finally, when we 632 // reach the non-constant operand y, we'll join chunks to form 633 // "abc" and reassign the "a" string literal's value. 634 // 635 // N.B., we need to be careful about named string constants 636 // (indicated by Sym != nil) because 1) we can't modify their 637 // value, as doing so would affect other uses of the string 638 // constant, and 2) they may have types, which we need to 639 // handle correctly. For now, we avoid these problems by 640 // treating named string constants the same as non-constant 641 // operands. 642 var nstr *Node 643 chunks := make([]string, 0, 1) 644 645 n := p.expr(x) 646 if Isconst(n, CTSTR) && n.Sym == nil { 647 nstr = n 648 chunks = append(chunks, nstr.Val().U.(string)) 649 } 650 651 for i := len(adds) - 1; i >= 0; i-- { 652 add := adds[i] 653 654 r := p.expr(add.Y) 655 if Isconst(r, CTSTR) && r.Sym == nil { 656 if nstr != nil { 657 // Collapse r into nstr instead of adding to n. 658 chunks = append(chunks, r.Val().U.(string)) 659 continue 660 } 661 662 nstr = r 663 chunks = append(chunks, nstr.Val().U.(string)) 664 } else { 665 if len(chunks) > 1 { 666 nstr.SetVal(Val{U: strings.Join(chunks, "")}) 667 } 668 nstr = nil 669 chunks = chunks[:0] 670 } 671 n = p.nod(add, OADD, n, r) 672 } 673 if len(chunks) > 1 { 674 nstr.SetVal(Val{U: strings.Join(chunks, "")}) 675 } 676 677 return n 678 } 679 680 func (p *noder) typeExpr(typ syntax.Expr) *Node { 681 // TODO(mdempsky): Be stricter? typecheck should handle errors anyway. 682 return p.expr(typ) 683 } 684 685 func (p *noder) typeExprOrNil(typ syntax.Expr) *Node { 686 if typ != nil { 687 return p.expr(typ) 688 } 689 return nil 690 } 691 692 func (p *noder) chanDir(dir syntax.ChanDir) types.ChanDir { 693 switch dir { 694 case 0: 695 return types.Cboth 696 case syntax.SendOnly: 697 return types.Csend 698 case syntax.RecvOnly: 699 return types.Crecv 700 } 701 panic("unhandled ChanDir") 702 } 703 704 func (p *noder) structType(expr *syntax.StructType) *Node { 705 var l []*Node 706 for i, field := range expr.FieldList { 707 p.lineno(field) 708 var n *Node 709 if field.Name == nil { 710 n = p.embedded(field.Type) 711 } else { 712 n = p.nod(field, ODCLFIELD, p.newname(field.Name), p.typeExpr(field.Type)) 713 } 714 if i < len(expr.TagList) && expr.TagList[i] != nil { 715 n.SetVal(p.basicLit(expr.TagList[i])) 716 } 717 l = append(l, n) 718 } 719 720 p.lineno(expr) 721 n := p.nod(expr, OTSTRUCT, nil, nil) 722 n.List.Set(l) 723 return n 724 } 725 726 func (p *noder) interfaceType(expr *syntax.InterfaceType) *Node { 727 var l []*Node 728 for _, method := range expr.MethodList { 729 p.lineno(method) 730 var n *Node 731 if method.Name == nil { 732 n = p.nod(method, ODCLFIELD, nil, oldname(p.packname(method.Type))) 733 } else { 734 mname := p.newname(method.Name) 735 sig := p.typeExpr(method.Type) 736 sig.Left = fakeRecv() 737 n = p.nod(method, ODCLFIELD, mname, sig) 738 ifacedcl(n) 739 } 740 l = append(l, n) 741 } 742 743 n := p.nod(expr, OTINTER, nil, nil) 744 n.List.Set(l) 745 return n 746 } 747 748 func (p *noder) packname(expr syntax.Expr) *types.Sym { 749 switch expr := expr.(type) { 750 case *syntax.Name: 751 name := p.name(expr) 752 if n := oldname(name); n.Name != nil && n.Name.Pack != nil { 753 n.Name.Pack.Name.SetUsed(true) 754 } 755 return name 756 case *syntax.SelectorExpr: 757 name := p.name(expr.X.(*syntax.Name)) 758 var pkg *types.Pkg 759 if asNode(name.Def) == nil || asNode(name.Def).Op != OPACK { 760 yyerror("%v is not a package", name) 761 pkg = localpkg 762 } else { 763 asNode(name.Def).Name.SetUsed(true) 764 pkg = asNode(name.Def).Name.Pkg 765 } 766 return restrictlookup(expr.Sel.Value, pkg) 767 } 768 panic(fmt.Sprintf("unexpected packname: %#v", expr)) 769 } 770 771 func (p *noder) embedded(typ syntax.Expr) *Node { 772 op, isStar := typ.(*syntax.Operation) 773 if isStar { 774 if op.Op != syntax.Mul || op.Y != nil { 775 panic("unexpected Operation") 776 } 777 typ = op.X 778 } 779 780 sym := p.packname(typ) 781 n := nod(ODCLFIELD, newname(lookup(sym.Name)), oldname(sym)) 782 n.SetEmbedded(true) 783 784 if isStar { 785 n.Right = p.nod(op, OIND, n.Right, nil) 786 } 787 return n 788 } 789 790 func (p *noder) stmts(stmts []syntax.Stmt) []*Node { 791 return p.stmtsFall(stmts, false) 792 } 793 794 func (p *noder) stmtsFall(stmts []syntax.Stmt, fallOK bool) []*Node { 795 var nodes []*Node 796 for i, stmt := range stmts { 797 s := p.stmtFall(stmt, fallOK && i+1 == len(stmts)) 798 if s == nil { 799 } else if s.Op == OBLOCK && s.Ninit.Len() == 0 { 800 nodes = append(nodes, s.List.Slice()...) 801 } else { 802 nodes = append(nodes, s) 803 } 804 } 805 return nodes 806 } 807 808 func (p *noder) stmt(stmt syntax.Stmt) *Node { 809 return p.stmtFall(stmt, false) 810 } 811 812 func (p *noder) stmtFall(stmt syntax.Stmt, fallOK bool) *Node { 813 p.lineno(stmt) 814 switch stmt := stmt.(type) { 815 case *syntax.EmptyStmt: 816 return nil 817 case *syntax.LabeledStmt: 818 return p.labeledStmt(stmt, fallOK) 819 case *syntax.BlockStmt: 820 l := p.blockStmt(stmt) 821 if len(l) == 0 { 822 // TODO(mdempsky): Line number? 823 return nod(OEMPTY, nil, nil) 824 } 825 return liststmt(l) 826 case *syntax.ExprStmt: 827 return p.wrapname(stmt, p.expr(stmt.X)) 828 case *syntax.SendStmt: 829 return p.nod(stmt, OSEND, p.expr(stmt.Chan), p.expr(stmt.Value)) 830 case *syntax.DeclStmt: 831 return liststmt(p.decls(stmt.DeclList)) 832 case *syntax.AssignStmt: 833 if stmt.Op != 0 && stmt.Op != syntax.Def { 834 n := p.nod(stmt, OASOP, p.expr(stmt.Lhs), p.expr(stmt.Rhs)) 835 n.SetImplicit(stmt.Rhs == syntax.ImplicitOne) 836 n.Etype = types.EType(p.binOp(stmt.Op)) 837 return n 838 } 839 840 n := p.nod(stmt, OAS, nil, nil) // assume common case 841 842 rhs := p.exprList(stmt.Rhs) 843 lhs := p.assignList(stmt.Lhs, n, stmt.Op == syntax.Def) 844 845 if len(lhs) == 1 && len(rhs) == 1 { 846 // common case 847 n.Left = lhs[0] 848 n.Right = rhs[0] 849 } else { 850 n.Op = OAS2 851 n.List.Set(lhs) 852 n.Rlist.Set(rhs) 853 } 854 return n 855 856 case *syntax.BranchStmt: 857 var op Op 858 switch stmt.Tok { 859 case syntax.Break: 860 op = OBREAK 861 case syntax.Continue: 862 op = OCONTINUE 863 case syntax.Fallthrough: 864 if !fallOK { 865 yyerror("fallthrough statement out of place") 866 } 867 op = OFALL 868 case syntax.Goto: 869 op = OGOTO 870 default: 871 panic("unhandled BranchStmt") 872 } 873 n := p.nod(stmt, op, nil, nil) 874 if stmt.Label != nil { 875 n.Left = p.newname(stmt.Label) 876 } 877 return n 878 case *syntax.CallStmt: 879 var op Op 880 switch stmt.Tok { 881 case syntax.Defer: 882 op = ODEFER 883 case syntax.Go: 884 op = OPROC 885 case syntax.Gosecure: 886 op = OGOSECURE 887 default: 888 panic("unhandled CallStmt") 889 } 890 return p.nod(stmt, op, p.expr(stmt.Call), nil) 891 case *syntax.ReturnStmt: 892 var results []*Node 893 if stmt.Results != nil { 894 results = p.exprList(stmt.Results) 895 } 896 n := p.nod(stmt, ORETURN, nil, nil) 897 n.List.Set(results) 898 if n.List.Len() == 0 && Curfn != nil { 899 for _, ln := range Curfn.Func.Dcl { 900 if ln.Class() == PPARAM { 901 continue 902 } 903 if ln.Class() != PPARAMOUT { 904 break 905 } 906 if asNode(ln.Sym.Def) != ln { 907 yyerror("%s is shadowed during return", ln.Sym.Name) 908 } 909 } 910 } 911 return n 912 case *syntax.IfStmt: 913 return p.ifStmt(stmt) 914 case *syntax.ForStmt: 915 return p.forStmt(stmt) 916 case *syntax.SwitchStmt: 917 return p.switchStmt(stmt) 918 case *syntax.SelectStmt: 919 return p.selectStmt(stmt) 920 } 921 panic("unhandled Stmt") 922 } 923 924 func (p *noder) assignList(expr syntax.Expr, defn *Node, colas bool) []*Node { 925 if !colas { 926 return p.exprList(expr) 927 } 928 929 defn.SetColas(true) 930 931 var exprs []syntax.Expr 932 if list, ok := expr.(*syntax.ListExpr); ok { 933 exprs = list.ElemList 934 } else { 935 exprs = []syntax.Expr{expr} 936 } 937 938 res := make([]*Node, len(exprs)) 939 seen := make(map[*types.Sym]bool, len(exprs)) 940 941 newOrErr := false 942 for i, expr := range exprs { 943 p.lineno(expr) 944 res[i] = nblank 945 946 name, ok := expr.(*syntax.Name) 947 if !ok { 948 yyerrorpos(expr.Pos(), "non-name %v on left side of :=", p.expr(expr)) 949 newOrErr = true 950 continue 951 } 952 953 sym := p.name(name) 954 if sym.IsBlank() { 955 continue 956 } 957 958 if seen[sym] { 959 yyerrorpos(expr.Pos(), "%v repeated on left side of :=", sym) 960 newOrErr = true 961 continue 962 } 963 seen[sym] = true 964 965 if sym.Block == types.Block { 966 res[i] = oldname(sym) 967 continue 968 } 969 970 newOrErr = true 971 n := newname(sym) 972 declare(n, dclcontext) 973 n.Name.Defn = defn 974 defn.Ninit.Append(nod(ODCL, n, nil)) 975 res[i] = n 976 } 977 978 if !newOrErr { 979 yyerrorl(defn.Pos, "no new variables on left side of :=") 980 } 981 return res 982 } 983 984 func (p *noder) blockStmt(stmt *syntax.BlockStmt) []*Node { 985 p.openScope(stmt.Pos()) 986 nodes := p.stmts(stmt.List) 987 p.closeScope(stmt.Rbrace) 988 return nodes 989 } 990 991 func (p *noder) ifStmt(stmt *syntax.IfStmt) *Node { 992 p.openScope(stmt.Pos()) 993 n := p.nod(stmt, OIF, nil, nil) 994 if stmt.Init != nil { 995 n.Ninit.Set1(p.stmt(stmt.Init)) 996 } 997 if stmt.Cond != nil { 998 n.Left = p.expr(stmt.Cond) 999 } 1000 n.Nbody.Set(p.blockStmt(stmt.Then)) 1001 if stmt.Else != nil { 1002 e := p.stmt(stmt.Else) 1003 if e.Op == OBLOCK && e.Ninit.Len() == 0 { 1004 n.Rlist.Set(e.List.Slice()) 1005 } else { 1006 n.Rlist.Set1(e) 1007 } 1008 } 1009 p.closeAnotherScope() 1010 return n 1011 } 1012 1013 func (p *noder) forStmt(stmt *syntax.ForStmt) *Node { 1014 p.openScope(stmt.Pos()) 1015 var n *Node 1016 if r, ok := stmt.Init.(*syntax.RangeClause); ok { 1017 if stmt.Cond != nil || stmt.Post != nil { 1018 panic("unexpected RangeClause") 1019 } 1020 1021 n = p.nod(r, ORANGE, nil, p.expr(r.X)) 1022 if r.Lhs != nil { 1023 n.List.Set(p.assignList(r.Lhs, n, r.Def)) 1024 } 1025 } else { 1026 n = p.nod(stmt, OFOR, nil, nil) 1027 if stmt.Init != nil { 1028 n.Ninit.Set1(p.stmt(stmt.Init)) 1029 } 1030 if stmt.Cond != nil { 1031 n.Left = p.expr(stmt.Cond) 1032 } 1033 if stmt.Post != nil { 1034 n.Right = p.stmt(stmt.Post) 1035 } 1036 } 1037 n.Nbody.Set(p.blockStmt(stmt.Body)) 1038 p.closeAnotherScope() 1039 return n 1040 } 1041 1042 func (p *noder) switchStmt(stmt *syntax.SwitchStmt) *Node { 1043 p.openScope(stmt.Pos()) 1044 n := p.nod(stmt, OSWITCH, nil, nil) 1045 if stmt.Init != nil { 1046 n.Ninit.Set1(p.stmt(stmt.Init)) 1047 } 1048 if stmt.Tag != nil { 1049 n.Left = p.expr(stmt.Tag) 1050 } 1051 1052 tswitch := n.Left 1053 if tswitch != nil && tswitch.Op != OTYPESW { 1054 tswitch = nil 1055 } 1056 n.List.Set(p.caseClauses(stmt.Body, tswitch, stmt.Rbrace)) 1057 1058 p.closeScope(stmt.Rbrace) 1059 return n 1060 } 1061 1062 func (p *noder) caseClauses(clauses []*syntax.CaseClause, tswitch *Node, rbrace src.Pos) []*Node { 1063 var nodes []*Node 1064 for i, clause := range clauses { 1065 p.lineno(clause) 1066 if i > 0 { 1067 p.closeScope(clause.Pos()) 1068 } 1069 p.openScope(clause.Pos()) 1070 1071 n := p.nod(clause, OXCASE, nil, nil) 1072 if clause.Cases != nil { 1073 n.List.Set(p.exprList(clause.Cases)) 1074 } 1075 if tswitch != nil && tswitch.Left != nil { 1076 nn := newname(tswitch.Left.Sym) 1077 declare(nn, dclcontext) 1078 n.Rlist.Set1(nn) 1079 // keep track of the instances for reporting unused 1080 nn.Name.Defn = tswitch 1081 } 1082 1083 // Trim trailing empty statements. We omit them from 1084 // the Node AST anyway, and it's easier to identify 1085 // out-of-place fallthrough statements without them. 1086 body := clause.Body 1087 for len(body) > 0 { 1088 if _, ok := body[len(body)-1].(*syntax.EmptyStmt); !ok { 1089 break 1090 } 1091 body = body[:len(body)-1] 1092 } 1093 1094 n.Nbody.Set(p.stmtsFall(body, true)) 1095 if l := n.Nbody.Len(); l > 0 && n.Nbody.Index(l-1).Op == OFALL { 1096 if tswitch != nil { 1097 yyerror("cannot fallthrough in type switch") 1098 } 1099 if i+1 == len(clauses) { 1100 yyerror("cannot fallthrough final case in switch") 1101 } 1102 } 1103 1104 nodes = append(nodes, n) 1105 } 1106 if len(clauses) > 0 { 1107 p.closeScope(rbrace) 1108 } 1109 return nodes 1110 } 1111 1112 func (p *noder) selectStmt(stmt *syntax.SelectStmt) *Node { 1113 n := p.nod(stmt, OSELECT, nil, nil) 1114 n.List.Set(p.commClauses(stmt.Body, stmt.Rbrace)) 1115 return n 1116 } 1117 1118 func (p *noder) commClauses(clauses []*syntax.CommClause, rbrace src.Pos) []*Node { 1119 var nodes []*Node 1120 for i, clause := range clauses { 1121 p.lineno(clause) 1122 if i > 0 { 1123 p.closeScope(clause.Pos()) 1124 } 1125 p.openScope(clause.Pos()) 1126 1127 n := p.nod(clause, OXCASE, nil, nil) 1128 if clause.Comm != nil { 1129 n.List.Set1(p.stmt(clause.Comm)) 1130 } 1131 n.Nbody.Set(p.stmts(clause.Body)) 1132 nodes = append(nodes, n) 1133 } 1134 if len(clauses) > 0 { 1135 p.closeScope(rbrace) 1136 } 1137 return nodes 1138 } 1139 1140 func (p *noder) labeledStmt(label *syntax.LabeledStmt, fallOK bool) *Node { 1141 lhs := p.nod(label, OLABEL, p.newname(label.Label), nil) 1142 1143 var ls *Node 1144 if label.Stmt != nil { // TODO(mdempsky): Should always be present. 1145 ls = p.stmtFall(label.Stmt, fallOK) 1146 } 1147 1148 lhs.Name.Defn = ls 1149 l := []*Node{lhs} 1150 if ls != nil { 1151 if ls.Op == OBLOCK && ls.Ninit.Len() == 0 { 1152 l = append(l, ls.List.Slice()...) 1153 } else { 1154 l = append(l, ls) 1155 } 1156 } 1157 return liststmt(l) 1158 } 1159 1160 var unOps = [...]Op{ 1161 syntax.Recv: ORECV, 1162 syntax.Mul: OIND, 1163 syntax.And: OADDR, 1164 1165 syntax.Not: ONOT, 1166 syntax.Xor: OCOM, 1167 syntax.Add: OPLUS, 1168 syntax.Sub: OMINUS, 1169 } 1170 1171 func (p *noder) unOp(op syntax.Operator) Op { 1172 if uint64(op) >= uint64(len(unOps)) || unOps[op] == 0 { 1173 panic("invalid Operator") 1174 } 1175 return unOps[op] 1176 } 1177 1178 var binOps = [...]Op{ 1179 syntax.OrOr: OOROR, 1180 syntax.AndAnd: OANDAND, 1181 1182 syntax.Eql: OEQ, 1183 syntax.Neq: ONE, 1184 syntax.Lss: OLT, 1185 syntax.Leq: OLE, 1186 syntax.Gtr: OGT, 1187 syntax.Geq: OGE, 1188 1189 syntax.Add: OADD, 1190 syntax.Sub: OSUB, 1191 syntax.Or: OOR, 1192 syntax.Xor: OXOR, 1193 1194 syntax.Mul: OMUL, 1195 syntax.Div: ODIV, 1196 syntax.Rem: OMOD, 1197 syntax.And: OAND, 1198 syntax.AndNot: OANDNOT, 1199 syntax.Shl: OLSH, 1200 syntax.Shr: ORSH, 1201 } 1202 1203 func (p *noder) binOp(op syntax.Operator) Op { 1204 if uint64(op) >= uint64(len(binOps)) || binOps[op] == 0 { 1205 panic("invalid Operator") 1206 } 1207 return binOps[op] 1208 } 1209 1210 func (p *noder) basicLit(lit *syntax.BasicLit) Val { 1211 // TODO: Don't try to convert if we had syntax errors (conversions may fail). 1212 // Use dummy values so we can continue to compile. Eventually, use a 1213 // form of "unknown" literals that are ignored during type-checking so 1214 // we can continue type-checking w/o spurious follow-up errors. 1215 switch s := lit.Value; lit.Kind { 1216 case syntax.IntLit: 1217 x := new(Mpint) 1218 x.SetString(s) 1219 return Val{U: x} 1220 1221 case syntax.FloatLit: 1222 x := newMpflt() 1223 x.SetString(s) 1224 return Val{U: x} 1225 1226 case syntax.ImagLit: 1227 x := new(Mpcplx) 1228 x.Imag.SetString(strings.TrimSuffix(s, "i")) 1229 return Val{U: x} 1230 1231 case syntax.RuneLit: 1232 var r rune 1233 if u, err := strconv.Unquote(s); err == nil && len(u) > 0 { 1234 // Package syntax already reported any errors. 1235 // Check for them again though because 0 is a 1236 // better fallback value for invalid rune 1237 // literals than 0xFFFD. 1238 if len(u) == 1 { 1239 r = rune(u[0]) 1240 } else { 1241 r, _ = utf8.DecodeRuneInString(u) 1242 } 1243 } 1244 x := new(Mpint) 1245 x.SetInt64(int64(r)) 1246 x.Rune = true 1247 return Val{U: x} 1248 1249 case syntax.StringLit: 1250 if len(s) > 0 && s[0] == '`' { 1251 // strip carriage returns from raw string 1252 s = strings.Replace(s, "\r", "", -1) 1253 } 1254 // Ignore errors because package syntax already reported them. 1255 u, _ := strconv.Unquote(s) 1256 return Val{U: u} 1257 1258 default: 1259 panic("unhandled BasicLit kind") 1260 } 1261 } 1262 1263 func (p *noder) name(name *syntax.Name) *types.Sym { 1264 return lookup(name.Value) 1265 } 1266 1267 func (p *noder) mkname(name *syntax.Name) *Node { 1268 // TODO(mdempsky): Set line number? 1269 return mkname(p.name(name)) 1270 } 1271 1272 func (p *noder) newname(name *syntax.Name) *Node { 1273 // TODO(mdempsky): Set line number? 1274 return newname(p.name(name)) 1275 } 1276 1277 func (p *noder) wrapname(n syntax.Node, x *Node) *Node { 1278 // These nodes do not carry line numbers. 1279 // Introduce a wrapper node to give them the correct line. 1280 switch x.Op { 1281 case OTYPE, OLITERAL: 1282 if x.Sym == nil { 1283 break 1284 } 1285 fallthrough 1286 case ONAME, ONONAME, OPACK: 1287 x = p.nod(n, OPAREN, x, nil) 1288 x.SetImplicit(true) 1289 } 1290 return x 1291 } 1292 1293 func (p *noder) nod(orig syntax.Node, op Op, left, right *Node) *Node { 1294 return p.setlineno(orig, nod(op, left, right)) 1295 } 1296 1297 func (p *noder) setlineno(src_ syntax.Node, dst *Node) *Node { 1298 pos := src_.Pos() 1299 if !pos.IsKnown() { 1300 // TODO(mdempsky): Shouldn't happen. Fix package syntax. 1301 return dst 1302 } 1303 dst.Pos = Ctxt.PosTable.XPos(pos) 1304 return dst 1305 } 1306 1307 func (p *noder) lineno(n syntax.Node) { 1308 if n == nil { 1309 return 1310 } 1311 pos := n.Pos() 1312 if !pos.IsKnown() { 1313 // TODO(mdempsky): Shouldn't happen. Fix package syntax. 1314 return 1315 } 1316 lineno = Ctxt.PosTable.XPos(pos) 1317 } 1318 1319 // error is called concurrently if files are parsed concurrently. 1320 func (p *noder) error(err error) { 1321 p.err <- err.(syntax.Error) 1322 } 1323 1324 // pragmas that are allowed in the std lib, but don't have 1325 // a syntax.Pragma value (see lex.go) associated with them. 1326 var allowedStdPragmas = map[string]bool{ 1327 "go:cgo_export_static": true, 1328 "go:cgo_export_dynamic": true, 1329 "go:cgo_import_static": true, 1330 "go:cgo_import_dynamic": true, 1331 "go:cgo_ldflag": true, 1332 "go:cgo_dynamic_linker": true, 1333 "go:generate": true, 1334 } 1335 1336 // pragma is called concurrently if files are parsed concurrently. 1337 func (p *noder) pragma(pos src.Pos, text string) syntax.Pragma { 1338 switch { 1339 case strings.HasPrefix(text, "line "): 1340 // line directives are handled by syntax package 1341 panic("unreachable") 1342 1343 case strings.HasPrefix(text, "go:linkname "): 1344 f := strings.Fields(text) 1345 if len(f) != 3 { 1346 p.error(syntax.Error{Pos: pos, Msg: "usage: //go:linkname localname linkname"}) 1347 break 1348 } 1349 p.linknames = append(p.linknames, linkname{pos, f[1], f[2]}) 1350 1351 case strings.HasPrefix(text, "go:cgo_import_dynamic "): 1352 // This is permitted for general use because Solaris 1353 // code relies on it in golang.org/x/sys/unix and others. 1354 fields := pragmaFields(text) 1355 if len(fields) >= 4 { 1356 lib := strings.Trim(fields[3], `"`) 1357 if lib != "" && !safeArg(lib) && !isCgoGeneratedFile(pos) { 1358 p.error(syntax.Error{Pos: pos, Msg: fmt.Sprintf("invalid library name %q in cgo_import_dynamic directive", lib)}) 1359 } 1360 p.pragcgobuf += p.pragcgo(pos, text) 1361 return pragmaValue("go:cgo_import_dynamic") 1362 } 1363 fallthrough 1364 case strings.HasPrefix(text, "go:cgo_"): 1365 // For security, we disallow //go:cgo_* directives other 1366 // than cgo_import_dynamic outside cgo-generated files. 1367 // Exception: they are allowed in the standard library, for runtime and syscall. 1368 if !isCgoGeneratedFile(pos) && !compiling_std { 1369 p.error(syntax.Error{Pos: pos, Msg: fmt.Sprintf("//%s only allowed in cgo-generated code", text)}) 1370 } 1371 p.pragcgobuf += p.pragcgo(pos, text) 1372 fallthrough // because of //go:cgo_unsafe_args 1373 default: 1374 verb := text 1375 if i := strings.Index(text, " "); i >= 0 { 1376 verb = verb[:i] 1377 } 1378 prag := pragmaValue(verb) 1379 const runtimePragmas = Systemstack | Nowritebarrier | Nowritebarrierrec | Yeswritebarrierrec 1380 if !compiling_runtime && prag&runtimePragmas != 0 { 1381 p.error(syntax.Error{Pos: pos, Msg: fmt.Sprintf("//%s only allowed in runtime", verb)}) 1382 } 1383 if prag == 0 && !allowedStdPragmas[verb] && compiling_std { 1384 p.error(syntax.Error{Pos: pos, Msg: fmt.Sprintf("//%s is not allowed in the standard library", verb)}) 1385 } 1386 return prag 1387 } 1388 1389 return 0 1390 } 1391 1392 // isCgoGeneratedFile reports whether pos is in a file 1393 // generated by cgo, which is to say a file with name 1394 // beginning with "_cgo_". Such files are allowed to 1395 // contain cgo directives, and for security reasons 1396 // (primarily misuse of linker flags), other files are not. 1397 // See golang.org/issue/23672. 1398 func isCgoGeneratedFile(pos src.Pos) bool { 1399 return strings.HasPrefix(filepath.Base(filepath.Clean(pos.AbsFilename())), "_cgo_") 1400 } 1401 1402 // safeArg reports whether arg is a "safe" command-line argument, 1403 // meaning that when it appears in a command-line, it probably 1404 // doesn't have some special meaning other than its own name. 1405 // This is copied from SafeArg in cmd/go/internal/load/pkg.go. 1406 func safeArg(name string) bool { 1407 if name == "" { 1408 return false 1409 } 1410 c := name[0] 1411 return '0' <= c && c <= '9' || 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || c == '.' || c == '_' || c == '/' || c >= utf8.RuneSelf 1412 } 1413 1414 func mkname(sym *types.Sym) *Node { 1415 n := oldname(sym) 1416 if n.Name != nil && n.Name.Pack != nil { 1417 n.Name.Pack.Name.SetUsed(true) 1418 } 1419 return n 1420 } 1421 1422 func unparen(x *Node) *Node { 1423 for x.Op == OPAREN { 1424 x = x.Left 1425 } 1426 return x 1427 }