-
Notifications
You must be signed in to change notification settings - Fork 1
/
compile.go
471 lines (421 loc) · 10.9 KB
/
compile.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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
package gmars
import (
"fmt"
"io"
"strings"
)
// compiler holds the input and state required to compile a program.
type compiler struct {
m Address // coresize
lines []sourceLine
config SimulatorConfig
values map[string][]token // symbols that represent expressions
labels map[string]int // symbols that represent addresses
startExpr []token
metadata WarriorData
}
func newCompiler(src []sourceLine, metadata WarriorData, config SimulatorConfig) (*compiler, error) {
err := config.Validate()
if err != nil {
return nil, fmt.Errorf("invalid config: %s", err)
}
return &compiler{
lines: src,
config: config,
metadata: metadata,
m: config.CoreSize,
startExpr: []token{{tokNumber, "0"}},
}, nil
}
func (c *compiler) loadConstants() {
c.values["CORESIZE"] = []token{{tokNumber, fmt.Sprintf("%d", c.config.CoreSize)}}
c.values["MAXLENGTH"] = []token{{tokNumber, fmt.Sprintf("%d", c.config.Length)}}
c.values["MAXPROCESSES"] = []token{{tokNumber, fmt.Sprintf("%d", c.config.Processes)}}
c.values["MINDISTANCE"] = []token{{tokNumber, fmt.Sprintf("%d", c.config.Distance)}}
// c.values["CURLINE"] = []token{{tokNumber, "0"}}
}
// load symbol []token values into value map and code line numbers of
// instruction labels into the label map
func (c *compiler) loadSymbols() {
c.values = make(map[string][]token)
c.labels = make(map[string]int)
c.loadConstants()
curPseudoLine := 0
for _, line := range c.lines {
if line.typ == linePseudoOp {
if strings.ToLower(line.op) == "equ" {
for _, label := range line.labels {
c.values[label] = line.a
}
} else if strings.ToLower(line.op) == "org" {
c.startExpr = line.a
} else if strings.ToLower(line.op) == "end" {
if len(line.a) > 0 {
c.startExpr = line.a
}
for _, label := range line.labels {
c.labels[label] = curPseudoLine
}
}
}
if line.typ == lineInstruction {
for _, label := range line.labels {
c.labels[label] = line.codeLine
}
curPseudoLine++
}
}
}
func (c *compiler) reloadReferences() error {
c.labels = make(map[string]int)
var curPseudoLine int
for _, line := range c.lines {
if line.typ == lineInstruction {
for _, label := range line.labels {
_, ok := c.labels[label]
if ok {
return fmt.Errorf("line %d: label '%s' redefined", line.line, label)
}
c.labels[label] = line.codeLine
curPseudoLine = line.codeLine + 1
}
} else if line.typ == linePseudoOp {
for _, label := range line.labels {
_, ok := c.labels[label]
if ok {
return fmt.Errorf("line %d: label '%s' redefined", line.line, label)
}
c.labels[label] = curPseudoLine
}
}
}
return nil
}
func (c *compiler) expandExpression(expr []token, line int) ([]token, error) {
input := expr
var output []token
for !exprEqual(input, output) {
if len(output) > 0 {
input = output
}
output = make([]token, 0)
for _, tok := range input {
if tok.typ == tokText {
val, valOk := c.values[tok.val]
if valOk {
output = append(output, val...)
continue
}
label, labelOk := c.labels[tok.val]
if labelOk {
val := (label - line) % int(c.m)
if val < 0 {
output = append(output, token{tokSymbol, "-"}, token{tokNumber, fmt.Sprintf("%d", -val)})
} else {
output = append(output, token{tokNumber, fmt.Sprintf("%d", val)})
}
} else {
return nil, fmt.Errorf("unresolved symbol '%s'", tok.val)
}
} else {
output = append(output, tok)
}
}
}
return output, nil
}
func (c *compiler) evaluateAssertion(assertText string) error {
assertTokens, err := LexInput(strings.NewReader(assertText))
if err != nil {
return err
}
assertTokens = assertTokens[:len(assertTokens)-1]
exprTokens, err := c.expandExpression(assertTokens, 0)
if err != nil {
return err
}
exprVal, err := evaluateExpression(exprTokens)
if err != nil {
return err
}
if exprVal == 0 {
return fmt.Errorf("assertion '%s' failed", assertText)
}
return nil
}
func (c *compiler) evaluateAssertions() error {
for _, line := range c.lines {
if line.typ != lineComment {
continue
}
if strings.HasPrefix(line.comment, ";assert") {
assertText := line.comment[7:]
err := c.evaluateAssertion(assertText)
if err != nil {
return err
}
}
}
return nil
}
func (c *compiler) assembleLine(in sourceLine) (Instruction, error) {
opLower := strings.ToLower(in.op)
var aMode, bMode AddressMode
if in.amode == "" {
if c.config.Mode == ICWS88 && opLower == "dat" {
aMode = IMMEDIATE
} else {
aMode = DIRECT
}
} else {
mode, err := getAddressMode(in.amode)
if err != nil {
return Instruction{}, fmt.Errorf("invalid amode: '%s'", in.amode)
}
aMode = mode
}
if in.bmode == "" {
if c.config.Mode == ICWS88 && opLower == "dat" {
bMode = IMMEDIATE
} else {
bMode = DIRECT
}
} else {
mode, err := getAddressMode(in.bmode)
if err != nil {
return Instruction{}, fmt.Errorf("invalid bmode: '%s'", in.bmode)
}
bMode = mode
}
var op OpCode
var opMode OpMode
if c.config.Mode == ICWS88 {
op88, err := getOpCode88(in.op)
if err != nil {
return Instruction{}, err
}
opMode88, err := getOpModeAndValidate88(op88, aMode, bMode)
if err != nil {
return Instruction{}, err
}
op, opMode = op88, opMode88
} else {
op94, opMode94, err := getOp94(in.op)
if err == nil {
op, opMode = op94, opMode94
} else {
op94, err := getOpCode(in.op)
if err != nil {
return Instruction{}, err
}
opMode94, err = getOpMode94(op94, aMode, bMode)
if err != nil {
return Instruction{}, err
}
op, opMode = op94, opMode94
}
}
aExpr, err := c.expandExpression(in.a, in.codeLine)
if err != nil {
return Instruction{}, err
}
aVal, err := evaluateExpression(aExpr)
if err != nil {
return Instruction{}, err
}
var bVal int
if len(in.b) == 0 {
if op == DAT {
// move aVal/aMode to B
bMode = aMode
bVal = aVal
// set A to #0
aMode = IMMEDIATE
aVal = 0
}
} else {
bExpr, err := c.expandExpression(in.b, in.codeLine)
if err != nil {
return Instruction{}, err
}
b, err := evaluateExpression(bExpr)
if err != nil {
return Instruction{}, err
}
bVal = b
}
aVal = aVal % int(c.m)
if aVal < 0 {
aVal = (int(c.m) + aVal) % int(c.m)
}
bVal = bVal % int(c.m)
if bVal < 0 {
bVal = (int(c.m) + bVal) % int(c.m)
}
return Instruction{
Op: op,
OpMode: opMode,
AMode: aMode,
A: Address(aVal),
BMode: bMode,
B: Address(bVal),
}, nil
}
func (c *compiler) expandFor(start, end int) error {
output := make([]sourceLine, 0)
codeLineIndex := 0
// concatenate lines preceding start
for i := 0; i < start; i++ {
// curLine := c.lines[i]
if c.lines[i].typ == lineInstruction {
// curLine.line = codeLineIndex
codeLineIndex++
}
output = append(output, c.lines[i])
}
// get labels and count from for line
labels := c.lines[start].labels
countExpr, err := c.expandExpression(c.lines[start].a, start)
if err != nil {
return err
}
count, err := evaluateExpression(countExpr)
if err != nil {
return fmt.Errorf("line %d: invalid for count '%s", c.lines[start].line, c.lines[start].a)
}
for j := 1; j <= count; j++ {
for i := start + 1; i < end; i++ {
if c.lines[i].typ == lineInstruction {
thisLine := c.lines[i]
// subtitute symbols in line
for iLabel, label := range labels {
var newValue []token
if iLabel == len(labels)-1 {
newValue = []token{{tokNumber, fmt.Sprintf("%d", j)}}
} else {
if j == 1 {
newValue = []token{{tokNumber, "0"}}
} else {
newValue = []token{{tokSymbol, "-"}, {tokNumber, fmt.Sprintf("%d", -(1 - j))}}
}
}
thisLine = thisLine.subSymbol(label, newValue)
}
// update codeLine
thisLine.codeLine = codeLineIndex
codeLineIndex++
output = append(output, thisLine)
} else {
output = append(output, c.lines[i])
}
}
}
// continue appending lines until the end of the file
for i := end + 1; i < len(c.lines); i++ {
if c.lines[i].typ == lineInstruction {
thisLine := c.lines[i]
thisLine.codeLine = codeLineIndex
codeLineIndex++
output = append(output, thisLine)
} else {
output = append(output, c.lines[i])
}
}
c.lines = output
return c.reloadReferences()
}
// look for for statements from the bottom up. if one is found it is expanded
// and the function calls itself again.
func (c *compiler) expandForLoops() error {
rofSourceIndex := -1
for i := len(c.lines) - 1; i >= 0; i-- {
if c.lines[i].typ == linePseudoOp {
lop := strings.ToLower(c.lines[i].op)
if lop == "rof" {
rofSourceIndex = i
} else if lop == "for" {
if rofSourceIndex == -1 {
return fmt.Errorf("line %d: unmatched for", c.lines[i].codeLine)
}
err := c.expandFor(i, rofSourceIndex)
if err != nil {
return err
}
return c.expandForLoops()
}
}
}
if rofSourceIndex != -1 {
return fmt.Errorf("line %d: unmatched rof", c.lines[rofSourceIndex].line)
}
return nil
}
func (c *compiler) compile() (WarriorData, error) {
c.loadSymbols()
err := c.evaluateAssertions()
if err != nil {
return WarriorData{}, err
}
graph := buildReferenceGraph(c.values)
cyclic, cyclicKey := graphContainsCycle(graph)
if cyclic {
return WarriorData{}, fmt.Errorf("expression '%s' is cyclic", cyclicKey)
}
resolved, err := expandExpressions(c.values, graph)
if err != nil {
return WarriorData{}, err
}
c.values = resolved
err = c.expandForLoops()
if err != nil {
return WarriorData{}, err
}
code := make([]Instruction, 0)
for _, line := range c.lines {
if line.typ != lineInstruction {
continue
}
instruction, err := c.assembleLine(line)
if err != nil {
return WarriorData{}, fmt.Errorf("line %d: %s", line.line, err)
}
code = append(code, instruction)
// c.values["CURLINE"] = []token{{tokNumber, fmt.Sprintf("%d", len(code))}}
}
startExpr, err := c.expandExpression(c.startExpr, 0)
if err != nil {
return WarriorData{}, fmt.Errorf("invalid start expression")
}
startVal, err := evaluateExpression(startExpr)
if err != nil {
return WarriorData{}, fmt.Errorf("invalid start expression: %s", err)
}
if startVal < 0 || startVal > len(code) {
return WarriorData{}, fmt.Errorf("invalid start value: %d", startVal)
}
c.metadata.Code = code
c.metadata.Start = startVal
return c.metadata, nil
}
func CompileWarrior(r io.Reader, config SimulatorConfig) (WarriorData, error) {
lexer := newLexer(r)
tokens, err := lexer.Tokens()
if err != nil {
return WarriorData{}, err
}
// scanner := newSymbolScanner(newBufTokenReader(tokens))
// _, err = scanner.ScanInput()
// if err != nil {
// return WarriorData{}, fmt.Errorf("symbol scanner: %s", err)
// }
parser := newParser(newBufTokenReader(tokens))
sourceLines, metadata, err := parser.parse()
if err != nil {
return WarriorData{}, err
}
compiler, err := newCompiler(sourceLines, metadata, config)
if err != nil {
return WarriorData{}, err
}
return compiler.compile()
}