aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/OpenSim/Region/ScriptEngine/XMREngine/MMRScriptCodeGen.cs
diff options
context:
space:
mode:
Diffstat (limited to '')
-rw-r--r--OpenSim/Region/ScriptEngine/XMREngine/MMRScriptCodeGen.cs6258
1 files changed, 6258 insertions, 0 deletions
diff --git a/OpenSim/Region/ScriptEngine/XMREngine/MMRScriptCodeGen.cs b/OpenSim/Region/ScriptEngine/XMREngine/MMRScriptCodeGen.cs
new file mode 100644
index 0000000..3b0ba66
--- /dev/null
+++ b/OpenSim/Region/ScriptEngine/XMREngine/MMRScriptCodeGen.cs
@@ -0,0 +1,6258 @@
1/*
2 * Copyright (c) Contributors, http://opensimulator.org/
3 * See CONTRIBUTORS.TXT for a full list of copyright holders.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are met:
7 * * Redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer.
9 * * Redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution.
12 * * Neither the name of the OpenSimulator Project nor the
13 * names of its contributors may be used to endorse or promote products
14 * derived from this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
17 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
18 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
19 * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
20 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
21 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
22 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
23 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
25 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28using OpenSim.Region.ScriptEngine.Shared.ScriptBase;
29using OpenSim.Region.ScriptEngine.XMREngine;
30using System;
31using System.Collections.Generic;
32using System.IO;
33using System.Reflection;
34using System.Reflection.Emit;
35using System.Runtime.Serialization;
36using System.Text;
37using System.Threading;
38
39using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat;
40using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger;
41using LSL_Key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
42using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list;
43using LSL_Rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion;
44using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString;
45using LSL_Vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3;
46
47/**
48 * @brief translate a reduced script token into corresponding CIL code.
49 * The single script token contains a tokenized and textured version of the whole script file.
50 */
51
52namespace OpenSim.Region.ScriptEngine.XMREngine
53{
54 public interface IScriptCodeGen
55 {
56 ScriptMyILGen ilGen { get; } // the output instruction stream
57 void ErrorMsg (Token token, string message);
58 void PushDefaultValue (TokenType type);
59 void PushXMRInst ();
60 }
61
62 public class ScriptCodeGen : IScriptCodeGen
63 {
64 private static readonly bool DEBUG_STACKCAPRES = false;
65 private static readonly bool DEBUG_TRYSTMT = false;
66
67 public static readonly string OBJECT_CODE_MAGIC = "XMRObjectCode";
68 public static int COMPILED_VERSION_VALUE = 20; // incremented when compiler changes for compatibility testing
69
70 public static readonly int CALL_FRAME_MEMUSE = 64;
71 public static readonly int STRING_LEN_TO_MEMUSE = 2;
72
73 public static Type xmrInstSuperType = null; // typeof whatever is actually malloc'd for script instances
74 // - must inherit from XMRInstAbstract
75
76 /*
77 * Static tables that there only needs to be one copy of for all.
78 */
79 private static VarDict legalEventHandlers = CreateLegalEventHandlers ();
80 private static CompValu[] zeroCompValus = new CompValu[0];
81 private static TokenType[] zeroArgs = new TokenType[0];
82 private static TokenTypeBool tokenTypeBool = new TokenTypeBool (null);
83 private static TokenTypeExc tokenTypeExc = new TokenTypeExc (null);
84 private static TokenTypeFloat tokenTypeFlt = new TokenTypeFloat (null);
85 private static TokenTypeInt tokenTypeInt = new TokenTypeInt (null);
86 private static TokenTypeObject tokenTypeObj = new TokenTypeObject (null);
87 private static TokenTypeRot tokenTypeRot = new TokenTypeRot (null);
88 private static TokenTypeStr tokenTypeStr = new TokenTypeStr (null);
89 private static TokenTypeVec tokenTypeVec = new TokenTypeVec (null);
90 private static Type[] instanceTypeArg = new Type[] { typeof (XMRInstAbstract) };
91 private static string[] instanceNameArg = new string[] { "$xmrthis" };
92
93 private static ConstructorInfo lslFloatConstructorInfo = typeof (LSL_Float).GetConstructor (new Type[] { typeof (double) });
94 private static ConstructorInfo lslIntegerConstructorInfo = typeof (LSL_Integer).GetConstructor (new Type[] { typeof (int) });
95 private static ConstructorInfo lslListConstructorInfo = typeof (LSL_List).GetConstructor (new Type[] { typeof (object[]) });
96 public static ConstructorInfo lslRotationConstructorInfo = typeof (LSL_Rotation).GetConstructor (new Type[] { typeof (double), typeof (double), typeof (double), typeof (double) });
97 private static ConstructorInfo lslStringConstructorInfo = typeof (LSL_String).GetConstructor (new Type[] { typeof (string) });
98 public static ConstructorInfo lslVectorConstructorInfo = typeof (LSL_Vector).GetConstructor (new Type[] { typeof (double), typeof (double), typeof (double) });
99 private static ConstructorInfo scriptBadCallNoExceptionConstructorInfo = typeof (ScriptBadCallNoException).GetConstructor (new Type[] { typeof (int) });
100 private static ConstructorInfo scriptChangeStateExceptionConstructorInfo = typeof (ScriptChangeStateException).GetConstructor (new Type[] { typeof (int) });
101 private static ConstructorInfo scriptRestoreCatchExceptionConstructorInfo = typeof (ScriptRestoreCatchException).GetConstructor (new Type[] { typeof (Exception) });
102 private static ConstructorInfo scriptUndefinedStateExceptionConstructorInfo = typeof (ScriptUndefinedStateException).GetConstructor (new Type[] { typeof (string) });
103 private static ConstructorInfo sdtClassConstructorInfo = typeof (XMRSDTypeClObj).GetConstructor (new Type[] { typeof (XMRInstAbstract), typeof (int) });
104 private static ConstructorInfo xmrArrayConstructorInfo = typeof (XMR_Array).GetConstructor (new Type[] { typeof (XMRInstAbstract) });
105 private static FieldInfo callModeFieldInfo = typeof (XMRInstAbstract).GetField ("callMode");
106 private static FieldInfo doGblInitFieldInfo = typeof (XMRInstAbstract).GetField ("doGblInit");
107 private static FieldInfo ehArgsFieldInfo = typeof (XMRInstAbstract).GetField ("ehArgs");
108 private static FieldInfo rotationXFieldInfo = typeof (LSL_Rotation).GetField ("x");
109 private static FieldInfo rotationYFieldInfo = typeof (LSL_Rotation).GetField ("y");
110 private static FieldInfo rotationZFieldInfo = typeof (LSL_Rotation).GetField ("z");
111 private static FieldInfo rotationSFieldInfo = typeof (LSL_Rotation).GetField ("s");
112 private static FieldInfo sdtXMRInstFieldInfo = typeof (XMRSDTypeClObj).GetField ("xmrInst");
113 private static FieldInfo vectorXFieldInfo = typeof (LSL_Vector).GetField ("x");
114 private static FieldInfo vectorYFieldInfo = typeof (LSL_Vector).GetField ("y");
115 private static FieldInfo vectorZFieldInfo = typeof (LSL_Vector).GetField ("z");
116
117 private static MethodInfo arrayClearMethodInfo = typeof (XMR_Array).GetMethod ("__pub_clear", new Type[] { });
118 private static MethodInfo arrayCountMethodInfo = typeof (XMR_Array).GetMethod ("__pub_count", new Type[] { });
119 private static MethodInfo arrayIndexMethodInfo = typeof (XMR_Array).GetMethod ("__pub_index", new Type[] { typeof (int) });
120 private static MethodInfo arrayValueMethodInfo = typeof (XMR_Array).GetMethod ("__pub_value", new Type[] { typeof (int) });
121 private static MethodInfo checkRunStackMethInfo = typeof (XMRInstAbstract).GetMethod ("CheckRunStack", new Type[] { });
122 private static MethodInfo checkRunQuickMethInfo = typeof (XMRInstAbstract).GetMethod ("CheckRunQuick", new Type[] { });
123 private static MethodInfo ehArgUnwrapFloat = GetStaticMethod (typeof (TypeCast), "EHArgUnwrapFloat", new Type[] { typeof (object) });
124 private static MethodInfo ehArgUnwrapInteger = GetStaticMethod (typeof (TypeCast), "EHArgUnwrapInteger", new Type[] { typeof (object) });
125 private static MethodInfo ehArgUnwrapRotation = GetStaticMethod (typeof (TypeCast), "EHArgUnwrapRotation", new Type[] { typeof (object) });
126 private static MethodInfo ehArgUnwrapString = GetStaticMethod (typeof (TypeCast), "EHArgUnwrapString", new Type[] { typeof (object) });
127 private static MethodInfo ehArgUnwrapVector = GetStaticMethod (typeof (TypeCast), "EHArgUnwrapVector", new Type[] { typeof (object) });
128 private static MethodInfo xmrArrPubIndexMethod = typeof (XMR_Array).GetMethod ("__pub_index", new Type[] { typeof (int) });
129 private static MethodInfo xmrArrPubValueMethod = typeof (XMR_Array).GetMethod ("__pub_value", new Type[] { typeof (int) });
130 private static MethodInfo captureStackFrameMethodInfo = typeof (XMRInstAbstract).GetMethod ("CaptureStackFrame", new Type[] { typeof (string), typeof (int), typeof (int) });
131 private static MethodInfo restoreStackFrameMethodInfo = typeof (XMRInstAbstract).GetMethod ("RestoreStackFrame", new Type[] { typeof (string), typeof (int).MakeByRefType () });
132 private static MethodInfo stringCompareMethodInfo = GetStaticMethod (typeof (String), "Compare", new Type[] { typeof (string), typeof (string), typeof (StringComparison) });
133 private static MethodInfo stringConcat2MethodInfo = GetStaticMethod (typeof (String), "Concat", new Type[] { typeof (string), typeof (string) });
134 private static MethodInfo stringConcat3MethodInfo = GetStaticMethod (typeof (String), "Concat", new Type[] { typeof (string), typeof (string), typeof (string) });
135 private static MethodInfo stringConcat4MethodInfo = GetStaticMethod (typeof (String), "Concat", new Type[] { typeof (string), typeof (string), typeof (string), typeof (string) });
136 private static MethodInfo lslRotationNegateMethodInfo = GetStaticMethod (typeof (ScriptCodeGen),
137 "LSLRotationNegate",
138 new Type[] { typeof (LSL_Rotation) });
139 private static MethodInfo lslVectorNegateMethodInfo = GetStaticMethod (typeof (ScriptCodeGen),
140 "LSLVectorNegate",
141 new Type[] { typeof (LSL_Vector) });
142 private static MethodInfo scriptRestoreCatchExceptionUnwrap = GetStaticMethod (typeof (ScriptRestoreCatchException), "Unwrap", new Type[] { typeof (Exception) });
143 private static MethodInfo thrownExceptionWrapMethodInfo = GetStaticMethod (typeof (ScriptThrownException), "Wrap", new Type[] { typeof (object) });
144
145 private static MethodInfo catchExcToStrMethodInfo = GetStaticMethod (typeof (ScriptCodeGen),
146 "CatchExcToStr",
147 new Type[] { typeof (Exception) });
148
149 private static MethodInfo consoleWriteMethodInfo = GetStaticMethod (typeof (ScriptCodeGen), "ConsoleWrite", new Type[] { typeof (object) });
150 public static void ConsoleWrite (object o)
151 {
152 if (o == null) o = "<<null>>";
153 Console.Write (o.ToString ());
154 }
155
156 public static bool CodeGen (TokenScript tokenScript, BinaryWriter objFileWriter, string sourceHash)
157 {
158 /*
159 * Run compiler such that it has a 'this' context for convenience.
160 */
161 ScriptCodeGen scg = new ScriptCodeGen (tokenScript, objFileWriter, sourceHash);
162
163 /*
164 * Return pointer to resultant script object code.
165 */
166 return !scg.youveAnError;
167 }
168
169 /*
170 * There is one set of these variables for each script being compiled.
171 */
172 private bool mightGetHere = false;
173 private bool youveAnError = false;
174 private BreakContTarg curBreakTarg = null;
175 private BreakContTarg curContTarg = null;
176 private int lastErrorLine = 0;
177 private int nStates = 0;
178 private string sourceHash;
179 private string lastErrorFile = "";
180 private string[] stateNames;
181 private XMRInstArSizes glblSizes = new XMRInstArSizes ();
182 private Token errorMessageToken = null;
183 private TokenDeclVar curDeclFunc = null;
184 private TokenStmtBlock curStmtBlock = null;
185 private BinaryWriter objFileWriter = null;
186 private TokenScript tokenScript = null;
187 public int tempCompValuNum = 0;
188 private TokenDeclSDTypeClass currentSDTClass = null;
189
190 private Dictionary<string, int> stateIndices = null;
191
192 // These get cleared at beginning of every function definition
193 private ScriptMyLocal instancePointer; // holds XMRInstanceSuperType pointer
194 private ScriptMyLabel retLabel = null; // where to jump to exit function
195 private ScriptMyLocal retValue = null;
196 private ScriptMyLocal actCallNo = null; // for the active try/catch/finally stack or the big one outside them all
197 private LinkedList<CallLabel> actCallLabels = new LinkedList<CallLabel> (); // for the active try/catch/finally stack or the big one outside them all
198 private LinkedList<CallLabel> allCallLabels = new LinkedList<CallLabel> (); // this holds each and every one for all stacks in total
199 public CallLabel openCallLabel = null; // only one call label can be open at a time
200 // - the call label is open from the time of CallPre() until corresponding CallPost()
201 // - so no non-trivial pushes/pops etc allowed between a CallPre() and a CallPost()
202
203 private ScriptMyILGen _ilGen;
204 public ScriptMyILGen ilGen { get { return _ilGen; } }
205
206 private ScriptCodeGen (TokenScript tokenScript, BinaryWriter objFileWriter, string sourceHash)
207 {
208 this.tokenScript = tokenScript;
209 this.objFileWriter = objFileWriter;
210 this.sourceHash = sourceHash;
211
212 try {
213 PerformCompilation ();
214 } catch {
215 // if we've an error, just punt on any exception
216 // it's probably just a null reference from something
217 // not being filled in etc.
218 if (!youveAnError) throw;
219 } finally {
220 objFileWriter = null;
221 }
222 }
223
224 /**
225 * @brief Convert 'tokenScript' to 'objFileWriter' format.
226 * 'tokenScript' is a parsed/reduced abstract syntax tree of the script source file
227 * 'objFileWriter' is a serialized form of the CIL code that we generate
228 */
229 private void PerformCompilation ()
230 {
231 /*
232 * errorMessageToken is used only when the given token doesn't have a
233 * output delegate associated with it such as for backend API functions
234 * that only have one copy for the whole system. It is kept up-to-date
235 * approximately but is rarely needed so going to assume it doesn't have
236 * to be exact.
237 */
238 errorMessageToken = tokenScript;
239
240 /*
241 * Set up dictionary to translate state names to their index number.
242 */
243 stateIndices = new Dictionary<string, int> ();
244
245 /*
246 * Assign each state its own unique index.
247 * The default state gets 0.
248 */
249 nStates = 0;
250 tokenScript.defaultState.body.index = nStates ++;
251 stateIndices.Add ("default", 0);
252 foreach (KeyValuePair<string, TokenDeclState> kvp in tokenScript.states) {
253 TokenDeclState declState = kvp.Value;
254 declState.body.index = nStates ++;
255 stateIndices.Add (declState.name.val, declState.body.index);
256 }
257
258 /*
259 * Make up an array that translates state indices to state name strings.
260 */
261 stateNames = new string[nStates];
262 stateNames[0] = "default";
263 foreach (KeyValuePair<string, TokenDeclState> kvp in tokenScript.states) {
264 TokenDeclState declState = kvp.Value;
265 stateNames[declState.body.index] = declState.name.val;
266 }
267
268 /*
269 * Make sure we have delegates for all script-defined functions and methods,
270 * creating anonymous ones if needed. Note that this includes all property
271 * getter and setter methods.
272 */
273 foreach (TokenDeclVar declFunc in tokenScript.variablesStack) {
274 if (declFunc.retType != null) {
275 declFunc.GetDelType ();
276 }
277 }
278 while (true) {
279 bool itIsAGoodDayToDie = true;
280 try {
281 foreach (TokenDeclSDType sdType in tokenScript.sdSrcTypesValues) {
282 itIsAGoodDayToDie = false;
283 if (sdType is TokenDeclSDTypeClass) {
284 TokenDeclSDTypeClass sdtClass = (TokenDeclSDTypeClass)sdType;
285 foreach (TokenDeclVar declFunc in sdtClass.members) {
286 if (declFunc.retType != null) {
287 declFunc.GetDelType ();
288 if (declFunc.funcNameSig.val.StartsWith ("$ctor(")) {
289 // this is for the "$new()" static method that we create below.
290 // See GenerateStmtNewobj() etc.
291 new TokenTypeSDTypeDelegate (declFunc, sdtClass.MakeRefToken (declFunc),
292 declFunc.argDecl.types, tokenScript);
293 }
294 }
295 }
296 }
297 if (sdType is TokenDeclSDTypeInterface) {
298 TokenDeclSDTypeInterface sdtIFace = (TokenDeclSDTypeInterface)sdType;
299 foreach (TokenDeclVar declFunc in sdtIFace.methsNProps) {
300 if (declFunc.retType != null) {
301 declFunc.GetDelType ();
302 }
303 }
304 }
305 itIsAGoodDayToDie = true;
306 }
307 break;
308 } catch (InvalidOperationException) {
309 if (!itIsAGoodDayToDie) throw;
310 // fetching the delegate created an anonymous entry in tokenScript.sdSrcTypesValues
311 // which made the foreach statement puque, so start over...
312 }
313 }
314
315 /*
316 * No more types can be defined or we won't be able to write them to the object file.
317 */
318 tokenScript.sdSrcTypesSeal ();
319
320 /*
321 * Assign all global variables a slot in its corresponding XMRInstance.gbl<Type>s[] array.
322 * Global variables are simply elements of those arrays at runtime, thus we don't need to create
323 * an unique class for each script, we can just use XMRInstance as is for all.
324 */
325 foreach (TokenDeclVar declVar in tokenScript.variablesStack) {
326
327 /*
328 * Omit 'constant' variables as they are coded inline so don't need a slot.
329 */
330 if (declVar.constant) continue;
331
332 /*
333 * Do functions later.
334 */
335 if (declVar.retType != null) continue;
336
337 /*
338 * Create entry in the value array for the variable or property.
339 */
340 declVar.location = new CompValuGlobalVar (declVar, glblSizes);
341 }
342
343 /*
344 * Likewise for any static fields in script-defined classes.
345 * They can be referenced anywhere by <typename>.<fieldname>, see
346 * GenerateFromLValSField().
347 */
348 foreach (TokenDeclSDType sdType in tokenScript.sdSrcTypesValues) {
349 if (!(sdType is TokenDeclSDTypeClass)) continue;
350 TokenDeclSDTypeClass sdtClass = (TokenDeclSDTypeClass)sdType;
351
352 foreach (TokenDeclVar declVar in sdtClass.members) {
353
354 /*
355 * Omit 'constant' variables as they are coded inline so don't need a slot.
356 */
357 if (declVar.constant) continue;
358
359 /*
360 * Do methods later.
361 */
362 if (declVar.retType != null) continue;
363
364 /*
365 * Ignore non-static fields for now.
366 * They get assigned below.
367 */
368 if ((declVar.sdtFlags & ScriptReduce.SDT_STATIC) == 0) continue;
369
370 /*
371 * Create entry in the value array for the static field or static property.
372 */
373 declVar.location = new CompValuGlobalVar (declVar, glblSizes);
374 }
375 }
376
377 /*
378 * Assign slots for all interface method prototypes.
379 * These indices are used to index the array of delegates that holds a class' implementation of an
380 * interface.
381 * Properties do not get a slot because they aren't called as such. But their corresponding
382 * <name>$get() and <name>$set(<type>) methods are in the table and they each get a slot.
383 */
384 foreach (TokenDeclSDType sdType in tokenScript.sdSrcTypesValues) {
385 if (!(sdType is TokenDeclSDTypeInterface)) continue;
386 TokenDeclSDTypeInterface sdtIFace = (TokenDeclSDTypeInterface)sdType;
387 int vti = 0;
388 foreach (TokenDeclVar im in sdtIFace.methsNProps) {
389 if ((im.getProp == null) && (im.setProp == null)) {
390 im.vTableIndex = vti ++;
391 }
392 }
393 }
394
395 /*
396 * Assign slots for all instance fields and virtual methods of script-defined classes.
397 */
398 int maxExtends = tokenScript.sdSrcTypesCount;
399 bool didOne;
400 do {
401 didOne = false;
402 foreach (TokenDeclSDType sdType in tokenScript.sdSrcTypesValues) {
403 if (!(sdType is TokenDeclSDTypeClass)) continue;
404 TokenDeclSDTypeClass sdtClass = (TokenDeclSDTypeClass)sdType;
405 if (sdtClass.slotsAssigned) continue;
406
407 /*
408 * If this class extends another, the extended class has to already
409 * be set up, because our slots add on to the end of the extended class.
410 */
411 TokenDeclSDTypeClass extends = sdtClass.extends;
412 if (extends != null) {
413 if (!extends.slotsAssigned) continue;
414 sdtClass.instSizes = extends.instSizes;
415 sdtClass.numVirtFuncs = extends.numVirtFuncs;
416 sdtClass.numInterfaces = extends.numInterfaces;
417
418 int n = maxExtends;
419 for (TokenDeclSDTypeClass ex = extends; ex != null; ex = ex.extends) {
420 if (-- n < 0) break;
421 }
422 if (n < 0) {
423 ErrorMsg (sdtClass, "loop in extended classes");
424 sdtClass.slotsAssigned = true;
425 continue;
426 }
427 }
428
429 /*
430 * Extended class's slots all assigned, assign our instance fields
431 * slots in the XMRSDTypeClObj arrays.
432 */
433 foreach (TokenDeclVar declVar in sdtClass.members) {
434 if (declVar.retType != null) continue;
435 if (declVar.constant) continue;
436 if ((declVar.sdtFlags & ScriptReduce.SDT_STATIC) != 0) continue;
437 if ((declVar.getProp == null) && (declVar.setProp == null)) {
438 declVar.type.AssignVarSlot (declVar, sdtClass.instSizes);
439 }
440 }
441
442 /*
443 * ... and assign virtual method vtable slots.
444 *
445 * - : error if any overridden method, doesn't need a slot
446 * abstract : error if any overridden method, alloc new slot but leave it empty
447 * new : ignore any overridden method, doesn't need a slot
448 * new abstract : ignore any overridden method, alloc new slot but leave it empty
449 * override : must have overridden abstract/virtual, use old slot
450 * override abstract : must have overridden abstract, use old slot but it is still empty
451 * static : error if any overridden method, doesn't need a slot
452 * static new : ignore any overridden method, doesn't need a slot
453 * virtual : error if any overridden method, alloc new slot and fill it in
454 * virtual new : ignore any overridden method, alloc new slot and fill it in
455 */
456 foreach (TokenDeclVar declFunc in sdtClass.members) {
457 if (declFunc.retType == null) continue;
458 curDeclFunc = declFunc;
459
460 /*
461 * See if there is a method in an extended class that this method overshadows.
462 * If so, check for various conflicts.
463 * In any case, SDT_NEW on our method means to ignore any overshadowed method.
464 */
465 string declLongName = sdtClass.longName.val + "." + declFunc.funcNameSig.val;
466 uint declFlags = declFunc.sdtFlags;
467 TokenDeclVar overridden = null;
468 if ((declFlags & ScriptReduce.SDT_NEW) == 0) {
469 for (TokenDeclSDTypeClass sdtd = extends; sdtd != null; sdtd = sdtd.extends) {
470 overridden = FindExactWithRet (sdtd.members, declFunc.name, declFunc.retType, declFunc.argDecl.types);
471 if (overridden != null) break;
472 }
473 }
474 if (overridden != null) do {
475 string overLongName = overridden.sdtClass.longName.val;
476 uint overFlags = overridden.sdtFlags;
477
478 /*
479 * See if overridden method allows itself to be overridden.
480 */
481 if ((overFlags & ScriptReduce.SDT_ABSTRACT) != 0) {
482 if ((declFlags & (ScriptReduce.SDT_ABSTRACT | ScriptReduce.SDT_OVERRIDE)) == 0) {
483 ErrorMsg (declFunc, declLongName + " overshadows abstract " + overLongName + " but is not marked abstract, new or override");
484 break;
485 }
486 } else if ((overFlags & ScriptReduce.SDT_FINAL) != 0) {
487 ErrorMsg (declFunc, declLongName + " overshadows final " + overLongName + " but is not marked new");
488 } else if ((overFlags & (ScriptReduce.SDT_OVERRIDE | ScriptReduce.SDT_VIRTUAL)) != 0) {
489 if ((declFlags & (ScriptReduce.SDT_NEW | ScriptReduce.SDT_OVERRIDE)) == 0) {
490 ErrorMsg (declFunc, declLongName + " overshadows virtual " + overLongName + " but is not marked new or override");
491 break;
492 }
493 } else {
494 ErrorMsg (declFunc, declLongName + " overshadows non-virtual " + overLongName + " but is not marked new");
495 break;
496 }
497
498 /*
499 * See if our method is capable of overriding the other method.
500 */
501 if ((declFlags & ScriptReduce.SDT_ABSTRACT) != 0) {
502 if ((overFlags & ScriptReduce.SDT_ABSTRACT) == 0) {
503 ErrorMsg (declFunc, declLongName + " abstract overshadows non-abstract " + overLongName + " but is not marked new");
504 break;
505 }
506 } else if ((declFlags & ScriptReduce.SDT_OVERRIDE) != 0) {
507 if ((overFlags & (ScriptReduce.SDT_ABSTRACT | ScriptReduce.SDT_OVERRIDE | ScriptReduce.SDT_VIRTUAL)) == 0) {
508 ErrorMsg (declFunc, declLongName + " override overshadows non-abstract/non-virtual " + overLongName);
509 break;
510 }
511 } else {
512 ErrorMsg (declFunc, declLongName + " overshadows " + overLongName + " but is not marked new");
513 break;
514 }
515 } while (false);
516
517 /*
518 * Now we can assign it a vtable slot if it needs one (ie, it is virtual).
519 */
520 declFunc.vTableIndex = -1;
521 if (overridden != null) {
522 declFunc.vTableIndex = overridden.vTableIndex;
523 } else if ((declFlags & ScriptReduce.SDT_OVERRIDE) != 0) {
524 ErrorMsg (declFunc, declLongName + " marked override but nothing matching found that it overrides");
525 }
526 if ((declFlags & (ScriptReduce.SDT_ABSTRACT | ScriptReduce.SDT_VIRTUAL)) != 0) {
527 declFunc.vTableIndex = sdtClass.numVirtFuncs ++;
528 }
529 }
530 curDeclFunc = null;
531
532 /*
533 * ... and assign implemented interface slots.
534 * Note that our implementations of a given interface is completely independent of any
535 * rootward class's implementation of that same interface.
536 */
537 int nIFaces = sdtClass.numInterfaces + sdtClass.implements.Count;
538 sdtClass.iFaces = new TokenDeclSDTypeInterface[nIFaces];
539 sdtClass.iImplFunc = new TokenDeclVar[nIFaces][];
540 for (int i = 0; i < sdtClass.numInterfaces; i ++) {
541 sdtClass.iFaces[i] = extends.iFaces[i];
542 sdtClass.iImplFunc[i] = extends.iImplFunc[i];
543 }
544
545 foreach (TokenDeclSDTypeInterface intf in sdtClass.implements) {
546 int i = sdtClass.numInterfaces ++;
547 sdtClass.iFaces[i] = intf;
548 sdtClass.intfIndices.Add (intf.longName.val, i);
549 int nMeths = 0;
550 foreach (TokenDeclVar m in intf.methsNProps) {
551 if ((m.getProp == null) && (m.setProp == null)) nMeths ++;
552 }
553 sdtClass.iImplFunc[i] = new TokenDeclVar[nMeths];
554 }
555
556 foreach (TokenDeclVar classMeth in sdtClass.members) {
557 if (classMeth.retType == null) continue;
558 curDeclFunc = classMeth;
559 for (TokenIntfImpl intfImpl = classMeth.implements; intfImpl != null; intfImpl = (TokenIntfImpl)intfImpl.nextToken) {
560
561 /*
562 * One of the class methods implements an interface method.
563 * Try to find the interface method that is implemented and verify its signature.
564 */
565 TokenDeclSDTypeInterface intfType = intfImpl.intfType.decl;
566 TokenDeclVar intfMeth = FindExactWithRet (intfType.methsNProps, intfImpl.methName, classMeth.retType, classMeth.argDecl.types);
567 if (intfMeth == null) {
568 ErrorMsg (intfImpl, "interface does not define method " + intfImpl.methName.val + classMeth.argDecl.GetArgSig ());
569 continue;
570 }
571
572 /*
573 * See if this class was declared to implement that interface.
574 */
575 bool found = false;
576 foreach (TokenDeclSDTypeInterface intf in sdtClass.implements) {
577 if (intf == intfType) {
578 found = true;
579 break;
580 }
581 }
582 if (!found) {
583 ErrorMsg (intfImpl, "class not declared to implement " + intfType.longName.val);
584 continue;
585 }
586
587 /*
588 * Get index in iFaces[] and iImplFunc[] arrays.
589 * Start scanning from the end in case one of our rootward classes also implements the interface.
590 * We should always be successful because we know by now that this class implements the interface.
591 */
592 int i;
593 for (i = sdtClass.numInterfaces; -- i >= 0;) {
594 if (sdtClass.iFaces[i] == intfType) break;
595 }
596
597 /*
598 * Now remember which of the class methods implements that interface method.
599 */
600 int j = intfMeth.vTableIndex;
601 if (sdtClass.iImplFunc[i][j] != null) {
602 ErrorMsg (intfImpl, "also implemented by " + sdtClass.iImplFunc[i][j].funcNameSig.val);
603 continue;
604 }
605 sdtClass.iImplFunc[i][j] = classMeth;
606 }
607 }
608 curDeclFunc = null;
609
610 /*
611 * Now make sure this class implements all methods for all declared interfaces.
612 */
613 for (int i = sdtClass.numInterfaces - sdtClass.implements.Count; i < sdtClass.numInterfaces; i ++) {
614 TokenDeclVar[] implementations = sdtClass.iImplFunc[i];
615 for (int j = implementations.Length; -- j >= 0;) {
616 if (implementations[j] == null) {
617 TokenDeclSDTypeInterface intf = sdtClass.iFaces[i];
618 TokenDeclVar meth = null;
619 foreach (TokenDeclVar im in intf.methsNProps) {
620 if (im.vTableIndex == j) {
621 meth = im;
622 break;
623 }
624 }
625 ErrorMsg (sdtClass, "does not implement " + intf.longName.val + "." + meth.funcNameSig.val);
626 }
627 }
628 }
629
630 /*
631 * All slots for this class have been assigned.
632 */
633 sdtClass.slotsAssigned = true;
634 didOne = true;
635 }
636 } while (didOne);
637
638 /*
639 * Compute final values for all variables/fields declared as 'constant'.
640 * Note that there may be forward references.
641 */
642 do {
643 didOne = false;
644 foreach (TokenDeclVar tdv in tokenScript.variablesStack) {
645 if (tdv.constant && !(tdv.init is TokenRValConst)) {
646 tdv.init = tdv.init.TryComputeConstant (LookupInitConstants, ref didOne);
647 }
648 }
649 foreach (TokenDeclSDType sdType in tokenScript.sdSrcTypesValues) {
650 if (!(sdType is TokenDeclSDTypeClass)) continue;
651 currentSDTClass = (TokenDeclSDTypeClass)sdType;
652 foreach (TokenDeclVar tdv in currentSDTClass.members) {
653 if (tdv.constant && !(tdv.init is TokenRValConst)) {
654 tdv.init = tdv.init.TryComputeConstant (LookupInitConstants, ref didOne);
655 }
656 }
657 }
658 currentSDTClass = null;
659 } while (didOne);
660
661 /*
662 * Now we should be able to assign all those constants their type and location.
663 */
664 foreach (TokenDeclVar tdv in tokenScript.variablesStack) {
665 if (tdv.constant) {
666 if (tdv.init is TokenRValConst) {
667 TokenRValConst rvc = (TokenRValConst)tdv.init;
668 tdv.type = rvc.tokType;
669 tdv.location = rvc.GetCompValu ();
670 } else {
671 ErrorMsg (tdv, "value is not constant");
672 }
673 }
674 }
675 foreach (TokenDeclSDType sdType in tokenScript.sdSrcTypesValues) {
676 if (!(sdType is TokenDeclSDTypeClass)) continue;
677 currentSDTClass = (TokenDeclSDTypeClass)sdType;
678 foreach (TokenDeclVar tdv in currentSDTClass.members) {
679 if (tdv.constant) {
680 if (tdv.init is TokenRValConst) {
681 TokenRValConst rvc = (TokenRValConst)tdv.init;
682 tdv.type = rvc.tokType;
683 tdv.location = rvc.GetCompValu ();
684 } else {
685 ErrorMsg (tdv, "value is not constant");
686 }
687 }
688 }
689 }
690 currentSDTClass = null;
691
692 /*
693 * For all classes that define all the methods needed for the class, ie, they aren't abstract,
694 * define a static class.$new() method with same args as the $ctor(s). This will allow the
695 * class to be instantiated via the new operator.
696 */
697 foreach (TokenDeclSDType sdType in tokenScript.sdSrcTypesValues) {
698 if (!(sdType is TokenDeclSDTypeClass)) continue;
699 TokenDeclSDTypeClass sdtClass = (TokenDeclSDTypeClass)sdType;
700
701 /*
702 * See if the class as it stands would be able to fill every slot of its vtable.
703 */
704 bool[] filled = new bool[sdtClass.numVirtFuncs];
705 int numFilled = 0;
706 for (TokenDeclSDTypeClass sdtc = sdtClass; sdtc != null; sdtc = sdtc.extends) {
707 foreach (TokenDeclVar tdf in sdtc.members) {
708 if ((tdf.retType != null) && (tdf.vTableIndex >= 0) && ((tdf.sdtFlags & ScriptReduce.SDT_ABSTRACT) == 0)) {
709 if (!filled[tdf.vTableIndex]) {
710 filled[tdf.vTableIndex] = true;
711 numFilled ++;
712 }
713 }
714 }
715 }
716
717 /*
718 * If so, define a static class.$new() method for every constructor defined for the class.
719 * Give it the same access (private/protected/public) as the script declared for the constructor.
720 * Note that the reducer made sure there is at least a default constructor for every class.
721 */
722 if (numFilled >= sdtClass.numVirtFuncs) {
723 List<TokenDeclVar> newobjDeclFuncs = new List<TokenDeclVar> ();
724 foreach (TokenDeclVar ctorDeclFunc in sdtClass.members) {
725 if ((ctorDeclFunc.funcNameSig != null) && ctorDeclFunc.funcNameSig.val.StartsWith ("$ctor(")) {
726 TokenDeclVar newobjDeclFunc = DefineNewobjFunc (ctorDeclFunc);
727 newobjDeclFuncs.Add (newobjDeclFunc);
728 }
729 }
730 foreach (TokenDeclVar newobjDeclFunc in newobjDeclFuncs) {
731 sdtClass.members.AddEntry (newobjDeclFunc);
732 }
733 }
734 }
735
736 /*
737 * Write fixed portion of object file.
738 */
739 objFileWriter.Write (OBJECT_CODE_MAGIC.ToCharArray ());
740 objFileWriter.Write (COMPILED_VERSION_VALUE);
741 objFileWriter.Write (sourceHash);
742 objFileWriter.Write (tokenScript.expiryDays);
743 glblSizes.WriteToFile (objFileWriter);
744
745 objFileWriter.Write (nStates);
746 for (int i = 0; i < nStates; i ++) {
747 objFileWriter.Write (stateNames[i]);
748 }
749
750 /*
751 * For debugging, we also write out global variable array slot assignments.
752 */
753 foreach (TokenDeclVar declVar in tokenScript.variablesStack) {
754 if (declVar.retType == null) {
755 WriteOutGblAssignment ("", declVar);
756 }
757 }
758 foreach (TokenDeclSDType sdType in tokenScript.sdSrcTypesValues) {
759 if (!(sdType is TokenDeclSDTypeClass)) continue;
760 TokenDeclSDTypeClass sdtClass = (TokenDeclSDTypeClass)sdType;
761 foreach (TokenDeclVar declVar in sdtClass.members) {
762 if ((declVar.sdtFlags & ScriptReduce.SDT_STATIC) != 0) {
763 WriteOutGblAssignment (sdtClass.longName.val + ".", declVar);
764 }
765 }
766 }
767 objFileWriter.Write ("");
768
769 /*
770 * Write out script-defined types.
771 */
772 foreach (TokenDeclSDType sdType in tokenScript.sdSrcTypesValues) {
773 objFileWriter.Write (sdType.longName.val);
774 sdType.WriteToFile (objFileWriter);
775 }
776 objFileWriter.Write ("");
777
778 /*
779 * Output function headers then bodies.
780 * Do all headers first in case bodies do forward references.
781 * Do both global functions, script-defined class static methods and
782 * script-defined instance methods, as we handle the differences
783 * during compilation of the functions/methods themselves.
784 */
785 for (int pass = 0; pass < 2; pass ++) {
786 foreach (TokenDeclVar declFunc in tokenScript.variablesStack) {
787 if (declFunc.retType != null) {
788 if (pass == 0) GenerateMethodHeader (declFunc);
789 else GenerateMethodBody (declFunc);
790 }
791 }
792 foreach (TokenDeclSDType sdType in tokenScript.sdSrcTypesValues) {
793 if (sdType is TokenDeclSDTypeClass) {
794 TokenDeclSDTypeClass sdtClass = (TokenDeclSDTypeClass)sdType;
795 foreach (TokenDeclVar declFunc in sdtClass.members) {
796 if ((declFunc.retType != null) && ((declFunc.sdtFlags & ScriptReduce.SDT_ABSTRACT) == 0)) {
797 if (pass == 0) GenerateMethodHeader (declFunc);
798 else GenerateMethodBody (declFunc);
799 }
800 }
801 }
802 }
803 }
804
805 /*
806 * Output default state event handler functions.
807 * Each event handler is a private static method named 'default <eventname>'.
808 * Splice in a default state_entry() handler if none defined so we can init global vars.
809 */
810 TokenDeclVar defaultStateEntry = null;
811 for (defaultStateEntry = tokenScript.defaultState.body.eventFuncs;
812 defaultStateEntry != null;
813 defaultStateEntry = (TokenDeclVar)defaultStateEntry.nextToken) {
814 if (defaultStateEntry.funcNameSig.val == "state_entry()") break;
815 }
816 if (defaultStateEntry == null) {
817 defaultStateEntry = new TokenDeclVar (tokenScript.defaultState.body, null, tokenScript);
818 defaultStateEntry.name = new TokenName (tokenScript.defaultState.body, "state_entry");
819 defaultStateEntry.retType = new TokenTypeVoid (tokenScript.defaultState.body);
820 defaultStateEntry.argDecl = new TokenArgDecl (tokenScript.defaultState.body);
821 defaultStateEntry.body = new TokenStmtBlock (tokenScript.defaultState.body);
822 defaultStateEntry.body.function = defaultStateEntry;
823
824 defaultStateEntry.nextToken = tokenScript.defaultState.body.eventFuncs;
825 tokenScript.defaultState.body.eventFuncs = defaultStateEntry;
826 }
827 GenerateStateEventHandlers ("default", tokenScript.defaultState.body);
828
829 /*
830 * Output script-defined state event handler methods.
831 * Each event handler is a private static method named <statename> <eventname>
832 */
833 foreach (KeyValuePair<string, TokenDeclState> kvp in tokenScript.states) {
834 TokenDeclState declState = kvp.Value;
835 GenerateStateEventHandlers (declState.name.val, declState.body);
836 }
837
838 ScriptObjWriter.TheEnd (objFileWriter);
839 }
840
841 /**
842 * @brief Write out what slot was assigned for a global or sdtclass static variable.
843 * Constants, functions, instance fields, methods, properties do not have slots in the global variables arrays.
844 */
845 private void WriteOutGblAssignment (string pfx, TokenDeclVar declVar)
846 {
847 if (!declVar.constant && (declVar.retType == null) && (declVar.getProp == null) && (declVar.setProp == null)) {
848 objFileWriter.Write (pfx + declVar.name.val); // string
849 objFileWriter.Write (declVar.vTableArray.Name); // string
850 objFileWriter.Write (declVar.vTableIndex); // int
851 }
852 }
853
854 /**
855 * @brief generate event handler code
856 * Writes out a function definition for each state handler
857 * named <statename> <eventname>
858 *
859 * However, each has just 'XMRInstance __sw' as its single argument
860 * and each of its user-visible argments is extracted from __sw.ehArgs[].
861 *
862 * So we end up generating something like this:
863 *
864 * private static void <statename> <eventname>(XMRInstance __sw)
865 * {
866 * <typeArg0> <nameArg0> = (<typeArg0>)__sw.ehArgs[0];
867 * <typeArg1> <nameArg1> = (<typeArg1>)__sw.ehArgs[1];
868 *
869 * ... script code ...
870 * }
871 *
872 * The continuations code assumes there will be no references to ehArgs[]
873 * after the first call to CheckRun() as CheckRun() makes no attempt to
874 * serialize the ehArgs[] array, as doing so would be redundant. Any values
875 * from ehArgs[] that are being used will be in local stack variables and
876 * thus preserved that way.
877 */
878 private void GenerateStateEventHandlers (string statename, TokenStateBody body)
879 {
880 Dictionary<string,TokenDeclVar> statehandlers = new Dictionary<string,TokenDeclVar> ();
881 for (Token t = body.eventFuncs; t != null; t = t.nextToken) {
882 TokenDeclVar tdv = (TokenDeclVar)t;
883 string eventname = tdv.GetSimpleName ();
884 if (statehandlers.ContainsKey (eventname)) {
885 ErrorMsg (tdv, "event handler " + eventname + " already defined for state " + statename);
886 } else {
887 statehandlers.Add (eventname, tdv);
888 GenerateEventHandler (statename, tdv);
889 }
890 }
891 }
892
893 private void GenerateEventHandler (string statename, TokenDeclVar declFunc)
894 {
895 string eventname = declFunc.GetSimpleName ();
896 TokenArgDecl argDecl = declFunc.argDecl;
897
898 /*
899 * Make sure event handler name is valid and that number and type of arguments is correct.
900 * Apparently some scripts exist with fewer than correct number of args in their declaration
901 * so allow for that. It is ok because the handlers are called with the arguments in an
902 * object[] array, and we just won't access the missing argments in the vector. But the
903 * specified types must match one of the prototypes in legalEventHandlers.
904 */
905 TokenDeclVar protoDeclFunc = legalEventHandlers.FindExact (eventname, argDecl.types);
906 if (protoDeclFunc == null) {
907 ErrorMsg (declFunc, "unknown event handler " + eventname + argDecl.GetArgSig ());
908 return;
909 }
910
911 /*
912 * Output function header.
913 * They just have the XMRInstAbstract pointer as the one argument.
914 */
915 string functionName = statename + " " + eventname;
916 _ilGen = new ScriptObjWriter (tokenScript,
917 functionName,
918 typeof (void),
919 instanceTypeArg,
920 instanceNameArg,
921 objFileWriter);
922 StartFunctionBody (declFunc);
923
924 /*
925 * Create a temp to hold XMRInstanceSuperType version of arg 0.
926 */
927 instancePointer = ilGen.DeclareLocal (xmrInstSuperType, "__xmrinst");
928 ilGen.Emit (declFunc, OpCodes.Ldarg_0);
929 ilGen.Emit (declFunc, OpCodes.Castclass, xmrInstSuperType);
930 ilGen.Emit (declFunc, OpCodes.Stloc, instancePointer);
931
932 /*
933 * Output args as variable definitions and initialize each from __sw.ehArgs[].
934 * If the script writer goofed, the typecast will complain.
935 */
936 int nArgs = argDecl.vars.Length;
937 for (int i = 0; i < nArgs; i ++) {
938
939 /*
940 * Say that the argument variable is going to be located in a local var.
941 */
942 TokenDeclVar argVar = argDecl.vars[i];
943 TokenType argTokType = argVar.type;
944 CompValuLocalVar local = new CompValuLocalVar (argTokType, argVar.name.val, this);
945 argVar.location = local;
946
947 /*
948 * Copy from the ehArgs[i] element to the temp var.
949 * Cast as needed, there is a lot of craziness like OpenMetaverse.Quaternion.
950 */
951 local.PopPre (this, argVar.name);
952 PushXMRInst (); // instance
953 ilGen.Emit (declFunc, OpCodes.Ldfld, ehArgsFieldInfo); // instance.ehArgs (array of objects)
954 ilGen.Emit (declFunc, OpCodes.Ldc_I4, i); // array index = i
955 ilGen.Emit (declFunc, OpCodes.Ldelem, typeof (object)); // select the argument we want
956 TokenType stkTokType = tokenTypeObj; // stack has a type 'object' on it now
957 Type argSysType = argTokType.ToSysType (); // this is the type the script expects
958 if (argSysType == typeof (double)) { // LSL_Float/double -> double
959 ilGen.Emit (declFunc, OpCodes.Call, ehArgUnwrapFloat);
960 stkTokType = tokenTypeFlt; // stack has a type 'double' on it now
961 }
962 if (argSysType == typeof (int)) { // LSL_Integer/int -> int
963 ilGen.Emit (declFunc, OpCodes.Call, ehArgUnwrapInteger);
964 stkTokType = tokenTypeInt; // stack has a type 'int' on it now
965 }
966 if (argSysType == typeof (LSL_List)) { // LSL_List -> LSL_List
967 TypeCast.CastTopOfStack (this, argVar.name, stkTokType, argTokType, true);
968 stkTokType = argTokType; // stack has a type 'LSL_List' on it now
969 }
970 if (argSysType == typeof (LSL_Rotation)) { // OpenMetaverse.Quaternion/LSL_Rotation -> LSL_Rotation
971 ilGen.Emit (declFunc, OpCodes.Call, ehArgUnwrapRotation);
972 stkTokType = tokenTypeRot; // stack has a type 'LSL_Rotation' on it now
973 }
974 if (argSysType == typeof (string)) { // LSL_Key/LSL_String/string -> string
975 ilGen.Emit (declFunc, OpCodes.Call, ehArgUnwrapString);
976 stkTokType = tokenTypeStr; // stack has a type 'string' on it now
977 }
978 if (argSysType == typeof (LSL_Vector)) { // OpenMetaverse.Vector3/LSL_Vector -> LSL_Vector
979 ilGen.Emit (declFunc, OpCodes.Call, ehArgUnwrapVector);
980 stkTokType = tokenTypeVec; // stack has a type 'LSL_Vector' on it now
981 }
982 local.PopPost (this, argVar.name, stkTokType); // pop stack type into argtype
983 }
984
985 /*
986 * Output code for the statements and clean up.
987 */
988 GenerateFuncBody ();
989 }
990
991 /**
992 * @brief generate header for an arbitrary script-defined global function.
993 * @param declFunc = function being defined
994 */
995 private void GenerateMethodHeader (TokenDeclVar declFunc)
996 {
997 curDeclFunc = declFunc;
998
999 /*
1000 * Make up array of all argument types as seen by the code generator.
1001 * We splice in XMRInstanceSuperType or XMRSDTypeClObj for the first
1002 * arg as the function itself is static, followed by script-visible
1003 * arg types.
1004 */
1005 TokenArgDecl argDecl = declFunc.argDecl;
1006 int nArgs = argDecl.vars.Length;
1007 Type[] argTypes = new Type[nArgs+1];
1008 string[] argNames = new string[nArgs+1];
1009 if (IsSDTInstMethod ()) {
1010 argTypes[0] = typeof (XMRSDTypeClObj);
1011 argNames[0] = "$sdtthis";
1012 } else {
1013 argTypes[0] = xmrInstSuperType;
1014 argNames[0] = "$xmrthis";
1015 }
1016 for (int i = 0; i < nArgs; i ++) {
1017 argTypes[i+1] = argDecl.vars[i].type.ToSysType ();
1018 argNames[i+1] = argDecl.vars[i].name.val;
1019 }
1020
1021 /*
1022 * Set up entrypoint.
1023 */
1024 string objCodeName = declFunc.GetObjCodeName ();
1025 declFunc.ilGen = new ScriptObjWriter (tokenScript,
1026 objCodeName,
1027 declFunc.retType.ToSysType (),
1028 argTypes,
1029 argNames,
1030 objFileWriter);
1031
1032 /*
1033 * This says how to generate a call to the function and to get a delegate.
1034 */
1035 declFunc.location = new CompValuGlobalMeth (declFunc);
1036
1037 curDeclFunc = null;
1038 }
1039
1040 /**
1041 * @brief generate code for an arbitrary script-defined function.
1042 * @param name = name of the function
1043 * @param argDecl = argument declarations
1044 * @param body = function's code body
1045 */
1046 private void GenerateMethodBody (TokenDeclVar declFunc)
1047 {
1048 /*
1049 * Set up code generator for the function's contents.
1050 */
1051 _ilGen = declFunc.ilGen;
1052 StartFunctionBody (declFunc);
1053
1054 /*
1055 * Create a temp to hold XMRInstanceSuperType version of arg 0.
1056 * For most functions, arg 0 is already XMRInstanceSuperType.
1057 * But for script-defined class instance methods, arg 0 holds
1058 * the XMRSDTypeClObj pointer and so we read the XMRInstAbstract
1059 * pointer from its XMRSDTypeClObj.xmrInst field then cast it to
1060 * XMRInstanceSuperType.
1061 */
1062 if (IsSDTInstMethod ()) {
1063 instancePointer = ilGen.DeclareLocal (xmrInstSuperType, "__xmrinst");
1064 ilGen.Emit (declFunc, OpCodes.Ldarg_0);
1065 ilGen.Emit (declFunc, OpCodes.Ldfld, sdtXMRInstFieldInfo);
1066 ilGen.Emit (declFunc, OpCodes.Castclass, xmrInstSuperType);
1067 ilGen.Emit (declFunc, OpCodes.Stloc, instancePointer);
1068 }
1069
1070 /*
1071 * Define location of all script-level arguments so script body can access them.
1072 * The argument indices need to have +1 added to them because XMRInstance or
1073 * XMRSDTypeClObj is spliced in at arg 0.
1074 */
1075 TokenArgDecl argDecl = declFunc.argDecl;
1076 int nArgs = argDecl.vars.Length;
1077 for (int i = 0; i < nArgs; i ++) {
1078 TokenDeclVar argVar = argDecl.vars[i];
1079 argVar.location = new CompValuArg (argVar.type, i + 1);
1080 }
1081
1082 /*
1083 * Output code for the statements and clean up.
1084 */
1085 GenerateFuncBody ();
1086 }
1087
1088 private void StartFunctionBody (TokenDeclVar declFunc)
1089 {
1090 /*
1091 * Start current function being processed.
1092 * Set 'mightGetHere' as the code at the top is always executed.
1093 */
1094 instancePointer = null;
1095 mightGetHere = true;
1096 curBreakTarg = null;
1097 curContTarg = null;
1098 curDeclFunc = declFunc;
1099
1100 /*
1101 * Start generating code.
1102 */
1103 ((ScriptObjWriter)ilGen).BegMethod ();
1104 }
1105
1106 /**
1107 * @brief Define function for a script-defined type's <typename>.$new(<argsig>) method.
1108 * See GenerateStmtNewobj() for more info.
1109 */
1110 private TokenDeclVar DefineNewobjFunc (TokenDeclVar ctorDeclFunc)
1111 {
1112 /*
1113 * Set up 'static classname $new(params-same-as-ctor) { }'.
1114 */
1115 TokenDeclVar newobjDeclFunc = new TokenDeclVar (ctorDeclFunc, null, tokenScript);
1116 newobjDeclFunc.name = new TokenName (newobjDeclFunc, "$new");
1117 newobjDeclFunc.retType = ctorDeclFunc.sdtClass.MakeRefToken (newobjDeclFunc);
1118 newobjDeclFunc.argDecl = ctorDeclFunc.argDecl;
1119 newobjDeclFunc.sdtClass = ctorDeclFunc.sdtClass;
1120 newobjDeclFunc.sdtFlags = ScriptReduce.SDT_STATIC | ctorDeclFunc.sdtFlags;
1121
1122 /*
1123 * Declare local variable named '$objptr' in a frame just under
1124 * what the '$new(...)' function's arguments are declared in.
1125 */
1126 TokenDeclVar objptrVar = new TokenDeclVar (newobjDeclFunc, newobjDeclFunc, tokenScript);
1127 objptrVar.type = newobjDeclFunc.retType;
1128 objptrVar.name = new TokenName (newobjDeclFunc, "$objptr");
1129 VarDict newFrame = new VarDict (false);
1130 newFrame.outerVarDict = ctorDeclFunc.argDecl.varDict;
1131 newFrame.AddEntry (objptrVar);
1132
1133 /*
1134 * Set up '$objptr.$ctor'
1135 */
1136 TokenLValName objptrLValName = new TokenLValName (objptrVar.name, newFrame);
1137 // ref a var by giving its name
1138 TokenLValIField objptrDotCtor = new TokenLValIField (newobjDeclFunc); // an instance member reference
1139 objptrDotCtor.baseRVal = objptrLValName; // '$objptr'
1140 objptrDotCtor.fieldName = ctorDeclFunc.name; // '.' '$ctor'
1141
1142 /*
1143 * Set up '$objptr.$ctor(arglist)' call for use in the '$new(...)' body.
1144 * Copy the arglist from the constructor declaration so triviality
1145 * processing will pick the correct overloaded constructor.
1146 */
1147 TokenRValCall callCtorRVal = new TokenRValCall (newobjDeclFunc); // doing a call of some sort
1148 callCtorRVal.meth = objptrDotCtor; // calling $objptr.$ctor()
1149 TokenDeclVar[] argList = newobjDeclFunc.argDecl.vars; // get args $new() was declared with
1150 callCtorRVal.nArgs = argList.Length; // ...that is nArgs we are passing to $objptr.$ctor()
1151 for (int i = argList.Length; -- i >= 0;) {
1152 TokenDeclVar arg = argList[i]; // find out about one of the args
1153 TokenLValName argLValName = new TokenLValName (arg.name, ctorDeclFunc.argDecl.varDict);
1154 // pass arg of that name to $objptr.$ctor()
1155 argLValName.nextToken = callCtorRVal.args; // link to list of args passed to $objptr.$ctor()
1156 callCtorRVal.args = argLValName;
1157 }
1158
1159 /*
1160 * Set up a funky call to the constructor for the code body.
1161 * This will let code generator know there is some craziness.
1162 * See GenerateStmtNewobj().
1163 *
1164 * This is in essence:
1165 * {
1166 * classname $objptr = newobj (classname);
1167 * $objptr.$ctor (...);
1168 * return $objptr;
1169 * }
1170 */
1171 TokenStmtNewobj newobjStmtBody = new TokenStmtNewobj (ctorDeclFunc);
1172 newobjStmtBody.objptrVar = objptrVar;
1173 newobjStmtBody.rValCall = callCtorRVal;
1174 TokenStmtBlock newobjBody = new TokenStmtBlock (ctorDeclFunc);
1175 newobjBody.statements = newobjStmtBody;
1176
1177 /*
1178 * Link that code as the body of the function.
1179 */
1180 newobjDeclFunc.body = newobjBody;
1181
1182 /*
1183 * Say the function calls '$objptr.$ctor(arglist)' so we will inherit ctor's triviality.
1184 */
1185 newobjDeclFunc.unknownTrivialityCalls.AddLast (callCtorRVal);
1186 return newobjDeclFunc;
1187 }
1188
1189 private class TokenStmtNewobj : TokenStmt {
1190 public TokenDeclVar objptrVar;
1191 public TokenRValCall rValCall;
1192 public TokenStmtNewobj (Token original) : base (original) { }
1193 }
1194
1195 /**
1196 * @brief Output function body (either event handler or script-defined method).
1197 */
1198 private void GenerateFuncBody ()
1199 {
1200 /*
1201 * We want to know if the function's code is trivial, ie,
1202 * if it doesn't have anything that might be an infinite
1203 * loop and that is doesn't call anything that might have
1204 * an infinite loop. If it is, we don't need any CheckRun()
1205 * stuff or any of the frame save/restore stuff.
1206 */
1207 bool isTrivial = curDeclFunc.IsFuncTrivial (this);
1208
1209 /*
1210 * Clear list of all call labels.
1211 * A call label is inserted just before every call that can possibly
1212 * call CheckRun(), including any direct calls to CheckRun().
1213 * Then, when restoring stack, we can just switch to this label to
1214 * resume at the correct spot.
1215 */
1216 actCallLabels.Clear ();
1217 allCallLabels.Clear ();
1218 openCallLabel = null;
1219
1220 /*
1221 * Alloc stack space for local vars.
1222 */
1223 AllocLocalVarStackSpace ();
1224
1225 /*
1226 * Any return statements inside function body jump to this label
1227 * after putting return value in __retval.
1228 */
1229 retLabel = ilGen.DefineLabel ("__retlbl");
1230 retValue = null;
1231 if (!(curDeclFunc.retType is TokenTypeVoid)) {
1232 retValue = ilGen.DeclareLocal (curDeclFunc.retType.ToSysType (), "__retval");
1233 }
1234
1235 /*
1236 * Output:
1237 * int __mainCallNo = -1;
1238 * try {
1239 * if (instance.callMode != CallMode_NORMAL) goto __cmRestore;
1240 */
1241 actCallNo = null;
1242 ScriptMyLabel cmRestore = null;
1243 if (!isTrivial) {
1244 actCallNo = ilGen.DeclareLocal (typeof (int), "__mainCallNo");
1245 SetCallNo (curDeclFunc, actCallNo, -1);
1246 cmRestore = ilGen.DefineLabel ("__cmRestore");
1247 ilGen.BeginExceptionBlock ();
1248 PushXMRInst ();
1249 ilGen.Emit (curDeclFunc, OpCodes.Ldfld, ScriptCodeGen.callModeFieldInfo);
1250 ilGen.Emit (curDeclFunc, OpCodes.Ldc_I4, XMRInstAbstract.CallMode_NORMAL);
1251 ilGen.Emit (curDeclFunc, OpCodes.Bne_Un, cmRestore);
1252 }
1253
1254 /*
1255 * Splice in the code optimizer for the body of the function.
1256 */
1257 ScriptCollector collector = new ScriptCollector ((ScriptObjWriter)ilGen);
1258 _ilGen = collector;
1259
1260 /*
1261 * If this is the default state_entry() handler, output code to set all global
1262 * variables to their initial values. Note that every script must have a
1263 * default state_entry() handler, we provide one if the script doesn't explicitly
1264 * define one.
1265 */
1266 string methname = ilGen.methName;
1267 if (methname == "default state_entry") {
1268
1269 // if (!doGblInit) goto skipGblInit;
1270 ScriptMyLabel skipGblInitLabel = ilGen.DefineLabel ("__skipGblInit");
1271 PushXMRInst (); // instance
1272 ilGen.Emit (curDeclFunc, OpCodes.Ldfld, doGblInitFieldInfo); // instance.doGblInit
1273 ilGen.Emit (curDeclFunc, OpCodes.Brfalse, skipGblInitLabel);
1274
1275 // $globalvarinit();
1276 TokenDeclVar gviFunc = tokenScript.globalVarInit;
1277 if (gviFunc.body.statements != null) {
1278 gviFunc.location.CallPre (this, gviFunc);
1279 gviFunc.location.CallPost (this, gviFunc);
1280 }
1281
1282 // various $staticfieldinit();
1283 foreach (TokenDeclSDType sdType in tokenScript.sdSrcTypesValues) {
1284 if (sdType is TokenDeclSDTypeClass) {
1285 TokenDeclVar sfiFunc = ((TokenDeclSDTypeClass)sdType).staticFieldInit;
1286 if ((sfiFunc != null) && (sfiFunc.body.statements != null)) {
1287 sfiFunc.location.CallPre (this, sfiFunc);
1288 sfiFunc.location.CallPost (this, sfiFunc);
1289 }
1290 }
1291 }
1292
1293 // doGblInit = 0;
1294 PushXMRInst (); // instance
1295 ilGen.Emit (curDeclFunc, OpCodes.Ldc_I4_0);
1296 ilGen.Emit (curDeclFunc, OpCodes.Stfld, doGblInitFieldInfo); // instance.doGblInit
1297
1298 //skipGblInit:
1299 ilGen.MarkLabel (skipGblInitLabel);
1300 }
1301
1302 /*
1303 * If this is a script-defined type constructor, call the base constructor and call
1304 * this class's $instfieldinit() method to initialize instance fields.
1305 */
1306 if ((curDeclFunc.sdtClass != null) && curDeclFunc.funcNameSig.val.StartsWith ("$ctor(")) {
1307 if (curDeclFunc.baseCtorCall != null) {
1308 GenerateFromRValCall (curDeclFunc.baseCtorCall);
1309 }
1310 TokenDeclVar ifiFunc = ((TokenDeclSDTypeClass)curDeclFunc.sdtClass).instFieldInit;
1311 if (ifiFunc.body.statements != null) {
1312 CompValu thisCompValu = new CompValuArg (ifiFunc.sdtClass.MakeRefToken (ifiFunc), 0);
1313 CompValu ifiFuncLocn = new CompValuInstMember (ifiFunc, thisCompValu, true);
1314 ifiFuncLocn.CallPre (this, ifiFunc);
1315 ifiFuncLocn.CallPost (this, ifiFunc);
1316 }
1317 }
1318
1319 /*
1320 * See if time to suspend in case they are doing a loop with recursion.
1321 */
1322 if (!isTrivial) EmitCallCheckRun (curDeclFunc, true);
1323
1324 /*
1325 * Output code body.
1326 */
1327 GenerateStmtBlock (curDeclFunc.body);
1328
1329 /*
1330 * If code falls through to this point, means they are missing
1331 * a return statement. And that is legal only if the function
1332 * returns 'void'.
1333 */
1334 if (mightGetHere) {
1335 if (!(curDeclFunc.retType is TokenTypeVoid)) {
1336 ErrorMsg (curDeclFunc.body, "missing final return statement");
1337 }
1338 ilGen.Emit (curDeclFunc, OpCodes.Leave, retLabel);
1339 }
1340
1341 /*
1342 * End of the code to be optimized.
1343 * Do optimizations then write it all out to object file.
1344 * After this, all code gets written directly to object file.
1345 * Optimization must be completed before we scan the allCallLabels
1346 * list below to look for active locals and temps.
1347 */
1348 collector.Optimize ();
1349 _ilGen = collector.WriteOutAll ();
1350 collector = null;
1351
1352 /*
1353 * Output code to restore stack frame from stream.
1354 * It jumps back to the call labels within the function body.
1355 */
1356 List<ScriptMyLocal> activeTemps = null;
1357 if (!isTrivial) {
1358
1359 /*
1360 * Build list of locals and temps active at all the call labels.
1361 */
1362 activeTemps = new List<ScriptMyLocal> ();
1363 foreach (CallLabel cl in allCallLabels) {
1364 foreach (ScriptMyLocal lcl in cl.callLabel.whereAmI.localsReadBeforeWritten) {
1365 if (!activeTemps.Contains (lcl)) {
1366 activeTemps.Add (lcl);
1367 }
1368 }
1369 }
1370
1371 /*
1372 * Output code to restore the args, locals and temps then jump to
1373 * the call label that we were interrupted at.
1374 */
1375 ilGen.MarkLabel (cmRestore);
1376 GenerateFrameRestoreCode (activeTemps);
1377 }
1378
1379 /*
1380 * Output epilog that saves stack frame state if CallMode_SAVE.
1381 *
1382 * finally {
1383 * if (instance.callMode != CallMode_SAVE) goto __endFin;
1384 * GenerateFrameCaptureCode();
1385 * __endFin:
1386 * }
1387 */
1388 ScriptMyLabel endFin = null;
1389 if (!isTrivial) {
1390 ilGen.BeginFinallyBlock ();
1391 endFin = ilGen.DefineLabel ("__endFin");
1392 PushXMRInst ();
1393 ilGen.Emit (curDeclFunc, OpCodes.Ldfld, callModeFieldInfo);
1394 ilGen.Emit (curDeclFunc, OpCodes.Ldc_I4, XMRInstAbstract.CallMode_SAVE);
1395 ilGen.Emit (curDeclFunc, OpCodes.Bne_Un, endFin);
1396 GenerateFrameCaptureCode (activeTemps);
1397 ilGen.MarkLabel (endFin);
1398 ilGen.Emit (curDeclFunc, OpCodes.Endfinally);
1399 ilGen.EndExceptionBlock ();
1400 }
1401
1402 /*
1403 * Output the 'real' return opcode.
1404 */
1405 ilGen.MarkLabel (retLabel);
1406 if (!(curDeclFunc.retType is TokenTypeVoid)) {
1407 ilGen.Emit (curDeclFunc, OpCodes.Ldloc, retValue);
1408 }
1409 ilGen.Emit (curDeclFunc, OpCodes.Ret);
1410 retLabel = null;
1411 retValue = null;
1412
1413 /*
1414 * No more instructions for this method.
1415 */
1416 ((ScriptObjWriter)ilGen).EndMethod ();
1417 _ilGen = null;
1418
1419 /*
1420 * Not generating function code any more.
1421 */
1422 curBreakTarg = null;
1423 curContTarg = null;
1424 curDeclFunc = null;
1425 }
1426
1427 /**
1428 * @brief Allocate stack space for all local variables, regardless of
1429 * which { } statement block they are actually defined in.
1430 */
1431 private void AllocLocalVarStackSpace ()
1432 {
1433 foreach (TokenDeclVar localVar in curDeclFunc.localVars) {
1434
1435 /*
1436 * Skip all 'constant' vars as they were handled by the reducer.
1437 */
1438 if (localVar.constant) continue;
1439
1440 /*
1441 * Get a stack location for the local variable.
1442 */
1443 localVar.location = new CompValuLocalVar (localVar.type, localVar.name.val, this);
1444 }
1445 }
1446
1447 /**
1448 * @brief Generate code to write all arguments and locals to the capture stack frame.
1449 * This includes temp variables.
1450 * We only need to save what is active at the point of callLabels through because
1451 * those are the only points we will jump to on restore. This saves us from saving
1452 * all the little temp vars we create.
1453 * @param activeTemps = list of locals and temps that we care about, ie, which
1454 * ones get restored by GenerateFrameRestoreCode().
1455 */
1456 private void GenerateFrameCaptureCode (List<ScriptMyLocal> activeTemps)
1457 {
1458 /*
1459 * Compute total number of slots we need to save stuff.
1460 * Assume we need to save all call arguments.
1461 */
1462 int nSaves = curDeclFunc.argDecl.vars.Length + activeTemps.Count;
1463
1464 /*
1465 * Output code to allocate a stack frame object with an object array.
1466 * This also pushes the stack frame object on the instance.stackFrames list.
1467 * It returns a pointer to the object array it allocated.
1468 */
1469 PushXMRInst ();
1470 ilGen.Emit (curDeclFunc, OpCodes.Ldstr, ilGen.methName);
1471 GetCallNo (curDeclFunc, actCallNo);
1472 ilGen.Emit (curDeclFunc, OpCodes.Ldc_I4, nSaves);
1473 ilGen.Emit (curDeclFunc, OpCodes.Call, captureStackFrameMethodInfo);
1474
1475 if (DEBUG_STACKCAPRES) {
1476 ilGen.Emit (curDeclFunc, OpCodes.Ldstr, ilGen.methName + "*: capture mainCallNo=");
1477 ilGen.Emit (curDeclFunc, OpCodes.Call, consoleWriteMethodInfo);
1478 ilGen.Emit (curDeclFunc, OpCodes.Ldloc, actCallNo);
1479 ilGen.Emit (curDeclFunc, OpCodes.Box, typeof (int));
1480 ilGen.Emit (curDeclFunc, OpCodes.Call, consoleWriteMethodInfo);
1481 }
1482
1483 /*
1484 * Copy arg values to object array, boxing as needed.
1485 */
1486 int i = 0;
1487 foreach (TokenDeclVar argVar in curDeclFunc.argDecl.varDict) {
1488 ilGen.Emit (curDeclFunc, OpCodes.Dup);
1489 ilGen.Emit (curDeclFunc, OpCodes.Ldc_I4, i);
1490 argVar.location.PushVal (this, argVar.name, tokenTypeObj);
1491 if (DEBUG_STACKCAPRES) {
1492 ilGen.Emit (curDeclFunc, OpCodes.Ldstr, "\n arg:" + argVar.name.val + "=");
1493 ilGen.Emit (curDeclFunc, OpCodes.Call, consoleWriteMethodInfo);
1494 ilGen.Emit (curDeclFunc, OpCodes.Dup);
1495 ilGen.Emit (curDeclFunc, OpCodes.Call, consoleWriteMethodInfo);
1496 }
1497 ilGen.Emit (curDeclFunc, OpCodes.Stelem_Ref);
1498 i ++;
1499 }
1500
1501 /*
1502 * Copy local and temp values to object array, boxing as needed.
1503 */
1504 foreach (ScriptMyLocal lcl in activeTemps) {
1505 ilGen.Emit (curDeclFunc, OpCodes.Dup);
1506 ilGen.Emit (curDeclFunc, OpCodes.Ldc_I4, i ++);
1507 ilGen.Emit (curDeclFunc, OpCodes.Ldloc, lcl);
1508 Type t = lcl.type;
1509 if (t == typeof (HeapTrackerList)) {
1510 t = HeapTrackerList.GenPush (curDeclFunc, ilGen);
1511 }
1512 if (t == typeof (HeapTrackerObject)) {
1513 t = HeapTrackerObject.GenPush (curDeclFunc, ilGen);
1514 }
1515 if (t == typeof(HeapTrackerString)) {
1516 t = HeapTrackerString.GenPush (curDeclFunc, ilGen);
1517 }
1518 if (t.IsValueType) {
1519 ilGen.Emit (curDeclFunc, OpCodes.Box, t);
1520 }
1521 if (DEBUG_STACKCAPRES) {
1522 ilGen.Emit (curDeclFunc, OpCodes.Ldstr, "\n lcl:" + lcl.name + "=");
1523 ilGen.Emit (curDeclFunc, OpCodes.Call, consoleWriteMethodInfo);
1524 ilGen.Emit (curDeclFunc, OpCodes.Dup);
1525 ilGen.Emit (curDeclFunc, OpCodes.Call, consoleWriteMethodInfo);
1526 }
1527 ilGen.Emit (curDeclFunc, OpCodes.Stelem_Ref);
1528 }
1529 if (DEBUG_STACKCAPRES) {
1530 ilGen.Emit (curDeclFunc, OpCodes.Ldstr, "\n");
1531 ilGen.Emit (curDeclFunc, OpCodes.Call, consoleWriteMethodInfo);
1532 }
1533
1534 ilGen.Emit (curDeclFunc, OpCodes.Pop);
1535 }
1536
1537 /**
1538 * @brief Generate code to restore all arguments and locals from the restore stack frame.
1539 * This includes temp variables.
1540 */
1541 private void GenerateFrameRestoreCode (List<ScriptMyLocal> activeTemps)
1542 {
1543 ScriptMyLocal objArray = ilGen.DeclareLocal (typeof (object[]), "__restObjArray");
1544
1545 /*
1546 * Output code to pop stack frame from instance.stackFrames.
1547 * It returns a pointer to the object array that contains values to be restored.
1548 */
1549 PushXMRInst ();
1550 ilGen.Emit (curDeclFunc, OpCodes.Ldstr, ilGen.methName);
1551 ilGen.Emit (curDeclFunc, OpCodes.Ldloca, actCallNo); // __mainCallNo
1552 ilGen.Emit (curDeclFunc, OpCodes.Call, restoreStackFrameMethodInfo);
1553 ilGen.Emit (curDeclFunc, OpCodes.Stloc, objArray);
1554 if (DEBUG_STACKCAPRES) {
1555 ilGen.Emit (curDeclFunc, OpCodes.Ldstr, ilGen.methName + "*: restore mainCallNo=");
1556 ilGen.Emit (curDeclFunc, OpCodes.Call, consoleWriteMethodInfo);
1557 ilGen.Emit (curDeclFunc, OpCodes.Ldloc, actCallNo);
1558 ilGen.Emit (curDeclFunc, OpCodes.Box, typeof (int));
1559 ilGen.Emit (curDeclFunc, OpCodes.Call, consoleWriteMethodInfo);
1560 }
1561
1562 /*
1563 * Restore argument values from object array, unboxing as needed.
1564 * Although the caller has restored them to what it called us with, it's possible that this
1565 * function has modified them since, so we need to do our own restore.
1566 */
1567 int i = 0;
1568 foreach (TokenDeclVar argVar in curDeclFunc.argDecl.varDict) {
1569 CompValu argLoc = argVar.location;
1570 argLoc.PopPre (this, argVar.name);
1571 ilGen.Emit (curDeclFunc, OpCodes.Ldloc, objArray);
1572 ilGen.Emit (curDeclFunc, OpCodes.Ldc_I4, i);
1573 ilGen.Emit (curDeclFunc, OpCodes.Ldelem_Ref);
1574 if (DEBUG_STACKCAPRES) {
1575 ilGen.Emit (curDeclFunc, OpCodes.Ldstr, "\n arg:" + argVar.name.val + "=");
1576 ilGen.Emit (curDeclFunc, OpCodes.Call, consoleWriteMethodInfo);
1577 ilGen.Emit (curDeclFunc, OpCodes.Dup);
1578 ilGen.Emit (curDeclFunc, OpCodes.Call, consoleWriteMethodInfo);
1579 }
1580 TypeCast.CastTopOfStack (this, argVar.name, tokenTypeObj, argLoc.type, true);
1581 argLoc.PopPost (this, argVar.name);
1582 i ++;
1583 }
1584
1585 /*
1586 * Restore local and temp values from object array, unboxing as needed.
1587 */
1588 foreach (ScriptMyLocal lcl in activeTemps) {
1589 Type t = lcl.type;
1590 Type u = t;
1591 if (t == typeof (HeapTrackerList)) u = typeof (LSL_List);
1592 if (t == typeof (HeapTrackerObject)) u = typeof (object);
1593 if (t == typeof (HeapTrackerString)) u = typeof (string);
1594 if (u != t) {
1595 ilGen.Emit (curDeclFunc, OpCodes.Ldloc, lcl);
1596 }
1597 ilGen.Emit (curDeclFunc, OpCodes.Ldloc, objArray);
1598 ilGen.Emit (curDeclFunc, OpCodes.Ldc_I4, i ++);
1599 ilGen.Emit (curDeclFunc, OpCodes.Ldelem_Ref);
1600 if (DEBUG_STACKCAPRES) {
1601 ilGen.Emit (curDeclFunc, OpCodes.Ldstr, "\n lcl:" + lcl.name + "=");
1602 ilGen.Emit (curDeclFunc, OpCodes.Call, consoleWriteMethodInfo);
1603 ilGen.Emit (curDeclFunc, OpCodes.Dup);
1604 ilGen.Emit (curDeclFunc, OpCodes.Call, consoleWriteMethodInfo);
1605 }
1606 if (u.IsValueType) {
1607 ilGen.Emit (curDeclFunc, OpCodes.Unbox_Any, u);
1608 } else if (u != typeof (object)) {
1609 ilGen.Emit (curDeclFunc, OpCodes.Castclass, u);
1610 }
1611 if (u != t) {
1612 if (t == typeof (HeapTrackerList)) HeapTrackerList.GenPop (curDeclFunc, ilGen);
1613 if (t == typeof (HeapTrackerObject)) HeapTrackerObject.GenPop (curDeclFunc, ilGen);
1614 if (t == typeof (HeapTrackerString)) HeapTrackerString.GenPop (curDeclFunc, ilGen);
1615 } else {
1616 ilGen.Emit (curDeclFunc, OpCodes.Stloc, lcl);
1617 }
1618 }
1619 if (DEBUG_STACKCAPRES) {
1620 ilGen.Emit (curDeclFunc, OpCodes.Ldstr, "\n");
1621 ilGen.Emit (curDeclFunc, OpCodes.Call, consoleWriteMethodInfo);
1622 }
1623
1624 OutputCallNoSwitchStmt ();
1625 }
1626
1627 /**
1628 * @brief Output a switch statement with a case for each possible
1629 * value of whatever callNo is currently active, either
1630 * __mainCallNo or one of the try/catch/finally's callNos.
1631 *
1632 * switch (callNo) {
1633 * case 0: goto __call_0;
1634 * case 1: goto __call_1;
1635 * ...
1636 * }
1637 * throw new ScriptBadCallNoException (callNo);
1638 */
1639 private void OutputCallNoSwitchStmt ()
1640 {
1641 ScriptMyLabel[] callLabels = new ScriptMyLabel[actCallLabels.Count];
1642 foreach (CallLabel cl in actCallLabels) {
1643 callLabels[cl.index] = cl.callLabel;
1644 }
1645 GetCallNo (curDeclFunc, actCallNo);
1646 ilGen.Emit (curDeclFunc, OpCodes.Switch, callLabels);
1647
1648 GetCallNo (curDeclFunc, actCallNo);
1649 ilGen.Emit (curDeclFunc, OpCodes.Newobj, scriptBadCallNoExceptionConstructorInfo);
1650 ilGen.Emit (curDeclFunc, OpCodes.Throw);
1651 }
1652
1653 /**
1654 * @brief There is one of these per call that can possibly call CheckRun(),
1655 * including direct calls to CheckRun().
1656 * They mark points that the stack capture/restore code will save & restore to.
1657 * All object-code level local vars active at the call label's point will
1658 * be saved & restored.
1659 *
1660 * callNo = 5;
1661 * __call_5:
1662 * push call arguments from temps
1663 * call SomethingThatCallsCheckRun()
1664 *
1665 * If SomethingThatCallsCheckRun() actually calls CheckRun(), our restore code
1666 * will restore our args, locals & temps, then jump to __call_5, which will then
1667 * call SomethingThatCallsCheckRun() again, which will restore its stuff likewise.
1668 * When eventually the actual CheckRun() call is restored, it will turn off restore
1669 * mode (by changing callMode from CallMode_RESTORE to CallMode_NORMAL) and return,
1670 * allowing the code to run normally from that point.
1671 */
1672 public class CallLabel {
1673 public int index; // sequential integer, starting at 0, within actCallLabels
1674 // - used for the switch statement
1675 public ScriptMyLabel callLabel; // the actual label token
1676
1677 public CallLabel (ScriptCodeGen scg, Token errorAt)
1678 {
1679 if (scg.openCallLabel != null) throw new Exception ("call label already open");
1680
1681 if (!scg.curDeclFunc.IsFuncTrivial (scg)) {
1682 this.index = scg.actCallLabels.Count;
1683 string name = "__call_" + index + "_" + scg.allCallLabels.Count;
1684
1685 /*
1686 * Make sure eval stack is empty because the frame capture/restore
1687 * code expects such (restore switch stmt has an empty stack).
1688 */
1689 int depth = ((ScriptCollector)scg.ilGen).stackDepth.Count;
1690 if (depth > 0) {
1691 // maybe need to call Trivialize()
1692 throw new Exception ("call label stack depth " + depth + " at " + errorAt.SrcLoc);
1693 }
1694
1695 /*
1696 * Eval stack is empty so the restore code can handle it.
1697 */
1698 this.index = scg.actCallLabels.Count;
1699 scg.actCallLabels.AddLast (this);
1700 scg.allCallLabels.AddLast (this);
1701 this.callLabel = scg.ilGen.DefineLabel (name);
1702 scg.SetCallNo (errorAt, scg.actCallNo, this.index);
1703 scg.ilGen.MarkLabel (this.callLabel);
1704 }
1705
1706 scg.openCallLabel = this;
1707 }
1708 };
1709
1710 /**
1711 * @brief generate code for an arbitrary statement.
1712 */
1713 private void GenerateStmt (TokenStmt stmt)
1714 {
1715 errorMessageToken = stmt;
1716 if (stmt is TokenDeclVar) { GenerateDeclVar ((TokenDeclVar)stmt); return; }
1717 if (stmt is TokenStmtBlock) { GenerateStmtBlock ((TokenStmtBlock)stmt); return; }
1718 if (stmt is TokenStmtBreak) { GenerateStmtBreak ((TokenStmtBreak)stmt); return; }
1719 if (stmt is TokenStmtCont) { GenerateStmtCont ((TokenStmtCont)stmt); return; }
1720 if (stmt is TokenStmtDo) { GenerateStmtDo ((TokenStmtDo)stmt); return; }
1721 if (stmt is TokenStmtFor) { GenerateStmtFor ((TokenStmtFor)stmt); return; }
1722 if (stmt is TokenStmtForEach) { GenerateStmtForEach ((TokenStmtForEach)stmt); return; }
1723 if (stmt is TokenStmtIf) { GenerateStmtIf ((TokenStmtIf)stmt); return; }
1724 if (stmt is TokenStmtJump) { GenerateStmtJump ((TokenStmtJump)stmt); return; }
1725 if (stmt is TokenStmtLabel) { GenerateStmtLabel ((TokenStmtLabel)stmt); return; }
1726 if (stmt is TokenStmtNewobj) { GenerateStmtNewobj ((TokenStmtNewobj)stmt); return; }
1727 if (stmt is TokenStmtNull) { return; }
1728 if (stmt is TokenStmtRet) { GenerateStmtRet ((TokenStmtRet)stmt); return; }
1729 if (stmt is TokenStmtRVal) { GenerateStmtRVal ((TokenStmtRVal)stmt); return; }
1730 if (stmt is TokenStmtState) { GenerateStmtState ((TokenStmtState)stmt); return; }
1731 if (stmt is TokenStmtSwitch) { GenerateStmtSwitch ((TokenStmtSwitch)stmt); return; }
1732 if (stmt is TokenStmtThrow) { GenerateStmtThrow ((TokenStmtThrow)stmt); return; }
1733 if (stmt is TokenStmtTry) { GenerateStmtTry ((TokenStmtTry)stmt); return; }
1734 if (stmt is TokenStmtVarIniDef) { GenerateStmtVarIniDef ((TokenStmtVarIniDef)stmt); return; }
1735 if (stmt is TokenStmtWhile) { GenerateStmtWhile ((TokenStmtWhile)stmt); return; }
1736 throw new Exception ("unknown TokenStmt type " + stmt.GetType ().ToString ());
1737 }
1738
1739 /**
1740 * @brief generate statement block (ie, with braces)
1741 */
1742 private void GenerateStmtBlock (TokenStmtBlock stmtBlock)
1743 {
1744 if (!mightGetHere) return;
1745
1746 /*
1747 * Push new current statement block pointer for anyone who cares.
1748 */
1749 TokenStmtBlock oldStmtBlock = curStmtBlock;
1750 curStmtBlock = stmtBlock;
1751
1752 /*
1753 * Output the statements that make up the block.
1754 */
1755 for (Token t = stmtBlock.statements; t != null; t = t.nextToken) {
1756 GenerateStmt ((TokenStmt)t);
1757 }
1758
1759 /*
1760 * Pop the current statement block.
1761 */
1762 curStmtBlock = oldStmtBlock;
1763 }
1764
1765 /**
1766 * @brief output code for a 'break' statement
1767 */
1768 private void GenerateStmtBreak (TokenStmtBreak breakStmt)
1769 {
1770 if (!mightGetHere) return;
1771
1772 /*
1773 * Make sure we are in a breakable situation.
1774 */
1775 if (curBreakTarg == null) {
1776 ErrorMsg (breakStmt, "not in a breakable situation");
1777 return;
1778 }
1779
1780 /*
1781 * Tell anyone who cares that the break target was actually used.
1782 */
1783 curBreakTarg.used = true;
1784
1785 /*
1786 * Output the instructions.
1787 */
1788 EmitJumpCode (curBreakTarg.label, curBreakTarg.block, breakStmt);
1789 }
1790
1791 /**
1792 * @brief output code for a 'continue' statement
1793 */
1794 private void GenerateStmtCont (TokenStmtCont contStmt)
1795 {
1796 if (!mightGetHere) return;
1797
1798 /*
1799 * Make sure we are in a contable situation.
1800 */
1801 if (curContTarg == null) {
1802 ErrorMsg (contStmt, "not in a continueable situation");
1803 return;
1804 }
1805
1806 /*
1807 * Tell anyone who cares that the continue target was actually used.
1808 */
1809 curContTarg.used = true;
1810
1811 /*
1812 * Output the instructions.
1813 */
1814 EmitJumpCode (curContTarg.label, curContTarg.block, contStmt);
1815 }
1816
1817 /**
1818 * @brief output code for a 'do' statement
1819 */
1820 private void GenerateStmtDo (TokenStmtDo doStmt)
1821 {
1822 if (!mightGetHere) return;
1823
1824 BreakContTarg oldBreakTarg = curBreakTarg;
1825 BreakContTarg oldContTarg = curContTarg;
1826 ScriptMyLabel loopLabel = ilGen.DefineLabel ("doloop_" + doStmt.Unique);
1827
1828 curBreakTarg = new BreakContTarg (this, "dobreak_" + doStmt.Unique);
1829 curContTarg = new BreakContTarg (this, "docont_" + doStmt.Unique);
1830
1831 ilGen.MarkLabel (loopLabel);
1832 GenerateStmt (doStmt.bodyStmt);
1833 if (curContTarg.used) {
1834 ilGen.MarkLabel (curContTarg.label);
1835 mightGetHere = true;
1836 }
1837
1838 if (mightGetHere) {
1839 EmitCallCheckRun (doStmt, false);
1840 CompValu testRVal = GenerateFromRVal (doStmt.testRVal);
1841 if (IsConstBoolExprTrue (testRVal)) {
1842
1843 /*
1844 * Unconditional looping, unconditional branch and
1845 * say we never fall through to next statement.
1846 */
1847 ilGen.Emit (doStmt, OpCodes.Br, loopLabel);
1848 mightGetHere = false;
1849 } else {
1850
1851 /*
1852 * Conditional looping, test and brach back to top of loop.
1853 */
1854 testRVal.PushVal (this, doStmt.testRVal, tokenTypeBool);
1855 ilGen.Emit (doStmt, OpCodes.Brtrue, loopLabel);
1856 }
1857 }
1858
1859 /*
1860 * If 'break' statement was used, output target label.
1861 * And assume that since a 'break' statement was used, it's possible for the code to get here.
1862 */
1863 if (curBreakTarg.used) {
1864 ilGen.MarkLabel (curBreakTarg.label);
1865 mightGetHere = true;
1866 }
1867
1868 curBreakTarg = oldBreakTarg;
1869 curContTarg = oldContTarg;
1870 }
1871
1872 /**
1873 * @brief output code for a 'for' statement
1874 */
1875 private void GenerateStmtFor (TokenStmtFor forStmt)
1876 {
1877 if (!mightGetHere) return;
1878
1879 BreakContTarg oldBreakTarg = curBreakTarg;
1880 BreakContTarg oldContTarg = curContTarg;
1881 ScriptMyLabel loopLabel = ilGen.DefineLabel ("forloop_" + forStmt.Unique);
1882
1883 curBreakTarg = new BreakContTarg (this, "forbreak_" + forStmt.Unique);
1884 curContTarg = new BreakContTarg (this, "forcont_" + forStmt.Unique);
1885
1886 if (forStmt.initStmt != null) {
1887 GenerateStmt (forStmt.initStmt);
1888 }
1889 ilGen.MarkLabel (loopLabel);
1890
1891 /*
1892 * See if we have a test expression that is other than a constant TRUE.
1893 * If so, test it and conditionally branch to end if false.
1894 */
1895 if (forStmt.testRVal != null) {
1896 CompValu testRVal = GenerateFromRVal (forStmt.testRVal);
1897 if (!IsConstBoolExprTrue (testRVal)) {
1898 testRVal.PushVal (this, forStmt.testRVal, tokenTypeBool);
1899 ilGen.Emit (forStmt, OpCodes.Brfalse, curBreakTarg.label);
1900 curBreakTarg.used = true;
1901 }
1902 }
1903
1904 /*
1905 * Output loop body.
1906 */
1907 GenerateStmt (forStmt.bodyStmt);
1908
1909 /*
1910 * Here's where a 'continue' statement jumps to.
1911 */
1912 if (curContTarg.used) {
1913 ilGen.MarkLabel (curContTarg.label);
1914 mightGetHere = true;
1915 }
1916
1917 if (mightGetHere) {
1918
1919 /*
1920 * After checking for excessive CPU time, output increment statement, if any.
1921 */
1922 EmitCallCheckRun (forStmt, false);
1923 if (forStmt.incrRVal != null) {
1924 GenerateFromRVal (forStmt.incrRVal);
1925 }
1926
1927 /*
1928 * Unconditional branch back to beginning of loop.
1929 */
1930 ilGen.Emit (forStmt, OpCodes.Br, loopLabel);
1931 }
1932
1933 /*
1934 * If test needs label, output label for it to jump to.
1935 * Otherwise, clear mightGetHere as we know loop never
1936 * falls out the bottom.
1937 */
1938 mightGetHere = curBreakTarg.used;
1939 if (mightGetHere) {
1940 ilGen.MarkLabel (curBreakTarg.label);
1941 }
1942
1943 curBreakTarg = oldBreakTarg;
1944 curContTarg = oldContTarg;
1945 }
1946
1947 private void GenerateStmtForEach (TokenStmtForEach forEachStmt)
1948 {
1949 if (!mightGetHere) return;
1950
1951 BreakContTarg oldBreakTarg = curBreakTarg;
1952 BreakContTarg oldContTarg = curContTarg;
1953 CompValu keyLVal = null;
1954 CompValu valLVal = null;
1955 CompValu arrayRVal = GenerateFromRVal (forEachStmt.arrayRVal);
1956
1957 if (forEachStmt.keyLVal != null) {
1958 keyLVal = GenerateFromLVal (forEachStmt.keyLVal);
1959 if (!(keyLVal.type is TokenTypeObject)) {
1960 ErrorMsg (forEachStmt.arrayRVal, "must be object");
1961 }
1962 }
1963 if (forEachStmt.valLVal != null) {
1964 valLVal = GenerateFromLVal (forEachStmt.valLVal);
1965 if (!(valLVal.type is TokenTypeObject)) {
1966 ErrorMsg (forEachStmt.arrayRVal, "must be object");
1967 }
1968 }
1969 if (!(arrayRVal.type is TokenTypeArray)) {
1970 ErrorMsg (forEachStmt.arrayRVal, "must be an array");
1971 }
1972
1973 curBreakTarg = new BreakContTarg (this, "foreachbreak_" + forEachStmt.Unique);
1974 curContTarg = new BreakContTarg (this, "foreachcont_" + forEachStmt.Unique);
1975
1976 CompValuTemp indexVar = new CompValuTemp (new TokenTypeInt (forEachStmt), this);
1977 ScriptMyLabel loopLabel = ilGen.DefineLabel ("foreachloop_" + forEachStmt.Unique);
1978
1979 // indexVar = 0
1980 ilGen.Emit (forEachStmt, OpCodes.Ldc_I4_0);
1981 indexVar.Pop (this, forEachStmt);
1982
1983 ilGen.MarkLabel (loopLabel);
1984
1985 // key = array.__pub_index (indexVar);
1986 // if (key == null) goto curBreakTarg;
1987 if (keyLVal != null) {
1988 keyLVal.PopPre (this, forEachStmt.keyLVal);
1989 arrayRVal.PushVal (this, forEachStmt.arrayRVal);
1990 indexVar.PushVal (this, forEachStmt);
1991 ilGen.Emit (forEachStmt, OpCodes.Call, xmrArrPubIndexMethod);
1992 keyLVal.PopPost (this, forEachStmt.keyLVal);
1993 keyLVal.PushVal (this, forEachStmt.keyLVal);
1994 ilGen.Emit (forEachStmt, OpCodes.Brfalse, curBreakTarg.label);
1995 curBreakTarg.used = true;
1996 }
1997
1998 // val = array._pub_value (indexVar);
1999 // if (val == null) goto curBreakTarg;
2000 if (valLVal != null) {
2001 valLVal.PopPre (this, forEachStmt.valLVal);
2002 arrayRVal.PushVal (this, forEachStmt.arrayRVal);
2003 indexVar.PushVal (this, forEachStmt);
2004 ilGen.Emit (forEachStmt, OpCodes.Call, xmrArrPubValueMethod);
2005 valLVal.PopPost (this, forEachStmt.valLVal);
2006 if (keyLVal == null) {
2007 valLVal.PushVal (this, forEachStmt.valLVal);
2008 ilGen.Emit (forEachStmt, OpCodes.Brfalse, curBreakTarg.label);
2009 curBreakTarg.used = true;
2010 }
2011 }
2012
2013 // indexVar ++;
2014 indexVar.PushVal (this, forEachStmt);
2015 ilGen.Emit (forEachStmt, OpCodes.Ldc_I4_1);
2016 ilGen.Emit (forEachStmt, OpCodes.Add);
2017 indexVar.Pop (this, forEachStmt);
2018
2019 // body statement
2020 GenerateStmt (forEachStmt.bodyStmt);
2021
2022 // continue label
2023 if (curContTarg.used) {
2024 ilGen.MarkLabel (curContTarg.label);
2025 mightGetHere = true;
2026 }
2027
2028 // call CheckRun()
2029 if (mightGetHere) {
2030 EmitCallCheckRun (forEachStmt, false);
2031 ilGen.Emit (forEachStmt, OpCodes.Br, loopLabel);
2032 }
2033
2034 // break label
2035 ilGen.MarkLabel (curBreakTarg.label);
2036 mightGetHere = true;
2037
2038 curBreakTarg = oldBreakTarg;
2039 curContTarg = oldContTarg;
2040 }
2041
2042 /**
2043 * @brief output code for an 'if' statement
2044 * Braces are necessary because what may be one statement for trueStmt or elseStmt in
2045 * the script may translate to more than one statement in the resultant C# code.
2046 */
2047 private void GenerateStmtIf (TokenStmtIf ifStmt)
2048 {
2049 if (!mightGetHere) return;
2050
2051 bool constVal;
2052
2053 /*
2054 * Test condition and see if constant test expression.
2055 */
2056 CompValu testRVal = GenerateFromRVal (ifStmt.testRVal);
2057 if (IsConstBoolExpr (testRVal, out constVal)) {
2058
2059 /*
2060 * Constant, output just either the true or else part.
2061 */
2062 if (constVal) {
2063 GenerateStmt (ifStmt.trueStmt);
2064 } else if (ifStmt.elseStmt != null) {
2065 GenerateStmt (ifStmt.elseStmt);
2066 }
2067 } else if (ifStmt.elseStmt == null) {
2068
2069 /*
2070 * This is an 'if' statement without an 'else' clause.
2071 */
2072 testRVal.PushVal (this, ifStmt.testRVal, tokenTypeBool);
2073 ScriptMyLabel doneLabel = ilGen.DefineLabel ("ifdone_" + ifStmt.Unique);
2074 ilGen.Emit (ifStmt, OpCodes.Brfalse, doneLabel); // brfalse doneLabel
2075 GenerateStmt (ifStmt.trueStmt); // generate true body code
2076 ilGen.MarkLabel (doneLabel);
2077 mightGetHere = true; // there's always a possibility of getting here
2078 } else {
2079
2080 /*
2081 * This is an 'if' statement with an 'else' clause.
2082 */
2083 testRVal.PushVal (this, ifStmt.testRVal, tokenTypeBool);
2084 ScriptMyLabel elseLabel = ilGen.DefineLabel ("ifelse_" + ifStmt.Unique);
2085 ilGen.Emit (ifStmt, OpCodes.Brfalse, elseLabel); // brfalse elseLabel
2086 GenerateStmt (ifStmt.trueStmt); // generate true body code
2087 bool trueMightGetHere = mightGetHere; // save whether or not true falls through
2088 ScriptMyLabel doneLabel = ilGen.DefineLabel ("ifdone_" + ifStmt.Unique);
2089 ilGen.Emit (ifStmt, OpCodes.Br, doneLabel); // branch to done
2090 ilGen.MarkLabel (elseLabel); // beginning of else code
2091 mightGetHere = true; // the top of the else might be executed
2092 GenerateStmt (ifStmt.elseStmt); // output else code
2093 ilGen.MarkLabel (doneLabel); // where end of true clause code branches to
2094 mightGetHere |= trueMightGetHere; // gets this far if either true or else falls through
2095 }
2096 }
2097
2098 /**
2099 * @brief output code for a 'jump' statement
2100 */
2101 private void GenerateStmtJump (TokenStmtJump jumpStmt)
2102 {
2103 if (!mightGetHere) return;
2104
2105 /*
2106 * Make sure the target label is defined somewhere in the function.
2107 */
2108 TokenStmtLabel stmtLabel;
2109 if (!curDeclFunc.labels.TryGetValue (jumpStmt.label.val, out stmtLabel)) {
2110 ErrorMsg (jumpStmt, "undefined label " + jumpStmt.label.val);
2111 return;
2112 }
2113 if (!stmtLabel.labelTagged) {
2114 stmtLabel.labelStruct = ilGen.DefineLabel ("jump_" + stmtLabel.name.val);
2115 stmtLabel.labelTagged = true;
2116 }
2117
2118 /*
2119 * Emit instructions to do the jump.
2120 */
2121 EmitJumpCode (stmtLabel.labelStruct, stmtLabel.block, jumpStmt);
2122 }
2123
2124 /**
2125 * @brief Emit code to jump to a label
2126 * @param target = label being jumped to
2127 * @param targetsBlock = { ... } the label is defined in
2128 */
2129 private void EmitJumpCode (ScriptMyLabel target, TokenStmtBlock targetsBlock, Token errorAt)
2130 {
2131 /*
2132 * Jumps never fall through.
2133 */
2134 mightGetHere = false;
2135
2136 /*
2137 * Find which block the target label is in. Must be in this or an outer block,
2138 * no laterals allowed. And if we exit a try/catch block, use Leave instead of Br.
2139 *
2140 * jump lateral;
2141 * {
2142 * @lateral;
2143 * }
2144 */
2145 bool useLeave = false;
2146 TokenStmtBlock stmtBlock;
2147 Stack<TokenStmtTry> finallyBlocksCalled = new Stack<TokenStmtTry> ();
2148 for (stmtBlock = curStmtBlock; stmtBlock != targetsBlock; stmtBlock = stmtBlock.outerStmtBlock) {
2149 if (stmtBlock == null) {
2150 ErrorMsg (errorAt, "no lateral jumps allowed");
2151 return;
2152 }
2153 if (stmtBlock.isFinally) {
2154 ErrorMsg (errorAt, "cannot jump out of finally");
2155 return;
2156 }
2157 if (stmtBlock.isTry || stmtBlock.isCatch) useLeave = true;
2158 if ((stmtBlock.tryStmt != null) && (stmtBlock.tryStmt.finallyStmt != null)) {
2159 finallyBlocksCalled.Push (stmtBlock.tryStmt);
2160 }
2161 }
2162
2163 /*
2164 * If popping through more than one finally block, we have to break it down for the stack
2165 * capture and restore code, one finally block at a time.
2166 *
2167 * try {
2168 * try {
2169 * try {
2170 * jump exit;
2171 * } finally {
2172 * llOwnerSay ("exiting inner");
2173 * }
2174 * } finally {
2175 * llOwnerSay ("exiting middle");
2176 * }
2177 * } finally {
2178 * llOwnerSay ("exiting outer");
2179 * }
2180 * @exit;
2181 *
2182 * try {
2183 * try {
2184 * try {
2185 * jump intr2_exit; <<< gets its own tryNo call label so inner try knows where to restore to
2186 * } finally {
2187 * llOwnerSay ("exiting inner");
2188 * }
2189 * jump outtry2;
2190 * @intr2_exit; jump intr1_exit; <<< gets its own tryNo call label so middle try knows where to restore to
2191 * @outtry2;
2192 * } finally {
2193 * llOwnerSay ("exiting middle");
2194 * }
2195 * jump outtry1;
2196 * @intr1_exit: jump exit; <<< gets its own tryNo call label so outer try knows where to restore to
2197 * @outtry1;
2198 * } finally {
2199 * llOwnerSay ("exiting outer");
2200 * }
2201 * @exit;
2202 */
2203 int level = 0;
2204 while (finallyBlocksCalled.Count > 1) {
2205 TokenStmtTry finallyBlock = finallyBlocksCalled.Pop ();
2206 string intername = "intr" + (++ level) + "_" + target.name;
2207 IntermediateLeave iLeave;
2208 if (!finallyBlock.iLeaves.TryGetValue (intername, out iLeave)) {
2209 iLeave = new IntermediateLeave ();
2210 iLeave.jumpIntoLabel = ilGen.DefineLabel (intername);
2211 iLeave.jumpAwayLabel = target;
2212 finallyBlock.iLeaves.Add (intername, iLeave);
2213 }
2214 target = iLeave.jumpIntoLabel;
2215 }
2216
2217 /*
2218 * Finally output the branch/leave opcode.
2219 * If using Leave, prefix with a call label in case the corresponding finally block
2220 * calls CheckRun() and that CheckRun() captures the stack, it will have a point to
2221 * restore to that will properly jump back into the finally block.
2222 */
2223 if (useLeave) {
2224 new CallLabel (this, errorAt);
2225 ilGen.Emit (errorAt, OpCodes.Leave, target);
2226 openCallLabel = null;
2227 } else {
2228 ilGen.Emit (errorAt, OpCodes.Br, target);
2229 }
2230 }
2231
2232 /**
2233 * @brief output code for a jump target label statement.
2234 * If there are any backward jumps to the label, do a CheckRun() also.
2235 */
2236 private void GenerateStmtLabel (TokenStmtLabel labelStmt)
2237 {
2238 if (!labelStmt.labelTagged) {
2239 labelStmt.labelStruct = ilGen.DefineLabel ("jump_" + labelStmt.name.val);
2240 labelStmt.labelTagged = true;
2241 }
2242 ilGen.MarkLabel (labelStmt.labelStruct);
2243 if (labelStmt.hasBkwdRefs) {
2244 EmitCallCheckRun (labelStmt, false);
2245 }
2246
2247 /*
2248 * We are going to say that the label falls through.
2249 * It would be nice if we could analyze all referencing
2250 * goto's to see if all of them are not used but we are
2251 * going to assume that if the script writer put a label
2252 * somewhere, it is probably going to be used.
2253 */
2254 mightGetHere = true;
2255 }
2256
2257 /**
2258 * @brief Generate code for a script-defined type's <typename>.$new(<argsig>) method.
2259 * It is used to malloc the object and initialize it.
2260 * It is defined as a script-defined type static method, so the object level
2261 * method gets the XMRInstance pointer passed as arg 0, and the method is
2262 * supposed to return the allocated and constructed XMRSDTypeClObj
2263 * object pointer.
2264 */
2265 private void GenerateStmtNewobj (TokenStmtNewobj newobjStmt)
2266 {
2267 /*
2268 * First off, malloc a new empty XMRSDTypeClObj object
2269 * then call the XMRSDTypeClObj()-level constructor.
2270 * Store the result in local var $objptr.
2271 */
2272 newobjStmt.objptrVar.location.PopPre (this, newobjStmt);
2273 ilGen.Emit (newobjStmt, OpCodes.Ldarg_0);
2274 ilGen.Emit (newobjStmt, OpCodes.Ldc_I4, curDeclFunc.sdtClass.sdTypeIndex);
2275 ilGen.Emit (newobjStmt, OpCodes.Newobj, sdtClassConstructorInfo);
2276 newobjStmt.objptrVar.location.PopPost (this, newobjStmt);
2277
2278 /*
2279 * Now call the script-level constructor.
2280 * Pass the object pointer in $objptr as it's 'this' argument.
2281 * The rest of the args are the script-visible args and are just copied from $new() call.
2282 */
2283 GenerateFromRValCall (newobjStmt.rValCall);
2284
2285 /*
2286 * Put object pointer in retval so it gets returned to caller.
2287 */
2288 newobjStmt.objptrVar.location.PushVal (this, newobjStmt);
2289 ilGen.Emit (newobjStmt, OpCodes.Stloc, retValue);
2290
2291 /*
2292 * Exit the function like a return statement.
2293 * And thus we don't fall through.
2294 */
2295 ilGen.Emit (newobjStmt, OpCodes.Leave, retLabel);
2296 mightGetHere = false;
2297 }
2298
2299 /**
2300 * @brief output code for a return statement.
2301 * @param retStmt = return statement token, including return value if any
2302 */
2303 private void GenerateStmtRet (TokenStmtRet retStmt)
2304 {
2305 if (!mightGetHere) return;
2306
2307 for (TokenStmtBlock stmtBlock = curStmtBlock; stmtBlock != null; stmtBlock = stmtBlock.outerStmtBlock) {
2308 if (stmtBlock.isFinally) {
2309 ErrorMsg (retStmt, "cannot return out of finally");
2310 return;
2311 }
2312 }
2313
2314 if (curDeclFunc.retType is TokenTypeVoid) {
2315 if (retStmt.rVal != null) {
2316 ErrorMsg (retStmt, "function returns void, no value allowed");
2317 return;
2318 }
2319 } else {
2320 if (retStmt.rVal == null) {
2321 ErrorMsg (retStmt, "function requires return value type " + curDeclFunc.retType.ToString ());
2322 return;
2323 }
2324 CompValu rVal = GenerateFromRVal (retStmt.rVal);
2325 rVal.PushVal (this, retStmt.rVal, curDeclFunc.retType);
2326 ilGen.Emit (retStmt, OpCodes.Stloc, retValue);
2327 }
2328
2329 /*
2330 * Use a OpCodes.Leave instruction to break out of any try { } blocks.
2331 * All Leave's inside script-defined try { } need call labels (see GenerateStmtTry()).
2332 */
2333 bool brokeOutOfTry = false;
2334 for (TokenStmtBlock stmtBlock = curStmtBlock; stmtBlock != null; stmtBlock = stmtBlock.outerStmtBlock) {
2335 if (stmtBlock.isTry) {
2336 brokeOutOfTry = true;
2337 break;
2338 }
2339 }
2340 if (brokeOutOfTry) new CallLabel (this, retStmt);
2341 ilGen.Emit (retStmt, OpCodes.Leave, retLabel);
2342 if (brokeOutOfTry) openCallLabel = null;
2343
2344 /*
2345 * 'return' statements never fall through.
2346 */
2347 mightGetHere = false;
2348 }
2349
2350 /**
2351 * @brief the statement is just an expression, most likely an assignment or a ++ or -- thing.
2352 */
2353 private void GenerateStmtRVal (TokenStmtRVal rValStmt)
2354 {
2355 if (!mightGetHere) return;
2356
2357 GenerateFromRVal (rValStmt.rVal);
2358 }
2359
2360 /**
2361 * @brief generate code for a 'state' statement that transitions state.
2362 * It sets the new state by throwing a ScriptChangeStateException.
2363 */
2364 private void GenerateStmtState (TokenStmtState stateStmt)
2365 {
2366 if (!mightGetHere) return;
2367
2368 int index = 0; // 'default' state
2369
2370 /*
2371 * Set new state value by throwing an exception.
2372 * These exceptions aren't catchable by script-level try { } catch { }.
2373 */
2374 if ((stateStmt.state != null) && !stateIndices.TryGetValue (stateStmt.state.val, out index)) {
2375 // The moron XEngine compiles scripts that reference undefined states.
2376 // So rather than produce a compile-time error, we'll throw an exception at runtime.
2377 // ErrorMsg (stateStmt, "undefined state " + stateStmt.state.val);
2378
2379 // throw new UndefinedStateException (stateStmt.state.val);
2380 ilGen.Emit (stateStmt, OpCodes.Ldstr, stateStmt.state.val);
2381 ilGen.Emit (stateStmt, OpCodes.Newobj, scriptUndefinedStateExceptionConstructorInfo);
2382 } else {
2383 ilGen.Emit (stateStmt, OpCodes.Ldc_I4, index); // new state's index
2384 ilGen.Emit (stateStmt, OpCodes.Newobj, scriptChangeStateExceptionConstructorInfo);
2385 }
2386 ilGen.Emit (stateStmt, OpCodes.Throw);
2387
2388 /*
2389 * 'state' statements never fall through.
2390 */
2391 mightGetHere = false;
2392 }
2393
2394 /**
2395 * @brief output code for a 'switch' statement
2396 */
2397 private void GenerateStmtSwitch (TokenStmtSwitch switchStmt)
2398 {
2399 if (!mightGetHere) return;
2400
2401 /*
2402 * Output code to calculate index.
2403 */
2404 CompValu testRVal = GenerateFromRVal (switchStmt.testRVal);
2405
2406 /*
2407 * Generate code based on string or integer index.
2408 */
2409 if ((testRVal.type is TokenTypeKey) || (testRVal.type is TokenTypeStr)) {
2410 GenerateStmtSwitchStr (testRVal, switchStmt);
2411 } else {
2412 GenerateStmtSwitchInt (testRVal, switchStmt);
2413 }
2414 }
2415
2416 private void GenerateStmtSwitchInt (CompValu testRVal, TokenStmtSwitch switchStmt)
2417 {
2418 testRVal.PushVal (this, switchStmt.testRVal, tokenTypeInt);
2419
2420 BreakContTarg oldBreakTarg = curBreakTarg;
2421 ScriptMyLabel defaultLabel = null;
2422 TokenSwitchCase sortedCases = null;
2423 TokenSwitchCase defaultCase = null;
2424
2425 curBreakTarg = new BreakContTarg (this, "switchbreak_" + switchStmt.Unique);
2426
2427 /*
2428 * Build list of cases sorted by ascending values.
2429 * There should not be any overlapping of values.
2430 */
2431 for (TokenSwitchCase thisCase = switchStmt.cases; thisCase != null; thisCase = thisCase.nextCase) {
2432 thisCase.label = ilGen.DefineLabel ("case_" + thisCase.Unique);
2433
2434 /*
2435 * The default case if any, goes in its own separate slot.
2436 */
2437 if (thisCase.rVal1 == null) {
2438 if (defaultCase != null) {
2439 ErrorMsg (thisCase, "only one default case allowed");
2440 ErrorMsg (defaultCase, "...prior default case");
2441 return;
2442 }
2443 defaultCase = thisCase;
2444 defaultLabel = thisCase.label;
2445 continue;
2446 }
2447
2448 /*
2449 * Evaluate case operands, they must be compile-time integer constants.
2450 */
2451 CompValu rVal = GenerateFromRVal (thisCase.rVal1);
2452 if (!IsConstIntExpr (rVal, out thisCase.val1)) {
2453 ErrorMsg (thisCase.rVal1, "must be compile-time char or integer constant");
2454 return;
2455 }
2456 thisCase.val2 = thisCase.val1;
2457 if (thisCase.rVal2 != null) {
2458 rVal = GenerateFromRVal (thisCase.rVal2);
2459 if (!IsConstIntExpr (rVal, out thisCase.val2)) {
2460 ErrorMsg (thisCase.rVal2, "must be compile-time char or integer constant");
2461 return;
2462 }
2463 }
2464 if (thisCase.val2 < thisCase.val1) {
2465 ErrorMsg (thisCase.rVal2, "must be .ge. first value for the case");
2466 return;
2467 }
2468
2469 /*
2470 * Insert into list, sorted by value.
2471 * Note that both limits are inclusive.
2472 */
2473 TokenSwitchCase lastCase = null;
2474 TokenSwitchCase nextCase;
2475 for (nextCase = sortedCases; nextCase != null; nextCase = nextCase.nextSortedCase) {
2476 if (nextCase.val1 > thisCase.val2) break;
2477 if (nextCase.val2 >= thisCase.val1) {
2478 ErrorMsg (thisCase, "value used by previous case");
2479 ErrorMsg (nextCase, "...previous case");
2480 return;
2481 }
2482 lastCase = nextCase;
2483 }
2484 thisCase.nextSortedCase = nextCase;
2485 if (lastCase == null) {
2486 sortedCases = thisCase;
2487 } else {
2488 lastCase.nextSortedCase = thisCase;
2489 }
2490 }
2491
2492 if (defaultLabel == null) {
2493 defaultLabel = ilGen.DefineLabel ("default_" + switchStmt.Unique);
2494 }
2495
2496 /*
2497 * Output code to jump to the case statement's labels based on integer index on stack.
2498 * Note that each case still has the integer index on stack when jumped to.
2499 */
2500 int offset = 0;
2501 for (TokenSwitchCase thisCase = sortedCases; thisCase != null;) {
2502
2503 /*
2504 * Scan through list of cases to find the maximum number of cases who's numvalues-to-case ratio
2505 * is from 0.5 to 2.0. If such a group is found, use a CIL switch for them. If not, just use a
2506 * compare-and-branch for the current case.
2507 */
2508 int numCases = 0;
2509 int numFound = 0;
2510 int lowValue = thisCase.val1;
2511 int numValues = 0;
2512 for (TokenSwitchCase scanCase = thisCase; scanCase != null; scanCase = scanCase.nextSortedCase) {
2513 int nVals = scanCase.val2 - thisCase.val1 + 1;
2514 double ratio = (double)nVals / (double)(++ numCases);
2515 if ((ratio >= 0.5) && (ratio <= 2.0)) {
2516 numFound = numCases;
2517 numValues = nVals;
2518 }
2519 }
2520 if (numFound > 1) {
2521
2522 /*
2523 * There is a group of case's, starting with thisCase, that fall within our criteria, ie,
2524 * that have a nice density of meaningful jumps.
2525 *
2526 * So first generate an array of jumps to the default label (explicit or implicit).
2527 */
2528 ScriptMyLabel[] labels = new ScriptMyLabel[numValues];
2529 for (int i = 0; i < numValues; i ++) {
2530 labels[i] = defaultLabel;
2531 }
2532
2533 /*
2534 * Next, for each case in that group, fill in the corresponding array entries to jump to
2535 * that case's label.
2536 */
2537 do {
2538 for (int i = thisCase.val1; i <= thisCase.val2; i ++) {
2539 labels[i-lowValue] = thisCase.label;
2540 }
2541 thisCase = thisCase.nextSortedCase;
2542 } while (-- numFound > 0);
2543
2544 /*
2545 * Subtract the low value and do the computed jump.
2546 * The OpCodes.Switch falls through if out of range (unsigned compare).
2547 */
2548 if (offset != lowValue) {
2549 ilGen.Emit (switchStmt, OpCodes.Ldc_I4, lowValue - offset);
2550 ilGen.Emit (switchStmt, OpCodes.Sub);
2551 offset = lowValue;
2552 }
2553 ilGen.Emit (switchStmt, OpCodes.Dup);
2554 ilGen.Emit (switchStmt, OpCodes.Switch, labels);
2555 } else {
2556
2557 /*
2558 * It's not economical to do with a computed jump, so output a subtract/compare/branch
2559 * for thisCase.
2560 */
2561 if (lowValue == thisCase.val2) {
2562 ilGen.Emit (switchStmt, OpCodes.Dup);
2563 ilGen.Emit (switchStmt, OpCodes.Ldc_I4, lowValue - offset);
2564 ilGen.Emit (switchStmt, OpCodes.Beq, thisCase.label);
2565 } else {
2566 if (offset != lowValue) {
2567 ilGen.Emit (switchStmt, OpCodes.Ldc_I4, lowValue - offset);
2568 ilGen.Emit (switchStmt, OpCodes.Sub);
2569 offset = lowValue;
2570 }
2571 ilGen.Emit (switchStmt, OpCodes.Dup);
2572 ilGen.Emit (switchStmt, OpCodes.Ldc_I4, thisCase.val2 - offset);
2573 ilGen.Emit (switchStmt, OpCodes.Ble_Un, thisCase.label);
2574 }
2575 thisCase = thisCase.nextSortedCase;
2576 }
2577 }
2578 ilGen.Emit (switchStmt, OpCodes.Br, defaultLabel);
2579
2580 /*
2581 * Output code for the cases themselves, in the order given by the programmer,
2582 * so they fall through as programmer wants. This includes the default case, if any.
2583 *
2584 * Each label is jumped to with the index still on the stack. So pop it off in case
2585 * the case body does a goto outside the switch or a return. If the case body might
2586 * fall through to the next case or the bottom of the switch, push a zero so the stack
2587 * matches in all cases.
2588 */
2589 for (TokenSwitchCase thisCase = switchStmt.cases; thisCase != null; thisCase = thisCase.nextCase) {
2590 ilGen.MarkLabel (thisCase.label); // the branch comes here
2591 ilGen.Emit (thisCase, OpCodes.Pop); // pop the integer index off stack
2592 mightGetHere = true; // it's possible to get here
2593 for (TokenStmt stmt = thisCase.stmts; stmt != null; stmt = (TokenStmt)(stmt.nextToken)) {
2594 GenerateStmt (stmt); // output the case/explicit default body
2595 }
2596 if (mightGetHere) {
2597 ilGen.Emit (thisCase, OpCodes.Ldc_I4_0);
2598 // in case we fall through, push a dummy integer index
2599 }
2600 }
2601
2602 /*
2603 * If no explicit default case, output the default label here.
2604 */
2605 if (defaultCase == null) {
2606 ilGen.MarkLabel (defaultLabel);
2607 mightGetHere = true;
2608 }
2609
2610 /*
2611 * If the last case of the switch falls through out the bottom,
2612 * we have to pop the index still on the stack.
2613 */
2614 if (mightGetHere) {
2615 ilGen.Emit (switchStmt, OpCodes.Pop);
2616 }
2617
2618 /*
2619 * Output the 'break' statement target label.
2620 * Note that the integer index is not on the stack at this point.
2621 */
2622 if (curBreakTarg.used) {
2623 ilGen.MarkLabel (curBreakTarg.label);
2624 mightGetHere = true;
2625 }
2626
2627 curBreakTarg = oldBreakTarg;
2628 }
2629
2630 private void GenerateStmtSwitchStr (CompValu testRVal, TokenStmtSwitch switchStmt)
2631 {
2632 BreakContTarg oldBreakTarg = curBreakTarg;
2633 ScriptMyLabel defaultLabel = null;
2634 TokenSwitchCase caseTreeTop = null;
2635 TokenSwitchCase defaultCase = null;
2636
2637 curBreakTarg = new BreakContTarg (this, "switchbreak_" + switchStmt.Unique);
2638
2639 /*
2640 * Make sure value is in a temp so we don't compute it more than once.
2641 */
2642 if (!(testRVal is CompValuTemp)) {
2643 CompValuTemp temp = new CompValuTemp (testRVal.type, this);
2644 testRVal.PushVal (this, switchStmt);
2645 temp.Pop (this, switchStmt);
2646 testRVal = temp;
2647 }
2648
2649 /*
2650 * Build tree of cases.
2651 * There should not be any overlapping of values.
2652 */
2653 for (TokenSwitchCase thisCase = switchStmt.cases; thisCase != null; thisCase = thisCase.nextCase) {
2654 thisCase.label = ilGen.DefineLabel ("case");
2655
2656 /*
2657 * The default case if any, goes in its own separate slot.
2658 */
2659 if (thisCase.rVal1 == null) {
2660 if (defaultCase != null) {
2661 ErrorMsg (thisCase, "only one default case allowed");
2662 ErrorMsg (defaultCase, "...prior default case");
2663 return;
2664 }
2665 defaultCase = thisCase;
2666 defaultLabel = thisCase.label;
2667 continue;
2668 }
2669
2670 /*
2671 * Evaluate case operands, they must be compile-time string constants.
2672 */
2673 CompValu rVal = GenerateFromRVal (thisCase.rVal1);
2674 if (!IsConstStrExpr (rVal, out thisCase.str1)) {
2675 ErrorMsg (thisCase.rVal1, "must be compile-time string constant");
2676 continue;
2677 }
2678 thisCase.str2 = thisCase.str1;
2679 if (thisCase.rVal2 != null) {
2680 rVal = GenerateFromRVal (thisCase.rVal2);
2681 if (!IsConstStrExpr (rVal, out thisCase.str2)) {
2682 ErrorMsg (thisCase.rVal2, "must be compile-time string constant");
2683 continue;
2684 }
2685 }
2686 if (String.Compare (thisCase.str2, thisCase.str1, StringComparison.Ordinal) < 0) {
2687 ErrorMsg (thisCase.rVal2, "must be .ge. first value for the case");
2688 continue;
2689 }
2690
2691 /*
2692 * Insert into list, sorted by value.
2693 * Note that both limits are inclusive.
2694 */
2695 caseTreeTop = InsertCaseInTree (caseTreeTop, thisCase);
2696 }
2697
2698 /*
2699 * Balance tree so we end up generating code that does O(log2 n) comparisons.
2700 */
2701 caseTreeTop = BalanceTree (caseTreeTop);
2702
2703 /*
2704 * Output compare and branch instructions in a tree-like fashion so we do O(log2 n) comparisons.
2705 */
2706 if (defaultLabel == null) {
2707 defaultLabel = ilGen.DefineLabel ("default");
2708 }
2709 OutputStrCase (testRVal, caseTreeTop, defaultLabel);
2710
2711 /*
2712 * Output code for the cases themselves, in the order given by the programmer,
2713 * so they fall through as programmer wants. This includes the default case, if any.
2714 */
2715 for (TokenSwitchCase thisCase = switchStmt.cases; thisCase != null; thisCase = thisCase.nextCase) {
2716 ilGen.MarkLabel (thisCase.label); // the branch comes here
2717 mightGetHere = true; // it's possible to get here
2718 for (TokenStmt stmt = thisCase.stmts; stmt != null; stmt = (TokenStmt)(stmt.nextToken)) {
2719 GenerateStmt (stmt); // output the case/explicit default body
2720 }
2721 }
2722
2723 /*
2724 * If no explicit default case, output the default label here.
2725 */
2726 if (defaultCase == null) {
2727 ilGen.MarkLabel (defaultLabel);
2728 mightGetHere = true;
2729 }
2730
2731 /*
2732 * Output the 'break' statement target label.
2733 */
2734 if (curBreakTarg.used) {
2735 ilGen.MarkLabel (curBreakTarg.label);
2736 mightGetHere = true;
2737 }
2738
2739 curBreakTarg = oldBreakTarg;
2740 }
2741
2742 /**
2743 * @brief Insert a case in a tree of cases
2744 * @param r = root of existing cases to insert into
2745 * @param n = new case being inserted
2746 * @returns new root with new case inserted
2747 */
2748 private TokenSwitchCase InsertCaseInTree (TokenSwitchCase r, TokenSwitchCase n)
2749 {
2750 if (r == null) return n;
2751
2752 TokenSwitchCase t = r;
2753 while (true) {
2754 if (String.Compare (n.str2, t.str1, StringComparison.Ordinal) < 0) {
2755 if (t.lowerCase == null) {
2756 t.lowerCase = n;
2757 break;
2758 }
2759 t = t.lowerCase;
2760 continue;
2761 }
2762 if (String.Compare (n.str1, t.str2, StringComparison.Ordinal) > 0) {
2763 if (t.higherCase == null) {
2764 t.higherCase = n;
2765 break;
2766 }
2767 t = t.higherCase;
2768 continue;
2769 }
2770 ErrorMsg (n, "duplicate case");
2771 ErrorMsg (r, "...duplicate of");
2772 break;
2773 }
2774 return r;
2775 }
2776
2777 /**
2778 * @brief Balance a tree so left & right halves contain same number within +-1
2779 * @param r = root of tree to balance
2780 * @returns new root
2781 */
2782 private static TokenSwitchCase BalanceTree (TokenSwitchCase r)
2783 {
2784 if (r == null) return r;
2785
2786 int lc = CountTree (r.lowerCase);
2787 int hc = CountTree (r.higherCase);
2788 TokenSwitchCase n, x;
2789
2790 /*
2791 * If lower side is heavy, move highest nodes from lower side to
2792 * higher side until balanced.
2793 */
2794 while (lc > hc + 1) {
2795 x = ExtractHighest (r.lowerCase, out n);
2796 n.lowerCase = x;
2797 n.higherCase = r;
2798 r.lowerCase = null;
2799 r = n;
2800 lc --;
2801 hc ++;
2802 }
2803
2804 /*
2805 * If higher side is heavy, move lowest nodes from higher side to
2806 * lower side until balanced.
2807 */
2808 while (hc > lc + 1) {
2809 x = ExtractLowest (r.higherCase, out n);
2810 n.higherCase = x;
2811 n.lowerCase = r;
2812 r.higherCase = null;
2813 r = n;
2814 lc ++;
2815 hc --;
2816 }
2817
2818 /*
2819 * Now balance each side because they can be lopsided individually.
2820 */
2821 r.lowerCase = BalanceTree (r.lowerCase);
2822 r.higherCase = BalanceTree (r.higherCase);
2823 return r;
2824 }
2825
2826 /**
2827 * @brief Get number of nodes in a tree
2828 * @param n = root of tree to count
2829 * @returns number of nodes including root
2830 */
2831 private static int CountTree (TokenSwitchCase n)
2832 {
2833 if (n == null) return 0;
2834 return 1 + CountTree (n.lowerCase) + CountTree (n.higherCase);
2835 }
2836
2837 // Extract highest node from a tree
2838 // @param r = root of tree to extract highest from
2839 // @returns new root after node has been extracted
2840 // n = node that was extracted from tree
2841 private static TokenSwitchCase ExtractHighest (TokenSwitchCase r, out TokenSwitchCase n)
2842 {
2843 if (r.higherCase == null) {
2844 n = r;
2845 return r.lowerCase;
2846 }
2847 r.higherCase = ExtractHighest (r.higherCase, out n);
2848 return r;
2849 }
2850
2851 // Extract lowest node from a tree
2852 // @param r = root of tree to extract lowest from
2853 // @returns new root after node has been extracted
2854 // n = node that was extracted from tree
2855 private static TokenSwitchCase ExtractLowest (TokenSwitchCase r, out TokenSwitchCase n)
2856 {
2857 if (r.lowerCase == null) {
2858 n = r;
2859 return r.higherCase;
2860 }
2861 r.lowerCase = ExtractLowest (r.lowerCase, out n);
2862 return r;
2863 }
2864
2865 /**
2866 * Output code for string-style case of a switch/case to jump to the script code associated with the case.
2867 * @param testRVal = value being switched on
2868 * @param thisCase = case that the code is being output for
2869 * @param defaultLabel = where the default clause is (or past all cases if none)
2870 * Note:
2871 * Outputs code for this case and the lowerCase and higherCases if any.
2872 * If no lowerCase or higherCase, outputs a br to defaultLabel so this code never falls through.
2873 */
2874 private void OutputStrCase (CompValu testRVal, TokenSwitchCase thisCase, ScriptMyLabel defaultLabel)
2875 {
2876 /*
2877 * If nothing lower on tree and there is a single case value,
2878 * just do one compare for equality.
2879 */
2880 if ((thisCase.lowerCase == null) && (thisCase.higherCase == null) && (thisCase.str1 == thisCase.str2)) {
2881 testRVal.PushVal (this, thisCase, tokenTypeStr);
2882 ilGen.Emit (thisCase, OpCodes.Ldstr, thisCase.str1);
2883 ilGen.Emit (thisCase, OpCodes.Ldc_I4, (int)StringComparison.Ordinal);
2884 ilGen.Emit (thisCase, OpCodes.Call, stringCompareMethodInfo);
2885 ilGen.Emit (thisCase, OpCodes.Brfalse, thisCase.label);
2886 ilGen.Emit (thisCase, OpCodes.Br, defaultLabel);
2887 return;
2888 }
2889
2890 /*
2891 * Determine where to jump if switch value is lower than lower case value.
2892 */
2893 ScriptMyLabel lowerLabel = defaultLabel;
2894 if (thisCase.lowerCase != null) {
2895 lowerLabel = ilGen.DefineLabel ("lower");
2896 }
2897
2898 /*
2899 * If single case value, put comparison result in this temp.
2900 */
2901 CompValuTemp cmpv1 = null;
2902 if (thisCase.str1 == thisCase.str2) {
2903 cmpv1 = new CompValuTemp (tokenTypeInt, this);
2904 }
2905
2906 /*
2907 * If switch value .lt. lower case value, jump to lower label.
2908 * Maybe save comparison result in a temp.
2909 */
2910 testRVal.PushVal (this, thisCase, tokenTypeStr);
2911 ilGen.Emit (thisCase, OpCodes.Ldstr, thisCase.str1);
2912 ilGen.Emit (thisCase, OpCodes.Ldc_I4, (int)StringComparison.Ordinal);
2913 ilGen.Emit (thisCase, OpCodes.Call, stringCompareMethodInfo);
2914 if (cmpv1 != null) {
2915 ilGen.Emit (thisCase, OpCodes.Dup);
2916 cmpv1.Pop (this, thisCase);
2917 }
2918 ilGen.Emit (thisCase, OpCodes.Ldc_I4_0);
2919 ilGen.Emit (thisCase, OpCodes.Blt, lowerLabel);
2920
2921 /*
2922 * If switch value .le. higher case value, jump to case code.
2923 * Maybe get comparison from the temp.
2924 */
2925 if (cmpv1 == null) {
2926 testRVal.PushVal (this, thisCase, tokenTypeStr);
2927 ilGen.Emit (thisCase, OpCodes.Ldstr, thisCase.str2);
2928 ilGen.Emit (thisCase, OpCodes.Ldc_I4, (int)StringComparison.Ordinal);
2929 ilGen.Emit (thisCase, OpCodes.Call, stringCompareMethodInfo);
2930 } else {
2931 cmpv1.PushVal (this, thisCase);
2932 }
2933 ilGen.Emit (thisCase, OpCodes.Ldc_I4_0);
2934 ilGen.Emit (thisCase, OpCodes.Ble, thisCase.label);
2935
2936 /*
2937 * Output code for higher comparison if any.
2938 */
2939 if (thisCase.higherCase == null) {
2940 ilGen.Emit (thisCase, OpCodes.Br, defaultLabel);
2941 } else {
2942 OutputStrCase (testRVal, thisCase.higherCase, defaultLabel);
2943 }
2944
2945 /*
2946 * Output code for lower comparison if any.
2947 */
2948 if (thisCase.lowerCase != null) {
2949 ilGen.MarkLabel (lowerLabel);
2950 OutputStrCase (testRVal, thisCase.lowerCase, defaultLabel);
2951 }
2952 }
2953
2954 /**
2955 * @brief output code for a throw statement.
2956 * @param throwStmt = throw statement token, including value to be thrown
2957 */
2958 private void GenerateStmtThrow (TokenStmtThrow throwStmt)
2959 {
2960 if (!mightGetHere) return;
2961
2962 /*
2963 * 'throw' statements never fall through.
2964 */
2965 mightGetHere = false;
2966
2967 /*
2968 * Output code for either a throw or a rethrow.
2969 */
2970 if (throwStmt.rVal == null) {
2971 for (TokenStmtBlock blk = curStmtBlock; blk != null; blk = blk.outerStmtBlock) {
2972 if (curStmtBlock.isCatch) {
2973 ilGen.Emit (throwStmt, OpCodes.Rethrow);
2974 return;
2975 }
2976 }
2977 ErrorMsg (throwStmt, "rethrow allowed only in catch clause");
2978 } else {
2979 CompValu rVal = GenerateFromRVal (throwStmt.rVal);
2980 rVal.PushVal (this, throwStmt.rVal, tokenTypeObj);
2981 ilGen.Emit (throwStmt, OpCodes.Call, thrownExceptionWrapMethodInfo);
2982 ilGen.Emit (throwStmt, OpCodes.Throw);
2983 }
2984 }
2985
2986 /**
2987 * @brief output code for a try/catch/finally block
2988 */
2989 private void GenerateStmtTry (TokenStmtTry tryStmt)
2990 {
2991 if (!mightGetHere) return;
2992
2993 /*
2994 * Reducer should make sure we have exactly one of catch or finally.
2995 */
2996 if ((tryStmt.catchStmt == null) && (tryStmt.finallyStmt == null)) {
2997 throw new Exception ("must have a catch or a finally on try");
2998 }
2999 if ((tryStmt.catchStmt != null) && (tryStmt.finallyStmt != null)) {
3000 throw new Exception ("can't have both catch and finally on same try");
3001 }
3002
3003 /*
3004 * Stack the call labels.
3005 * Try blocks have their own series of call labels.
3006 */
3007 ScriptMyLocal saveCallNo = actCallNo;
3008 LinkedList<CallLabel> saveCallLabels = actCallLabels;
3009
3010 /*
3011 * Generate code for either try { } catch { } or try { } finally { }.
3012 */
3013 if (tryStmt.catchStmt != null) GenerateStmtTryCatch (tryStmt);
3014 if (tryStmt.finallyStmt != null) GenerateStmtTryFinally (tryStmt);
3015
3016 /*
3017 * Restore call labels.
3018 */
3019 actCallNo = saveCallNo;
3020 actCallLabels = saveCallLabels;
3021 }
3022
3023
3024 /**
3025 * @brief output code for a try/catch block
3026 *
3027 * int __tryCallNo = -1; // call number within try { } subblock
3028 * int __catCallNo = -1; // call number within catch { } subblock
3029 * Exception __catThrown = null; // caught exception
3030 * <oldCallLabel>: // the outside world jumps here to restore us no matter ...
3031 * try { // ... where we actually were inside of try/catch
3032 * if (__tryCallNo >= 0) goto tryCallSw; // maybe go do restore
3033 * <try body using __tryCallNo> // execute script-defined code
3034 * // ...stack capture WILL run catch { } subblock
3035 * leave tryEnd; // exits
3036 * tryThrow:<tryCallLabel>:
3037 * throw new ScriptRestoreCatchException(__catThrown); // catch { } was running, jump to its beginning
3038 * tryCallSw: // restoring...
3039 * switch (__tryCallNo) back up into <try body> // not catching, jump back inside try
3040 * } catch (Exception exc) {
3041 * exc = ScriptRestoreCatchException.Unwrap(exc); // unwrap possible ScriptRestoreCatchException
3042 * if (exc == null) goto catchRetro; // rethrow if IXMRUncatchable (eg, StackCaptureException)
3043 * __catThrown = exc; // save what was thrown so restoring try { } will throw it again
3044 * catchVar = exc; // set up script-visible variable
3045 * __tryCallNo = tryThrow:<tryCallLabel>
3046 * if (__catCallNo >= 0) goto catchCallSw; // if restoring, go check below
3047 * <catch body using __catCallNo> // normal, execute script-defined code
3048 * leave tryEnd; // all done, exit catch { }
3049 * catchRetro:
3050 * rethrow;
3051 * catchCallSw:
3052 * switch (__catCallNo) back up into <catch body> // restart catch { } code wherever it was
3053 * }
3054 * tryEnd:
3055 */
3056 private void GenerateStmtTryCatch (TokenStmtTry tryStmt)
3057 {
3058 CompValuTemp tryCallNo = new CompValuTemp (tokenTypeInt, this);
3059 CompValuTemp catCallNo = new CompValuTemp (tokenTypeInt, this);
3060 CompValuTemp catThrown = new CompValuTemp (tokenTypeExc, this);
3061
3062 ScriptMyLabel tryCallSw = ilGen.DefineLabel ("__tryCallSw_" + tryStmt.Unique);
3063 ScriptMyLabel catchRetro = ilGen.DefineLabel ("__catchRetro_" + tryStmt.Unique);
3064 ScriptMyLabel catchCallSw = ilGen.DefineLabel ("__catchCallSw_" + tryStmt.Unique);
3065 ScriptMyLabel tryEnd = ilGen.DefineLabel ("__tryEnd_" + tryStmt.Unique);
3066
3067 SetCallNo (tryStmt, tryCallNo, -1);
3068 SetCallNo (tryStmt, catCallNo, -1);
3069 ilGen.Emit (tryStmt, OpCodes.Ldnull);
3070 catThrown.Pop (this, tryStmt);
3071
3072 new CallLabel (this, tryStmt); // <oldcalllabel>:
3073 ilGen.BeginExceptionBlock (); // try {
3074 openCallLabel = null;
3075 if (DEBUG_TRYSTMT) {
3076 ilGen.Emit (tryStmt, OpCodes.Ldstr, "enter try*: " + tryStmt.line + " callMode=");
3077 ilGen.Emit (tryStmt, OpCodes.Call, consoleWriteMethodInfo);
3078 PushXMRInst ();
3079 ilGen.Emit (tryStmt, OpCodes.Ldfld, callModeFieldInfo);
3080 ilGen.Emit (tryStmt, OpCodes.Box, typeof (int));
3081 ilGen.Emit (tryStmt, OpCodes.Call, consoleWriteMethodInfo);
3082 ilGen.Emit (tryStmt, OpCodes.Ldstr, " tryCallNo=");
3083 ilGen.Emit (tryStmt, OpCodes.Call, consoleWriteMethodInfo);
3084 tryCallNo.PushVal (this, tryStmt);
3085 ilGen.Emit (tryStmt, OpCodes.Box, typeof (int));
3086 ilGen.Emit (tryStmt, OpCodes.Call, consoleWriteMethodInfo);
3087 ilGen.Emit (tryStmt, OpCodes.Ldstr, " catThrown.IsNull=");
3088 ilGen.Emit (tryStmt, OpCodes.Call, consoleWriteMethodInfo);
3089 catThrown.PushVal (this, tryStmt);
3090 ilGen.Emit (tryStmt, OpCodes.Ldnull);
3091 ilGen.Emit (tryStmt, OpCodes.Ceq);
3092 ilGen.Emit (tryStmt, OpCodes.Box, typeof (int));
3093 ilGen.Emit (tryStmt, OpCodes.Call, consoleWriteMethodInfo);
3094 ilGen.Emit (tryStmt, OpCodes.Ldstr, " catCallNo=");
3095 ilGen.Emit (tryStmt, OpCodes.Call, consoleWriteMethodInfo);
3096 catCallNo.PushVal (this, tryStmt);
3097 ilGen.Emit (tryStmt, OpCodes.Box, typeof (int));
3098 ilGen.Emit (tryStmt, OpCodes.Call, consoleWriteMethodInfo);
3099 ilGen.Emit (tryStmt, OpCodes.Ldstr, "\n");
3100 ilGen.Emit (tryStmt, OpCodes.Call, consoleWriteMethodInfo);
3101 }
3102
3103 GetCallNo (tryStmt, tryCallNo); // if (__tryCallNo >= 0) goto tryCallSw;
3104 ilGen.Emit (tryStmt, OpCodes.Ldc_I4_0);
3105 ilGen.Emit (tryStmt, OpCodes.Bge, tryCallSw);
3106
3107 actCallNo = tryCallNo.localBuilder; // set up __tryCallNo for call labels
3108 actCallLabels = new LinkedList<CallLabel> ();
3109
3110 GenerateStmtBlock (tryStmt.tryStmt); // output the try block statement subblock
3111
3112 bool tryBlockFallsOutBottom = mightGetHere;
3113 if (tryBlockFallsOutBottom) {
3114 new CallLabel (this, tryStmt); // <tryCallLabel>:
3115 ilGen.Emit (tryStmt, OpCodes.Leave, tryEnd); // leave tryEnd;
3116 openCallLabel = null;
3117 }
3118
3119 CallLabel tryThrow = new CallLabel (this, tryStmt); // tryThrow:<tryCallLabel>:
3120 if (DEBUG_TRYSTMT) {
3121 ilGen.Emit (tryStmt, OpCodes.Ldstr, "tryThrow*: " + tryStmt.line + " catThrown=");
3122 ilGen.Emit (tryStmt, OpCodes.Call, consoleWriteMethodInfo);
3123 catThrown.PushVal (this, tryStmt);
3124 ilGen.Emit (tryStmt, OpCodes.Call, consoleWriteMethodInfo);
3125 ilGen.Emit (tryStmt, OpCodes.Ldstr, "\n");
3126 ilGen.Emit (tryStmt, OpCodes.Call, consoleWriteMethodInfo);
3127 }
3128 catThrown.PushVal (this, tryStmt); // throw new ScriptRestoreCatchException (__catThrown);
3129 ilGen.Emit (tryStmt, OpCodes.Newobj, scriptRestoreCatchExceptionConstructorInfo);
3130 ilGen.Emit (tryStmt, OpCodes.Throw);
3131 openCallLabel = null;
3132
3133 ilGen.MarkLabel (tryCallSw); // tryCallSw:
3134 if (DEBUG_TRYSTMT) {
3135 ilGen.Emit (tryStmt, OpCodes.Ldstr, "tryCallSw*: " + tryStmt.line + " tryCallNo=");
3136 ilGen.Emit (tryStmt, OpCodes.Call, consoleWriteMethodInfo);
3137 tryCallNo.PushVal (this, tryStmt);
3138 ilGen.Emit (tryStmt, OpCodes.Box, typeof (int));
3139 ilGen.Emit (tryStmt, OpCodes.Call, consoleWriteMethodInfo);
3140 ilGen.Emit (tryStmt, OpCodes.Ldstr, "\n");
3141 ilGen.Emit (tryStmt, OpCodes.Call, consoleWriteMethodInfo);
3142 }
3143 OutputCallNoSwitchStmt (); // switch (tryCallNo) ...
3144
3145 CompValuLocalVar catchVarLocExc = null;
3146 CompValuTemp catchVarLocStr = null;
3147
3148 if (tryStmt.catchVar.type.ToSysType () == typeof (Exception)) {
3149 catchVarLocExc = new CompValuLocalVar (tryStmt.catchVar.type, tryStmt.catchVar.name.val, this);
3150 } else if (tryStmt.catchVar.type.ToSysType () == typeof (String)) {
3151 catchVarLocStr = new CompValuTemp (tryStmt.catchVar.type, this);
3152 }
3153
3154 ScriptMyLocal excLocal = ilGen.DeclareLocal (typeof (String), "catchstr_" + tryStmt.Unique);
3155
3156 ilGen.BeginCatchBlock (typeof (Exception)); // start of the catch block that can catch any exception
3157 if (DEBUG_TRYSTMT) {
3158 ilGen.Emit (tryStmt.catchStmt, OpCodes.Ldstr, "enter catch*: " + tryStmt.line + " callMode=");
3159 ilGen.Emit (tryStmt.catchStmt, OpCodes.Call, consoleWriteMethodInfo);
3160 PushXMRInst ();
3161 ilGen.Emit (tryStmt.catchStmt, OpCodes.Ldfld, callModeFieldInfo);
3162 ilGen.Emit (tryStmt.catchStmt, OpCodes.Box, typeof (int));
3163 ilGen.Emit (tryStmt.catchStmt, OpCodes.Call, consoleWriteMethodInfo);
3164 ilGen.Emit (tryStmt.catchStmt, OpCodes.Ldstr, " catCallNo=");
3165 ilGen.Emit (tryStmt.catchStmt, OpCodes.Call, consoleWriteMethodInfo);
3166 catCallNo.PushVal (this, tryStmt);
3167 ilGen.Emit (tryStmt.catchStmt, OpCodes.Box, typeof (int));
3168 ilGen.Emit (tryStmt.catchStmt, OpCodes.Call, consoleWriteMethodInfo);
3169 ilGen.Emit (tryStmt.catchStmt, OpCodes.Ldstr, " exc=");
3170 ilGen.Emit (tryStmt.catchStmt, OpCodes.Call, consoleWriteMethodInfo);
3171 ilGen.Emit (tryStmt.catchStmt, OpCodes.Dup);
3172 ilGen.Emit (tryStmt.catchStmt, OpCodes.Call, consoleWriteMethodInfo);
3173 ilGen.Emit (tryStmt.catchStmt, OpCodes.Ldstr, "\n");
3174 ilGen.Emit (tryStmt.catchStmt, OpCodes.Call, consoleWriteMethodInfo);
3175 }
3176 ilGen.Emit (tryStmt.catchStmt, OpCodes.Call, scriptRestoreCatchExceptionUnwrap);
3177 // exc = ScriptRestoreCatchException.Unwrap (exc);
3178 ilGen.Emit (tryStmt.catchStmt, OpCodes.Dup); // rethrow if IXMRUncatchable (eg, StackCaptureException)
3179 ilGen.Emit (tryStmt.catchStmt, OpCodes.Brfalse, catchRetro);
3180 if (tryStmt.catchVar.type.ToSysType () == typeof (Exception)) {
3181 tryStmt.catchVar.location = catchVarLocExc;
3182 ilGen.Emit (tryStmt.catchStmt, OpCodes.Dup);
3183 catThrown.Pop (this, tryStmt); // store exception object in catThrown
3184 catchVarLocExc.Pop (this, tryStmt.catchVar.name); // also store in script-visible variable
3185 } else if (tryStmt.catchVar.type.ToSysType () == typeof (String)) {
3186 tryStmt.catchVar.location = catchVarLocStr;
3187 ilGen.Emit (tryStmt.catchStmt, OpCodes.Dup);
3188 catThrown.Pop (this, tryStmt); // store exception object in catThrown
3189 ilGen.Emit (tryStmt.catchStmt, OpCodes.Call, catchExcToStrMethodInfo);
3190
3191 ilGen.Emit (tryStmt.catchStmt, OpCodes.Stloc, excLocal);
3192 catchVarLocStr.PopPre (this, tryStmt.catchVar.name);
3193 ilGen.Emit (tryStmt.catchStmt, OpCodes.Ldloc, excLocal);
3194 catchVarLocStr.PopPost (this, tryStmt.catchVar.name, tokenTypeStr);
3195 } else {
3196 throw new Exception ("bad catch var type " + tryStmt.catchVar.type.ToString ());
3197 }
3198
3199 SetCallNo (tryStmt, tryCallNo, tryThrow.index); // __tryCallNo = tryThrow so it knows to do 'throw catThrown' on restore
3200
3201 GetCallNo (tryStmt, catCallNo); // if (__catCallNo >= 0) goto catchCallSw;
3202 ilGen.Emit (tryStmt.catchStmt, OpCodes.Ldc_I4_0);
3203 ilGen.Emit (tryStmt.catchStmt, OpCodes.Bge, catchCallSw);
3204
3205 actCallNo = catCallNo.localBuilder; // set up __catCallNo for call labels
3206 actCallLabels.Clear ();
3207 mightGetHere = true; // if we can get to the 'try' assume we can get to the 'catch'
3208 GenerateStmtBlock (tryStmt.catchStmt); // output catch clause statement subblock
3209
3210 if (mightGetHere) {
3211 new CallLabel (this, tryStmt.catchStmt);
3212 ilGen.Emit (tryStmt.catchStmt, OpCodes.Leave, tryEnd);
3213 openCallLabel = null;
3214 }
3215
3216 ilGen.MarkLabel (catchRetro); // not a script-visible exception, rethrow it
3217 ilGen.Emit (tryStmt.catchStmt, OpCodes.Pop);
3218 ilGen.Emit (tryStmt.catchStmt, OpCodes.Rethrow);
3219
3220 ilGen.MarkLabel (catchCallSw);
3221 OutputCallNoSwitchStmt (); // restoring, jump back inside script-defined body
3222
3223 ilGen.EndExceptionBlock ();
3224 ilGen.MarkLabel (tryEnd);
3225
3226 mightGetHere |= tryBlockFallsOutBottom; // also get here if try body falls out bottom
3227 }
3228
3229 /**
3230 * @brief output code for a try/finally block
3231 *
3232 * This is such a mess because there is hidden state for the finally { } that we have to recreate.
3233 * The finally { } can be entered either via an exception being thrown in the try { } or a leave
3234 * being executed in the try { } whose target is outside the try { } finally { }.
3235 *
3236 * For the thrown exception case, we slip in a try { } catch { } wrapper around the original try { }
3237 * body. This will sense any thrown exception that would execute the finally { }. Then we have our
3238 * try { } throw the exception on restore which gets the finally { } called and on its way again.
3239 *
3240 * For the leave case, we prefix all leave instructions with a call label and we explicitly chain
3241 * all leaves through each try { } that has an associated finally { } that the leave would unwind
3242 * through. This gets each try { } to simply jump to the correct leave instruction which immediately
3243 * invokes the corresponding finally { } and then chains to the next leave instruction on out until
3244 * it gets to its target.
3245 *
3246 * int __finCallNo = -1; // call number within finally { } subblock
3247 * int __tryCallNo = -1; // call number within try { } subblock
3248 * Exception __catThrown = null; // caught exception
3249 * <oldCallLabel>: // the outside world jumps here to restore us no matter ...
3250 * try { // ... where we actually were inside of try/finally
3251 * try {
3252 * if (__tryCallNo >= 0) goto tryCallSw; // maybe go do restore
3253 * <try body using __tryCallNo> // execute script-defined code
3254 * // ...stack capture WILL run catch/finally { } subblock
3255 * leave tryEnd; // executes finally { } subblock and exits
3256 * tryThrow:<tryCallLabel>:
3257 * throw new ScriptRestoreCatchException(__catThrown); // catch { } was running, jump to its beginning
3258 * tryCallSw: // restoring...
3259 * switch (__tryCallNo) back up into <try body> // jump back inside try, ...
3260 * // ... maybe to a leave if we were doing finally { } subblock
3261 * } catch (Exception exc) { // in case we're getting to finally { } via a thrown exception:
3262 * exc = ScriptRestoreCatchException.Unwrap(exc); // unwrap possible ScriptRestoreCatchException
3263 * if (callMode == CallMode_SAVE) goto catchRetro; // don't touch anything if capturing stack
3264 * __catThrown = exc; // save exception so try { } can throw it on restore
3265 * __tryCallNo = tryThrow:<tryCallLabel>; // tell try { } to throw it on restore
3266 * catchRetro:
3267 * rethrow; // in any case, go on to finally { } subblock now
3268 * }
3269 * } finally {
3270 * if (callMode == CallMode_SAVE) goto finEnd; // don't touch anything if capturing stack
3271 * if (__finCallNo >= 0) goto finCallSw; // maybe go do restore
3272 * <finally body using __finCallNo> // normal, execute script-defined code
3273 * finEnd:
3274 * endfinally // jump to leave/throw target or next outer finally { }
3275 * finCallSw:
3276 * switch (__finCallNo) back up into <finally body> // restoring, restart finally { } code wherever it was
3277 * }
3278 * tryEnd:
3279 */
3280 private void GenerateStmtTryFinally (TokenStmtTry tryStmt)
3281 {
3282 CompValuTemp finCallNo = new CompValuTemp (tokenTypeInt, this);
3283 CompValuTemp tryCallNo = new CompValuTemp (tokenTypeInt, this);
3284 CompValuTemp catThrown = new CompValuTemp (tokenTypeExc, this);
3285
3286 ScriptMyLabel tryCallSw = ilGen.DefineLabel ( "__tryCallSw_" + tryStmt.Unique);
3287 ScriptMyLabel catchRetro = ilGen.DefineLabel ( "__catchRetro_" + tryStmt.Unique);
3288 ScriptMyLabel finCallSw = ilGen.DefineLabel ( "__finCallSw_" + tryStmt.Unique);
3289 BreakContTarg finEnd = new BreakContTarg (this, "__finEnd_" + tryStmt.Unique);
3290 ScriptMyLabel tryEnd = ilGen.DefineLabel ( "__tryEnd_" + tryStmt.Unique);
3291
3292 SetCallNo (tryStmt, finCallNo, -1);
3293 SetCallNo (tryStmt, tryCallNo, -1);
3294 ilGen.Emit (tryStmt, OpCodes.Ldnull);
3295 catThrown.Pop (this, tryStmt);
3296
3297 new CallLabel (this, tryStmt); // <oldcalllabel>:
3298 ilGen.BeginExceptionBlock (); // try {
3299 ilGen.BeginExceptionBlock (); // try {
3300 openCallLabel = null;
3301 if (DEBUG_TRYSTMT) {
3302 ilGen.Emit (tryStmt, OpCodes.Ldstr, "enter try*: " + tryStmt.line + " callMode=");
3303 ilGen.Emit (tryStmt, OpCodes.Call, consoleWriteMethodInfo);
3304 PushXMRInst ();
3305 ilGen.Emit (tryStmt, OpCodes.Ldfld, callModeFieldInfo);
3306 ilGen.Emit (tryStmt, OpCodes.Box, typeof (int));
3307 ilGen.Emit (tryStmt, OpCodes.Call, consoleWriteMethodInfo);
3308 ilGen.Emit (tryStmt, OpCodes.Ldstr, " tryCallNo=");
3309 ilGen.Emit (tryStmt, OpCodes.Call, consoleWriteMethodInfo);
3310 tryCallNo.PushVal (this, tryStmt);
3311 ilGen.Emit (tryStmt, OpCodes.Box, typeof (int));
3312 ilGen.Emit (tryStmt, OpCodes.Call, consoleWriteMethodInfo);
3313 ilGen.Emit (tryStmt, OpCodes.Ldstr, " finCallNo=");
3314 ilGen.Emit (tryStmt, OpCodes.Call, consoleWriteMethodInfo);
3315 finCallNo.PushVal (this, tryStmt);
3316 ilGen.Emit (tryStmt, OpCodes.Box, typeof (int));
3317 ilGen.Emit (tryStmt, OpCodes.Call, consoleWriteMethodInfo);
3318 ilGen.Emit (tryStmt, OpCodes.Ldstr, " catThrown.IsNull=");
3319 ilGen.Emit (tryStmt, OpCodes.Call, consoleWriteMethodInfo);
3320 catThrown.PushVal (this, tryStmt);
3321 ilGen.Emit (tryStmt, OpCodes.Ldnull);
3322 ilGen.Emit (tryStmt, OpCodes.Ceq);
3323 ilGen.Emit (tryStmt, OpCodes.Box, typeof (int));
3324 ilGen.Emit (tryStmt, OpCodes.Call, consoleWriteMethodInfo);
3325 ilGen.Emit (tryStmt, OpCodes.Ldstr, "\n");
3326 ilGen.Emit (tryStmt, OpCodes.Call, consoleWriteMethodInfo);
3327 }
3328
3329 GetCallNo (tryStmt, tryCallNo); // if (__tryCallNo >= 0) goto tryCallSw;
3330 ilGen.Emit (tryStmt, OpCodes.Ldc_I4_0);
3331 ilGen.Emit (tryStmt, OpCodes.Bge, tryCallSw);
3332
3333 actCallNo = tryCallNo.localBuilder; // set up __tryCallNo for call labels
3334 actCallLabels = new LinkedList<CallLabel> ();
3335
3336 GenerateStmtBlock (tryStmt.tryStmt); // output the try block statement subblock
3337
3338 if (mightGetHere) {
3339 new CallLabel (this, tryStmt); // <newCallLabel>:
3340 ilGen.Emit (tryStmt, OpCodes.Leave, tryEnd); // leave tryEnd;
3341 openCallLabel = null;
3342 }
3343
3344 foreach (IntermediateLeave iLeave in tryStmt.iLeaves.Values) {
3345 ilGen.MarkLabel (iLeave.jumpIntoLabel); // intr2_exit:
3346 new CallLabel (this, tryStmt); // tryCallNo = n;
3347 ilGen.Emit (tryStmt, OpCodes.Leave, iLeave.jumpAwayLabel); // __callNo_n_: leave int1_exit;
3348 openCallLabel = null;
3349 }
3350
3351 CallLabel tryThrow = new CallLabel (this, tryStmt); // tryThrow:<tryCallLabel>:
3352 if (DEBUG_TRYSTMT) {
3353 ilGen.Emit (tryStmt, OpCodes.Ldstr, "tryThrow*: " + tryStmt.line + " catThrown=");
3354 ilGen.Emit (tryStmt, OpCodes.Call, consoleWriteMethodInfo);
3355 catThrown.PushVal (this, tryStmt);
3356 ilGen.Emit (tryStmt, OpCodes.Call, consoleWriteMethodInfo);
3357 ilGen.Emit (tryStmt, OpCodes.Ldstr, "\n");
3358 ilGen.Emit (tryStmt, OpCodes.Call, consoleWriteMethodInfo);
3359 }
3360 catThrown.PushVal (this, tryStmt); // throw new ScriptRestoreCatchException (__catThrown);
3361 ilGen.Emit (tryStmt, OpCodes.Newobj, scriptRestoreCatchExceptionConstructorInfo);
3362 ilGen.Emit (tryStmt, OpCodes.Throw);
3363 openCallLabel = null;
3364
3365 ilGen.MarkLabel (tryCallSw); // tryCallSw:
3366 OutputCallNoSwitchStmt (); // switch (tryCallNo) ...
3367 // }
3368
3369 ilGen.BeginCatchBlock (typeof (Exception)); // start of the catch block that can catch any exception
3370 if (DEBUG_TRYSTMT) {
3371 ilGen.Emit (tryStmt, OpCodes.Ldstr, "enter catch*: " + tryStmt.line + " callMode=");
3372 ilGen.Emit (tryStmt, OpCodes.Call, consoleWriteMethodInfo);
3373 PushXMRInst ();
3374 ilGen.Emit (tryStmt, OpCodes.Ldfld, callModeFieldInfo);
3375 ilGen.Emit (tryStmt, OpCodes.Box, typeof (int));
3376 ilGen.Emit (tryStmt, OpCodes.Call, consoleWriteMethodInfo);
3377 ilGen.Emit (tryStmt, OpCodes.Ldstr, " exc=");
3378 ilGen.Emit (tryStmt, OpCodes.Call, consoleWriteMethodInfo);
3379 ilGen.Emit (tryStmt, OpCodes.Dup);
3380 ilGen.Emit (tryStmt, OpCodes.Call, consoleWriteMethodInfo);
3381 ilGen.Emit (tryStmt, OpCodes.Ldstr, "\n");
3382 ilGen.Emit (tryStmt, OpCodes.Call, consoleWriteMethodInfo);
3383 }
3384 ilGen.Emit (tryStmt, OpCodes.Call, scriptRestoreCatchExceptionUnwrap); // exc = ScriptRestoreCatchException.Unwrap (exc);
3385 PushXMRInst (); // if (callMode == CallMode_SAVE) goto catchRetro;
3386 ilGen.Emit (tryStmt, OpCodes.Ldfld, callModeFieldInfo);
3387 ilGen.Emit (tryStmt, OpCodes.Ldc_I4, XMRInstAbstract.CallMode_SAVE);
3388 ilGen.Emit (tryStmt, OpCodes.Beq, catchRetro);
3389
3390 catThrown.Pop (this, tryStmt); // __catThrown = exc;
3391 SetCallNo (tryStmt, tryCallNo, tryThrow.index); // __tryCallNo = tryThrow:<tryCallLabel>;
3392 ilGen.Emit (tryStmt, OpCodes.Rethrow);
3393
3394 ilGen.MarkLabel (catchRetro); // catchRetro:
3395 ilGen.Emit (tryStmt, OpCodes.Pop);
3396 ilGen.Emit (tryStmt, OpCodes.Rethrow); // rethrow;
3397
3398 ilGen.EndExceptionBlock (); // }
3399
3400 ilGen.BeginFinallyBlock (); // start of the finally block
3401
3402 PushXMRInst (); // if (callMode == CallMode_SAVE) goto finEnd;
3403 ilGen.Emit (tryStmt, OpCodes.Ldfld, callModeFieldInfo);
3404 ilGen.Emit (tryStmt, OpCodes.Ldc_I4, XMRInstAbstract.CallMode_SAVE);
3405 ilGen.Emit (tryStmt, OpCodes.Beq, finEnd.label);
3406
3407 GetCallNo (tryStmt, finCallNo); // if (__finCallNo >= 0) goto finCallSw;
3408 ilGen.Emit (tryStmt, OpCodes.Ldc_I4_0);
3409 ilGen.Emit (tryStmt, OpCodes.Bge, finCallSw);
3410
3411 actCallNo = finCallNo.localBuilder; // set up __finCallNo for call labels
3412 actCallLabels.Clear ();
3413 mightGetHere = true; // if we can get to the 'try' assume we can get to the 'finally'
3414 GenerateStmtBlock (tryStmt.finallyStmt); // output finally clause statement subblock
3415
3416 ilGen.MarkLabel (finEnd.label); // finEnd:
3417 ilGen.Emit (tryStmt, OpCodes.Endfinally); // return out to next finally { } or catch { } or leave target
3418
3419 ilGen.MarkLabel (finCallSw); // restore mode, switch (finCallNo) ...
3420 OutputCallNoSwitchStmt ();
3421
3422 ilGen.EndExceptionBlock ();
3423 ilGen.MarkLabel (tryEnd);
3424
3425 mightGetHere |= finEnd.used; // get here if finally body falls through or has a break statement
3426 }
3427
3428 /**
3429 * @brief Generate code to initialize a variable to its default value.
3430 */
3431 private void GenerateStmtVarIniDef (TokenStmtVarIniDef varIniDefStmt)
3432 {
3433 if (!mightGetHere) return;
3434
3435 CompValu left = GenerateFromLVal (varIniDefStmt.var);
3436 left.PopPre (this, varIniDefStmt);
3437 PushDefaultValue (left.type);
3438 left.PopPost (this, varIniDefStmt);
3439 }
3440
3441 /**
3442 * @brief generate code for a 'while' statement including the loop body.
3443 */
3444 private void GenerateStmtWhile (TokenStmtWhile whileStmt)
3445 {
3446 if (!mightGetHere) return;
3447
3448 BreakContTarg oldBreakTarg = curBreakTarg;
3449 BreakContTarg oldContTarg = curContTarg;
3450 ScriptMyLabel loopLabel = ilGen.DefineLabel ("whileloop_" + whileStmt.Unique);
3451
3452 curBreakTarg = new BreakContTarg (this, "whilebreak_" + whileStmt.Unique);
3453 curContTarg = new BreakContTarg (this, "whilecont_" + whileStmt.Unique);
3454
3455 ilGen.MarkLabel (loopLabel); // loop:
3456 CompValu testRVal = GenerateFromRVal (whileStmt.testRVal); // testRVal = while test expression
3457 if (!IsConstBoolExprTrue (testRVal)) {
3458 testRVal.PushVal (this, whileStmt.testRVal, tokenTypeBool); // if (!testRVal)
3459 ilGen.Emit (whileStmt, OpCodes.Brfalse, curBreakTarg.label); // goto break
3460 curBreakTarg.used = true;
3461 }
3462 GenerateStmt (whileStmt.bodyStmt); // while body statement
3463 if (curContTarg.used) {
3464 ilGen.MarkLabel (curContTarg.label); // cont:
3465 mightGetHere = true;
3466 }
3467 if (mightGetHere) {
3468 EmitCallCheckRun (whileStmt, false); // __sw.CheckRun()
3469 ilGen.Emit (whileStmt, OpCodes.Br, loopLabel); // goto loop
3470 }
3471 mightGetHere = curBreakTarg.used;
3472 if (mightGetHere) {
3473 ilGen.MarkLabel (curBreakTarg.label); // done:
3474 }
3475
3476 curBreakTarg = oldBreakTarg;
3477 curContTarg = oldContTarg;
3478 }
3479
3480 /**
3481 * @brief process a local variable declaration statement, possibly with initialization expression.
3482 * Note that the function header processing allocated stack space (CompValuTemp) for the
3483 * variable and now all we do is write its initialization value.
3484 */
3485 private void GenerateDeclVar (TokenDeclVar declVar)
3486 {
3487 /*
3488 * Script gave us an initialization value, so just store init value in var like an assignment statement.
3489 * If no init given, set it to its default value.
3490 */
3491 CompValu local = declVar.location;
3492 if (declVar.init != null) {
3493 CompValu rVal = GenerateFromRVal (declVar.init, local.GetArgTypes ());
3494 local.PopPre (this, declVar);
3495 rVal.PushVal (this, declVar.init, declVar.type);
3496 local.PopPost (this, declVar);
3497 } else {
3498 local.PopPre (this, declVar);
3499 PushDefaultValue (declVar.type);
3500 local.PopPost (this, declVar);
3501 }
3502 }
3503
3504 /**
3505 * @brief Get the type and location of an L-value (eg, variable)
3506 * @param lVal = L-value expression to evaluate
3507 * @param argsig = null: it's a field/property
3508 * else: select overload method that fits these arg types
3509 */
3510 private CompValu GenerateFromLVal (TokenLVal lVal)
3511 {
3512 return GenerateFromLVal (lVal, null);
3513 }
3514 private CompValu GenerateFromLVal (TokenLVal lVal, TokenType[] argsig)
3515 {
3516 if (lVal is TokenLValArEle) return GenerateFromLValArEle ((TokenLValArEle)lVal);
3517 if (lVal is TokenLValBaseField) return GenerateFromLValBaseField ((TokenLValBaseField)lVal, argsig);
3518 if (lVal is TokenLValIField) return GenerateFromLValIField ((TokenLValIField)lVal, argsig);
3519 if (lVal is TokenLValName) return GenerateFromLValName ((TokenLValName)lVal, argsig);
3520 if (lVal is TokenLValSField) return GenerateFromLValSField ((TokenLValSField)lVal, argsig);
3521 throw new Exception ("bad lval class");
3522 }
3523
3524 /**
3525 * @brief we have an L-value token that is an element within an array.
3526 * @returns a CompValu giving the type and location of the element of the array.
3527 */
3528 private CompValu GenerateFromLValArEle (TokenLValArEle lVal)
3529 {
3530 CompValu subCompValu;
3531
3532 /*
3533 * Compute location of array itself.
3534 */
3535 CompValu baseCompValu = GenerateFromRVal (lVal.baseRVal);
3536
3537 /*
3538 * Maybe it is a fixed array access.
3539 */
3540 string basetypestring = baseCompValu.type.ToString ();
3541 if (basetypestring.EndsWith ("]")) {
3542 TokenRVal subRVal = lVal.subRVal;
3543 int nSubs = 1;
3544 if (subRVal is TokenRValList) {
3545 nSubs = ((TokenRValList)subRVal).nItems;
3546 subRVal = ((TokenRValList)subRVal).rVal;
3547 }
3548
3549 int rank = basetypestring.IndexOf (']') - basetypestring.IndexOf ('[');
3550 if (nSubs != rank) {
3551 ErrorMsg (lVal.baseRVal, "expect " + rank + " subscript" + ((rank == 1) ? "" : "s") + " but have " + nSubs);
3552 }
3553 CompValu[] subCompValus = new CompValu[rank];
3554 int i;
3555 for (i = 0; (subRVal != null) && (i < rank); i ++) {
3556 subCompValus[i] = GenerateFromRVal (subRVal);
3557 subRVal = (TokenRVal)subRVal.nextToken;
3558 }
3559 while (i < rank) subCompValus[i++] = new CompValuInteger (new TokenTypeInt (lVal.subRVal), 0);
3560 return new CompValuFixArEl (this, baseCompValu, subCompValus);
3561 }
3562
3563 /*
3564 * Maybe it is accessing the $idxprop property of a script-defined class.
3565 */
3566 if (baseCompValu.type is TokenTypeSDTypeClass) {
3567 TokenName name = new TokenName (lVal, "$idxprop");
3568 TokenTypeSDTypeClass sdtType = (TokenTypeSDTypeClass)baseCompValu.type;
3569 TokenDeclSDTypeClass sdtDecl = sdtType.decl;
3570 TokenDeclVar idxProp = FindThisMember (sdtDecl, name, null);
3571 if (idxProp == null) {
3572 ErrorMsg (lVal, "no index property in class " + sdtDecl.longName.val);
3573 return new CompValuVoid (lVal);
3574 }
3575 if ((idxProp.sdtFlags & ScriptReduce.SDT_STATIC) != 0) {
3576 ErrorMsg (lVal, "non-static reference to static member " + idxProp.name.val);
3577 return new CompValuVoid (idxProp);
3578 }
3579 CheckAccess (idxProp, name);
3580
3581 TokenType[] argTypes = IdxPropArgTypes (idxProp);
3582 CompValu[] compValus = IdxPropCompValus (lVal, argTypes.Length);
3583 return new CompValuIdxProp (idxProp, baseCompValu, argTypes, compValus);
3584
3585 }
3586
3587 /*
3588 * Maybe they are accessing $idxprop property of a script-defined interface.
3589 */
3590 if (baseCompValu.type is TokenTypeSDTypeInterface) {
3591 TokenName name = new TokenName (lVal, "$idxprop");
3592 TokenTypeSDTypeInterface sdtType = (TokenTypeSDTypeInterface)baseCompValu.type;
3593 TokenDeclVar idxProp = FindInterfaceMember (sdtType, name, null, ref baseCompValu);
3594 if (idxProp == null) {
3595 ErrorMsg (lVal, "no index property defined for interface " + sdtType.decl.longName.val);
3596 return baseCompValu;
3597 }
3598
3599 TokenType[] argTypes = IdxPropArgTypes (idxProp);
3600 CompValu[] compValus = IdxPropCompValus (lVal, argTypes.Length);
3601 return new CompValuIdxProp (idxProp, baseCompValu, argTypes, compValus);
3602 }
3603
3604 /*
3605 * Maybe it is extracting a character from a string.
3606 */
3607 if ((baseCompValu.type is TokenTypeKey) || (baseCompValu.type is TokenTypeStr)) {
3608 subCompValu = GenerateFromRVal (lVal.subRVal);
3609 return new CompValuStrChr (new TokenTypeChar (lVal), baseCompValu, subCompValu);
3610 }
3611
3612 /*
3613 * Maybe it is extracting an element from a list.
3614 */
3615 if (baseCompValu.type is TokenTypeList) {
3616 subCompValu = GenerateFromRVal (lVal.subRVal);
3617 return new CompValuListEl (new TokenTypeObject (lVal), baseCompValu, subCompValu);
3618 }
3619
3620 /*
3621 * Access should be to XMR_Array otherwise.
3622 */
3623 if (!(baseCompValu.type is TokenTypeArray)) {
3624 ErrorMsg (lVal, "taking subscript of non-array");
3625 return baseCompValu;
3626 }
3627 subCompValu = GenerateFromRVal (lVal.subRVal);
3628 return new CompValuArEle (new TokenTypeObject (lVal), baseCompValu, subCompValu);
3629 }
3630
3631 /**
3632 * @brief Get number and type of arguments required by an index property.
3633 */
3634 private static TokenType[] IdxPropArgTypes (TokenDeclVar idxProp)
3635 {
3636 TokenType[] argTypes;
3637 if (idxProp.getProp != null) {
3638 int nArgs = idxProp.getProp.argDecl.varDict.Count;
3639 argTypes = new TokenType[nArgs];
3640 foreach (TokenDeclVar var in idxProp.getProp.argDecl.varDict) {
3641 argTypes[var.vTableIndex] = var.type;
3642 }
3643 } else {
3644 int nArgs = idxProp.setProp.argDecl.varDict.Count - 1;
3645 argTypes = new TokenType[nArgs];
3646 foreach (TokenDeclVar var in idxProp.setProp.argDecl.varDict) {
3647 if (var.vTableIndex < nArgs) {
3648 argTypes[var.vTableIndex] = var.type;
3649 }
3650 }
3651 }
3652 return argTypes;
3653 }
3654
3655 /**
3656 * @brief Get number and computed value of index property arguments.
3657 * @param lVal = list of arguments
3658 * @param nArgs = number of arguments required
3659 * @returns null: argument count mismatch
3660 * else: array of index property argument values
3661 */
3662 private CompValu[] IdxPropCompValus (TokenLValArEle lVal, int nArgs)
3663 {
3664 TokenRVal subRVal = lVal.subRVal;
3665 int nSubs = 1;
3666 if (subRVal is TokenRValList) {
3667 nSubs = ((TokenRValList)subRVal).nItems;
3668 subRVal = ((TokenRValList)subRVal).rVal;
3669 }
3670
3671 if (nSubs != nArgs) {
3672 ErrorMsg (lVal, "index property requires " + nArgs + " subscript(s)");
3673 return null;
3674 }
3675
3676 CompValu[] subCompValus = new CompValu[nArgs];
3677 for (int i = 0; i < nArgs; i ++) {
3678 subCompValus[i] = GenerateFromRVal (subRVal);
3679 subRVal = (TokenRVal)subRVal.nextToken;
3680 }
3681 return subCompValus;
3682 }
3683
3684 /**
3685 * @brief using 'base' within a script-defined instance method to refer to an instance field/method
3686 * of the class being extended.
3687 */
3688 private CompValu GenerateFromLValBaseField (TokenLValBaseField baseField, TokenType[] argsig)
3689 {
3690 string fieldName = baseField.fieldName.val;
3691
3692 TokenDeclSDType sdtDecl = curDeclFunc.sdtClass;
3693 if ((sdtDecl == null) || ((curDeclFunc.sdtFlags & ScriptReduce.SDT_STATIC) != 0)) {
3694 ErrorMsg (baseField, "cannot use 'base' outside instance method body");
3695 return new CompValuVoid (baseField);
3696 }
3697 if (!IsSDTInstMethod ()) {
3698 ErrorMsg (baseField, "cannot access instance member of base class from static method");
3699 return new CompValuVoid (baseField);
3700 }
3701
3702 TokenDeclVar declVar = FindThisMember (sdtDecl.extends, baseField.fieldName, argsig);
3703 if (declVar != null) {
3704 CheckAccess (declVar, baseField.fieldName);
3705 TokenType baseType = declVar.sdtClass.MakeRefToken (baseField);
3706 CompValu basePtr = new CompValuArg (baseType, 0);
3707 return AccessInstanceMember (declVar, basePtr, baseField, true);
3708 }
3709
3710 ErrorMsg (baseField, "no member " + fieldName + ArgSigString (argsig) + " rootward of " + sdtDecl.longName.val);
3711 return new CompValuVoid (baseField);
3712 }
3713
3714 /**
3715 * @brief We have an L-value token that is an instance field/method within a struct.
3716 * @returns a CompValu giving the type and location of the field/method in the struct.
3717 */
3718 private CompValu GenerateFromLValIField (TokenLValIField lVal, TokenType[] argsig)
3719 {
3720 CompValu baseRVal = GenerateFromRVal (lVal.baseRVal);
3721 string fieldName = lVal.fieldName.val + ArgSigString (argsig);
3722
3723 /*
3724 * Maybe they are accessing an instance field, method or property of a script-defined class.
3725 */
3726 if (baseRVal.type is TokenTypeSDTypeClass) {
3727 TokenTypeSDTypeClass sdtType = (TokenTypeSDTypeClass)baseRVal.type;
3728 TokenDeclSDTypeClass sdtDecl = sdtType.decl;
3729 TokenDeclVar declVar = FindThisMember (sdtDecl, lVal.fieldName, argsig);
3730 if (declVar != null) {
3731 CheckAccess (declVar, lVal.fieldName);
3732 return AccessInstanceMember (declVar, baseRVal, lVal, false);
3733 }
3734 ErrorMsg (lVal.fieldName, "no member " + fieldName + " in class " + sdtDecl.longName.val);
3735 return new CompValuVoid (lVal.fieldName);
3736 }
3737
3738 /*
3739 * Maybe they are accessing a method or property of a script-defined interface.
3740 */
3741 if (baseRVal.type is TokenTypeSDTypeInterface) {
3742 TokenTypeSDTypeInterface sdtType = (TokenTypeSDTypeInterface)baseRVal.type;
3743 TokenDeclVar declVar = FindInterfaceMember (sdtType, lVal.fieldName, argsig, ref baseRVal);
3744 if (declVar != null) {
3745 return new CompValuIntfMember (declVar, baseRVal);
3746 }
3747 ErrorMsg (lVal.fieldName, "no member " + fieldName + " in interface " + sdtType.decl.longName.val);
3748 return new CompValuVoid (lVal.fieldName);
3749 }
3750
3751 /*
3752 * Since we only have a few built-in types with fields, just pound them out.
3753 */
3754 if (baseRVal.type is TokenTypeArray) {
3755
3756 // no arguments, no parentheses, just the field name, returning integer
3757 // but internally, it is a call to a method()
3758 if (fieldName == "count") {
3759 return new CompValuIntInstROProp (tokenTypeInt, baseRVal, arrayCountMethodInfo);
3760 }
3761
3762 // no arguments but with the parentheses, returning void
3763 if (fieldName == "clear()") {
3764 return new CompValuIntInstMeth (XMR_Array.clearDelegate, baseRVal, arrayClearMethodInfo);
3765 }
3766
3767 // single integer argument, returning an object
3768 if (fieldName == "index(integer)") {
3769 return new CompValuIntInstMeth (XMR_Array.indexDelegate, baseRVal, arrayIndexMethodInfo);
3770 }
3771 if (fieldName == "value(integer)") {
3772 return new CompValuIntInstMeth (XMR_Array.valueDelegate, baseRVal, arrayValueMethodInfo);
3773 }
3774 }
3775 if (baseRVal.type is TokenTypeRot) {
3776 FieldInfo fi = null;
3777 if (fieldName == "x") fi = rotationXFieldInfo;
3778 if (fieldName == "y") fi = rotationYFieldInfo;
3779 if (fieldName == "z") fi = rotationZFieldInfo;
3780 if (fieldName == "s") fi = rotationSFieldInfo;
3781 if (fi != null) {
3782 return new CompValuField (new TokenTypeFloat (lVal), baseRVal, fi);
3783 }
3784 }
3785 if (baseRVal.type is TokenTypeVec) {
3786 FieldInfo fi = null;
3787 if (fieldName == "x") fi = vectorXFieldInfo;
3788 if (fieldName == "y") fi = vectorYFieldInfo;
3789 if (fieldName == "z") fi = vectorZFieldInfo;
3790 if (fi != null) {
3791 return new CompValuField (new TokenTypeFloat (lVal), baseRVal, fi);
3792 }
3793 }
3794
3795 ErrorMsg (lVal, "type " + baseRVal.type.ToString () + " does not define member " + fieldName);
3796 return baseRVal;
3797 }
3798
3799 /**
3800 * @brief We have an L-value token that is a function, method or variable name.
3801 * @param lVal = name we are looking for
3802 * @param argsig = null: just look for name as a variable
3803 * else: look for name as a function/method being called with the given argument types
3804 * eg, "(string,integer,list)"
3805 * @returns a CompValu giving the type and location of the function, method or variable.
3806 */
3807 private CompValu GenerateFromLValName (TokenLValName lVal, TokenType[] argsig)
3808 {
3809 /*
3810 * Look in variable stack then look for built-in constants and functions.
3811 */
3812 TokenDeclVar var = FindNamedVar (lVal, argsig);
3813 if (var == null) {
3814 ErrorMsg (lVal, "undefined constant/function/variable " + lVal.name.val + ArgSigString (argsig));
3815 return new CompValuVoid (lVal);
3816 }
3817
3818 /*
3819 * Maybe it has an implied 'this.' on the front.
3820 */
3821 if ((var.sdtClass != null) && ((var.sdtFlags & ScriptReduce.SDT_STATIC) == 0)) {
3822
3823 if (!IsSDTInstMethod ()) {
3824 ErrorMsg (lVal, "cannot access instance member of class from static method");
3825 return new CompValuVoid (lVal);
3826 }
3827
3828 /*
3829 * Don't allow something such as:
3830 *
3831 * class A {
3832 * integer I;
3833 * class B {
3834 * Print ()
3835 * {
3836 * llOwnerSay ("I=" + (string)I); <- access to I not allowed inside class B.
3837 * explicit reference required as we don't
3838 * have a valid reference to class A.
3839 * }
3840 * }
3841 * }
3842 *
3843 * But do allow something such as:
3844 *
3845 * class A {
3846 * integer I;
3847 * }
3848 * class B : A {
3849 * Print ()
3850 * {
3851 * llOwnerSay ("I=" + (string)I);
3852 * }
3853 * }
3854 */
3855 for (TokenDeclSDType c = curDeclFunc.sdtClass; c != var.sdtClass; c = c.extends) {
3856 if (c == null) {
3857 // our arg0 points to an instance of curDeclFunc.sdtClass, not var.sdtClass
3858 ErrorMsg (lVal, "cannot access instance member of outer class with implied 'this'");
3859 break;
3860 }
3861 }
3862
3863 CompValu thisCompValu = new CompValuArg (var.sdtClass.MakeRefToken (lVal), 0);
3864 return AccessInstanceMember (var, thisCompValu, lVal, false);
3865 }
3866
3867 /*
3868 * It's a local variable, static field, global, constant, etc.
3869 */
3870 return var.location;
3871 }
3872
3873 /**
3874 * @brief Access a script-defined type's instance member
3875 * @param declVar = which member (field,method,property) to access
3876 * @param basePtr = points to particular object instance
3877 * @param ignoreVirt = true: access declVar's method directly; else: maybe use vTable
3878 * @returns where the field/method/property is located
3879 */
3880 private CompValu AccessInstanceMember (TokenDeclVar declVar, CompValu basePtr, Token errorAt, bool ignoreVirt)
3881 {
3882 if ((declVar.sdtFlags & ScriptReduce.SDT_STATIC) != 0) {
3883 ErrorMsg (errorAt, "non-static reference to static member " + declVar.name.val);
3884 return new CompValuVoid (declVar);
3885 }
3886 return new CompValuInstMember (declVar, basePtr, ignoreVirt);
3887 }
3888
3889 /**
3890 * @brief we have an L-value token that is a static member within a struct.
3891 * @returns a CompValu giving the type and location of the member in the struct.
3892 */
3893 private CompValu GenerateFromLValSField (TokenLValSField lVal, TokenType[] argsig)
3894 {
3895 TokenType stType = lVal.baseType;
3896 string fieldName = lVal.fieldName.val + ArgSigString (argsig);
3897
3898 /*
3899 * Maybe they are accessing a static member of a script-defined class.
3900 */
3901 if (stType is TokenTypeSDTypeClass) {
3902 TokenTypeSDTypeClass sdtType = (TokenTypeSDTypeClass)stType;
3903 TokenDeclVar declVar = FindThisMember (sdtType.decl, lVal.fieldName, argsig);
3904 if (declVar != null) {
3905 CheckAccess (declVar, lVal.fieldName);
3906 if ((declVar.sdtFlags & ScriptReduce.SDT_STATIC) == 0) {
3907 ErrorMsg (lVal.fieldName, "static reference to non-static member " + fieldName);
3908 return new CompValuVoid (lVal.fieldName);
3909 }
3910 return declVar.location;
3911 }
3912 }
3913
3914 ErrorMsg (lVal.fieldName, "no member " + fieldName + " in " + stType.ToString ());
3915 return new CompValuVoid (lVal.fieldName);
3916 }
3917
3918 /**
3919 * @brief generate code from an RVal expression and return its type and where the result is stored.
3920 * For anything that has side-effects, statements are generated that perform the computation then
3921 * the result it put in a temp var and the temp var name is returned.
3922 * For anything without side-effects, they are returned as an equivalent sequence of Emits.
3923 * @param rVal = rVal token to be evaluated
3924 * @param argsig = null: not being used in an function/method context
3925 * else: string giving argument types, eg, "(string,integer,list,vector)"
3926 * that can be used to select among overloaded methods
3927 * @returns resultant type and location
3928 */
3929 private CompValu GenerateFromRVal (TokenRVal rVal)
3930 {
3931 return GenerateFromRVal (rVal, null);
3932 }
3933 private CompValu GenerateFromRVal (TokenRVal rVal, TokenType[] argsig)
3934 {
3935 errorMessageToken = rVal;
3936
3937 /*
3938 * Maybe the expression can be converted to a constant.
3939 */
3940 bool didOne;
3941 do {
3942 didOne = false;
3943 rVal = rVal.TryComputeConstant (LookupBodyConstants, ref didOne);
3944 } while (didOne);
3945
3946 /*
3947 * Generate code for the computation and return resulting type and location.
3948 */
3949 CompValu cVal = null;
3950 if (rVal is TokenRValAsnPost) cVal = GenerateFromRValAsnPost ((TokenRValAsnPost)rVal);
3951 if (rVal is TokenRValAsnPre) cVal = GenerateFromRValAsnPre ((TokenRValAsnPre)rVal);
3952 if (rVal is TokenRValCall) cVal = GenerateFromRValCall ((TokenRValCall)rVal);
3953 if (rVal is TokenRValCast) cVal = GenerateFromRValCast ((TokenRValCast)rVal);
3954 if (rVal is TokenRValCondExpr) cVal = GenerateFromRValCondExpr ((TokenRValCondExpr)rVal);
3955 if (rVal is TokenRValConst) cVal = GenerateFromRValConst ((TokenRValConst)rVal);
3956 if (rVal is TokenRValInitDef) cVal = GenerateFromRValInitDef ((TokenRValInitDef)rVal);
3957 if (rVal is TokenRValIsType) cVal = GenerateFromRValIsType ((TokenRValIsType)rVal);
3958 if (rVal is TokenRValList) cVal = GenerateFromRValList ((TokenRValList)rVal);
3959 if (rVal is TokenRValNewArIni) cVal = GenerateFromRValNewArIni ((TokenRValNewArIni)rVal);
3960 if (rVal is TokenRValOpBin) cVal = GenerateFromRValOpBin ((TokenRValOpBin)rVal);
3961 if (rVal is TokenRValOpUn) cVal = GenerateFromRValOpUn ((TokenRValOpUn)rVal);
3962 if (rVal is TokenRValParen) cVal = GenerateFromRValParen ((TokenRValParen)rVal);
3963 if (rVal is TokenRValRot) cVal = GenerateFromRValRot ((TokenRValRot)rVal);
3964 if (rVal is TokenRValThis) cVal = GenerateFromRValThis ((TokenRValThis)rVal);
3965 if (rVal is TokenRValUndef) cVal = GenerateFromRValUndef ((TokenRValUndef)rVal);
3966 if (rVal is TokenRValVec) cVal = GenerateFromRValVec ((TokenRValVec)rVal);
3967 if (rVal is TokenLVal) cVal = GenerateFromLVal ((TokenLVal)rVal, argsig);
3968
3969 if (cVal == null) throw new Exception ("bad rval class " + rVal.GetType ().ToString ());
3970
3971 /*
3972 * Sanity check.
3973 */
3974 if (!youveAnError) {
3975 if (cVal.type == null) throw new Exception ("cVal has no type " + cVal.GetType ());
3976 string cValType = cVal.type.ToString ();
3977 string rValType = rVal.GetRValType (this, argsig).ToString ();
3978 if (cValType == "bool") cValType = "integer";
3979 if (rValType == "bool") rValType = "integer";
3980 if (cValType != rValType) {
3981 throw new Exception ("cVal.type " + cValType + " != rVal.type " + rValType +
3982 " (" + rVal.GetType ().Name + " " + rVal.SrcLoc + ")");
3983 }
3984 }
3985
3986 return cVal;
3987 }
3988
3989 /**
3990 * @brief compute the result of a binary operator (eg, add, subtract, multiply, lessthan)
3991 * @param token = binary operator token, includes the left and right operands
3992 * @returns where the resultant R-value is as something that doesn't have side effects
3993 */
3994 private CompValu GenerateFromRValOpBin (TokenRValOpBin token)
3995 {
3996 CompValu left, right;
3997 string opcodeIndex = token.opcode.ToString ();
3998
3999 /*
4000 * Comma operators are special, as they say to compute the left-hand value and
4001 * discard it, then compute the right-hand argument and that is the result.
4002 */
4003 if (opcodeIndex == ",") {
4004
4005 /*
4006 * Compute left-hand operand but throw away result.
4007 */
4008 GenerateFromRVal (token.rValLeft);
4009
4010 /*
4011 * Compute right-hand operand and that is the value of the expression.
4012 */
4013 return GenerateFromRVal (token.rValRight);
4014 }
4015
4016 /*
4017 * Simple overwriting assignments are their own special case,
4018 * as we want to cast the R-value to the type of the L-value.
4019 * And in the case of delegates, we want to use the arg signature
4020 * of the delegate to select which overloaded method to use.
4021 */
4022 if (opcodeIndex == "=") {
4023 if (!(token.rValLeft is TokenLVal)) {
4024 ErrorMsg (token, "invalid L-value for =");
4025 return GenerateFromRVal (token.rValLeft);
4026 }
4027 left = GenerateFromLVal ((TokenLVal)token.rValLeft);
4028 right = Trivialize (GenerateFromRVal (token.rValRight, left.GetArgTypes ()), token.rValRight);
4029 left.PopPre (this, token.rValLeft);
4030 right.PushVal (this, token.rValRight, left.type); // push (left.type)right
4031 left.PopPost (this, token.rValLeft); // pop to left
4032 return left;
4033 }
4034
4035 /*
4036 * There are String.Concat() methods available for 2, 3 and 4 operands.
4037 * So see if we have a string concat op and optimize if so.
4038 */
4039 if ((opcodeIndex == "+") ||
4040 ((opcodeIndex == "+=") &&
4041 (token.rValLeft is TokenLVal) &&
4042 (token.rValLeft.GetRValType (this, null) is TokenTypeStr))) {
4043
4044 /*
4045 * We are adding something. Maybe it's a bunch of strings together.
4046 */
4047 List<TokenRVal> scorvs = new List<TokenRVal> ();
4048 if (StringConcatOperands (token.rValLeft, token.rValRight, scorvs, token.opcode)) {
4049
4050 /*
4051 * Evaluate all the operands, right-to-left on purpose per LSL scripting.
4052 */
4053 int i;
4054 int n = scorvs.Count;
4055 CompValu[] scocvs = new CompValu[n];
4056 for (i = n; -- i >= 0;) {
4057 scocvs[i] = GenerateFromRVal (scorvs[i]);
4058 if (i > 0) scocvs[i] = Trivialize (scocvs[i], scorvs[i]);
4059 }
4060
4061 /*
4062 * Figure out where to put the result.
4063 * A temp if '+', or back in original L-value if '+='.
4064 */
4065 CompValu retcv;
4066 if (opcodeIndex == "+") {
4067 retcv = new CompValuTemp (new TokenTypeStr (token.opcode), this);
4068 } else {
4069 retcv = GenerateFromLVal ((TokenLVal)token.rValLeft);
4070 }
4071 retcv.PopPre (this, token);
4072
4073 /*
4074 * Call the String.Concat() methods, passing operands in left-to-right order.
4075 * Force a cast to string (retcv.type) for each operand.
4076 */
4077 ++ i; scocvs[i].PushVal (this, scorvs[i], retcv.type);
4078 while (i + 3 < n) {
4079 ++ i; scocvs[i].PushVal (this, scorvs[i], retcv.type);
4080 ++ i; scocvs[i].PushVal (this, scorvs[i], retcv.type);
4081 ++ i; scocvs[i].PushVal (this, scorvs[i], retcv.type);
4082 ilGen.Emit (scorvs[i], OpCodes.Call, stringConcat4MethodInfo);
4083 }
4084 if (i + 2 < n) {
4085 ++ i; scocvs[i].PushVal (this, scorvs[i], retcv.type);
4086 ++ i; scocvs[i].PushVal (this, scorvs[i], retcv.type);
4087 ilGen.Emit (scorvs[i], OpCodes.Call, stringConcat3MethodInfo);
4088 }
4089 if (i + 1 < n) {
4090 ++ i; scocvs[i].PushVal (this, scorvs[i], retcv.type);
4091 ilGen.Emit (scorvs[i], OpCodes.Call, stringConcat2MethodInfo);
4092 }
4093
4094 /*
4095 * Put the result where we want it and return where we put it.
4096 */
4097 retcv.PopPost (this, token);
4098 return retcv;
4099 }
4100 }
4101
4102 /*
4103 * If "&&&", it is a short-circuiting AND.
4104 * Compute left-hand operand and if true, compute right-hand operand.
4105 */
4106 if (opcodeIndex == "&&&") {
4107 bool leftVal, rightVal;
4108 left = GenerateFromRVal (token.rValLeft);
4109 if (!IsConstBoolExpr (left, out leftVal)) {
4110 ScriptMyLabel falseLabel = ilGen.DefineLabel ("ssandfalse");
4111 left.PushVal (this, tokenTypeBool);
4112 ilGen.Emit (token, OpCodes.Brfalse, falseLabel);
4113 right = GenerateFromRVal (token.rValRight);
4114 if (!IsConstBoolExpr (right, out rightVal)) {
4115 right.PushVal (this, tokenTypeBool);
4116 goto donessand;
4117 }
4118 if (!rightVal) {
4119 ilGen.MarkLabel (falseLabel);
4120 return new CompValuInteger (new TokenTypeInt (token.rValLeft), 0);
4121 }
4122 ilGen.Emit (token, OpCodes.Ldc_I4_1);
4123 donessand:
4124 ScriptMyLabel doneLabel = ilGen.DefineLabel ("ssanddone");
4125 ilGen.Emit (token, OpCodes.Br, doneLabel);
4126 ilGen.MarkLabel (falseLabel);
4127 ilGen.Emit (token, OpCodes.Ldc_I4_0);
4128 ilGen.MarkLabel (doneLabel);
4129 CompValuTemp retRVal = new CompValuTemp (new TokenTypeInt (token), this);
4130 retRVal.Pop (this, token);
4131 return retRVal;
4132 }
4133
4134 if (!leftVal) {
4135 return new CompValuInteger (new TokenTypeInt (token.rValLeft), 0);
4136 }
4137
4138 right = GenerateFromRVal (token.rValRight);
4139 if (!IsConstBoolExpr (right, out rightVal)) {
4140 right.PushVal (this, tokenTypeBool);
4141 CompValuTemp retRVal = new CompValuTemp (new TokenTypeInt (token), this);
4142 retRVal.Pop (this, token);
4143 return retRVal;
4144 }
4145 return new CompValuInteger (new TokenTypeInt (token), rightVal ? 1 : 0);
4146 }
4147
4148 /*
4149 * If "|||", it is a short-circuiting OR.
4150 * Compute left-hand operand and if false, compute right-hand operand.
4151 */
4152 if (opcodeIndex == "|||") {
4153 bool leftVal, rightVal;
4154 left = GenerateFromRVal (token.rValLeft);
4155 if (!IsConstBoolExpr (left, out leftVal)) {
4156 ScriptMyLabel trueLabel = ilGen.DefineLabel ("ssortrue");
4157 left.PushVal (this, tokenTypeBool);
4158 ilGen.Emit (token, OpCodes.Brtrue, trueLabel);
4159 right = GenerateFromRVal (token.rValRight);
4160 if (!IsConstBoolExpr (right, out rightVal)) {
4161 right.PushVal (this, tokenTypeBool);
4162 goto donessor;
4163 }
4164 if (rightVal) {
4165 ilGen.MarkLabel (trueLabel);
4166 return new CompValuInteger (new TokenTypeInt (token.rValLeft), 1);
4167 }
4168 ilGen.Emit (token, OpCodes.Ldc_I4_0);
4169 donessor:
4170 ScriptMyLabel doneLabel = ilGen.DefineLabel ("ssanddone");
4171 ilGen.Emit (token, OpCodes.Br, doneLabel);
4172 ilGen.MarkLabel (trueLabel);
4173 ilGen.Emit (token, OpCodes.Ldc_I4_1);
4174 ilGen.MarkLabel (doneLabel);
4175 CompValuTemp retRVal = new CompValuTemp (new TokenTypeInt (token), this);
4176 retRVal.Pop (this, token);
4177 return retRVal;
4178 }
4179
4180 if (leftVal) {
4181 return new CompValuInteger (new TokenTypeInt (token.rValLeft), 1);
4182 }
4183
4184 right = GenerateFromRVal (token.rValRight);
4185 if (!IsConstBoolExpr (right, out rightVal)) {
4186 right.PushVal (this, tokenTypeBool);
4187 CompValuTemp retRVal = new CompValuTemp (new TokenTypeInt (token), this);
4188 retRVal.Pop (this, token);
4189 return retRVal;
4190 }
4191 return new CompValuInteger (new TokenTypeInt (token), rightVal ? 1 : 0);
4192 }
4193
4194 /*
4195 * Computation of some sort, compute right-hand operand value then left-hand value
4196 * because LSL is supposed to be right-to-left evaluation.
4197 */
4198 right = Trivialize (GenerateFromRVal (token.rValRight), token.rValRight);
4199
4200 /*
4201 * If left is a script-defined class and there is a method with the operator's name,
4202 * convert this to a call to that method with the right value as its single parameter.
4203 * Except don't if the right value is 'undef' so they can always compare to undef.
4204 */
4205 TokenType leftType = token.rValLeft.GetRValType (this, null);
4206 if ((leftType is TokenTypeSDTypeClass) && !(right.type is TokenTypeUndef)) {
4207 TokenTypeSDTypeClass sdtType = (TokenTypeSDTypeClass)leftType;
4208 TokenDeclSDTypeClass sdtDecl = sdtType.decl;
4209 TokenType[] argsig = new TokenType[] { right.type };
4210 TokenName funcName = new TokenName (token.opcode, "$op" + opcodeIndex);
4211 TokenDeclVar declFunc = FindThisMember (sdtDecl, funcName, argsig);
4212 if (declFunc != null) {
4213 CheckAccess (declFunc, funcName);
4214 left = GenerateFromRVal (token.rValLeft);
4215 CompValu method = AccessInstanceMember (declFunc, left, token, false);
4216 CompValu[] argRVals = new CompValu[] { right };
4217 return GenerateACall (method, argRVals, token);
4218 }
4219 }
4220
4221 /*
4222 * Formulate key string for binOpStrings = (lefttype)(operator)(righttype)
4223 */
4224 string leftIndex = leftType.ToString ();
4225 string rightIndex = right.type.ToString ();
4226 string key = leftIndex + opcodeIndex + rightIndex;
4227
4228 /*
4229 * If that key exists in table, then the operation is defined between those types
4230 * ... and it produces an R-value of type as given in the table.
4231 */
4232 BinOpStr binOpStr;
4233 if (BinOpStr.defined.TryGetValue (key, out binOpStr)) {
4234
4235 /*
4236 * If table contained an explicit assignment type like +=, output the statement without
4237 * casting the L-value, then return the L-value as the resultant value.
4238 *
4239 * Make sure we don't include comparisons (such as ==, >=, etc).
4240 * Nothing like +=, -=, %=, etc, generate a boolean, only the comparisons.
4241 */
4242 if ((binOpStr.outtype != typeof (bool)) && opcodeIndex.EndsWith ("=") && (opcodeIndex != "!=")) {
4243 if (!(token.rValLeft is TokenLVal)) {
4244 ErrorMsg (token.rValLeft, "invalid L-value");
4245 return GenerateFromRVal (token.rValLeft);
4246 }
4247 left = GenerateFromLVal ((TokenLVal)token.rValLeft);
4248 binOpStr.emitBO (this, token, left, right, left);
4249 return left;
4250 }
4251
4252 /*
4253 * It's of the form left binop right.
4254 * Compute left, perform operation then put result in a temp.
4255 */
4256 left = GenerateFromRVal (token.rValLeft);
4257 CompValu retRVal = new CompValuTemp (TokenType.FromSysType (token.opcode, binOpStr.outtype), this);
4258 binOpStr.emitBO (this, token, left, right, retRVal);
4259 return retRVal;
4260 }
4261
4262 /*
4263 * Nothing in the table, check for comparing object pointers because of the myriad of types possible.
4264 * This will compare list pointers, null pointers, script-defined type pointers, array pointers, etc.
4265 * It will show equal iff the memory addresses are equal and that is good enough.
4266 */
4267 if (!leftType.ToSysType().IsValueType && !right.type.ToSysType().IsValueType && ((opcodeIndex == "==") || (opcodeIndex == "!="))) {
4268 CompValuTemp retRVal = new CompValuTemp (new TokenTypeInt (token), this);
4269 left = GenerateFromRVal (token.rValLeft);
4270 left.PushVal (this, token.rValLeft);
4271 right.PushVal (this, token.rValRight);
4272 ilGen.Emit (token, OpCodes.Ceq);
4273 if (opcodeIndex == "!=") {
4274 ilGen.Emit (token, OpCodes.Ldc_I4_1);
4275 ilGen.Emit (token, OpCodes.Xor);
4276 }
4277 retRVal.Pop (this, token);
4278 return retRVal;
4279 }
4280
4281 /*
4282 * If the opcode ends with "=", it may be something like "+=".
4283 * So look up the key as if we didn't have the "=" to tell us if the operation is legal.
4284 * Also, the binary operation's output type must be the same as the L-value type.
4285 * Likewise, integer += float not allowed because result is float, but float += integer is ok.
4286 */
4287 if (opcodeIndex.EndsWith ("=")) {
4288 key = leftIndex + opcodeIndex.Substring (0, opcodeIndex.Length - 1) + rightIndex;
4289 if (BinOpStr.defined.TryGetValue (key, out binOpStr)) {
4290 if (!(token.rValLeft is TokenLVal)) {
4291 ErrorMsg (token, "invalid L-value for <op>=");
4292 return GenerateFromRVal (token.rValLeft);
4293 }
4294 if (!binOpStr.rmwOK) {
4295 ErrorMsg (token, "<op>= not allowed: " + leftIndex + " " + opcodeIndex + " " + rightIndex);
4296 return new CompValuVoid (token);
4297 }
4298
4299 /*
4300 * Now we know for something like %= that left%right is legal for the types given.
4301 */
4302 left = GenerateFromLVal ((TokenLVal)token.rValLeft);
4303 if (binOpStr.outtype == leftType.ToSysType ()) {
4304 binOpStr.emitBO (this, token, left, right, left);
4305 } else {
4306 CompValu temp = new CompValuTemp (TokenType.FromSysType (token, binOpStr.outtype), this);
4307 binOpStr.emitBO (this, token, left, right, temp);
4308 left.PopPre (this, token);
4309 temp.PushVal (this, token, leftType);
4310 left.PopPost (this, token);
4311 }
4312 return left;
4313 }
4314 }
4315
4316 /*
4317 * Can't find it, oh well.
4318 */
4319 ErrorMsg (token, "op not defined: " + leftIndex + " " + opcodeIndex + " " + rightIndex);
4320 return new CompValuVoid (token);
4321 }
4322
4323 /**
4324 * @brief Queue the given operands to the end of the scos list.
4325 * If it can be broken down into more string concat operands, do so.
4326 * Otherwise, just push it as one operand.
4327 * @param leftRVal = left-hand operand of a '+' operation
4328 * @param rightRVal = right-hand operand of a '+' operation
4329 * @param scos = left-to-right list of operands for the string concat so far
4330 * @param addop = the add operator token (either '+' or '+=')
4331 * @returns false: neither operand is a string, nothing added to scos
4332 * true: scos = updated with leftRVal then rightRVal added onto the end, possibly broken down further
4333 */
4334 private bool StringConcatOperands (TokenRVal leftRVal, TokenRVal rightRVal, List<TokenRVal> scos, TokenKw addop)
4335 {
4336 /*
4337 * If neither operand is a string (eg, float+integer), then the result isn't going to be a string.
4338 */
4339 TokenType leftType = leftRVal.GetRValType (this, null);
4340 TokenType rightType = rightRVal.GetRValType (this, null);
4341 if (!(leftType is TokenTypeStr) && !(rightType is TokenTypeStr)) return false;
4342
4343 /*
4344 * Also, list+string => list so reject that too.
4345 * Also, string+list => list so reject that too.
4346 */
4347 if (leftType is TokenTypeList) return false;
4348 if (rightType is TokenTypeList) return false;
4349
4350 /*
4351 * Append values to the end of the list in left-to-right order.
4352 * If value is formed from a something+something => string,
4353 * push them as separate values, otherwise push as one value.
4354 */
4355 StringConcatOperand (leftType, leftRVal, scos);
4356 StringConcatOperand (rightType, rightRVal, scos);
4357
4358 /*
4359 * Maybe constant strings can be concatted.
4360 */
4361 try {
4362 int len;
4363 while (((len = scos.Count) >= 2) &&
4364 ((leftRVal = scos[len-2]) is TokenRValConst) &&
4365 ((rightRVal = scos[len-1]) is TokenRValConst)) {
4366 object sum = addop.binOpConst (((TokenRValConst)leftRVal).val,
4367 ((TokenRValConst)rightRVal).val);
4368 scos[len-2] = new TokenRValConst (addop, sum);
4369 scos.RemoveAt (len - 1);
4370 }
4371 } catch {
4372 }
4373
4374 /*
4375 * We pushed some string stuff.
4376 */
4377 return true;
4378 }
4379
4380 /**
4381 * @brief Queue the given operand to the end of the scos list.
4382 * If it can be broken down into more string concat operands, do so.
4383 * Otherwise, just push it as one operand.
4384 * @param type = rVal's resultant type
4385 * @param rVal = operand to examine
4386 * @param scos = left-to-right list of operands for the string concat so far
4387 * @returns with scos = updated with rVal added onto the end, possibly broken down further
4388 */
4389 private void StringConcatOperand (TokenType type, TokenRVal rVal, List<TokenRVal> scos)
4390 {
4391 bool didOne;
4392 do {
4393 didOne = false;
4394 rVal = rVal.TryComputeConstant (LookupBodyConstants, ref didOne);
4395 } while (didOne);
4396
4397 if (!(type is TokenTypeStr)) goto pushasis;
4398 if (!(rVal is TokenRValOpBin)) goto pushasis;
4399 TokenRValOpBin rValOpBin = (TokenRValOpBin)rVal;
4400 if (!(rValOpBin.opcode is TokenKwAdd)) goto pushasis;
4401 if (StringConcatOperands (rValOpBin.rValLeft, rValOpBin.rValRight, scos, rValOpBin.opcode)) return;
4402 pushasis:
4403 scos.Add (rVal);
4404 }
4405
4406 /**
4407 * @brief compute the result of an unary operator
4408 * @param token = unary operator token, includes the operand
4409 * @returns where the resultant R-value is
4410 */
4411 private CompValu GenerateFromRValOpUn (TokenRValOpUn token)
4412 {
4413 CompValu inRVal = GenerateFromRVal (token.rVal);
4414
4415 /*
4416 * Script-defined types can define their own methods to handle unary operators.
4417 */
4418 if (inRVal.type is TokenTypeSDTypeClass) {
4419 TokenTypeSDTypeClass sdtType = (TokenTypeSDTypeClass)inRVal.type;
4420 TokenDeclSDTypeClass sdtDecl = sdtType.decl;
4421 TokenName funcName = new TokenName (token.opcode, "$op" + token.opcode.ToString ());
4422 TokenDeclVar declFunc = FindThisMember (sdtDecl, funcName, zeroArgs);
4423 if (declFunc != null) {
4424 CheckAccess (declFunc, funcName);
4425 CompValu method = AccessInstanceMember (declFunc, inRVal, token, false);
4426 return GenerateACall (method, zeroCompValus, token);
4427 }
4428 }
4429
4430 /*
4431 * Otherwise use the default.
4432 */
4433 return UnOpGenerate (inRVal, token.opcode);
4434 }
4435
4436 /**
4437 * @brief postfix operator -- this returns the type and location of the resultant value
4438 */
4439 private CompValu GenerateFromRValAsnPost (TokenRValAsnPost asnPost)
4440 {
4441 CompValu lVal = GenerateFromLVal (asnPost.lVal);
4442
4443 /*
4444 * Make up a temp to save original value in.
4445 */
4446 CompValuTemp result = new CompValuTemp (lVal.type, this);
4447
4448 /*
4449 * Prepare to pop incremented value back into variable being incremented.
4450 */
4451 lVal.PopPre (this, asnPost.lVal);
4452
4453 /*
4454 * Copy original value to temp and leave value on stack.
4455 */
4456 lVal.PushVal (this, asnPost.lVal);
4457 ilGen.Emit (asnPost.lVal, OpCodes.Dup);
4458 result.Pop (this, asnPost.lVal);
4459
4460 /*
4461 * Perform the ++/--.
4462 */
4463 if ((lVal.type is TokenTypeChar) || (lVal.type is TokenTypeInt)) {
4464 ilGen.Emit (asnPost, OpCodes.Ldc_I4_1);
4465 } else if (lVal.type is TokenTypeFloat) {
4466 ilGen.Emit (asnPost, OpCodes.Ldc_R4, 1.0f);
4467 } else {
4468 lVal.PopPost (this, asnPost.lVal);
4469 ErrorMsg (asnPost, "invalid type for " + asnPost.postfix.ToString ());
4470 return lVal;
4471 }
4472 switch (asnPost.postfix.ToString ()) {
4473 case "++": {
4474 ilGen.Emit (asnPost, OpCodes.Add);
4475 break;
4476 }
4477 case "--": {
4478 ilGen.Emit (asnPost, OpCodes.Sub);
4479 break;
4480 }
4481 default: throw new Exception ("unknown asnPost op");
4482 }
4483
4484 /*
4485 * Store new value in original variable.
4486 */
4487 lVal.PopPost (this, asnPost.lVal);
4488
4489 return result;
4490 }
4491
4492 /**
4493 * @brief prefix operator -- this returns the type and location of the resultant value
4494 */
4495 private CompValu GenerateFromRValAsnPre (TokenRValAsnPre asnPre)
4496 {
4497 CompValu lVal = GenerateFromLVal (asnPre.lVal);
4498
4499 /*
4500 * Make up a temp to put result in.
4501 */
4502 CompValuTemp result = new CompValuTemp (lVal.type, this);
4503
4504 /*
4505 * Prepare to pop incremented value back into variable being incremented.
4506 */
4507 lVal.PopPre (this, asnPre.lVal);
4508
4509 /*
4510 * Push original value.
4511 */
4512 lVal.PushVal (this, asnPre.lVal);
4513
4514 /*
4515 * Perform the ++/--.
4516 */
4517 if ((lVal.type is TokenTypeChar) || (lVal.type is TokenTypeInt)) {
4518 ilGen.Emit (asnPre, OpCodes.Ldc_I4_1);
4519 } else if (lVal.type is TokenTypeFloat) {
4520 ilGen.Emit (asnPre, OpCodes.Ldc_R4, 1.0f);
4521 } else {
4522 lVal.PopPost (this, asnPre.lVal);
4523 ErrorMsg (asnPre, "invalid type for " + asnPre.prefix.ToString ());
4524 return lVal;
4525 }
4526 switch (asnPre.prefix.ToString ()) {
4527 case "++": {
4528 ilGen.Emit (asnPre, OpCodes.Add);
4529 break;
4530 }
4531 case "--": {
4532 ilGen.Emit (asnPre, OpCodes.Sub);
4533 break;
4534 }
4535 default: throw new Exception ("unknown asnPre op");
4536 }
4537
4538 /*
4539 * Store new value in temp variable, keeping new value on stack.
4540 */
4541 ilGen.Emit (asnPre.lVal, OpCodes.Dup);
4542 result.Pop (this, asnPre.lVal);
4543
4544 /*
4545 * Store new value in original variable.
4546 */
4547 lVal.PopPost (this, asnPre.lVal);
4548
4549 return result;
4550 }
4551
4552 /**
4553 * @brief Generate code that calls a function or object's method.
4554 * @returns where the call's return value is stored (a TokenTypeVoid if void)
4555 */
4556 private CompValu GenerateFromRValCall (TokenRValCall call)
4557 {
4558 CompValu method;
4559 CompValu[] argRVals;
4560 int i, nargs;
4561 TokenRVal arg;
4562 TokenType[] argTypes;
4563
4564 /*
4565 * Compute the values of all the function's call arguments.
4566 * Save where the computation results are in the argRVals[] array.
4567 * Might as well build the argument signature from the argument types, too.
4568 */
4569 nargs = call.nArgs;
4570 argRVals = new CompValu[nargs];
4571 argTypes = new TokenType[nargs];
4572 if (nargs > 0) {
4573 i = 0;
4574 for (arg = call.args; arg != null; arg = (TokenRVal)arg.nextToken) {
4575 argRVals[i] = GenerateFromRVal (arg);
4576 argTypes[i] = argRVals[i].type;
4577 i ++;
4578 }
4579 }
4580
4581 /*
4582 * Get function/method's entrypoint that matches the call argument types.
4583 */
4584 method = GenerateFromRVal (call.meth, argTypes);
4585 if (method == null) return null;
4586
4587 return GenerateACall (method, argRVals, call);
4588 }
4589
4590 /**
4591 * @brief Generate call to a function/method.
4592 * @param method = function/method being called
4593 * @param argVRVals = its call parameters (zero length if none)
4594 * @param call = where in source code call is being made from (for error messages)
4595 * @returns type and location of return value (CompValuVoid if none)
4596 */
4597 private CompValu GenerateACall (CompValu method, CompValu[] argRVals, Token call)
4598 {
4599 CompValuTemp result;
4600 int i, nArgs;
4601 TokenType retType;
4602 TokenType[] argTypes;
4603
4604 /*
4605 * Must be some kind of callable.
4606 */
4607 retType = method.GetRetType (); // TokenTypeVoid if void; null means a variable
4608 if (retType == null) {
4609 ErrorMsg (call, "must be a delegate, function or method");
4610 return new CompValuVoid (call);
4611 }
4612
4613 /*
4614 * Get a location for return value.
4615 */
4616 if (retType is TokenTypeVoid) {
4617 result = new CompValuVoid (call);
4618 } else {
4619 result = new CompValuTemp (retType, this);
4620 }
4621
4622 /*
4623 * Make sure all arguments are trivial, ie, don't involve their own call labels.
4624 * For any that aren't, output code to calculate the arg and put in a temporary.
4625 */
4626 nArgs = argRVals.Length;
4627 for (i = 0; i < nArgs; i ++) {
4628 if (!argRVals[i].IsReadTrivial (this, call)) {
4629 argRVals[i] = Trivialize (argRVals[i], call);
4630 }
4631 }
4632
4633 /*
4634 * Inline functions know how to generate their own call.
4635 */
4636 if (method is CompValuInline) {
4637 CompValuInline inline = (CompValuInline)method;
4638 inline.declInline.CodeGen (this, call, result, argRVals);
4639 return result;
4640 }
4641
4642 /*
4643 * Push whatever the function/method needs as a this argument, if anything.
4644 */
4645 method.CallPre (this, call);
4646
4647 /*
4648 * Push the script-visible args, left-to-right.
4649 */
4650 argTypes = method.GetArgTypes ();
4651 for (i = 0; i < nArgs; i ++) {
4652 if (argTypes == null) {
4653 argRVals[i].PushVal (this, call);
4654 } else {
4655 argRVals[i].PushVal (this, call, argTypes[i]);
4656 }
4657 }
4658
4659 /*
4660 * Now output call instruction.
4661 */
4662 method.CallPost (this, call);
4663
4664 /*
4665 * Deal with the return value (if any), by putting it in 'result'.
4666 */
4667 result.Pop (this, call, retType);
4668 return result;
4669 }
4670
4671 /**
4672 * @brief This is needed to avoid nesting call labels around non-trivial properties.
4673 * It should be used for the second (and later) operands.
4674 * Note that a 'call' is considered an operator, so all arguments of a call
4675 * should be trivialized, but the method itself does not need to be.
4676 */
4677 public CompValu Trivialize (CompValu operand, Token errorAt)
4678 {
4679 if (operand.IsReadTrivial (this, errorAt)) return operand;
4680 CompValuTemp temp = new CompValuTemp (operand.type, this);
4681 operand.PushVal (this, errorAt);
4682 temp.Pop (this, errorAt);
4683 return temp;
4684 }
4685
4686 /**
4687 * @brief Generate code that casts a value to a particular type.
4688 * @returns where the result of the conversion is stored.
4689 */
4690 private CompValu GenerateFromRValCast (TokenRValCast cast)
4691 {
4692 /*
4693 * If casting to a delegate type, use the argment signature
4694 * of the delegate to help select the function/method, eg,
4695 * '(delegate string(integer))ToString'
4696 * will select 'string ToString(integer x)'
4697 * instaead of 'string ToString(float x)' or anything else
4698 */
4699 TokenType[] argsig = null;
4700 TokenType outType = cast.castTo;
4701 if (outType is TokenTypeSDTypeDelegate) {
4702 argsig = ((TokenTypeSDTypeDelegate)outType).decl.GetArgTypes ();
4703 }
4704
4705 /*
4706 * Generate the value that is being cast.
4707 * If the value is already the requested type, just use it as is.
4708 */
4709 CompValu inRVal = GenerateFromRVal (cast.rVal, argsig);
4710 if (inRVal.type == outType) return inRVal;
4711
4712 /*
4713 * Different type, generate casting code, putting the result in a temp of the output type.
4714 */
4715 CompValu outRVal = new CompValuTemp (outType, this);
4716 outRVal.PopPre (this, cast);
4717 inRVal.PushVal (this, cast, outType, true);
4718 outRVal.PopPost (this, cast);
4719 return outRVal;
4720 }
4721
4722 /**
4723 * @brief Compute conditional expression value.
4724 * @returns type and location of computed value.
4725 */
4726 private CompValu GenerateFromRValCondExpr (TokenRValCondExpr rValCondExpr)
4727 {
4728 bool condVal;
4729 CompValu condValu = GenerateFromRVal (rValCondExpr.condExpr);
4730 if (IsConstBoolExpr (condValu, out condVal)) {
4731 return GenerateFromRVal (condVal ? rValCondExpr.trueExpr : rValCondExpr.falseExpr);
4732 }
4733
4734 ScriptMyLabel falseLabel = ilGen.DefineLabel ("condexfalse");
4735 ScriptMyLabel doneLabel = ilGen.DefineLabel ("condexdone");
4736
4737 condValu.PushVal (this, rValCondExpr.condExpr, tokenTypeBool);
4738 ilGen.Emit (rValCondExpr, OpCodes.Brfalse, falseLabel);
4739
4740 CompValu trueValu = GenerateFromRVal (rValCondExpr.trueExpr);
4741 trueValu.PushVal (this, rValCondExpr.trueExpr);
4742 ilGen.Emit (rValCondExpr, OpCodes.Br, doneLabel);
4743
4744 ilGen.MarkLabel (falseLabel);
4745 CompValu falseValu = GenerateFromRVal (rValCondExpr.falseExpr);
4746 falseValu.PushVal (this, rValCondExpr.falseExpr);
4747
4748 if (trueValu.type.GetType () != falseValu.type.GetType ()) {
4749 ErrorMsg (rValCondExpr, "? operands " + trueValu.type.ToString () + " : " +
4750 falseValu.type.ToString () + " must be of same type");
4751 }
4752
4753 ilGen.MarkLabel (doneLabel);
4754 CompValuTemp retRVal = new CompValuTemp (trueValu.type, this);
4755 retRVal.Pop (this, rValCondExpr);
4756 return retRVal;
4757 }
4758
4759 /**
4760 * @brief Constant in the script somewhere
4761 * @returns where the constants value is stored
4762 */
4763 private CompValu GenerateFromRValConst (TokenRValConst rValConst)
4764 {
4765 switch (rValConst.type) {
4766 case TokenRValConstType.CHAR: {
4767 return new CompValuChar (new TokenTypeChar (rValConst), (char)(rValConst.val));
4768 }
4769 case TokenRValConstType.FLOAT: {
4770 return new CompValuFloat (new TokenTypeFloat (rValConst), (double)(rValConst.val));
4771 }
4772 case TokenRValConstType.INT: {
4773 return new CompValuInteger (new TokenTypeInt (rValConst), (int)(rValConst.val));
4774 }
4775 case TokenRValConstType.KEY: {
4776 return new CompValuString (new TokenTypeKey (rValConst), (string)(rValConst.val));
4777 }
4778 case TokenRValConstType.STRING: {
4779 return new CompValuString (new TokenTypeStr (rValConst), (string)(rValConst.val));
4780 }
4781 }
4782 throw new Exception ("unknown constant type " + rValConst.val.GetType ());
4783 }
4784
4785 /**
4786 * @brief generate a new list object
4787 * @param rValList = an rVal to create it from
4788 */
4789 private CompValu GenerateFromRValList (TokenRValList rValList)
4790 {
4791 /*
4792 * Compute all element values and remember where we put them.
4793 * Do it right-to-left as customary for LSL scripts.
4794 */
4795 int i = 0;
4796 TokenRVal lastRVal = null;
4797 for (TokenRVal val = rValList.rVal; val != null; val = (TokenRVal)val.nextToken) {
4798 i ++;
4799 val.prevToken = lastRVal;
4800 lastRVal = val;
4801 }
4802 CompValu[] vals = new CompValu[i];
4803 for (TokenRVal val = lastRVal; val != null; val = (TokenRVal)val.prevToken) {
4804 vals[--i] = GenerateFromRVal (val);
4805 }
4806
4807 /*
4808 * This is the temp that will hold the created list.
4809 */
4810 CompValuTemp newList = new CompValuTemp (new TokenTypeList (rValList.rVal), this);
4811
4812 /*
4813 * Create a temp object[] array to hold all the initial values.
4814 */
4815 ilGen.Emit (rValList, OpCodes.Ldc_I4, rValList.nItems);
4816 ilGen.Emit (rValList, OpCodes.Newarr, typeof (object));
4817
4818 /*
4819 * Populate the array.
4820 */
4821 i = 0;
4822 for (TokenRVal val = rValList.rVal; val != null; val = (TokenRVal)val.nextToken) {
4823
4824 /*
4825 * Get pointer to temp array object.
4826 */
4827 ilGen.Emit (rValList, OpCodes.Dup);
4828
4829 /*
4830 * Get index in that array.
4831 */
4832 ilGen.Emit (rValList, OpCodes.Ldc_I4, i);
4833
4834 /*
4835 * Store initialization value in array location.
4836 * However, floats and ints need to be converted to LSL_Float and LSL_Integer,
4837 * or things like llSetPayPrice() will puque when they try to cast the elements
4838 * to LSL_Float or LSL_Integer. Likewise with string/LSL_String.
4839 *
4840 * Maybe it's already LSL-boxed so we don't do anything with it except make sure
4841 * it is an object, not a struct.
4842 */
4843 CompValu eRVal = vals[i++];
4844 eRVal.PushVal (this, val);
4845 if (eRVal.type.ToLSLWrapType () == null) {
4846 if (eRVal.type is TokenTypeFloat) {
4847 ilGen.Emit (val, OpCodes.Newobj, lslFloatConstructorInfo);
4848 ilGen.Emit (val, OpCodes.Box, typeof (LSL_Float));
4849 } else if (eRVal.type is TokenTypeInt) {
4850 ilGen.Emit (val, OpCodes.Newobj, lslIntegerConstructorInfo);
4851 ilGen.Emit (val, OpCodes.Box, typeof (LSL_Integer));
4852 } else if ((eRVal.type is TokenTypeKey) || (eRVal.type is TokenTypeStr)) {
4853 ilGen.Emit (val, OpCodes.Newobj, lslStringConstructorInfo);
4854 ilGen.Emit (val, OpCodes.Box, typeof (LSL_String));
4855 } else if (eRVal.type.ToSysType ().IsValueType) {
4856 ilGen.Emit (val, OpCodes.Box, eRVal.type.ToSysType ());
4857 }
4858 } else if (eRVal.type.ToLSLWrapType ().IsValueType) {
4859
4860 // Convert the LSL value structs to an object of the LSL-boxed type
4861 ilGen.Emit (val, OpCodes.Box, eRVal.type.ToLSLWrapType ());
4862 }
4863 ilGen.Emit (val, OpCodes.Stelem, typeof (object));
4864 }
4865
4866 /*
4867 * Create new list object from temp initial value array (whose ref is still on the stack).
4868 */
4869 ilGen.Emit (rValList, OpCodes.Newobj, lslListConstructorInfo);
4870 newList.Pop (this, rValList);
4871 return newList;
4872 }
4873
4874 /**
4875 * @brief New array allocation with initializer expressions.
4876 */
4877 private CompValu GenerateFromRValNewArIni (TokenRValNewArIni rValNewArIni)
4878 {
4879 return MallocAndInitArray (rValNewArIni.arrayType, rValNewArIni.valueList);
4880 }
4881
4882 /**
4883 * @brief Mallocate and initialize an array from its initialization list.
4884 * @param arrayType = type of the array to be allocated and initialized
4885 * @param values = initialization value list used to size and initialize the array.
4886 * @returns memory location of the resultant initialized array.
4887 */
4888 private CompValu MallocAndInitArray (TokenType arrayType, TokenList values)
4889 {
4890 TokenDeclSDTypeClass arrayDecl = ((TokenTypeSDTypeClass)arrayType).decl;
4891 TokenType eleType = arrayDecl.arrayOfType;
4892 int rank = arrayDecl.arrayOfRank;
4893
4894 // Get size of each of the dimensions by scanning the initialization value list
4895 int[] dimSizes = new int[rank];
4896 FillInDimSizes (dimSizes, 0, rank, values);
4897
4898 // Figure out where the array's $new() method is
4899 TokenType[] newargsig = new TokenType[rank];
4900 for (int k = 0; k < rank; k ++) {
4901 newargsig[k] = tokenTypeInt;
4902 }
4903 TokenDeclVar newMeth = FindThisMember (arrayDecl, new TokenName (null, "$new"), newargsig);
4904
4905 // Output a call to malloc the array with all default values
4906 // array = ArrayType.$new (dimSizes[0], dimSizes[1], ...)
4907 CompValuTemp array = new CompValuTemp (arrayType, this);
4908 PushXMRInst ();
4909 for (int k = 0; k < rank; k ++) {
4910 ilGen.Emit (values, OpCodes.Ldc_I4, dimSizes[k]);
4911 }
4912 ilGen.Emit (values, OpCodes.Call, newMeth.ilGen);
4913 array.Pop (this, arrayType);
4914
4915 // Figure out where the array's Set() method is
4916 TokenType[] setargsig = new TokenType[rank+1];
4917 for (int k = 0; k < rank; k ++) {
4918 setargsig[k] = tokenTypeInt;
4919 }
4920 setargsig[rank] = eleType;
4921 TokenDeclVar setMeth = FindThisMember (arrayDecl, new TokenName (null, "Set"), setargsig);
4922
4923 // Fill in the array with the initializer values
4924 FillInInitVals (array, setMeth, dimSizes, 0, rank, values, eleType);
4925
4926 // The array is our resultant value
4927 return array;
4928 }
4929
4930 /**
4931 * @brief Compute an array's dimensions given its initialization value list
4932 * @param dimSizes = filled in with array's dimensions
4933 * @param dimNo = what dimension the 'values' list applies to
4934 * @param rank = total number of dimensions of the array
4935 * @param values = list of values to initialize the array's 'dimNo' dimension with
4936 * @returns with dimSizes[dimNo..rank-1] filled in
4937 */
4938 private static void FillInDimSizes (int[] dimSizes, int dimNo, int rank, TokenList values)
4939 {
4940 // the size of a dimension is the largest number of initializer elements at this level
4941 // for dimNo 0, this is the number of elements in the top-level list
4942 if (dimSizes[dimNo] < values.tl.Count) dimSizes[dimNo] = values.tl.Count;
4943
4944 // see if there is another dimension to calculate
4945 if (++ dimNo < rank) {
4946
4947 // its size is the size of the largest initializer list at the next inner level
4948 foreach (Token val in values.tl) {
4949 if (val is TokenList) {
4950 TokenList subvals = (TokenList)val;
4951 FillInDimSizes (dimSizes, dimNo, rank, subvals);
4952 }
4953 }
4954 }
4955 }
4956
4957 /**
4958 * @brief Output code to fill in array's initialization values
4959 * @param array = array to be filled in
4960 * @param setMeth = the array's Set() method
4961 * @param subscripts = holds subscripts being built
4962 * @param dimNo = which dimension the 'values' are for
4963 * @param values = list of initialization values for dimension 'dimNo'
4964 * @param rank = number of dimensions of 'array'
4965 * @param values = list of values to initialize the array's 'dimNo' dimension with
4966 * @param eleType = the element's type
4967 * @returns with code emitted to initialize array's [subscripts[0], ..., subscripts[dimNo-1], *, *, ...]
4968 * dimNo and up completely filled ---^
4969 */
4970 private void FillInInitVals (CompValu array, TokenDeclVar setMeth, int[] subscripts, int dimNo, int rank, TokenList values, TokenType eleType)
4971 {
4972 subscripts[dimNo] = 0;
4973 foreach (Token val in values.tl) {
4974 CompValu initValue = null;
4975
4976 /*
4977 * If it is a sublist, process it.
4978 * If we don't have enough subscripts yet, hopefully that sublist will have enough.
4979 * If we already have enough subscripts, then that sublist can be for an element of this supposedly jagged array.
4980 */
4981 if (val is TokenList) {
4982 TokenList sublist = (TokenList)val;
4983 if (dimNo + 1 < rank) {
4984
4985 /*
4986 * We don't have enough subscripts yet, hopefully the sublist has the rest.
4987 */
4988 FillInInitVals (array, setMeth, subscripts, dimNo + 1, rank, sublist, eleType);
4989 } else if ((eleType is TokenTypeSDTypeClass) && (((TokenTypeSDTypeClass)eleType).decl.arrayOfType == null)) {
4990
4991 /*
4992 * If we aren't a jagged array either, we can't do anything with the sublist.
4993 */
4994 ErrorMsg (val, "too many brace levels");
4995 } else {
4996
4997 /*
4998 * We are a jagged array, so malloc a subarray and initialize it with the sublist.
4999 * Then we can use that subarray to fill this array's element.
5000 */
5001 initValue = MallocAndInitArray (eleType, sublist);
5002 }
5003 }
5004
5005 /*
5006 * If it is a value expression, then output code to compute the value.
5007 */
5008 if (val is TokenRVal) {
5009 if (dimNo + 1 < rank) {
5010 ErrorMsg ((Token)val, "not enough brace levels");
5011 } else {
5012 initValue = GenerateFromRVal ((TokenRVal)val);
5013 }
5014 }
5015
5016 /*
5017 * If there is an initValue, output "array.Set (subscript[0], subscript[1], ..., initValue)"
5018 */
5019 if (initValue != null) {
5020 array.PushVal (this, val);
5021 for (int i = 0; i <= dimNo; i ++) {
5022 ilGen.Emit (val, OpCodes.Ldc_I4, subscripts[i]);
5023 }
5024 initValue.PushVal (this, val, eleType);
5025 ilGen.Emit (val, OpCodes.Call, setMeth.ilGen);
5026 }
5027
5028 /*
5029 * That subscript is processed one way or another, on to the next.
5030 */
5031 subscripts[dimNo] ++;
5032 }
5033 }
5034
5035 /**
5036 * @brief parenthesized expression
5037 * @returns type and location of the result of the computation.
5038 */
5039 private CompValu GenerateFromRValParen (TokenRValParen rValParen)
5040 {
5041 return GenerateFromRVal (rValParen.rVal);
5042 }
5043
5044 /**
5045 * @brief create a rotation object from the x,y,z,w value expressions.
5046 */
5047 private CompValu GenerateFromRValRot (TokenRValRot rValRot)
5048 {
5049 CompValu xRVal, yRVal, zRVal, wRVal;
5050
5051 xRVal = Trivialize (GenerateFromRVal (rValRot.xRVal), rValRot);
5052 yRVal = Trivialize (GenerateFromRVal (rValRot.yRVal), rValRot);
5053 zRVal = Trivialize (GenerateFromRVal (rValRot.zRVal), rValRot);
5054 wRVal = Trivialize (GenerateFromRVal (rValRot.wRVal), rValRot);
5055 return new CompValuRot (new TokenTypeRot (rValRot), xRVal, yRVal, zRVal, wRVal);
5056 }
5057
5058 /**
5059 * @brief Using 'this' as a pointer to the current script-defined instance object.
5060 * The value is located in arg #0 of the current instance method.
5061 */
5062 private CompValu GenerateFromRValThis (TokenRValThis zhis)
5063 {
5064 if (!IsSDTInstMethod ()) {
5065 ErrorMsg (zhis, "cannot access instance member of class from static method");
5066 return new CompValuVoid (zhis);
5067 }
5068 return new CompValuArg (curDeclFunc.sdtClass.MakeRefToken (zhis), 0);
5069 }
5070
5071 /**
5072 * @brief 'undefined' constant.
5073 * If this constant gets written to an array element, it will delete that element from the array.
5074 * If the script retrieves an element by key that is not defined, it will get this value.
5075 * This value can be stored in and retrieved from variables of type 'object' or script-defined classes.
5076 * It is a runtime error to cast this value to any other type, eg,
5077 * we don't allow list or string variables to be null pointers.
5078 */
5079 private CompValu GenerateFromRValUndef (TokenRValUndef rValUndef)
5080 {
5081 return new CompValuNull (new TokenTypeUndef (rValUndef));
5082 }
5083
5084 /**
5085 * @brief create a vector object from the x,y,z value expressions.
5086 */
5087 private CompValu GenerateFromRValVec (TokenRValVec rValVec)
5088 {
5089 CompValu xRVal, yRVal, zRVal;
5090
5091 xRVal = Trivialize (GenerateFromRVal (rValVec.xRVal), rValVec);
5092 yRVal = Trivialize (GenerateFromRVal (rValVec.yRVal), rValVec);
5093 zRVal = Trivialize (GenerateFromRVal (rValVec.zRVal), rValVec);
5094 return new CompValuVec (new TokenTypeVec (rValVec), xRVal, yRVal, zRVal);
5095 }
5096
5097 /**
5098 * @brief Generate code to get the default initialization value for a variable.
5099 */
5100 private CompValu GenerateFromRValInitDef (TokenRValInitDef rValInitDef)
5101 {
5102 TokenType type = rValInitDef.type;
5103
5104 if (type is TokenTypeChar) {
5105 return new CompValuChar (type, (char)0);
5106 }
5107 if (type is TokenTypeRot) {
5108 CompValuFloat x = new CompValuFloat (type, ScriptBaseClass.ZERO_ROTATION.x);
5109 CompValuFloat y = new CompValuFloat (type, ScriptBaseClass.ZERO_ROTATION.y);
5110 CompValuFloat z = new CompValuFloat (type, ScriptBaseClass.ZERO_ROTATION.z);
5111 CompValuFloat s = new CompValuFloat (type, ScriptBaseClass.ZERO_ROTATION.s);
5112 return new CompValuRot (type, x, y, z, s);
5113 }
5114 if ((type is TokenTypeKey) || (type is TokenTypeStr)) {
5115 return new CompValuString (type, "");
5116 }
5117 if (type is TokenTypeVec) {
5118 CompValuFloat x = new CompValuFloat (type, ScriptBaseClass.ZERO_VECTOR.x);
5119 CompValuFloat y = new CompValuFloat (type, ScriptBaseClass.ZERO_VECTOR.y);
5120 CompValuFloat z = new CompValuFloat (type, ScriptBaseClass.ZERO_VECTOR.z);
5121 return new CompValuVec (type, x, y, z);
5122 }
5123 if (type is TokenTypeInt) {
5124 return new CompValuInteger (type, 0);
5125 }
5126 if (type is TokenTypeFloat) {
5127 return new CompValuFloat (type, 0);
5128 }
5129 if (type is TokenTypeVoid) {
5130 return new CompValuVoid (type);
5131 }
5132
5133 /*
5134 * Default for 'object' type is 'undef'.
5135 * Likewise for script-defined classes and interfaces.
5136 */
5137 if ((type is TokenTypeObject) || (type is TokenTypeSDTypeClass) || (type is TokenTypeSDTypeDelegate) ||
5138 (type is TokenTypeSDTypeInterface) || (type is TokenTypeExc)) {
5139 return new CompValuNull (type);
5140 }
5141
5142 /*
5143 * array and list
5144 */
5145 CompValuTemp temp = new CompValuTemp (type, this);
5146 PushDefaultValue (type);
5147 temp.Pop (this, rValInitDef, type);
5148 return temp;
5149 }
5150
5151 /**
5152 * @brief Generate code to process an <rVal> is <type> expression, and produce a boolean value.
5153 */
5154 private CompValu GenerateFromRValIsType (TokenRValIsType rValIsType)
5155 {
5156 /*
5157 * Expression we want to know the type of.
5158 */
5159 CompValu val = GenerateFromRVal (rValIsType.rValExp);
5160
5161 /*
5162 * Pass it in to top-level type expression decoder.
5163 */
5164 return GenerateFromTypeExp (val, rValIsType.typeExp);
5165 }
5166
5167 /**
5168 * @brief See if the type of the given value matches the type expression.
5169 * @param val = where the value to be evaluated is stored
5170 * @param typeExp = script tokens representing type expression
5171 * @returns location where the boolean result is stored
5172 */
5173 private CompValu GenerateFromTypeExp (CompValu val, TokenTypeExp typeExp)
5174 {
5175 if (typeExp is TokenTypeExpBinOp) {
5176 CompValu left = GenerateFromTypeExp (val, ((TokenTypeExpBinOp)typeExp).leftOp);
5177 CompValu right = GenerateFromTypeExp (val, ((TokenTypeExpBinOp)typeExp).rightOp);
5178 CompValuTemp result = new CompValuTemp (tokenTypeBool, this);
5179 Token op = ((TokenTypeExpBinOp)typeExp).binOp;
5180 left.PushVal (this, ((TokenTypeExpBinOp)typeExp).leftOp);
5181 right.PushVal (this, ((TokenTypeExpBinOp)typeExp).rightOp);
5182 if (op is TokenKwAnd) {
5183 ilGen.Emit (typeExp, OpCodes.And);
5184 } else if (op is TokenKwOr) {
5185 ilGen.Emit (typeExp, OpCodes.Or);
5186 } else {
5187 throw new Exception ("unknown TokenTypeExpBinOp " + op.GetType ());
5188 }
5189 result.Pop (this, typeExp);
5190 return result;
5191 }
5192 if (typeExp is TokenTypeExpNot) {
5193 CompValu interm = GenerateFromTypeExp (val, ((TokenTypeExpNot)typeExp).typeExp);
5194 CompValuTemp result = new CompValuTemp (tokenTypeBool, this);
5195 interm.PushVal (this, ((TokenTypeExpNot)typeExp).typeExp, tokenTypeBool);
5196 ilGen.Emit (typeExp, OpCodes.Ldc_I4_1);
5197 ilGen.Emit (typeExp, OpCodes.Xor);
5198 result.Pop (this, typeExp);
5199 return result;
5200 }
5201 if (typeExp is TokenTypeExpPar) {
5202 return GenerateFromTypeExp (val, ((TokenTypeExpPar)typeExp).typeExp);
5203 }
5204 if (typeExp is TokenTypeExpType) {
5205 CompValuTemp result = new CompValuTemp (tokenTypeBool, this);
5206 val.PushVal (this, typeExp);
5207 ilGen.Emit (typeExp, OpCodes.Isinst, ((TokenTypeExpType)typeExp).typeToken.ToSysType ());
5208 ilGen.Emit (typeExp, OpCodes.Ldnull);
5209 ilGen.Emit (typeExp, OpCodes.Ceq);
5210 ilGen.Emit (typeExp, OpCodes.Ldc_I4_1);
5211 ilGen.Emit (typeExp, OpCodes.Xor);
5212 result.Pop (this, typeExp);
5213 return result;
5214 }
5215 if (typeExp is TokenTypeExpUndef) {
5216 CompValuTemp result = new CompValuTemp (tokenTypeBool, this);
5217 val.PushVal (this, typeExp);
5218 ilGen.Emit (typeExp, OpCodes.Ldnull);
5219 ilGen.Emit (typeExp, OpCodes.Ceq);
5220 result.Pop (this, typeExp);
5221 return result;
5222 }
5223 throw new Exception ("unknown TokenTypeExp type " + typeExp.GetType ());
5224 }
5225
5226 /**
5227 * @brief Push the default (null) value for a particular variable
5228 * @param var = variable to get the default value for
5229 * @returns with value pushed on stack
5230 */
5231 public void PushVarDefaultValue (TokenDeclVar var)
5232 {
5233 PushDefaultValue (var.type);
5234 }
5235 public void PushDefaultValue (TokenType type)
5236 {
5237 if (type is TokenTypeArray) {
5238 PushXMRInst (); // instance
5239 ilGen.Emit (type, OpCodes.Newobj, xmrArrayConstructorInfo);
5240 return;
5241 }
5242 if (type is TokenTypeChar) {
5243 ilGen.Emit (type, OpCodes.Ldc_I4_0);
5244 return;
5245 }
5246 if (type is TokenTypeList) {
5247 ilGen.Emit (type, OpCodes.Ldc_I4_0);
5248 ilGen.Emit (type, OpCodes.Newarr, typeof (object));
5249 ilGen.Emit (type, OpCodes.Newobj, lslListConstructorInfo);
5250 return;
5251 }
5252 if (type is TokenTypeRot) {
5253 // Mono is tOO stOOpid to allow: ilGen.Emit (OpCodes.Ldsfld, zeroRotationFieldInfo);
5254 ilGen.Emit (type, OpCodes.Ldc_R8, ScriptBaseClass.ZERO_ROTATION.x);
5255 ilGen.Emit (type, OpCodes.Ldc_R8, ScriptBaseClass.ZERO_ROTATION.y);
5256 ilGen.Emit (type, OpCodes.Ldc_R8, ScriptBaseClass.ZERO_ROTATION.z);
5257 ilGen.Emit (type, OpCodes.Ldc_R8, ScriptBaseClass.ZERO_ROTATION.s);
5258 ilGen.Emit (type, OpCodes.Newobj, lslRotationConstructorInfo);
5259 return;
5260 }
5261 if ((type is TokenTypeKey) || (type is TokenTypeStr)) {
5262 ilGen.Emit (type, OpCodes.Ldstr, "");
5263 return;
5264 }
5265 if (type is TokenTypeVec) {
5266 // Mono is tOO stOOpid to allow: ilGen.Emit (OpCodes.Ldsfld, zeroVectorFieldInfo);
5267 ilGen.Emit (type, OpCodes.Ldc_R8, ScriptBaseClass.ZERO_VECTOR.x);
5268 ilGen.Emit (type, OpCodes.Ldc_R8, ScriptBaseClass.ZERO_VECTOR.y);
5269 ilGen.Emit (type, OpCodes.Ldc_R8, ScriptBaseClass.ZERO_VECTOR.z);
5270 ilGen.Emit (type, OpCodes.Newobj, lslVectorConstructorInfo);
5271 return;
5272 }
5273 if (type is TokenTypeInt) {
5274 ilGen.Emit (type, OpCodes.Ldc_I4_0);
5275 return;
5276 }
5277 if (type is TokenTypeFloat) {
5278 ilGen.Emit (type, OpCodes.Ldc_R4, 0.0f);
5279 return;
5280 }
5281
5282 /*
5283 * Default for 'object' type is 'undef'.
5284 * Likewise for script-defined classes and interfaces.
5285 */
5286 if ((type is TokenTypeObject) || (type is TokenTypeSDTypeClass) || (type is TokenTypeSDTypeInterface) || (type is TokenTypeExc)) {
5287 ilGen.Emit (type, OpCodes.Ldnull);
5288 return;
5289 }
5290
5291 /*
5292 * Void is pushed as the default return value of a void function.
5293 * So just push nothing as expected of void functions.
5294 */
5295 if (type is TokenTypeVoid) {
5296 return;
5297 }
5298
5299 /*
5300 * Default for 'delegate' type is 'undef'.
5301 */
5302 if (type is TokenTypeSDTypeDelegate) {
5303 ilGen.Emit (type, OpCodes.Ldnull);
5304 return;
5305 }
5306
5307 throw new Exception ("unknown type " + type.GetType ().ToString ());
5308 }
5309
5310 /**
5311 * @brief Determine if the expression has a constant boolean value
5312 * and if so, if the value is true or false.
5313 * @param expr = expression to evaluate
5314 * @returns true: expression is contant and has boolean value true
5315 * false: otherwise
5316 */
5317 private bool IsConstBoolExprTrue (CompValu expr)
5318 {
5319 bool constVal;
5320 return IsConstBoolExpr (expr, out constVal) && constVal;
5321 }
5322
5323 private bool IsConstBoolExpr (CompValu expr, out bool constVal)
5324 {
5325 if (expr is CompValuChar) {
5326 constVal = ((CompValuChar)expr).x != 0;
5327 return true;
5328 }
5329 if (expr is CompValuFloat) {
5330 constVal = ((CompValuFloat)expr).x != (double)0;
5331 return true;
5332 }
5333 if (expr is CompValuInteger) {
5334 constVal = ((CompValuInteger)expr).x != 0;
5335 return true;
5336 }
5337 if (expr is CompValuString) {
5338 string s = ((CompValuString)expr).x;
5339 constVal = s != "";
5340 if (constVal && (expr.type is TokenTypeKey)) {
5341 constVal = s != ScriptBaseClass.NULL_KEY;
5342 }
5343 return true;
5344 }
5345
5346 constVal = false;
5347 return false;
5348 }
5349
5350 /**
5351 * @brief Determine if the expression has a constant integer value
5352 * and if so, return the integer value.
5353 * @param expr = expression to evaluate
5354 * @returns true: expression is contant and has integer value
5355 * false: otherwise
5356 */
5357 private bool IsConstIntExpr (CompValu expr, out int constVal)
5358 {
5359 if (expr is CompValuChar) {
5360 constVal = (int)((CompValuChar)expr).x;
5361 return true;
5362 }
5363 if (expr is CompValuInteger) {
5364 constVal = ((CompValuInteger)expr).x;
5365 return true;
5366 }
5367
5368 constVal = 0;
5369 return false;
5370 }
5371
5372 /**
5373 * @brief Determine if the expression has a constant string value
5374 * and if so, return the string value.
5375 * @param expr = expression to evaluate
5376 * @returns true: expression is contant and has string value
5377 * false: otherwise
5378 */
5379 private bool IsConstStrExpr (CompValu expr, out string constVal)
5380 {
5381 if (expr is CompValuString) {
5382 constVal = ((CompValuString)expr).x;
5383 return true;
5384 }
5385 constVal = "";
5386 return false;
5387 }
5388
5389 /**
5390 * @brief create table of legal event handler prototypes.
5391 * This is used to make sure script's event handler declrations are valid.
5392 */
5393 private static VarDict CreateLegalEventHandlers ()
5394 {
5395 /*
5396 * Get handler prototypes with full argument lists.
5397 */
5398 VarDict leh = new InternalFuncDict (typeof (IEventHandlers), false);
5399
5400 /*
5401 * We want the scripts to be able to declare their handlers with
5402 * fewer arguments than the full argument lists. So define additional
5403 * prototypes with fewer arguments.
5404 */
5405 TokenDeclVar[] fullArgProtos = new TokenDeclVar[leh.Count];
5406 int i = 0;
5407 foreach (TokenDeclVar fap in leh) fullArgProtos[i++] = fap;
5408
5409 foreach (TokenDeclVar fap in fullArgProtos) {
5410 TokenArgDecl fal = fap.argDecl;
5411 int fullArgCount = fal.vars.Length;
5412 for (i = 0; i < fullArgCount; i ++) {
5413 TokenArgDecl shortArgList = new TokenArgDecl (null);
5414 for (int j = 0; j < i; j ++) {
5415 TokenDeclVar var = fal.vars[j];
5416 shortArgList.AddArg (var.type, var.name);
5417 }
5418 TokenDeclVar shortArgProto = new TokenDeclVar (null, null, null);
5419 shortArgProto.name = new TokenName (null, fap.GetSimpleName ());
5420 shortArgProto.retType = fap.retType;
5421 shortArgProto.argDecl = shortArgList;
5422 leh.AddEntry (shortArgProto);
5423 }
5424 }
5425
5426 return leh;
5427 }
5428
5429 /**
5430 * @brief Emit a call to CheckRun(), (voluntary multitasking switch)
5431 */
5432 public void EmitCallCheckRun (Token errorAt, bool stack)
5433 {
5434 if (curDeclFunc.IsFuncTrivial (this)) throw new Exception (curDeclFunc.fullName + " is supposed to be trivial");
5435 new CallLabel (this, errorAt); // jump here when stack restored
5436 PushXMRInst (); // instance
5437 ilGen.Emit (errorAt, OpCodes.Call, stack ? checkRunStackMethInfo : checkRunQuickMethInfo);
5438 openCallLabel = null;
5439 }
5440
5441 /**
5442 * @brief Emit code to push a callNo var on the stack.
5443 */
5444 public void GetCallNo (Token errorAt, ScriptMyLocal callNoVar)
5445 {
5446 ilGen.Emit (errorAt, OpCodes.Ldloc, callNoVar);
5447 //ilGen.Emit (errorAt, OpCodes.Ldloca, callNoVar);
5448 //ilGen.Emit (errorAt, OpCodes.Volatile);
5449 //ilGen.Emit (errorAt, OpCodes.Ldind_I4);
5450 }
5451 public void GetCallNo (Token errorAt, CompValu callNoVar)
5452 {
5453 callNoVar.PushVal (this, errorAt);
5454 //callNoVar.PushRef (this, errorAt);
5455 //ilGen.Emit (errorAt, OpCodes.Volatile);
5456 //ilGen.Emit (errorAt, OpCodes.Ldind_I4);
5457 }
5458
5459 /**
5460 * @brief Emit code to set a callNo var to a given constant.
5461 */
5462 public void SetCallNo (Token errorAt, ScriptMyLocal callNoVar, int val)
5463 {
5464 ilGen.Emit (errorAt, OpCodes.Ldc_I4, val);
5465 ilGen.Emit (errorAt, OpCodes.Stloc, callNoVar);
5466 //ilGen.Emit (errorAt, OpCodes.Ldloca, callNoVar);
5467 //ilGen.Emit (errorAt, OpCodes.Ldc_I4, val);
5468 //ilGen.Emit (errorAt, OpCodes.Volatile);
5469 //ilGen.Emit (errorAt, OpCodes.Stind_I4);
5470 }
5471 public void SetCallNo (Token errorAt, CompValu callNoVar, int val)
5472 {
5473 callNoVar.PopPre (this, errorAt);
5474 ilGen.Emit (errorAt, OpCodes.Ldc_I4, val);
5475 callNoVar.PopPost (this, errorAt);
5476 //callNoVar.PushRef (this, errorAt);
5477 //ilGen.Emit (errorAt, OpCodes.Ldc_I4, val);
5478 //ilGen.Emit (errorAt, OpCodes.Volatile);
5479 //ilGen.Emit (errorAt, OpCodes.Stind_I4);
5480 }
5481
5482 /**
5483 * @brief handle a unary operator, such as -x.
5484 */
5485 private CompValu UnOpGenerate (CompValu inRVal, Token opcode)
5486 {
5487 /*
5488 * - Negate
5489 */
5490 if (opcode is TokenKwSub) {
5491 if (inRVal.type is TokenTypeFloat) {
5492 CompValuTemp outRVal = new CompValuTemp (new TokenTypeFloat (opcode), this);
5493 inRVal.PushVal (this, opcode, outRVal.type); // push value to negate, make sure not LSL-boxed
5494 ilGen.Emit (opcode, OpCodes.Neg); // compute the negative
5495 outRVal.Pop (this, opcode); // pop into result
5496 return outRVal; // tell caller where we put it
5497 }
5498 if (inRVal.type is TokenTypeInt) {
5499 CompValuTemp outRVal = new CompValuTemp (new TokenTypeInt (opcode), this);
5500 inRVal.PushVal (this, opcode, outRVal.type); // push value to negate, make sure not LSL-boxed
5501 ilGen.Emit (opcode, OpCodes.Neg); // compute the negative
5502 outRVal.Pop (this, opcode); // pop into result
5503 return outRVal; // tell caller where we put it
5504 }
5505 if (inRVal.type is TokenTypeRot) {
5506 CompValuTemp outRVal = new CompValuTemp (inRVal.type, this);
5507 inRVal.PushVal (this, opcode); // push rotation, then call negate routine
5508 ilGen.Emit (opcode, OpCodes.Call, lslRotationNegateMethodInfo);
5509 outRVal.Pop (this, opcode); // pop into result
5510 return outRVal; // tell caller where we put it
5511 }
5512 if (inRVal.type is TokenTypeVec) {
5513 CompValuTemp outRVal = new CompValuTemp (inRVal.type, this);
5514 inRVal.PushVal (this, opcode); // push vector, then call negate routine
5515 ilGen.Emit (opcode, OpCodes.Call, lslVectorNegateMethodInfo);
5516 outRVal.Pop (this, opcode); // pop into result
5517 return outRVal; // tell caller where we put it
5518 }
5519 ErrorMsg (opcode, "can't negate a " + inRVal.type.ToString ());
5520 return inRVal;
5521 }
5522
5523 /*
5524 * ~ Complement (bitwise integer)
5525 */
5526 if (opcode is TokenKwTilde) {
5527 if (inRVal.type is TokenTypeInt) {
5528 CompValuTemp outRVal = new CompValuTemp (new TokenTypeInt (opcode), this);
5529 inRVal.PushVal (this, opcode, outRVal.type); // push value to negate, make sure not LSL-boxed
5530 ilGen.Emit (opcode, OpCodes.Not); // compute the complement
5531 outRVal.Pop (this, opcode); // pop into result
5532 return outRVal; // tell caller where we put it
5533 }
5534 ErrorMsg (opcode, "can't complement a " + inRVal.type.ToString ());
5535 return inRVal;
5536 }
5537
5538 /*
5539 * ! Not (boolean)
5540 *
5541 * We stuff the 0/1 result in an int because I've seen x+!y in scripts
5542 * and we don't want to have to create tables to handle int+bool and
5543 * everything like that.
5544 */
5545 if (opcode is TokenKwExclam) {
5546 CompValuTemp outRVal = new CompValuTemp (new TokenTypeInt (opcode), this);
5547 inRVal.PushVal (this, opcode, tokenTypeBool); // anything converts to boolean
5548 ilGen.Emit (opcode, OpCodes.Ldc_I4_1); // then XOR with 1 to flip it
5549 ilGen.Emit (opcode, OpCodes.Xor);
5550 outRVal.Pop (this, opcode); // pop into result
5551 return outRVal; // tell caller where we put it
5552 }
5553
5554 throw new Exception ("unhandled opcode " + opcode.ToString ());
5555 }
5556
5557 /**
5558 * @brief This is called while trying to compute the value of constant initializers.
5559 * It is passed a name and that name is looked up in the constant tables.
5560 */
5561 private TokenRVal LookupInitConstants (TokenRVal rVal, ref bool didOne)
5562 {
5563 /*
5564 * If it is a static field of a script-defined type, look it up and hopefully we find a constant there.
5565 */
5566 TokenDeclVar gblVar;
5567 if (rVal is TokenLValSField) {
5568 TokenLValSField lvsf = (TokenLValSField)rVal;
5569 if (lvsf.baseType is TokenTypeSDTypeClass) {
5570 TokenDeclSDTypeClass sdtClass = ((TokenTypeSDTypeClass)lvsf.baseType).decl;
5571 gblVar = sdtClass.members.FindExact (lvsf.fieldName.val, null);
5572 if (gblVar != null) {
5573 if (gblVar.constant && (gblVar.init is TokenRValConst)) {
5574 didOne = true;
5575 return gblVar.init;
5576 }
5577 }
5578 }
5579 return rVal;
5580 }
5581
5582 /*
5583 * Only other thing we handle is stand-alone names.
5584 */
5585 if (!(rVal is TokenLValName)) return rVal;
5586 string name = ((TokenLValName)rVal).name.val;
5587
5588 /*
5589 * If we are doing the initializations for a script-defined type,
5590 * look for the constant among the fields for that type.
5591 */
5592 if (currentSDTClass != null) {
5593 gblVar = currentSDTClass.members.FindExact (name, null);
5594 if (gblVar != null) {
5595 if (gblVar.constant && (gblVar.init is TokenRValConst)) {
5596 didOne = true;
5597 return gblVar.init;
5598 }
5599 return rVal;
5600 }
5601 }
5602
5603 /*
5604 * Look it up as a script-defined global variable.
5605 * Then if the variable is defined as a constant and has a constant value,
5606 * we are successful. If it is defined as something else, return failure.
5607 */
5608 gblVar = tokenScript.variablesStack.FindExact (name, null);
5609 if (gblVar != null) {
5610 if (gblVar.constant && (gblVar.init is TokenRValConst)) {
5611 didOne = true;
5612 return gblVar.init;
5613 }
5614 return rVal;
5615 }
5616
5617 /*
5618 * Maybe it is a built-in symbolic constant.
5619 */
5620 ScriptConst scriptConst = ScriptConst.Lookup (name);
5621 if (scriptConst != null) {
5622 rVal = CompValuConst2RValConst (scriptConst.rVal, rVal);
5623 if (rVal is TokenRValConst) {
5624 didOne = true;
5625 return rVal;
5626 }
5627 }
5628
5629 /*
5630 * Don't know what it is, return failure.
5631 */
5632 return rVal;
5633 }
5634
5635 /**
5636 * @brief This is called while trying to compute the value of constant expressions.
5637 * It is passed a name and that name is looked up in the constant tables.
5638 */
5639 private TokenRVal LookupBodyConstants (TokenRVal rVal, ref bool didOne)
5640 {
5641 /*
5642 * If it is a static field of a script-defined type, look it up and hopefully we find a constant there.
5643 */
5644 TokenDeclVar gblVar;
5645 if (rVal is TokenLValSField) {
5646 TokenLValSField lvsf = (TokenLValSField)rVal;
5647 if (lvsf.baseType is TokenTypeSDTypeClass) {
5648 TokenDeclSDTypeClass sdtClass = ((TokenTypeSDTypeClass)lvsf.baseType).decl;
5649 gblVar = sdtClass.members.FindExact (lvsf.fieldName.val, null);
5650 if ((gblVar != null) && gblVar.constant && (gblVar.init is TokenRValConst)) {
5651 didOne = true;
5652 return gblVar.init;
5653 }
5654 }
5655 return rVal;
5656 }
5657
5658 /*
5659 * Only other thing we handle is stand-alone names.
5660 */
5661 if (!(rVal is TokenLValName)) return rVal;
5662 string name = ((TokenLValName)rVal).name.val;
5663
5664 /*
5665 * Scan through the variable stack and hopefully we find a constant there.
5666 * But we stop as soon as we get a match because that's what the script is referring to.
5667 */
5668 CompValu val;
5669 for (VarDict vars = ((TokenLValName)rVal).stack; vars != null; vars = vars.outerVarDict) {
5670 TokenDeclVar var = vars.FindExact (name, null);
5671 if (var != null) {
5672 val = var.location;
5673 goto foundit;
5674 }
5675
5676 TokenDeclSDTypeClass baseClass = vars.thisClass;
5677 if (baseClass != null) {
5678 while ((baseClass = baseClass.extends) != null) {
5679 var = baseClass.members.FindExact (name, null);
5680 if (var != null) {
5681 val = var.location;
5682 goto foundit;
5683 }
5684 }
5685 }
5686 }
5687
5688 /*
5689 * Maybe it is a built-in symbolic constant.
5690 */
5691 ScriptConst scriptConst = ScriptConst.Lookup (name);
5692 if (scriptConst != null) {
5693 val = scriptConst.rVal;
5694 goto foundit;
5695 }
5696
5697 /*
5698 * Don't know what it is, return failure.
5699 */
5700 return rVal;
5701
5702 /*
5703 * Found a CompValu. If it's a simple constant, then use it.
5704 * Otherwise tell caller we failed to simplify.
5705 */
5706 foundit:
5707 rVal = CompValuConst2RValConst (val, rVal);
5708 if (rVal is TokenRValConst) {
5709 didOne = true;
5710 }
5711 return rVal;
5712 }
5713
5714 private static TokenRVal CompValuConst2RValConst (CompValu val, TokenRVal rVal)
5715 {
5716 if (val is CompValuChar) rVal = new TokenRValConst (rVal, ((CompValuChar)val).x);
5717 if (val is CompValuFloat) rVal = new TokenRValConst (rVal, ((CompValuFloat)val).x);
5718 if (val is CompValuInteger) rVal = new TokenRValConst (rVal, ((CompValuInteger)val).x);
5719 if (val is CompValuString) rVal = new TokenRValConst (rVal, ((CompValuString)val).x);
5720 return rVal;
5721 }
5722
5723 /**
5724 * @brief Generate code to push XMRInstanceSuperType pointer on stack.
5725 */
5726 public void PushXMRInst ()
5727 {
5728 if (instancePointer == null) {
5729 ilGen.Emit (null, OpCodes.Ldarg_0);
5730 } else {
5731 ilGen.Emit (null, OpCodes.Ldloc, instancePointer);
5732 }
5733 }
5734
5735 /**
5736 * @returns true: Ldarg_0 gives XMRSDTypeClObj pointer
5737 * - this is the case for instance methods
5738 * false: Ldarg_0 gives XMR_Instance pointer
5739 * - this is the case for both global functions and static methods
5740 */
5741 public bool IsSDTInstMethod ()
5742 {
5743 return (curDeclFunc.sdtClass != null) &&
5744 ((curDeclFunc.sdtFlags & ScriptReduce.SDT_STATIC) == 0);
5745 }
5746
5747 /**
5748 * @brief Look for a simply named function or variable (not a field or method)
5749 */
5750 public TokenDeclVar FindNamedVar (TokenLValName lValName, TokenType[] argsig)
5751 {
5752 /*
5753 * Look in variable stack for the given name.
5754 */
5755 for (VarDict vars = lValName.stack; vars != null; vars = vars.outerVarDict) {
5756
5757 // first look for it possibly with an argument signature
5758 // so we pick the correct overloaded method
5759 TokenDeclVar var = FindSingleMember (vars, lValName.name, argsig);
5760 if (var != null) return var;
5761
5762 // if that fails, try it without the argument signature.
5763 // delegates get entered like any other variable, ie,
5764 // no signature on their name.
5765 if (argsig != null) {
5766 var = FindSingleMember (vars, lValName.name, null);
5767 if (var != null) return var;
5768 }
5769
5770 // if this is the frame for some class members, try searching base class members too
5771 TokenDeclSDTypeClass baseClass = vars.thisClass;
5772 if (baseClass != null) {
5773 while ((baseClass = baseClass.extends) != null) {
5774 var = FindSingleMember (baseClass.members, lValName.name, argsig);
5775 if (var != null) return var;
5776 if (argsig != null) {
5777 var = FindSingleMember (baseClass.members, lValName.name, null);
5778 if (var != null) return var;
5779 }
5780 }
5781 }
5782 }
5783
5784 /*
5785 * If not found, try one of the built-in constants or functions.
5786 */
5787 if (argsig == null) {
5788 ScriptConst scriptConst = ScriptConst.Lookup (lValName.name.val);
5789 if (scriptConst != null) {
5790 TokenDeclVar var = new TokenDeclVar (lValName.name, null, tokenScript);
5791 var.name = lValName.name;
5792 var.type = scriptConst.rVal.type;
5793 var.location = scriptConst.rVal;
5794 return var;
5795 }
5796 } else {
5797 TokenDeclVar inline = FindSingleMember (TokenDeclInline.inlineFunctions, lValName.name, argsig);
5798 if (inline != null) return inline;
5799 }
5800
5801 return null;
5802 }
5803
5804
5805 /**
5806 * @brief Find a member of an interface.
5807 * @param sdType = interface type
5808 * @param name = name of member to find
5809 * @param argsig = null: field/property; else: script-visible method argument types
5810 * @param baseRVal = pointer to interface object
5811 * @returns null: no such member
5812 * else: pointer to member
5813 * baseRVal = possibly modified to point to type-casted interface object
5814 */
5815 private TokenDeclVar FindInterfaceMember (TokenTypeSDTypeInterface sdtType, TokenName name, TokenType[] argsig, ref CompValu baseRVal)
5816 {
5817 TokenDeclSDTypeInterface sdtDecl = sdtType.decl;
5818 TokenDeclSDTypeInterface impl;
5819 TokenDeclVar declVar = sdtDecl.FindIFaceMember (this, name, argsig, out impl);
5820 if ((declVar != null) && (impl != sdtDecl)) {
5821
5822 /*
5823 * Accessing a method or propterty of another interface that the primary interface says it implements.
5824 * In this case, we have to cast from the primary interface to that secondary interface.
5825 *
5826 * interface IEnumerable {
5827 * IEnumerator GetEnumerator ();
5828 * }
5829 * interface ICountable : IEnumerable {
5830 * integer GetCount ();
5831 * }
5832 * class List : ICountable {
5833 * public GetCount () : ICountable { ... }
5834 * public GetEnumerator () : IEnumerable { ... }
5835 * }
5836 *
5837 * ICountable aList = new List ();
5838 * IEnumerator anEnumer = aList.GetEnumerator (); << we are here
5839 * << baseRVal = aList
5840 * << sdtDecl = ICountable
5841 * << impl = IEnumerable
5842 * << name = GetEnumerator
5843 * << argsig = ()
5844 * So we have to cast aList from ICountable to IEnumerable.
5845 */
5846
5847 // make type token for the secondary interface type
5848 TokenType subIntfType = impl.MakeRefToken (name);
5849
5850 // make a temp variable of the secondary interface type
5851 CompValuTemp castBase = new CompValuTemp (subIntfType, this);
5852
5853 // output code to cast from the primary interface to the secondary interface
5854 // this is 2 basic steps:
5855 // 1) cast from primary interface object -> class object
5856 // ...gets it from interfaceObject.delegateArray[0].Target
5857 // 2) cast from class object -> secondary interface object
5858 // ...gets it from classObject.sdtcITable[interfaceIndex]
5859 baseRVal.PushVal (this, name, subIntfType);
5860
5861 // save result of casting in temp
5862 castBase.Pop (this, name);
5863
5864 // return temp reference
5865 baseRVal = castBase;
5866 }
5867
5868 return declVar;
5869 }
5870
5871 /**
5872 * @brief Find a member of a script-defined type class.
5873 * @param sdtType = reference to class declaration
5874 * @param name = name of member to find
5875 * @param argsig = argument signature used to select among overloaded members
5876 * @returns null: no such member found
5877 * else: the member found
5878 */
5879 public TokenDeclVar FindThisMember (TokenTypeSDTypeClass sdtType, TokenName name, TokenType[] argsig)
5880 {
5881 return FindThisMember (sdtType.decl, name, argsig);
5882 }
5883 public TokenDeclVar FindThisMember (TokenDeclSDTypeClass sdtDecl, TokenName name, TokenType[] argsig)
5884 {
5885 for (TokenDeclSDTypeClass sdtd = sdtDecl; sdtd != null; sdtd = sdtd.extends) {
5886 TokenDeclVar declVar = FindSingleMember (sdtd.members, name, argsig);
5887 if (declVar != null) return declVar;
5888 }
5889 return null;
5890 }
5891
5892 /**
5893 * @brief Look for a single member that matches the given name and argument signature
5894 * @param where = which dictionary to look in
5895 * @param name = basic name of the field or method, eg, "Printable"
5896 * @param argsig = argument types the method is being called with, eg, "(string)"
5897 * or null to find a field
5898 * @returns null: no member found
5899 * else: the member found
5900 */
5901 public TokenDeclVar FindSingleMember (VarDict where, TokenName name, TokenType[] argsig)
5902 {
5903 TokenDeclVar[] members = where.FindCallables (name.val, argsig);
5904 if (members == null) return null;
5905 if (members.Length > 1) {
5906 ErrorMsg (name, "more than one matching member");
5907 for (int i = 0; i < members.Length; i ++) {
5908 ErrorMsg (members[i], " " + members[i].argDecl.GetArgSig ());
5909 }
5910 }
5911 return members[0];
5912 }
5913
5914 /**
5915 * @brief Find an exact function name and argument signature match.
5916 * Also verify that the return value type is an exact match.
5917 * @param where = which method dictionary to look in
5918 * @param name = basic name of the method, eg, "Printable"
5919 * @param ret = expected return value type
5920 * @param argsig = argument types the method is being called with, eg, "(string)"
5921 * @returns null: no exact match found
5922 * else: the matching function
5923 */
5924 private TokenDeclVar FindExactWithRet (VarDict where, TokenName name, TokenType ret, TokenType[] argsig)
5925 {
5926 TokenDeclVar func = where.FindExact (name.val, argsig);
5927 if ((func != null) && (func.retType.ToString () != ret.ToString ())) {
5928 ErrorMsg (name, "return type mismatch, have " + func.retType.ToString () + ", expect " + ret.ToString ());
5929 }
5930 if (func != null) CheckAccess (func, name);
5931 return func;
5932 }
5933
5934 /**
5935 * @brief Check the private/protected/public access flags of a member.
5936 */
5937 private void CheckAccess (TokenDeclVar var, Token errorAt)
5938 {
5939 TokenDeclSDType nested;
5940 TokenDeclSDType definedBy = var.sdtClass;
5941 TokenDeclSDType accessedBy = curDeclFunc.sdtClass;
5942
5943 /*******************************\
5944 * Check member-level access *
5945 \*******************************/
5946
5947 /*
5948 * Note that if accessedBy is null, ie, accessing from global function (or event handlers),
5949 * anything tagged as SDT_PRIVATE or SDT_PROTECTED will fail.
5950 */
5951
5952 /*
5953 * Private means accessed by the class that defined the member or accessed by a nested class
5954 * of the class that defined the member.
5955 */
5956 if ((var.sdtFlags & ScriptReduce.SDT_PRIVATE) != 0) {
5957 for (nested = accessedBy; nested != null; nested = nested.outerSDType) {
5958 if (nested == definedBy) goto acc1ok;
5959 }
5960 ErrorMsg (errorAt, "private member " + var.fullName + " cannot be accessed by " + curDeclFunc.fullName);
5961 return;
5962 }
5963
5964 /*
5965 * Protected means:
5966 * If being accessed by an inner class, the inner class has access to it if the inner class derives
5967 * from the declaring class. It also has access to it if an outer class derives from the declaring
5968 * class.
5969 */
5970 if ((var.sdtFlags & ScriptReduce.SDT_PROTECTED) != 0) {
5971 for (nested = accessedBy; nested != null; nested = nested.outerSDType) {
5972 for (TokenDeclSDType rootward = nested; rootward != null; rootward = rootward.extends) {
5973 if (rootward == definedBy) goto acc1ok;
5974 }
5975 }
5976 ErrorMsg (errorAt, "protected member " + var.fullName + " cannot be accessed by " + curDeclFunc.fullName);
5977 return;
5978 }
5979 acc1ok:
5980
5981 /******************************\
5982 * Check class-level access *
5983 \******************************/
5984
5985 /*
5986 * If being accessed by same or inner class than where defined, it is ok.
5987 *
5988 * class DefiningClass {
5989 * varBeingAccessed;
5990 * .
5991 * .
5992 * .
5993 * class AccessingClass {
5994 * functionDoingAccess() { }
5995 * }
5996 * .
5997 * .
5998 * .
5999 * }
6000 */
6001 nested = accessedBy;
6002 while (true) {
6003 if (nested == definedBy) return;
6004 if (nested == null) break;
6005 nested = (TokenDeclSDTypeClass)nested.outerSDType;
6006 }
6007
6008 /*
6009 * It is being accessed by an outer class than where defined,
6010 * check for a 'private' or 'protected' class tag that blocks.
6011 */
6012 do {
6013
6014 /*
6015 * If the field's class is defined directly inside the accessing class,
6016 * access is allowed regardless of class-level private or protected tags.
6017 *
6018 * class AccessingClass {
6019 * functionDoingAccess() { }
6020 * class DefiningClass {
6021 * varBeingAccessed;
6022 * }
6023 * }
6024 */
6025 if (definedBy.outerSDType == accessedBy) return;
6026
6027 /*
6028 * If the field's class is defined two or more levels inside the accessing class,
6029 * access is denied if the defining class is tagged private.
6030 *
6031 * class AccessingClass {
6032 * functionDoingAccess() { }
6033 * .
6034 * .
6035 * .
6036 * class IntermediateClass {
6037 * private class DefiningClass {
6038 * varBeingAccessed;
6039 * }
6040 * }
6041 * .
6042 * .
6043 * .
6044 * }
6045 */
6046 if ((definedBy.accessLevel & ScriptReduce.SDT_PRIVATE) != 0) {
6047 ErrorMsg (errorAt, "member " + var.fullName + " cannot be accessed by " + curDeclFunc.fullName +
6048 " because of private class " + definedBy.longName.val);
6049 return;
6050 }
6051
6052 /*
6053 * Likewise, if DefiningClass is tagged protected, the AccessingClass must derive from the
6054 * IntermediateClass or access is denied.
6055 */
6056 if ((definedBy.accessLevel & ScriptReduce.SDT_PROTECTED) != 0) {
6057 for (TokenDeclSDType extends = accessedBy; extends != definedBy.outerSDType; extends = extends.extends) {
6058 if (extends == null) {
6059 ErrorMsg (errorAt, "member " + var.fullName + " cannot be accessed by " + curDeclFunc.fullName +
6060 " because of protected class " + definedBy.longName.val);
6061 return;
6062 }
6063 }
6064 }
6065
6066 /*
6067 * Check next outer level.
6068 */
6069 definedBy = definedBy.outerSDType;
6070 } while (definedBy != null);
6071 }
6072
6073 /**
6074 * @brief Convert a list of argument types to printable string, eg, "(list,string,float,integer)"
6075 * If given a null, return "" indicating it is a field not a method
6076 */
6077 public static string ArgSigString (TokenType[] argsig)
6078 {
6079 if (argsig == null) return "";
6080 StringBuilder sb = new StringBuilder ("(");
6081 for (int i = 0; i < argsig.Length; i ++) {
6082 if (i > 0) sb.Append (",");
6083 sb.Append (argsig[i].ToString ());
6084 }
6085 sb.Append (")");
6086 return sb.ToString ();
6087 }
6088
6089 /**
6090 * @brief output error message and remember that we did
6091 */
6092 public void ErrorMsg (Token token, string message)
6093 {
6094 if ((token == null) || (token.emsg == null)) token = errorMessageToken;
6095 if (!youveAnError || (token.file != lastErrorFile) || (token.line > lastErrorLine)) {
6096 token.ErrorMsg (message);
6097 youveAnError = true;
6098 lastErrorFile = token.file;
6099 lastErrorLine = token.line;
6100 }
6101 }
6102
6103 /**
6104 * @brief Find a private static method.
6105 * @param owner = class the method is part of
6106 * @param name = name of method to find
6107 * @param args = array of argument types
6108 * @returns pointer to method
6109 */
6110 public static MethodInfo GetStaticMethod (Type owner, string name, Type[] args)
6111 {
6112 MethodInfo mi = owner.GetMethod (name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, args, null);
6113 if (mi == null) {
6114 throw new Exception ("undefined method " + owner.ToString () + "." + name);
6115 }
6116 return mi;
6117 }
6118
6119 // http://wiki.secondlife.com/wiki/Rotation 'negate a rotation' says just negate .s component
6120 // but http://wiki.secondlife.com/wiki/LSL_Language_Test (lslangtest1.lsl) says negate all 4 values
6121 public static LSL_Rotation LSLRotationNegate (LSL_Rotation r) { return new LSL_Rotation (-r.x,-r.y,-r.z,-r.s); }
6122 public static LSL_Vector LSLVectorNegate (LSL_Vector v) { return -v; }
6123 public static string CatchExcToStr (Exception exc) { return exc.ToString(); }
6124 //public static void ConsoleWrite (string str) { Console.Write(str); }
6125
6126 /**
6127 * @brief Defines an internal label that is used as a target for 'break' and 'continue' statements.
6128 */
6129 private class BreakContTarg {
6130 public bool used;
6131 public ScriptMyLabel label;
6132 public TokenStmtBlock block;
6133
6134 public BreakContTarg (ScriptCodeGen scg, string name) {
6135 used = false; // assume it isn't referenced at all
6136 label = scg.ilGen.DefineLabel (name); // label that the break/continue jumps to
6137 block = scg.curStmtBlock; // { ... } that the break/continue label is in
6138 }
6139 }
6140 }
6141
6142 /**
6143 * @brief Marker interface indicates an exception that can't be caught by a script-level try/catch.
6144 */
6145 public interface IXMRUncatchable { }
6146
6147 /**
6148 * @brief Thrown by a script when it attempts to change to an undefined state.
6149 * These can be detected at compile time but the moron XEngine compiles
6150 * such things, so we compile them as runtime errors.
6151 */
6152 [SerializableAttribute]
6153 public class ScriptUndefinedStateException : Exception, ISerializable {
6154 public string stateName;
6155 public ScriptUndefinedStateException (string stateName) : base ("undefined state " + stateName) {
6156 this.stateName = stateName;
6157 }
6158 protected ScriptUndefinedStateException (SerializationInfo info, StreamingContext context) : base (info, context)
6159 { }
6160 }
6161
6162 /**
6163 * @brief Created by a throw statement.
6164 */
6165 [SerializableAttribute]
6166 public class ScriptThrownException : Exception, ISerializable {
6167 public object thrown;
6168
6169 /**
6170 * @brief Called by a throw statement to wrap the object in a unique
6171 * tag that capable of capturing a stack trace. Script can
6172 * unwrap it by calling xmrExceptionThrownValue().
6173 */
6174 public static Exception Wrap (object thrown)
6175 {
6176 return new ScriptThrownException (thrown);
6177 }
6178 private ScriptThrownException (object thrown) : base (thrown.ToString ())
6179 {
6180 this.thrown = thrown;
6181 }
6182
6183 /**
6184 * @brief Used by serialization/deserialization.
6185 */
6186 protected ScriptThrownException (SerializationInfo info, StreamingContext context) : base (info, context)
6187 { }
6188 }
6189
6190 /**
6191 * @brief Thrown by a script when it attempts to change to a defined state.
6192 */
6193 [SerializableAttribute]
6194 public class ScriptChangeStateException : Exception, ISerializable, IXMRUncatchable {
6195 public int newState;
6196 public ScriptChangeStateException (int newState) {
6197 this.newState = newState;
6198 }
6199 protected ScriptChangeStateException (SerializationInfo info, StreamingContext context) : base (info, context)
6200 { }
6201 }
6202
6203 /**
6204 * @brief We are restoring to the body of a catch { } so we need to
6205 * wrap the original exception in an outer exception, so the
6206 * system won't try to refill the stack trace.
6207 *
6208 * We don't mark this one serializable as it should never get
6209 * serialized out. It only lives from the throw to the very
6210 * beginning of the catch handler where it is promptly unwrapped.
6211 * No CheckRun() call can possibly intervene.
6212 */
6213 public class ScriptRestoreCatchException : Exception {
6214
6215 // old code uses these
6216 private object e;
6217 public ScriptRestoreCatchException (object e) {
6218 this.e = e;
6219 }
6220 public static object Unwrap (object o)
6221 {
6222 if (o is IXMRUncatchable) return null;
6223 if (o is ScriptRestoreCatchException) return ((ScriptRestoreCatchException)o).e;
6224 return o;
6225 }
6226
6227 // new code uses these
6228 private Exception ee;
6229 public ScriptRestoreCatchException (Exception ee) {
6230 this.ee = ee;
6231 }
6232 public static Exception Unwrap (Exception oo)
6233 {
6234 if (oo is IXMRUncatchable) return null;
6235 if (oo is ScriptRestoreCatchException) return ((ScriptRestoreCatchException)oo).ee;
6236 return oo;
6237 }
6238 }
6239
6240 [SerializableAttribute]
6241 public class ScriptBadCallNoException : Exception {
6242 public ScriptBadCallNoException (int callNo) : base ("bad callNo " + callNo) { }
6243 protected ScriptBadCallNoException (SerializationInfo info, StreamingContext context) : base (info, context)
6244 { }
6245 }
6246
6247 public class CVVMismatchException : Exception {
6248 public int oldcvv;
6249 public int newcvv;
6250
6251 public CVVMismatchException (int oldcvv, int newcvv) : base ("object version is " + oldcvv.ToString () +
6252 " but accept only " + newcvv.ToString ())
6253 {
6254 this.oldcvv = oldcvv;
6255 this.newcvv = newcvv;
6256 }
6257 }
6258}