Black Lives Matter. Support the Equal Justice Initiative.

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

View as plain text