forked from KSP-KOS/KOS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOpcode.cs
More file actions
2628 lines (2326 loc) · 106 KB
/
Opcode.cs
File metadata and controls
2628 lines (2326 loc) · 106 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.Reflection;
using System.Linq;
using System.Collections.Generic;
using kOS.Safe.Encapsulation;
using kOS.Safe.Encapsulation.Suffixes;
using kOS.Safe.Execution;
using kOS.Safe.Exceptions;
using kOS.Safe.Utilities;
using kOS.Safe.Persistence;
namespace kOS.Safe.Compilation
{
/// A very short numerical ID for the opcode. <br/>
/// When adding a new opcode, remember to also add it to this enum list.<br/>
/// <br/>
/// BACKWARD COMPATIBILITY WARNING:<br/>
/// If a value is ever inserted or
/// deleted from this list, it will cause all existing precompiled kos
/// programs to break.<br/>
/// It will change the meaning of the bytecoes in
/// the compiled files. Try to only tack values onto the end of the list,
/// if possible:
///
public enum ByteCode :byte
{
// It's good practice to always have a zero value in an enum, even if not used:
BOGUS = 0,
// This is the "%" character that will be used as a section delimiter in the
// machine code file - when there's an "instruction" with a ByteCode of '%',
// that means it's not an instruction. It's the start of a different section
// of the program:
DELIMITER = 0x25,
// The explicit picking of the hex numbers is not strictly necessary,
// but it's being done to aid in debugging the ML load/unload process,
// as it makes it possible to look at hexdumps of the machine code
// and compare that to this list:
EOF = 0x31,
EOP = 0x32,
NOP = 0x33,
STORE = 0x34,
UNSET = 0x35,
GETMEMBER = 0x36,
SETMEMBER = 0x37,
GETINDEX = 0x38,
SETINDEX = 0x39,
BRANCHFALSE = 0x3a,
JUMP = 0x3b,
ADD = 0x3c,
SUB = 0x3d,
MULT = 0x3e,
DIV = 0x3f,
POW = 0x40,
GT = 0x41,
LT = 0x42,
GTE = 0x43,
LTE = 0x44,
EQ = 0x45,
NE = 0x46,
NEGATE = 0x47,
BOOL = 0x48,
NOT = 0x49,
AND = 0x4a,
OR = 0x4b,
CALL = 0x4c,
RETURN = 0x4d,
PUSH = 0x4e,
POP = 0x4f,
DUP = 0x50,
SWAP = 0x51,
EVAL = 0x52,
ADDTRIGGER = 0x53,
REMOVETRIGGER = 0x54,
WAIT = 0x55,
// Removing ENDWAIT, 0x56 may be reused in a future version
GETMETHOD = 0x57,
STORELOCAL = 0x58,
STOREGLOBAL = 0x59,
PUSHSCOPE = 0x5a,
POPSCOPE = 0x5b,
STOREEXIST = 0x5c,
PUSHDELEGATE = 0x5d,
BRANCHTRUE = 0x5e,
EXISTS = 0x5f,
ARGBOTTOM = 0x60,
TESTARGBOTTOM = 0x61,
TESTCANCELLED = 0x62,
JUMPSTACK = 0x63,
// Augmented bogus placeholder versions of the normal
// opcodes: These only exist in the program temporarily
// or in the ML file but never actually can be executed.
PUSHRELOCATELATER = 0xce,
PUSHDELEGATERELOCATELATER = 0xcd,
LABELRESET = 0xf0 // for storing the fact that the Opcode.Label's positional index jumps weirdly.
}
/// <summary>
/// Attach this attribute to all members of the opcode that are meant to be encoded into the packed
/// byte-wise machine language version of this opcode: There should be enough information
/// in all the Opcode's MLFields to reconstruct the entire program again.<br/>
/// But the members who's value is calculated upon loading, like the DeltaInstructionPointer,
/// the SourceName, and so on, do not need to be MLFields.
/// <br/>
/// One important consequence of the phrase "there should be enough information in all the
/// Opcode's MLFields to reconstruct the entire program again" is that if you make an
/// Opcode which requires arguments to the constructor, then all those arguments must be
/// flagged as [MLField]'s, otherwise it will be impossible to obtain the information
/// needed to reconstruct the Opcode when loading the ML file.
/// <br/>
/// WARNING! BE SURE TO EDIT CompiledObject.InitTypeData() if you add any new [MLField]'s that
/// refer to argument types that haven't already been mentioned in CompiledObject.InitTypeData().
/// </summary>
[AttributeUsage(AttributeTargets.Property)]
public class MLField : Attribute
{
public int Ordering { get; private set; }
public bool NeedReindex { get; private set;}
/// <summary>
/// When constructing an MLField attribute, it's important
/// to give it a sort order to ensure that it comes out in the
/// ML file in a predictable consistent order.
/// </summary>
/// <param name="sortNumber">Sort the MLField by the order of these numbers</param>
/// <param name="needReindex">True if this is a numeric value that needs its value adjusted by the base code offset.</param>
public MLField(int sortNumber, bool needReindex)
{
Ordering = sortNumber;
NeedReindex = needReindex;
}
}
public class MLArgInfo
{
public PropertyInfo PropertyInfo {get; private set;}
public bool NeedReindex {get; private set;}
public MLArgInfo(PropertyInfo pInfo, bool needReindex)
{
PropertyInfo = pInfo;
NeedReindex = needReindex;
}
}
#region Base classes
// All classes derived from Opcode MUST be capable of producing at least a
// dummy instance without having to provide any constructor argument.
// Either define NO constructors, or if any constructors are defined. then there
// must also be a default constructor (no parameters) as well.
//
public abstract class Opcode
{
private static int lastId;
private readonly int id = ++lastId;
// SHOULD-BE-STATIC MEMBERS:
// ========================
//
// There are places in this class where a static abstract member was the intent,
// meaning "Enforce that all derived classes MUST override this", but also
// meaning "To make a new value for this should require making a new derived class. You
// should not be able to make two instances of the same derived class differ in this value."
// (i.e. all OpcodePush'es should have Name="push", and all OpcodeBranchJump's should have
// Name="jump", and so on.)
//
// But C# cannot support this, apparently, due to a limitation in how it implements class
// inheritances. It doesn't know how to store overrides at the static level where there's just
// one instance per subclass definition. It only knows how to override dynamic members. Because of
// this the compiler will call it an error to try to make a member be both abstract and static.
//
// Any place you see a member which is marked with a SHOULD-BE-STATIC comment, please do NOT
// try to store separate values per instance into it. Treat it like a static member, where to
// change its value you should make a new derived class for the new value.
protected abstract /*SHOULD-BE-STATIC*/ string Name { get; }
/// <summary>
/// The short coded value that indicates what kind of instruction this is.
/// Hopefully one byte will be enough, and we won't have more than 256 different opcodes.
/// </summary>
public abstract /*SHOULD-BE-STATIC*/ ByteCode Code { get; }
// A mapping of CodeName to Opcode type, built at initialization time:
private static Dictionary<ByteCode,Type> mapCodeToType; // will init this later.
// A mapping of Name to Opcode type, built at initialization time:
private static Dictionary<string,Type> mapNameToType; // will init this later.
// A table describing the arguments in machine language form that each opcode needs.
// This is populated by using Reflection to scan all the Opcodes for their MLField Attributes.
private static Dictionary<Type,List<MLArgInfo>> mapOpcodeToArgs;
private const string FORCE_DEFAULT_CONSTRUCTOR_MSG =
"+----------- ERROR IN OPCODE DEFINITION ----------------------------------+\n" +
"| |\n" +
"| This is a message that only developers of the kOS mod are |\n" +
"| likely to ever see. |\n" +
"| If you are NOT a developer of kOS and this message happens |\n" +
"| then that means some kOS developer should hang their head |\n" +
"| in shame for giving out code without ever trying to run it once.|\n" +
"| |\n" +
"| THE PROBLEM: |\n" +
"| |\n" +
"| All Opcodes in kOS must be capable of being instanced from a default |\n" +
"| constructor with no parameters. The default constructor need not lead |\n" +
"| to a useful Opcode that works, and it can be protected if you like. |\n" +
"| |\n" +
"| THE FOLLOWING DOES NOT HAVE A DEFAULT CONSTRUCTOR: |\n" +
"| {0,30} |\n" +
"| |\n" +
"+-------------------------------------------------------------------------+\n";
public int Id { get { return id; } }
/// <summary>
/// How far to jump to the next opcode. 1 is typical (just go to the next opcode),
/// but in the case of jump and branch statements, it can be other numbers. This will
/// be ignored if the CPU has been put into a yield state with CPU.YieldProgram().
/// </summary>
public int DeltaInstructionPointer { get; protected set; }
public int MLIndex { get; set; } // index into the Machine Language code file for the COMPILE command.
/// <summary>
/// Used when profiling: Number of times this one instruction got executed in the life of a program run.
/// </summary>
public int ProfileExecutionCount { get; set; }
/// <summary>
/// Used when profiling: Total stopwatch ticks (not Unity update ticks) spent on this instruction during the
/// program run. If this instruction occurs in a loop and thus gets executed more than once, this will be the sum
/// of all its executions that took place. Divide by ProfileExecutionCount to get what the
/// average for a single execution of it was.
/// </summary>
public long ProfileTicksElapsed { get; set; }
public string Label {get{return label;} set {label = value;} }
public virtual string DestinationLabel {get;set;}
public GlobalPath SourcePath;
public short SourceLine { get; set; } // line number in the source code that this was compiled from.
public short SourceColumn { get; set; } // column number of the token nearest the cause of this Opcode.
private string label = string.Empty;
public bool AbortProgram { get; set; }
public bool AbortContext { get; set; }
public virtual void Execute(ICpu cpu)
{
}
public override string ToString()
{
return Name;
}
protected Opcode()
{
DeltaInstructionPointer = 1;
AbortProgram = false;
AbortContext = false;
}
/// <summary>
/// Starting from an empty instance of this opcode that you can assume was created
/// from the default constructor, populate the Opcode's properties from a
/// list of all the [MLFields] saved to the machine language file.<br/>
/// This needs to be overridden only if your Opcode has declared [MLField]'s.
/// If your Opcode has no [MLFields] then the generic base version of this method works
/// well enough.<br/>
/// <br/>
/// TODO: Perhaps add an assert to the Init methods that will throw up a NagMessage
/// if it detects an Opcode has be defined which has [MLFields] but lacks an override
/// of this method.
/// <br/>
/// </summary>
/// <param name="fields">A list of all the [MLFields] to populate the opcode with,
/// given *IN ORDER* of their Ordering fields. This is important. If the
/// opcode has 2 properties, one that was given attribute [MLField(10)] and the
/// other that was given attribute [MLField(20)], then the one with ordering=10
/// will be the first one in this list, and the one with ordering=20 will be the
/// second. You can process the list in the guaranteed assumption that the caller
/// ordered the arguments this way.<br/>
/// NOTE: If the opcode has no MLField's attributes, then this may be passed in
/// as null, rather than as a list of 0 items.<br/>
/// </param>
public virtual void PopulateFromMLFields(List<object> fields)
{
// No use of the fields argument in the generic base version
// of this. The compiler warning about this is ignorable.
}
/// <summary>
/// This is intended to be called once, during the mod's initialization, and never again.
/// It builds the Dictionaries that look up the type of opcode given its string name or code.
/// </summary>
public static void InitMachineCodeData()
{
// Because of how hard it is to guarantee that KSP only runs a method once and never again, and
// how so many of the Unity initializer hooks seem to be called repeatedly, this check ensures this
// only ever does its work once, no matter how many times it's called:
if (mapCodeToType != null)
return;
mapCodeToType = new Dictionary<ByteCode,Type>();
mapNameToType = new Dictionary<string,Type>();
mapOpcodeToArgs = new Dictionary<Type,List<MLArgInfo>>();
// List of all subclasses of Opcode:
Type opcodeType = typeof(Opcode);
IEnumerable<Type> opcodeTypes = ReflectUtil.GetLoadedTypes(opcodeType.Assembly).Where( t => t.IsSubclassOf(opcodeType) );
foreach (Type opType in opcodeTypes)
{
if (!opType.IsAbstract) // only the ones that can be instanced matter.
{
// (Because overridden values cannot be static, discovering the Opcode's overridden names and codes
// requires making a dummy instance. See the comment about SHOULD-BE-STATIC up at the top of this
// class definition for a longer explanation of why.)
// New rule: all Opcode derivatives must have a default constructor, or this won't work:
object dummyInstance;
try
{
dummyInstance = Activator.CreateInstance(opType,true);
}
catch (MissingMethodException)
{
SafeHouse.Logger.Log( String.Format(FORCE_DEFAULT_CONSTRUCTOR_MSG, opType.Name) );
Debug.AddNagMessage( Debug.NagType.NAGFOREVER, "ERROR IN OPCODE DEFINITION " + opType.Name );
return;
}
var argsInfo = new List<MLArgInfo>();
PropertyInfo[] props = opType.GetProperties(BindingFlags.Instance |
BindingFlags.FlattenHierarchy |
BindingFlags.Public |
BindingFlags.NonPublic);
foreach (PropertyInfo pInfo in props)
{
object[] attribs = pInfo.GetCustomAttributes(true);
if (pInfo.Name == "Code")
{
// Add to the map from codename to Opcode type:
var opCodeName = (ByteCode) pInfo.GetValue(dummyInstance, null);
mapCodeToType.Add(opCodeName, opType);
}
else if (pInfo.Name == "Name")
{
// Add to the map from Name to Opcode type:
var opName = (string) pInfo.GetValue(dummyInstance, null);
mapNameToType.Add(opName, opType);
}
else
{
// See if this property has an MLFields attribute somewhere on it.
foreach (object attrib in attribs)
{
var field = attrib as MLField;
if (field == null) continue;
argsInfo.Add(new MLArgInfo(pInfo, field.NeedReindex));
break;
}
}
}
argsInfo.Sort(MLFieldComparator);
mapOpcodeToArgs.Add(opType, argsInfo);
}
}
}
/// <summary>
/// Delegate function used for Sort() of the MLFields on an Opcode.
/// Should only be called on properties that have [MLField] attributes
/// on them.
/// </summary>
/// <param name="a1"></param>
/// <param name="a2"></param>
/// <returns>negative if a1 less than a2, 0 if same, positive if a1 greater than a2</returns>
private static int MLFieldComparator(MLArgInfo a1, MLArgInfo a2)
{
// All the following is doing is just comparing p1 and p2's
// MLField.Ordering fields to decide the sort order.
//
// Reflection: A good way to make a simple idea look messier than it really is.
//
var attributes1 = a1.PropertyInfo.GetCustomAttributes(true).Cast<Attribute>().ToList();
var attributes2 = a2.PropertyInfo.GetCustomAttributes(true).Cast<Attribute>().ToList();
var f1 = (MLField) attributes1.First(a => a is MLField);
var f2 = (MLField) attributes2.First(a => a is MLField);
return (f1.Ordering < f2.Ordering) ? -1 : (f1.Ordering > f2.Ordering) ? 1 : 0;
}
/// <summary>
/// Given a string value of Code, find the Opcode Type that uses that as its CodeName.
/// </summary>
/// <param name="code">ByteCode to look up</param>
/// <returns>Type, one of the subclasses of Opcode, or PseudoNull if there was no match</returns>
public static Type TypeFromCode(ByteCode code)
{
Type returnValue;
if (! mapCodeToType.TryGetValue(code, out returnValue))
{
returnValue = typeof(PseudoNull); // flag telling the caller "not found".
}
return returnValue;
}
/// <summary>
/// Given a string value of Name, find the Opcode Type that uses that as its Name.
/// </summary>
/// <param name="name">name to look up</param>
/// <returns>Type, one of the subclasses of Opcode, or PseudoNull if there was no match</returns>
public static Type TypeFromName(string name)
{
Type returnValue;
if (! mapNameToType.TryGetValue(name, out returnValue))
{
returnValue = typeof(PseudoNull); // flag telling the caller "not found".
}
return returnValue;
}
/// <summary>
/// Return the list of member Properties that are part of what gets stored to machine language
/// for this opcode.
/// </summary>
/// <returns></returns>
public IEnumerable<MLArgInfo> GetArgumentDefs()
{
return mapOpcodeToArgs[GetType()];
}
/// <summary>
/// A utility function that will do a cpu.PopValue, but with an additional check to ensure
/// the value atop the stack isn't the arg bottom marker.
/// </summary>
/// <returns>object popped if it all worked fine</returns>
protected object PopValueAssert(ICpu cpu, bool barewordOkay = false)
{
object returnValue = cpu.PopValueArgument(barewordOkay);
if (returnValue != null && returnValue.GetType() == OpcodeCall.ArgMarkerType)
throw new KOSArgumentMismatchException("Called with not enough arguments.");
return returnValue;
}
/// <summary>
/// A utility function that will do the same as a cpu.PopValueEncapsulated, but with an additional check to ensure
/// the value atop the stack isn't the arg bottom marker.
/// </summary>
/// <returns>object popped if it all worked fine</returns>
protected object PopValueAssertEncapsulated(ICpu cpu, bool barewordOkay = false)
{
return Structure.FromPrimitive(PopValueAssert(cpu, barewordOkay));
}
/// <summary>
/// A utility function that will do the same as a cpu.PopStructureEncapsulated, but with an additional check to ensure
/// the value atop the stack isn't the arg bottom marker.
/// </summary>
/// <returns>object popped if it all worked fine</returns>
protected Structure PopStructureAssertEncapsulated(ICpu cpu, bool barewordOkay = false)
{
return Structure.FromPrimitiveWithAssert(PopValueAssert(cpu, barewordOkay));
}
}
public abstract class BinaryOpcode : Opcode
{
protected OperandPair Operands { get; private set; }
public override void Execute(ICpu cpu)
{
object right = cpu.PopValueArgument();
object left = cpu.PopValueArgument();
var operands = new OperandPair(left, right);
Calculator calc = Calculator.GetCalculator(operands);
Operands = operands;
object result = ExecuteCalculation(calc);
cpu.PushArgumentStack(result);
}
protected virtual object ExecuteCalculation(Calculator calc)
{
return null;
}
}
/// <summary>
/// The base class for opcodes that operate on an identifier as an MLfield
/// (rather than reading the identifier from a stack argument).
/// </summary>
public abstract class OpcodeIdentifierBase : Opcode
{
[MLField(1, false)]
public string Identifier { get; set; }
protected OpcodeIdentifierBase(string identifier)
{
Identifier = identifier;
}
public override void PopulateFromMLFields(List<object> fields)
{
// Expect fields in the same order as the [MLField] properties of this class:
if (fields == null || fields.Count<1)
throw new Exception(String.Format("Saved field in ML file for {0} seems to be missing. Version mismatch?", Name));
Identifier = Convert.ToString(fields[0]);
}
public override string ToString()
{
return String.Format("{0} {1}", Name, (string)Identifier);
}
}
#endregion
#region General
/// <summary>
/// Consumes the topmost value of the stack, storing it into
/// a variable named by the Identifier MLField of this opcode.<br/>
/// <br/>
/// If the variable does not exist in the local scope, then it will attempt to look for
/// it in the next scoping level up, and the next one up, and so on
/// until it hits global scope and if it still hasn't found it,
/// it will CREATE the variable anew there, at global scope, and
/// then store the value there.<br/>
/// <br/>
/// This is the usual way to make a new GLOBAL variable, or to overwrite
/// an existing LOCAL variable. Note that since this
/// is the way to make a variable, it's impossible to make a variable
/// that hasn't been given an initial value. Its the act of storing a value into
/// the variable that causues it to exist. This is deliberate design.
/// </summary>
public class OpcodeStore : OpcodeIdentifierBase
{
protected override string Name { get { return "store"; } }
public override ByteCode Code { get { return ByteCode.STORE; } }
public OpcodeStore(string identifier) : base(identifier)
{
}
protected OpcodeStore() : base("")
{
}
public override void Execute(ICpu cpu)
{
Structure value = PopStructureAssertEncapsulated(cpu);
cpu.SetValue(Identifier, value);
}
}
/// <summary>
/// Tests if the identifier atop the stack is an identifier that exists in the system
/// and is accessible in scope at the moment. If the identifier doesn't
/// exist, or if it does but it's out of scope right now, then it results in
/// a FALSE, else it results in a TRUE. The result is pushed onto the stack
/// for reading.
/// Note that the ident atop the stack must be formatted like a variable
/// name (i.e. have the leading '$').
/// </summary>
public class OpcodeExists : Opcode
{
protected override string Name { get { return "exists"; } }
public override ByteCode Code { get { return ByteCode.EXISTS; } }
public override void Execute(ICpu cpu)
{
bool result = false; //pessimistic default
// Convert to string instead of cast in case the identifier is stored
// as an encapsulated StringValue, preventing an unboxing collision.
string ident = Convert.ToString(cpu.PopArgumentStack());
if (ident != null && cpu.IdentifierExistsInScope(ident))
{
result = true;
}
cpu.PushArgumentStack(result);
}
}
/// <summary>
/// Consumes the topmost value of the stack, storing it into
/// a variable described by Identifer MLField of this opcode,
/// which must already exist as a variable before this is executed.<br/>
/// <br/>
/// Unlike OpcodeStore, OpcodeStoreExist will NOT create the variable if it
/// does not already exist. Instead it will cause an
/// error. (It corresponds to kerboscript's @LAZYGLOBAL OFF directive).<br/>
/// <br/>
/// </summary>
public class OpcodeStoreExist : OpcodeIdentifierBase
{
protected override string Name { get { return "storeexist"; } }
public override ByteCode Code { get { return ByteCode.STOREEXIST; } }
public OpcodeStoreExist(string identifier) : base(identifier)
{
}
protected OpcodeStoreExist() : base("")
{
}
public override void Execute(ICpu cpu)
{
Structure value = PopStructureAssertEncapsulated(cpu);
cpu.SetValueExists(Identifier, value);
}
}
/// <summary>
/// Consumes the topmost value of the stack, storing it into
/// a variable named in the Identiver MLField of this Opcode.<br/>
/// <br/>
/// The variable must not exist already in the local nesting level, and it will
/// NOT attempt to look for it in the next scoping level up.<br/>
/// <br/>
/// Instead it will attempt to create the variable anew at the current local
/// nesting scope.<br/>
/// <br/>
/// This is the usual way to make a new LOCAL variable. Do not attempt to
/// use this opcode to store the value into an existing variable - just use it
/// when making new variables. If you use it to store into an existing
/// local variable, it will generate an error at runtime.<br/>
/// <br/>
/// Note that since this
/// is the way to make a variable, it's impossible to make a variable
/// that hasn't been given an initial value. Its the act of storing a value into
/// the variable that causues it to exist. This is deliberate design.
/// </summary>
public class OpcodeStoreLocal : OpcodeIdentifierBase
{
protected override string Name { get { return "storelocal"; } }
public override ByteCode Code { get { return ByteCode.STORELOCAL; } }
public OpcodeStoreLocal(string identifier) : base(identifier)
{
}
protected OpcodeStoreLocal() : base("")
{
}
public override void Execute(ICpu cpu)
{
Structure value = PopStructureAssertEncapsulated(cpu);
cpu.SetNewLocal(Identifier, value);
}
}
/// <summary>
/// Consumes the topmost value of the stack, storing it into
/// a variable named by the Identifier MLfield of this Opcode.<br/>
/// <br/>
/// The variable will always be stored at a global scope, overwriting
/// whatever else was there if the variable already existed.<br/>
/// <br/>
/// It will ignore local scoping and never store the value in a local
/// variable<br/>
/// <br/>
/// It's impossible to make a variable that hasn't been given an initial value.
/// Its the act of storing a value into the variable that causues it to exist.
/// This is deliberate design.
/// </summary>
public class OpcodeStoreGlobal : OpcodeIdentifierBase
{
protected override string Name { get { return "storeglobal"; } }
public override ByteCode Code { get { return ByteCode.STOREGLOBAL; } }
public OpcodeStoreGlobal(string identifier) : base(identifier)
{
}
protected OpcodeStoreGlobal() : base("")
{
}
public override void Execute(ICpu cpu)
{
Structure value = PopStructureAssertEncapsulated(cpu);
cpu.SetGlobal(Identifier, value);
}
}
/// <summary>
/// Consumes the topmost value of the stack as an identifier, unsetting
/// the variable referenced by this identifier. This will remove the
/// variable referenced by this identifier in the innermost scope that
/// it is set in.
/// </summary>
public class OpcodeUnset : Opcode
{
protected override string Name { get { return "unset"; } }
public override ByteCode Code { get { return ByteCode.UNSET; } }
public override void Execute(ICpu cpu)
{
object identifier = cpu.PopArgumentStack();
if (identifier != null)
{
cpu.RemoveVariable(identifier.ToString());
}
else
{
throw new KOSObsoletionException("0.17","UNSET ALL", "<not supported anymore now that we have nested scoping>", "");
}
}
}
/// <summary>
/// <para>
/// Consumes the topmost value of the stack, getting the suffix of it
/// specified by the Identifier MLField and putting that value back on
/// the stack. If this suffix refers to a method suffix, it will be
/// called with no arguments.
/// </para>
/// <para></para>
/// <para>getmember identifier</para>
/// <para>... obj -- ... result</para>
/// <para></para>
/// <para>
/// If this is instead a GetMethod call, it will leave the
/// DelegateSuffixResult on the stack to be called by a later instruction.
/// </para>
/// </summary>
public class OpcodeGetMember : OpcodeIdentifierBase
{
protected override string Name { get { return "getmember"; } }
public override ByteCode Code { get { return ByteCode.GETMEMBER; } }
protected bool IsMethodCallAttempt = false;
public OpcodeGetMember(string identifier) : base(identifier)
{
}
protected OpcodeGetMember() : base("")
{
}
public override void Execute(ICpu cpu)
{
object popValue = cpu.PopValueEncapsulatedArgument();
var specialValue = popValue as ISuffixed;
if (specialValue == null)
{
throw new Exception(string.Format("Values of type {0} cannot have suffixes", popValue.GetType()));
}
ISuffixResult result = specialValue.GetSuffix(Identifier);
// If the result is a suffix that is still in need of being invoked and hasn't resolved to a value yet:
if (result != null && !IsMethodCallAttempt && !result.HasValue)
{
// This is what happens when someone tries to call a suffix method as if
// it wasn't a method (i.e. leaving the parentheses off the call). The
// member returned is a delegate that needs to be called to get its actual
// value. Borrowing the same routine that OpcodeCall uses for its method calls:
cpu.PushArgumentStack(result);
cpu.PushArgumentStack(new KOSArgMarkerType());
OpcodeCall.StaticExecute(cpu, false, "", false); // this will push the return value on the stack for us.
}
else
{
if (result.HasValue)
{
// Push the already calculated value.
cpu.PushArgumentStack(result.Value);
}
else
{
// Push the indirect suffix delegate, but don't execute it yet
// because we need to put the upcoming arg list above it on the stack.
// Eventually an <indirect> OpcodeCall will occur further down the program which
// will actually execute this.
cpu.PushArgumentStack(result);
}
}
}
}
/// <summary>
/// <para>
/// OpcodeGetMethod is *exactly* the same thing as OpcodeGetMember, and is in fact a subclass of it.
/// The only reason for the distinction is so that at runtime the Opcode can tell whether the
/// getting of the member was done with method call syntax with parentheses, like SHIP:NAME(), or
/// non-method call syntax, like SHIP:NAME. It needs to know whether there is an upcoming
/// OpcodeCall coming next or not, so it knows whether the delegate will get dealt with later
/// or if it needs to perform it now.
/// </para>
/// <para></para>
/// <para>getmethod identifier</para>
/// <para>... obj -- ... DelegateSuffixResult</para>
/// </summary>
public class OpcodeGetMethod : OpcodeGetMember
{
protected override string Name { get { return "getmethod"; } }
public override ByteCode Code { get { return ByteCode.GETMETHOD; } }
public OpcodeGetMethod(string identifier) : base(identifier)
{
}
protected OpcodeGetMethod() : base("")
{
}
public override void Execute(ICpu cpu)
{
IsMethodCallAttempt = true;
base.Execute(cpu);
}
}
/// <summary>
/// <para>
/// Consumes a value and a destination object from the stack,
/// setting the objects suffix specified by the Identifier MLField
/// to the popped value.
/// </para>
/// <para></para>
/// <para>setmember identifier</para>
/// <para>... obj value -- ...</para>
/// </summary>
public class OpcodeSetMember : OpcodeIdentifierBase
{
protected override string Name { get { return "setmember"; } }
public override ByteCode Code { get { return ByteCode.SETMEMBER; } }
public OpcodeSetMember(string identifier) : base(identifier)
{
}
protected OpcodeSetMember() : base("")
{
}
public override void Execute(ICpu cpu)
{
Structure value = cpu.PopStructureEncapsulatedArgument(); // new value to set it to
Structure popValue = cpu.PopStructureEncapsulatedArgument(); // object to which the suffix is attached.
// We aren't converting the popValue to a Scalar, Boolean, or String structure here because
// the referenced variable wouldn't be updated. The primitives themselves are treated as value
// types instead of reference types. This is also why I removed the string unboxing
// from the ISuffixed check below.
var specialValue = popValue as ISuffixed;
if (specialValue == null)
{
throw new Exception(string.Format("Values of type {0} cannot have suffixes", popValue.GetType()));
}
// TODO: When we refactor to make every structure use the new suffix style, this conversion
// to primative can be removed. Right now there are too many structures that override the
// SetSuffix method while relying on unboxing the object rahter than using Convert
if (!specialValue.SetSuffix(Identifier, Structure.ToPrimitive(value)))
{
throw new Exception(string.Format("Suffix {0} not found on object", Identifier));
}
}
}
/// <summary>
/// <para>
/// Consumes an index and an target object from the stack,
/// getting the indexed value from the object and pushing
/// the result back on the stack.
/// </para>
/// <para></para>
/// <para>getindex</para>
/// <para>... obj index -- ... result</para>
/// </summary>
public class OpcodeGetIndex : Opcode
{
protected override string Name { get { return "getindex"; } }
public override ByteCode Code { get { return ByteCode.GETINDEX; } }
public override void Execute(ICpu cpu)
{
Structure index = cpu.PopStructureEncapsulatedArgument();
Structure collection = cpu.PopStructureEncapsulatedArgument();
Structure result;
var indexable = collection as IIndexable;
if (indexable != null)
{
result = indexable.GetIndex(index);
}
else
{
throw new Exception(string.Format("Can't iterate on an object of type {0}", collection.GetType()));
}
cpu.PushArgumentStack(result);
}
}
/// <summary>
/// <para>
/// Consumes a value, an index, and an object from the stack,
/// setting the specified index on the object to the given value.
/// </para>
/// <para></para>
/// <para>setindex</para>
/// <para>... obj index value -- ...</para>
/// </summary>
public class OpcodeSetIndex : Opcode
{
protected override string Name { get { return "setindex"; } }
public override ByteCode Code { get { return ByteCode.SETINDEX; } }
public override void Execute(ICpu cpu)
{
Structure value = cpu.PopStructureEncapsulatedArgument();
Structure index = cpu.PopStructureEncapsulatedArgument();
Structure list = cpu.PopStructureEncapsulatedArgument();
if (index == null || value == null)
{
throw new KOSException("Neither the key nor the index of a collection may be null");
}
var indexable = list as IIndexable;
if (indexable == null)
{
throw new KOSException(string.Format("Can't set indexed elements on an object of type {0}", list.GetType()));
}
indexable.SetIndex(index, value);
}
}
/// <summary>
/// Stops executing for this cycle. Has no stack effect.
/// </summary>
public class OpcodeEOF : Opcode
{
protected override string Name { get { return "EOF"; } }
public override ByteCode Code { get { return ByteCode.EOF; } }
public override void Execute(ICpu cpu)
{
AbortContext = true;
}
}
/// <summary>
/// Aborts the current program. This is used to return back to the interpreter context
/// once a program is finished executing. Has no stack effect. (The
/// system may wipe some things off the stack as it performs cleanup associated
/// with ending the program, but this opcode doesn't do it directly itself.)
/// </summary>
public class OpcodeEOP : Opcode
{
protected override string Name { get { return "EOP"; } }
public override ByteCode Code { get { return ByteCode.EOP; } }
public override void Execute(ICpu cpu)
{
AbortProgram = true;
}
}
/// <summary>
/// No-op. Does nothing.
/// </summary>
public class OpcodeNOP : Opcode
{
protected override string Name { get { return "nop"; } }
public override ByteCode Code { get { return ByteCode.NOP; } }
}
/// <summary>
/// Opcode to be returned when getting an opcode that doesn't exist (outside program range).
/// This generally happens only when there's an exception that occurs outside running
/// a program, and the KSPLogger has to have something valid returned or it throws
/// an exception that hides the original exception it was trying to report.
/// </summary>
public class OpcodeBogus : Opcode
{
protected override string Name { get { return "not an opcode in the program."; } }
public override ByteCode Code { get { return ByteCode.BOGUS; } }
}