...

Source file src/go/parser/interface.go

Documentation: go/parser

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

View as plain text