Run Format

Source file src/pkg/go/parser/interface.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	// This file contains the exported entry points for invoking the parser.
     6	
     7	package parser
     8	
     9	import (
    10		"bytes"
    11		"errors"
    12		"go/ast"
    13		"go/token"
    14		"io"
    15		"io/ioutil"
    16		"os"
    17		"path/filepath"
    18	)
    19	
    20	// If src != nil, readSource converts src to a []byte if possible;
    21	// otherwise it returns an error. If src == nil, readSource returns
    22	// the result of reading the file specified by filename.
    23	//
    24	func readSource(filename string, src interface{}) ([]byte, error) {
    25		if src != nil {
    26			switch s := src.(type) {
    27			case string:
    28				return []byte(s), nil
    29			case []byte:
    30				return s, nil
    31			case *bytes.Buffer:
    32				// is io.Reader, but src is already available in []byte form
    33				if s != nil {
    34					return s.Bytes(), nil
    35				}
    36			case io.Reader:
    37				var buf bytes.Buffer
    38				if _, err := io.Copy(&buf, s); err != nil {
    39					return nil, err
    40				}
    41				return buf.Bytes(), nil
    42			}
    43			return nil, errors.New("invalid source")
    44		}
    45		return ioutil.ReadFile(filename)
    46	}
    47	
    48	// A Mode value is a set of flags (or 0).
    49	// They control the amount of source code parsed and other optional
    50	// parser functionality.
    51	//
    52	type Mode uint
    53	
    54	const (
    55		PackageClauseOnly Mode             = 1 << iota // stop parsing after package clause
    56		ImportsOnly                                    // stop parsing after import declarations
    57		ParseComments                                  // parse comments and add them to AST
    58		Trace                                          // print a trace of parsed productions
    59		DeclarationErrors                              // report declaration errors
    60		SpuriousErrors                                 // same as AllErrors, for backward-compatibility
    61		AllErrors         = SpuriousErrors             // report all errors (not just the first 10 on different lines)
    62	)
    63	
    64	// ParseFile parses the source code of a single Go source file and returns
    65	// the corresponding ast.File node. The source code may be provided via
    66	// the filename of the source file, or via the src parameter.
    67	//
    68	// If src != nil, ParseFile parses the source from src and the filename is
    69	// only used when recording position information. The type of the argument
    70	// for the src parameter must be string, []byte, or io.Reader.
    71	// If src == nil, ParseFile parses the file specified by filename.
    72	//
    73	// The mode parameter controls the amount of source text parsed and other
    74	// optional parser functionality. Position information is recorded in the
    75	// file set fset.
    76	//
    77	// If the source couldn't be read, the returned AST is nil and the error
    78	// indicates the specific failure. If the source was read but syntax
    79	// errors were found, the result is a partial AST (with ast.Bad* nodes
    80	// representing the fragments of erroneous source code). Multiple errors
    81	// are returned via a scanner.ErrorList which is sorted by file position.
    82	//
    83	func ParseFile(fset *token.FileSet, filename string, src interface{}, mode Mode) (f *ast.File, err error) {
    84		// get source
    85		text, err := readSource(filename, src)
    86		if err != nil {
    87			return nil, err
    88		}
    89	
    90		var p parser
    91		defer func() {
    92			if e := recover(); e != nil {
    93				_ = e.(bailout) // re-panics if it's not a bailout
    94			}
    95	
    96			// set result values
    97			if f == nil {
    98				// source is not a valid Go source file - satisfy
    99				// ParseFile API and return a valid (but) empty
   100				// *ast.File
   101				f = &ast.File{
   102					Name:  new(ast.Ident),
   103					Scope: ast.NewScope(nil),
   104				}
   105			}
   106	
   107			p.errors.Sort()
   108			err = p.errors.Err()
   109		}()
   110	
   111		// parse source
   112		p.init(fset, filename, text, mode)
   113		f = p.parseFile()
   114	
   115		return
   116	}
   117	
   118	// ParseDir calls ParseFile for the files in the directory specified by path and
   119	// returns a map of package name -> package AST with all the packages found. If
   120	// filter != nil, only the files with os.FileInfo entries passing through the filter
   121	// are considered. The mode bits are passed to ParseFile unchanged. Position
   122	// information is recorded in the file set fset.
   123	//
   124	// If the directory couldn't be read, a nil map and the respective error are
   125	// returned. If a parse error occurred, a non-nil but incomplete map and the
   126	// first error encountered are returned.
   127	//
   128	func ParseDir(fset *token.FileSet, path string, filter func(os.FileInfo) bool, mode Mode) (pkgs map[string]*ast.Package, first error) {
   129		fd, err := os.Open(path)
   130		if err != nil {
   131			return nil, err
   132		}
   133		defer fd.Close()
   134	
   135		list, err := fd.Readdir(-1)
   136		if err != nil {
   137			return nil, err
   138		}
   139	
   140		pkgs = make(map[string]*ast.Package)
   141		for _, d := range list {
   142			if filter == nil || filter(d) {
   143				filename := filepath.Join(path, d.Name())
   144				if src, err := ParseFile(fset, filename, nil, mode); err == nil {
   145					name := src.Name.Name
   146					pkg, found := pkgs[name]
   147					if !found {
   148						pkg = &ast.Package{
   149							Name:  name,
   150							Files: make(map[string]*ast.File),
   151						}
   152						pkgs[name] = pkg
   153					}
   154					pkg.Files[filename] = src
   155				} else if first == nil {
   156					first = err
   157				}
   158			}
   159		}
   160	
   161		return
   162	}
   163	
   164	// ParseExpr is a convenience function for obtaining the AST of an expression x.
   165	// The position information recorded in the AST is undefined. The filename used
   166	// in error messages is the empty string.
   167	//
   168	func ParseExpr(x string) (ast.Expr, error) {
   169		var p parser
   170		p.init(token.NewFileSet(), "", []byte(x), 0)
   171	
   172		// Set up pkg-level scopes to avoid nil-pointer errors.
   173		// This is not needed for a correct expression x as the
   174		// parser will be ok with a nil topScope, but be cautious
   175		// in case of an erroneous x.
   176		p.openScope()
   177		p.pkgScope = p.topScope
   178		e := p.parseRhsOrType()
   179		p.closeScope()
   180		assert(p.topScope == nil, "unbalanced scopes")
   181	
   182		if p.errors.Len() > 0 {
   183			p.errors.Sort()
   184			return nil, p.errors.Err()
   185		}
   186	
   187		return e, nil
   188	}

View as plain text