forked from microsoft/microcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jacs_topwriter.ts
1381 lines (1259 loc) · 51.1 KB
/
jacs_topwriter.ts
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
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
namespace jacs {
export let debugOut = false
export function addUnique<T>(arr: T[], v: T) {
let idx = arr.indexOf(v)
if (idx < 0) {
idx = arr.length
arr.push(v)
}
return idx
}
export interface SMap<T> {
[k: string]: T
}
class Variable {
index: number
constructor(
lst: Variable[],
public kind: CellKind,
public name: string
) {
this.index = lst.length
lst.push(this)
}
get varIndex() {
if (this.kind == CellKind.LOCAL) return LOCAL_OFFSET + this.index
else return this.index
}
read(wr: OpWriter) {
return wr.emitMemRef(loadExpr(this.kind), this.varIndex)
}
write(wr: OpWriter, val: Value) {
wr.emitStmt(storeStmt(this.kind), [literal(this.varIndex), val])
}
}
export class Procedure {
writer: OpWriter
locals: Variable[] = []
params: Variable[] = []
index: number
constructor(
private parent: TopWriter,
public name: string,
lst: Procedure[]
) {
this.index = lst.length
lst.push(this)
this.writer = new OpWriter(this.parent, this.name, this.index)
}
finalize() {
this.writer.patchLabels()
}
toString() {
return this.writer.getAssembly()
}
addLocal(name: string) {
return new Variable(this.locals, CellKind.LOCAL, name)
}
lookupLocal(name: string) {
let v = this.locals.find(v => v.name == name)
if (!v) v = this.addLocal(name)
return v
}
}
class Role {
stringIndex: number
index: number
top: Label
private dispatcher: Procedure
constructor(
private parent: TopWriter,
public classIdentifier: number,
public name: string
) {
this.stringIndex = this.parent.addString(this.name)
this.index = this.parent.roles.length
this.parent.roles.push(this)
}
serialize() {
const r = Buffer.create(BinFmt.ROLE_HEADER_SIZE)
write32(r, 0, this.classIdentifier)
write16(r, 4, this.stringIndex)
return r
}
finalize() {
if (!this.dispatcher) return
this.parent.withProcedure(this.dispatcher, wr => {
wr.emitJump(this.top)
})
this.parent.withProcedure(this.parent.mainProc, wr => {
wr.emitCall(this.dispatcher.index, [], OpCall.BG_MAX1)
})
}
emit(wr: OpWriter) {
return wr.emitExpr(Op.EXPRx_STATIC_ROLE, [literal(this.index)])
}
getDispatcher() {
if (!this.dispatcher) {
this.dispatcher = this.parent.addProc(this.name + "_disp")
this.parent.withProcedure(this.dispatcher, wr => {
const wakeup = needsWakeup.find(
r => r.classId == this.classIdentifier
)
if (wakeup) {
wr.emitStmt(Op.STMT3_QUERY_REG, [
this.emit(wr),
literal(JD_REG_STREAMING_SAMPLES),
literal(1000),
])
this.parent.ifEq(
wr.emitExpr(Op.EXPR0_RET_VAL, []),
0,
() => {
this.parent.emitSetReg(
this,
JD_REG_STREAMING_SAMPLES,
hex`0a`
)
}
)
}
if (needsEnable.indexOf(this.classIdentifier) >= 0) {
this.parent.emitSetReg(this, JD_REG_INTENSITY, hex`01`)
if (this.classIdentifier == serviceClasses["radio"]) {
// set group to 1
this.parent.emitSetReg(this, 0x80, hex`01`)
}
}
this.top = wr.mkLabel("tp")
wr.emitLabel(this.top)
wr.emitStmt(Op.STMT1_WAIT_ROLE, [this.emit(wr)])
if (wakeup && wakeup.convert) {
const roleGlobal = this.parent.lookupGlobal(
"z_role" + this.index
)
const roleGlobalChanged = this.parent.lookupGlobal(
"z_role_c" + this.index
)
roleGlobalChanged.write(wr, literal(0))
this.parent.callLinked(wakeup.convert, [this.emit(wr)])
wr.emitIf(
wr.emitExpr(Op.EXPR2_NE, [
wr.emitExpr(Op.EXPR0_RET_VAL, []),
roleGlobal.read(wr),
]),
() => {
roleGlobal.write(
wr,
wr.emitExpr(Op.EXPR0_RET_VAL, [])
)
roleGlobalChanged.write(wr, literal(1))
}
)
} else if (
this.classIdentifier == serviceClasses.rotaryEncoder ||
this.classIdentifier == serviceClasses.temperature
) {
const isRotary =
this.classIdentifier == serviceClasses.rotaryEncoder
const sensorVar = isRotary
? this.parent.lookupGlobal("z_rotary" + this.index)
: this.parent.lookupGlobal("z_temp")
const sensorVarChanged = this.parent.lookupGlobal(
"z_var_changed" + this.index
)
sensorVarChanged.write(wr, literal(0))
this.parent.callLinked(
isRotary ? "get_rotary" : "round_temp",
[this.emit(wr)]
)
wr.emitIf(
wr.emitExpr(Op.EXPR2_NE, [
wr.emitExpr(Op.EXPR0_RET_VAL, []),
sensorVar.read(wr),
]),
() => {
wr.emitIf(
wr.emitExpr(Op.EXPR2_LT, [
wr.emitExpr(Op.EXPR0_RET_VAL, []),
sensorVar.read(wr),
]),
() => {
sensorVar.write(
wr,
wr.emitExpr(Op.EXPR0_RET_VAL, [])
)
sensorVarChanged.write(wr, literal(1))
},
() => {
sensorVar.write(
wr,
wr.emitExpr(Op.EXPR0_RET_VAL, [])
)
sensorVarChanged.write(wr, literal(2))
}
)
}
)
}
})
}
return this.dispatcher
}
}
export class TopWriter implements TopOpWriter {
private floatLiterals: number[] = []
private stringLiterals: (string | Buffer)[] = []
writer: OpWriter
proc: Procedure
hasErrors: boolean
resolverPC: number
globals: Variable[] = []
procs: Procedure[] = []
roles: Role[] = []
roleLocks: Variable[] = []
currPage: Variable
currRuleId = 0
currPageId = 0
pageProcs: Procedure[] = []
stopPage: Procedure
pageStartCondition: Role
constructor() {}
addString(str: string | Buffer) {
if (typeof str == "string") {
for (let i = 0; i < this.stringLiterals.length; ++i)
if (str == this.stringLiterals[i]) return i
} else {
for (let i = 0; i < this.stringLiterals.length; ++i)
if (
typeof this.stringLiterals[i] != "string" &&
str.equals(this.stringLiterals[i] as Buffer)
)
return i
}
this.stringLiterals.push(str)
return this.stringLiterals.length - 1
}
emitString(str: string | Buffer) {
return this.writer.emitExpr(Op.EXPRx_STATIC_BUFFER, [
literal(this.addString(str)),
])
}
addFloat(f: number): number {
return addUnique(this.floatLiterals, f)
}
describeCell(ff: string, idx: number): string {
switch (ff) {
case "R":
return this.roles[idx] ? this.roles[idx].name : ""
case "S":
return this.describeString(idx)
case "P":
return "" // param
case "L":
return "" // local
case "G":
return this.globals[idx] ? this.globals[idx].name : ""
case "D":
return this.floatLiterals[idx] + ""
case "F":
return this.procs[idx] ? this.procs[idx].name : ""
default:
return ""
}
}
private serialize() {
const fixHeader = new SectionWriter(BinFmt.FIX_HEADER_SIZE)
const sectDescs = new SectionWriter()
const sections: SectionWriter[] = [fixHeader, sectDescs]
const hd = Buffer.create(BinFmt.FIX_HEADER_SIZE)
hd.write(
0,
Buffer.pack("IIIH", [
BinFmt.MAGIC0,
BinFmt.MAGIC1,
BinFmt.IMG_VERSION,
this.globals.length,
])
)
fixHeader.append(hd)
const funDesc = new SectionWriter()
const funData = new SectionWriter()
const floatData = new SectionWriter()
const roleData = new SectionWriter()
const strDesc = new SectionWriter()
const strData = new SectionWriter()
for (const s of [
funDesc,
funData,
floatData,
roleData,
strDesc,
strData,
]) {
sectDescs.append(s.desc)
sections.push(s)
}
funDesc.size = BinFmt.FUNCTION_HEADER_SIZE * this.procs.length
for (const proc of this.procs) {
funDesc.append(proc.writer.desc)
proc.writer.offsetInFuncs = funData.currSize
funData.append(proc.writer.serialize())
}
const floatBuf = Buffer.create(this.floatLiterals.length * 8)
for (let i = 0; i < this.floatLiterals.length; ++i) {
const f = this.floatLiterals[i]
if ((f | 0) == f) {
// nan-box it
floatBuf.setNumber(NumberFormat.Int32LE, i << 3, f)
floatBuf.setNumber(NumberFormat.Int32LE, 4 + (i << 3), -1)
} else {
floatBuf.setNumber(NumberFormat.Float64LE, i << 3, f)
}
}
floatData.append(floatBuf)
for (const r of this.roles) {
roleData.append(r.serialize())
}
const descs = this.stringLiterals.map((str, idx) => {
let buf: Buffer
let len: number
if (typeof str == "string") {
buf = Buffer.fromUTF8(str + "\u0000")
len = buf.length - 1
} else {
buf = str as Buffer
len = buf.length
}
const desc = Buffer.create(8)
write32(desc, 0, strData.currSize) // initially use offsets in strData section
write32(desc, 4, len)
strData.append(buf)
strDesc.append(desc)
return desc
})
strData.align()
let off = 0
for (const s of sections) {
s.finalize(off)
off += s.size
}
// shift offsets from strData-local to global
for (const d of descs) {
write32(d, 0, read32(d, 0) + strData.offset)
}
for (const proc of this.procs) {
proc.writer.finalizeDesc(
funData.offset + proc.writer.offsetInFuncs,
proc.locals.length,
proc.params.length
)
}
// GC stuff before we allocate the final buffer
this.writer = undefined
this.proc = undefined
this.procs = undefined
this.pageProcs = undefined
this.roleLocks = undefined
this.pageStartCondition = undefined
this.stopPage = undefined
this.roles = undefined
const mask = BinFmt.BINARY_SIZE_ALIGN - 1
off = (off + mask) & ~mask
const outp = Buffer.create(off)
off = 0
for (const s of sections) {
for (const d of s.data) {
outp.write(off, d)
off += d.length
}
}
const left = outp.length - off
assert(0 <= left && left < BinFmt.BINARY_SIZE_ALIGN)
return outp
}
withProcedure<T>(proc: Procedure, f: (wr: OpWriter) => T) {
assert(!!proc)
const prevProc = this.proc
let r: T
try {
this.proc = proc
this.writer = proc.writer
r = f(proc.writer)
} finally {
this.proc = prevProc
if (prevProc) this.writer = prevProc.writer
}
return r
}
printAssembly() {
for (const p of this.procs) {
console.log(p.toString())
}
for (let idx = 0; idx < this.stringLiterals.length; ++idx) {
console.log(idx + ": " + this.describeString(idx))
}
}
private finalize() {
for (const r of this.roles) r.finalize()
this.withProcedure(this.mainProc, wr => {
for (const g of this.globals)
if (g.name[0] == "z" && g.name[1] == "_") {
g.write(wr, literal(0))
}
this.emitClearScreen()
wr.emitCall(this.pageProc(1).index, [])
wr.emitStmt(Op.STMT1_RETURN, [literal(0)])
})
this.withProcedure(this.stopPage, wr => {
for (const v of this.roleLocks) {
wr.emitStmt(Op.STMT1_TERMINATE_FIBER, [v.read(wr)])
v.write(wr, literal(null))
}
wr.emitStmt(Op.STMT1_RETURN, [literal(0)])
})
this.finalizePageProcs()
for (const p of this.procs) p.finalize()
}
describeString(idx: number) {
const s = this.stringLiterals[idx]
if (s == null) return "NULL"
if (typeof s == "string") return JSON.stringify(s)
else return (s as Buffer).toHex()
}
get mainProc() {
return this.procs[0]
}
addProc(name: string) {
return new Procedure(this, name, this.procs)
}
addGlobal(name: string) {
return new Variable(this.globals, CellKind.GLOBAL, name)
}
addRole(name: string, classId: number) {
const r = new Role(this, classId, name)
if (needsEnable.indexOf(classId) >= 0) r.getDispatcher()
return r
}
addOrGetRole(name: string, classId: number) {
const r = this.roles.find(r => r.name == name)
if (r) return r
return this.addRole(name, classId)
}
error(msg: string) {
this.hasErrors = true
console.error("Error: " + msg)
}
lookupServiceClass(name: string) {
const id = serviceClasses[name]
if (id === undefined) {
this.error(`service '${name}' not defined`)
return 0
}
return id
}
lookupRole(name: string, idx: number) {
const id = this.lookupServiceClass(name)
if (!id) return this.pageStartCondition
let ptr = 0
for (const r of this.roles) {
if (r.classIdentifier == id) {
if (ptr == idx) return r
ptr++
}
}
let r: Role
while (ptr <= idx) {
r = this.addRole(name + "_" + ptr, id)
ptr++
}
return r
}
lookupActuatorRole(rule: microcode.RuleDefn) {
const act = rule.actuators.length ? rule.actuators[0] : null
if (!act) return this.pageStartCondition
return this.lookupRole(
act.serviceClassName,
act.serviceInstanceIndex
)
}
lookupSensorRole(rule: microcode.RuleDefn) {
const sensor = rule.sensor
if (sensor.tid == microcode.TID_SENSOR_START_PAGE)
return this.pageStartCondition
let idx = sensor.serviceInstanceIndex
for (const f of rule.filters)
if (f.jdKind == microcode.JdKind.ServiceInstanceIndex)
idx = f.jdParam
if (!sensor.serviceClassName) this.error(`can't emit ${sensor.tid}`)
return this.lookupRole(sensor.serviceClassName, idx)
}
lookupEventCode(role: Role, rule: microcode.RuleDefn) {
const sensor = rule.sensor
if (sensor.eventCode != undefined) {
let evCode = sensor.eventCode
for (const m of rule.filters)
if (m.jdKind == microcode.JdKind.EventCode)
evCode = m.jdParam
return evCode
}
return null
}
emitSetReg(role: Role, reg: number, buf: string | Buffer) {
this.emitLoadBuffer(buf)
this.emitSendCmd(role, CMD_SET_REG | reg)
}
emitLoadBuffer(buf: string | Buffer) {
let len = 0
if (buf == null) {
buf = ""
this.error("no buffer")
}
if (typeof buf == "string")
len = Buffer.fromUTF8(buf as string).length
else len = (buf as Buffer).length
const wr = this.writer
wr.emitStmt(Op.STMT1_SETUP_PKT_BUFFER, [literal(len)])
wr.emitStmt(Op.STMT2_SET_PKT, [this.emitString(buf), literal(0)])
}
callLinked(name: string, parms: Value[]) {
const proc = linkFunction(this, name)
const args = this.writer.allocTmpLocals(parms.length)
for (let i = 0; i < parms.length; ++i) args[i].store(parms[i])
this.writer.emitCall(proc.index, args)
}
private emitLockCode(role: Role) {
const v = this.lookupGlobal(role.name + "_lock")
if (this.roleLocks.indexOf(v) < 0) this.roleLocks.push(v)
const wr = this.writer
wr.emitStmt(Op.STMT1_TERMINATE_FIBER, [v.read(wr)])
v.write(wr, wr.emitExpr(Op.EXPR1_GET_FIBER_HANDLE, [literal(null)]))
// shift the "logical top" for loop code
const lbl = wr.mkLabel("top2")
wr.emitLabel(lbl)
wr.top = lbl
}
private emitSequence(rule: microcode.RuleDefn, delay: number) {
const actuator = rule.actuators[0]
const shortCutFn = actuator.jdParam
let params = this.baseModifiers(rule).filter(
m =>
(m.jdKind == microcode.JdKind.ExtLibFn && !shortCutFn) ||
m.jdKind == microcode.JdKind.ServiceCommandArg ||
m.jdKind === microcode.JdKind.NumFmt
)
if (params.length == 0) params = [rule.actuators[0].defaultModifier]
const role = this.lookupActuatorRole(rule)
this.emitLockCode(role)
const wr = this.writer
if (shortCutFn) {
const totalBufferSize = params.reduce(
(sum, tile) =>
(tile.serviceCommandArg() as Buffer).length + sum,
0
)
const b = Buffer.create(totalBufferSize)
let index = 0
for (let i = 0; i < params.length; ++i) {
const buf = params[i].serviceCommandArg() as Buffer
b.write(index, buf)
index += buf.length
}
this.callLinked(shortCutFn, [
role.emit(wr),
this.emitString(b),
literal(params[0].jdParam2 || delay),
])
} else {
for (let i = 0; i < params.length; ++i) {
const p = params[i]
if (p.jdKind == microcode.JdKind.ServiceCommandArg) {
this.emitLoadBuffer(p.serviceCommandArg())
this.emitSendCmd(role, actuator.serviceCommand)
this.emitSleep(p.jdParam2 || delay)
} else if (p.jdKind == microcode.JdKind.ExtLibFn) {
const args = [role.emit(wr)]
if (p.jdParam2 !== undefined)
args.push(literal(p.jdParam2))
this.callLinked(p.jdParam, args)
} else if (
p.jdKind == microcode.JdKind.NumFmt &&
p.jdParam == NumFmt.F64
) {
// TODO: generalize this to work with other formats
const fmt: NumFmt = NumFmt.F64
const sz = bitSize(fmt) >> 3
wr.emitStmt(Op.STMT1_SETUP_PKT_BUFFER, [literal(sz)])
wr.emitBufStore(
literal(p.jdParam2, Op.EXPRx_LITERAL_F64),
NumFmt.F64,
0
)
this.emitSendCmd(role, actuator.serviceCommand)
this.emitSleep(5)
wr.emitStmt(Op.STMT1_SETUP_PKT_BUFFER, [literal(sz)])
wr.emitBufStore(
literal(p.jdParam2, Op.EXPRx_LITERAL_F64),
NumFmt.F64,
0
)
this.emitSendCmd(role, actuator.serviceCommand)
this.emitSleep(500)
} else {
throw "oops"
}
}
}
}
lookupGlobal(n: string) {
let g = this.globals.find(v => v.name == n)
if (!g) g = this.addGlobal(n)
return g
}
private pipeVar(id: number) {
return this.lookupGlobal("z_pipe" + (id || 0))
}
private pipeRole(id: number) {
return this.addOrGetRole("pipe_cond_" + id, SRV_JACSCRIPT_CONDITION)
}
private currValue() {
return this.proc.lookupLocal("currVal")
}
emitSendCmd(r: Role, cmd: number) {
this.writer.emitStmt(Op.STMT2_SEND_CMD, [
r.emit(this.writer),
literal(cmd),
])
}
private modExprSetup(mod: microcode.FilterModifierBase) {
const wr = this.writer
switch (mod.jdKind) {
case microcode.JdKind.Temperature:
const temperatureRole = this.lookupRole("temperature", 0)
const temperatureVar = this.lookupGlobal("z_temp")
this.callLinked("round_temp", [temperatureRole.emit(wr)])
temperatureVar.write(wr, wr.emitExpr(Op.EXPR0_RET_VAL, []))
break
default:
break
}
}
private modExpr(mod: microcode.FilterModifierBase) {
const wr = this.writer
switch (mod.jdKind) {
case microcode.JdKind.Temperature:
return this.lookupGlobal("z_temp").read(wr)
case microcode.JdKind.Literal:
return literal(mod.jdParam)
case microcode.JdKind.Variable:
return this.pipeVar(mod.jdParam).read(wr)
case microcode.JdKind.RadioValue:
return this.lookupGlobal("z_radio").read(wr)
default:
this.error("can't emit kind: " + mod.jdKind)
return literal(0)
}
}
private constantFold(mods: microcode.FilterModifierBase[], defl = 0) {
if (mods.length == 0) return defl
let v = 0
for (const m of mods) {
if (m.jdKind != microcode.JdKind.Literal) return undefined
v += m.jdParam
}
return v
}
private emitAddSeq(
mods: microcode.FilterModifierBase[],
target: Variable,
defl: number = 0,
clear = true
) {
const wr = this.writer
const addOrSet = (vv: Value) => {
target.write(
wr,
clear
? vv
: wr.emitExpr(Op.EXPR2_ADD, [target.read(wr), vv])
)
clear = false
}
if (mods.length == 0) target.write(wr, literal(defl))
else {
if (mods[0].jdKind == microcode.JdKind.RandomToss) {
mods = mods.slice(1)
let rnd: Value
let folded = this.constantFold(mods, 5)
if (folded != undefined) {
if (folded <= 2) folded = 2
rnd = this.emitRandomInt(folded - 1)
} else {
const bndVar = this.proc.lookupLocal("rndBnd")
this.emitAddSeq(mods, bndVar, 5)
wr.emitIf(
// !(2<wr) == 2>=wr == wr<=2, but use negation because of 'bndVar' being possibly nan
wr.emitExpr(Op.EXPR1_NOT, [
wr.emitExpr(Op.EXPR2_LT, [
literal(2),
bndVar.read(wr),
]),
]),
() => {
bndVar.write(wr, literal(2))
}
)
rnd = wr.emitExpr(Op.EXPR1_RANDOM_INT, [
this.emitAdd(bndVar.read(wr), -1),
])
}
addOrSet(this.emitAdd(rnd, 1))
} else {
const folded = this.constantFold(mods, defl)
if (folded != undefined) {
addOrSet(literal(folded))
} else {
for (let i = 0; i < mods.length; ++i)
this.modExprSetup(mods[i])
for (let i = 0; i < mods.length; ++i)
addOrSet(this.modExpr(mods[i]))
}
}
}
}
private breaksValSeq(mod: microcode.FilterModifierBase) {
switch (mod.jdKind) {
case microcode.JdKind.RandomToss:
return true
default:
return false
}
}
private emitValue(
trg: Variable,
modifiers: microcode.FilterModifierBase[],
defl: number
) {
let currSeq: microcode.FilterModifierBase[] = []
let first = true
for (const m of modifiers) {
if (
m.category == "value_in" ||
m.category == "value_out" ||
m.category == "constant" ||
m.category == "line"
) {
if (this.breaksValSeq(m) && currSeq.length) {
this.emitAddSeq(currSeq, trg, 0, first)
currSeq = []
first = false
}
currSeq.push(m)
}
}
if (currSeq.length) {
this.emitAddSeq(currSeq, trg, 0, first)
first = false
}
if (first) trg.write(this.writer, literal(defl))
}
private baseModifiers(rule: microcode.RuleDefn) {
let modifiers = rule.modifiers
for (let i = 0; i < modifiers.length; ++i)
if (modifiers[i].jdKind == microcode.JdKind.Loop)
return modifiers.slice(0, i)
return modifiers
}
private emitValueOut(rule: microcode.RuleDefn, defl: number) {
this.emitValue(this.currValue(), this.baseModifiers(rule), defl)
}
// 0-max inclusive
private emitRandomInt(max: number) {
if (max <= 0) return literal(0)
return this.writer.emitExpr(Op.EXPR1_RANDOM_INT, [literal(max)])
}
private emitAdd(a: Value, off: number) {
if (a.op == Op.EXPRx_LITERAL && a.numValue == 0) return literal(off)
return this.writer.emitExpr(Op.EXPR2_ADD, [a, literal(off)])
}
private loopModifierIdx(rule: microcode.RuleDefn) {
for (let i = 0; i < rule.modifiers.length; ++i) {
if (rule.modifiers[i].jdKind == microcode.JdKind.Loop) return i
}
return -1
}
private emitPossibleLoop(rule: microcode.RuleDefn) {
const idx = this.loopModifierIdx(rule)
if (idx < 0) return
const args = rule.modifiers.slice(idx + 1)
const bound = this.proc.lookupLocal("loopBnd")
const index = this.proc.lookupLocal("loopIdx")
// TODO Inf not yet supporter in JacsVM
if (args.length) this.emitValue(bound, args, Infinity)
const wr = this.writer
this.emitSleep(ANTI_FREEZE_DELAY)
if (args.length) {
index.write(
wr,
this.emitAdd(
// NaN -> 0
wr.emitExpr(Op.EXPR2_BIT_OR, [
index.read(wr),
literal(0),
]),
1
)
)
wr.emitJumpIfTrue(
wr.top,
wr.emitExpr(Op.EXPR2_LT, [index.read(wr), bound.read(wr)])
)
} else {
wr.emitJump(wr.top)
}
const bodyProc = this.proc
this.withProcedure(this.stopPage, () => {
this.ifCurrPage(() => {
this.terminateProc(bodyProc)
})
})
}
private emitRoleCommand(rule: microcode.RuleDefn) {
const actuator = rule.actuators.length ? rule.actuators[0] : null
const wr = this.writer
const currValue = () => this.currValue().read(wr)
if (actuator == null) return // do nothing
if (actuator.tid == microcode.TID_ACTUATOR_SWITCH_PAGE) {
let targetPage = 1
for (const m of rule.modifiers)
if (m.jdKind == microcode.JdKind.Page)
targetPage = m.jdParam
wr.emitCall(this.pageProc(targetPage).index, [])
} else if (actuator.jdKind == microcode.JdKind.Variable) {
this.emitSleep(ANTI_FREEZE_DELAY)
this.emitValueOut(rule, 0)
const pv = this.pipeVar(actuator.jdParam)
pv.write(wr, currValue())
this.emitSendCmd(
this.pipeRole(actuator.jdParam),
CMD_CONDITION_FIRE
)
} else if (actuator.jdKind == microcode.JdKind.NumFmt) {
this.emitValueOut(rule, 1)
const fmt: NumFmt = actuator.jdParam
const sz = bitSize(fmt) >> 3
wr.emitStmt(Op.STMT1_SETUP_PKT_BUFFER, [literal(sz)])
if (actuator.tid == microcode.TID_MODIFIER_SERVO_SET_ANGLE) {
// TODO no modulo yet in Jacs
// if (curr >= 12) { curr -= 12 }
wr.emitIf(
wr.emitExpr(Op.EXPR2_LE, [literal(12), currValue()]),
() => {
this.currValue().write(
wr,
wr.emitExpr(Op.EXPR2_SUB, [
currValue(),
literal(12),
])
)
}
)
// curr = curr * ((360/12) << 16)
this.currValue().write(
wr,
wr.emitExpr(Op.EXPR2_MUL, [
currValue(),
literal((360 / 12) << 16),
])
)
}
wr.emitBufStore(currValue(), fmt, 0)
this.emitSendCmd(
this.lookupActuatorRole(rule),
actuator.serviceCommand
)
} else if (actuator.jdKind == microcode.JdKind.Sequence) {
this.emitSequence(rule, 400)
} else if (actuator.jdKind == microcode.JdKind.ExtLibFn) {
this.emitValueOut(rule, 1)
const role = this.lookupActuatorRole(rule)
this.callLinked(actuator.jdParam, [role.emit(wr), currValue()])
} else {
this.error(`can't map act role for ${JSON.stringify(actuator)}`)
}
this.emitPossibleLoop(rule)
}
private emitRuleActuator(name: string, rule: microcode.RuleDefn) {
const body = this.addProc(name)
this.withProcedure(body, wr => {
this.emitRoleCommand(rule)
wr.emitStmt(Op.STMT1_RETURN, [literal(0)])
})
body.writer.serialize() // trim the buffer
return body
}
ifEq(v: Value, val: number, then: () => void) {
const wr = this.writer
wr.emitIf(wr.emitExpr(Op.EXPR2_EQ, [v, literal(val)]), then)
}
private ifCurrPage(then: () => void) {
this.ifEq(this.currPage.read(this.writer), this.currPageId, then)
}
private pageProc(pageIdx: number) {
if (!this.pageProcs[pageIdx]) {
this.pageProcs[pageIdx] = this.addProc("startPage" + pageIdx)
this.withProcedure(this.pageProcs[pageIdx], wr => {
// first stop the current page
wr.emitCall(this.stopPage.index, [])
// wait a bit
this.emitSleep(ANTI_FREEZE_DELAY)