Source file src/go/ast/ast.go

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

View as plain text