github.com/zebozhuang/go@v0.0.0-20200207033046-f8a98f6f5c5d/src/go/ast/ast.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 // Package ast declares the types used to represent syntax trees for Go 6 // packages. 7 // 8 package ast 9 10 import ( 11 "go/token" 12 "strings" 13 "unicode" 14 "unicode/utf8" 15 ) 16 // Go语法树: Expressions, type, statement, declaration nodes 17 // ---------------------------------------------------------------------------- 18 // Interfaces 19 // 20 // There are 3 main classes of nodes: Expressions and type nodes, 21 // statement nodes, and declaration nodes. The node names usually 22 // match the corresponding Go spec production names to which they 23 // correspond. The node fields correspond to the individual parts 24 // of the respective productions. 25 // 26 // All nodes contain position information marking the beginning of 27 // the corresponding source text segment; it is accessible via the 28 // Pos accessor method. Nodes may contain additional position info 29 // for language constructs where comments may be found between parts 30 // of the construct (typically any larger, parenthesized subpart). 31 // That position information is needed to properly position comments 32 // when printing the construct. 33 34 // 所有节点的接口 35 // All node types implement the Node interface. 36 type Node interface { 37 Pos() token.Pos // position of first character belonging to the node 节点开始的位置 38 End() token.Pos // position of first character immediately after the node 节点结束的位置 39 } 40 41 // 表达式接口 42 // All expression nodes implement the Expr interface. 43 type Expr interface { 44 Node 45 exprNode() 46 } 47 48 // 语句接口 49 // All statement nodes implement the Stmt interface. 50 type Stmt interface { 51 Node 52 stmtNode() 53 } 54 55 // 声明接口 56 // All declaration nodes implement the Decl interface. 57 type Decl interface { 58 Node 59 declNode() 60 } 61 62 // ---------------------------------------------------------------------------- 63 // Comments 64 // 注释结构对象 65 // A Comment node represents a single //-style or /*-style comment. 66 type Comment struct { 67 Slash token.Pos // position of "/" starting the comment 斜线开始位置 68 Text string // comment text (excluding '\n' for //-style comments) // 文本 69 } 70 71 func (c *Comment) Pos() token.Pos { return c.Slash } // 开始位置 72 func (c *Comment) End() token.Pos { return token.Pos(int(c.Slash) + len(c.Text)) } // 结束位置 73 74 // A CommentGroup represents a sequence of comments 75 // with no other tokens and no empty lines between. 76 // 注释组,没有空行或其他token在里面 77 type CommentGroup struct { 78 List []*Comment // len(List) > 0 79 } 80 81 func (g *CommentGroup) Pos() token.Pos { return g.List[0].Pos() } // 开始位置 82 func (g *CommentGroup) End() token.Pos { return g.List[len(g.List)-1].End() } // 结束位置 83 84 func isWhitespace(ch byte) bool { return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r' } // 判断空格 85 86 // 去掉末尾空白 87 func stripTrailingWhitespace(s string) string { 88 i := len(s) 89 for i > 0 && isWhitespace(s[i-1]) { 90 i-- 91 } 92 return s[0:i] 93 } 94 95 // Text returns the text of the comment. 96 // Comment markers (//, /*, and */), the first space of a line comment, and 97 // leading and trailing empty lines are removed. Multiple empty lines are 98 // reduced to one, and trailing space on lines is trimmed. Unless the result 99 // is empty, it is newline-terminated. 100 // 101 func (g *CommentGroup) Text() string { // 返回注释文本 102 if g == nil { 103 return "" 104 } 105 comments := make([]string, len(g.List)) 106 for i, c := range g.List { 107 comments[i] = c.Text 108 } 109 110 lines := make([]string, 0, 10) // most comments are less than 10 lines 111 for _, c := range comments { 112 // Remove comment markers. 113 // The parser has given us exactly the comment text. 114 switch c[1] { 115 case '/': 116 //-style comment (no newline at the end) 117 c = c[2:] 118 // strip first space - required for Example tests 119 if len(c) > 0 && c[0] == ' ' { 120 c = c[1:] 121 } 122 case '*': 123 /*-style comment */ 124 c = c[2 : len(c)-2] 125 } 126 127 // Split on newlines. 128 cl := strings.Split(c, "\n") 129 130 // Walk lines, stripping trailing white space and adding to list. 131 for _, l := range cl { 132 lines = append(lines, stripTrailingWhitespace(l)) 133 } 134 } 135 136 // Remove leading blank lines; convert runs of 137 // interior blank lines to a single blank line. 138 n := 0 139 for _, line := range lines { 140 if line != "" || n > 0 && lines[n-1] != "" { 141 lines[n] = line 142 n++ 143 } 144 } 145 lines = lines[0:n] 146 147 // Add final "" entry to get trailing newline from Join. 148 if n > 0 && lines[n-1] != "" { 149 lines = append(lines, "") 150 } 151 152 return strings.Join(lines, "\n") 153 } 154 155 // ---------------------------------------------------------------------------- 156 // Expressions and types 157 158 // A Field represents a Field declaration list in a struct type, 159 // a method list in an interface type, or a parameter/result declaration 160 // in a signature. 161 // 162 // struct 结构体内的字段 163 type Field struct { 164 Doc *CommentGroup // associated documentation; or nil 文档关联 165 Names []*Ident // field/method/parameter names; or nil if anonymous field 166 Type Expr // field/method/parameter type 167 Tag *BasicLit // field tag; or nil 168 Comment *CommentGroup // line comments; or nil // 行注释 169 } 170 171 func (f *Field) Pos() token.Pos { 172 if len(f.Names) > 0 { 173 return f.Names[0].Pos() 174 } 175 return f.Type.Pos() 176 } 177 178 func (f *Field) End() token.Pos { 179 if f.Tag != nil { 180 return f.Tag.End() 181 } 182 return f.Type.End() 183 } 184 185 // A FieldList represents a list of Fields, enclosed by parentheses or braces. 186 type FieldList struct { 187 Opening token.Pos // position of opening parenthesis/brace, if any 左括号 188 List []*Field // field list; or nil 189 Closing token.Pos // position of closing parenthesis/brace, if any 右括号 190 } 191 192 func (f *FieldList) Pos() token.Pos { // 开始位置 193 if f.Opening.IsValid() { 194 return f.Opening 195 } 196 // the list should not be empty in this case; 197 // be conservative and guard against bad ASTs 198 if len(f.List) > 0 { 199 return f.List[0].Pos() 200 } 201 return token.NoPos 202 } 203 204 func (f *FieldList) End() token.Pos { // 结束位置 205 if f.Closing.IsValid() { 206 return f.Closing + 1 207 } 208 // the list should not be empty in this case; 209 // be conservative and guard against bad ASTs 210 if n := len(f.List); n > 0 { 211 return f.List[n-1].End() 212 } 213 return token.NoPos 214 } 215 216 // NumFields returns the number of (named and anonymous fields) in a FieldList. 217 func (f *FieldList) NumFields() int { // 字段数量 218 n := 0 219 if f != nil { 220 for _, g := range f.List { 221 m := len(g.Names) 222 if m == 0 { 223 m = 1 // anonymous field 224 } 225 n += m 226 } 227 } 228 return n 229 } 230 231 // An expression is represented by a tree consisting of one 232 // or more of the following concrete expression nodes. 233 // 234 type ( 235 // A BadExpr node is a placeholder for expressions containing 236 // syntax errors for which no correct expression nodes can be 237 // created. 238 // 239 BadExpr struct { 240 From, To token.Pos // position range of bad expression 241 } 242 243 // An Ident node represents an identifier. 244 // 标志 245 Ident struct { 246 NamePos token.Pos // identifier position 位置 247 Name string // identifier name 名称 248 Obj *Object // denoted object; or nil 对象 249 } 250 251 // An Ellipsis node stands for the "..." type in a 252 // parameter list or the "..." length in an array type. 253 // 数组展开 254 Ellipsis struct { 255 Ellipsis token.Pos // position of "..." 256 Elt Expr // ellipsis element type (parameter lists only); or nil 257 } 258 259 // A BasicLit node represents a literal of basic type. 260 // 基本数据类型 261 BasicLit struct { 262 ValuePos token.Pos // literal position 263 Kind token.Token // token.INT, token.FLOAT, token.IMAG, token.CHAR, or token.STRING 264 Value string // literal string; e.g. 42, 0x7f, 3.14, 1e-9, 2.4i, 'a', '\x7f', "foo" or `\m\n\o` 265 } 266 267 // A FuncLit node represents a function literal. 268 // 函数 269 FuncLit struct { 270 Type *FuncType // function type 271 Body *BlockStmt // function body 272 } 273 274 // A CompositeLit node represents a composite literal. 275 // 花括号 276 CompositeLit struct { 277 Type Expr // literal type; or nil 278 Lbrace token.Pos // position of "{" 279 Elts []Expr // list of composite elements; or nil 280 Rbrace token.Pos // position of "}" 281 } 282 283 // A ParenExpr node represents a parenthesized expression. 284 // 括号 285 ParenExpr struct { 286 Lparen token.Pos // position of "(" 287 X Expr // parenthesized expression 288 Rparen token.Pos // position of ")" 289 } 290 291 // A SelectorExpr node represents an expression followed by a selector. 292 // select 表达式 293 SelectorExpr struct { 294 X Expr // expression 295 Sel *Ident // field selector 296 } 297 298 // An IndexExpr node represents an expression followed by an index. 299 // 下标 300 IndexExpr struct { 301 X Expr // expression 302 Lbrack token.Pos // position of "[" 303 Index Expr // index expression 304 Rbrack token.Pos // position of "]" 305 } 306 307 // An SliceExpr node represents an expression followed by slice indices. 308 // 切片 309 SliceExpr struct { 310 X Expr // expression 311 Lbrack token.Pos // position of "[" 312 Low Expr // begin of slice range; or nil 313 High Expr // end of slice range; or nil 314 Max Expr // maximum capacity of slice; or nil 315 Slice3 bool // true if 3-index slice (2 colons present) 316 Rbrack token.Pos // position of "]" 317 } 318 319 // A TypeAssertExpr node represents an expression followed by a 320 // type assertion. 321 // 类型断言 322 TypeAssertExpr struct { 323 X Expr // expression 324 Lparen token.Pos // position of "(" 325 Type Expr // asserted type; nil means type switch X.(type) 326 Rparen token.Pos // position of ")" 327 } 328 329 // A CallExpr node represents an expression followed by an argument list. 330 // 调用 331 CallExpr struct { 332 Fun Expr // function expression 333 Lparen token.Pos // position of "(" 334 Args []Expr // function arguments; or nil 335 Ellipsis token.Pos // position of "..." (token.NoPos if there is no "...") 336 Rparen token.Pos // position of ")" 337 } 338 339 // A StarExpr node represents an expression of the form "*" Expression. 340 // Semantically it could be a unary "*" expression, or a pointer type. 341 // 星号表达式 342 StarExpr struct { 343 Star token.Pos // position of "*" 344 X Expr // operand 345 } 346 347 // A UnaryExpr node represents a unary expression. 348 // Unary "*" expressions are represented via StarExpr nodes. 349 // 如 i++ 350 UnaryExpr struct { 351 OpPos token.Pos // position of Op 352 Op token.Token // operator 353 X Expr // operand 354 } 355 356 // A BinaryExpr node represents a binary expression. 357 BinaryExpr struct { 358 X Expr // left operand 359 OpPos token.Pos // position of Op 360 Op token.Token // operator 361 Y Expr // right operand 362 } 363 364 // A KeyValueExpr node represents (key : value) pairs 365 // in composite literals. 366 // 键值对 367 KeyValueExpr struct { 368 Key Expr 369 Colon token.Pos // position of ":" 370 Value Expr 371 } 372 ) 373 374 // The direction of a channel type is indicated by one 375 // of the following constants. 376 // 377 type ChanDir int 378 379 const ( 380 SEND ChanDir = 1 << iota 381 RECV 382 ) 383 384 // A type is represented by a tree consisting of one 385 // or more of the following type-specific expression 386 // nodes. 387 // 388 type ( 389 // An ArrayType node represents an array or slice type. 390 // 数组类型 391 ArrayType struct { 392 Lbrack token.Pos // position of "[" 393 Len Expr // Ellipsis node for [...]T array types, nil for slice types 394 Elt Expr // element type 395 } 396 397 // A StructType node represents a struct type. 398 // 结构类型 399 StructType struct { 400 Struct token.Pos // position of "struct" keyword 401 Fields *FieldList // list of field declarations 402 Incomplete bool // true if (source) fields are missing in the Fields list 403 } 404 405 // Pointer types are represented via StarExpr nodes. 406 407 // A FuncType node represents a function type. 408 // 函数类型 409 FuncType struct { 410 Func token.Pos // position of "func" keyword (token.NoPos if there is no "func") 411 Params *FieldList // (incoming) parameters; non-nil 412 Results *FieldList // (outgoing) results; or nil 413 } 414 415 // An InterfaceType node represents an interface type. 416 // 接口类型 417 InterfaceType struct { 418 Interface token.Pos // position of "interface" keyword 419 Methods *FieldList // list of methods 420 Incomplete bool // true if (source) methods are missing in the Methods list 421 } 422 423 // A MapType node represents a map type. 424 // map类型 425 MapType struct { 426 Map token.Pos // position of "map" keyword 427 Key Expr 428 Value Expr 429 } 430 431 // A ChanType node represents a channel type. 432 // channel类型 433 ChanType struct { 434 Begin token.Pos // position of "chan" keyword or "<-" (whichever comes first) 435 Arrow token.Pos // position of "<-" (token.NoPos if there is no "<-") 436 Dir ChanDir // channel direction 437 Value Expr // value type 438 } 439 ) 440 441 // Pos and End implementations for expression/type nodes. 442 443 func (x *BadExpr) Pos() token.Pos { return x.From } 444 func (x *Ident) Pos() token.Pos { return x.NamePos } 445 func (x *Ellipsis) Pos() token.Pos { return x.Ellipsis } 446 func (x *BasicLit) Pos() token.Pos { return x.ValuePos } 447 func (x *FuncLit) Pos() token.Pos { return x.Type.Pos() } 448 func (x *CompositeLit) Pos() token.Pos { 449 if x.Type != nil { 450 return x.Type.Pos() 451 } 452 return x.Lbrace 453 } 454 func (x *ParenExpr) Pos() token.Pos { return x.Lparen } 455 func (x *SelectorExpr) Pos() token.Pos { return x.X.Pos() } 456 func (x *IndexExpr) Pos() token.Pos { return x.X.Pos() } 457 func (x *SliceExpr) Pos() token.Pos { return x.X.Pos() } 458 func (x *TypeAssertExpr) Pos() token.Pos { return x.X.Pos() } 459 func (x *CallExpr) Pos() token.Pos { return x.Fun.Pos() } 460 func (x *StarExpr) Pos() token.Pos { return x.Star } 461 func (x *UnaryExpr) Pos() token.Pos { return x.OpPos } 462 func (x *BinaryExpr) Pos() token.Pos { return x.X.Pos() } 463 func (x *KeyValueExpr) Pos() token.Pos { return x.Key.Pos() } 464 func (x *ArrayType) Pos() token.Pos { return x.Lbrack } 465 func (x *StructType) Pos() token.Pos { return x.Struct } 466 func (x *FuncType) Pos() token.Pos { 467 if x.Func.IsValid() || x.Params == nil { // see issue 3870 468 return x.Func 469 } 470 return x.Params.Pos() // interface method declarations have no "func" keyword 471 } 472 func (x *InterfaceType) Pos() token.Pos { return x.Interface } 473 func (x *MapType) Pos() token.Pos { return x.Map } 474 func (x *ChanType) Pos() token.Pos { return x.Begin } 475 476 func (x *BadExpr) End() token.Pos { return x.To } 477 func (x *Ident) End() token.Pos { return token.Pos(int(x.NamePos) + len(x.Name)) } 478 func (x *Ellipsis) End() token.Pos { 479 if x.Elt != nil { 480 return x.Elt.End() 481 } 482 return x.Ellipsis + 3 // len("...") 483 } 484 func (x *BasicLit) End() token.Pos { return token.Pos(int(x.ValuePos) + len(x.Value)) } 485 func (x *FuncLit) End() token.Pos { return x.Body.End() } 486 func (x *CompositeLit) End() token.Pos { return x.Rbrace + 1 } 487 func (x *ParenExpr) End() token.Pos { return x.Rparen + 1 } 488 func (x *SelectorExpr) End() token.Pos { return x.Sel.End() } 489 func (x *IndexExpr) End() token.Pos { return x.Rbrack + 1 } 490 func (x *SliceExpr) End() token.Pos { return x.Rbrack + 1 } 491 func (x *TypeAssertExpr) End() token.Pos { return x.Rparen + 1 } 492 func (x *CallExpr) End() token.Pos { return x.Rparen + 1 } 493 func (x *StarExpr) End() token.Pos { return x.X.End() } 494 func (x *UnaryExpr) End() token.Pos { return x.X.End() } 495 func (x *BinaryExpr) End() token.Pos { return x.Y.End() } 496 func (x *KeyValueExpr) End() token.Pos { return x.Value.End() } 497 func (x *ArrayType) End() token.Pos { return x.Elt.End() } 498 func (x *StructType) End() token.Pos { return x.Fields.End() } 499 func (x *FuncType) End() token.Pos { 500 if x.Results != nil { 501 return x.Results.End() 502 } 503 return x.Params.End() 504 } 505 func (x *InterfaceType) End() token.Pos { return x.Methods.End() } 506 func (x *MapType) End() token.Pos { return x.Value.End() } 507 func (x *ChanType) End() token.Pos { return x.Value.End() } 508 509 // exprNode() ensures that only expression/type nodes can be 510 // assigned to an Expr. 511 // 512 func (*BadExpr) exprNode() {} 513 func (*Ident) exprNode() {} 514 func (*Ellipsis) exprNode() {} 515 func (*BasicLit) exprNode() {} 516 func (*FuncLit) exprNode() {} 517 func (*CompositeLit) exprNode() {} 518 func (*ParenExpr) exprNode() {} 519 func (*SelectorExpr) exprNode() {} 520 func (*IndexExpr) exprNode() {} 521 func (*SliceExpr) exprNode() {} 522 func (*TypeAssertExpr) exprNode() {} 523 func (*CallExpr) exprNode() {} 524 func (*StarExpr) exprNode() {} 525 func (*UnaryExpr) exprNode() {} 526 func (*BinaryExpr) exprNode() {} 527 func (*KeyValueExpr) exprNode() {} 528 529 func (*ArrayType) exprNode() {} 530 func (*StructType) exprNode() {} 531 func (*FuncType) exprNode() {} 532 func (*InterfaceType) exprNode() {} 533 func (*MapType) exprNode() {} 534 func (*ChanType) exprNode() {} 535 536 // ---------------------------------------------------------------------------- 537 // Convenience functions for Idents 538 539 // NewIdent creates a new Ident without position. 540 // Useful for ASTs generated by code other than the Go parser. 541 // 542 func NewIdent(name string) *Ident { return &Ident{token.NoPos, name, nil} } 543 544 // IsExported reports whether name is an exported Go symbol 545 // (that is, whether it begins with an upper-case letter). 546 // 547 func IsExported(name string) bool { 548 ch, _ := utf8.DecodeRuneInString(name) 549 return unicode.IsUpper(ch) 550 } 551 552 // IsExported reports whether id is an exported Go symbol 553 // (that is, whether it begins with an uppercase letter). 554 // 555 func (id *Ident) IsExported() bool { return IsExported(id.Name) } 556 557 func (id *Ident) String() string { 558 if id != nil { 559 return id.Name 560 } 561 return "<nil>" 562 } 563 564 // ---------------------------------------------------------------------------- 565 // Statements 566 567 // A statement is represented by a tree consisting of one 568 // or more of the following concrete statement nodes. 569 // 570 type ( 571 // A BadStmt node is a placeholder for statements containing 572 // syntax errors for which no correct statement nodes can be 573 // created. 574 // 575 BadStmt struct { 576 From, To token.Pos // position range of bad statement 577 } 578 579 // A DeclStmt node represents a declaration in a statement list. 580 // 声明 581 DeclStmt struct { 582 Decl Decl // *GenDecl with CONST, TYPE, or VAR token 583 } 584 585 // An EmptyStmt node represents an empty statement. 586 // The "position" of the empty statement is the position 587 // of the immediately following (explicit or implicit) semicolon. 588 // 空语句 589 EmptyStmt struct { 590 Semicolon token.Pos // position of following ";" 591 Implicit bool // if set, ";" was omitted in the source 592 } 593 594 // A LabeledStmt node represents a labeled statement. 595 // 标签语句 596 LabeledStmt struct { 597 Label *Ident 598 Colon token.Pos // position of ":" 599 Stmt Stmt 600 } 601 602 // An ExprStmt node represents a (stand-alone) expression 603 // in a statement list. 604 // 表达式 605 ExprStmt struct { 606 X Expr // expression 607 } 608 609 // A SendStmt node represents a send statement. 610 // chanenl 发送 611 SendStmt struct { 612 Chan Expr 613 Arrow token.Pos // position of "<-" 614 Value Expr 615 } 616 617 // An IncDecStmt node represents an increment or decrement statement. 618 IncDecStmt struct { 619 X Expr 620 TokPos token.Pos // position of Tok 621 Tok token.Token // INC or DEC 622 } 623 624 // An AssignStmt node represents an assignment or 625 // a short variable declaration. 626 // 赋值 627 AssignStmt struct { 628 Lhs []Expr 629 TokPos token.Pos // position of Tok 630 Tok token.Token // assignment token, DEFINE 631 Rhs []Expr 632 } 633 634 // A GoStmt node represents a go statement. 635 // go表达式 636 GoStmt struct { 637 Go token.Pos // position of "go" keyword 638 Call *CallExpr 639 } 640 641 // A DeferStmt node represents a defer statement. 642 // defer语句 643 DeferStmt struct { 644 Defer token.Pos // position of "defer" keyword 645 Call *CallExpr 646 } 647 648 // A ReturnStmt node represents a return statement. 649 // 返回语句 650 ReturnStmt struct { 651 Return token.Pos // position of "return" keyword 652 Results []Expr // result expressions; or nil 653 } 654 655 // A BranchStmt node represents a break, continue, goto, 656 // or fallthrough statement. 657 // break, continue, goto, fallthrought 语句 658 BranchStmt struct { 659 TokPos token.Pos // position of Tok 660 Tok token.Token // keyword token (BREAK, CONTINUE, GOTO, FALLTHROUGH) 661 Label *Ident // label name; or nil 662 } 663 664 // A BlockStmt node represents a braced statement list. 665 // 代码块语句 666 BlockStmt struct { 667 Lbrace token.Pos // position of "{" 668 List []Stmt 669 Rbrace token.Pos // position of "}" 670 } 671 672 // An IfStmt node represents an if statement. 673 // if语句 674 IfStmt struct { 675 If token.Pos // position of "if" keyword 676 Init Stmt // initialization statement; or nil 677 Cond Expr // condition 678 Body *BlockStmt 679 Else Stmt // else branch; or nil 680 } 681 682 // A CaseClause represents a case of an expression or type switch statement. 683 // case语句 684 CaseClause struct { 685 Case token.Pos // position of "case" or "default" keyword 686 List []Expr // list of expressions or types; nil means default case 687 Colon token.Pos // position of ":" 688 Body []Stmt // statement list; or nil 689 } 690 691 // A SwitchStmt node represents an expression switch statement. 692 // switch语句 693 SwitchStmt struct { 694 Switch token.Pos // position of "switch" keyword 695 Init Stmt // initialization statement; or nil 696 Tag Expr // tag expression; or nil 697 Body *BlockStmt // CaseClauses only 698 } 699 700 // An TypeSwitchStmt node represents a type switch statement. 701 // type语句 702 TypeSwitchStmt struct { 703 Switch token.Pos // position of "switch" keyword 704 Init Stmt // initialization statement; or nil 705 Assign Stmt // x := y.(type) or y.(type) 706 Body *BlockStmt // CaseClauses only 707 } 708 709 // A CommClause node represents a case of a select statement. 710 CommClause struct { 711 Case token.Pos // position of "case" or "default" keyword 712 Comm Stmt // send or receive statement; nil means default case 713 Colon token.Pos // position of ":" 714 Body []Stmt // statement list; or nil 715 } 716 717 // An SelectStmt node represents a select statement. 718 // select语句 719 SelectStmt struct { 720 Select token.Pos // position of "select" keyword 721 Body *BlockStmt // CommClauses only 722 } 723 724 // A ForStmt represents a for statement. 725 // for语句 726 ForStmt struct { 727 For token.Pos // position of "for" keyword 728 Init Stmt // initialization statement; or nil 729 Cond Expr // condition; or nil 730 Post Stmt // post iteration statement; or nil 731 Body *BlockStmt 732 } 733 734 // A RangeStmt represents a for statement with a range clause. 735 // range语句 736 RangeStmt struct { 737 For token.Pos // position of "for" keyword 738 Key, Value Expr // Key, Value may be nil 739 TokPos token.Pos // position of Tok; invalid if Key == nil 740 Tok token.Token // ILLEGAL if Key == nil, ASSIGN, DEFINE 741 X Expr // value to range over 742 Body *BlockStmt 743 } 744 ) 745 746 // Pos and End implementations for statement nodes. 747 748 func (s *BadStmt) Pos() token.Pos { return s.From } 749 func (s *DeclStmt) Pos() token.Pos { return s.Decl.Pos() } 750 func (s *EmptyStmt) Pos() token.Pos { return s.Semicolon } 751 func (s *LabeledStmt) Pos() token.Pos { return s.Label.Pos() } 752 func (s *ExprStmt) Pos() token.Pos { return s.X.Pos() } 753 func (s *SendStmt) Pos() token.Pos { return s.Chan.Pos() } 754 func (s *IncDecStmt) Pos() token.Pos { return s.X.Pos() } 755 func (s *AssignStmt) Pos() token.Pos { return s.Lhs[0].Pos() } 756 func (s *GoStmt) Pos() token.Pos { return s.Go } 757 func (s *DeferStmt) Pos() token.Pos { return s.Defer } 758 func (s *ReturnStmt) Pos() token.Pos { return s.Return } 759 func (s *BranchStmt) Pos() token.Pos { return s.TokPos } 760 func (s *BlockStmt) Pos() token.Pos { return s.Lbrace } 761 func (s *IfStmt) Pos() token.Pos { return s.If } 762 func (s *CaseClause) Pos() token.Pos { return s.Case } 763 func (s *SwitchStmt) Pos() token.Pos { return s.Switch } 764 func (s *TypeSwitchStmt) Pos() token.Pos { return s.Switch } 765 func (s *CommClause) Pos() token.Pos { return s.Case } 766 func (s *SelectStmt) Pos() token.Pos { return s.Select } 767 func (s *ForStmt) Pos() token.Pos { return s.For } 768 func (s *RangeStmt) Pos() token.Pos { return s.For } 769 770 func (s *BadStmt) End() token.Pos { return s.To } 771 func (s *DeclStmt) End() token.Pos { return s.Decl.End() } 772 func (s *EmptyStmt) End() token.Pos { 773 if s.Implicit { 774 return s.Semicolon 775 } 776 return s.Semicolon + 1 /* len(";") */ 777 } 778 func (s *LabeledStmt) End() token.Pos { return s.Stmt.End() } 779 func (s *ExprStmt) End() token.Pos { return s.X.End() } 780 func (s *SendStmt) End() token.Pos { return s.Value.End() } 781 func (s *IncDecStmt) End() token.Pos { 782 return s.TokPos + 2 /* len("++") */ 783 } 784 func (s *AssignStmt) End() token.Pos { return s.Rhs[len(s.Rhs)-1].End() } 785 func (s *GoStmt) End() token.Pos { return s.Call.End() } 786 func (s *DeferStmt) End() token.Pos { return s.Call.End() } 787 func (s *ReturnStmt) End() token.Pos { 788 if n := len(s.Results); n > 0 { 789 return s.Results[n-1].End() 790 } 791 return s.Return + 6 // len("return") 792 } 793 func (s *BranchStmt) End() token.Pos { 794 if s.Label != nil { 795 return s.Label.End() 796 } 797 return token.Pos(int(s.TokPos) + len(s.Tok.String())) 798 } 799 func (s *BlockStmt) End() token.Pos { return s.Rbrace + 1 } 800 func (s *IfStmt) End() token.Pos { 801 if s.Else != nil { 802 return s.Else.End() 803 } 804 return s.Body.End() 805 } 806 func (s *CaseClause) End() token.Pos { 807 if n := len(s.Body); n > 0 { 808 return s.Body[n-1].End() 809 } 810 return s.Colon + 1 811 } 812 func (s *SwitchStmt) End() token.Pos { return s.Body.End() } 813 func (s *TypeSwitchStmt) End() token.Pos { return s.Body.End() } 814 func (s *CommClause) End() token.Pos { 815 if n := len(s.Body); n > 0 { 816 return s.Body[n-1].End() 817 } 818 return s.Colon + 1 819 } 820 func (s *SelectStmt) End() token.Pos { return s.Body.End() } 821 func (s *ForStmt) End() token.Pos { return s.Body.End() } 822 func (s *RangeStmt) End() token.Pos { return s.Body.End() } 823 824 // stmtNode() ensures that only statement nodes can be 825 // assigned to a Stmt. 826 // 827 func (*BadStmt) stmtNode() {} 828 func (*DeclStmt) stmtNode() {} 829 func (*EmptyStmt) stmtNode() {} 830 func (*LabeledStmt) stmtNode() {} 831 func (*ExprStmt) stmtNode() {} 832 func (*SendStmt) stmtNode() {} 833 func (*IncDecStmt) stmtNode() {} 834 func (*AssignStmt) stmtNode() {} 835 func (*GoStmt) stmtNode() {} 836 func (*DeferStmt) stmtNode() {} 837 func (*ReturnStmt) stmtNode() {} 838 func (*BranchStmt) stmtNode() {} 839 func (*BlockStmt) stmtNode() {} 840 func (*IfStmt) stmtNode() {} 841 func (*CaseClause) stmtNode() {} 842 func (*SwitchStmt) stmtNode() {} 843 func (*TypeSwitchStmt) stmtNode() {} 844 func (*CommClause) stmtNode() {} 845 func (*SelectStmt) stmtNode() {} 846 func (*ForStmt) stmtNode() {} 847 func (*RangeStmt) stmtNode() {} 848 849 // ---------------------------------------------------------------------------- 850 // Declarations 851 852 // A Spec node represents a single (non-parenthesized) import, 853 // constant, type, or variable declaration. 854 // 855 type ( 856 // The Spec type stands for any of *ImportSpec, *ValueSpec, and *TypeSpec. 857 Spec interface { 858 Node 859 specNode() 860 } 861 862 // An ImportSpec node represents a single package import. 863 // import Spec 864 // 导入 865 ImportSpec struct { 866 Doc *CommentGroup // associated documentation; or nil 867 Name *Ident // local package name (including "."); or nil 868 Path *BasicLit // import path 869 Comment *CommentGroup // line comments; or nil 870 EndPos token.Pos // end of spec (overrides Path.Pos if nonzero) 871 } 872 873 // A ValueSpec node represents a constant or variable declaration 874 // (ConstSpec or VarSpec production). 875 // 声明变量 var 876 ValueSpec struct { 877 Doc *CommentGroup // associated documentation; or nil 878 Names []*Ident // value names (len(Names) > 0) 879 Type Expr // value type; or nil 880 Values []Expr // initial values; or nil 881 Comment *CommentGroup // line comments; or nil 882 } 883 884 // A TypeSpec node represents a type declaration (TypeSpec production). 885 // 类型声明 886 TypeSpec struct { 887 Doc *CommentGroup // associated documentation; or nil 888 Name *Ident // type name 889 Assign token.Pos // position of '=', if any 890 Type Expr // *Ident, *ParenExpr, *SelectorExpr, *StarExpr, or any of the *XxxTypes 891 Comment *CommentGroup // line comments; or nil 892 } 893 ) 894 895 // Pos and End implementations for spec nodes. 896 897 func (s *ImportSpec) Pos() token.Pos { 898 if s.Name != nil { 899 return s.Name.Pos() 900 } 901 return s.Path.Pos() 902 } 903 func (s *ValueSpec) Pos() token.Pos { return s.Names[0].Pos() } 904 func (s *TypeSpec) Pos() token.Pos { return s.Name.Pos() } 905 906 func (s *ImportSpec) End() token.Pos { 907 if s.EndPos != 0 { 908 return s.EndPos 909 } 910 return s.Path.End() 911 } 912 913 func (s *ValueSpec) End() token.Pos { 914 if n := len(s.Values); n > 0 { 915 return s.Values[n-1].End() 916 } 917 if s.Type != nil { 918 return s.Type.End() 919 } 920 return s.Names[len(s.Names)-1].End() 921 } 922 func (s *TypeSpec) End() token.Pos { return s.Type.End() } 923 924 // specNode() ensures that only spec nodes can be 925 // assigned to a Spec. 926 // 927 func (*ImportSpec) specNode() {} 928 func (*ValueSpec) specNode() {} 929 func (*TypeSpec) specNode() {} 930 931 // A declaration is represented by one of the following declaration nodes. 932 // 933 type ( 934 // A BadDecl node is a placeholder for declarations containing 935 // syntax errors for which no correct declaration nodes can be 936 // created. 937 // 938 BadDecl struct { 939 From, To token.Pos // position range of bad declaration 940 } 941 942 // A GenDecl node (generic declaration node) represents an import, 943 // constant, type or variable declaration. A valid Lparen position 944 // (Lparen.IsValid()) indicates a parenthesized declaration. 945 // 946 // Relationship between Tok value and Specs element type: 947 // 948 // token.IMPORT *ImportSpec 949 // token.CONST *ValueSpec 950 // token.TYPE *TypeSpec 951 // token.VAR *ValueSpec 952 // 953 GenDecl struct { 954 Doc *CommentGroup // associated documentation; or nil 955 TokPos token.Pos // position of Tok 956 Tok token.Token // IMPORT, CONST, TYPE, VAR 957 Lparen token.Pos // position of '(', if any 958 Specs []Spec 959 Rparen token.Pos // position of ')', if any 960 } 961 962 // A FuncDecl node represents a function declaration. 963 FuncDecl struct { 964 Doc *CommentGroup // associated documentation; or nil 965 Recv *FieldList // receiver (methods); or nil (functions) 966 Name *Ident // function/method name 967 Type *FuncType // function signature: parameters, results, and position of "func" keyword 968 Body *BlockStmt // function body; or nil for external (non-Go) function 969 } 970 ) 971 972 // Pos and End implementations for declaration nodes. 973 974 func (d *BadDecl) Pos() token.Pos { return d.From } 975 func (d *GenDecl) Pos() token.Pos { return d.TokPos } 976 func (d *FuncDecl) Pos() token.Pos { return d.Type.Pos() } 977 978 func (d *BadDecl) End() token.Pos { return d.To } 979 func (d *GenDecl) End() token.Pos { 980 if d.Rparen.IsValid() { 981 return d.Rparen + 1 982 } 983 return d.Specs[0].End() 984 } 985 func (d *FuncDecl) End() token.Pos { 986 if d.Body != nil { 987 return d.Body.End() 988 } 989 return d.Type.End() 990 } 991 992 // declNode() ensures that only declaration nodes can be 993 // assigned to a Decl. 994 // 995 func (*BadDecl) declNode() {} 996 func (*GenDecl) declNode() {} 997 func (*FuncDecl) declNode() {} 998 999 // ---------------------------------------------------------------------------- 1000 // Files and packages 1001 1002 // A File node represents a Go source file. 1003 // 1004 // The Comments list contains all comments in the source file in order of 1005 // appearance, including the comments that are pointed to from other nodes 1006 // via Doc and Comment fields. 1007 // 1008 // For correct printing of source code containing comments (using packages 1009 // go/format and go/printer), special care must be taken to update comments 1010 // when a File's syntax tree is modified: For printing, comments are interspersed 1011 // between tokens based on their position. If syntax tree nodes are 1012 // removed or moved, relevant comments in their vicinity must also be removed 1013 // (from the File.Comments list) or moved accordingly (by updating their 1014 // positions). A CommentMap may be used to facilitate some of these operations. 1015 // 1016 // Whether and how a comment is associated with a node depends on the 1017 // interpretation of the syntax tree by the manipulating program: Except for Doc 1018 // and Comment comments directly associated with nodes, the remaining comments 1019 // are "free-floating" (see also issues #18593, #20744). 1020 // 1021 type File struct { 1022 Doc *CommentGroup // associated documentation; or nil 1023 Package token.Pos // position of "package" keyword 1024 Name *Ident // package name 1025 Decls []Decl // top-level declarations; or nil 1026 Scope *Scope // package scope (this file only) 1027 Imports []*ImportSpec // imports in this file 1028 Unresolved []*Ident // unresolved identifiers in this file 1029 Comments []*CommentGroup // list of all comments in the source file 1030 } 1031 1032 func (f *File) Pos() token.Pos { return f.Package } 1033 func (f *File) End() token.Pos { 1034 if n := len(f.Decls); n > 0 { 1035 return f.Decls[n-1].End() 1036 } 1037 return f.Name.End() 1038 } 1039 1040 // A Package node represents a set of source files 1041 // collectively building a Go package. 1042 // 1043 type Package struct { 1044 Name string // package name 1045 Scope *Scope // package scope across all files 1046 Imports map[string]*Object // map of package id -> package object 1047 Files map[string]*File // Go source files by filename 1048 } 1049 1050 func (p *Package) Pos() token.Pos { return token.NoPos } 1051 func (p *Package) End() token.Pos { return token.NoPos }