commit dbb76704dbeb1765e6c49384f9cc978569aa01c0
parent 959785dc64cb1385268664b73fc7d25f8ae98097
Author: Pavel Renev <an2qzavok@gmail.com>
Date: Sun, 7 Nov 2021 14:38:53 +0000
io is now provided by io.Reader/io.Writer in forth
Diffstat:
M | dForth.go | | | 35 | +++++++++++++++++++++-------------- |
1 file changed, 21 insertions(+), 14 deletions(-)
diff --git a/dForth.go b/dForth.go
@@ -1,7 +1,9 @@
package main
import (
+ "io"
"fmt"
+ "os"
"strconv"
"encoding/binary"
)
@@ -36,6 +38,8 @@ func NewWord(name string, builtin func() error) *Word {
}
type Forth struct {
+ in io.Reader
+ out io.Writer
Dict []*Word
Mem []byte
}
@@ -161,7 +165,7 @@ func (forth *Forth) Exec(w *Word) error {
func (forth *Forth) biDot() error {
val := forth.Pop(stpt)
- fmt.Print(val, " ")
+ fmt.Fprint(forth.out, val, " ")
return nil
}
@@ -188,7 +192,7 @@ func (forth *Forth) biRead() error {
i, id, num int
w *Word
)
- if _, err = fmt.Scan(&s); err != nil {
+ if _, err = fmt.Fscan(forth.in, &s); err != nil {
return err
}
/* We shouldn't get empty reads, but on 9front
@@ -211,7 +215,7 @@ func (forth *Forth) biRead() error {
return forth.Exec(w)
} else {
if num, nerr = strconv.Atoi(s); nerr != nil {
- fmt.Println("?")
+ fmt.Fprintln(forth.out, "?")
} else {
forth.Push(stpt, int32(num))
}
@@ -281,7 +285,7 @@ func (forth *Forth) biNewWord() error {
s string
w *Word
)
- if _, err = fmt.Scan(&s); err != nil {
+ if _, err = fmt.Fscan(forth.in, &s); err != nil {
return err
}
w = NewWord(s, nil)
@@ -304,7 +308,7 @@ func (forth *Forth) biCompile() error {
)
s = ""
for ;; {
- if _, err := fmt.Scan(&s); err != nil {
+ if _, err := fmt.Fscan(forth.in, &s); err != nil {
return err
}
if s == ";" {
@@ -325,7 +329,7 @@ func (forth *Forth) biCompile() error {
}
} else {
if num, err := strconv.Atoi(s); err != nil {
- fmt.Println("?")
+ fmt.Fprintln(forth.out, "?")
/* TODO: we should revert changes to before compilation start */
return nil
} else {
@@ -337,16 +341,19 @@ func (forth *Forth) biCompile() error {
return nil
}
-func main() {
+func (forth *Forth) Run(in io.Reader, out io.Writer) error {
var err error
+ forth.in = in
+ forth.out = out
+ for err == nil {
+ err = forth.Step()
+ }
+ return err
+}
+
+func main() {
fmt.Println("Welcome to dForth.")
forth := NewForth()
- for err = nil; err == nil; err = forth.Step() {
- }
+ err := forth.Run(os.Stdin, os.Stdout)
fmt.Println("done: ", err)
- for i := 0; i < 32; i++ {
- addr := int32(dictstart + i * 4)
- inst, _ := forth.memFetch(addr)
- fmt.Println(addr, inst)
- }
}