-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcompile.ts
executable file
·2593 lines (2381 loc) · 74.5 KB
/
compile.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
// Copyright 2023 Ryan Brown
import { CompilerOptions } from "./compiler_options";
import { gameData, SocketSize } from "./data";
import { generateAsm } from "./decompile/disasm";
import { Code } from "./ir/code";
import {
Arg,
Instruction,
Label,
LiteralValue,
RegRef,
Stop,
StringLiteral,
VariableRef,
regNums,
TRUE,
FALSE,
} from "./ir/instruction";
import { MethodInfo, methods } from "./methods";
import * as tsApiUtils from "ts-api-utils";
import * as ts from "typescript";
export { CompilerOptions };
// Some arbitrary things to use for dynamic jump labels
const dynamicLabels = [
"v_own_faction",
"v_ally_faction",
"v_enemy_faction",
"v_world_faction",
"v_bot",
"v_building",
"v_is_foundation",
"v_construction",
"v_droppeditem",
"v_resource",
"v_mineable",
"v_anomaly",
"v_valley",
"v_plateau",
"v_not_blight",
"v_blight",
"v_alien_faction",
"v_human_faction",
"v_robot_faction",
"v_bug_faction",
"v_solved",
"v_unsolved",
"v_can_loot",
"v_in_powergrid",
"v_mothership",
"v_damaged",
"v_infected",
"v_broken",
"v_unpowered",
"v_emergency",
"v_powereddown",
"v_pathblocked",
"v_idle",
];
function findParent<N extends ts.Node>(
n: ts.Node,
predicate: (n: ts.Node) => n is N,
): N | undefined {
let parent = n.parent;
while (parent != null && !predicate(parent)) {
parent = parent.parent;
}
return parent as N;
}
function compileFile(
mainFileName: string,
sourceFiles: ts.SourceFile[],
): string {
const c = new Compiler();
sourceFiles.forEach((f) => c.addSourceFile(f));
let main:
| { sub: ts.FunctionDeclaration }
| { blueprint: BlueprintDeclaration }
| null = null;
for (const sub of c.subs.values()) {
if (
isExported(sub) &&
findParent(sub, ts.isSourceFile)?.fileName === mainFileName
) {
if (main == null) {
main = { sub };
} else {
throw new Error("Only one declaration may be exported");
}
}
}
for (const blueprint of c.blueprints.values()) {
if (
isExported(blueprint.statement) &&
findParent(blueprint.statement, ts.isSourceFile)?.fileName ===
mainFileName
) {
if (main == null) {
main = { blueprint };
} else {
throw new Error("Only one declaration may be exported");
}
}
}
if (main == null) {
throw new Error("One declaration must be exported");
}
if ("sub" in main) {
c.compileBehavior(main.sub, true);
} else if ("blueprint" in main) {
c.compileBlueprint(main.blueprint, true);
}
for (const sub of c.subs.values()) {
if (!("sub" in main) || main.sub !== sub) {
c.compileBehavior(sub, false);
}
}
for (const blueprint of c.blueprints.values()) {
if (!("blueprint" in main) || main.blueprint !== blueprint) {
c.compileBlueprint(blueprint, false);
}
}
return c.asm();
}
interface LoopInfo {
label?: string;
cont?: string;
brk?: string;
needLabel?: boolean;
}
class VariableScope {
parent?: VariableScope;
children: VariableScope[] = [];
namedVariables = new Map<string, Variable>();
anonymousVariables: Variable[] = [];
newScope(): VariableScope {
let result = new VariableScope();
result.parent = this;
this.children.push(result);
return result;
}
has(name: string): boolean {
return this.namedVariables.has(name) || (this.parent?.has(name) ?? false);
}
new(name: string): Variable {
if (!this.namedVariables.has(name)) {
this.namedVariables.set(name, new Variable());
}
return this.get(name);
}
name(name: string, variable: Variable): Variable {
if (this.namedVariables.has(name)) {
throw new Error("Name already in use in scope: " + name);
}
this.namedVariables.set(name, variable);
const anonymousIndex = this.anonymousVariables.indexOf(variable);
if (anonymousIndex > -1) {
this.anonymousVariables.splice(anonymousIndex, 1);
}
return variable;
}
get(name: string, reg?: RegRef): Variable {
if (!this.has(name)) {
this.namedVariables.set(name, new Variable(reg));
}
return this.namedVariables.get(name) || this.parent!.get(name);
}
newAnonymousVariable(): Variable {
let variable = new Variable();
this.anonymousVariables.push(variable);
return variable;
}
allocate(availables: RegRef[], paramCounter: number): number {
const currentAvailables = [...availables];
let newParametersCount = 0;
const assignVariable = (variable: Variable) => {
if (variable.reg !== undefined) {
return;
}
if (variable.operations != VariableOperations.All) {
variable.reg = nilReg;
return;
}
if (currentAvailables.length > 0) {
variable.reg = currentAvailables.shift()!;
return;
}
// A new parameter is introduced
variable.reg = new RegRef(paramCounter + ++newParametersCount);
};
this.namedVariables.forEach(assignVariable);
this.anonymousVariables.forEach(assignVariable);
let chidrenNewParametersCount = 0;
this.children.forEach((scope) => {
chidrenNewParametersCount = Math.max(
chidrenNewParametersCount,
scope.allocate(currentAvailables, paramCounter + newParametersCount),
);
});
return newParametersCount + chidrenNewParametersCount;
}
}
class FunctionScope {
paramCounter = 0;
program = new Code();
scope = new VariableScope();
outputs: Variable[] = [];
loops: LoopInfo[] = [];
pendingLabels: string[] = [];
addOutputParameter() {
let i = this.paramCounter + 1;
this.paramCounter++;
const reg = new RegRef(i);
this.emit(".pname", reg);
this.emit(".out", reg);
this.outputs.push(new Variable(reg));
}
withNewVariableScope(f: () => undefined) {
let scope = this.scope;
this.scope = this.scope.newScope();
try {
f();
} finally {
this.scope = scope;
}
}
emitLabel(label: string) {
this.pendingLabels.push(label);
}
emit(name: string, ...args: Arg[]): Instruction {
const instr = new Instruction(name, args);
this.rawEmit(instr);
return instr;
}
rawEmit(i: Instruction) {
if (this.pendingLabels.length > 0) {
i.labels.push(...this.pendingLabels);
this.pendingLabels = [];
}
this.program.add(i);
}
}
function isExported(f: { modifiers?: ts.NodeArray<ts.ModifierLike> }): boolean {
return (
f.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword) || false
);
}
type BlueprintDeclaration = {
name: string;
frame: string;
statement: ts.VariableStatement;
initializer: ts.CallExpression;
};
class Compiler {
labelCounter = 0;
dynamicLabelCounter = 0;
subs = new Map<string, ts.FunctionDeclaration>();
blueprints = new Map<string, BlueprintDeclaration>();
functionScopes: FunctionScope[] = [];
currentScope: FunctionScope = new FunctionScope();
haveBehavior = false;
addSourceFile(f: ts.SourceFile) {
f.statements.forEach((n) => {
if (ts.isFunctionDeclaration(n)) {
let subName = (n.name as ts.Identifier).text;
if (this.subs.has(subName)) {
this.#error("sub ${subName} declared multiple times", n);
}
this.subs.set(subName, n);
} else if (ts.isVariableStatement(n)) {
if (n.declarationList.declarations.length > 0) {
for (const declaration of n.declarationList.declarations) {
if (this.#extractBlueprint(n, declaration)) {
continue;
}
this.#error(`unsupported declaration: ${declaration}`, declaration);
}
} else {
this.#error(`unsupported node ${ts.SyntaxKind[n.kind]}`, n);
}
} else if (ts.isImportDeclaration(n)) {
// Import statements are ignored. Currently all functions in all files share the same global namespace.
} else {
this.#error(`unsupported node ${ts.SyntaxKind[n.kind]}`, n);
}
});
}
#extractBlueprint(
statement: ts.VariableStatement,
declaration: ts.VariableDeclaration,
): boolean {
if (!ts.isIdentifier(declaration.name)) {
return false;
}
if (!declaration.initializer) {
return false;
}
if (
!ts.isCallExpression(declaration.initializer) ||
!ts.isPropertyAccessExpression(declaration.initializer.expression)
) {
return false;
}
let thisArg = declaration.initializer.expression.expression;
if (!ts.isIdentifier(thisArg)) {
return false;
}
if (thisArg.text === "blueprint") {
const blueprintName = declaration.name.text;
const frameName = declaration.initializer.expression.name.text;
const frame = gameData.framesByJsName.get(frameName);
if (frame == null) {
this.#error(
`Unknown frame: ${frameName}`,
declaration.initializer.expression.name,
);
}
this.blueprints.set(blueprintName, {
name: blueprintName,
statement: statement,
frame: frame.id,
initializer: declaration.initializer,
});
return true;
}
return false;
}
setupNewScope() {
this.currentScope = new FunctionScope();
this.functionScopes.push(this.currentScope);
}
compileBehavior(f: ts.FunctionDeclaration, isMain: boolean) {
let subName = (f.name as ts.Identifier).text;
if (isMain && this.haveBehavior) {
throw new Error("only one behavior supported per file");
}
this.haveBehavior = isMain;
this.setupNewScope();
// TODO: use jsdoc if present
this.#emitLabel(subName);
if (!isMain) {
this.#rawEmit(".sub");
}
this.#rawEmit(".name", new StringLiteral(subName));
this.compileInstructions(f);
}
compileBlueprint(blueprint: BlueprintDeclaration, isMain: boolean) {
this.setupNewScope();
this.#emitLabel(blueprint.name);
if (blueprint.initializer.arguments.length !== 1) {
this.#error(`Blueprint argument count must be 1`, blueprint.initializer);
}
const blueprintArg = blueprint.initializer.arguments[0];
if (!ts.isObjectLiteralExpression(blueprintArg)) {
this.#error(
`Unsupported blueprint argument 1: ${ts.SyntaxKind[blueprintArg.kind]}`,
blueprintArg,
);
}
const frame =
gameData.frames.get(blueprint.frame) ??
gameData.frames.get(`f_${blueprint.frame}`);
if (frame == null || frame.visual == null) {
this.#error(`Unknown frame: ${blueprint.frame}`, blueprint.initializer);
}
const visual = gameData.visuals.get(frame.visual);
if (visual == null) {
this.#error(
`Unknown visual ${frame.visual} of frame: ${frame.id}`,
blueprint.initializer.arguments[0],
);
}
this.#rawEmit(".blueprint", new LiteralValue({ id: frame.id }));
const parsedBlueprint: {
name?: ParsedLiteral;
power?: ParsedLiteral;
connected?: ParsedLiteral;
channels?: ParsedLiteral;
transportRoute?: ParsedLiteral;
requester?: ParsedLiteral;
supplier?: ParsedLiteral;
deliver?: ParsedLiteral;
itemTransporterOnly?: ParsedLiteral;
highPriority?: ParsedLiteral;
construction?: ParsedLiteral;
signal?: ParsedLiteral;
visual?: ParsedLiteral;
store?: ParsedLiteral;
goto?: ParsedLiteral;
internal?: ParsedLiteral;
small?: ParsedLiteral;
medium?: ParsedLiteral;
large?: ParsedLiteral;
locks?: ParsedLiteral;
} = this.parseBlueprint(blueprintArg) as any;
if (parsedBlueprint == null || typeof parsedBlueprint !== "object") {
this.#error(
`Unsupported blueprint argument 1: ${parsedBlueprint}`,
blueprintArg,
);
}
if (typeof parsedBlueprint.name?.value === "string") {
this.#rawEmit(".name", new StringLiteral(parsedBlueprint.name.value));
}
if (!(parsedBlueprint.power?.value ?? true)) {
this.#rawEmit(".powered_down");
}
if (!(parsedBlueprint?.connected?.value ?? !frame.start_disconnected)) {
this.#rawEmit(".disconnected");
}
if (parsedBlueprint?.channels?.value != null) {
if (!Array.isArray(parsedBlueprint.channels.value)) {
this.#error(
"Blueprint logistics channels must be array",
parsedBlueprint.channels.node,
);
}
const logisticChannels = parsedBlueprint.channels.value.map(
(v) => v.value,
);
for (let i = 1; i <= 4; i++) {
this.#rawEmit(
".logistics",
new StringLiteral(`channel_${i}`),
logisticChannels.includes(i) ? TRUE : FALSE,
);
}
}
const processLogisticsBoolean = (key: string, name: string = key) => {
if (parsedBlueprint?.[key]?.value != null) {
if (typeof parsedBlueprint[key].value !== "boolean") {
this.#error(
`Blueprint ${key} must be boolean`,
parsedBlueprint[key].node,
);
}
this.#rawEmit(
".logistics",
new StringLiteral(name),
parsedBlueprint[key].value ? TRUE : FALSE,
);
}
};
processLogisticsBoolean("transportRoute", "transport_route");
processLogisticsBoolean("requester");
processLogisticsBoolean("supplier");
processLogisticsBoolean("deliver", "carrier");
processLogisticsBoolean("itemTransporterOnly", "crane_only");
processLogisticsBoolean("highPriority", "high_priority");
processLogisticsBoolean("construction", "can_construction");
const allSockets = (visual.sockets ?? []).map((socket) => {
return socket[1] as SocketSize;
});
const registerLinks: Array<{
from: number;
to: string | number;
node: ts.Node;
}> = [];
const registerNames: Map<string, number> = new Map();
const duplicateBehaviorControllerParameterNames: Set<string> = new Set();
const behaviorControllerParameterNames: Map<string, number> = new Map();
const registerValues: Record<number, LiteralValue> = {};
const updateLinks = (
registerNum: number,
item: ParsedLiteral | undefined,
) => {
if (!item) return;
const linkAsArray = Array.isArray(item.value) ? item.value : [item];
for (const link of linkAsArray) {
if (link.value == null) continue;
if (typeof link.value === "string") {
registerValues[registerNum] = new LiteralValue({ id: link.value });
} else if (typeof link.value === "number") {
registerValues[registerNum] = new LiteralValue({ num: link.value });
} else if (typeof link.value != "object") {
this.#error(
`Invalid link type: ${ts.SyntaxKind[link.node.kind]}`,
link.node,
);
} else if ("id" in link.value || "num" in link.value) {
registerValues[registerNum] = new LiteralValue(link.value);
} else {
const name: ParsedLiteral = link.value["name"];
if (name != null) {
if (typeof name.value !== "string") {
this.#error("name must be string", name.node);
}
if (registerNames.has(name.value)) {
this.#error(`Duplicate register name: ${name}`, name.node);
}
registerNames.set(name.value, registerNum);
}
const value = link.value["value"];
if (value != null) {
if (typeof value.value === "string") {
registerValues[registerNum] = new LiteralValue({
id: value.value,
});
} else if (typeof value.value === "number") {
registerValues[registerNum] = new LiteralValue({
num: value.value,
});
} else if ("id" in value.value || "num" in value.value) {
registerValues[registerNum] = new LiteralValue(value.value);
} else {
this.#error("Invalid link value type", value.node);
}
}
const to = link.value["to"];
if (to != null) {
const tos: ParsedLiteral[] = Array.isArray(to.value)
? to.value
: [to];
for (const to of tos) {
if (
typeof to.value !== "string" &&
typeof to.value !== "number"
) {
this.#error("Invalid to link type", to.node);
}
registerLinks.push({
from: registerNum,
to: to.value,
node: to.node,
});
}
}
}
}
};
updateLinks(Math.abs(regNums.signal), parsedBlueprint.signal);
updateLinks(Math.abs(regNums.visual), parsedBlueprint.visual);
updateLinks(Math.abs(regNums.store), parsedBlueprint.store);
updateLinks(Math.abs(regNums.goto), parsedBlueprint.goto);
let registerIndex = 5;
for (let socketIndex = 0; socketIndex < allSockets.length; socketIndex++) {
const socketType = allSockets[socketIndex];
const socketsOfType = parsedBlueprint[socketType.toLowerCase()];
if (socketsOfType?.value == null) {
continue;
}
if (!Array.isArray(socketsOfType.value)) {
this.#error(`${socketType} must be array`, socketsOfType.node);
}
if (socketsOfType.value.length === 0) {
continue;
}
const component = socketsOfType.value.shift();
if (component?.value == null) {
continue;
}
if (typeof component.value !== "object") {
this.#error(`${socketType} socket must be object`, component.node);
}
const id = component.value["id"] as ParsedLiteral;
if (id == null || typeof id.value !== "string") {
this.#error(`${socketType} socket id must be string`, id.node);
}
const componentData = gameData.components.get(id.value);
if (componentData == null) {
this.#error(`Unknown component: ${id.value}`, id.node);
}
const behavior = component.value["behavior"] as ParsedLiteral;
let componentRegisters: Array<{}>;
const componentRegisterNames: Map<string, number> = new Map();
if (behavior != null) {
// If the component has a behavior then look up the subroutine to get register (parameter) count
if (
typeof behavior.value !== "string" ||
!this.subs.has(behavior.value)
) {
this.#error(
`${socketType} socket behavior must be reference to function`,
behavior.node,
);
}
const sub = this.subs.get(behavior.value)!;
componentRegisters = sub.parameters.map((p) => ({}));
for (
let parameterIndex = 0;
parameterIndex < sub.parameters.length;
parameterIndex++
) {
const parameter = sub.parameters[parameterIndex];
if (!ts.isIdentifier(parameter.name)) {
this.#error("Parameter name must be identifier", parameter);
}
const parameterName = parameter.name.text;
componentRegisterNames.set(parameterName, parameterIndex);
if (!duplicateBehaviorControllerParameterNames.has(parameterName)) {
if (behaviorControllerParameterNames.has(parameterName)) {
behaviorControllerParameterNames.delete(parameterName);
duplicateBehaviorControllerParameterNames.add(parameterName);
} else {
behaviorControllerParameterNames.set(
parameterName,
registerIndex + parameterIndex,
);
}
}
}
} else {
// Otherwise the componentData will tell us how many registers this component has
componentRegisters = componentData.registers ?? [];
}
const links = component.value["links"] as ParsedLiteral;
if (links != null) {
if (Array.isArray(links.value)) {
for (let linkIndex = 0; linkIndex < links.value.length; linkIndex++) {
const item = links.value[linkIndex];
const registerNum = registerIndex + linkIndex;
if (linkIndex >= componentRegisters.length) {
this.#error(
`Component only has ${componentRegisters.length} registers`,
item.node,
);
}
updateLinks(registerNum, item);
}
} else if (typeof links.value === "object") {
for (const key in links.value) {
const item = links.value[key];
const linkIndex = componentRegisterNames.get(key) ?? key;
const linkIndexNum = Number(linkIndex);
if (isNaN(linkIndexNum) || linkIndexNum < 0) {
this.#error(
`Socket links object keys must be positive numbers`,
links.node,
);
}
if (linkIndexNum >= componentRegisters.length) {
this.#error(
`Component only has ${componentRegisters.length} registers`,
item.node,
);
}
const registerNum = registerIndex + Number(linkIndex);
updateLinks(registerNum, item);
}
} else {
this.#error(
`${socketType} socket links must be array or object`,
links.node,
);
}
}
registerIndex += componentRegisters.length;
if (behavior?.value == null) {
this.#rawEmit(
".component",
new LiteralValue({ num: socketIndex + 1 }),
new LiteralValue({ id: id.value }),
);
} else {
this.#rawEmit(
".component",
new LiteralValue({ num: socketIndex + 1 }),
new LiteralValue({ id: id.value }),
new Label(behavior.value as string),
);
}
}
if (parsedBlueprint.locks != null) {
if (!Array.isArray(parsedBlueprint.locks.value)) {
this.#error("Locks must be array", parsedBlueprint.locks.node);
}
for (let i = 0; i < parsedBlueprint.locks.value.length; i++) {
const lock = parsedBlueprint.locks.value[i];
if (typeof lock.value === "string") {
this.#rawEmit(
".lock",
new LiteralValue({ num: i }),
new LiteralValue({ id: lock.value }),
);
} else if (typeof lock.value === "boolean") {
this.#rawEmit(
".lock",
new LiteralValue({ num: i }),
lock.value ? TRUE : FALSE,
);
} else if (lock.value != null) {
this.#error(
"Locks must be string or boolean",
parsedBlueprint.locks.node,
);
}
}
}
// Emit the literal values for registers
for (const key in registerValues) {
this.#rawEmit(
".reg",
new LiteralValue({ num: Number(key) - 1 }),
registerValues[key],
);
}
const resolvedLinks = new Set<string>();
for (const registerLink of registerLinks) {
let to: number;
if (typeof registerLink.to === "number") {
to = registerLink.to;
} else {
const resolvedTo =
registerNames.get(registerLink.to) ??
behaviorControllerParameterNames.get(registerLink.to);
if (resolvedTo == null) {
this.#error(
`Unknown register name: ${registerLink.to}`,
registerLink.node,
);
}
to = resolvedTo;
}
const linkId = `${registerLink.from}|${to}`;
if (resolvedLinks.has(linkId)) continue;
resolvedLinks.add(linkId);
this.#rawEmit(
".link",
new LiteralValue({ num: to }),
new LiteralValue({ num: registerLink.from }),
);
}
}
parseBlueprint(n: ts.ObjectLiteralExpression) {
return this.#parseLiteral(n, {
call: (call, handlers) => {
if (ts.isPropertyAccessExpression(call.expression)) {
const functionName = call.expression.name.text;
const thisArg = call.expression.expression;
if (!ts.isIdentifier(thisArg)) {
this.#error(
`Property access must be on identifier: ${ts.SyntaxKind[thisArg.kind]}`,
thisArg,
);
}
switch (thisArg.text) {
case "component": {
const jsName = functionName;
const component = gameData.componentsByJsName.get(jsName);
if (component == null) {
this.#error(`Unknown component: ${jsName}`, call.expression);
}
const hasBehaviorArgument = component.id === "c_behavior";
if (call.arguments.length > 2) {
this.#error(
"Component function accept 0, 1 or 2 arguments",
call,
);
}
if (!hasBehaviorArgument && call.arguments.length === 2) {
// only behaviorControllers accept 3 arguments
this.#error("Component function accepts 1 argument", call);
}
let behavior: SpecificLiteral<string> | null = null;
let links: ParsedLiteral | null = null;
let argIdx = 0;
if (call.arguments.length > argIdx && hasBehaviorArgument) {
const arg = call.arguments[argIdx];
const parsed = this.#parseLiteral(arg, {
...handlers,
identifier: (identifier, handlers) => {
return identifier.text;
},
});
if (parsed.value == null) {
behavior = null;
} else if (typeof parsed.value === "string") {
behavior = parsed as SpecificLiteral<string>;
} else {
this.#error(
`Behavior reference must be an identifier: ${ts.SyntaxKind[call.arguments[argIdx].kind]}`,
call.arguments[argIdx],
);
}
argIdx++;
}
if (call.arguments.length > argIdx) {
const arg = call.arguments[argIdx];
links = this.#parseLiteral(arg, {
...handlers,
identifier: (identifier, handlers) => {
if (identifier.text in regNums) {
return Math.abs(regNums[identifier.text]);
}
return (
handlers.identifier?.(identifier, handlers) ??
this.#error(
`Unsupported identifier: ${identifier.text}`,
identifier,
)
);
},
});
argIdx++;
}
return {
id: {
node: call.expression.name,
value: component.id,
} as SpecificLiteral<string>,
behavior,
links,
};
}
}
} else if (ts.isIdentifier(call.expression)) {
const functionName = call.expression.text;
switch (functionName) {
case "from":
case "to": {
const values: string[] = [];
for (const argument of call.arguments) {
const parsed = this.#parseLiteral(argument, handlers);
if (typeof parsed.value !== "string") {
this.#error(
`${functionName} function accept string literal argument`,
call,
);
}
values.push(parsed.value);
}
return { [functionName]: values };
}
case "value": {
return this.builtins.value(call).value;
}
}
}
this.#error(
`Unsupported call: ${call.expression.getText()} (${ts.SyntaxKind[call.expression.kind]})`,
call,
);
},
}).value;
}
countOutputs(f: ts.FunctionDeclaration): number {
if (f.type) {
if (ts.isTypeReferenceNode(f.type)) {
return 1;
} else if (ts.isTupleTypeNode(f.type)) {
return f.type.elements.length;
} else {
this.#error(`Unsupported return type.`, f.type);
}
}
return 0;
}
compileInstructions(f: ts.FunctionDeclaration) {
f.parameters.forEach((param, i) => {
const name = param.name.getText();
const reg = new RegRef(i + 1);
this.currentScope.paramCounter = i + 1;
this.#rawEmit(".pname", reg, new StringLiteral(name));
this.variable(param.name as ts.Identifier, reg);
});
let outsCount = this.countOutputs(f);
for (let outIndex = 0; outIndex < outsCount; outIndex++) {
this.currentScope.addOutputParameter();
}
f.body?.statements.forEach(this.compileStatement.bind(this));
this.#rawEmit(".ret");
this.#regAlloc();
}
#regAlloc() {
// TODO: could probably do better dataflow analysis if we used SSA.
const availables = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
.split("")
.map((c) => new RegRef(c));
let newParameters = this.currentScope.scope.allocate(
availables,
this.currentScope.paramCounter,
);
for (let i = 0; i < newParameters; ++i) {
let reg = new RegRef(++this.currentScope.paramCounter);
this.#rawEmit(".pname", reg, new LiteralValue({ id: `temp` }));
}
}
comment(txt: string) {
this.currentScope.program.code[
this.currentScope.program.code.length - 1
].comment = txt;
}
compileStatement(n: ts.Statement) {
if (ts.isExpressionStatement(n)) {