generated from bitfield/gmachine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gmachine.go
547 lines (501 loc) · 11.7 KB
/
gmachine.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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
// Package gmachine implements a simple virtual CPU, known as the G-machine.
package gmachine
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"gmachine/ast"
"gmachine/lexer"
"gmachine/parser"
"io"
"os"
"strings"
)
const MemSize = 1024
const StackSize = 256
const (
OpHALT Word = iota + 1
OpNOOP
OpOUTA
OpINCA
OpINCX
OpINCY
OpDECA
OpDECX
OpDECY
OpADDA
OpMULA
OpMVAX
OpMVIAX
OpMVAY
OpMVAV
OpMVVA
OpSETA
OpSETX
OpSETY
OpPSHA
OpPOPA
OpJUMP
OpJXNZ
)
const (
RegA Word = iota
RegX
RegY
)
const (
ExceptionOK Word = iota
ExceptionIllegalInstruction
ExceptionOutOfMemory
)
var ErrInvalidOperand error = errors.New("invalid operand")
var ErrUnknownIdentifier error = errors.New("missing label")
var ErrInvalidNumber error = errors.New("invalid number")
var ErrInvalidRegister error = errors.New("invalid register")
var ErrUndefinedInstruction error = errors.New("undefined instruction")
var ErrUnknownOpcode error = errors.New("unknown opcode")
var registers = map[string]Word{
"A": RegA,
"X": RegX,
"Y": RegY,
}
var opcodes = map[string]Word{
"HALT": OpHALT,
"NOOP": OpNOOP,
"OUTA": OpOUTA,
"INCA": OpINCA,
"INCX": OpINCX,
"INCY": OpINCY,
"DECA": OpDECA,
"DECX": OpDECX,
"DECY": OpDECY,
"ADDA": OpADDA,
"MULA": OpMULA,
"MVAX": OpMVAX,
"MVIAX": OpMVIAX,
"MVAY": OpMVAY,
"MVAV": OpMVAV,
"MVVA": OpMVVA,
"SETA": OpSETA,
"SETX": OpSETX,
"SETY": OpSETY,
"PSHA": OpPSHA,
"POPA": OpPOPA,
"JUMP": OpJUMP,
"JXNZ": OpJXNZ,
}
type Word uint64
type Machine struct {
P Word
S Word
A Word
X Word
Y Word
E Word
Out io.Writer
MemOffset Word
Memory []Word
}
func New(out io.Writer) *Machine {
return &Machine{
P: Word(0),
S: Word(0),
A: Word(0),
X: Word(0),
Y: Word(0),
E: Word(0),
Out: out,
MemOffset: StackSize,
Memory: make([]Word, MemSize),
}
}
func (g *Machine) Next() Word {
word := g.Memory[g.MemOffset+g.P]
g.P++
return word
}
func (g *Machine) Run() {
for {
instruction := g.Next()
if g.MemOffset+g.P >= MemSize {
g.E = ExceptionOutOfMemory
return
}
switch instruction {
case OpHALT:
return
case OpNOOP:
continue
case OpOUTA:
binary.Write(g.Out, binary.BigEndian, g.A)
case OpINCA:
g.A++
case OpINCX:
g.X++
case OpINCY:
g.Y++
case OpDECA:
g.A--
case OpDECX:
g.X--
case OpDECY:
g.Y--
case OpADDA:
switch g.Next() {
case RegX:
g.A += g.X
case RegY:
g.A += g.Y
}
case OpMULA:
switch g.Next() {
case RegX:
g.A *= g.X
case RegY:
g.A *= g.Y
}
case OpMVAX:
g.X = g.A
case OpMVIAX:
g.X = g.Memory[g.MemOffset+g.A]
case OpMVAY:
g.Y = g.A
case OpMVAV:
offset := g.Next()
g.Memory[g.MemOffset+offset] = g.A
case OpMVVA:
offset := g.Next()
g.A = g.Memory[g.MemOffset+offset]
case OpSETA:
g.A = g.Next()
case OpSETX:
g.X = g.Next()
case OpSETY:
g.Y = g.Next()
case OpPSHA:
g.Memory[g.S] = g.A
g.S++
case OpPOPA:
g.S--
g.A = g.Memory[g.S]
case OpJUMP:
g.P = g.Memory[g.MemOffset+g.P]
case OpJXNZ:
if g.X != 0 {
g.P = g.Memory[g.MemOffset+g.P]
} else {
g.P++
}
default:
g.E = ExceptionIllegalInstruction
return
}
}
}
func (g *Machine) RunProgram(program []Word) {
// Load program into machine
copy(g.Memory[g.MemOffset:], program)
g.Run()
}
type ref struct {
Name string
Line int
Address Word
Value Word
}
type symbolTable struct {
labels map[string]Word
consts map[string]Word
variables map[string]Word
}
func newSymbolTable() *symbolTable {
return &symbolTable{
labels: make(map[string]Word),
consts: make(map[string]Word),
variables: make(map[string]Word),
}
}
func (t *symbolTable) defineLabel(name string, address Word) {
t.labels[name] = address
}
func (t *symbolTable) defineConst(name string, value Word) {
t.consts[name] = value
}
func (t *symbolTable) defineVariable(name string, value Word) {
t.variables[name] = value
}
func (t *symbolTable) lookup(name string) (Word, bool) {
if value, ok := t.labels[name]; ok {
return value, ok
}
if value, ok := t.consts[name]; ok {
return value, ok
}
if value, ok := t.variables[name]; ok {
return value, ok
}
return Word(0), false
}
func Assemble(reader io.Reader) ([]Word, error) {
program := []Word{}
refs := []ref{}
symbols := newSymbolTable()
l, err := lexer.New(reader)
if err != nil {
return nil, err
}
p := parser.New(l)
astProgram := p.ParseProgram()
if astProgram == nil {
return nil, errors.New("failed to parse program")
}
if len(p.Errors()) > 0 {
return nil, p.Errors()[0]
}
// Assemble program
for _, stmt := range astProgram.Statements {
switch stmt := stmt.(type) {
case ast.ConstantDefinitionStatement:
value := stmt.Value.(ast.IntegerLiteral).Value
symbols.defineConst(stmt.Name.Value, Word(value))
case ast.LabelDefinitionStatement:
name := strings.TrimPrefix(stmt.TokenLiteral(), ".")
symbols.defineLabel(name, Word(len(program)))
case ast.VariableDefinitionStatement:
symbols.defineVariable(stmt.Name.Value, Word(len(program)))
switch operand := stmt.Value.(type) {
case ast.IntegerLiteral:
program = append(program, Word(operand.Value))
case ast.StringLiteral:
strSlice := make([]Word, len(operand.Value)+1)
for i, c := range operand.Value {
strSlice[i] = Word(c)
}
program = append(program, strSlice...)
default:
return nil, errors.New("invalid variable definition")
}
case ast.InstructionStatement:
program, refs, err = assembleInstructionStatement(stmt, program, refs)
if err != nil {
return nil, err
}
default:
return nil, fmt.Errorf("unknown statement type: %T", stmt)
}
}
// Resolve references to labels and consts
for _, r := range refs {
value, ok := symbols.lookup(r.Name)
if !ok {
return nil, fmt.Errorf("%w: %s at line %d", ErrUnknownIdentifier, r.Name, r.Line)
}
program[r.Address] = value
}
return program, nil
}
func assembleInstructionStatement(stmt ast.InstructionStatement, program []Word, refs []ref) ([]Word, []ref, error) {
if stmt.Operand1 == nil {
opcode, ok := opcodes[stmt.TokenLiteral()]
if !ok {
return nil, nil, fmt.Errorf("%w: %s at line %d", ErrUndefinedInstruction, stmt.TokenLiteral(), stmt.Token.Line)
}
program = append(program, opcode)
return program, refs, nil
}
instruction := stmt.TokenLiteral()
switch instruction {
case "MOVE":
opcodeStr := "MV"
switch operand1 := stmt.Operand1.(type) {
case ast.RegisterLiteral:
if operand1.Dereferenced {
opcodeStr += "I"
}
opcodeStr += operand1.TokenLiteral()
switch operand2 := stmt.Operand2.(type) {
case ast.RegisterLiteral:
opcodeStr += operand2.TokenLiteral()
opcode, ok := opcodes[opcodeStr]
if !ok {
return nil, nil, fmt.Errorf("%w: %s at line %d", ErrUnknownOpcode, opcodeStr, stmt.Token.Line)
}
program = append(program, opcode)
case ast.Identifier:
opcodeStr := fmt.Sprintf("%s%s%s", "MV", operand1.TokenLiteral(), "V")
opcode, ok := opcodes[opcodeStr]
if !ok {
return nil, nil, fmt.Errorf("%w: %s at line %d", ErrUnknownOpcode, opcodeStr, stmt.Token.Line)
}
program = append(program, opcode)
r := ref{
Name: operand2.TokenLiteral(),
Line: operand2.Token.Line,
Address: Word(len(program)),
}
refs = append(refs, r)
program = append(program, Word(0))
}
case ast.Identifier:
opcodeStr += "V"
switch operand2 := stmt.Operand2.(type) {
case ast.RegisterLiteral:
opcodeStr += operand2.TokenLiteral()
opcode, ok := opcodes[opcodeStr]
if !ok {
return nil, nil, fmt.Errorf("%w: %s at line %d", ErrUnknownOpcode, opcodeStr, stmt.Token.Line)
}
program = append(program, opcode)
r := ref{
Name: operand1.TokenLiteral(),
Line: operand1.Token.Line,
Address: Word(len(program)),
}
refs = append(refs, r)
program = append(program, Word(0))
}
default:
return nil, nil, fmt.Errorf("%w: %s at line %d", ErrInvalidOperand, operand1.TokenLiteral(), stmt.Token.Line)
}
case "MULA", "ADDA":
opcode, ok := opcodes[instruction]
if !ok {
return nil, nil, fmt.Errorf("%w: %s at line %d", ErrUndefinedInstruction, stmt.TokenLiteral(), stmt.Token.Line)
}
switch operand := stmt.Operand1.(type) {
case ast.RegisterLiteral:
register, ok := registers[operand.TokenLiteral()]
if !ok {
return nil, nil, fmt.Errorf("%w: %s at line %d", ErrInvalidRegister, operand.TokenLiteral(), operand.Token.Line)
}
program = append(program, opcode, register)
default:
return nil, nil, fmt.Errorf("%w: %s at line %d", ErrInvalidOperand, stmt.TokenLiteral(), stmt.Token.Line)
}
case "SETA", "SETX", "SETY":
opcode, ok := opcodes[instruction]
if !ok {
return nil, nil, fmt.Errorf("%w: %s at line %d", ErrUndefinedInstruction, stmt.TokenLiteral(), stmt.Token.Line)
}
switch operand := stmt.Operand1.(type) {
case ast.IntegerLiteral:
program = append(program, opcode, Word(operand.Value))
case ast.CharacterLiteral:
program = append(program, opcode, Word(operand.Value))
case ast.Identifier:
program = append(program, opcode)
r := ref{
Name: operand.TokenLiteral(),
Line: operand.Token.Line,
Address: Word(len(program)),
}
refs = append(refs, r)
program = append(program, Word(0))
default:
return nil, nil, fmt.Errorf("%w: %s at line %d", ErrInvalidOperand, stmt.TokenLiteral(), stmt.Token.Line)
}
case "JUMP", "JXNZ":
opcode, ok := opcodes[instruction]
if !ok {
return nil, nil, fmt.Errorf("%w: %s at line %d", ErrUndefinedInstruction, stmt.TokenLiteral(), stmt.Token.Line)
}
switch operand := stmt.Operand1.(type) {
case ast.IntegerLiteral:
program = append(program, opcode, Word(operand.Value))
case ast.Identifier:
program = append(program, opcode)
r := ref{
Name: operand.TokenLiteral(),
Line: operand.Token.Line,
Address: Word(len(program)),
}
refs = append(refs, r)
program = append(program, Word(0))
default:
return nil, nil, fmt.Errorf("%w: %s at line %d", ErrInvalidOperand, stmt.TokenLiteral(), stmt.Token.Line)
}
}
return program, refs, nil
}
func (g *Machine) AssembleAndRun(r io.Reader) error {
program, err := Assemble(r)
if err != nil {
return err
}
g.RunProgram(program)
return nil
}
func RunFile(path string) int {
content, err := os.Open(path)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return 1
}
g := New(os.Stdout)
err = g.AssembleAndRun(content)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return 1
}
return 0
}
func Compile(in io.Reader, out io.Writer) error {
program, err := Assemble(in)
if err != nil {
return err
}
err = binary.Write(out, binary.BigEndian, program)
if err != nil {
return err
}
return nil
}
func MainCompile() int {
fileName := os.Args[1]
outputFile := strings.TrimSuffix(fileName, ".g")
in, err := os.Open(fileName)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return 1
}
defer in.Close()
out, err := os.Create(outputFile)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return 1
}
defer out.Close()
err = Compile(in, out)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return 1
}
return 0
}
func MainRun() int {
f, err := os.Open(os.Args[1])
if err != nil {
fmt.Fprintln(os.Stderr, err)
return 1
}
defer f.Close()
input, err := io.ReadAll(f)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return 1
}
program := make([]Word, len(input)/8)
err = binary.Read(bytes.NewReader(input), binary.BigEndian, &program)
if err != nil {
fmt.Fprintln(os.Stderr, err)
return 1
}
g := New(os.Stdout)
g.RunProgram(program)
if g.E != 0 {
fmt.Fprintf(os.Stderr, "exception number: %d\n", g.E)
return 1
}
return 0
}