The Go Programming Language

Source file src/pkg/go/parser/parser.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 parser implements a parser for Go source files. Input may be
     6	// provided in a variety of forms (see the various Parse* functions); the
     7	// output is an abstract syntax tree (AST) representing the Go source. The
     8	// parser is invoked through one of the Parse* functions.
     9	//
    10	package parser
    11	
    12	import (
    13		"fmt"
    14		"go/ast"
    15		"go/scanner"
    16		"go/token"
    17	)
    18	
    19	// The mode parameter to the Parse* functions is a set of flags (or 0).
    20	// They control the amount of source code parsed and other optional
    21	// parser functionality.
    22	//
    23	const (
    24		PackageClauseOnly uint = 1 << iota // parsing stops after package clause
    25		ImportsOnly                        // parsing stops after import declarations
    26		ParseComments                      // parse comments and add them to AST
    27		Trace                              // print a trace of parsed productions
    28		DeclarationErrors                  // report declaration errors
    29		SpuriousErrors                     // report all (not just the first) errors per line
    30	)
    31	
    32	// The parser structure holds the parser's internal state.
    33	type parser struct {
    34		file *token.File
    35		scanner.ErrorVector
    36		scanner scanner.Scanner
    37	
    38		// Tracing/debugging
    39		mode   uint // parsing mode
    40		trace  bool // == (mode & Trace != 0)
    41		indent uint // indentation used for tracing output
    42	
    43		// Comments
    44		comments    []*ast.CommentGroup
    45		leadComment *ast.CommentGroup // last lead comment
    46		lineComment *ast.CommentGroup // last line comment
    47	
    48		// Next token
    49		pos token.Pos   // token position
    50		tok token.Token // one token look-ahead
    51		lit string      // token literal
    52	
    53		// Non-syntactic parser control
    54		exprLev int // < 0: in control clause, >= 0: in expression
    55	
    56		// Ordinary identifier scopes
    57		pkgScope   *ast.Scope        // pkgScope.Outer == nil
    58		topScope   *ast.Scope        // top-most scope; may be pkgScope
    59		unresolved []*ast.Ident      // unresolved identifiers
    60		imports    []*ast.ImportSpec // list of imports
    61	
    62		// Label scope
    63		// (maintained by open/close LabelScope)
    64		labelScope  *ast.Scope     // label scope for current function
    65		targetStack [][]*ast.Ident // stack of unresolved labels
    66	}
    67	
    68	// scannerMode returns the scanner mode bits given the parser's mode bits.
    69	func scannerMode(mode uint) uint {
    70		var m uint = scanner.InsertSemis
    71		if mode&ParseComments != 0 {
    72			m |= scanner.ScanComments
    73		}
    74		return m
    75	}
    76	
    77	func (p *parser) init(fset *token.FileSet, filename string, src []byte, mode uint) {
    78		p.file = fset.AddFile(filename, fset.Base(), len(src))
    79		p.scanner.Init(p.file, src, p, scannerMode(mode))
    80	
    81		p.mode = mode
    82		p.trace = mode&Trace != 0 // for convenience (p.trace is used frequently)
    83	
    84		p.next()
    85	
    86		// set up the pkgScope here (as opposed to in parseFile) because
    87		// there are other parser entry points (ParseExpr, etc.)
    88		p.openScope()
    89		p.pkgScope = p.topScope
    90	
    91		// for the same reason, set up a label scope
    92		p.openLabelScope()
    93	}
    94	
    95	// ----------------------------------------------------------------------------
    96	// Scoping support
    97	
    98	func (p *parser) openScope() {
    99		p.topScope = ast.NewScope(p.topScope)
   100	}
   101	
   102	func (p *parser) closeScope() {
   103		p.topScope = p.topScope.Outer
   104	}
   105	
   106	func (p *parser) openLabelScope() {
   107		p.labelScope = ast.NewScope(p.labelScope)
   108		p.targetStack = append(p.targetStack, nil)
   109	}
   110	
   111	func (p *parser) closeLabelScope() {
   112		// resolve labels
   113		n := len(p.targetStack) - 1
   114		scope := p.labelScope
   115		for _, ident := range p.targetStack[n] {
   116			ident.Obj = scope.Lookup(ident.Name)
   117			if ident.Obj == nil && p.mode&DeclarationErrors != 0 {
   118				p.error(ident.Pos(), fmt.Sprintf("label %s undefined", ident.Name))
   119			}
   120		}
   121		// pop label scope
   122		p.targetStack = p.targetStack[0:n]
   123		p.labelScope = p.labelScope.Outer
   124	}
   125	
   126	func (p *parser) declare(decl, data interface{}, scope *ast.Scope, kind ast.ObjKind, idents ...*ast.Ident) {
   127		for _, ident := range idents {
   128			assert(ident.Obj == nil, "identifier already declared or resolved")
   129			obj := ast.NewObj(kind, ident.Name)
   130			// remember the corresponding declaration for redeclaration
   131			// errors and global variable resolution/typechecking phase
   132			obj.Decl = decl
   133			obj.Data = data
   134			ident.Obj = obj
   135			if ident.Name != "_" {
   136				if alt := scope.Insert(obj); alt != nil && p.mode&DeclarationErrors != 0 {
   137					prevDecl := ""
   138					if pos := alt.Pos(); pos.IsValid() {
   139						prevDecl = fmt.Sprintf("\n\tprevious declaration at %s", p.file.Position(pos))
   140					}
   141					p.error(ident.Pos(), fmt.Sprintf("%s redeclared in this block%s", ident.Name, prevDecl))
   142				}
   143			}
   144		}
   145	}
   146	
   147	func (p *parser) shortVarDecl(idents []*ast.Ident) {
   148		// Go spec: A short variable declaration may redeclare variables
   149		// provided they were originally declared in the same block with
   150		// the same type, and at least one of the non-blank variables is new.
   151		n := 0 // number of new variables
   152		for _, ident := range idents {
   153			assert(ident.Obj == nil, "identifier already declared or resolved")
   154			obj := ast.NewObj(ast.Var, ident.Name)
   155			// short var declarations cannot have redeclaration errors
   156			// and are not global => no need to remember the respective
   157			// declaration
   158			ident.Obj = obj
   159			if ident.Name != "_" {
   160				if alt := p.topScope.Insert(obj); alt != nil {
   161					ident.Obj = alt // redeclaration
   162				} else {
   163					n++ // new declaration
   164				}
   165			}
   166		}
   167		if n == 0 && p.mode&DeclarationErrors != 0 {
   168			p.error(idents[0].Pos(), "no new variables on left side of :=")
   169		}
   170	}
   171	
   172	// The unresolved object is a sentinel to mark identifiers that have been added
   173	// to the list of unresolved identifiers. The sentinel is only used for verifying
   174	// internal consistency.
   175	var unresolved = new(ast.Object)
   176	
   177	func (p *parser) resolve(x ast.Expr) {
   178		// nothing to do if x is not an identifier or the blank identifier
   179		ident, _ := x.(*ast.Ident)
   180		if ident == nil {
   181			return
   182		}
   183		assert(ident.Obj == nil, "identifier already declared or resolved")
   184		if ident.Name == "_" {
   185			return
   186		}
   187		// try to resolve the identifier
   188		for s := p.topScope; s != nil; s = s.Outer {
   189			if obj := s.Lookup(ident.Name); obj != nil {
   190				ident.Obj = obj
   191				return
   192			}
   193		}
   194		// all local scopes are known, so any unresolved identifier
   195		// must be found either in the file scope, package scope
   196		// (perhaps in another file), or universe scope --- collect
   197		// them so that they can be resolved later
   198		ident.Obj = unresolved
   199		p.unresolved = append(p.unresolved, ident)
   200	}
   201	
   202	// ----------------------------------------------------------------------------
   203	// Parsing support
   204	
   205	func (p *parser) printTrace(a ...interface{}) {
   206		const dots = ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . " +
   207			". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
   208		const n = uint(len(dots))
   209		pos := p.file.Position(p.pos)
   210		fmt.Printf("%5d:%3d: ", pos.Line, pos.Column)
   211		i := 2 * p.indent
   212		for ; i > n; i -= n {
   213			fmt.Print(dots)
   214		}
   215		fmt.Print(dots[0:i])
   216		fmt.Println(a...)
   217	}
   218	
   219	func trace(p *parser, msg string) *parser {
   220		p.printTrace(msg, "(")
   221		p.indent++
   222		return p
   223	}
   224	
   225	// Usage pattern: defer un(trace(p, "..."));
   226	func un(p *parser) {
   227		p.indent--
   228		p.printTrace(")")
   229	}
   230	
   231	// Advance to the next token.
   232	func (p *parser) next0() {
   233		// Because of one-token look-ahead, print the previous token
   234		// when tracing as it provides a more readable output. The
   235		// very first token (!p.pos.IsValid()) is not initialized
   236		// (it is token.ILLEGAL), so don't print it .
   237		if p.trace && p.pos.IsValid() {
   238			s := p.tok.String()
   239			switch {
   240			case p.tok.IsLiteral():
   241				p.printTrace(s, p.lit)
   242			case p.tok.IsOperator(), p.tok.IsKeyword():
   243				p.printTrace("\"" + s + "\"")
   244			default:
   245				p.printTrace(s)
   246			}
   247		}
   248	
   249		p.pos, p.tok, p.lit = p.scanner.Scan()
   250	}
   251	
   252	// Consume a comment and return it and the line on which it ends.
   253	func (p *parser) consumeComment() (comment *ast.Comment, endline int) {
   254		// /*-style comments may end on a different line than where they start.
   255		// Scan the comment for '\n' chars and adjust endline accordingly.
   256		endline = p.file.Line(p.pos)
   257		if p.lit[1] == '*' {
   258			// don't use range here - no need to decode Unicode code points
   259			for i := 0; i < len(p.lit); i++ {
   260				if p.lit[i] == '\n' {
   261					endline++
   262				}
   263			}
   264		}
   265	
   266		comment = &ast.Comment{p.pos, p.lit}
   267		p.next0()
   268	
   269		return
   270	}
   271	
   272	// Consume a group of adjacent comments, add it to the parser's
   273	// comments list, and return it together with the line at which
   274	// the last comment in the group ends. An empty line or non-comment
   275	// token terminates a comment group.
   276	//
   277	func (p *parser) consumeCommentGroup() (comments *ast.CommentGroup, endline int) {
   278		var list []*ast.Comment
   279		endline = p.file.Line(p.pos)
   280		for p.tok == token.COMMENT && endline+1 >= p.file.Line(p.pos) {
   281			var comment *ast.Comment
   282			comment, endline = p.consumeComment()
   283			list = append(list, comment)
   284		}
   285	
   286		// add comment group to the comments list
   287		comments = &ast.CommentGroup{list}
   288		p.comments = append(p.comments, comments)
   289	
   290		return
   291	}
   292	
   293	// Advance to the next non-comment token. In the process, collect
   294	// any comment groups encountered, and remember the last lead and
   295	// and line comments.
   296	//
   297	// A lead comment is a comment group that starts and ends in a
   298	// line without any other tokens and that is followed by a non-comment
   299	// token on the line immediately after the comment group.
   300	//
   301	// A line comment is a comment group that follows a non-comment
   302	// token on the same line, and that has no tokens after it on the line
   303	// where it ends.
   304	//
   305	// Lead and line comments may be considered documentation that is
   306	// stored in the AST.
   307	//
   308	func (p *parser) next() {
   309		p.leadComment = nil
   310		p.lineComment = nil
   311		line := p.file.Line(p.pos) // current line
   312		p.next0()
   313	
   314		if p.tok == token.COMMENT {
   315			var comment *ast.CommentGroup
   316			var endline int
   317	
   318			if p.file.Line(p.pos) == line {
   319				// The comment is on same line as the previous token; it
   320				// cannot be a lead comment but may be a line comment.
   321				comment, endline = p.consumeCommentGroup()
   322				if p.file.Line(p.pos) != endline {
   323					// The next token is on a different line, thus
   324					// the last comment group is a line comment.
   325					p.lineComment = comment
   326				}
   327			}
   328	
   329			// consume successor comments, if any
   330			endline = -1
   331			for p.tok == token.COMMENT {
   332				comment, endline = p.consumeCommentGroup()
   333			}
   334	
   335			if endline+1 == p.file.Line(p.pos) {
   336				// The next token is following on the line immediately after the
   337				// comment group, thus the last comment group is a lead comment.
   338				p.leadComment = comment
   339			}
   340		}
   341	}
   342	
   343	func (p *parser) error(pos token.Pos, msg string) {
   344		p.Error(p.file.Position(pos), msg)
   345	}
   346	
   347	func (p *parser) errorExpected(pos token.Pos, msg string) {
   348		msg = "expected " + msg
   349		if pos == p.pos {
   350			// the error happened at the current position;
   351			// make the error message more specific
   352			if p.tok == token.SEMICOLON && p.lit[0] == '\n' {
   353				msg += ", found newline"
   354			} else {
   355				msg += ", found '" + p.tok.String() + "'"
   356				if p.tok.IsLiteral() {
   357					msg += " " + p.lit
   358				}
   359			}
   360		}
   361		p.error(pos, msg)
   362	}
   363	
   364	func (p *parser) expect(tok token.Token) token.Pos {
   365		pos := p.pos
   366		if p.tok != tok {
   367			p.errorExpected(pos, "'"+tok.String()+"'")
   368		}
   369		p.next() // make progress
   370		return pos
   371	}
   372	
   373	func (p *parser) expectSemi() {
   374		if p.tok != token.RPAREN && p.tok != token.RBRACE {
   375			p.expect(token.SEMICOLON)
   376		}
   377	}
   378	
   379	func assert(cond bool, msg string) {
   380		if !cond {
   381			panic("go/parser internal error: " + msg)
   382		}
   383	}
   384	
   385	// ----------------------------------------------------------------------------
   386	// Identifiers
   387	
   388	func (p *parser) parseIdent() *ast.Ident {
   389		pos := p.pos
   390		name := "_"
   391		if p.tok == token.IDENT {
   392			name = p.lit
   393			p.next()
   394		} else {
   395			p.expect(token.IDENT) // use expect() error handling
   396		}
   397		return &ast.Ident{pos, name, nil}
   398	}
   399	
   400	func (p *parser) parseIdentList() (list []*ast.Ident) {
   401		if p.trace {
   402			defer un(trace(p, "IdentList"))
   403		}
   404	
   405		list = append(list, p.parseIdent())
   406		for p.tok == token.COMMA {
   407			p.next()
   408			list = append(list, p.parseIdent())
   409		}
   410	
   411		return
   412	}
   413	
   414	// ----------------------------------------------------------------------------
   415	// Common productions
   416	
   417	// If lhs is set, result list elements which are identifiers are not resolved.
   418	func (p *parser) parseExprList(lhs bool) (list []ast.Expr) {
   419		if p.trace {
   420			defer un(trace(p, "ExpressionList"))
   421		}
   422	
   423		list = append(list, p.checkExpr(p.parseExpr(lhs)))
   424		for p.tok == token.COMMA {
   425			p.next()
   426			list = append(list, p.checkExpr(p.parseExpr(lhs)))
   427		}
   428	
   429		return
   430	}
   431	
   432	func (p *parser) parseLhsList() []ast.Expr {
   433		list := p.parseExprList(true)
   434		switch p.tok {
   435		case token.DEFINE:
   436			// lhs of a short variable declaration
   437			p.shortVarDecl(p.makeIdentList(list))
   438		case token.COLON:
   439			// lhs of a label declaration or a communication clause of a select
   440			// statement (parseLhsList is not called when parsing the case clause
   441			// of a switch statement):
   442			// - labels are declared by the caller of parseLhsList
   443			// - for communication clauses, if there is a stand-alone identifier
   444			//   followed by a colon, we have a syntax error; there is no need
   445			//   to resolve the identifier in that case
   446		default:
   447			// identifiers must be declared elsewhere
   448			for _, x := range list {
   449				p.resolve(x)
   450			}
   451		}
   452		return list
   453	}
   454	
   455	func (p *parser) parseRhsList() []ast.Expr {
   456		return p.parseExprList(false)
   457	}
   458	
   459	// ----------------------------------------------------------------------------
   460	// Types
   461	
   462	func (p *parser) parseType() ast.Expr {
   463		if p.trace {
   464			defer un(trace(p, "Type"))
   465		}
   466	
   467		typ := p.tryType()
   468	
   469		if typ == nil {
   470			pos := p.pos
   471			p.errorExpected(pos, "type")
   472			p.next() // make progress
   473			return &ast.BadExpr{pos, p.pos}
   474		}
   475	
   476		return typ
   477	}
   478	
   479	// If the result is an identifier, it is not resolved.
   480	func (p *parser) parseTypeName() ast.Expr {
   481		if p.trace {
   482			defer un(trace(p, "TypeName"))
   483		}
   484	
   485		ident := p.parseIdent()
   486		// don't resolve ident yet - it may be a parameter or field name
   487	
   488		if p.tok == token.PERIOD {
   489			// ident is a package name
   490			p.next()
   491			p.resolve(ident)
   492			sel := p.parseIdent()
   493			return &ast.SelectorExpr{ident, sel}
   494		}
   495	
   496		return ident
   497	}
   498	
   499	func (p *parser) parseArrayType(ellipsisOk bool) ast.Expr {
   500		if p.trace {
   501			defer un(trace(p, "ArrayType"))
   502		}
   503	
   504		lbrack := p.expect(token.LBRACK)
   505		var len ast.Expr
   506		if ellipsisOk && p.tok == token.ELLIPSIS {
   507			len = &ast.Ellipsis{p.pos, nil}
   508			p.next()
   509		} else if p.tok != token.RBRACK {
   510			len = p.parseRhs()
   511		}
   512		p.expect(token.RBRACK)
   513		elt := p.parseType()
   514	
   515		return &ast.ArrayType{lbrack, len, elt}
   516	}
   517	
   518	func (p *parser) makeIdentList(list []ast.Expr) []*ast.Ident {
   519		idents := make([]*ast.Ident, len(list))
   520		for i, x := range list {
   521			ident, isIdent := x.(*ast.Ident)
   522			if !isIdent {
   523				pos := x.(ast.Expr).Pos()
   524				p.errorExpected(pos, "identifier")
   525				ident = &ast.Ident{pos, "_", nil}
   526			}
   527			idents[i] = ident
   528		}
   529		return idents
   530	}
   531	
   532	func (p *parser) parseFieldDecl(scope *ast.Scope) *ast.Field {
   533		if p.trace {
   534			defer un(trace(p, "FieldDecl"))
   535		}
   536	
   537		doc := p.leadComment
   538	
   539		// fields
   540		list, typ := p.parseVarList(false)
   541	
   542		// optional tag
   543		var tag *ast.BasicLit
   544		if p.tok == token.STRING {
   545			tag = &ast.BasicLit{p.pos, p.tok, p.lit}
   546			p.next()
   547		}
   548	
   549		// analyze case
   550		var idents []*ast.Ident
   551		if typ != nil {
   552			// IdentifierList Type
   553			idents = p.makeIdentList(list)
   554		} else {
   555			// ["*"] TypeName (AnonymousField)
   556			typ = list[0] // we always have at least one element
   557			p.resolve(typ)
   558			if n := len(list); n > 1 || !isTypeName(deref(typ)) {
   559				pos := typ.Pos()
   560				p.errorExpected(pos, "anonymous field")
   561				typ = &ast.BadExpr{pos, list[n-1].End()}
   562			}
   563		}
   564	
   565		p.expectSemi() // call before accessing p.linecomment
   566	
   567		field := &ast.Field{doc, idents, typ, tag, p.lineComment}
   568		p.declare(field, nil, scope, ast.Var, idents...)
   569	
   570		return field
   571	}
   572	
   573	func (p *parser) parseStructType() *ast.StructType {
   574		if p.trace {
   575			defer un(trace(p, "StructType"))
   576		}
   577	
   578		pos := p.expect(token.STRUCT)
   579		lbrace := p.expect(token.LBRACE)
   580		scope := ast.NewScope(nil) // struct scope
   581		var list []*ast.Field
   582		for p.tok == token.IDENT || p.tok == token.MUL || p.tok == token.LPAREN {
   583			// a field declaration cannot start with a '(' but we accept
   584			// it here for more robust parsing and better error messages
   585			// (parseFieldDecl will check and complain if necessary)
   586			list = append(list, p.parseFieldDecl(scope))
   587		}
   588		rbrace := p.expect(token.RBRACE)
   589	
   590		// TODO(gri): store struct scope in AST
   591		return &ast.StructType{pos, &ast.FieldList{lbrace, list, rbrace}, false}
   592	}
   593	
   594	func (p *parser) parsePointerType() *ast.StarExpr {
   595		if p.trace {
   596			defer un(trace(p, "PointerType"))
   597		}
   598	
   599		star := p.expect(token.MUL)
   600		base := p.parseType()
   601	
   602		return &ast.StarExpr{star, base}
   603	}
   604	
   605	func (p *parser) tryVarType(isParam bool) ast.Expr {
   606		if isParam && p.tok == token.ELLIPSIS {
   607			pos := p.pos
   608			p.next()
   609			typ := p.tryIdentOrType(isParam) // don't use parseType so we can provide better error message
   610			if typ == nil {
   611				p.error(pos, "'...' parameter is missing type")
   612				typ = &ast.BadExpr{pos, p.pos}
   613			}
   614			if p.tok != token.RPAREN {
   615				p.error(pos, "can use '...' with last parameter type only")
   616			}
   617			return &ast.Ellipsis{pos, typ}
   618		}
   619		return p.tryIdentOrType(false)
   620	}
   621	
   622	func (p *parser) parseVarType(isParam bool) ast.Expr {
   623		typ := p.tryVarType(isParam)
   624		if typ == nil {
   625			pos := p.pos
   626			p.errorExpected(pos, "type")
   627			p.next() // make progress
   628			typ = &ast.BadExpr{pos, p.pos}
   629		}
   630		return typ
   631	}
   632	
   633	func (p *parser) parseVarList(isParam bool) (list []ast.Expr, typ ast.Expr) {
   634		if p.trace {
   635			defer un(trace(p, "VarList"))
   636		}
   637	
   638		// a list of identifiers looks like a list of type names
   639		for {
   640			// parseVarType accepts any type (including parenthesized ones)
   641			// even though the syntax does not permit them here: we
   642			// accept them all for more robust parsing and complain
   643			// afterwards
   644			list = append(list, p.parseVarType(isParam))
   645			if p.tok != token.COMMA {
   646				break
   647			}
   648			p.next()
   649		}
   650	
   651		// if we had a list of identifiers, it must be followed by a type
   652		typ = p.tryVarType(isParam)
   653		if typ != nil {
   654			p.resolve(typ)
   655		}
   656	
   657		return
   658	}
   659	
   660	func (p *parser) parseParameterList(scope *ast.Scope, ellipsisOk bool) (params []*ast.Field) {
   661		if p.trace {
   662			defer un(trace(p, "ParameterList"))
   663		}
   664	
   665		list, typ := p.parseVarList(ellipsisOk)
   666		if typ != nil {
   667			// IdentifierList Type
   668			idents := p.makeIdentList(list)
   669			field := &ast.Field{nil, idents, typ, nil, nil}
   670			params = append(params, field)
   671			// Go spec: The scope of an identifier denoting a function
   672			// parameter or result variable is the function body.
   673			p.declare(field, nil, scope, ast.Var, idents...)
   674			if p.tok == token.COMMA {
   675				p.next()
   676			}
   677	
   678			for p.tok != token.RPAREN && p.tok != token.EOF {
   679				idents := p.parseIdentList()
   680				typ := p.parseVarType(ellipsisOk)
   681				field := &ast.Field{nil, idents, typ, nil, nil}
   682				params = append(params, field)
   683				// Go spec: The scope of an identifier denoting a function
   684				// parameter or result variable is the function body.
   685				p.declare(field, nil, scope, ast.Var, idents...)
   686				if p.tok != token.COMMA {
   687					break
   688				}
   689				p.next()
   690			}
   691	
   692		} else {
   693			// Type { "," Type } (anonymous parameters)
   694			params = make([]*ast.Field, len(list))
   695			for i, x := range list {
   696				p.resolve(x)
   697				params[i] = &ast.Field{Type: x}
   698			}
   699		}
   700	
   701		return
   702	}
   703	
   704	func (p *parser) parseParameters(scope *ast.Scope, ellipsisOk bool) *ast.FieldList {
   705		if p.trace {
   706			defer un(trace(p, "Parameters"))
   707		}
   708	
   709		var params []*ast.Field
   710		lparen := p.expect(token.LPAREN)
   711		if p.tok != token.RPAREN {
   712			params = p.parseParameterList(scope, ellipsisOk)
   713		}
   714		rparen := p.expect(token.RPAREN)
   715	
   716		return &ast.FieldList{lparen, params, rparen}
   717	}
   718	
   719	func (p *parser) parseResult(scope *ast.Scope) *ast.FieldList {
   720		if p.trace {
   721			defer un(trace(p, "Result"))
   722		}
   723	
   724		if p.tok == token.LPAREN {
   725			return p.parseParameters(scope, false)
   726		}
   727	
   728		typ := p.tryType()
   729		if typ != nil {
   730			list := make([]*ast.Field, 1)
   731			list[0] = &ast.Field{Type: typ}
   732			return &ast.FieldList{List: list}
   733		}
   734	
   735		return nil
   736	}
   737	
   738	func (p *parser) parseSignature(scope *ast.Scope) (params, results *ast.FieldList) {
   739		if p.trace {
   740			defer un(trace(p, "Signature"))
   741		}
   742	
   743		params = p.parseParameters(scope, true)
   744		results = p.parseResult(scope)
   745	
   746		return
   747	}
   748	
   749	func (p *parser) parseFuncType() (*ast.FuncType, *ast.Scope) {
   750		if p.trace {
   751			defer un(trace(p, "FuncType"))
   752		}
   753	
   754		pos := p.expect(token.FUNC)
   755		scope := ast.NewScope(p.topScope) // function scope
   756		params, results := p.parseSignature(scope)
   757	
   758		return &ast.FuncType{pos, params, results}, scope
   759	}
   760	
   761	func (p *parser) parseMethodSpec(scope *ast.Scope) *ast.Field {
   762		if p.trace {
   763			defer un(trace(p, "MethodSpec"))
   764		}
   765	
   766		doc := p.leadComment
   767		var idents []*ast.Ident
   768		var typ ast.Expr
   769		x := p.parseTypeName()
   770		if ident, isIdent := x.(*ast.Ident); isIdent && p.tok == token.LPAREN {
   771			// method
   772			idents = []*ast.Ident{ident}
   773			scope := ast.NewScope(nil) // method scope
   774			params, results := p.parseSignature(scope)
   775			typ = &ast.FuncType{token.NoPos, params, results}
   776		} else {
   777			// embedded interface
   778			typ = x
   779			p.resolve(typ)
   780		}
   781		p.expectSemi() // call before accessing p.linecomment
   782	
   783		spec := &ast.Field{doc, idents, typ, nil, p.lineComment}
   784		p.declare(spec, nil, scope, ast.Fun, idents...)
   785	
   786		return spec
   787	}
   788	
   789	func (p *parser) parseInterfaceType() *ast.InterfaceType {
   790		if p.trace {
   791			defer un(trace(p, "InterfaceType"))
   792		}
   793	
   794		pos := p.expect(token.INTERFACE)
   795		lbrace := p.expect(token.LBRACE)
   796		scope := ast.NewScope(nil) // interface scope
   797		var list []*ast.Field
   798		for p.tok == token.IDENT {
   799			list = append(list, p.parseMethodSpec(scope))
   800		}
   801		rbrace := p.expect(token.RBRACE)
   802	
   803		// TODO(gri): store interface scope in AST
   804		return &ast.InterfaceType{pos, &ast.FieldList{lbrace, list, rbrace}, false}
   805	}
   806	
   807	func (p *parser) parseMapType() *ast.MapType {
   808		if p.trace {
   809			defer un(trace(p, "MapType"))
   810		}
   811	
   812		pos := p.expect(token.MAP)
   813		p.expect(token.LBRACK)
   814		key := p.parseType()
   815		p.expect(token.RBRACK)
   816		value := p.parseType()
   817	
   818		return &ast.MapType{pos, key, value}
   819	}
   820	
   821	func (p *parser) parseChanType() *ast.ChanType {
   822		if p.trace {
   823			defer un(trace(p, "ChanType"))
   824		}
   825	
   826		pos := p.pos
   827		dir := ast.SEND | ast.RECV
   828		if p.tok == token.CHAN {
   829			p.next()
   830			if p.tok == token.ARROW {
   831				p.next()
   832				dir = ast.SEND
   833			}
   834		} else {
   835			p.expect(token.ARROW)
   836			p.expect(token.CHAN)
   837			dir = ast.RECV
   838		}
   839		value := p.parseType()
   840	
   841		return &ast.ChanType{pos, dir, value}
   842	}
   843	
   844	// If the result is an identifier, it is not resolved.
   845	func (p *parser) tryIdentOrType(ellipsisOk bool) ast.Expr {
   846		switch p.tok {
   847		case token.IDENT:
   848			return p.parseTypeName()
   849		case token.LBRACK:
   850			return p.parseArrayType(ellipsisOk)
   851		case token.STRUCT:
   852			return p.parseStructType()
   853		case token.MUL:
   854			return p.parsePointerType()
   855		case token.FUNC:
   856			typ, _ := p.parseFuncType()
   857			return typ
   858		case token.INTERFACE:
   859			return p.parseInterfaceType()
   860		case token.MAP:
   861			return p.parseMapType()
   862		case token.CHAN, token.ARROW:
   863			return p.parseChanType()
   864		case token.LPAREN:
   865			lparen := p.pos
   866			p.next()
   867			typ := p.parseType()
   868			rparen := p.expect(token.RPAREN)
   869			return &ast.ParenExpr{lparen, typ, rparen}
   870		}
   871	
   872		// no type found
   873		return nil
   874	}
   875	
   876	func (p *parser) tryType() ast.Expr {
   877		typ := p.tryIdentOrType(false)
   878		if typ != nil {
   879			p.resolve(typ)
   880		}
   881		return typ
   882	}
   883	
   884	// ----------------------------------------------------------------------------
   885	// Blocks
   886	
   887	func (p *parser) parseStmtList() (list []ast.Stmt) {
   888		if p.trace {
   889			defer un(trace(p, "StatementList"))
   890		}
   891	
   892		for p.tok != token.CASE && p.tok != token.DEFAULT && p.tok != token.RBRACE && p.tok != token.EOF {
   893			list = append(list, p.parseStmt())
   894		}
   895	
   896		return
   897	}
   898	
   899	func (p *parser) parseBody(scope *ast.Scope) *ast.BlockStmt {
   900		if p.trace {
   901			defer un(trace(p, "Body"))
   902		}
   903	
   904		lbrace := p.expect(token.LBRACE)
   905		p.topScope = scope // open function scope
   906		p.openLabelScope()
   907		list := p.parseStmtList()
   908		p.closeLabelScope()
   909		p.closeScope()
   910		rbrace := p.expect(token.RBRACE)
   911	
   912		return &ast.BlockStmt{lbrace, list, rbrace}
   913	}
   914	
   915	func (p *parser) parseBlockStmt() *ast.BlockStmt {
   916		if p.trace {
   917			defer un(trace(p, "BlockStmt"))
   918		}
   919	
   920		lbrace := p.expect(token.LBRACE)
   921		p.openScope()
   922		list := p.parseStmtList()
   923		p.closeScope()
   924		rbrace := p.expect(token.RBRACE)
   925	
   926		return &ast.BlockStmt{lbrace, list, rbrace}
   927	}
   928	
   929	// ----------------------------------------------------------------------------
   930	// Expressions
   931	
   932	func (p *parser) parseFuncTypeOrLit() ast.Expr {
   933		if p.trace {
   934			defer un(trace(p, "FuncTypeOrLit"))
   935		}
   936	
   937		typ, scope := p.parseFuncType()
   938		if p.tok != token.LBRACE {
   939			// function type only
   940			return typ
   941		}
   942	
   943		p.exprLev++
   944		body := p.parseBody(scope)
   945		p.exprLev--
   946	
   947		return &ast.FuncLit{typ, body}
   948	}
   949	
   950	// parseOperand may return an expression or a raw type (incl. array
   951	// types of the form [...]T. Callers must verify the result.
   952	// If lhs is set and the result is an identifier, it is not resolved.
   953	//
   954	func (p *parser) parseOperand(lhs bool) ast.Expr {
   955		if p.trace {
   956			defer un(trace(p, "Operand"))
   957		}
   958	
   959		switch p.tok {
   960		case token.IDENT:
   961			x := p.parseIdent()
   962			if !lhs {
   963				p.resolve(x)
   964			}
   965			return x
   966	
   967		case token.INT, token.FLOAT, token.IMAG, token.CHAR, token.STRING:
   968			x := &ast.BasicLit{p.pos, p.tok, p.lit}
   969			p.next()
   970			return x
   971	
   972		case token.LPAREN:
   973			lparen := p.pos
   974			p.next()
   975			p.exprLev++
   976			x := p.parseRhsOrType() // types may be parenthesized: (some type)
   977			p.exprLev--
   978			rparen := p.expect(token.RPAREN)
   979			return &ast.ParenExpr{lparen, x, rparen}
   980	
   981		case token.FUNC:
   982			return p.parseFuncTypeOrLit()
   983	
   984		default:
   985			if typ := p.tryIdentOrType(true); typ != nil {
   986				// could be type for composite literal or conversion
   987				_, isIdent := typ.(*ast.Ident)
   988				assert(!isIdent, "type cannot be identifier")
   989				return typ
   990			}
   991		}
   992	
   993		pos := p.pos
   994		p.errorExpected(pos, "operand")
   995		p.next() // make progress
   996		return &ast.BadExpr{pos, p.pos}
   997	}
   998	
   999	func (p *parser) parseSelector(x ast.Expr) ast.Expr {
  1000		if p.trace {
  1001			defer un(trace(p, "Selector"))
  1002		}
  1003	
  1004		sel := p.parseIdent()
  1005	
  1006		return &ast.SelectorExpr{x, sel}
  1007	}
  1008	
  1009	func (p *parser) parseTypeAssertion(x ast.Expr) ast.Expr {
  1010		if p.trace {
  1011			defer un(trace(p, "TypeAssertion"))
  1012		}
  1013	
  1014		p.expect(token.LPAREN)
  1015		var typ ast.Expr
  1016		if p.tok == token.TYPE {
  1017			// type switch: typ == nil
  1018			p.next()
  1019		} else {
  1020			typ = p.parseType()
  1021		}
  1022		p.expect(token.RPAREN)
  1023	
  1024		return &ast.TypeAssertExpr{x, typ}
  1025	}
  1026	
  1027	func (p *parser) parseIndexOrSlice(x ast.Expr) ast.Expr {
  1028		if p.trace {
  1029			defer un(trace(p, "IndexOrSlice"))
  1030		}
  1031	
  1032		lbrack := p.expect(token.LBRACK)
  1033		p.exprLev++
  1034		var low, high ast.Expr
  1035		isSlice := false
  1036		if p.tok != token.COLON {
  1037			low = p.parseRhs()
  1038		}
  1039		if p.tok == token.COLON {
  1040			isSlice = true
  1041			p.next()
  1042			if p.tok != token.RBRACK {
  1043				high = p.parseRhs()
  1044			}
  1045		}
  1046		p.exprLev--
  1047		rbrack := p.expect(token.RBRACK)
  1048	
  1049		if isSlice {
  1050			return &ast.SliceExpr{x, lbrack, low, high, rbrack}
  1051		}
  1052		return &ast.IndexExpr{x, lbrack, low, rbrack}
  1053	}
  1054	
  1055	func (p *parser) parseCallOrConversion(fun ast.Expr) *ast.CallExpr {
  1056		if p.trace {
  1057			defer un(trace(p, "CallOrConversion"))
  1058		}
  1059	
  1060		lparen := p.expect(token.LPAREN)
  1061		p.exprLev++
  1062		var list []ast.Expr
  1063		var ellipsis token.Pos
  1064		for p.tok != token.RPAREN && p.tok != token.EOF && !ellipsis.IsValid() {
  1065			list = append(list, p.parseRhsOrType()) // builtins may expect a type: make(some type, ...)
  1066			if p.tok == token.ELLIPSIS {
  1067				ellipsis = p.pos
  1068				p.next()
  1069			}
  1070			if p.tok != token.COMMA {
  1071				break
  1072			}
  1073			p.next()
  1074		}
  1075		p.exprLev--
  1076		rparen := p.expect(token.RPAREN)
  1077	
  1078		return &ast.CallExpr{fun, lparen, list, ellipsis, rparen}
  1079	}
  1080	
  1081	func (p *parser) parseElement(keyOk bool) ast.Expr {
  1082		if p.trace {
  1083			defer un(trace(p, "Element"))
  1084		}
  1085	
  1086		if p.tok == token.LBRACE {
  1087			return p.parseLiteralValue(nil)
  1088		}
  1089	
  1090		x := p.checkExpr(p.parseExpr(keyOk)) // don't resolve if map key
  1091		if keyOk {
  1092			if p.tok == token.COLON {
  1093				colon := p.pos
  1094				p.next()
  1095				return &ast.KeyValueExpr{x, colon, p.parseElement(false)}
  1096			}
  1097			p.resolve(x) // not a map key
  1098		}
  1099	
  1100		return x
  1101	}
  1102	
  1103	func (p *parser) parseElementList() (list []ast.Expr) {
  1104		if p.trace {
  1105			defer un(trace(p, "ElementList"))
  1106		}
  1107	
  1108		for p.tok != token.RBRACE && p.tok != token.EOF {
  1109			list = append(list, p.parseElement(true))
  1110			if p.tok != token.COMMA {
  1111				break
  1112			}
  1113			p.next()
  1114		}
  1115	
  1116		return
  1117	}
  1118	
  1119	func (p *parser) parseLiteralValue(typ ast.Expr) ast.Expr {
  1120		if p.trace {
  1121			defer un(trace(p, "LiteralValue"))
  1122		}
  1123	
  1124		lbrace := p.expect(token.LBRACE)
  1125		var elts []ast.Expr
  1126		p.exprLev++
  1127		if p.tok != token.RBRACE {
  1128			elts = p.parseElementList()
  1129		}
  1130		p.exprLev--
  1131		rbrace := p.expect(token.RBRACE)
  1132		return &ast.CompositeLit{typ, lbrace, elts, rbrace}
  1133	}
  1134	
  1135	// checkExpr checks that x is an expression (and not a type).
  1136	func (p *parser) checkExpr(x ast.Expr) ast.Expr {
  1137		switch t := unparen(x).(type) {
  1138		case *ast.BadExpr:
  1139		case *ast.Ident:
  1140		case *ast.BasicLit:
  1141		case *ast.FuncLit:
  1142		case *ast.CompositeLit:
  1143		case *ast.ParenExpr:
  1144			panic("unreachable")
  1145		case *ast.SelectorExpr:
  1146		case *ast.IndexExpr:
  1147		case *ast.SliceExpr:
  1148		case *ast.TypeAssertExpr:
  1149			// If t.Type == nil we have a type assertion of the form
  1150			// y.(type), which is only allowed in type switch expressions.
  1151			// It's hard to exclude those but for the case where we are in
  1152			// a type switch. Instead be lenient and test this in the type
  1153			// checker.
  1154		case *ast.CallExpr:
  1155		case *ast.StarExpr:
  1156		case *ast.UnaryExpr:
  1157		case *ast.BinaryExpr:
  1158		default:
  1159			// all other nodes are not proper expressions
  1160			p.errorExpected(x.Pos(), "expression")
  1161			x = &ast.BadExpr{x.Pos(), x.End()}
  1162		}
  1163		return x
  1164	}
  1165	
  1166	// isTypeName returns true iff x is a (qualified) TypeName.
  1167	func isTypeName(x ast.Expr) bool {
  1168		switch t := x.(type) {
  1169		case *ast.BadExpr:
  1170		case *ast.Ident:
  1171		case *ast.SelectorExpr:
  1172			_, isIdent := t.X.(*ast.Ident)
  1173			return isIdent
  1174		default:
  1175			return false // all other nodes are not type names
  1176		}
  1177		return true
  1178	}
  1179	
  1180	// isLiteralType returns true iff x is a legal composite literal type.
  1181	func isLiteralType(x ast.Expr) bool {
  1182		switch t := x.(type) {
  1183		case *ast.BadExpr:
  1184		case *ast.Ident:
  1185		case *ast.SelectorExpr:
  1186			_, isIdent := t.X.(*ast.Ident)
  1187			return isIdent
  1188		case *ast.ArrayType:
  1189		case *ast.StructType:
  1190		case *ast.MapType:
  1191		default:
  1192			return false // all other nodes are not legal composite literal types
  1193		}
  1194		return true
  1195	}
  1196	
  1197	// If x is of the form *T, deref returns T, otherwise it returns x.
  1198	func deref(x ast.Expr) ast.Expr {
  1199		if p, isPtr := x.(*ast.StarExpr); isPtr {
  1200			x = p.X
  1201		}
  1202		return x
  1203	}
  1204	
  1205	// If x is of the form (T), unparen returns unparen(T), otherwise it returns x.
  1206	func unparen(x ast.Expr) ast.Expr {
  1207		if p, isParen := x.(*ast.ParenExpr); isParen {
  1208			x = unparen(p.X)
  1209		}
  1210		return x
  1211	}
  1212	
  1213	// checkExprOrType checks that x is an expression or a type
  1214	// (and not a raw type such as [...]T).
  1215	//
  1216	func (p *parser) checkExprOrType(x ast.Expr) ast.Expr {
  1217		switch t := unparen(x).(type) {
  1218		case *ast.ParenExpr:
  1219			panic("unreachable")
  1220		case *ast.UnaryExpr:
  1221		case *ast.ArrayType:
  1222			if len, isEllipsis := t.Len.(*ast.Ellipsis); isEllipsis {
  1223				p.error(len.Pos(), "expected array length, found '...'")
  1224				x = &ast.BadExpr{x.Pos(), x.End()}
  1225			}
  1226		}
  1227	
  1228		// all other nodes are expressions or types
  1229		return x
  1230	}
  1231	
  1232	// If lhs is set and the result is an identifier, it is not resolved.
  1233	func (p *parser) parsePrimaryExpr(lhs bool) ast.Expr {
  1234		if p.trace {
  1235			defer un(trace(p, "PrimaryExpr"))
  1236		}
  1237	
  1238		x := p.parseOperand(lhs)
  1239	L:
  1240		for {
  1241			switch p.tok {
  1242			case token.PERIOD:
  1243				p.next()
  1244				if lhs {
  1245					p.resolve(x)
  1246				}
  1247				switch p.tok {
  1248				case token.IDENT:
  1249					x = p.parseSelector(p.checkExpr(x))
  1250				case token.LPAREN:
  1251					x = p.parseTypeAssertion(p.checkExpr(x))
  1252				default:
  1253					pos := p.pos
  1254					p.next() // make progress
  1255					p.errorExpected(pos, "selector or type assertion")
  1256					x = &ast.BadExpr{pos, p.pos}
  1257				}
  1258			case token.LBRACK:
  1259				if lhs {
  1260					p.resolve(x)
  1261				}
  1262				x = p.parseIndexOrSlice(p.checkExpr(x))
  1263			case token.LPAREN:
  1264				if lhs {
  1265					p.resolve(x)
  1266				}
  1267				x = p.parseCallOrConversion(p.checkExprOrType(x))
  1268			case token.LBRACE:
  1269				if isLiteralType(x) && (p.exprLev >= 0 || !isTypeName(x)) {
  1270					if lhs {
  1271						p.resolve(x)
  1272					}
  1273					x = p.parseLiteralValue(x)
  1274				} else {
  1275					break L
  1276				}
  1277			default:
  1278				break L
  1279			}
  1280			lhs = false // no need to try to resolve again
  1281		}
  1282	
  1283		return x
  1284	}
  1285	
  1286	// If lhs is set and the result is an identifier, it is not resolved.
  1287	func (p *parser) parseUnaryExpr(lhs bool) ast.Expr {
  1288		if p.trace {
  1289			defer un(trace(p, "UnaryExpr"))
  1290		}
  1291	
  1292		switch p.tok {
  1293		case token.ADD, token.SUB, token.NOT, token.XOR, token.AND:
  1294			pos, op := p.pos, p.tok
  1295			p.next()
  1296			x := p.parseUnaryExpr(false)
  1297			return &ast.UnaryExpr{pos, op, p.checkExpr(x)}
  1298	
  1299		case token.ARROW:
  1300			// channel type or receive expression
  1301			pos := p.pos
  1302			p.next()
  1303			if p.tok == token.CHAN {
  1304				p.next()
  1305				value := p.parseType()
  1306				return &ast.ChanType{pos, ast.RECV, value}
  1307			}
  1308	
  1309			x := p.parseUnaryExpr(false)
  1310			return &ast.UnaryExpr{pos, token.ARROW, p.checkExpr(x)}
  1311	
  1312		case token.MUL:
  1313			// pointer type or unary "*" expression
  1314			pos := p.pos
  1315			p.next()
  1316			x := p.parseUnaryExpr(false)
  1317			return &ast.StarExpr{pos, p.checkExprOrType(x)}
  1318		}
  1319	
  1320		return p.parsePrimaryExpr(lhs)
  1321	}
  1322	
  1323	// If lhs is set and the result is an identifier, it is not resolved.
  1324	func (p *parser) parseBinaryExpr(lhs bool, prec1 int) ast.Expr {
  1325		if p.trace {
  1326			defer un(trace(p, "BinaryExpr"))
  1327		}
  1328	
  1329		x := p.parseUnaryExpr(lhs)
  1330		for prec := p.tok.Precedence(); prec >= prec1; prec-- {
  1331			for p.tok.Precedence() == prec {
  1332				pos, op := p.pos, p.tok
  1333				p.next()
  1334				if lhs {
  1335					p.resolve(x)
  1336					lhs = false
  1337				}
  1338				y := p.parseBinaryExpr(false, prec+1)
  1339				x = &ast.BinaryExpr{p.checkExpr(x), pos, op, p.checkExpr(y)}
  1340			}
  1341		}
  1342	
  1343		return x
  1344	}
  1345	
  1346	// If lhs is set and the result is an identifier, it is not resolved.
  1347	// The result may be a type or even a raw type ([...]int). Callers must
  1348	// check the result (using checkExpr or checkExprOrType), depending on
  1349	// context.
  1350	func (p *parser) parseExpr(lhs bool) ast.Expr {
  1351		if p.trace {
  1352			defer un(trace(p, "Expression"))
  1353		}
  1354	
  1355		return p.parseBinaryExpr(lhs, token.LowestPrec+1)
  1356	}
  1357	
  1358	func (p *parser) parseRhs() ast.Expr {
  1359		return p.checkExpr(p.parseExpr(false))
  1360	}
  1361	
  1362	func (p *parser) parseRhsOrType() ast.Expr {
  1363		return p.checkExprOrType(p.parseExpr(false))
  1364	}
  1365	
  1366	// ----------------------------------------------------------------------------
  1367	// Statements
  1368	
  1369	// Parsing modes for parseSimpleStmt.
  1370	const (
  1371		basic = iota
  1372		labelOk
  1373		rangeOk
  1374	)
  1375	
  1376	// parseSimpleStmt returns true as 2nd result if it parsed the assignment
  1377	// of a range clause (with mode == rangeOk). The returned statement is an
  1378	// assignment with a right-hand side that is a single unary expression of
  1379	// the form "range x". No guarantees are given for the left-hand side.
  1380	func (p *parser) parseSimpleStmt(mode int) (ast.Stmt, bool) {
  1381		if p.trace {
  1382			defer un(trace(p, "SimpleStmt"))
  1383		}
  1384	
  1385		x := p.parseLhsList()
  1386	
  1387		switch p.tok {
  1388		case
  1389			token.DEFINE, token.ASSIGN, token.ADD_ASSIGN,
  1390			token.SUB_ASSIGN, token.MUL_ASSIGN, token.QUO_ASSIGN,
  1391			token.REM_ASSIGN, token.AND_ASSIGN, token.OR_ASSIGN,
  1392			token.XOR_ASSIGN, token.SHL_ASSIGN, token.SHR_ASSIGN, token.AND_NOT_ASSIGN:
  1393			// assignment statement, possibly part of a range clause
  1394			pos, tok := p.pos, p.tok
  1395			p.next()
  1396			var y []ast.Expr
  1397			isRange := false
  1398			if mode == rangeOk && p.tok == token.RANGE && (tok == token.DEFINE || tok == token.ASSIGN) {
  1399				pos := p.pos
  1400				p.next()
  1401				y = []ast.Expr{&ast.UnaryExpr{pos, token.RANGE, p.parseRhs()}}
  1402				isRange = true
  1403			} else {
  1404				y = p.parseRhsList()
  1405			}
  1406			return &ast.AssignStmt{x, pos, tok, y}, isRange
  1407		}
  1408	
  1409		if len(x) > 1 {
  1410			p.errorExpected(x[0].Pos(), "1 expression")
  1411			// continue with first expression
  1412		}
  1413	
  1414		switch p.tok {
  1415		case token.COLON:
  1416			// labeled statement
  1417			colon := p.pos
  1418			p.next()
  1419			if label, isIdent := x[0].(*ast.Ident); mode == labelOk && isIdent {
  1420				// Go spec: The scope of a label is the body of the function
  1421				// in which it is declared and excludes the body of any nested
  1422				// function.
  1423				stmt := &ast.LabeledStmt{label, colon, p.parseStmt()}
  1424				p.declare(stmt, nil, p.labelScope, ast.Lbl, label)
  1425				return stmt, false
  1426			}
  1427			// The label declaration typically starts at x[0].Pos(), but the label
  1428			// declaration may be erroneous due to a token after that position (and
  1429			// before the ':'). If SpuriousErrors is not set, the (only) error re-
  1430			// ported for the line is the illegal label error instead of the token
  1431			// before the ':' that caused the problem. Thus, use the (latest) colon
  1432			// position for error reporting.
  1433			p.error(colon, "illegal label declaration")
  1434			return &ast.BadStmt{x[0].Pos(), colon + 1}, false
  1435	
  1436		case token.ARROW:
  1437			// send statement
  1438			arrow := p.pos
  1439			p.next() // consume "<-"
  1440			y := p.parseRhs()
  1441			return &ast.SendStmt{x[0], arrow, y}, false
  1442	
  1443		case token.INC, token.DEC:
  1444			// increment or decrement
  1445			s := &ast.IncDecStmt{x[0], p.pos, p.tok}
  1446			p.next() // consume "++" or "--"
  1447			return s, false
  1448		}
  1449	
  1450		// expression
  1451		return &ast.ExprStmt{x[0]}, false
  1452	}
  1453	
  1454	func (p *parser) parseCallExpr() *ast.CallExpr {
  1455		x := p.parseRhsOrType() // could be a conversion: (some type)(x)
  1456		if call, isCall := x.(*ast.CallExpr); isCall {
  1457			return call
  1458		}
  1459		p.errorExpected(x.Pos(), "function/method call")
  1460		return nil
  1461	}
  1462	
  1463	func (p *parser) parseGoStmt() ast.Stmt {
  1464		if p.trace {
  1465			defer un(trace(p, "GoStmt"))
  1466		}
  1467	
  1468		pos := p.expect(token.GO)
  1469		call := p.parseCallExpr()
  1470		p.expectSemi()
  1471		if call == nil {
  1472			return &ast.BadStmt{pos, pos + 2} // len("go")
  1473		}
  1474	
  1475		return &ast.GoStmt{pos, call}
  1476	}
  1477	
  1478	func (p *parser) parseDeferStmt() ast.Stmt {
  1479		if p.trace {
  1480			defer un(trace(p, "DeferStmt"))
  1481		}
  1482	
  1483		pos := p.expect(token.DEFER)
  1484		call := p.parseCallExpr()
  1485		p.expectSemi()
  1486		if call == nil {
  1487			return &ast.BadStmt{pos, pos + 5} // len("defer")
  1488		}
  1489	
  1490		return &ast.DeferStmt{pos, call}
  1491	}
  1492	
  1493	func (p *parser) parseReturnStmt() *ast.ReturnStmt {
  1494		if p.trace {
  1495			defer un(trace(p, "ReturnStmt"))
  1496		}
  1497	
  1498		pos := p.pos
  1499		p.expect(token.RETURN)
  1500		var x []ast.Expr
  1501		if p.tok != token.SEMICOLON && p.tok != token.RBRACE {
  1502			x = p.parseRhsList()
  1503		}
  1504		p.expectSemi()
  1505	
  1506		return &ast.ReturnStmt{pos, x}
  1507	}
  1508	
  1509	func (p *parser) parseBranchStmt(tok token.Token) *ast.BranchStmt {
  1510		if p.trace {
  1511			defer un(trace(p, "BranchStmt"))
  1512		}
  1513	
  1514		pos := p.expect(tok)
  1515		var label *ast.Ident
  1516		if tok != token.FALLTHROUGH && p.tok == token.IDENT {
  1517			label = p.parseIdent()
  1518			// add to list of unresolved targets
  1519			n := len(p.targetStack) - 1
  1520			p.targetStack[n] = append(p.targetStack[n], label)
  1521		}
  1522		p.expectSemi()
  1523	
  1524		return &ast.BranchStmt{pos, tok, label}
  1525	}
  1526	
  1527	func (p *parser) makeExpr(s ast.Stmt) ast.Expr {
  1528		if s == nil {
  1529			return nil
  1530		}
  1531		if es, isExpr := s.(*ast.ExprStmt); isExpr {
  1532			return p.checkExpr(es.X)
  1533		}
  1534		p.error(s.Pos(), "expected condition, found simple statement")
  1535		return &ast.BadExpr{s.Pos(), s.End()}
  1536	}
  1537	
  1538	func (p *parser) parseIfStmt() *ast.IfStmt {
  1539		if p.trace {
  1540			defer un(trace(p, "IfStmt"))
  1541		}
  1542	
  1543		pos := p.expect(token.IF)
  1544		p.openScope()
  1545		defer p.closeScope()
  1546	
  1547		var s ast.Stmt
  1548		var x ast.Expr
  1549		{
  1550			prevLev := p.exprLev
  1551			p.exprLev = -1
  1552			if p.tok == token.SEMICOLON {
  1553				p.next()
  1554				x = p.parseRhs()
  1555			} else {
  1556				s, _ = p.parseSimpleStmt(basic)
  1557				if p.tok == token.SEMICOLON {
  1558					p.next()
  1559					x = p.parseRhs()
  1560				} else {
  1561					x = p.makeExpr(s)
  1562					s = nil
  1563				}
  1564			}
  1565			p.exprLev = prevLev
  1566		}
  1567	
  1568		body := p.parseBlockStmt()
  1569		var else_ ast.Stmt
  1570		if p.tok == token.ELSE {
  1571			p.next()
  1572			else_ = p.parseStmt()
  1573		} else {
  1574			p.expectSemi()
  1575		}
  1576	
  1577		return &ast.IfStmt{pos, s, x, body, else_}
  1578	}
  1579	
  1580	func (p *parser) parseTypeList() (list []ast.Expr) {
  1581		if p.trace {
  1582			defer un(trace(p, "TypeList"))
  1583		}
  1584	
  1585		list = append(list, p.parseType())
  1586		for p.tok == token.COMMA {
  1587			p.next()
  1588			list = append(list, p.parseType())
  1589		}
  1590	
  1591		return
  1592	}
  1593	
  1594	func (p *parser) parseCaseClause(exprSwitch bool) *ast.CaseClause {
  1595		if p.trace {
  1596			defer un(trace(p, "CaseClause"))
  1597		}
  1598	
  1599		pos := p.pos
  1600		var list []ast.Expr
  1601		if p.tok == token.CASE {
  1602			p.next()
  1603			if exprSwitch {
  1604				list = p.parseRhsList()
  1605			} else {
  1606				list = p.parseTypeList()
  1607			}
  1608		} else {
  1609			p.expect(token.DEFAULT)
  1610		}
  1611	
  1612		colon := p.expect(token.COLON)
  1613		p.openScope()
  1614		body := p.parseStmtList()
  1615		p.closeScope()
  1616	
  1617		return &ast.CaseClause{pos, list, colon, body}
  1618	}
  1619	
  1620	func isExprSwitch(s ast.Stmt) bool {
  1621		if s == nil {
  1622			return true
  1623		}
  1624		if e, ok := s.(*ast.ExprStmt); ok {
  1625			if a, ok := e.X.(*ast.TypeAssertExpr); ok {
  1626				return a.Type != nil // regular type assertion
  1627			}
  1628			return true
  1629		}
  1630		return false
  1631	}
  1632	
  1633	func (p *parser) parseSwitchStmt() ast.Stmt {
  1634		if p.trace {
  1635			defer un(trace(p, "SwitchStmt"))
  1636		}
  1637	
  1638		pos := p.expect(token.SWITCH)
  1639		p.openScope()
  1640		defer p.closeScope()
  1641	
  1642		var s1, s2 ast.Stmt
  1643		if p.tok != token.LBRACE {
  1644			prevLev := p.exprLev
  1645			p.exprLev = -1
  1646			if p.tok != token.SEMICOLON {
  1647				s2, _ = p.parseSimpleStmt(basic)
  1648			}
  1649			if p.tok == token.SEMICOLON {
  1650				p.next()
  1651				s1 = s2
  1652				s2 = nil
  1653				if p.tok != token.LBRACE {
  1654					s2, _ = p.parseSimpleStmt(basic)
  1655				}
  1656			}
  1657			p.exprLev = prevLev
  1658		}
  1659	
  1660		exprSwitch := isExprSwitch(s2)
  1661		lbrace := p.expect(token.LBRACE)
  1662		var list []ast.Stmt
  1663		for p.tok == token.CASE || p.tok == token.DEFAULT {
  1664			list = append(list, p.parseCaseClause(exprSwitch))
  1665		}
  1666		rbrace := p.expect(token.RBRACE)
  1667		p.expectSemi()
  1668		body := &ast.BlockStmt{lbrace, list, rbrace}
  1669	
  1670		if exprSwitch {
  1671			return &ast.SwitchStmt{pos, s1, p.makeExpr(s2), body}
  1672		}
  1673		// type switch
  1674		// TODO(gri): do all the checks!
  1675		return &ast.TypeSwitchStmt{pos, s1, s2, body}
  1676	}
  1677	
  1678	func (p *parser) parseCommClause() *ast.CommClause {
  1679		if p.trace {
  1680			defer un(trace(p, "CommClause"))
  1681		}
  1682	
  1683		p.openScope()
  1684		pos := p.pos
  1685		var comm ast.Stmt
  1686		if p.tok == token.CASE {
  1687			p.next()
  1688			lhs := p.parseLhsList()
  1689			if p.tok == token.ARROW {
  1690				// SendStmt
  1691				if len(lhs) > 1 {
  1692					p.errorExpected(lhs[0].Pos(), "1 expression")
  1693					// continue with first expression
  1694				}
  1695				arrow := p.pos
  1696				p.next()
  1697				rhs := p.parseRhs()
  1698				comm = &ast.SendStmt{lhs[0], arrow, rhs}
  1699			} else {
  1700				// RecvStmt
  1701				pos := p.pos
  1702				tok := p.tok
  1703				var rhs ast.Expr
  1704				if tok == token.ASSIGN || tok == token.DEFINE {
  1705					// RecvStmt with assignment
  1706					if len(lhs) > 2 {
  1707						p.errorExpected(lhs[0].Pos(), "1 or 2 expressions")
  1708						// continue with first two expressions
  1709						lhs = lhs[0:2]
  1710					}
  1711					p.next()
  1712					rhs = p.parseRhs()
  1713				} else {
  1714					// rhs must be single receive operation
  1715					if len(lhs) > 1 {
  1716						p.errorExpected(lhs[0].Pos(), "1 expression")
  1717						// continue with first expression
  1718					}
  1719					rhs = lhs[0]
  1720					lhs = nil // there is no lhs
  1721				}
  1722				if lhs != nil {
  1723					comm = &ast.AssignStmt{lhs, pos, tok, []ast.Expr{rhs}}
  1724				} else {
  1725					comm = &ast.ExprStmt{rhs}
  1726				}
  1727			}
  1728		} else {
  1729			p.expect(token.DEFAULT)
  1730		}
  1731	
  1732		colon := p.expect(token.COLON)
  1733		body := p.parseStmtList()
  1734		p.closeScope()
  1735	
  1736		return &ast.CommClause{pos, comm, colon, body}
  1737	}
  1738	
  1739	func (p *parser) parseSelectStmt() *ast.SelectStmt {
  1740		if p.trace {
  1741			defer un(trace(p, "SelectStmt"))
  1742		}
  1743	
  1744		pos := p.expect(token.SELECT)
  1745		lbrace := p.expect(token.LBRACE)
  1746		var list []ast.Stmt
  1747		for p.tok == token.CASE || p.tok == token.DEFAULT {
  1748			list = append(list, p.parseCommClause())
  1749		}
  1750		rbrace := p.expect(token.RBRACE)
  1751		p.expectSemi()
  1752		body := &ast.BlockStmt{lbrace, list, rbrace}
  1753	
  1754		return &ast.SelectStmt{pos, body}
  1755	}
  1756	
  1757	func (p *parser) parseForStmt() ast.Stmt {
  1758		if p.trace {
  1759			defer un(trace(p, "ForStmt"))
  1760		}
  1761	
  1762		pos := p.expect(token.FOR)
  1763		p.openScope()
  1764		defer p.closeScope()
  1765	
  1766		var s1, s2, s3 ast.Stmt
  1767		var isRange bool
  1768		if p.tok != token.LBRACE {
  1769			prevLev := p.exprLev
  1770			p.exprLev = -1
  1771			if p.tok != token.SEMICOLON {
  1772				s2, isRange = p.parseSimpleStmt(rangeOk)
  1773			}
  1774			if !isRange && p.tok == token.SEMICOLON {
  1775				p.next()
  1776				s1 = s2
  1777				s2 = nil
  1778				if p.tok != token.SEMICOLON {
  1779					s2, _ = p.parseSimpleStmt(basic)
  1780				}
  1781				p.expectSemi()
  1782				if p.tok != token.LBRACE {
  1783					s3, _ = p.parseSimpleStmt(basic)
  1784				}
  1785			}
  1786			p.exprLev = prevLev
  1787		}
  1788	
  1789		body := p.parseBlockStmt()
  1790		p.expectSemi()
  1791	
  1792		if isRange {
  1793			as := s2.(*ast.AssignStmt)
  1794			// check lhs
  1795			var key, value ast.Expr
  1796			switch len(as.Lhs) {
  1797			case 2:
  1798				key, value = as.Lhs[0], as.Lhs[1]
  1799			case 1:
  1800				key = as.Lhs[0]
  1801			default:
  1802				p.errorExpected(as.Lhs[0].Pos(), "1 or 2 expressions")
  1803				return &ast.BadStmt{pos, body.End()}
  1804			}
  1805			// parseSimpleStmt returned a right-hand side that
  1806			// is a single unary expression of the form "range x"
  1807			x := as.Rhs[0].(*ast.UnaryExpr).X
  1808			return &ast.RangeStmt{pos, key, value, as.TokPos, as.Tok, x, body}
  1809		}
  1810	
  1811		// regular for statement
  1812		return &ast.ForStmt{pos, s1, p.makeExpr(s2), s3, body}
  1813	}
  1814	
  1815	func (p *parser) parseStmt() (s ast.Stmt) {
  1816		if p.trace {
  1817			defer un(trace(p, "Statement"))
  1818		}
  1819	
  1820		switch p.tok {
  1821		case token.CONST, token.TYPE, token.VAR:
  1822			s = &ast.DeclStmt{p.parseDecl()}
  1823		case
  1824			// tokens that may start a top-level expression
  1825			token.IDENT, token.INT, token.FLOAT, token.CHAR, token.STRING, token.FUNC, token.LPAREN, // operand
  1826			token.LBRACK, token.STRUCT, // composite type
  1827			token.MUL, token.AND, token.ARROW, token.ADD, token.SUB, token.XOR: // unary operators
  1828			s, _ = p.parseSimpleStmt(labelOk)
  1829			// because of the required look-ahead, labeled statements are
  1830			// parsed by parseSimpleStmt - don't expect a semicolon after
  1831			// them
  1832			if _, isLabeledStmt := s.(*ast.LabeledStmt); !isLabeledStmt {
  1833				p.expectSemi()
  1834			}
  1835		case token.GO:
  1836			s = p.parseGoStmt()
  1837		case token.DEFER:
  1838			s = p.parseDeferStmt()
  1839		case token.RETURN:
  1840			s = p.parseReturnStmt()
  1841		case token.BREAK, token.CONTINUE, token.GOTO, token.FALLTHROUGH:
  1842			s = p.parseBranchStmt(p.tok)
  1843		case token.LBRACE:
  1844			s = p.parseBlockStmt()
  1845			p.expectSemi()
  1846		case token.IF:
  1847			s = p.parseIfStmt()
  1848		case token.SWITCH:
  1849			s = p.parseSwitchStmt()
  1850		case token.SELECT:
  1851			s = p.parseSelectStmt()
  1852		case token.FOR:
  1853			s = p.parseForStmt()
  1854		case token.SEMICOLON:
  1855			s = &ast.EmptyStmt{p.pos}
  1856			p.next()
  1857		case token.RBRACE:
  1858			// a semicolon may be omitted before a closing "}"
  1859			s = &ast.EmptyStmt{p.pos}
  1860		default:
  1861			// no statement found
  1862			pos := p.pos
  1863			p.errorExpected(pos, "statement")
  1864			p.next() // make progress
  1865			s = &ast.BadStmt{pos, p.pos}
  1866		}
  1867	
  1868		return
  1869	}
  1870	
  1871	// ----------------------------------------------------------------------------
  1872	// Declarations
  1873	
  1874	type parseSpecFunction func(p *parser, doc *ast.CommentGroup, iota int) ast.Spec
  1875	
  1876	func parseImportSpec(p *parser, doc *ast.CommentGroup, _ int) ast.Spec {
  1877		if p.trace {
  1878			defer un(trace(p, "ImportSpec"))
  1879		}
  1880	
  1881		var ident *ast.Ident
  1882		switch p.tok {
  1883		case token.PERIOD:
  1884			ident = &ast.Ident{p.pos, ".", nil}
  1885			p.next()
  1886		case token.IDENT:
  1887			ident = p.parseIdent()
  1888		}
  1889	
  1890		var path *ast.BasicLit
  1891		if p.tok == token.STRING {
  1892			path = &ast.BasicLit{p.pos, p.tok, p.lit}
  1893			p.next()
  1894		} else {
  1895			p.expect(token.STRING) // use expect() error handling
  1896		}
  1897		p.expectSemi() // call before accessing p.linecomment
  1898	
  1899		// collect imports
  1900		spec := &ast.ImportSpec{doc, ident, path, p.lineComment}
  1901		p.imports = append(p.imports, spec)
  1902	
  1903		return spec
  1904	}
  1905	
  1906	func parseConstSpec(p *parser, doc *ast.CommentGroup, iota int) ast.Spec {
  1907		if p.trace {
  1908			defer un(trace(p, "ConstSpec"))
  1909		}
  1910	
  1911		idents := p.parseIdentList()
  1912		typ := p.tryType()
  1913		var values []ast.Expr
  1914		if typ != nil || p.tok == token.ASSIGN || iota == 0 {
  1915			p.expect(token.ASSIGN)
  1916			values = p.parseRhsList()
  1917		}
  1918		p.expectSemi() // call before accessing p.linecomment
  1919	
  1920		// Go spec: The scope of a constant or variable identifier declared inside
  1921		// a function begins at the end of the ConstSpec or VarSpec and ends at
  1922		// the end of the innermost containing block.
  1923		// (Global identifiers are resolved in a separate phase after parsing.)
  1924		spec := &ast.ValueSpec{doc, idents, typ, values, p.lineComment}
  1925		p.declare(spec, iota, p.topScope, ast.Con, idents...)
  1926	
  1927		return spec
  1928	}
  1929	
  1930	func parseTypeSpec(p *parser, doc *ast.CommentGroup, _ int) ast.Spec {
  1931		if p.trace {
  1932			defer un(trace(p, "TypeSpec"))
  1933		}
  1934	
  1935		ident := p.parseIdent()
  1936	
  1937		// Go spec: The scope of a type identifier declared inside a function begins
  1938		// at the identifier in the TypeSpec and ends at the end of the innermost
  1939		// containing block.
  1940		// (Global identifiers are resolved in a separate phase after parsing.)
  1941		spec := &ast.TypeSpec{doc, ident, nil, nil}
  1942		p.declare(spec, nil, p.topScope, ast.Typ, ident)
  1943	
  1944		spec.Type = p.parseType()
  1945		p.expectSemi() // call before accessing p.linecomment
  1946		spec.Comment = p.lineComment
  1947	
  1948		return spec
  1949	}
  1950	
  1951	func parseVarSpec(p *parser, doc *ast.CommentGroup, _ int) ast.Spec {
  1952		if p.trace {
  1953			defer un(trace(p, "VarSpec"))
  1954		}
  1955	
  1956		idents := p.parseIdentList()
  1957		typ := p.tryType()
  1958		var values []ast.Expr
  1959		if typ == nil || p.tok == token.ASSIGN {
  1960			p.expect(token.ASSIGN)
  1961			values = p.parseRhsList()
  1962		}
  1963		p.expectSemi() // call before accessing p.linecomment
  1964	
  1965		// Go spec: The scope of a constant or variable identifier declared inside
  1966		// a function begins at the end of the ConstSpec or VarSpec and ends at
  1967		// the end of the innermost containing block.
  1968		// (Global identifiers are resolved in a separate phase after parsing.)
  1969		spec := &ast.ValueSpec{doc, idents, typ, values, p.lineComment}
  1970		p.declare(spec, nil, p.topScope, ast.Var, idents...)
  1971	
  1972		return spec
  1973	}
  1974	
  1975	func (p *parser) parseGenDecl(keyword token.Token, f parseSpecFunction) *ast.GenDecl {
  1976		if p.trace {
  1977			defer un(trace(p, "GenDecl("+keyword.String()+")"))
  1978		}
  1979	
  1980		doc := p.leadComment
  1981		pos := p.expect(keyword)
  1982		var lparen, rparen token.Pos
  1983		var list []ast.Spec
  1984		if p.tok == token.LPAREN {
  1985			lparen = p.pos
  1986			p.next()
  1987			for iota := 0; p.tok != token.RPAREN && p.tok != token.EOF; iota++ {
  1988				list = append(list, f(p, p.leadComment, iota))
  1989			}
  1990			rparen = p.expect(token.RPAREN)
  1991			p.expectSemi()
  1992		} else {
  1993			list = append(list, f(p, nil, 0))
  1994		}
  1995	
  1996		return &ast.GenDecl{doc, pos, keyword, lparen, list, rparen}
  1997	}
  1998	
  1999	func (p *parser) parseReceiver(scope *ast.Scope) *ast.FieldList {
  2000		if p.trace {
  2001			defer un(trace(p, "Receiver"))
  2002		}
  2003	
  2004		pos := p.pos
  2005		par := p.parseParameters(scope, false)
  2006	
  2007		// must have exactly one receiver
  2008		if par.NumFields() != 1 {
  2009			p.errorExpected(pos, "exactly one receiver")
  2010			// TODO determine a better range for BadExpr below
  2011			par.List = []*ast.Field{&ast.Field{Type: &ast.BadExpr{pos, pos}}}
  2012			return par
  2013		}
  2014	
  2015		// recv type must be of the form ["*"] identifier
  2016		recv := par.List[0]
  2017		base := deref(recv.Type)
  2018		if _, isIdent := base.(*ast.Ident); !isIdent {
  2019			p.errorExpected(base.Pos(), "(unqualified) identifier")
  2020			par.List = []*ast.Field{&ast.Field{Type: &ast.BadExpr{recv.Pos(), recv.End()}}}
  2021		}
  2022	
  2023		return par
  2024	}
  2025	
  2026	func (p *parser) parseFuncDecl() *ast.FuncDecl {
  2027		if p.trace {
  2028			defer un(trace(p, "FunctionDecl"))
  2029		}
  2030	
  2031		doc := p.leadComment
  2032		pos := p.expect(token.FUNC)
  2033		scope := ast.NewScope(p.topScope) // function scope
  2034	
  2035		var recv *ast.FieldList
  2036		if p.tok == token.LPAREN {
  2037			recv = p.parseReceiver(scope)
  2038		}
  2039	
  2040		ident := p.parseIdent()
  2041	
  2042		params, results := p.parseSignature(scope)
  2043	
  2044		var body *ast.BlockStmt
  2045		if p.tok == token.LBRACE {
  2046			body = p.parseBody(scope)
  2047		}
  2048		p.expectSemi()
  2049	
  2050		decl := &ast.FuncDecl{doc, recv, ident, &ast.FuncType{pos, params, results}, body}
  2051		if recv == nil {
  2052			// Go spec: The scope of an identifier denoting a constant, type,
  2053			// variable, or function (but not method) declared at top level
  2054			// (outside any function) is the package block.
  2055			//
  2056			// init() functions cannot be referred to and there may
  2057			// be more than one - don't put them in the pkgScope
  2058			if ident.Name != "init" {
  2059				p.declare(decl, nil, p.pkgScope, ast.Fun, ident)
  2060			}
  2061		}
  2062	
  2063		return decl
  2064	}
  2065	
  2066	func (p *parser) parseDecl() ast.Decl {
  2067		if p.trace {
  2068			defer un(trace(p, "Declaration"))
  2069		}
  2070	
  2071		var f parseSpecFunction
  2072		switch p.tok {
  2073		case token.CONST:
  2074			f = parseConstSpec
  2075	
  2076		case token.TYPE:
  2077			f = parseTypeSpec
  2078	
  2079		case token.VAR:
  2080			f = parseVarSpec
  2081	
  2082		case token.FUNC:
  2083			return p.parseFuncDecl()
  2084	
  2085		default:
  2086			pos := p.pos
  2087			p.errorExpected(pos, "declaration")
  2088			p.next() // make progress
  2089			decl := &ast.BadDecl{pos, p.pos}
  2090			return decl
  2091		}
  2092	
  2093		return p.parseGenDecl(p.tok, f)
  2094	}
  2095	
  2096	func (p *parser) parseDeclList() (list []ast.Decl) {
  2097		if p.trace {
  2098			defer un(trace(p, "DeclList"))
  2099		}
  2100	
  2101		for p.tok != token.EOF {
  2102			list = append(list, p.parseDecl())
  2103		}
  2104	
  2105		return
  2106	}
  2107	
  2108	// ----------------------------------------------------------------------------
  2109	// Source files
  2110	
  2111	func (p *parser) parseFile() *ast.File {
  2112		if p.trace {
  2113			defer un(trace(p, "File"))
  2114		}
  2115	
  2116		// package clause
  2117		doc := p.leadComment
  2118		pos := p.expect(token.PACKAGE)
  2119		// Go spec: The package clause is not a declaration;
  2120		// the package name does not appear in any scope.
  2121		ident := p.parseIdent()
  2122		if ident.Name == "_" {
  2123			p.error(p.pos, "invalid package name _")
  2124		}
  2125		p.expectSemi()
  2126	
  2127		var decls []ast.Decl
  2128	
  2129		// Don't bother parsing the rest if we had errors already.
  2130		// Likely not a Go source file at all.
  2131	
  2132		if p.ErrorCount() == 0 && p.mode&PackageClauseOnly == 0 {
  2133			// import decls
  2134			for p.tok == token.IMPORT {
  2135				decls = append(decls, p.parseGenDecl(token.IMPORT, parseImportSpec))
  2136			}
  2137	
  2138			if p.mode&ImportsOnly == 0 {
  2139				// rest of package body
  2140				for p.tok != token.EOF {
  2141					decls = append(decls, p.parseDecl())
  2142				}
  2143			}
  2144		}
  2145	
  2146		assert(p.topScope == p.pkgScope, "imbalanced scopes")
  2147	
  2148		// resolve global identifiers within the same file
  2149		i := 0
  2150		for _, ident := range p.unresolved {
  2151			// i <= index for current ident
  2152			assert(ident.Obj == unresolved, "object already resolved")
  2153			ident.Obj = p.pkgScope.Lookup(ident.Name) // also removes unresolved sentinel
  2154			if ident.Obj == nil {
  2155				p.unresolved[i] = ident
  2156				i++
  2157			}
  2158		}
  2159	
  2160		return &ast.File{doc, pos, ident, decls, p.pkgScope, p.imports, p.unresolved[0:i], p.comments}
  2161	}

release.r60.3. Except as noted, this content is licensed under a Creative Commons Attribution 3.0 License.