From 7212f3d9f6c1e3af3b6b6dd0c628d4dd97afadef Mon Sep 17 00:00:00 2001 From: David Ashby Date: Sun, 14 Feb 2021 11:58:43 -0500 Subject: [PATCH] add return stack --- builtins.go | 37 +++++++++++++++++++++++++++++++++++++ eval.go | 1 + main.go | 5 +++++ 3 files changed, 43 insertions(+) diff --git a/builtins.go b/builtins.go index 050a12b..5bf339c 100644 --- a/builtins.go +++ b/builtins.go @@ -184,6 +184,43 @@ func (b *Builtins) Emit(s *Stack) func() error { } } +// ToR pops from the stack to the return stack +func (b *Builtins) ToR(s *Stack, r *Stack) func() error { + return func() error { + r1, err := s.Pop() + if err != nil { + return err + } + r.Push(r1) + return nil + } +} + +// RFrom pops from the return stack to the stack +func (b *Builtins) RFrom(s *Stack, r *Stack) func() error { + return func() error { + r1, err := r.Pop() + if err != nil { + return err + } + s.Push(r1) + return nil + } +} + +// RFetch copies from the return stack to the stack +func (b *Builtins) RFetch(s *Stack, r *Stack) func() error { + return func() error { + r1, err := r.Pop() + if err != nil { + return err + } + r.Push(r1) + s.Push(r1) + return nil + } +} + // CR prints a newline to standard out func (b *Builtins) CR() func() error { return func() error { diff --git a/eval.go b/eval.go index a1d1ad7..915a9f9 100644 --- a/eval.go +++ b/eval.go @@ -10,6 +10,7 @@ import ( type Context struct { Dictionary Dictionary Stack *Stack + RStack *Stack } // Eval evaulates a given line, recursively descending into given words as needed diff --git a/main.go b/main.go index ee97b85..42b5eeb 100644 --- a/main.go +++ b/main.go @@ -10,6 +10,7 @@ import ( func main() { stack := Stack{values: []int{}} + rstack := Stack{values: []int{}} dict := Dictionary{} b := &Builtins{} @@ -26,12 +27,16 @@ func main() { dict.AddWord("WORDS", b.Words(dict), "") dict.AddWord(".S", b.Debug(&stack), "") dict.AddWord("EMIT", b.Emit(&stack), "") + dict.AddWord("R>", b.RFrom(&stack, &rstack), "") + dict.AddWord(">R", b.ToR(&stack, &rstack), "") + dict.AddWord("R@", b.RFetch(&stack, &rstack), "") dict.AddWord("CR", b.CR(), "") dict.AddWord("QUIT", b.Quit(), "") c := Context{ Dictionary: dict, Stack: &stack, + RStack: &rstack, } reader := bufio.NewReader(os.Stdin)