aboutsummaryrefslogtreecommitdiff
path: root/pkg/interpreter/interpreter.go
blob: 76917b772297b9a839949c9da5a9b1056ee06d58 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package interpreter

import (
	"git.adyxax.org/adyxax/gofunge/pkg/field"
	"git.adyxax.org/adyxax/gofunge/pkg/pointer"
)

type Interpreter struct {
	f *field.Field
	p *pointer.Pointer
}

func NewInterpreter(f *field.Field, p *pointer.Pointer) *Interpreter {
	return &Interpreter{f: f, p: p}
}

func (i *Interpreter) Run() int {
	for i.p != nil {
		if v := i.Step(); v != nil {
			return *v
		}
	}
	return 0
}

func (i *Interpreter) Step() *int {
	var prev *pointer.Pointer = nil
	for p := i.p; p != nil; p = p.Next {
		done, v := p.Exec(i.f)
		if v != nil {
			return v
		}
		if done {
			if prev == nil {
				i.p = p.Next
			} else {
				prev.Next = p.Next
			}
		}
	}
	return nil
}