commit b85f968aa25b96bc869a908dc229104d65bde105
parent a810762abd78929e5af31822e8061131526e45aa
Author: Pavel Renev <an2qzavok@gmail.com>
Date: Sat, 30 Oct 2021 21:52:04 +0000
add forth.Step()
Diffstat:
M | dForth.go | | | 32 | +++++++++++++++++++++++++------- |
1 file changed, 25 insertions(+), 7 deletions(-)
diff --git a/dForth.go b/dForth.go
@@ -23,7 +23,7 @@ const (
type Word struct {
Name string
Builtin func() error
- Code []int
+ Addr int32
}
func NewWord(name string, builtin func() error) *Word {
@@ -33,10 +33,6 @@ func NewWord(name string, builtin func() error) *Word {
return word
}
-func (word *Word) Compile(codes ...int) {
- word.Code = append(word.Code, codes...)
-}
-
type Forth struct {
Dict []*Word
Mem []byte
@@ -61,7 +57,11 @@ func NewForth() *Forth {
_ = forth.memStore(dtpt, dictstart)
_ = forth.memStore(lwpt, 0)
_ = forth.memStore(pcpt, dictstart)
- forth.memCompile(0, 2, dictstart, 3)
+ forth.memCompile(
+ 0, /* _read */
+ 2, dictstart, /* _lit dictstart */
+ 3, /* _jump */
+ )
return forth
}
@@ -93,6 +93,24 @@ func (forth *Forth) memCompile(codes ...int32) {
forth.memStore(dtpt, int32(int(dt) + len(codes) * 4))
}
+func (forth *Forth) Step() error {
+ pc, _ := forth.memFetch(pcpt);
+ inst, _ := forth.memFetch(pc);
+ pc++;
+ if (inst > 0) && (int(inst) < len(forth.Dict)) {
+ w := forth.Dict[inst]
+ if w.Builtin != nil {
+ return w.Builtin()
+ } else {
+ pc = w.Addr
+ }
+ } else {
+ return fmt.Errorf("invalid instruction: %d, pc %d", inst, pc - 1);
+ }
+ _ = forth.memStore(pcpt, pc);
+ return nil
+}
+
func (forth *Forth) Push(pt, val int32) {
tos, err := forth.memFetch(pt)
if err != nil {
@@ -227,6 +245,6 @@ func (forth *Forth) biJump() error {
func main() {
fmt.Println("Welcome to dForth.")
forth := NewForth()
- for forth.biRead() == nil {
+ for forth.Step() == nil {
}
}