aboutsummaryrefslogtreecommitdiff
path: root/src/go/parser/interface.go
diff options
context:
space:
mode:
authorRobert Griesemer <gri@golang.org>2015-06-12 16:33:49 -0700
committerRobert Griesemer <gri@golang.org>2015-06-12 23:46:32 +0000
commitcb2d02c8032aee0e253eb1091556408cbf205f41 (patch)
treebb66589617ac70882ee9815415722103c28a45c3 /src/go/parser/interface.go
parent965584ac07c87839cb28f28e40f2f9a74ebaff76 (diff)
downloadgo-cb2d02c8032aee0e253eb1091556408cbf205f41.tar.gz
go-cb2d02c8032aee0e253eb1091556408cbf205f41.zip
go/parser: add ParseExprFrom function
This is needed for code that relies on having the correct file set when parsing an expression only. There's currently no other way to get to the file set otherwise or to invoke the parser correctly to work on an expression only with a given file set. Change-Id: I325f174cb34b69284e627f59fe8334efa4eaa45c Reviewed-on: https://go-review.googlesource.com/10998 Reviewed-by: Alan Donovan <adonovan@google.com>
Diffstat (limited to 'src/go/parser/interface.go')
-rw-r--r--src/go/parser/interface.go35
1 files changed, 30 insertions, 5 deletions
diff --git a/src/go/parser/interface.go b/src/go/parser/interface.go
index f3bc4b9cc8..c6fd93240a 100644
--- a/src/go/parser/interface.go
+++ b/src/go/parser/interface.go
@@ -167,14 +167,31 @@ func ParseDir(fset *token.FileSet, path string, filter func(os.FileInfo) bool, m
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.
+// ParseExprFrom is a convenience function for parsing an expression.
+// The arguments have the same meaning as for Parse, but the source must
+// be a valid Go (type or value) expression.
//
-func ParseExpr(x string) (ast.Expr, error) {
+func ParseExprFrom(fset *token.FileSet, filename string, src interface{}, mode Mode) (ast.Expr, error) {
+ // get source
+ text, err := readSource(filename, src)
+ if err != nil {
+ return nil, err
+ }
+
var p parser
- p.init(token.NewFileSet(), "", []byte(x), 0)
+ defer func() {
+ if e := recover(); e != nil {
+ // resume same panic if it's not a bailout
+ if _, ok := e.(bailout); !ok {
+ panic(e)
+ }
+ }
+ p.errors.Sort()
+ err = p.errors.Err()
+ }()
+ // parse expr
+ p.init(fset, filename, text, mode)
// Set up pkg-level scopes to avoid nil-pointer errors.
// This is not needed for a correct expression x as the
// parser will be ok with a nil topScope, but be cautious
@@ -199,3 +216,11 @@ func ParseExpr(x string) (ast.Expr, error) {
return e, nil
}
+
+// 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.
+//
+func ParseExpr(x string) (ast.Expr, error) {
+ return ParseExprFrom(token.NewFileSet(), "", []byte(x), 0)
+}