...

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

View as plain text