...
Run Format

Source file src/go/ast/ast.go

Documentation: go/ast

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

View as plain text