...
Run Format

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

View as plain text