From 980c18099e0cfd68dc6c6f51661e24772cade079 Mon Sep 17 00:00:00 2001 From: Maurice Makaay Date: Tue, 28 May 2019 07:26:50 +0000 Subject: [PATCH] A small change to the computation interpreter to get rid of one useless level of recursion. --- example_basiccalculator1_test.go | 4 +++- example_basiccalculator2_test.go | 10 +++++----- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/example_basiccalculator1_test.go b/example_basiccalculator1_test.go index c1f86a8..03a801c 100644 --- a/example_basiccalculator1_test.go +++ b/example_basiccalculator1_test.go @@ -28,6 +28,7 @@ func Example_basicCalculator1() { {"+", 0}, {"10.8 + 12", 0}, {"42+ ", 0}, + {"9999999999999999999 + 8888888", 0}, } { output, err := ComputeSimple(c.input) if err != nil { @@ -46,6 +47,7 @@ func Example_basicCalculator1() { // Input: "+", got error: unexpected character '+' (expected integer number) // Input: "10.8 + 12", got error: unexpected character '.' (expected operator, '+' or '-') // Input: "42+ ", got error: unexpected character ' ' (expected integer number) + // Input: "9999999999999999999 + 8888888", got error: invalid value: strconv.ParseInt: parsing "9999999999999999999": value out of range } // --------------------------------------------------------------------------- @@ -80,7 +82,7 @@ func (c *simpleCalculator) number(p *parsekit.ParseAPI) { value, err := strconv.ParseInt(p.BufLiteral(), 10, 64) p.BufClear() if err != nil { - p.EmitError("invalid value %q: %s", value, err) + p.EmitError("invalid value: %s", err) } else { c.Result += c.op * value p.Handle(c.operatorOrEndOfFile) diff --git a/example_basiccalculator2_test.go b/example_basiccalculator2_test.go index f1363e8..659f1cd 100644 --- a/example_basiccalculator2_test.go +++ b/example_basiccalculator2_test.go @@ -84,13 +84,11 @@ func Compute(input string) (float64, *parsekit.Error) { } func (c *calculator) computation(p *parsekit.ParseAPI) { - c.interpreter.push() - p.Handle(c.expr) p.ExpectEndOfFile() p.Handle(c.factor) - c.result = c.interpreter.pop() + c.result = c.interpreter.result } // expr : term ((ADD|SUB) term)* @@ -160,8 +158,9 @@ type stackFrame struct { } type interpreter struct { - stack []*stackFrame - top *stackFrame + stack []*stackFrame + top *stackFrame + result float64 } func (i *interpreter) push() *stackFrame { @@ -179,6 +178,7 @@ func (i *interpreter) pop() float64 { i.top = i.stack[len(i.stack)-1] i.pushValue(value) } else { + i.result = i.top.b i.top = nil } return value