-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
616 lines (528 loc) · 14.4 KB
/
main.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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
package main
import (
"fmt"
"os"
"numskull/parser"
"numskull/token"
"numskull/utils"
)
//Usage strings
const (
usage_v string = "-v, --version Prints program version number"
usage_h string = "-h, --help <argument> Prints usage for given argument"
usage_i string = "-i, --input <path> File to read input from"
usage_o string = "-o, --output <path> File to print output to"
usage_t string = "-t, --type Tells program to read input file as text"
usage_c string = "-c, --console Force program output to console"
)
//Version numbers
const (
version_interpreter string = "v0.3"
version_language string = "1.2"
)
//Runtime variables
var program []float64
var memory map[float64]float64 = make(map[float64]float64)
var input []float64
var inputPos int
//Settings
var consoleOutput bool = true
var readFromFile bool = false
var inputBinary bool = true
var writeToFile bool = false
var outputFile *os.File = nil
//Entrypoint, reads command line arguments
func main() {
//Uncomment only for debugging
/*os.Args = []string{
os.Args[0],
//"--input", "examples/hello.bf",
//"examples/brainfrick.nms",
}*/
//No arguments provided
fmt.Println()
if len(os.Args) == 1 {
printUsage()
return
}
//Variables
var forceConsole bool = false
var inputRaw []byte
//Read and process arguments
var somethingDone bool = false
for argPos := 1; argPos < len(os.Args); argPos++ {
switch os.Args[argPos] {
//Help :)
case "-h", "-H", "--help":
argPos++
//No help thing provided
if argPos == len(os.Args) {
fmt.Println("Error: specify an argument to explain.")
fmt.Println("Example:", os.Args[0], os.Args[argPos-1], "v")
fmt.Println("Pass in no arguments to see list of available arguments.")
return
}
switch os.Args[argPos] {
//Help for the version tag
case "v", "V", "version":
fmt.Println(usage_v)
fmt.Println("That's it really.")
//Help for the help tag
case "h", "H", "help":
fmt.Println(usage_h)
fmt.Println()
fmt.Println("Example: numskull", os.Args[argPos-1], "v")
fmt.Println("Shows the help page for the parameter '-v'.")
fmt.Println("The program stops once help has been printed.")
//Help for the input tag
case "i", "I", "input":
if len(os.Args[argPos]) != 1 {
os.Args[argPos] = "-" + os.Args[argPos]
}
fmt.Println(usage_i)
fmt.Println()
fmt.Println("When reading after the end of file, the result is always -1.")
fmt.Println("If this argument isn't present, input is given through the console.")
fmt.Println("Input file will be read as binary by default, look up \"numskull --help -t\" for more info.")
fmt.Println()
fmt.Println("Example: numskull", "-"+os.Args[argPos], "numbers.bin program.nms")
fmt.Println("Opens program.nms, and reads from numbers.bin when reading input.")
//Help for the output tag
case "o", "O", "output":
if len(os.Args[argPos]) != 1 {
os.Args[argPos] = "-" + os.Args[argPos]
}
fmt.Println(usage_o)
fmt.Println()
fmt.Println("When outputting, you can choose to also write that output to a file.")
fmt.Println("The file is treated as a byte array.")
fmt.Println("If this argument isn't present, the output of the program is displayed in the console.")
fmt.Println("If you still want console output AND saving to a file, use the \"-c\" argument.")
fmt.Println("If the program stops due to an error, the file is still saved.")
fmt.Println()
fmt.Println("Example: numskull", "-"+os.Args[argPos], "numbers.bin program.nms")
fmt.Println("Opens program.nms, and saves output to numbers.bin, once the program stops running.")
//Help for the type tag
case "t", "T", "type":
if len(os.Args[argPos]) != 1 {
os.Args[argPos] = "-" + os.Args[argPos]
}
fmt.Println(usage_t)
fmt.Println()
fmt.Println("Normally when reading input from a file, the input will be read as binary.")
fmt.Println("That is, one byte per input, each consisting of a number from 0 to 255.")
fmt.Println("Some may not want this behaviour, so passing in", "-"+os.Args[argPos], "will make input read as text.")
fmt.Println("Entries are read as numbers, seperated by whitespace (tabs, spaces, or newlines).")
fmt.Println("An incorrectly formatted entry will cause an error when trying to read it.")
fmt.Println("If the -i argument isn't present, this argument does nothing.")
//Help for the console tag
case "c", "C", "console":
fmt.Println(usage_c)
fmt.Println()
fmt.Println("When outputting to a file, console output is turned off by default.")
fmt.Println("Use this argument to reenable it, while also writing the output to a file, using -o.")
fmt.Println("If the -o argument isn't present, this argument does nothing.")
default:
fmt.Println("Error: unknown argument.")
fmt.Println()
printUsage()
return
}
//Exit
return
//Print numskull version
case "-v", "-V", "--version":
fmt.Println("Numskull interpreter", version_interpreter)
fmt.Println("runs Numskull version", version_language)
somethingDone = true
//Force console output
case "-c", "-C", "--console":
forceConsole = true
//Text reading mode
case "-t", "-T", "--type":
inputBinary = false
//Specify output file
case "-o", "-O", "--output":
argPos++
//No file specified
if argPos >= len(os.Args)-1 {
fmt.Println("Error: no output file specified")
fmt.Println(usage_o)
break
}
//Update stuff
var err error
outputFile, err = os.Create(os.Args[argPos])
if err != nil {
fmt.Println("Error creating output file")
fmt.Println(err.Error())
return
}
consoleOutput = false
writeToFile = true
//Read input file
case "-i", "-I", "--input":
argPos++
//No file specified
if argPos >= len(os.Args)-1 {
fmt.Println("Error: no input file specified")
fmt.Println(usage_i)
break
}
//Open file
raw, err := os.ReadFile(os.Args[argPos])
if err != nil {
fmt.Println("Error while opening input file")
fmt.Println(err.Error())
fmt.Println(usage_i)
return
}
//Read thing
inputRaw = raw
readFromFile = true
//Unknown parameter
default:
if argPos == len(os.Args)-1 {
break
}
fmt.Println("Error: Unknown argument: " + os.Args[argPos])
printUsage()
return
}
}
//No more arguments? Was anything achieved?
finArg := os.Args[len(os.Args)-1]
if finArg[0] == '-' && somethingDone {
return
}
//Try to read program file
file, err := os.ReadFile(finArg)
if err != nil {
fmt.Println("Error opening program file")
fmt.Println(err.Error())
return
}
//Read input file
if readFromFile {
//Convert input from text to []float64
if !inputBinary {
input = make([]float64, len(inputRaw)/5)[:0]
pos := 0
for {
numData := make([]byte, 64)[:0]
foundChar := false
foundComma := false
foundWhitespace := false
//Read ONE number
for {
if pos == len(inputRaw) || foundWhitespace {
break
}
//Read char
char := inputRaw[pos]
pos++
switch char {
//Numbers
case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
foundChar = true
numData = append(numData, char)
//Decimal indicators
case '.', ',':
if !foundChar {
numData = append(numData, '0')
foundChar = true
}
if foundComma {
fmt.Println("Error converting number")
fmt.Println("Double commas on entry", len(input)+1, ".")
return
}
foundComma = true
numData = append(numData, '.')
//Minus sign
case '-':
if foundChar {
fmt.Println("Error converting number")
fmt.Println("Unexpected character encountered '", string(char), "' on entry", len(input)+1)
return
}
foundChar = true
numData = append(numData, char)
//Whitespace
case ' ', 0x0D, '\t', '\n':
if !foundChar {
continue
} else {
foundWhitespace = true
}
//Unknown character
default:
fmt.Println("Error converting number")
fmt.Println("Unexpected character encountered '", string(char), "' on entry", len(input)+1)
return
}
}
//Convert to number
number, err := utils.BytesliceToNumber(numData)
if err != nil {
fmt.Println("Error when converting input file")
fmt.Println(err.Error())
return
}
input = append(input, number)
//Is this all?
if pos == len(inputRaw) {
break
}
}
}
//Convert from []byte to []float64
if inputBinary {
input = make([]float64, len(inputRaw))
for i := 0; i < len(inputRaw); i++ {
input[i] = float64(inputRaw[i])
}
}
}
//Console?
if forceConsole {
consoleOutput = true
}
//Start executing it
success := true
program, success = parser.ParseProgram(string(file))
if success {
//Run program
err = runProgram(program)
//Handle program output
fmt.Println()
fmt.Println()
if err != nil {
//Print error
fmt.Println(err.Error())
} else {
//Program finished :)
fmt.Println("Program finished :)")
}
}
//Close file maybe
if writeToFile {
outputFile.Close()
}
}
//Read from memory
func memoryRead(pos float64) float64 {
//Does value exist in memory?
if val, exists := memory[pos]; exists {
//It does, return that!
return val
}
//It doesn't, return number itself
return pos
}
//Main program function
func runProgram(program []float64) error {
callstack := make([]int, 0, 64)
for readPos := 0; readPos < len(program); {
tok := token.Token(program[readPos])
readPos++
switch tok {
//End of function (return)
case token.FunctionEnd:
if len(callstack) == 0 {
return fmt.Errorf("empty call stack, can't return from function")
}
readPos = callstack[len(callstack)-1]
callstack = callstack[:len(callstack)-1]
//Jump indicator
case token.FunctionStart, token.SquareEnd:
//Read jump point and jump
readPos = int(program[readPos])
continue
//It's a number
case token.Number:
lefthand := program[readPos]
readPos++
//Start chaining lefthands
for {
//Make sure this is a chainer
tok = token.Token(program[readPos])
readPos++
if tok != token.ChainMinus && tok != token.ChainPlus {
break
}
readPos++
//Chain lefthand
if tok == token.ChainMinus {
lefthand -= memoryRead(program[readPos])
} else {
lefthand += memoryRead(program[readPos])
}
readPos++
}
//We got us an operation
switch tok {
case token.Increment:
memory[lefthand] = memoryRead(lefthand) + 1
case token.Decrement:
memory[lefthand] = memoryRead(lefthand) - 1
case token.Assign:
readPos++
righthand := program[readPos]
readPos++
memory[lefthand] = memoryRead(righthand)
case token.Add:
readPos++
righthand := program[readPos]
readPos++
memory[lefthand] = memoryRead(lefthand) + memoryRead(righthand)
case token.Sub:
readPos++
righthand := program[readPos]
readPos++
memory[lefthand] = memoryRead(lefthand) - memoryRead(righthand)
case token.Multiply:
readPos++
righthand := program[readPos]
readPos++
memory[lefthand] = memoryRead(lefthand) * memoryRead(righthand)
case token.Divide:
readPos++
righthand := program[readPos]
readPos++
memory[lefthand] = memoryRead(lefthand) / memoryRead(righthand)
case token.PrintChar:
if consoleOutput {
fmt.Print(string(byte(memoryRead(lefthand))))
}
if writeToFile {
outputFile.Write([]byte{(byte(memoryRead(lefthand)))})
}
case token.PrintNumber:
if consoleOutput {
fmt.Print(memoryRead(lefthand))
}
if writeToFile {
outputFile.WriteString(fmt.Sprint(memoryRead(lefthand)))
}
case token.ReadInput:
//Read value
val, err := getInput()
if err != nil {
return err
}
//Assign it to memory
memory[lefthand] = val
case token.Equals:
readPos++
righthand := memoryRead(program[readPos])
readPos++
if memoryRead(lefthand) == righthand {
readPos++
} else {
//Jump
readPos = int(program[readPos])
}
case token.Different:
readPos++
righthand := memoryRead(program[readPos])
readPos++
if memoryRead(lefthand) != righthand {
readPos++
} else {
//Jump
readPos = int(program[readPos])
}
case token.LessThan:
readPos++
righthand := memoryRead(program[readPos])
readPos++
if memoryRead(lefthand) < righthand {
readPos++
} else {
//Jump
readPos = int(program[readPos])
}
case token.LessEquals:
readPos++
righthand := memoryRead(program[readPos])
readPos++
if memoryRead(lefthand) <= righthand {
readPos++
} else {
//Jump
readPos = int(program[readPos])
}
case token.GreaterThan:
readPos++
righthand := memoryRead(program[readPos])
readPos++
if memoryRead(lefthand) > righthand {
readPos++
} else {
//Jump
readPos = int(program[readPos])
}
case token.GreaterEquals:
readPos++
righthand := memoryRead(program[readPos])
readPos++
if memoryRead(lefthand) >= righthand {
readPos++
} else {
//Jump
readPos = int(program[readPos])
}
case token.FunctionRun:
//Push current position onto program stack
callstack = append(callstack, readPos)
if len(callstack) == 32 {
fmt.Println("warning: callstack is big")
}
//Move read position and verify function
readPos = int(memoryRead(lefthand))
if program[readPos] != float64(token.FunctionStart) {
return fmt.Errorf("error: invalid function call")
}
readPos += 2
default:
return fmt.Errorf("unknown operation '%s'", tok.GetTokenName())
}
}
}
//Everything worked out
return nil
}
//Prints program usage
func printUsage() {
fmt.Println("Usage: numskull [-i file] [-t] [-o file] [-c] <program-file>")
fmt.Println("Useful options:")
fmt.Println("\t", usage_h)
fmt.Println("\t", usage_v)
fmt.Println("\t", usage_i)
fmt.Println("\t", usage_t)
fmt.Println("\t", usage_o)
fmt.Println("\t", usage_c)
}
//Get input from file or command line
func getInput() (float64, error) {
if readFromFile {
//OOB read?
if inputPos >= len(input) {
return -1, nil
}
//Read data at position and return
data := input[inputPos]
inputPos++
return data, nil
} else {
//Read input from stdin
var str string
_, err := fmt.Scan(&str)
if err != nil {
return 0, err
}
//Convert this to float64 and return
return utils.BytesliceToNumber([]byte(str))
}
}