Source file src/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/fs"
    16  	"os"
    17  	"path/filepath"
    18  	"strings"
    19  )
    20  
    21  // If src != nil, readSource converts src to a []byte if possible;
    22  // otherwise it returns an error. If src == nil, readSource returns
    23  // the result of reading the file specified by filename.
    24  //
    25  func readSource(filename string, src any) ([]byte, error) {
    26  	if src != nil {
    27  		switch s := src.(type) {
    28  		case string:
    29  			return []byte(s), nil
    30  		case []byte:
    31  			return s, nil
    32  		case *bytes.Buffer:
    33  			// is io.Reader, but src is already available in []byte form
    34  			if s != nil {
    35  				return s.Bytes(), nil
    36  			}
    37  		case io.Reader:
    38  			return io.ReadAll(s)
    39  		}
    40  		return nil, errors.New("invalid source")
    41  	}
    42  	return os.ReadFile(filename)
    43  }
    44  
    45  // A Mode value is a set of flags (or 0).
    46  // They control the amount of source code parsed and other optional
    47  // parser functionality.
    48  //
    49  type Mode uint
    50  
    51  const (
    52  	PackageClauseOnly    Mode             = 1 << iota // stop parsing after package clause
    53  	ImportsOnly                                       // stop parsing after import declarations
    54  	ParseComments                                     // parse comments and add them to AST
    55  	Trace                                             // print a trace of parsed productions
    56  	DeclarationErrors                                 // report declaration errors
    57  	SpuriousErrors                                    // same as AllErrors, for backward-compatibility
    58  	SkipObjectResolution                              // don't resolve identifiers to objects - see ParseFile
    59  	AllErrors            = SpuriousErrors             // report all errors (not just the first 10 on different lines)
    60  )
    61  
    62  // ParseFile parses the source code of a single Go source file and returns
    63  // the corresponding ast.File node. The source code may be provided via
    64  // the filename of the source file, or via the src parameter.
    65  //
    66  // If src != nil, ParseFile parses the source from src and the filename is
    67  // only used when recording position information. The type of the argument
    68  // for the src parameter must be string, []byte, or io.Reader.
    69  // If src == nil, ParseFile parses the file specified by filename.
    70  //
    71  // The mode parameter controls the amount of source text parsed and other
    72  // optional parser functionality. If the SkipObjectResolution mode bit is set,
    73  // the object resolution phase of parsing will be skipped, causing File.Scope,
    74  // File.Unresolved, and all Ident.Obj fields to be nil.
    75  //
    76  // Position information is recorded in the file set fset, which must not be
    77  // nil.
    78  //
    79  // If the source couldn't be read, the returned AST is nil and the error
    80  // indicates the specific failure. If the source was read but syntax
    81  // errors were found, the result is a partial AST (with ast.Bad* nodes
    82  // representing the fragments of erroneous source code). Multiple errors
    83  // are returned via a scanner.ErrorList which is sorted by source position.
    84  //
    85  func ParseFile(fset *token.FileSet, filename string, src any, mode Mode) (f *ast.File, err error) {
    86  	if fset == nil {
    87  		panic("parser.ParseFile: no token.FileSet provided (fset == nil)")
    88  	}
    89  
    90  	// get source
    91  	text, err := readSource(filename, src)
    92  	if err != nil {
    93  		return nil, err
    94  	}
    95  
    96  	var p parser
    97  	defer func() {
    98  		if e := recover(); e != nil {
    99  			// resume same panic if it's not a bailout
   100  			if _, ok := e.(bailout); !ok {
   101  				panic(e)
   102  			}
   103  		}
   104  
   105  		// set result values
   106  		if f == nil {
   107  			// source is not a valid Go source file - satisfy
   108  			// ParseFile API and return a valid (but) empty
   109  			// *ast.File
   110  			f = &ast.File{
   111  				Name:  new(ast.Ident),
   112  				Scope: ast.NewScope(nil),
   113  			}
   114  		}
   115  
   116  		p.errors.Sort()
   117  		err = p.errors.Err()
   118  	}()
   119  
   120  	// parse source
   121  	p.init(fset, filename, text, mode)
   122  	f = p.parseFile()
   123  
   124  	return
   125  }
   126  
   127  // ParseDir calls ParseFile for all files with names ending in ".go" in the
   128  // directory specified by path and returns a map of package name -> package
   129  // AST with all the packages found.
   130  //
   131  // If filter != nil, only the files with fs.FileInfo entries passing through
   132  // the filter (and ending in ".go") are considered. The mode bits are passed
   133  // to ParseFile unchanged. Position information is recorded in fset, which
   134  // must not be nil.
   135  //
   136  // If the directory couldn't be read, a nil map and the respective error are
   137  // returned. If a parse error occurred, a non-nil but incomplete map and the
   138  // first error encountered are returned.
   139  //
   140  func ParseDir(fset *token.FileSet, path string, filter func(fs.FileInfo) bool, mode Mode) (pkgs map[string]*ast.Package, first error) {
   141  	list, err := os.ReadDir(path)
   142  	if err != nil {
   143  		return nil, err
   144  	}
   145  
   146  	pkgs = make(map[string]*ast.Package)
   147  	for _, d := range list {
   148  		if d.IsDir() || !strings.HasSuffix(d.Name(), ".go") {
   149  			continue
   150  		}
   151  		if filter != nil {
   152  			info, err := d.Info()
   153  			if err != nil {
   154  				return nil, err
   155  			}
   156  			if !filter(info) {
   157  				continue
   158  			}
   159  		}
   160  		filename := filepath.Join(path, d.Name())
   161  		if src, err := ParseFile(fset, filename, nil, mode); err == nil {
   162  			name := src.Name.Name
   163  			pkg, found := pkgs[name]
   164  			if !found {
   165  				pkg = &ast.Package{
   166  					Name:  name,
   167  					Files: make(map[string]*ast.File),
   168  				}
   169  				pkgs[name] = pkg
   170  			}
   171  			pkg.Files[filename] = src
   172  		} else if first == nil {
   173  			first = err
   174  		}
   175  	}
   176  
   177  	return
   178  }
   179  
   180  // ParseExprFrom is a convenience function for parsing an expression.
   181  // The arguments have the same meaning as for ParseFile, but the source must
   182  // be a valid Go (type or value) expression. Specifically, fset must not
   183  // be nil.
   184  //
   185  // If the source couldn't be read, the returned AST is nil and the error
   186  // indicates the specific failure. If the source was read but syntax
   187  // errors were found, the result is a partial AST (with ast.Bad* nodes
   188  // representing the fragments of erroneous source code). Multiple errors
   189  // are returned via a scanner.ErrorList which is sorted by source position.
   190  //
   191  func ParseExprFrom(fset *token.FileSet, filename string, src any, mode Mode) (expr ast.Expr, err error) {
   192  	if fset == nil {
   193  		panic("parser.ParseExprFrom: no token.FileSet provided (fset == nil)")
   194  	}
   195  
   196  	// get source
   197  	text, err := readSource(filename, src)
   198  	if err != nil {
   199  		return nil, err
   200  	}
   201  
   202  	var p parser
   203  	defer func() {
   204  		if e := recover(); e != nil {
   205  			// resume same panic if it's not a bailout
   206  			if _, ok := e.(bailout); !ok {
   207  				panic(e)
   208  			}
   209  		}
   210  		p.errors.Sort()
   211  		err = p.errors.Err()
   212  	}()
   213  
   214  	// parse expr
   215  	p.init(fset, filename, text, mode)
   216  	expr = p.parseRhsOrType()
   217  
   218  	// If a semicolon was inserted, consume it;
   219  	// report an error if there's more tokens.
   220  	if p.tok == token.SEMICOLON && p.lit == "\n" {
   221  		p.next()
   222  	}
   223  	p.expect(token.EOF)
   224  
   225  	return
   226  }
   227  
   228  // ParseExpr is a convenience function for obtaining the AST of an expression x.
   229  // The position information recorded in the AST is undefined. The filename used
   230  // in error messages is the empty string.
   231  //
   232  // If syntax errors were found, the result is a partial AST (with ast.Bad* nodes
   233  // representing the fragments of erroneous source code). Multiple errors are
   234  // returned via a scanner.ErrorList which is sorted by source position.
   235  //
   236  func ParseExpr(x string) (ast.Expr, error) {
   237  	return ParseExprFrom(token.NewFileSet(), "", []byte(x), 0)
   238  }
   239  

View as plain text