From 4727312da46304e7c248c0c54a1e196e56bd02ec Mon Sep 17 00:00:00 2001 From: David Ashby Date: Wed, 24 Feb 2021 20:44:56 -0500 Subject: [PATCH] implement string handling! --- builtins.go | 32 +++++++++++++++++++++++++++++++- main.go | 4 ++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/builtins.go b/builtins.go index 2fe4004..1633a09 100644 --- a/builtins.go +++ b/builtins.go @@ -58,7 +58,7 @@ func (b *Builtins) OpenComment(c *Context) func(string) error { } } -// CloseComment resumes parsing +// CloseComment resumes parsing by consuming itself and resetting the immediate flag func (b *Builtins) CloseComment(c *Context) func(string) error { return func(_ string) error { c.Flags.SetFlag("Immediate", false) @@ -66,6 +66,36 @@ func (b *Builtins) CloseComment(c *Context) func(string) error { } } +// OpenQuote consumes text until its closing pair to output +func (b *Builtins) OpenQuote(out io.Writer, r *Stack, close byte) func(string) error { + if out == nil { + out = os.Stdout + } + return func(next string) error { + w := []byte{} + for i := 0; i < len(next); i = i + 1 { + switch next[i] { + case close: + fmt.Fprint(out, string(w)) + j, _ := r.Pop() + r.Push(j + i - 1) // push the end-point onto the stack + return nil + default: + w = append(w, next[i]) + continue + } + } + return nil + } +} + +// CloseQuote consumes itself. +func (b *Builtins) CloseQuote(c *Context) func(string) error { + return func(next string) error { + return nil + } +} + // Eq compares TOS and NOS and puts -1 on the stack if they're equal, 0 otherwise. func (b *Builtins) Eq(s *Stack) func(string) error { return func(_ string) error { diff --git a/main.go b/main.go index cdd0104..f1286d9 100644 --- a/main.go +++ b/main.go @@ -50,6 +50,10 @@ func main() { dict.AddWord(".", Word{Name: ".", Impl: b.Print(os.Stdout, &stack)}) dict.AddWord("EMIT", Word{Name: "EMIT", Impl: b.Emit(os.Stdout, &stack)}) dict.AddWord("CR", Word{Name: "CR", Source: []string{"10", "EMIT"}}) // emit a newline + // strings + dict.AddWord(`."`, Word{Name: `."`, Impl: b.OpenQuote(os.Stdout, &rstack, '"')}) + dict.AddWord(`"`, Word{Name: `"`, Impl: b.CloseQuote(&c)}) + dict.AddWord(`.(`, Word{Name: `.(`, Impl: b.OpenQuote(os.Stdout, &rstack, ')'), Immediate: true}) // logic dict.AddWord("=", Word{Name: "=", Impl: b.Eq(&stack)}) dict.AddWord("0=", Word{Name: "0=", Source: []string{"0", "="}})