A small change to the computation interpreter to get rid of one useless level of recursion.

This commit is contained in:
Maurice Makaay 2019-05-28 07:26:50 +00:00
parent 41f8733e99
commit 980c18099e
2 changed files with 8 additions and 6 deletions

View File

@ -28,6 +28,7 @@ func Example_basicCalculator1() {
{"+", 0}, {"+", 0},
{"10.8 + 12", 0}, {"10.8 + 12", 0},
{"42+ ", 0}, {"42+ ", 0},
{"9999999999999999999 + 8888888", 0},
} { } {
output, err := ComputeSimple(c.input) output, err := ComputeSimple(c.input)
if err != nil { if err != nil {
@ -46,6 +47,7 @@ func Example_basicCalculator1() {
// Input: "+", got error: unexpected character '+' (expected integer number) // Input: "+", got error: unexpected character '+' (expected integer number)
// Input: "10.8 + 12", got error: unexpected character '.' (expected operator, '+' or '-') // Input: "10.8 + 12", got error: unexpected character '.' (expected operator, '+' or '-')
// Input: "42+ ", got error: unexpected character ' ' (expected integer number) // 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) value, err := strconv.ParseInt(p.BufLiteral(), 10, 64)
p.BufClear() p.BufClear()
if err != nil { if err != nil {
p.EmitError("invalid value %q: %s", value, err) p.EmitError("invalid value: %s", err)
} else { } else {
c.Result += c.op * value c.Result += c.op * value
p.Handle(c.operatorOrEndOfFile) p.Handle(c.operatorOrEndOfFile)

View File

@ -84,13 +84,11 @@ func Compute(input string) (float64, *parsekit.Error) {
} }
func (c *calculator) computation(p *parsekit.ParseAPI) { func (c *calculator) computation(p *parsekit.ParseAPI) {
c.interpreter.push()
p.Handle(c.expr) p.Handle(c.expr)
p.ExpectEndOfFile() p.ExpectEndOfFile()
p.Handle(c.factor) p.Handle(c.factor)
c.result = c.interpreter.pop() c.result = c.interpreter.result
} }
// expr : term ((ADD|SUB) term)* // expr : term ((ADD|SUB) term)*
@ -162,6 +160,7 @@ type stackFrame struct {
type interpreter struct { type interpreter struct {
stack []*stackFrame stack []*stackFrame
top *stackFrame top *stackFrame
result float64
} }
func (i *interpreter) push() *stackFrame { func (i *interpreter) push() *stackFrame {
@ -179,6 +178,7 @@ func (i *interpreter) pop() float64 {
i.top = i.stack[len(i.stack)-1] i.top = i.stack[len(i.stack)-1]
i.pushValue(value) i.pushValue(value)
} else { } else {
i.result = i.top.b
i.top = nil i.top = nil
} }
return value return value