Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
553 lines (485 loc) · 12.3 KB
/
Copy pathmain.go
File metadata and controls
553 lines (485 loc) · 12.3 KB
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
package main
import (
"embed"
"fmt"
"maps"
"os"
"runtime"
"slices"
"strconv"
"strings"
)
//go:embed std/*.rh
var stdDir embed.FS
const (
numeric instructionType = "numeric"
str instructionType = "string"
list instructionType = "list"
word instructionType = "word"
load instructionType = "load"
store instructionType = "store"
)
type instructionType = string
type instruction struct {
value any
itype instructionType
lineNo int
}
type RhaeInstructions struct {
ptr int
ins []instruction
procedures map[string]stackFunc
extern map[string]any
}
func getStdModules() string {
var fileContents strings.Builder
// TODO: dynamic import? raylib not standard lib
for _, filename := range []string{
"std/math.rh",
"std/io.rh",
"std/json.rh",
"std/list.rh",
"std/sort.rh",
"std/str.rh",
"std/utils.rh",
} {
dat, err := stdDir.ReadFile(filename)
if err != nil {
panic("could not open file")
}
fileContents.WriteString("\n\n")
fileContents.WriteString(string(dat))
}
return fileContents.String() + "\n"
}
func ParseProcessModules(fileContents string) RhaeInstructions {
this := RhaeInstructions{
ins: []instruction{},
extern: map[string]any{},
procedures: map[string]stackFunc{},
}
lineNo := 0
for line := range strings.Lines(fileContents) {
lineNo += 1
b, _, found := strings.Cut(line, "//")
if found {
line = b
}
line = strings.TrimSpace(line)
if line == "" {
continue
}
this.lex(lineNo, line)
}
this.preprocess()
return this
}
func LoadModule(moduleName string) (any, *RhaeInstructions) {
var ref any
var ins RhaeInstructions
if moduleName == "external/raylib" {
ref = RaylibInit()
ins = ParseProcessModules(GetFileContents("./external/raylib.rh"))
} else {
panic(fmt.Sprintf("module '%s' does not exist\n", moduleName))
}
return ref, &ins
}
func NewRhaeInstructions(fileContents string) RhaeInstructions {
/* Create one interpretable module/instruction set. The module would be like this:
[standard modules all included here]
[imported vendor modules all included here; --minus the import statements]
[imported local modules all included here; --minus the import statements]
[main code block; --minus the import statements]
*/
stdModules := ParseProcessModules(getStdModules())
mainModule := ParseProcessModules(fileContents)
modulesToBeIncluded := []string{}
modulesToBeIncluded = append(modulesToBeIncluded, slices.Collect(maps.Keys(mainModule.extern))...)
finalInstructions := []instruction{}
finalInstructions = append(finalInstructions, stdModules.ins...)
extern := map[string]any{}
procedures := initBuiltInProcedures()
maps.Insert(procedures, maps.All(stdModules.procedures))
for _, moduleName := range modulesToBeIncluded {
// load the module here
// handle can be nil, but that's fine
handle, module := LoadModule(moduleName)
extern[moduleName] = handle
finalInstructions = append(finalInstructions, module.ins...)
maps.Insert(procedures, maps.All(module.procedures))
}
finalInstructions = append(finalInstructions, mainModule.ins...)
maps.Insert(procedures, maps.All(mainModule.procedures))
return RhaeInstructions{
ptr: -1,
ins: finalInstructions,
procedures: procedures,
extern: extern,
}
}
// returns index, success, instruction
func (this *RhaeInstructions) Next() (int, bool, instruction) {
this.ptr += 1
if this.ptr >= len(this.ins) {
return -1, false, instruction{}
}
ins := this.ins[this.ptr]
return this.ptr, true, ins
}
func (this *RhaeInstructions) Seek(progress int) {
this.ptr += progress
}
func (this *RhaeInstructions) ResetPtr() {
this.ptr = -1
}
func (this *RhaeInstructions) split(s string) []string {
var quote = []rune(`'"`)
var delim = []rune(" ")
const none = '\000'
open := none
return strings.FieldsFunc(s, func(r rune) bool {
switch open {
case none:
if strings.ContainsRune(string(quote), r) {
open = r
return false
}
return strings.ContainsRune(string(delim), r)
case r:
open = none
}
return false
})
}
func (this *RhaeInstructions) lex(lineNo int, line string) {
for _, t := range this.split(line) {
var tt instruction
t = strings.TrimSpace(t)
if vf, err := strconv.ParseFloat(t, 32); err == nil {
tt = instruction{value: float32(vf), itype: numeric}
} else if (strings.HasPrefix(t, "\"") && strings.HasSuffix(t, "\"")) || strings.HasPrefix(t, "'") && strings.HasSuffix(t, "'") {
t = t[1 : len(t)-1]
tt = instruction{value: t, itype: str}
} else {
if len(t) > 1 && strings.HasSuffix(t, ">") {
t = t[0 : len(t)-1]
tt = instruction{value: t, itype: load}
} else if len(t) > 1 && strings.HasSuffix(t, "<") {
t = t[0 : len(t)-1]
tt = instruction{value: t, itype: store}
} else {
tt = instruction{value: t, itype: word}
}
}
tt.lineNo = lineNo
this.ins = append(this.ins, tt)
}
}
func (this *RhaeInstructions) Eval(stack *stack) {
var variables = make(map[string]stackValue)
for {
_, ok, ins := this.Next()
if !ok {
break
}
switch ins.itype {
case numeric:
stack.Push(ins.value, NUMERIC)
case str:
stack.Push(ins.value, STRING)
case word:
fn, ok := this.procedures[ins.value.(string)]
if !ok {
panic(fmt.Sprintf("word '%s' is missing [lineno: %d]", ins.value.(string), ins.lineNo))
}
fn(stack, this)
case load:
varName := ins.value.(string)
if v, ok := variables[varName]; ok {
stack.Push(v.v, v.t)
} else {
panic(fmt.Sprintf("loading unknown variable: [%s]", varName))
}
case store:
varName := ins.value.(string)
v, _ := stack.Pop()
variables[varName] = v
}
}
}
func (this *RhaeInstructions) AddExternalLibrary(name string) {
this.extern[name] = nil
}
const (
NUMERIC stackValueType = "NUMERIC"
STRING stackValueType = "STRING"
BOOL stackValueType = "BOOL"
LIST stackValueType = "LIST"
DICT stackValueType = "DICT"
FILE stackValueType = "FILE"
OBJECT stackValueType = "OBJECT"
REF stackValueType = "REF"
)
type stackValueType = string
type stackValue struct {
v any
t stackValueType
}
func (sv stackValue) String() string {
switch sv.t {
case NUMERIC:
return fmt.Sprint(sv.v)
case STRING:
return fmt.Sprint(sv.v)
case BOOL:
return fmt.Sprintf("%t", sv.v)
case LIST:
return fmt.Sprint(*(sv.v.(*RhaeList)))
case DICT:
return fmt.Sprint((sv.v.(*RhaeDict)).String())
case FILE:
return fmt.Sprint((sv.v.(*RhaeFile)).String())
case OBJECT:
return fmt.Sprint((sv.v.(*Raylib)).String())
}
return fmt.Sprintf("%v", sv.v)
}
func (s stackValue) assertType(prefix string, assertedTypes ...stackValueType) {
if slices.Contains(assertedTypes, s.t) {
return
}
panic(fmt.Sprintf("[%s] expected %-v, got %s", prefix, assertedTypes, s.t))
}
type stack struct {
pointer uint
stack []stackValue
}
func NewStack() stack {
return stack{}
}
func (s *stack) Push(v any, t stackValueType) {
switch t {
case NUMERIC, STRING, BOOL, REF, LIST, DICT, FILE, OBJECT:
default:
panic(fmt.Sprintf("unknown stack entry type: [%s], value: [%v]", t, v))
}
s.stack = append(s.stack, stackValue{v, t})
}
func (s *stack) Pop() (stackValue, bool) {
ix := len(s.stack) - 1
if ix == -1 {
return stackValue{}, false
}
sv := s.stack[ix]
out := stackValue{sv.v, sv.t}
s.stack = s.stack[:ix]
return out, true
}
type offsetT = int
type offsetL = struct {
label string
start int
end int
}
func (this *RhaeInstructions) preprocess() {
controlStack := NewStack()
finalIns := []instruction{}
insPos := func() int { return len(finalIns) - 1 }
this.ResetPtr()
for {
_, ok, ins := this.Next()
if !ok {
break
}
if ins.itype == word {
fn := ins.value.(string)
switch fn {
case "import":
moduleToBeIncluded := finalIns[len(finalIns)-1]
if moduleToBeIncluded.itype != str {
panic(`import function needs a module name: e.g., "module_name" import`)
}
this.AddExternalLibrary(moduleToBeIncluded.value.(string))
finalIns = finalIns[0 : len(finalIns)-1] // remove the imported module name string
case "if":
var offset offsetT
finalIns = append(finalIns,
instruction{
itype: "offset",
value: &offset,
},
instruction{
itype: word,
value: "jump0",
},
)
offset = insPos()
controlStack.Push(&offset, REF)
case "else":
var elseOffset offsetT
finalIns = append(finalIns,
instruction{
itype: "offset",
value: &elseOffset,
},
instruction{
itype: word,
value: "jump",
},
)
myIx := insPos()
svalue, ok := controlStack.Pop()
if !ok {
panic("cannot pop this stack")
}
// update if offset value
gap := myIx - *svalue.v.(*offsetT)
finalIns = slices.Replace(finalIns, myIx-gap-1, myIx-gap, instruction{
itype: numeric, value: gap,
})
// push else offset value
elseOffset = myIx
controlStack.Push(&elseOffset, REF)
case "loop":
finalIns = append(finalIns,
instruction{itype: word, value: "loop"},
)
offset := offsetL{"loop", insPos(), -1}
controlStack.Push(&offset, REF)
case "func":
finalIns = append(finalIns,
instruction{itype: word, value: "func"},
)
offset := offsetL{"func", insPos(), -1}
controlStack.Push(&offset, REF)
case "do":
svalue, ok := controlStack.Pop()
if !ok {
panic("cannot pop this stack")
}
labelOffset := svalue.v.(*offsetL)
if labelOffset.label == "loop" {
finalIns = append(finalIns,
instruction{
itype: "offset",
value: labelOffset,
},
instruction{
itype: word,
value: "jump0",
},
)
labelOffset.end = insPos()
controlStack.Push(labelOffset, REF)
} else {
this.Seek(-2)
_, _, funcName := this.Next()
this.Next() // skip me
fName := funcName.value.(string)
labelOffset.label = fName
labelOffset.start = insPos() + 1
controlStack.Push(labelOffset, REF)
}
case "end":
svalue, ok := controlStack.Pop()
if !ok {
panic("cannot pop this stack")
}
if vv, isSimpleOffset := svalue.v.(*offsetT); isSimpleOffset {
// handles if/else/end
finalIns = append(finalIns, instruction{
itype: word,
value: "end",
})
myIx := insPos()
gap := myIx - int(*vv)
finalIns = slices.Replace(finalIns, myIx-gap-1, myIx-gap, instruction{
itype: numeric, value: gap,
})
} else if vv, isLabelOffset := svalue.v.(*offsetL); isLabelOffset {
// handles loops
lStart := vv.start
lEnd := vv.end
label := vv.label
if label == "loop" {
finalIns = append(finalIns,
instruction{
itype: numeric,
value: lStart - (insPos() + 2), // this instructions position
},
instruction{
itype: word,
value: "jump",
},
instruction{
itype: word,
value: "end",
},
)
myIx := insPos()
gap := myIx - lEnd
finalIns = slices.Replace(finalIns, myIx-gap-1, myIx-gap, instruction{
itype: numeric, value: gap,
})
} else {
lastInsPos := insPos()
finalIns = slices.Replace(finalIns, lStart-2, lStart,
instruction{
itype: numeric, value: (lastInsPos - lStart) + 2, // +2 for offset and jump
},
instruction{
itype: word, value: "jump",
},
)
finalIns = append(finalIns,
instruction{
itype: word,
value: "end",
},
)
allFuncInstructions := finalIns[lStart : lastInsPos+1]
this.procedures[label] = func(s *stack, r *RhaeInstructions) {
t := RhaeInstructions{
ptr: -1,
ins: allFuncInstructions,
procedures: r.procedures,
extern: r.extern,
}
t.Eval(s)
}
}
}
default:
finalIns = append(finalIns, ins)
}
} else {
finalIns = append(finalIns, ins)
}
}
this.ResetPtr()
this.ins = finalIns
}
func main() {
runtime.LockOSThread()
defer runtime.UnlockOSThread()
var filename string
if len(os.Args) > 1 {
filename = os.Args[1]
} else {
fmt.Println("please provide a file to run")
}
fileContents := GetFileContents(filename)
rhInstructions := NewRhaeInstructions(fileContents)
for false {
ix, ok, ins := rhInstructions.Next()
if !ok {
break
}
fmt.Printf("%3d - nor: %-v\n", ix, ins)
}
fmt.Printf("---------------------|\n")
rhInstructions.ResetPtr()
stack := NewStack()
rhInstructions.Eval(&stack)
}