|
| 1 | +// Package strparse provides convenience wrappers around `go/parser` for simple |
| 2 | +// expression, statement and declaretion parsing from string. |
| 3 | +// |
| 4 | +// Can be used to construct AST nodes using source syntax. |
| 5 | +package strparse |
| 6 | + |
| 7 | +import ( |
| 8 | + "go/ast" |
| 9 | + "go/parser" |
| 10 | + "go/token" |
| 11 | +) |
| 12 | + |
| 13 | +var ( |
| 14 | + // BadExpr is returned as a parse result for malformed expressions. |
| 15 | + // Should be treated as constant or readonly variable. |
| 16 | + BadExpr = &ast.BadExpr{} |
| 17 | + |
| 18 | + // BadStmt is returned as a parse result for malformed statmenents. |
| 19 | + // Should be treated as constant or readonly variable. |
| 20 | + BadStmt = &ast.BadStmt{} |
| 21 | + |
| 22 | + // BadDecl is returned as a parse result for malformed declarations. |
| 23 | + // Should be treated as constant or readonly variable. |
| 24 | + BadDecl = &ast.BadDecl{} |
| 25 | +) |
| 26 | + |
| 27 | +// Expr parses single expression node from s. |
| 28 | +// In case of parse error, BadExpr is returned. |
| 29 | +func Expr(s string) ast.Expr { |
| 30 | + node, err := parser.ParseExpr(s) |
| 31 | + if err != nil { |
| 32 | + return BadExpr |
| 33 | + } |
| 34 | + return node |
| 35 | +} |
| 36 | + |
| 37 | +// Stmt parses single statement node from s. |
| 38 | +// In case of parse error, BadStmt is returned. |
| 39 | +func Stmt(s string) ast.Stmt { |
| 40 | + node, err := parser.ParseFile(token.NewFileSet(), "", "package main;func main() {"+s+"}", 0) |
| 41 | + if err != nil { |
| 42 | + return BadStmt |
| 43 | + } |
| 44 | + return node.Decls[0].(*ast.FuncDecl).Body.List[0] |
| 45 | +} |
| 46 | + |
| 47 | +// Decl parses single declaration node from s. |
| 48 | +// In case of parse error, BadDecl is returned. |
| 49 | +func Decl(s string) ast.Decl { |
| 50 | + node, err := parser.ParseFile(token.NewFileSet(), "", "package main;"+s, 0) |
| 51 | + if err != nil { |
| 52 | + return BadDecl |
| 53 | + } |
| 54 | + return node.Decls[0] |
| 55 | +} |
0 commit comments