-
Notifications
You must be signed in to change notification settings - Fork 245
Expand file tree
/
Copy pathCompiler.cs
More file actions
2825 lines (2473 loc) · 122 KB
/
Copy pathCompiler.cs
File metadata and controls
2825 lines (2473 loc) · 122 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
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
using System;
using System.Collections.Generic;
using System.Linq;
using kOS.Safe.Exceptions;
using kOS.Safe.Utilities;
using kOS.Safe.Execution;
using kOS.Safe.Encapsulation;
using System.Text;
namespace kOS.Safe.Compilation.KS
{
class Compiler : IExpressionVisitor
{
private CodePart part;
private Context context;
private List<Opcode> currentCodeSection;
private bool addBranchDestination;
private ParseNode lastNode;
private int startLineNum;
private short lastLine;
private short lastColumn;
private readonly List<BreakInfo> breakList = new List<BreakInfo>();
private readonly List<int> returnList = new List<int>();
private readonly List<string> triggerKeepNames = new List<string>();
private bool nowCompilingTrigger;
private bool nowInALoop;
private bool needImplicitReturn;
private bool nextBraceIsFunction;
private bool allowLazyGlobal;
/// <summary>Used when you want to set the next opcode's label but there's many places the next AddOpcode call might happen in the code</summary>
private string forcedNextLabel;
private Int16 braceNestLevel;
private readonly List<Int16> scopeStack = new List<Int16>();
private readonly Dictionary<ParseNode, Scope> scopeMap = new Dictionary<ParseNode, Scope>();
private CompilerOptions options;
private const bool TRACE_PARSE = false; // set to true to Debug Log each ParseNode as it's visited.
private string boilerplateLoadAndRunEntryLabel;
private enum StorageModifier {
/// <summary>The storage will definitely be at the localmost scope.</summary>
LOCAL,
/// <summary>The storage will definitely be at the globalmost scope.</summary>
GLOBAL,
/// <summary>The storage will be whatever scope it happens to find the first hit, or global if not found.</summary>
LAZYGLOBAL
};
// Because the Compiler object can be re-used, with its Compile()
// method called a second time, we can't rely on the constructor or C#'s rules about default
// variable values to guarantee these are all set properly. They might be leftover values
// from a previous aborted use of Compiler.Compile(). I've noticed sometimes after an
// error I end up with the very next command always failing even when it's right, and
// only the next command after that works right, and I suspect this was why - these
// weren't being reset after a failed compile.
private void InitCompileFlags()
{
addBranchDestination = false;
lastNode = null;
startLineNum = 1;
lastLine = 0;
lastColumn = 0;
breakList.Clear();
returnList.Clear();
triggerKeepNames.Clear();
nowCompilingTrigger = false;
nowInALoop = false;
needImplicitReturn = true;
braceNestLevel = 0;
nextBraceIsFunction = false;
allowLazyGlobal = true;
forcedNextLabel = String.Empty;
scopeStack.Clear();
scopeMap.Clear();
// Zero-th instruction of the loader/runner that will have to be built by something
// outside of Compiler.cs (probably ProgramBuilder.cs - look there to find it).
boilerplateLoadAndRunEntryLabel = "@LR00";
}
public CodePart Compile(int startLineNum, ParseTree tree, Context context, CompilerOptions options)
{
InitCompileFlags();
part = new CodePart();
this.context = context;
this.options = options;
this.startLineNum = startLineNum;
++context.NumCompilesSoFar;
if (tree.Nodes.Count > 0)
{
PreProcess(tree);
CompileProgram(tree);
}
return part;
}
private void CompileProgram(ParseTree tree)
{
currentCodeSection = part.MainCode;
VisitNode(tree.Nodes[0]);
if (addBranchDestination || currentCodeSection.Count == 0)
{
AddOpcode(new OpcodeNOP());
}
}
/// <summary>
/// Set the current line/column info and potentially also make a helpful
/// debug trace useful when making syntax changes.
/// </summary>
private void NodeStartHousekeeping(ParseNode node)
{
if (node == null) { throw new ArgumentNullException("node"); }
if (TRACE_PARSE)
SafeHouse.Logger.Log("traceParse: visiting node: " + node.Token.Type.ToString() + ", " + node.Token.Text);
LineCol location = GetLineCol(node);
lastLine = location.Line;
lastColumn = location.Column;
}
/// <summary>
/// Get a line number and column for a given parse node. Handles the
/// fact that TinyPG does not provide line and col information for all
/// nodes - just the terminals. This means if you, say, ask for the
/// line or column of a complex node like an expression, you get the bogus answer 0,0 back
/// from TinyPG normally. This method performs a leftmost walk of the
/// parse tree to get the first instance where a token exists with actual
/// line and column information populated, and returns that.
/// </summary>
/// <param name="node">The node to get the line number for</param>
/// <returns>line and column pair of the firstmost terminal within the parse node</returns>
private LineCol GetLineCol(ParseNode node)
{
if (node.Token == null || node.Token.Line <= 0)
{
foreach (ParseNode child in node.Nodes)
{
LineCol candidate = GetLineCol(child);
if (candidate.Line >= 0)
return candidate;
}
}
return new LineCol( (node.Token.Line + (startLineNum - 1)), (node.Token.Column) );
}
private Opcode AddOpcode(Opcode opcode, string destinationLabel)
{
opcode.Label = GetNextLabel(true);
opcode.DestinationLabel = destinationLabel;
opcode.SourceLine = lastLine;
opcode.SourceColumn = lastColumn;
currentCodeSection.Add(opcode);
addBranchDestination = false;
return opcode;
}
private Opcode AddOpcode(Opcode opcode)
{
Opcode code = AddOpcode(opcode, string.Empty);
if (! String.IsNullOrEmpty(forcedNextLabel))
{
code.Label = forcedNextLabel;
forcedNextLabel = String.Empty;
}
return code;
}
private string GetNextLabel(bool increment)
{
string newLabel = string.Format("@{0:0000}", context.LabelIndex + 1);
if (increment) context.LabelIndex++;
return newLabel;
}
private void PreProcess(ParseTree tree)
{
ParseNode rootNode = tree.Nodes[0];
LowercaseConversions(rootNode);
RearrangeParseNodes(rootNode);
TraverseScopeBranch(rootNode);
IterateUserFunctions(rootNode, IdentifyUserFunctions);
PreProcessStatements(rootNode);
IterateUserFunctions(rootNode, PreProcessUserFunctionStatement);
}
/// <summary>
/// Lowercase every IDENTIFIER and FILEIDENT token in the parse.
/// </summary>
/// <param name="node">branch head to start from in the compiler</param>
private void LowercaseConversions(ParseNode node)
{
switch (node.Token.Type)
{
case TokenType.IDENTIFIER:
case TokenType.FILEIDENT:
node.Token.Text = node.Token.Text.ToLower();
break;
default:
foreach (ParseNode child in node.Nodes)
LowercaseConversions(child);
break;
}
}
/// <summary>
/// Some of the parse rules in Kerboscript may be implemented on the back
/// of other rules. In this case all the compiler really does is just
/// re-arrange a more complex parse rule to be expressed in the form of
/// building blocks made of other simpler rules before continuing the compile that way.
/// </summary>
/// <param name="node">make the transformation from this point downward</param>
private void RearrangeParseNodes(ParseNode node)
{
if (node.Token.Type == TokenType.fromloop_stmt) // change to switch stmt if more such rules get added later.
{
RearrangeLoopFromNode(node);
}
// Recurse children EVEN IF the node got re-arranged. If the node got re-arranged, then its children will now look
// different than they did before, but they still need to be iterated over to look for other rearrangements.
// (for example, a loopfrom loop nested inside another loopfrom loop).
foreach (ParseNode child in node.Nodes)
RearrangeParseNodes(child);
}
private void IterateUserFunctions(ParseNode node, Action<ParseNode> action)
{
bool doChildren = true;
bool doInvoke = false;
switch (node.Token.Type)
{
// Any statement which might have another statement nested inside
// it should be recursed into to check if that other statement
// might be a lock, or a user function (anonymous or named).
//
// We assume by default a node should be recursed into unless explicitly
// told otherwise here. Doing it this way around is the safer default
// because of what happens when we fail to mention a part of speech here.
// If we fail to recurse when we should have, that can be fatal as it makes
// the compiler produce wrong code. But if we do recurse when we didn't have
// to, that just wastes a bit of CPU time, which isn't as bad.
//
case TokenType.onoff_trailer:
case TokenType.stage_stmt:
case TokenType.clear_stmt:
case TokenType.break_stmt:
case TokenType.preserve_stmt:
case TokenType.run_stmt:
case TokenType.compile_stmt:
case TokenType.list_stmt:
case TokenType.reboot_stmt:
case TokenType.shutdown_stmt:
case TokenType.unset_stmt:
case TokenType.sci_number:
case TokenType.number:
case TokenType.INTEGER:
case TokenType.DOUBLE:
case TokenType.PLUSMINUS:
case TokenType.MULT:
case TokenType.DIV:
case TokenType.POWER:
case TokenType.IDENTIFIER:
case TokenType.FILEIDENT:
case TokenType.STRING:
case TokenType.TRUEFALSE:
case TokenType.COMPARATOR:
case TokenType.AND:
case TokenType.OR:
case TokenType.directive:
doChildren = false;
break;
// These are the statements we're searching for to work on here:
//
case TokenType.declare_stmt: // for DECLARE FUNCTION's.
case TokenType.instruction_block: // just in case it's an anon function's body
doInvoke = true;
break;
default:
break;
}
// for catching functions nested inside functions, or locks nested inside functions:
// Depth-first: Walk my children first, then iterate through me. Thus the functions nested inside
// me have already been compiled before I start compiling my own code. This allows my code to make
// forward-calls into my nested functions, because they've been compiled and we know where they live
// in memory now.
if (doChildren)
foreach (ParseNode childNode in node.Nodes)
IterateUserFunctions(childNode, action);
if (doInvoke)
action.Invoke(node);
}
/// <summary>
/// Edit the parse branch for a loopfrom statement, rearranging its component
/// parts into a simpler unrolled form.<br/>
/// When given this rule:<br/>
/// <br/>
/// FROM {(init statements)} UNTIL expr STEP {(inc statements)} DO {(body statements)} <br/>
/// <br/>
/// It will edit its own child nodes and transform them into a new parse tree branch as if this had
/// been what was in the source code instead:<br/>
/// <br/>
/// { (init statements) UNTIL expr { (body statements) (inc statements) } }<br/>
/// <br/>
/// Thus any variables declared inside (init statements) are in scope during the body of the loop.<br/>
/// The actual logic of doing an UNTIL loop will fall upon VisitUntilNode to deal with later in the compile.<br/>
/// </summary>
/// <param name="node"></param>
private void RearrangeLoopFromNode(ParseNode node)
{
// Safety check to see if I've already been rearranged into my final form, just in case
// the recursion logic is messed up and this gets called twice on the same node:
if (node.Nodes.Count == 1 && node.Nodes[0].Token.Type == TokenType.instruction_block)
return;
// ReSharper disable RedundantDefaultFieldInitializer
ParseNode initBlock = null;
ParseNode checkExpression = null;
ParseNode untilTokenNode = null;
ParseNode stepBlock = null;
ParseNode doBlock = null;
// ReSharper enable RedundantDefaultFieldInitializer
for( int index = 0 ; index < node.Nodes.Count - 1 ; index += 2 )
{
switch (node.Nodes[index].Token.Type)
{
case TokenType.FROM:
initBlock = node.Nodes[index+1];
break;
case TokenType.UNTIL:
untilTokenNode = node.Nodes[index];
checkExpression = node.Nodes[index+1];
break;
case TokenType.STEP:
stepBlock = node.Nodes[index+1];
break;
case TokenType.DO:
doBlock = node.Nodes[index+1];
break;
// no default because anything else is a syntax error and it won't even get as far as this method in that case.
}
}
// These probably can't happen because the parser would have barfed before it got to this method:
if (initBlock == null)
throw new KOSCompileException(node.Token, "Missing FROM block in FROM loop.");
if (checkExpression == null || untilTokenNode == null)
throw new KOSCompileException(node.Token, "Missing UNTIL check expression in FROM loop.");
if (stepBlock == null)
throw new KOSCompileException(node.Token, "Missing STEP block in FROM loop.");
if (doBlock == null)
throw new KOSCompileException(node.Token, "Missing loop body (DO block) in FROM loop.");
// Append the step instructions to the tail end of the body block's instructions:
foreach (ParseNode child in stepBlock.Nodes)
doBlock.Nodes.Add(child);
// Make a new empty until loop node, which will get added to the init block eventually:
var untilStatementTok = new Token
{
Type = TokenType.until_stmt,
Line = untilTokenNode.Token.Line,
Column = untilTokenNode.Token.Column,
File = untilTokenNode.Token.File
};
ParseNode untilNode = initBlock.CreateNode(untilStatementTok, untilStatementTok.ToString());
// (The direct manipulation of the tree's parent pointers, seen below, is bad form,
// but TinyPg doesn't seem to have given us good primitives to append an existing node to the tree to do it for us.
// CreateNode() makes a brand new empty node attached to the parent, but there seems to be no way to take an
// existing node and attach it elsewhere without directly changing the Parent property as seen in the lines below:)
// Populate that until loop node with the parts from this rule:
untilNode.Nodes.Add(untilTokenNode); untilTokenNode.Parent = untilNode;
untilNode.Nodes.Add(checkExpression); checkExpression.Parent = untilNode;
untilNode.Nodes.Add(doBlock); doBlock.Parent = untilNode;
// And now append that until loop to the tail end of the init block:
initBlock.Nodes.Add(untilNode); // parent already assigned by initBlock.CreateNode() above.
// The init block is now actually the entire loop, having been exploded and unrolled into its
// new form, make that be our only node:
node.Nodes.Clear();
node.Nodes.Add(initBlock); // initBlock's parent already points at node to begin with.
// The FROM loop node is still in the parent's list, but it contains this new rearranged sub-tree
// instead of its original.
}
private void PreProcessStatements(ParseNode node)
{
lastNode = node;
NodeStartHousekeeping(node);
switch (node.Token.Type)
{
// statements that can have a lock inside
case TokenType.Start:
case TokenType.instruction_block:
case TokenType.instruction:
case TokenType.if_stmt:
case TokenType.fromloop_stmt:
case TokenType.until_stmt:
case TokenType.for_stmt:
case TokenType.declare_function_clause:
case TokenType.declare_stmt:
PreProcessChildNodes(node);
break;
case TokenType.on_stmt:
PreProcessChildNodes(node);
PreProcessOnStatement(node);
break;
case TokenType.when_stmt:
PreProcessChildNodes(node);
PreProcessWhenStatement(node);
break;
}
}
private void PreProcessChildNodes(ParseNode node)
{
foreach (ParseNode childNode in node.Nodes)
{
PreProcessStatements(childNode);
}
}
private void PreProcessOnStatement(ParseNode node)
{
NodeStartHousekeeping(node);
nextBraceIsFunction = true; // triggers aren't really functions but act like it a lot.
int expressionHash = ConcatenateNodes(node).GetHashCode();
string triggerIdentifier = "on-" + expressionHash.ToString();
Trigger triggerObject = context.Triggers.GetTrigger(triggerIdentifier);
// - - - - - - - - - - - -
// TODO: If we ever implement triggers that can be named and cancelled by name later,
// then right here we'd need to add some opcodes that implement the same logic as
// the cooked steering triggers use (check OpcodeTestCancelled and premature return
// if this trigger has been cancelled elsewhere before we begin running it.)
// - - - - - - - - - - - -
currentCodeSection = triggerObject.Code;
// Put the old value on top of the stack for equals comparison later:
AddOpcode(new OpcodePush(triggerObject.OldValueIdentifier));
AddOpcode(new OpcodeEval());
// eval the expression for the new value, and leave it on the stack twice.
VisitExpression(node.Nodes[1]);
AddOpcode(new OpcodeEval());
AddOpcode(new OpcodeDup());
// Put one of those two copies of the new value into the old value identifier for next time:
AddOpcode(new OpcodeStoreGlobal(triggerObject.OldValueIdentifier));
// Use the other dup'ed copy of the new value to actually do the equals
// comparison with the old value that's still under it on the stack:
AddOpcode(new OpcodeCompareEqual());
OpcodeBranchIfFalse branchToBody = new OpcodeBranchIfFalse();
branchToBody.Distance = 3;
AddOpcode(branchToBody);
AddOpcode(new OpcodePush(true)); // wasn't triggered yet, so preserve.
AddOpcode(new OpcodeReturn((short)0)); // premature return because it wasn't triggered
// make flag that remembers whether to remove trigger:
// defaults to true = removal should happen.
string triggerKeepName = "$keep-" + triggerIdentifier;
PushTriggerKeepName(triggerKeepName);
AddOpcode(new OpcodePush(false));
AddOpcode(new OpcodeStoreGlobal(triggerKeepName));
VisitNode(node.Nodes[2]);
// PRESERVE will determine whether or not the trigger returns true (true means
// re-enable the trigger upon exit.)
PopTriggerKeepName();
AddOpcode(new OpcodePush(triggerKeepName));
AddOpcode(new OpcodeReturn((short)0));
nextBraceIsFunction = false;
}
private void PreProcessWhenStatement(ParseNode node)
{
NodeStartHousekeeping(node);
nextBraceIsFunction = true; // triggers aren't really functions but act like it a lot.
int expressionHash = ConcatenateNodes(node).GetHashCode();
string triggerIdentifier = "when-" + expressionHash.ToString();
Trigger triggerObject = context.Triggers.GetTrigger(triggerIdentifier);
// - - - - - - - - - - - -
// TODO: If we ever implement triggers that can be named and cancelled by name later,
// then right here we'd need to add some opcodes that implement the same logic as
// the cooked steering triggers use (check OpcodeTestCancelled and premature return
// if this trigger has been cancelled elsewhere before we begin running it.)
// - - - - - - - - - - - -
currentCodeSection = triggerObject.Code;
VisitExpression(node.Nodes[1]);
OpcodeBranchIfTrue branchToBody = new OpcodeBranchIfTrue();
branchToBody.Distance = 3;
AddOpcode(branchToBody);
AddOpcode(new OpcodePush(true)); // wasn't triggered yet, so preserve.
AddOpcode(new OpcodeReturn((short)0)); // premature return because it wasn't triggered
// make flag that remembers whether to remove trigger:
// defaults to true = removal should happen.
string triggerKeepName = "$keep-" + triggerIdentifier;
PushTriggerKeepName(triggerKeepName);
AddOpcode(new OpcodePush(false));
AddOpcode(new OpcodeStoreGlobal(triggerKeepName));
VisitNode(node.Nodes[3]);
// PRESERVE will determine whether or not the trigger returns true (true means
// re-enable the trigger upon exit.)
PopTriggerKeepName();
AddOpcode(new OpcodePush(triggerKeepName));
AddOpcode(new OpcodeReturn((short)0));
nextBraceIsFunction = false;
}
/// <summary>
/// Create a unique string out of a sub-branch of the parse tree that
/// can be used to uniquely identify it. The purpose is so that two
/// sub-branches of the parse tree can be compared to see if they are
/// the exact same code as each other.
/// </summary>
private string ConcatenateNodes(ParseNode node)
{
LineCol whereNodeIs = GetLineCol(node);
return string.Format("{0}L{1}C{2}{3}{4}",
context.NumCompilesSoFar,
whereNodeIs.Line,
whereNodeIs.Column,
GetContainingScopeId(node),
ConcatenateNodesRecurse(node));
}
private string ConcatenateNodesRecurse(ParseNode node)
{
string concatenated = string.Format("{0}{1}", context.NumCompilesSoFar, node.Token.Text);
if (node.Nodes.Any())
{
return node.Nodes.Aggregate(concatenated, (current, childNode) => current + ConcatenateNodesRecurse(childNode));
}
return concatenated;
}
private void IdentifyUserFunctions(ParseNode node)
{
if (node.Nodes.Count <= 0 )
return;
string funcIdentifier;
StorageModifier storageType = GetStorageModifierFor(node);
ParseNode bodyNode;
ParseNode lastSubNode = node.Nodes[node.Nodes.Count-1];
bool isLock = IsLockStatement(node);
if (isLock)
{
funcIdentifier = lastSubNode.Nodes[1].Token.Text;
bodyNode = lastSubNode.Nodes[3];
}
else if (IsDefineFunctionStatement(node))
{
funcIdentifier = lastSubNode.Nodes[1].Token.Text;
bodyNode = lastSubNode.Nodes[2];
}
else
return; // not one of the types of statement we're really meant to run IdentifyUserFunctions on.
UserFunction userFuncObject =
context.UserFunctions.GetUserFunction(funcIdentifier, storageType == StorageModifier.GLOBAL ? (Int16)0 : GetContainingScopeId(node), node);
int expressionHash = ConcatenateNodes(bodyNode).GetHashCode();
userFuncObject.GetUserFunctionOpcodes(expressionHash);
userFuncObject.IsFunction = !isLock;
if (userFuncObject.IsSystemLock())
BuildSystemTrigger(userFuncObject);
}
/// <summary>
/// Walk up the parent chain finding the first instance of a
/// ParseNode for which a scope ID has been assigned to it, and
/// return that scope ID. Returns 0 (the global scope) when no
/// hit was found.
/// <br/>
/// That will usually be the containing instruction_block braces,
/// but might not be, if dealing with file scoping, or the
/// hidden extra scopes of FOR loops and so on.
/// </summary>
/// <param name="node"></param>
/// <returns></returns>
private Int16 GetContainingScopeId(ParseNode node)
{
ParseNode current = node;
while (current != null)
{
Scope hitScope;
if (scopeMap.TryGetValue(current, out hitScope))
return hitScope.ScopeId;
current = current.Parent;
}
return 0;
}
/// <summary>
/// Much like UserFunctionCollection.GetUserFunction(), except that it won't
/// generate a function if one doesn't exist. Instead it will try to walk up
/// the parent scopes until it finds a func or lock with the given name. If it
/// cannot find an existing function, it will return null rather than make one.
/// </summary>
/// <param name="funcIdentifier">identifier for the lock or function</param>
/// <param name="node">ParseNode to begin looking from (for scope reasons). It will walk the parents looking for scopes that have the ident.</param>
/// <returns>The found UserFunction, or null if none found</returns>
private UserFunction FindExistingUserFunction(string funcIdentifier, ParseNode node)
{
for (ParseNode containingNode = node ; containingNode != null ; containingNode = containingNode.Parent)
{
Int16 thisNodeScope = GetContainingScopeId(containingNode);
if (context.UserFunctions.Contains(funcIdentifier, thisNodeScope))
return context.UserFunctions.GetUserFunction(funcIdentifier, thisNodeScope, containingNode);
}
return null;
}
private bool IsLockStatement(ParseNode node)
{
return
node.Token.Type == TokenType.declare_stmt &&
node.Nodes[node.Nodes.Count-1].Token.Type == TokenType.declare_lock_clause;
}
private bool IsDefineFunctionStatement(ParseNode node)
{
if (node.Nodes.Count > 0)
{
ParseNode lastSubNode = node.Nodes[node.Nodes.Count-1];
if (lastSubNode.Token.Type == TokenType.declare_function_clause)
return true;
}
return false;
}
private bool IsInsideDefineFunctionStatement(ParseNode node)
{
while (node != null)
{
if (IsDefineFunctionStatement(node))
return true;
node = node.Parent;
}
return false;
}
// This is actually used for BOTH LOCK expressions and DEFINE FUNCTIONs, as they
// both end up creating, effectively, a user function.
private void PreProcessUserFunctionStatement(ParseNode node)
{
NodeStartHousekeeping(node);
// The name of the lock or function to be executed:
string userFuncIdentifier;
// The syntax node for the body of the lock or function: the stuff it actually executes.
ParseNode bodyNode;
bool isLock = IsLockStatement(node);
bool isDefFunc = IsDefineFunctionStatement(node);
bool needImplicitArgBottom = false;
StorageModifier storageType = GetStorageModifierFor(node);
ParseNode lastSubNode = node.Nodes[node.Nodes.Count-1];
if (isLock)
{
userFuncIdentifier = lastSubNode.Nodes[1].Token.Text; // The IDENT of: LOCK IDENT TO EXPR.
bodyNode = lastSubNode.Nodes[3]; // The EXPR of: LOCK IDENT TO EXPR.
needImplicitArgBottom = true;
}
else if (isDefFunc)
{
userFuncIdentifier = lastSubNode.Nodes[1].Token.Text; // The IDENT of: DEFINE FUNCTION IDENT INSTRUCTION_BLOCK.
bodyNode = lastSubNode.Nodes[2]; // The INSTRUCTION_BLOCK of: DEFINE FUNCTION IDENT INSTRUCTION_BLOCK.
}
else
return; // Should only be the case when scanning elements for anonymous functions
UserFunction userFuncObject = context.UserFunctions.GetUserFunction(
userFuncIdentifier,
(storageType == StorageModifier.GLOBAL ? (Int16)0 : GetContainingScopeId(node)),
node );
int expressionHash = ConcatenateNodes(bodyNode).GetHashCode();
needImplicitReturn = true; // Locks always need an implicit return. Functions might not if all paths have an explicit one.
// Both locks and functions also get an identifier storing their
// destination instruction pointer, but the means of doing so
// is slightly different. Locks always need a dummy do-nothing
// function to exist at first, which then can get replaced later
// when the statement containing the lock definition is encountered.
// Whereas, function bodies don't get overwritten like that. They
// exist exactly once, and can be "forward" called from higher up in
// the same scope so they get assigned when the scope is first opened.
//
if (isLock && !userFuncObject.IsInitialized())
{
currentCodeSection = userFuncObject.InitializationCode;
if (userFuncObject.IsSystemLock())
{
AddOpcode(new OpcodePush(userFuncObject.ScopelessPointerIdentifier));
AddOpcode(new OpcodeExists());
var branch = new OpcodeBranchIfTrue();
branch.Distance = 4;
AddOpcode(branch);
AddOpcode(new OpcodePushRelocateLater(null), userFuncObject.DefaultLabel);
AddOpcode(new OpcodeStore(userFuncObject.ScopelessPointerIdentifier));
}
else
{
// initialization code - unfortunately the lock implementation presumed global namespace
// and insisted on inserting an initialization block in front of the entire program to set up
// the GLOBAL lock value. This assumption was thorny to remove, so for now, we'll make the init
// code consist of a dummy NOP until a better solution can be found. Note this does put a NOP
// into the code PER LOCK. Which is silly. It's because lockObject.IsInitialized() doesn't
// know how to tell the difference between initialization code that's deliberately empty versus
// initialization code being empty because the lock has never been set up properly yet.
AddOpcode(new OpcodeNOP());
}
// build default dummy function to be used when this is a LOCK:
currentCodeSection = userFuncObject.GetUserFunctionOpcodes(0);
AddOpcode(new OpcodeArgBottom()).Label = userFuncObject.DefaultLabel;;
AddOpcode(new OpcodePush("$" + userFuncObject.ScopelessIdentifier));
AddOpcode(new OpcodeReturn(0));
}
// lock expression's or function body's code
currentCodeSection = userFuncObject.GetUserFunctionOpcodes(expressionHash);
bool secondInstanceSameLock = currentCodeSection.Count > 0;
if (! secondInstanceSameLock)
{
forcedNextLabel = userFuncObject.GetUserFunctionLabel(expressionHash);
if (isLock) // locks need to behave as if they had braces even though they don't - so they get lexical scope ids for closure reasons:
BeginScope(bodyNode);
if (isDefFunc)
nextBraceIsFunction = true;
if (needImplicitArgBottom)
AddOpcode(new OpcodeArgBottom());
if (isLock)
{
VisitExpression(bodyNode);
}
else
{
VisitNode(bodyNode);
}
Int16 implicitReturnScopeDepth = 0;
if (isDefFunc)
nextBraceIsFunction = false;
if (isLock) // locks need to behave as if they had braces even though they don't - so they get lexical scope ids for closure reasons:
{
EndScope(bodyNode, false);
implicitReturnScopeDepth = 1;
}
if (needImplicitReturn)
{
if (isDefFunc)
AddOpcode(new OpcodePush(0)); // Functions must push a dummy return val when making implicit returns. Locks already leave an expr atop the stack.
AddOpcode(new OpcodeReturn(implicitReturnScopeDepth));
}
userFuncObject.ScopeNode = GetContainingBlockNode(node); // This limits the scope of the function to the instruction_block the DEFINE was in.
userFuncObject.IsFunction = !(isLock);
}
}
/// <summary>
/// Build the system trigger to go with a user function (lock)
/// such as LOCK STEERING or LOCK THROTTLE
/// </summary>
/// <param name="func">Represents the lock object, which might not be fully populated yet.</param>
private void BuildSystemTrigger(UserFunction func)
{
string triggerIdentifier = "lock-" + func.ScopelessIdentifier;
Trigger triggerObject = context.Triggers.GetTrigger(triggerIdentifier);
if (triggerObject.IsInitialized())
return;
short rememberLastLine = lastLine;
lastLine = -1; // special flag telling the error handler that these opcodes came from the system itself, when reporting the error
List<Opcode> rememberCurrentCodeSection = currentCodeSection;
currentCodeSection = triggerObject.Code;
// Premature return if someone cancelled this trigger from
// within another trigger that fired in the same physics tick:
AddOpcode(new OpcodeTestCancelled());
OpcodeBranchIfFalse proceedOkay = new OpcodeBranchIfFalse();
proceedOkay.Distance = 3;
AddOpcode(proceedOkay);
AddOpcode(new OpcodePush(false)); // Return false. Don't preserve this trigger.
AddOpcode(new OpcodeReturn((short)0));
// Main body:
AddOpcode(new OpcodePush(new KOSArgMarkerType())); // need these for all locks now.
AddOpcode(new OpcodeCall(func.ScopelessPointerIdentifier));
AddOpcode(new OpcodeStoreGlobal("$" + func.ScopelessIdentifier));
AddOpcode(new OpcodePush(true)); // always preserve this particular kind of trigger.
AddOpcode(new OpcodeReturn((short)0));
lastLine = rememberLastLine;
currentCodeSection = rememberCurrentCodeSection;
}
/// <summary>
/// Get the instruction_block (or file Start block at outermost level) this node is immediately inside of.
/// Gives a null if the node isn't in one (it's global).
/// </summary>
private ParseNode GetContainingBlockNode(ParseNode node)
{
while (node != null &&
node.Token.Type != TokenType.instruction_block &&
node.Token.Type != TokenType.Start)
node = node.Parent;
return node;
}
private void PushTriggerKeepName(string newLabel)
{
triggerKeepNames.Add(newLabel);
nowCompilingTrigger = true;
}
private string PeekTriggerKeepName()
{
return nowCompilingTrigger ? triggerKeepNames[triggerKeepNames.Count - 1] : string.Empty;
}
private string PopTriggerKeepName()
{
// Will throw exception if list is empty, but that "should
// never happen" as pushes and pops should be balanced in
// the compiler's code. If it throws exception we want to
// let the exception happen to highlight the bug
string returnVal = triggerKeepNames[triggerKeepNames.Count - 1];
triggerKeepNames.RemoveAt(triggerKeepNames.Count - 1);
nowCompilingTrigger = (triggerKeepNames.Count > 0);
return returnVal;
}
private void PushBreakList(int nestLevel)
{
breakList.Add(new BreakInfo(nestLevel));
}
private void AddToBreakList(Opcode opcode)
{
if (breakList.Count > 0)
{
BreakInfo list = breakList[breakList.Count - 1];
list.Opcodes.Add(opcode);
}
}
private void PopBreakList(string label)
{
if (breakList.Count > 0)
{
BreakInfo list = breakList[breakList.Count - 1];
if (list == null) return;
breakList.Remove(list);
foreach (Opcode opcode in list.Opcodes)
{
OpcodePopScope popScopeOp = opcode as OpcodePopScope;
if (popScopeOp != null)
// calculate how many nesting levels it needs to really pop
// by comparing the nest level where the break statement was to
// the nest level where the break context started:
popScopeOp.NumLevels = (Int16)(popScopeOp.NumLevels - list.NestLevel);
else // assume all others are branch opcodes of some sort:
opcode.DestinationLabel = label;
}
}
}
private void PushReturnList()
{
returnList.Add(braceNestLevel);
}
private void PopReturnList()
{
if (returnList.Count > 0)
returnList.RemoveAt(returnList.Count-1);
}
private int GetReturnNestLevel()
{
return (returnList.Count > 0) ? returnList.Last() : -1;
}
/// <summary>
/// Insert the Opcode to start a new lexical scope, handling the parent id mapping.
/// Call upon every open brace "{"
/// </summary>
private void BeginScope(ParseNode node)
{
// walk up parse tree until a node with a scope is found:
while (node != null && !scopeMap.ContainsKey(node))
node = node.Parent;
// defaults if the node isn't found:
Int16 scopeId = 0;
Int16 parentScopeId = 0;
braceNestLevel = 0;
if (node != null)
{
Scope thisScope = scopeMap[node];
scopeId = thisScope.ScopeId;
parentScopeId = thisScope.ParentScopeId;
braceNestLevel = thisScope.NestDepth;
}
AddOpcode(new OpcodePushScope(scopeId, parentScopeId));
}
/// <summary>
/// Insert the Opcode to finish a lexical scope
/// Call upon every close brace "}"
/// <param name="withPopScope">Should this code insert its own popscope. Only say false when
/// you intend to immediately do a return statement and have the return statement be
/// responsible for the popscope itself.</param>
/// </summary>
private void EndScope(ParseNode node, bool withPopScope = true)
{
node = node.Parent;
// Walk up parse tree starting with my parent, until a node with a scope is found.
// The goal here is to get the scope one level outside the current scope.
while (node != null && ! scopeMap.ContainsKey(node))
node = node.Parent;
if (node != null)
{
Scope thisScope = scopeMap[node];
braceNestLevel = thisScope.NestDepth;
}
else
{
braceNestLevel = 0;
}
if (withPopScope)
AddOpcode(new OpcodePopScope());
}
/// <summary>
/// Because the compile occurs a bit out of order (doing the most deeply nested function
/// first, then working out from there) it walks the scope nesting in the wrong order.
/// Therefore before doing the compile, run through in one pass just recording the nesting
/// levels and lexical parent tree of the scoping before we begin, so we can
/// use that information later in the parse:
/// </summary>
/// <param name="node"></param>
private void TraverseScopeBranch(ParseNode node)
{
switch (node.Token.Type)
{
// List all the types of parse node that open a new variable scope here:
// ---------------------------------------------------------------------
case TokenType.Start: // Here because all programs start with an outer scope block
case TokenType.for_stmt: // Here because it wraps the body inside an outer scope that holds the for-iterator variable.
case TokenType.declare_lock_clause: // here because the lock body needs a scope in order to work with closures. The scope remembers the lexical id.
case TokenType.instruction_block:
++braceNestLevel;
Int16 parentId = ( (scopeStack.Count == 0) ? (Int16)0 : scopeStack.Last() );
scopeStack.Add(++context.MaxScopeIdSoFar);