prosper/eval.go

94 lines
2.0 KiB
Go
Raw Normal View History

2021-02-14 02:09:56 +00:00
package main
import (
"fmt"
"strconv"
"strings"
)
// Context is a set of Dictionary + Stacks + Flags representing a runtime environment
2021-02-14 02:09:56 +00:00
type Context struct {
Dictionary Dictionary
Stack *Stack
2021-02-14 16:58:43 +00:00
RStack *Stack
Flags Flags
2021-02-15 20:35:40 +00:00
Words []string
2021-02-14 02:09:56 +00:00
}
// Eval evaulates a given line, recursively descending into given words as needed
func (c *Context) Eval(line string) error {
// state
var word []byte
for i := 0; i < len(line); i = i + 1 {
switch line[i] {
case ' ':
sword := strings.TrimSpace(string(word))
2021-02-14 02:09:56 +00:00
if len(word) == 0 {
// empty space, just continue...
2021-02-14 02:09:56 +00:00
continue
}
// Is this a word we know?
w, _ := c.Dictionary.GetWord(sword)
// check if it's an IMMEDIATE mode toggle word
if !c.Flags.GetFlag("Immediate") {
c.Flags.SetFlag("Immediate", w.Immediate)
2021-02-14 02:09:56 +00:00
}
if !c.Flags.GetFlag("Immediate") {
if !c.Flags.GetFlag("Comment") {
c.Words = append(c.Words, sword)
}
word = []byte{}
2021-02-14 02:09:56 +00:00
continue
}
2021-02-15 01:26:30 +00:00
int, err := strconv.Atoi(sword)
2021-02-14 02:09:56 +00:00
if err == nil {
// it was a number! put it on the stack.
c.Stack.Push(int)
word = []byte{}
continue
}
2021-02-14 02:09:56 +00:00
// it wasn't a number. Is it a word we know?
w, err = c.Dictionary.GetWord(sword)
2021-02-14 02:09:56 +00:00
if err != nil {
return fmt.Errorf("could not parse %s; %v", w.Name, err)
}
2021-02-15 01:26:30 +00:00
// run word
c.RStack.Push(i)
if err = c.Exec(w); err != nil {
return err
2021-02-14 02:09:56 +00:00
}
2021-02-15 01:26:30 +00:00
i, err = c.RStack.Pop()
if err != nil {
return fmt.Errorf("error while popping from return stack: %v", err)
}
word = []byte{}
2021-02-14 02:09:56 +00:00
default:
word = append(word, line[i])
2021-02-14 02:09:56 +00:00
}
}
return nil
}
2021-02-15 01:26:30 +00:00
// Exec wraps the branched execution of words (either built-in or user-defined)
2021-02-15 01:26:30 +00:00
func (c *Context) Exec(w Word) error {
if w.Impl != nil {
// we have an implementation for that word. Run it.
err := w.Impl()
if err != nil {
return err
}
} else if len(w.Source) != 0 {
// user-defined word; let's descend...
err := c.Eval(strings.Join(w.Source, " ") + " ")
if err != nil {
return err
}
}
return nil
}