MCPcopy
hub / github.com/adonovan/gopl.io / Parse

Function Parse

ch7/eval/parse.go:59–80  ·  view source on GitHub ↗

---- parser ---- Parse parses the input string as an arithmetic expression. expr = num a literal number, e.g., 3.14159 | id a variable name, e.g., x | id '(' expr ',' ... ')' a function call | '-' expr a unary operator (+-) | e

(input string)

Source from the content-addressed store, hash-verified

57// | expr '+' expr a binary operator (+-*/)
58//
59func Parse(input string) (_ Expr, err error) {
60 defer func() {
61 switch x := recover().(type) {
62 case nil:
63 // no panic
64 case lexPanic:
65 err = fmt.Errorf("%s", x)
66 default:
67 // unexpected panic: resume state of panic.
68 panic(x)
69 }
70 }()
71 lex := new(lexer)
72 lex.scan.Init(strings.NewReader(input))
73 lex.scan.Mode = scanner.ScanIdents | scanner.ScanInts | scanner.ScanFloats
74 lex.next() // initial lookahead
75 e := parseExpr(lex)
76 if lex.token != scanner.EOF {
77 return nil, fmt.Errorf("unexpected %s", lex.describe())
78 }
79 return e, nil
80}
81
82func parseExpr(lex *lexer) Expr { return parseBinary(lex, 1) }
83

Callers 5

Example_exprFunction · 0.92
parseAndCheckFunction · 0.92
TestCoverageFunction · 0.85
TestEvalFunction · 0.85
TestErrorsFunction · 0.85

Calls 3

parseExprFunction · 0.85
describeMethod · 0.80
nextMethod · 0.45

Tested by 4

Example_exprFunction · 0.74
TestCoverageFunction · 0.68
TestEvalFunction · 0.68
TestErrorsFunction · 0.68