<- Back to shtanton's homepage
summaryrefslogtreecommitdiff
path: root/main/main.go
blob: cc671ee5b3e1965adfb5ac70f773b655e67077c6 (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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package main

import (
	"os"
	"fmt"
	"io"
)

type TransducerOutput interface {
	build(Store) string
}

type TransducerReplacementRune rune
func (replacement TransducerReplacementRune) build(store Store) string {
	return string(replacement)
}

type TransducerReplacementLoad rune
func (replacement TransducerReplacementLoad) build(store Store) string {
	return store[rune(replacement)]
}

type Store map[rune]string
func (store Store) clone() Store {
	newStore := make(Store)
	for key, val := range store {
		newStore[key] = val
	}
	return newStore
}
func (store Store) withValue(key rune, value string) Store {
	newStore := store.clone()
	newStore[key] = value
	return newStore
}

func compileTransducer(transducerAst SubexAST) SubexState {
	return transducerAst.compileWith(SubexNoneState{})
}

type SubexBranch struct {
	store Store
	state SubexState
	output string
}
func (pair SubexBranch) eat(char rune) []SubexBranch {
	states := pair.state.eat(pair.store, char)
	for i := range states {
		states[i].output = pair.output + states[i].output
	}
	return states
}
func (pair SubexBranch) accepting() []string {
	return pair.state.accepting(pair.store)
}

func equalStates(left SubexBranch, right SubexBranch) bool {
	// Only care about if they are the same pointer
	return left.state == right.state
}

func pruneStates(states []SubexBranch) (newStates []SubexBranch) {
	outer: for _, state := range states {
		for _, newState := range newStates {
			if equalStates(state, newState) {
				continue outer
			}
		}
		newStates = append(newStates, state)
	}
	return newStates
}

func runTransducer(transducer SubexState, input string) (output string, err bool) {
	states := []SubexBranch{{
		state: transducer,
		output: "",
		store: make(Store),
	}}
	for _, char := range input {
		var newStates []SubexBranch
		for _, state := range states {
			newStates = append(newStates, state.eat(char)...)
		}
		states = pruneStates(newStates)
	}
	for _, state := range states {
		outputEnds := state.accepting()
		for _, outputEnd := range outputEnds {
			return state.output + outputEnd, false
		}
	}
	return "", true
}

func main() {
	if len(os.Args) != 2 {
		panic("Expected: program [subex]")
	}
	inputBytes, inputErr := io.ReadAll(os.Stdin)
	input := string(inputBytes)
	if inputErr != nil {
		fmt.Println("Error reading")
	}
	program := os.Args[1]
	ast := parse(program)
	transducer := compileTransducer(ast)
	output, err := runTransducer(transducer, input)
	if err {
		output = input
	}
	fmt.Print(output)
}