// 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.
+// are returned via a scanner.ErrorList which is sorted by source position.
//
func ParseFile(fset *token.FileSet, filename string, src interface{}, mode Mode) (f *ast.File, err error) {
if fset == nil {
// be a valid Go (type or value) expression. Specifically, fset must not
// be nil.
//
+// 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 source position.
+//
func ParseExprFrom(fset *token.FileSet, filename string, src interface{}, mode Mode) (expr ast.Expr, err error) {
if fset == nil {
panic("parser.ParseExprFrom: no token.FileSet provided (fset == nil)")
// in case of an erroneous x.
p.openScope()
p.pkgScope = p.topScope
- e := p.parseRhsOrType()
+ expr = p.parseRhsOrType()
p.closeScope()
assert(p.topScope == nil, "unbalanced scopes")
}
p.expect(token.EOF)
- if p.errors.Len() > 0 {
- p.errors.Sort()
- return nil, p.errors.Err()
- }
-
- return e, nil
+ return
}
// ParseExpr is a convenience function for obtaining the AST of an expression x.
// The position information recorded in the AST is undefined. The filename used
// in error messages is the empty string.
//
+// If 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 source position.
+//
func ParseExpr(x string) (ast.Expr, error) {
return ParseExprFrom(token.NewFileSet(), "", []byte(x), 0)
}
// an invalid expression
src = "a + *"
- if _, err := ParseExpr(src); err == nil {
+ x, err = ParseExpr(src)
+ if err == nil {
t.Errorf("ParseExpr(%q): got no error", src)
}
+ if x == nil {
+ t.Errorf("ParseExpr(%q): got no (partial) result", src)
+ }
+ if _, ok := x.(*ast.BinaryExpr); !ok {
+ t.Errorf("ParseExpr(%q): got %T, want *ast.BinaryExpr", src, x)
+ }
// a valid expression followed by extra tokens is invalid
src = "a[i] := x"