A small change to the computation interpreter to get rid of one useless level of recursion.
This commit is contained in:
parent
41f8733e99
commit
980c18099e
|
@ -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)
|
||||
|
|
|
@ -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)*
|
||||
|
@ -162,6 +160,7 @@ type stackFrame struct {
|
|||
type interpreter struct {
|
||||
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
|
||||
|
|
Loading…
Reference in New Issue