<- Back to shtanton's homepage
aboutsummaryrefslogtreecommitdiff
path: root/main/main.go
blob: 3a864ada36bd60429cfd2bbc78615710c5015466 (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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package main

import (
	"io"
	"os"
	"bufio"
	"main/walk"
	"main/json"
)

type ProgramState struct {
	value, xreg, yreg, zreg []walk.Value
	in walk.StredReader
	out walk.StredWriter
	program []Command
	pc int
}

type config struct {
	quiet bool
	program string
	in io.Reader
	out io.Writer
}

func run(config config) {
	tokens := Lex(config.program)
	program := Parse(tokens)

	stdin := bufio.NewReader(config.in)
	stdout := bufio.NewWriter(config.out)

	state := ProgramState {
		in: json.NewJSONReader(stdin),
		out: json.NewJSONWriter(stdout),
		program: program,
	}

	for {
		walkItem, err := state.in.Read()
		if err != nil {
			break
		}
		state.value = []walk.Value{walkItem.Value}
		state.pc = 0
		for state.pc < len(state.program) {
			state.program[state.pc].exec(&state)
		}
		if !config.quiet {
			for _, value := range state.value {
				err := state.out.Write(value)
				if err != nil {
					panic("Error while outputting")
				}
			}
		}
	}

	state.in.AssertDone()
	state.out.AssertDone()
}

func main() {
	config := config {
		quiet: false,
		in: os.Stdin,
		out: os.Stdout,
	}
	hasInput := false
	
	for i := 1; i < len(os.Args); i += 1 {
		switch os.Args[i] {
			case "-n":
				config.quiet = true
				continue
		}
		if i < len(os.Args) - 1 {
			panic("Unexpected arguments after program")
		}
		config.program = os.Args[i]
		hasInput = true
	}
	if !hasInput {
		panic("Missing program")
	}

	run(config)

}