Golang go/parser.ParseFile() function examples

package go/parser

ParseFile parses the source code of a single Go source file and returns the corresponding ast.File node. The source code may be provided via the filename of the source file, or via the src parameter.

If src != nil, ParseFile parses the source from src and the filename is only used when recording position information. The type of the argument for the src parameter must be string, []byte, or io.Reader. If src == nil, ParseFile parses the file specified by filename.

The mode parameter controls the amount of source text parsed and other optional parser functionality. Position information is recorded in the file set fset.

If the source couldn't be read, the returned AST is nil and the error indicates the specific failure. If the source was read but syntax errors were found, the result is a partial AST (with ast.Bad* nodes representing the fragments of erroneous source code). Multiple errors are returned via a scanner.ErrorList which is sorted by file position.

Golang go/parser.ParseFile() function usage examples

Example 1:

 var path string
 fset := token.NewFileSet()
 pkg, err := parser.ParseFile(fset, path, nil, 0)
 if err != nil {
 fmt.Println(err)
 os.Exit(1) 
 }

Example 2: (from http://golang.org/pkg/go/parser/#ParseFile )

 package main

 import (
  "fmt"
  "go/parser"
  "go/token"
 )

 func main() {
  fset := token.NewFileSet() // positions are relative to fset

  // Parse the file containing this very example
  // but stop after processing the imports.
  f, err := parser.ParseFile(fset, "example_test.go", nil, parser.ImportsOnly)
  if err != nil {
 fmt.Println(err)
 return
  }

  // Print the imports from the file's AST.
  for _, s := range f.Imports {
 fmt.Println(s.Path.Value)
  }

 }

References :

http://golang.org/pkg/go/parser/#ParseFile

Advertisement