Skip to content

Instantly share code, notes, and snippets.

@pstuifzand
Created May 17, 2013 09:52
Show Gist options
  • Save pstuifzand/5598110 to your computer and use it in GitHub Desktop.
Save pstuifzand/5598110 to your computer and use it in GitHub Desktop.
The first result of some work on the Go version of the wrapper for Marpa. You can have more control over the evaluator. In the first version (in 'go-marpa') you needed to specify actions on interface{} parameters. Now you can create your own stack with your own type. This uses the go feature where a switch statement values don't need to be const…
/* Copyright (C) 2013 Peter Stuifzand
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package marpa2
import "strconv"
type CalcEvaluator struct {
rule_op_plus, rule_value RuleID
stack []int
tokens map[int]string
re *Recognizer
}
func resize(stack []int, size int) []int {
size += 1
copy(n, stack)
return n
}
func NewCalcEvaluator() *CalcEvaluator {
calc := &CalcEvaluator{}
grammar := NewGrammar()
calc.rule_op_plus = grammar.AddRule("expr", []string{"expr", "op_plus", "expr"})
calc.rule_value = grammar.AddRule("expr", []string{"value"})
grammar.StartRule("expr")
grammar.Precompute()
re, _ := NewRecognizer(grammar)
calc.re = re
return calc
}
func (eval *CalcEvaluator) Read(terminal, value string) {
eval.re.Read(terminal, value)
}
func (eval *CalcEvaluator) StepInitial() {
eval.stack = make([]int, 1)
}
func (eval *CalcEvaluator) StepToken(result, token_value int) {
eval.stack = resize(eval.stack, result)
val, err := strconv.ParseInt(eval.re.tokens[token_value], 10, 0)
if err == nil {
eval.stack[result] = int(val)
}
}
func (eval *CalcEvaluator) StepRule(rule_id RuleID, result, arg0, argn int) {
args := eval.stack[arg0 : argn+1]
switch rule_id {
case eval.rule_op_plus:
val := args[0] + args[2]
eval.stack[result] = val
case eval.rule_value:
val := args[0]
eval.stack[result] = val
}
}
func (eval *CalcEvaluator) StepNullingSymbol(result, token_value int) {
eval.stack = resize(eval.stack, result+1)
val, err := strconv.ParseInt(eval.re.tokens[token_value], 10, 0)
if err == nil {
eval.stack[result] = int(val)
}
}
func (eval *CalcEvaluator) Value() int {
val := eval.re.Value()
val.Next(eval)
return eval.stack[0]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment