-
Notifications
You must be signed in to change notification settings - Fork 9
/
ante.go
239 lines (205 loc) · 5.56 KB
/
ante.go
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
// Copyright (c) 2013-2104 Michael Dvorkin
// Ante is an esoteric programming language where all you've got is a deck of cards.
//
// This is Ante implementation in Go.
package main
import (
`bytes`
`fmt`
`io/ioutil`
`math/big`
`os`
`regexp`
`strings`
`unicode/utf8`
)
type Card struct {
rank rune
suit rune
}
type Ante struct {
pc int // Program counter (index within ante.code)
line int // Current line number.
code []Card // Array of cards.
vars map[rune]*big.Int // Four registers hashed by suit.
labels map[rune]int // Labels for ante.pc to jump to.
buffer []byte // Buffer to collect UTF-8 character bytes.
}
func (ante *Ante) Initialize() *Ante {
ante.labels = map[rune]int{}
ante.vars = map[rune]*big.Int{
'♦': big.NewInt(0),
'♥': big.NewInt(0),
'♠': big.NewInt(0),
'♣': big.NewInt(0),
}
return ante
}
func (ante *Ante) Run(filename string) *Ante {
program, err := ioutil.ReadFile(filename)
if err != nil {
ante.exception(fmt.Sprintf(`%q`, err))
}
ante.parse(program)
for ante.pc < len(ante.code) {
card := ante.code[ante.pc]
ante.pc++
switch card.rank {
case 0:
ante.newline(card)
case 'K':
ante.jump(card)
case 'Q':
continue
case 'J':
ante.dump(card, true)
case 10:
ante.dump(card, false)
default:
ante.assign(card)
}
}
return ante
}
func (ante *Ante) parse(program []byte) *Ante {
// Split program blob into lines.
lines := bytes.Split(program, []byte("\n"))
// Get rid of comments and whitespaces.
comments := regexp.MustCompile(`#.*$`)
whitespace := regexp.MustCompile(`^\s+|\s+$`)
for i := 0; i < len(lines); i++ {
lines[i] = comments.ReplaceAllLiteral(lines[i], []byte(``))
lines[i] = whitespace.ReplaceAllLiteral(lines[i], []byte(``))
}
// Parse lines to turn them into array of cards.
re := regexp.MustCompile(`(10|[2-9JQKA])([♦♥♠♣])`)
for i := 0; i < len(lines); i++ {
// Line number cards have 0 rank.
ante.code = append(ante.code, Card{0, rune(i + 1)})
cards := re.FindAllSubmatch(lines[i], -1)
for _, c := range cards {
ante.code = append(ante.code, Card{bytes.Runes(c[1])[0], bytes.Runes(c[2])[0]})
}
}
// A pass to convert ranks to integers and extract labels.
for pc := 0; pc < len(ante.code) - 1; {
card := ante.code[pc]
pc++
if card.rank == '1' {
ante.code[pc-1].rank = 10
} else if card.rank >= '2' && card.rank <= '9' {
ante.code[pc-1].rank = card.rank - '0'
} else if card.rank == 'Q' {
queen := card.suit
for pc < len(ante.code) && ante.code[pc].rank == 'Q' && ante.code[pc].suit == card.suit {
queen += card.suit
pc++
}
ante.labels[queen] = pc
}
}
return ante
}
func (ante *Ante) newline(card Card) *Ante {
ante.line++
return ante
}
func (ante *Ante) jump(card Card) *Ante {
suit := card.suit
for ante.pc < len(ante.code) && ante.code[ante.pc].rank == 'K' && ante.code[ante.pc].suit == card.suit {
suit += card.suit
ante.pc++
}
// if ante.vars[card.suit] != 0 ...
if ante.vars[card.suit].Cmp(big.NewInt(0)) != 0 {
if _, ok := ante.labels[suit]; ok {
ante.pc = ante.labels[suit]
} else {
label := strings.Repeat(fmt.Sprintf(`Q%c`, card.suit), int(suit/card.suit))
ante.exception(`can't find ` + label + ` to go to`)
}
}
return ante
}
func (ante *Ante) dump(card Card, char bool) *Ante {
value := ante.vars[card.suit]
if char {
// if value < 0 || value > 255 ...
if value.Cmp(big.NewInt(0)) == -1 || value.Cmp(big.NewInt(255)) == 1 {
ante.exception(fmt.Sprintf(`character code %d is not in 0..255 range`, value))
} else {
// Collect the bytes till we have full UTF-8 character.
// Once the character is built dump it and reset the buffer.
ante.buffer = append(ante.buffer, byte(value.Int64()))
if utf8.FullRune(ante.buffer) {
fmt.Printf(`%s`, ante.buffer)
ante.buffer = []byte{}
}
}
} else {
fmt.Print(value)
}
return ante
}
func (ante *Ante) assign(card Card) *Ante {
operands := ante.remaining(card)
return ante.expression(operands)
}
// Fetch the rest of the assignment expression.
func (ante *Ante) remaining(card Card) []Card {
operands := []Card{card}
for ante.pc < len(ante.code) {
card = ante.code[ante.pc]
if card.rank == 0 || card.rank == 'K' || card.rank == 'Q' || card.rank == 'J' {
break
}
operands = append(operands, card)
ante.pc++
}
return operands
}
func (ante *Ante) expression(operands []Card) *Ante {
initial := big.NewInt(int64(operands[0].rank))
target := operands[0].suit
// if initial == 'A' ...
if initial.Cmp(big.NewInt('A')) == 0 {
// initial = ante.vars[target] // <-- Wrong!!! We need local copy, not a pointer to register.
initial.Set(ante.vars[target]) // <-- The right way to interpolate.
}
// Go through remaining operands.
for _, card := range operands[1:] {
rank := big.NewInt(int64(card.rank))
suit := card.suit
// if rank == 'A' ...
if rank.Cmp(big.NewInt('A')) == 0 {
rank.Set(ante.vars[suit]) // <-- The right way to interpolate.
}
switch suit {
case '♦':
initial.Add(initial, rank)
case '♥':
initial.Mul(initial, rank)
case '♠':
initial.Sub(initial, rank)
case '♣':
if rank.Cmp(big.NewInt(0)) != 0 {
initial.Div(initial, rank)
} else {
ante.exception(`division by zero`)
}
}
}
ante.vars[target] = initial
return ante
}
func (ante *Ante) exception(message string) {
fmt.Printf("Ante exception: %s on line %d (pc:%d)\n", message, ante.line, ante.pc)
os.Exit(1)
}
func main() {
if len(os.Args) == 2 {
new(Ante).Initialize().Run(os.Args[1])
} else {
fmt.Println(`usage: ante filename.ante`)
}
}