github.com/mh-cbon/go@v0.0.0-20160603070303-9e112a3fe4c0/src/cmd/compile/internal/gc/syntax.go (about) 1 // Copyright 2009 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 // “Abstract” syntax representation. 6 7 package gc 8 9 // A Node is a single node in the syntax tree. 10 // Actually the syntax tree is a syntax DAG, because there is only one 11 // node with Op=ONAME for a given instance of a variable x. 12 // The same is true for Op=OTYPE and Op=OLITERAL. 13 type Node struct { 14 // Tree structure. 15 // Generic recursive walks should follow these fields. 16 Left *Node 17 Right *Node 18 Ninit Nodes 19 Nbody Nodes 20 List Nodes 21 Rlist Nodes 22 23 // most nodes 24 Type *Type 25 Orig *Node // original form, for printing, and tracking copies of ONAMEs 26 27 // func 28 Func *Func 29 30 // ONAME 31 Name *Name 32 33 Sym *Sym // various 34 E interface{} // Opt or Val, see methods below 35 36 // Various. Usually an offset into a struct. For example, ONAME nodes 37 // that refer to local variables use it to identify their stack frame 38 // position. ODOT, ODOTPTR, and OINDREG use it to indicate offset 39 // relative to their base address. ONAME nodes on the left side of an 40 // OKEY within an OSTRUCTLIT use it to store the named field's offset. 41 // OXCASE and OXFALL use it to validate the use of fallthrough. 42 // Possibly still more uses. If you find any, document them. 43 Xoffset int64 44 45 Lineno int32 46 47 // OREGISTER, OINDREG 48 Reg int16 49 50 Esc uint16 // EscXXX 51 52 Op Op 53 Ullman uint8 // sethi/ullman number 54 Addable bool // addressable 55 Etype EType // op for OASOP, etype for OTYPE, exclam for export, 6g saved reg, ChanDir for OTCHAN 56 Bounded bool // bounds check unnecessary 57 NonNil bool // guaranteed to be non-nil 58 Class Class // PPARAM, PAUTO, PEXTERN, etc 59 Embedded uint8 // ODCLFIELD embedded type 60 Colas bool // OAS resulting from := 61 Diag uint8 // already printed error about this 62 Noescape bool // func arguments do not escape; TODO(rsc): move Noescape to Func struct (see CL 7360) 63 Walkdef uint8 64 Typecheck uint8 65 Local bool 66 Dodata uint8 67 Initorder uint8 68 Used bool 69 Isddd bool // is the argument variadic 70 Implicit bool 71 Addrtaken bool // address taken, even if not moved to heap 72 Assigned bool // is the variable ever assigned to 73 Likely int8 // likeliness of if statement 74 hasVal int8 // +1 for Val, -1 for Opt, 0 for not yet set 75 flags uint8 // TODO: store more bool fields in this flag field 76 } 77 78 const ( 79 hasBreak = 1 << iota 80 notLiveAtEnd 81 isClosureVar 82 ) 83 84 func (n *Node) HasBreak() bool { 85 return n.flags&hasBreak != 0 86 } 87 func (n *Node) SetHasBreak(b bool) { 88 if b { 89 n.flags |= hasBreak 90 } else { 91 n.flags &^= hasBreak 92 } 93 } 94 func (n *Node) NotLiveAtEnd() bool { 95 return n.flags¬LiveAtEnd != 0 96 } 97 func (n *Node) SetNotLiveAtEnd(b bool) { 98 if b { 99 n.flags |= notLiveAtEnd 100 } else { 101 n.flags &^= notLiveAtEnd 102 } 103 } 104 func (n *Node) isClosureVar() bool { 105 return n.flags&isClosureVar != 0 106 } 107 func (n *Node) setIsClosureVar(b bool) { 108 if b { 109 n.flags |= isClosureVar 110 } else { 111 n.flags &^= isClosureVar 112 } 113 } 114 115 // Val returns the Val for the node. 116 func (n *Node) Val() Val { 117 if n.hasVal != +1 { 118 return Val{} 119 } 120 return Val{n.E} 121 } 122 123 // SetVal sets the Val for the node, which must not have been used with SetOpt. 124 func (n *Node) SetVal(v Val) { 125 if n.hasVal == -1 { 126 Debug['h'] = 1 127 Dump("have Opt", n) 128 Fatalf("have Opt") 129 } 130 n.hasVal = +1 131 n.E = v.U 132 } 133 134 // Opt returns the optimizer data for the node. 135 func (n *Node) Opt() interface{} { 136 if n.hasVal != -1 { 137 return nil 138 } 139 return n.E 140 } 141 142 // SetOpt sets the optimizer data for the node, which must not have been used with SetVal. 143 // SetOpt(nil) is ignored for Vals to simplify call sites that are clearing Opts. 144 func (n *Node) SetOpt(x interface{}) { 145 if x == nil && n.hasVal >= 0 { 146 return 147 } 148 if n.hasVal == +1 { 149 Debug['h'] = 1 150 Dump("have Val", n) 151 Fatalf("have Val") 152 } 153 n.hasVal = -1 154 n.E = x 155 } 156 157 // Name holds Node fields used only by named nodes (ONAME, OPACK, OLABEL, ODCLFIELD, some OLITERAL). 158 type Name struct { 159 Pack *Node // real package for import . names 160 Pkg *Pkg // pkg for OPACK nodes 161 Heapaddr *Node // temp holding heap address of param (could move to Param?) 162 Inlvar *Node // ONAME substitute while inlining (could move to Param?) 163 Defn *Node // initializing assignment 164 Curfn *Node // function for local variables 165 Param *Param // additional fields for ONAME, ODCLFIELD 166 Decldepth int32 // declaration loop depth, increased for every loop or label 167 Vargen int32 // unique name for ONAME within a function. Function outputs are numbered starting at one. 168 Iota int32 // value if this name is iota 169 Funcdepth int32 170 Method bool // OCALLMETH name 171 Readonly bool 172 Captured bool // is the variable captured by a closure 173 Byval bool // is the variable captured by value or by reference 174 Needzero bool // if it contains pointers, needs to be zeroed on function entry 175 Keepalive bool // mark value live across unknown assembly call 176 } 177 178 type Param struct { 179 Ntype *Node 180 181 // ONAME PAUTOHEAP 182 Stackcopy *Node // the PPARAM/PPARAMOUT on-stack slot (moved func params only) 183 184 // ONAME PPARAM 185 Field *Field // TFIELD in arg struct 186 187 // ONAME closure linkage 188 // Consider: 189 // 190 // func f() { 191 // x := 1 // x1 192 // func() { 193 // use(x) // x2 194 // func() { 195 // use(x) // x3 196 // --- parser is here --- 197 // }() 198 // }() 199 // } 200 // 201 // There is an original declaration of x and then a chain of mentions of x 202 // leading into the current function. Each time x is mentioned in a new closure, 203 // we create a variable representing x for use in that specific closure, 204 // since the way you get to x is different in each closure. 205 // 206 // Let's number the specific variables as shown in the code: 207 // x1 is the original x, x2 is when mentioned in the closure, 208 // and x3 is when mentioned in the closure in the closure. 209 // 210 // We keep these linked (assume N > 1): 211 // 212 // - x1.Defn = original declaration statement for x (like most variables) 213 // - x1.Innermost = current innermost closure x (in this case x3), or nil for none 214 // - x1.isClosureVar() = false 215 // 216 // - xN.Defn = x1, N > 1 217 // - xN.isClosureVar() = true, N > 1 218 // - x2.Outer = nil 219 // - xN.Outer = x(N-1), N > 2 220 // 221 // 222 // When we look up x in the symbol table, we always get x1. 223 // Then we can use x1.Innermost (if not nil) to get the x 224 // for the innermost known closure function, 225 // but the first reference in a closure will find either no x1.Innermost 226 // or an x1.Innermost with .Funcdepth < Funcdepth. 227 // In that case, a new xN must be created, linked in with: 228 // 229 // xN.Defn = x1 230 // xN.Outer = x1.Innermost 231 // x1.Innermost = xN 232 // 233 // When we finish the function, we'll process its closure variables 234 // and find xN and pop it off the list using: 235 // 236 // x1 := xN.Defn 237 // x1.Innermost = xN.Outer 238 // 239 // We leave xN.Innermost set so that we can still get to the original 240 // variable quickly. Not shown here, but once we're 241 // done parsing a function and no longer need xN.Outer for the 242 // lexical x reference links as described above, closurebody 243 // recomputes xN.Outer as the semantic x reference link tree, 244 // even filling in x in intermediate closures that might not 245 // have mentioned it along the way to inner closures that did. 246 // See closurebody for details. 247 // 248 // During the eventual compilation, then, for closure variables we have: 249 // 250 // xN.Defn = original variable 251 // xN.Outer = variable captured in next outward scope 252 // to make closure where xN appears 253 // 254 // Because of the sharding of pieces of the node, x.Defn means x.Name.Defn 255 // and x.Innermost/Outer means x.Name.Param.Innermost/Outer. 256 Innermost *Node 257 Outer *Node 258 } 259 260 // Func holds Node fields used only with function-like nodes. 261 type Func struct { 262 Shortname *Node 263 Enter Nodes // for example, allocate and initialize memory for escaping parameters 264 Exit Nodes 265 Cvars Nodes // closure params 266 Dcl []*Node // autodcl for this func/closure 267 Inldcl Nodes // copy of dcl for use in inlining 268 Closgen int 269 Outerfunc *Node // outer function (for closure) 270 FieldTrack map[*Sym]struct{} 271 Ntype *Node // signature 272 Top int // top context (Ecall, Eproc, etc) 273 Closure *Node // OCLOSURE <-> ODCLFUNC 274 FCurfn *Node 275 Nname *Node 276 277 Inl Nodes // copy of the body for use in inlining 278 InlCost int32 279 Depth int32 280 281 Endlineno int32 282 WBLineno int32 // line number of first write barrier 283 284 Pragma Pragma // go:xxx function annotations 285 Dupok bool // duplicate definitions ok 286 Wrapper bool // is method wrapper 287 Needctxt bool // function uses context register (has closure variables) 288 ReflectMethod bool // function calls reflect.Type.Method or MethodByName 289 } 290 291 type Op uint8 292 293 // Node ops. 294 const ( 295 OXXX = Op(iota) 296 297 // names 298 ONAME // var, const or func name 299 ONONAME // unnamed arg or return value: f(int, string) (int, error) { etc } 300 OTYPE // type name 301 OPACK // import 302 OLITERAL // literal 303 304 // expressions 305 OADD // Left + Right 306 OSUB // Left - Right 307 OOR // Left | Right 308 OXOR // Left ^ Right 309 OADDSTR // +{List} (string addition, list elements are strings) 310 OADDR // &Left 311 OANDAND // Left && Right 312 OAPPEND // append(List) 313 OARRAYBYTESTR // Type(Left) (Type is string, Left is a []byte) 314 OARRAYBYTESTRTMP // Type(Left) (Type is string, Left is a []byte, ephemeral) 315 OARRAYRUNESTR // Type(Left) (Type is string, Left is a []rune) 316 OSTRARRAYBYTE // Type(Left) (Type is []byte, Left is a string) 317 OSTRARRAYBYTETMP // Type(Left) (Type is []byte, Left is a string, ephemeral) 318 OSTRARRAYRUNE // Type(Left) (Type is []rune, Left is a string) 319 OAS // Left = Right or (if Colas=true) Left := Right 320 OAS2 // List = Rlist (x, y, z = a, b, c) 321 OAS2FUNC // List = Rlist (x, y = f()) 322 OAS2RECV // List = Rlist (x, ok = <-c) 323 OAS2MAPR // List = Rlist (x, ok = m["foo"]) 324 OAS2DOTTYPE // List = Rlist (x, ok = I.(int)) 325 OASOP // Left Etype= Right (x += y) 326 OASWB // Left = Right (with write barrier) 327 OCALL // Left(List) (function call, method call or type conversion) 328 OCALLFUNC // Left(List) (function call f(args)) 329 OCALLMETH // Left(List) (direct method call x.Method(args)) 330 OCALLINTER // Left(List) (interface method call x.Method(args)) 331 OCALLPART // Left.Right (method expression x.Method, not called) 332 OCAP // cap(Left) 333 OCLOSE // close(Left) 334 OCLOSURE // func Type { Body } (func literal) 335 OCMPIFACE // Left Etype Right (interface comparison, x == y or x != y) 336 OCMPSTR // Left Etype Right (string comparison, x == y, x < y, etc) 337 OCOMPLIT // Right{List} (composite literal, not yet lowered to specific form) 338 OMAPLIT // Type{List} (composite literal, Type is map) 339 OSTRUCTLIT // Type{List} (composite literal, Type is struct) 340 OARRAYLIT // Type{List} (composite literal, Type is array or slice) 341 OPTRLIT // &Left (left is composite literal) 342 OCONV // Type(Left) (type conversion) 343 OCONVIFACE // Type(Left) (type conversion, to interface) 344 OCONVNOP // Type(Left) (type conversion, no effect) 345 OCOPY // copy(Left, Right) 346 ODCL // var Left (declares Left of type Left.Type) 347 348 // Used during parsing but don't last. 349 ODCLFUNC // func f() or func (r) f() 350 ODCLFIELD // struct field, interface field, or func/method argument/return value. 351 ODCLCONST // const pi = 3.14 352 ODCLTYPE // type Int int 353 354 ODELETE // delete(Left, Right) 355 ODOT // Left.Sym (Left is of struct type) 356 ODOTPTR // Left.Sym (Left is of pointer to struct type) 357 ODOTMETH // Left.Sym (Left is non-interface, Right is method name) 358 ODOTINTER // Left.Sym (Left is interface, Right is method name) 359 OXDOT // Left.Sym (before rewrite to one of the preceding) 360 ODOTTYPE // Left.Right or Left.Type (.Right during parsing, .Type once resolved) 361 ODOTTYPE2 // Left.Right or Left.Type (.Right during parsing, .Type once resolved; on rhs of OAS2DOTTYPE) 362 OEQ // Left == Right 363 ONE // Left != Right 364 OLT // Left < Right 365 OLE // Left <= Right 366 OGE // Left >= Right 367 OGT // Left > Right 368 OIND // *Left 369 OINDEX // Left[Right] (index of array or slice) 370 OINDEXMAP // Left[Right] (index of map) 371 OKEY // Left:Right (key:value in struct/array/map literal, or slice index pair) 372 _ // was OPARAM, but cannot remove without breaking binary blob in builtin.go 373 OLEN // len(Left) 374 OMAKE // make(List) (before type checking converts to one of the following) 375 OMAKECHAN // make(Type, Left) (type is chan) 376 OMAKEMAP // make(Type, Left) (type is map) 377 OMAKESLICE // make(Type, Left, Right) (type is slice) 378 OMUL // Left * Right 379 ODIV // Left / Right 380 OMOD // Left % Right 381 OLSH // Left << Right 382 ORSH // Left >> Right 383 OAND // Left & Right 384 OANDNOT // Left &^ Right 385 ONEW // new(Left) 386 ONOT // !Left 387 OCOM // ^Left 388 OPLUS // +Left 389 OMINUS // -Left 390 OOROR // Left || Right 391 OPANIC // panic(Left) 392 OPRINT // print(List) 393 OPRINTN // println(List) 394 OPAREN // (Left) 395 OSEND // Left <- Right 396 OSLICE // Left[Right.Left : Right.Right] (Left is untypechecked or slice; Right.Op==OKEY) 397 OSLICEARR // Left[Right.Left : Right.Right] (Left is array) 398 OSLICESTR // Left[Right.Left : Right.Right] (Left is string) 399 OSLICE3 // Left[R.Left : R.R.Left : R.R.R] (R=Right; Left is untypedchecked or slice; R.Op and R.R.Op==OKEY) 400 OSLICE3ARR // Left[R.Left : R.R.Left : R.R.R] (R=Right; Left is array; R.Op and R.R.Op==OKEY) 401 ORECOVER // recover() 402 ORECV // <-Left 403 ORUNESTR // Type(Left) (Type is string, Left is rune) 404 OSELRECV // Left = <-Right.Left: (appears as .Left of OCASE; Right.Op == ORECV) 405 OSELRECV2 // List = <-Right.Left: (apperas as .Left of OCASE; count(List) == 2, Right.Op == ORECV) 406 OIOTA // iota 407 OREAL // real(Left) 408 OIMAG // imag(Left) 409 OCOMPLEX // complex(Left, Right) 410 411 // statements 412 OBLOCK // { List } (block of code) 413 OBREAK // break 414 OCASE // case List: Nbody (select case after processing; List==nil means default) 415 OXCASE // case List: Nbody (select case before processing; List==nil means default) 416 OCONTINUE // continue 417 ODEFER // defer Left (Left must be call) 418 OEMPTY // no-op (empty statement) 419 OFALL // fallthrough (after processing) 420 OXFALL // fallthrough (before processing) 421 OFOR // for Ninit; Left; Right { Nbody } 422 OGOTO // goto Left 423 OIF // if Ninit; Left { Nbody } else { Rlist } 424 OLABEL // Left: 425 OPROC // go Left (Left must be call) 426 ORANGE // for List = range Right { Nbody } 427 ORETURN // return List 428 OSELECT // select { List } (List is list of OXCASE or OCASE) 429 OSWITCH // switch Ninit; Left { List } (List is a list of OXCASE or OCASE) 430 OTYPESW // List = Left.(type) (appears as .Left of OSWITCH) 431 432 // types 433 OTCHAN // chan int 434 OTMAP // map[string]int 435 OTSTRUCT // struct{} 436 OTINTER // interface{} 437 OTFUNC // func() 438 OTARRAY // []int, [8]int, [N]int or [...]int 439 440 // misc 441 ODDD // func f(args ...int) or f(l...) or var a = [...]int{0, 1, 2}. 442 ODDDARG // func f(args ...int), introduced by escape analysis. 443 OINLCALL // intermediary representation of an inlined call. 444 OEFACE // itable and data words of an empty-interface value. 445 OITAB // itable word of an interface value. 446 OSPTR // base pointer of a slice or string. 447 OCLOSUREVAR // variable reference at beginning of closure function 448 OCFUNC // reference to c function pointer (not go func value) 449 OCHECKNIL // emit code to ensure pointer/interface not nil 450 OVARKILL // variable is dead 451 OVARLIVE // variable is alive 452 453 // thearch-specific registers 454 OREGISTER // a register, such as AX. 455 OINDREG // offset plus indirect of a register, such as 8(SP). 456 457 // arch-specific opcodes 458 OCMP // compare: ACMP. 459 ODEC // decrement: ADEC. 460 OINC // increment: AINC. 461 OEXTEND // extend: ACWD/ACDQ/ACQO. 462 OHMUL // high mul: AMUL/AIMUL for unsigned/signed (OMUL uses AIMUL for both). 463 OLROT // left rotate: AROL. 464 ORROTC // right rotate-carry: ARCR. 465 ORETJMP // return to other function 466 OPS // compare parity set (for x86 NaN check) 467 OPC // compare parity clear (for x86 NaN check) 468 OSQRT // sqrt(float64), on systems that have hw support 469 OGETG // runtime.getg() (read g pointer) 470 471 OEND 472 ) 473 474 // Nodes is a pointer to a slice of *Node. 475 // For fields that are not used in most nodes, this is used instead of 476 // a slice to save space. 477 type Nodes struct{ slice *[]*Node } 478 479 // Slice returns the entries in Nodes as a slice. 480 // Changes to the slice entries (as in s[i] = n) will be reflected in 481 // the Nodes. 482 func (n Nodes) Slice() []*Node { 483 if n.slice == nil { 484 return nil 485 } 486 return *n.slice 487 } 488 489 // Len returns the number of entries in Nodes. 490 func (n Nodes) Len() int { 491 if n.slice == nil { 492 return 0 493 } 494 return len(*n.slice) 495 } 496 497 // Index returns the i'th element of Nodes. 498 // It panics if n does not have at least i+1 elements. 499 func (n Nodes) Index(i int) *Node { 500 return (*n.slice)[i] 501 } 502 503 // First returns the first element of Nodes (same as n.Index(0)). 504 // It panics if n has no elements. 505 func (n Nodes) First() *Node { 506 return (*n.slice)[0] 507 } 508 509 // Second returns the second element of Nodes (same as n.Index(1)). 510 // It panics if n has fewer than two elements. 511 func (n Nodes) Second() *Node { 512 return (*n.slice)[1] 513 } 514 515 // Set sets n to a slice. 516 // This takes ownership of the slice. 517 func (n *Nodes) Set(s []*Node) { 518 if len(s) == 0 { 519 n.slice = nil 520 } else { 521 // Copy s and take address of t rather than s to avoid 522 // allocation in the case where len(s) == 0 (which is 523 // over 3x more common, dynamically, for make.bash). 524 t := s 525 n.slice = &t 526 } 527 } 528 529 // Set1 sets n to a slice containing a single node. 530 func (n *Nodes) Set1(node *Node) { 531 n.slice = &[]*Node{node} 532 } 533 534 // MoveNodes sets n to the contents of n2, then clears n2. 535 func (n *Nodes) MoveNodes(n2 *Nodes) { 536 n.slice = n2.slice 537 n2.slice = nil 538 } 539 540 // SetIndex sets the i'th element of Nodes to node. 541 // It panics if n does not have at least i+1 elements. 542 func (n Nodes) SetIndex(i int, node *Node) { 543 (*n.slice)[i] = node 544 } 545 546 // Addr returns the address of the i'th element of Nodes. 547 // It panics if n does not have at least i+1 elements. 548 func (n Nodes) Addr(i int) **Node { 549 return &(*n.slice)[i] 550 } 551 552 // Append appends entries to Nodes. 553 // If a slice is passed in, this will take ownership of it. 554 func (n *Nodes) Append(a ...*Node) { 555 if n.slice == nil { 556 if len(a) > 0 { 557 n.slice = &a 558 } 559 } else { 560 *n.slice = append(*n.slice, a...) 561 } 562 } 563 564 // AppendNodes appends the contents of *n2 to n, then clears n2. 565 func (n *Nodes) AppendNodes(n2 *Nodes) { 566 switch { 567 case n2.slice == nil: 568 case n.slice == nil: 569 n.slice = n2.slice 570 default: 571 *n.slice = append(*n.slice, *n2.slice...) 572 } 573 n2.slice = nil 574 }