compiledEval.cpp 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2013 GarageGames, LLC
  3. // Copyright (c) 2015 Faust Logic, Inc.
  4. // Copyright (c) 2021 TGEMIT Authors & Contributors
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to
  8. // deal in the Software without restriction, including without limitation the
  9. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  10. // sell copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  21. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  22. // IN THE SOFTWARE.
  23. //-----------------------------------------------------------------------------
  24. #include "platform/platform.h"
  25. #include "ast.h"
  26. #include "compiler.h"
  27. #include "core/strings/stringUnit.h"
  28. #include "console/consoleInternal.h"
  29. #include "console/simBase.h"
  30. #include "sim/netStringTable.h"
  31. #include "console/stringStack.h"
  32. #include "util/messaging/message.h"
  33. #include "core/frameAllocator.h"
  34. #include "console/returnBuffer.h"
  35. #include "console/consoleValueStack.h"
  36. #include "console/telnetDebugger.h"
  37. #ifndef TORQUE_TGB_ONLY
  38. #include "materials/materialDefinition.h"
  39. #endif
  40. using namespace Compiler;
  41. enum EvalConstants
  42. {
  43. MaxStackSize = 1024,
  44. FieldBufferSizeString = 2048,
  45. FieldBufferSizeNumeric = 128,
  46. ConcatBufferInitialSize = 8192,
  47. MethodOnComponent = -2
  48. };
  49. /// Frame data for a foreach/foreach$ loop.
  50. struct IterStackRecord
  51. {
  52. /// If true, this is a foreach$ loop; if not, it's a foreach loop.
  53. bool mIsStringIter;
  54. /// True if the variable referenced is a global
  55. bool mIsGlobalVariable;
  56. union
  57. {
  58. /// The iterator variable if we are a global variable
  59. Dictionary::Entry* mVariable;
  60. /// The register variable if we are a local variable
  61. S32 mRegister;
  62. } mVar;
  63. /// Information for an object iterator loop.
  64. struct ObjectPos
  65. {
  66. /// The set being iterated over.
  67. SimSet* mSet;
  68. /// Current index in the set.
  69. U32 mIndex;
  70. };
  71. /// Information for a string iterator loop.
  72. struct StringPos
  73. {
  74. /// The raw string data on the string stack.
  75. const char* mString;
  76. /// Current parsing position.
  77. U32 mIndex;
  78. };
  79. union
  80. {
  81. ObjectPos mObj;
  82. StringPos mStr;
  83. } mData;
  84. };
  85. ConsoleValueStack<4096> gCallStack;
  86. StringStack STR;
  87. IterStackRecord iterStack[MaxStackSize];
  88. U32 _ITER = 0; ///< Stack pointer for iterStack.
  89. ConsoleValue stack[MaxStackSize];
  90. S32 _STK = 0;
  91. ReturnBuffer retBuffer;
  92. char *getReturnBuffer(U32 bufferSize)
  93. {
  94. return retBuffer.getBuffer(bufferSize);
  95. }
  96. const char* tsconcat(const char* strA, const char* strB, S32& outputLen)
  97. {
  98. S32 lenA = dStrlen(strA);
  99. S32 lenB = dStrlen(strB);
  100. S32 len = lenA + lenB + 1;
  101. char* concatBuffer = (char*)dMalloc(len);
  102. concatBuffer[len - 1] = '\0';
  103. memcpy(concatBuffer, strA, lenA);
  104. memcpy(concatBuffer + lenA, strB, lenB);
  105. outputLen = lenA + lenB;
  106. return concatBuffer;
  107. }
  108. namespace Con
  109. {
  110. // Current script file name and root, these are registered as
  111. // console variables.
  112. extern StringTableEntry gCurrentFile;
  113. extern StringTableEntry gCurrentRoot;
  114. extern S32 gObjectCopyFailures;
  115. }
  116. namespace Con
  117. {
  118. const char *getNamespaceList(Namespace *ns)
  119. {
  120. U32 size = 1;
  121. Namespace * walk;
  122. for (walk = ns; walk; walk = walk->mParent)
  123. size += dStrlen(walk->mName) + 4;
  124. char *ret = getReturnBuffer(size);
  125. ret[0] = 0;
  126. for (walk = ns; walk; walk = walk->mParent)
  127. {
  128. dStrcat(ret, walk->mName, size);
  129. if (walk->mParent)
  130. dStrcat(ret, " -> ", size);
  131. }
  132. return ret;
  133. }
  134. }
  135. static void getFieldComponent(SimObject* object, StringTableEntry field, const char* array, StringTableEntry subField, char val[], S32 currentLocalRegister)
  136. {
  137. const char* prevVal = NULL;
  138. if (object && field)
  139. prevVal = object->getDataField(field, array);
  140. else if (currentLocalRegister != -1)
  141. prevVal = Script::gEvalState.getLocalStringVariable(currentLocalRegister);
  142. else if (Script::gEvalState.currentVariable)
  143. prevVal = Script::gEvalState.getStringVariable();
  144. // Make sure we got a value.
  145. if (prevVal && *prevVal)
  146. {
  147. static const StringTableEntry xyzw[] =
  148. {
  149. StringTable->insert("x"),
  150. StringTable->insert("y"),
  151. StringTable->insert("z"),
  152. StringTable->insert("w")
  153. };
  154. static const StringTableEntry rgba[] =
  155. {
  156. StringTable->insert("r"),
  157. StringTable->insert("g"),
  158. StringTable->insert("b"),
  159. StringTable->insert("a")
  160. };
  161. // Translate xyzw and rgba into the indexed component
  162. // of the variable or field.
  163. if (subField == xyzw[0] || subField == rgba[0])
  164. dStrcpy(val, StringUnit::getUnit(prevVal, 0, " \t\n"), 128);
  165. else if (subField == xyzw[1] || subField == rgba[1])
  166. dStrcpy(val, StringUnit::getUnit(prevVal, 1, " \t\n"), 128);
  167. else if (subField == xyzw[2] || subField == rgba[2])
  168. dStrcpy(val, StringUnit::getUnit(prevVal, 2, " \t\n"), 128);
  169. else if (subField == xyzw[3] || subField == rgba[3])
  170. dStrcpy(val, StringUnit::getUnit(prevVal, 3, " \t\n"), 128);
  171. else
  172. val[0] = 0;
  173. }
  174. else
  175. val[0] = 0;
  176. }
  177. static void setFieldComponent(SimObject* object, StringTableEntry field, const char* array, StringTableEntry subField, S32 currentLocalRegister)
  178. {
  179. // Copy the current string value
  180. char strValue[1024];
  181. dStrncpy(strValue, stack[_STK].getString(), 1024);
  182. char val[1024] = "";
  183. const char* prevVal = NULL;
  184. if (object && field)
  185. prevVal = object->getDataField(field, array);
  186. else if (currentLocalRegister != -1)
  187. prevVal = Script::gEvalState.getLocalStringVariable(currentLocalRegister);
  188. // Set the value on a variable.
  189. else if (Script::gEvalState.currentVariable)
  190. prevVal = Script::gEvalState.getStringVariable();
  191. // Ensure that the variable has a value
  192. if (!prevVal)
  193. return;
  194. static const StringTableEntry xyzw[] =
  195. {
  196. StringTable->insert("x"),
  197. StringTable->insert("y"),
  198. StringTable->insert("z"),
  199. StringTable->insert("w")
  200. };
  201. static const StringTableEntry rgba[] =
  202. {
  203. StringTable->insert("r"),
  204. StringTable->insert("g"),
  205. StringTable->insert("b"),
  206. StringTable->insert("a")
  207. };
  208. // Insert the value into the specified
  209. // component of the string.
  210. if (subField == xyzw[0] || subField == rgba[0])
  211. dStrcpy(val, StringUnit::setUnit(prevVal, 0, strValue, " \t\n"), 128);
  212. else if (subField == xyzw[1] || subField == rgba[1])
  213. dStrcpy(val, StringUnit::setUnit(prevVal, 1, strValue, " \t\n"), 128);
  214. else if (subField == xyzw[2] || subField == rgba[2])
  215. dStrcpy(val, StringUnit::setUnit(prevVal, 2, strValue, " \t\n"), 128);
  216. else if (subField == xyzw[3] || subField == rgba[3])
  217. dStrcpy(val, StringUnit::setUnit(prevVal, 3, strValue, " \t\n"), 128);
  218. if (val[0] != 0)
  219. {
  220. // Update the field or variable.
  221. if (object && field)
  222. object->setDataField(field, 0, val);
  223. else if (currentLocalRegister != -1)
  224. Script::gEvalState.setLocalStringVariable(currentLocalRegister, val, dStrlen(val));
  225. else if (Script::gEvalState.currentVariable)
  226. Script::gEvalState.setStringVariable(val);
  227. }
  228. }
  229. //------------------------------------------------------------
  230. F64 consoleStringToNumber(const char *str, StringTableEntry file, U32 line)
  231. {
  232. F64 val = dAtof(str);
  233. if (val != 0)
  234. return val;
  235. else if (!dStricmp(str, "true"))
  236. return 1;
  237. else if (!dStricmp(str, "false"))
  238. return 0;
  239. else if (file)
  240. {
  241. Con::warnf(ConsoleLogEntry::General, "%s (%d): string always evaluates to 0.", file, line);
  242. return 0;
  243. }
  244. return 0;
  245. }
  246. SimObject* getThisObject(ConsoleValue& simObjectLookupValue)
  247. {
  248. SimObject* thisObject = NULL;
  249. // Optimization: If we're an integer, we can lookup the value by SimObjectId
  250. if (simObjectLookupValue.getType() == ConsoleValueType::cvInteger)
  251. thisObject = Sim::findObject(static_cast<SimObjectId>(simObjectLookupValue.getFastInt()));
  252. else
  253. {
  254. SimObject *foundObject = Sim::findObject(simObjectLookupValue.getString());
  255. // Optimization: If we're not an integer, let's make it so that the fast path exists
  256. // on the first argument of the method call (speeds up future usage of %this, for example)
  257. if (foundObject != NULL)
  258. simObjectLookupValue.setInt(static_cast<S64>(foundObject->getId()));
  259. thisObject = foundObject;
  260. }
  261. return thisObject;
  262. }
  263. //------------------------------------------------------------
  264. void ExprEvalState::setCurVarName(StringTableEntry name)
  265. {
  266. if (name[0] == '$')
  267. currentVariable = Con::gGlobalVars.lookup(name);
  268. else if (getStackDepth() > 0)
  269. currentVariable = getCurrentFrame().lookup(name);
  270. if (!currentVariable && gWarnUndefinedScriptVariables)
  271. Con::warnf(ConsoleLogEntry::Script, "Variable referenced before assignment: %s", name);
  272. }
  273. void ExprEvalState::setCurVarNameCreate(StringTableEntry name)
  274. {
  275. if (name[0] == '$')
  276. currentVariable = Con::gGlobalVars.add(name);
  277. else if (getStackDepth() > 0)
  278. currentVariable = getCurrentFrame().add(name);
  279. else
  280. {
  281. currentVariable = NULL;
  282. Con::warnf(ConsoleLogEntry::Script, "Accessing local variable in global scope... failed: %s", name);
  283. }
  284. }
  285. //------------------------------------------------------------
  286. S32 ExprEvalState::getIntVariable()
  287. {
  288. return currentVariable ? currentVariable->getIntValue() : 0;
  289. }
  290. F64 ExprEvalState::getFloatVariable()
  291. {
  292. return currentVariable ? currentVariable->getFloatValue() : 0;
  293. }
  294. const char *ExprEvalState::getStringVariable()
  295. {
  296. return currentVariable ? currentVariable->getStringValue() : "";
  297. }
  298. //------------------------------------------------------------
  299. void ExprEvalState::setIntVariable(S32 val)
  300. {
  301. AssertFatal(currentVariable != NULL, "Invalid evaluator state - trying to set null variable!");
  302. currentVariable->setIntValue(val);
  303. }
  304. void ExprEvalState::setFloatVariable(F64 val)
  305. {
  306. AssertFatal(currentVariable != NULL, "Invalid evaluator state - trying to set null variable!");
  307. currentVariable->setFloatValue(val);
  308. }
  309. void ExprEvalState::setStringVariable(const char *val)
  310. {
  311. AssertFatal(currentVariable != NULL, "Invalid evaluator state - trying to set null variable!");
  312. currentVariable->setStringValue(val);
  313. }
  314. //-----------------------------------------------------------------------------
  315. enum class FloatOperation
  316. {
  317. Add,
  318. Sub,
  319. Mul,
  320. Div,
  321. LT,
  322. LE,
  323. GR,
  324. GE,
  325. EQ,
  326. NE
  327. };
  328. template<FloatOperation Op>
  329. TORQUE_NOINLINE void doSlowMathOp()
  330. {
  331. ConsoleValue& a = stack[_STK];
  332. ConsoleValue& b = stack[_STK - 1];
  333. // Arithmetic
  334. if constexpr (Op == FloatOperation::Add)
  335. stack[_STK - 1].setFloat(a.getFloat() + b.getFloat());
  336. else if constexpr (Op == FloatOperation::Sub)
  337. stack[_STK - 1].setFloat(a.getFloat() - b.getFloat());
  338. else if constexpr (Op == FloatOperation::Mul)
  339. stack[_STK - 1].setFloat(a.getFloat() * b.getFloat());
  340. else if constexpr (Op == FloatOperation::Div)
  341. stack[_STK - 1].setFloat(a.getFloat() / b.getFloat());
  342. // Logical
  343. if constexpr (Op == FloatOperation::LT)
  344. stack[_STK - 1].setInt(a.getFloat() < b.getFloat());
  345. if constexpr (Op == FloatOperation::LE)
  346. stack[_STK - 1].setInt(a.getFloat() <= b.getFloat());
  347. if constexpr (Op == FloatOperation::GR)
  348. stack[_STK - 1].setInt(a.getFloat() > b.getFloat());
  349. if constexpr (Op == FloatOperation::GE)
  350. stack[_STK - 1].setInt(a.getFloat() >= b.getFloat());
  351. if constexpr (Op == FloatOperation::EQ)
  352. stack[_STK - 1].setInt(a.getFloat() == b.getFloat());
  353. if constexpr (Op == FloatOperation::NE)
  354. stack[_STK - 1].setInt(a.getFloat() != b.getFloat());
  355. _STK--;
  356. }
  357. template<FloatOperation Op>
  358. TORQUE_FORCEINLINE void doFloatMathOperation()
  359. {
  360. ConsoleValue& a = stack[_STK];
  361. ConsoleValue& b = stack[_STK - 1];
  362. S32 fastIf = (a.getType() == ConsoleValueType::cvFloat) & (b.getType() == ConsoleValueType::cvFloat);
  363. if (fastIf)
  364. {
  365. // Arithmetic
  366. if constexpr (Op == FloatOperation::Add)
  367. stack[_STK - 1].setFastFloat(a.getFastFloat() + b.getFastFloat());
  368. if constexpr (Op == FloatOperation::Sub)
  369. stack[_STK - 1].setFastFloat(a.getFastFloat() - b.getFastFloat());
  370. if constexpr (Op == FloatOperation::Mul)
  371. stack[_STK - 1].setFastFloat(a.getFastFloat() * b.getFastFloat());
  372. if constexpr (Op == FloatOperation::Div)
  373. stack[_STK - 1].setFastFloat(a.getFastFloat() / b.getFastFloat());
  374. // Logical
  375. if constexpr (Op == FloatOperation::LT)
  376. stack[_STK - 1].setFastInt(a.getFastFloat() < b.getFastFloat());
  377. if constexpr (Op == FloatOperation::LE)
  378. stack[_STK - 1].setFastInt(a.getFastFloat() <= b.getFastFloat());
  379. if constexpr (Op == FloatOperation::GR)
  380. stack[_STK - 1].setFastInt(a.getFastFloat() > b.getFastFloat());
  381. if constexpr (Op == FloatOperation::GE)
  382. stack[_STK - 1].setFastInt(a.getFastFloat() >= b.getFastFloat());
  383. if constexpr (Op == FloatOperation::EQ)
  384. stack[_STK - 1].setFastInt(a.getFastFloat() == b.getFastFloat());
  385. if constexpr (Op == FloatOperation::NE)
  386. stack[_STK - 1].setFastInt(a.getFastFloat() != b.getFastFloat());
  387. _STK--;
  388. }
  389. else
  390. {
  391. doSlowMathOp<Op>();
  392. }
  393. }
  394. //-----------------------------------------------------------------------------
  395. enum class IntegerOperation
  396. {
  397. BitAnd,
  398. BitOr,
  399. Xor,
  400. LShift,
  401. RShift,
  402. LogicalAnd,
  403. LogicalOr
  404. };
  405. template<IntegerOperation Op>
  406. TORQUE_NOINLINE void doSlowIntegerOp()
  407. {
  408. ConsoleValue& a = stack[_STK];
  409. ConsoleValue& b = stack[_STK - 1];
  410. // Bitwise Op
  411. if constexpr (Op == IntegerOperation::BitAnd)
  412. stack[_STK - 1].setInt(a.getInt() & b.getInt());
  413. if constexpr (Op == IntegerOperation::BitOr)
  414. stack[_STK - 1].setInt(a.getInt() | b.getInt());
  415. if constexpr (Op == IntegerOperation::Xor)
  416. stack[_STK - 1].setInt(a.getInt() ^ b.getInt());
  417. if constexpr (Op == IntegerOperation::LShift)
  418. stack[_STK - 1].setInt(a.getInt() << b.getInt());
  419. if constexpr (Op == IntegerOperation::RShift)
  420. stack[_STK - 1].setInt(a.getInt() >> b.getInt());
  421. // Logical Op
  422. if constexpr (Op == IntegerOperation::LogicalAnd)
  423. stack[_STK - 1].setBool(a.getInt() && b.getInt());
  424. if constexpr (Op == IntegerOperation::LogicalOr)
  425. stack[_STK - 1].setBool(a.getInt() || b.getInt());
  426. _STK--;
  427. }
  428. template<IntegerOperation Op>
  429. TORQUE_FORCEINLINE void doIntOperation()
  430. {
  431. ConsoleValue& a = stack[_STK];
  432. ConsoleValue& b = stack[_STK - 1];
  433. if (a.isNumberType() && b.isNumberType())
  434. {
  435. // Bitwise Op
  436. if constexpr (Op == IntegerOperation::BitAnd)
  437. stack[_STK - 1].setFastInt(a.getFastInt() & b.getFastInt());
  438. if constexpr (Op == IntegerOperation::BitOr)
  439. stack[_STK - 1].setFastInt(a.getFastInt() | b.getFastInt());
  440. if constexpr (Op == IntegerOperation::Xor)
  441. stack[_STK - 1].setFastInt(a.getFastInt() ^ b.getFastInt());
  442. if constexpr (Op == IntegerOperation::LShift)
  443. stack[_STK - 1].setFastInt(a.getFastInt() << b.getFastInt());
  444. if constexpr (Op == IntegerOperation::RShift)
  445. stack[_STK - 1].setFastInt(a.getFastInt() >> b.getFastInt());
  446. // Logical Op
  447. if constexpr (Op == IntegerOperation::LogicalAnd)
  448. stack[_STK - 1].setBool(a.getFastInt() && b.getFastInt());
  449. if constexpr (Op == IntegerOperation::LogicalOr)
  450. stack[_STK - 1].setBool(a.getFastInt() || b.getFastInt());
  451. _STK--;
  452. }
  453. else
  454. {
  455. doSlowIntegerOp<Op>();
  456. }
  457. }
  458. //-----------------------------------------------------------------------------
  459. U32 gExecCount = 0;
  460. Con::EvalResult CodeBlock::exec(U32 ip, const char* functionName, Namespace* thisNamespace, U32 argc, ConsoleValue* argv, bool noCalls, StringTableEntry packageName, S32 setFrame)
  461. {
  462. #ifdef TORQUE_DEBUG
  463. U32 stackStart = _STK;
  464. gExecCount++;
  465. #endif
  466. const U32 TRACE_BUFFER_SIZE = 1024;
  467. static char traceBuffer[TRACE_BUFFER_SIZE];
  468. U32 i;
  469. U32 iterDepth = 0;
  470. ConsoleValue returnValue;
  471. incRefCount();
  472. F64* curFloatTable;
  473. char* curStringTable;
  474. S32 curStringTableLen = 0; //clint to ensure we dont overwrite it
  475. StringTableEntry thisFunctionName = NULL;
  476. bool popFrame = false;
  477. if (argv)
  478. {
  479. // assume this points into a function decl:
  480. U32 fnArgc = code[ip + 2 + 6];
  481. U32 regCount = code[ip + 2 + 7];
  482. thisFunctionName = CodeToSTE(code, ip);
  483. S32 wantedArgc = getMin(argc - 1, fnArgc); // argv[0] is func name
  484. if (Con::gTraceOn)
  485. {
  486. traceBuffer[0] = 0;
  487. dStrcat(traceBuffer, "Entering ", TRACE_BUFFER_SIZE);
  488. if (packageName)
  489. {
  490. dStrcat(traceBuffer, "[", TRACE_BUFFER_SIZE);
  491. dStrcat(traceBuffer, packageName, TRACE_BUFFER_SIZE);
  492. dStrcat(traceBuffer, "]", TRACE_BUFFER_SIZE);
  493. }
  494. if (thisNamespace && thisNamespace->mName)
  495. {
  496. dSprintf(traceBuffer + (U32)dStrlen(traceBuffer), sizeof(traceBuffer) - (U32)dStrlen(traceBuffer),
  497. "%s::%s(", thisNamespace->mName, thisFunctionName);
  498. }
  499. else
  500. {
  501. dSprintf(traceBuffer + (U32)dStrlen(traceBuffer), sizeof(traceBuffer) - (U32)dStrlen(traceBuffer),
  502. "%s(", thisFunctionName);
  503. }
  504. for (i = 0; i < wantedArgc; i++)
  505. {
  506. dStrcat(traceBuffer, argv[i + 1].getString(), TRACE_BUFFER_SIZE);
  507. if (i != wantedArgc - 1)
  508. dStrcat(traceBuffer, ", ", TRACE_BUFFER_SIZE);
  509. }
  510. dStrcat(traceBuffer, ")", TRACE_BUFFER_SIZE);
  511. Con::printf("%s", traceBuffer);
  512. }
  513. Script::gEvalState.pushFrame(thisFunctionName, thisNamespace, regCount);
  514. popFrame = true;
  515. for (i = 0; i < wantedArgc; i++)
  516. {
  517. S32 reg = code[ip + (2 + 6 + 1 + 1) + i];
  518. ConsoleValue& value = argv[i + 1];
  519. Script::gEvalState.moveConsoleValue(reg, (value));
  520. }
  521. ip = ip + fnArgc + (2 + 6 + 1 + 1);
  522. curFloatTable = functionFloats;
  523. curStringTable = functionStrings;
  524. curStringTableLen = functionStringsMaxLen;
  525. }
  526. else
  527. {
  528. curFloatTable = globalFloats;
  529. curStringTable = globalStrings;
  530. curStringTableLen = globalStringsMaxLen;
  531. // If requested stack frame isn't available, request a new one
  532. // (this prevents assert failures when creating local
  533. // variables without a stack frame)
  534. if (Script::gEvalState.getStackDepth() <= setFrame)
  535. setFrame = -1;
  536. // Do we want this code to execute using a new stack frame?
  537. // compiling a file will force setFrame to 0, forcing us to get a new frame.
  538. if (setFrame <= 0)
  539. {
  540. // argc is the local count for eval
  541. Script::gEvalState.pushFrame(NULL, NULL, argc);
  542. }
  543. else
  544. {
  545. // We want to copy a reference to an existing stack frame
  546. // on to the top of the stack. Any change that occurs to
  547. // the locals during this new frame will also occur in the
  548. // original frame.
  549. S32 stackIndex = Script::gEvalState.getTopOfStack() - setFrame - 1;
  550. Script::gEvalState.pushFrameRef(stackIndex);
  551. }
  552. popFrame = true;
  553. }
  554. Script::gEvalState.getCurrentFrame().module = this;
  555. Script::gEvalState.getCurrentFrame().ip = ip;
  556. // Grab the state of the telenet debugger here once
  557. // so that the push and pop frames are always balanced.
  558. const bool telDebuggerOn = TelDebugger && TelDebugger->isConnected();
  559. if (telDebuggerOn && setFrame < 0)
  560. TelDebugger->pushStackFrame();
  561. StringTableEntry var, objParent;
  562. U32 failJump = 0;
  563. StringTableEntry fnName;
  564. StringTableEntry fnNamespace, fnPackage;
  565. static const U32 objectCreationStackSize = 32;
  566. S32 objectCreationStackIndex = 0;
  567. struct {
  568. SimObject* newObject;
  569. U32 failJump;
  570. } objectCreationStack[objectCreationStackSize] = {};
  571. SimObject* currentNewObject = 0;
  572. StringTableEntry prevField = NULL;
  573. StringTableEntry curField = NULL;
  574. SimObject* prevObject = NULL;
  575. SimObject* curObject = NULL;
  576. SimObject* thisObject = NULL;
  577. Namespace::Entry* nsEntry;
  578. Namespace* ns = NULL;
  579. const char* curFNDocBlock = NULL;
  580. const char* curNSDocBlock = NULL;
  581. const S32 nsDocLength = 128;
  582. char nsDocBlockClass[nsDocLength];
  583. S32 callArgc;
  584. ConsoleValue* callArgv;
  585. static char curFieldArray[256];
  586. static char prevFieldArray[256];
  587. if (this->name)
  588. {
  589. Con::gCurrentFile = this->name;
  590. Con::gCurrentRoot = this->modPath;
  591. }
  592. const char* val;
  593. S32 reg;
  594. S32 currentRegister = -1;
  595. // The frame temp is used by the variable accessor ops (OP_SAVEFIELD_* and
  596. // OP_LOADFIELD_*) to store temporary values for the fields.
  597. static S32 VAL_BUFFER_SIZE = 1024;
  598. FrameTemp<char> valBuffer(VAL_BUFFER_SIZE);
  599. for (;;)
  600. {
  601. U32 instruction = code[ip++];
  602. breakContinue:
  603. switch (instruction)
  604. {
  605. case OP_FUNC_DECL:
  606. if (!noCalls)
  607. {
  608. fnName = CodeToSTE(code, ip);
  609. fnNamespace = CodeToSTE(code, ip + 2);
  610. fnPackage = CodeToSTE(code, ip + 4);
  611. bool hasBody = (code[ip + 6] & 0x01) != 0;
  612. Namespace::unlinkPackages();
  613. if (fnNamespace == NULL && fnPackage == NULL)
  614. ns = Namespace::global();
  615. else
  616. ns = Namespace::find(fnNamespace, fnPackage);
  617. ns->addFunction(fnName, this, hasBody ? ip : 0);// if no body, set the IP to 0
  618. if (curNSDocBlock)
  619. {
  620. if (fnNamespace == StringTable->lookup(nsDocBlockClass))
  621. {
  622. char* usageStr = dStrdup(curNSDocBlock);
  623. usageStr[dStrlen(usageStr)] = '\0';
  624. ns->mUsage = usageStr;
  625. ns->mCleanUpUsage = true;
  626. curNSDocBlock = NULL;
  627. }
  628. }
  629. Namespace::relinkPackages();
  630. // If we had a docblock, it's definitely not valid anymore, so clear it out.
  631. curFNDocBlock = NULL;
  632. //Con::printf("Adding function %s::%s (%d)", fnNamespace, fnName, ip);
  633. }
  634. ip = code[ip + 7];
  635. break;
  636. case OP_CREATE_OBJECT:
  637. {
  638. // Read some useful info.
  639. objParent = CodeToSTE(code, ip);
  640. bool isDataBlock = code[ip + 2];
  641. bool isInternal = code[ip + 3];
  642. bool isSingleton = code[ip + 4];
  643. U32 lineNumber = code[ip + 5];
  644. failJump = code[ip + 6];
  645. // If we don't allow calls, we certainly don't allow creating objects!
  646. // Moved this to after failJump is set. Engine was crashing when
  647. // noCalls = true and an object was being created at the beginning of
  648. // a file. ADL.
  649. if (noCalls)
  650. {
  651. ip = failJump;
  652. break;
  653. }
  654. // Push the old info to the stack
  655. //Assert( objectCreationStackIndex < objectCreationStackSize );
  656. objectCreationStack[objectCreationStackIndex].newObject = currentNewObject;
  657. objectCreationStack[objectCreationStackIndex++].failJump = failJump;
  658. // Get the constructor information off the stack.
  659. gCallStack.argvc(NULL, callArgc, &callArgv);
  660. AssertFatal(callArgc - 3 >= 0, avar("Call Arg needs at least 3, only has %d", callArgc));
  661. const char* objectName = callArgv[2].getString();
  662. // Con::printf("Creating object...");
  663. // objectName = argv[1]...
  664. currentNewObject = NULL;
  665. // Are we creating a datablock? If so, deal with case where we override
  666. // an old one.
  667. if (isDataBlock)
  668. {
  669. // Con::printf(" - is a datablock");
  670. // Find the old one if any.
  671. SimObject* db = Sim::getDataBlockGroup()->findObject(objectName);
  672. // Make sure we're not changing types on ourselves...
  673. if (db && dStricmp(db->getClassName(), callArgv[1].getString()))
  674. {
  675. Con::errorf(ConsoleLogEntry::General, "Cannot re-declare data block %s with a different class.", objectName);
  676. ip = failJump;
  677. gCallStack.popFrame();
  678. break;
  679. }
  680. // If there was one, set the currentNewObject and move on.
  681. if (db)
  682. currentNewObject = db;
  683. }
  684. else if (!isInternal)
  685. {
  686. AbstractClassRep* rep = AbstractClassRep::findClassRep(objectName);
  687. if (rep != NULL)
  688. {
  689. Con::errorf(ConsoleLogEntry::General, "%s: Cannot name object [%s] the same name as a script class.",
  690. getFileLine(ip), objectName);
  691. ip = failJump;
  692. gCallStack.popFrame();
  693. break;
  694. }
  695. SimObject* obj = Sim::findObject((const char*)objectName);
  696. if (obj)
  697. {
  698. if (isSingleton)
  699. {
  700. // Make sure we're not trying to change types
  701. if (dStricmp(obj->getClassName(), callArgv[1].getString()) != 0)
  702. {
  703. Con::errorf(ConsoleLogEntry::General, "%s: Cannot re-declare object [%s] with a different class [%s] - was [%s].",
  704. getFileLine(ip), objectName, callArgv[1].getString(), obj->getClassName());
  705. ip = failJump;
  706. gCallStack.popFrame();
  707. break;
  708. }
  709. // We're creating a singleton, so use the found object instead of creating a new object.
  710. currentNewObject = obj;
  711. Con::warnf("%s: Singleton Object was already created with name %s. Using existing object.",
  712. getFileLine(ip), objectName);
  713. }
  714. }
  715. }
  716. gCallStack.popFrame();
  717. if (!currentNewObject)
  718. {
  719. // Well, looks like we have to create a new object.
  720. ConsoleObject* object = ConsoleObject::create(callArgv[1].getString());
  721. // Deal with failure!
  722. if (!object)
  723. {
  724. Con::errorf(ConsoleLogEntry::General, "%s: Unable to instantiate non-conobject class %s.", getFileLine(ip - 1), callArgv[1].getString());
  725. ip = failJump;
  726. break;
  727. }
  728. // Do special datablock init if appropros
  729. if (isDataBlock)
  730. {
  731. SimDataBlock* dataBlock = dynamic_cast<SimDataBlock*>(object);
  732. if (dataBlock)
  733. {
  734. dataBlock->assignId();
  735. }
  736. else
  737. {
  738. // They tried to make a non-datablock with a datablock keyword!
  739. Con::errorf(ConsoleLogEntry::General, "%s: Unable to instantiate non-datablock class %s.", getFileLine(ip - 1), callArgv[1].getString());
  740. // Clean up...
  741. delete object;
  742. currentNewObject = NULL;
  743. ip = failJump;
  744. break;
  745. }
  746. }
  747. // Finally, set currentNewObject to point to the new one.
  748. currentNewObject = dynamic_cast<SimObject*>(object);
  749. // Deal with the case of a non-SimObject.
  750. if (!currentNewObject)
  751. {
  752. Con::errorf(ConsoleLogEntry::General, "%s: Unable to instantiate non-SimObject class %s.", getFileLine(ip - 1), callArgv[1].getString());
  753. delete object;
  754. ip = failJump;
  755. break;
  756. }
  757. // Set the declaration line
  758. currentNewObject->setDeclarationLine(lineNumber);
  759. // Set the file that this object was created in
  760. currentNewObject->setFilename(this->name);
  761. // Does it have a parent object? (ie, the copy constructor : syntax, not inheriance)
  762. if (*objParent)
  763. {
  764. // Find it!
  765. SimObject* parent;
  766. if (Sim::findObject(objParent, parent))
  767. {
  768. // Con::printf(" - Parent object found: %s", parent->getClassName());
  769. currentNewObject->setCopySource(parent);
  770. currentNewObject->assignFieldsFrom(parent);
  771. // copy any substitution statements
  772. SimDataBlock* parent_db = dynamic_cast<SimDataBlock*>(parent);
  773. if (parent_db)
  774. {
  775. SimDataBlock* currentNewObject_db = dynamic_cast<SimDataBlock*>(currentNewObject);
  776. if (currentNewObject_db)
  777. currentNewObject_db->copySubstitutionsFrom(parent_db);
  778. }
  779. }
  780. else
  781. {
  782. if (Con::gObjectCopyFailures == -1)
  783. Con::errorf(ConsoleLogEntry::General, "%s: Unable to find parent object %s for %s.", getFileLine(ip - 1), objParent, callArgv[1].getString());
  784. ++Con::gObjectCopyFailures;
  785. delete object;
  786. currentNewObject = NULL;
  787. ip = failJump;
  788. break;
  789. }
  790. }
  791. // If a name was passed, assign it.
  792. if (objectName[0])
  793. {
  794. if (!isInternal)
  795. currentNewObject->assignName(objectName);
  796. else
  797. currentNewObject->setInternalName(objectName);
  798. // Set the original name
  799. currentNewObject->setOriginalName( objectName );
  800. }
  801. // Do the constructor parameters.
  802. if (!currentNewObject->processArguments(callArgc - 3, callArgv + 3))
  803. {
  804. delete currentNewObject;
  805. currentNewObject = NULL;
  806. ip = failJump;
  807. break;
  808. }
  809. // If it's not a datablock, allow people to modify bits of it.
  810. if (!isDataBlock)
  811. {
  812. currentNewObject->setModStaticFields(true);
  813. currentNewObject->setModDynamicFields(true);
  814. }
  815. }
  816. else
  817. {
  818. currentNewObject->reloadReset(); // AFX (reload-reset)
  819. // Does it have a parent object? (ie, the copy constructor : syntax, not inheriance)
  820. if (*objParent)
  821. {
  822. // Find it!
  823. SimObject* parent;
  824. if (Sim::findObject(objParent, parent))
  825. {
  826. // Con::printf(" - Parent object found: %s", parent->getClassName());
  827. // temporarily block name change
  828. SimObject::preventNameChanging = true;
  829. currentNewObject->setCopySource(parent);
  830. currentNewObject->assignFieldsFrom(parent);
  831. // restore name changing
  832. SimObject::preventNameChanging = false;
  833. // copy any substitution statements
  834. SimDataBlock* parent_db = dynamic_cast<SimDataBlock*>(parent);
  835. if (parent_db)
  836. {
  837. SimDataBlock* currentNewObject_db = dynamic_cast<SimDataBlock*>(currentNewObject);
  838. if (currentNewObject_db)
  839. currentNewObject_db->copySubstitutionsFrom(parent_db);
  840. }
  841. }
  842. else
  843. {
  844. Con::errorf(ConsoleLogEntry::General, "%d: Unable to find parent object %s for %s.", lineNumber, objParent, callArgv[1].getString());
  845. }
  846. }
  847. }
  848. // Advance the IP past the create info...
  849. ip += 7;
  850. break;
  851. }
  852. case OP_ADD_OBJECT:
  853. {
  854. // See OP_SETCURVAR for why we do this.
  855. curFNDocBlock = NULL;
  856. curNSDocBlock = NULL;
  857. // Do we place this object at the root?
  858. bool placeAtRoot = code[ip++];
  859. // Con::printf("Adding object %s", currentNewObject->getName());
  860. // Make sure it wasn't already added, then add it.
  861. if (currentNewObject == NULL)
  862. {
  863. break;
  864. }
  865. bool isMessage = dynamic_cast<Message*>(currentNewObject) != NULL;
  866. if (currentNewObject->isProperlyAdded() == false)
  867. {
  868. bool ret = false;
  869. if (isMessage)
  870. {
  871. SimObjectId id = Message::getNextMessageID();
  872. if (id != 0xffffffff)
  873. ret = currentNewObject->registerObject(id);
  874. else
  875. Con::errorf("%s: No more object IDs available for messages", getFileLine(ip));
  876. }
  877. else
  878. ret = currentNewObject->registerObject();
  879. if (!ret)
  880. {
  881. // This error is usually caused by failing to call Parent::initPersistFields in the class' initPersistFields().
  882. Con::warnf(ConsoleLogEntry::General, "%s: Register object failed for object %s of class %s.", getFileLine(ip - 2), currentNewObject->getName(), currentNewObject->getClassName());
  883. ++Con::gObjectCopyFailures;
  884. delete currentNewObject;
  885. currentNewObject = NULL;
  886. ip = failJump;
  887. break;
  888. }
  889. }
  890. // Are we dealing with a datablock?
  891. SimDataBlock* dataBlock = dynamic_cast<SimDataBlock*>(currentNewObject);
  892. String errorStr;
  893. // If so, preload it.
  894. if (dataBlock && !dataBlock->preload(true, errorStr))
  895. {
  896. Con::errorf(ConsoleLogEntry::General, "%s: preload failed for %s: %s.", getFileLine(ip - 2),
  897. currentNewObject->getName(), errorStr.c_str());
  898. ++Con::gObjectCopyFailures;
  899. dataBlock->deleteObject();
  900. currentNewObject = NULL;
  901. ip = failJump;
  902. break;
  903. }
  904. // What group will we be added to, if any?
  905. U32 groupAddId = (U32)stack[_STK].getInt();
  906. SimGroup* grp = NULL;
  907. SimSet* set = NULL;
  908. if (!placeAtRoot || !currentNewObject->getGroup())
  909. {
  910. if (!isMessage)
  911. {
  912. if (!placeAtRoot)
  913. {
  914. // Otherwise just add to the requested group or set.
  915. if (!Sim::findObject(groupAddId, grp))
  916. Sim::findObject(groupAddId, set);
  917. }
  918. if (placeAtRoot)
  919. {
  920. // Deal with the instantGroup if we're being put at the root or we're adding to a component.
  921. if (Con::gInstantGroup.isEmpty() || !Sim::findObject(Con::gInstantGroup, grp))
  922. grp = Sim::getRootGroup();
  923. }
  924. }
  925. // If we didn't get a group, then make sure we have a pointer to
  926. // the rootgroup.
  927. if (!grp)
  928. grp = Sim::getRootGroup();
  929. // add to the parent group
  930. grp->addObject(currentNewObject);
  931. // If for some reason the add failed, add the object to the
  932. // root group so it won't leak.
  933. if (currentNewObject->getGroup() == NULL)
  934. Sim::getRootGroup()->addObject(currentNewObject);
  935. // add to any set we might be in
  936. if (set)
  937. set->addObject(currentNewObject);
  938. }
  939. // store the new object's ID on the stack (overwriting the group/set
  940. // id, if one was given, otherwise getting pushed)
  941. S32 id = currentNewObject->getId();
  942. if (placeAtRoot)
  943. stack[_STK].setInt(id);
  944. else
  945. stack[++_STK].setInt(id);
  946. break;
  947. }
  948. case OP_END_OBJECT:
  949. {
  950. // If we're not to be placed at the root, make sure we clean up
  951. // our group reference.
  952. bool placeAtRoot = code[ip++];
  953. if (!placeAtRoot)
  954. _STK--;
  955. break;
  956. }
  957. case OP_FINISH_OBJECT:
  958. {
  959. if (currentNewObject)
  960. currentNewObject->onPostAdd();
  961. AssertFatal( objectCreationStackIndex >= 0, "Object Stack is empty." );
  962. // Restore the object info from the stack [7/9/2007 Black]
  963. currentNewObject = objectCreationStack[--objectCreationStackIndex].newObject;
  964. failJump = objectCreationStack[objectCreationStackIndex].failJump;
  965. break;
  966. }
  967. case OP_JMPIFFNOT:
  968. if (stack[_STK--].getFloat())
  969. {
  970. ip++;
  971. break;
  972. }
  973. ip = code[ip];
  974. break;
  975. case OP_JMPIFNOT:
  976. if (stack[_STK--].getInt())
  977. {
  978. ip++;
  979. break;
  980. }
  981. ip = code[ip];
  982. break;
  983. case OP_JMPNOTSTRING:
  984. if (stack[_STK--].getBool())
  985. {
  986. ip++;
  987. break;
  988. }
  989. ip = code[ip];
  990. break;
  991. case OP_JMPIFF:
  992. if (!stack[_STK--].getFloat())
  993. {
  994. ip++;
  995. break;
  996. }
  997. ip = code[ip];
  998. break;
  999. case OP_JMPIF:
  1000. if (!stack[_STK--].getFloat())
  1001. {
  1002. ip++;
  1003. break;
  1004. }
  1005. ip = code[ip];
  1006. break;
  1007. case OP_JMPIFNOT_NP:
  1008. if (stack[_STK].getInt())
  1009. {
  1010. _STK--;
  1011. ip++;
  1012. break;
  1013. }
  1014. ip = code[ip];
  1015. break;
  1016. case OP_JMPIF_NP:
  1017. if (!stack[_STK].getInt())
  1018. {
  1019. _STK--;
  1020. ip++;
  1021. break;
  1022. }
  1023. ip = code[ip];
  1024. break;
  1025. case OP_JMP:
  1026. ip = code[ip];
  1027. break;
  1028. case OP_RETURN_VOID:
  1029. {
  1030. if (iterDepth > 0)
  1031. {
  1032. // Clear iterator state.
  1033. while (iterDepth > 0)
  1034. {
  1035. iterStack[--_ITER].mIsStringIter = false;
  1036. --iterDepth;
  1037. _STK--; // this is a pop from foreach()
  1038. }
  1039. }
  1040. returnValue.setEmptyString();
  1041. goto execFinished;
  1042. }
  1043. case OP_RETURN:
  1044. {
  1045. returnValue = (stack[_STK]);
  1046. _STK--;
  1047. // Clear iterator state.
  1048. while (iterDepth > 0)
  1049. {
  1050. iterStack[--_ITER].mIsStringIter = false;
  1051. --iterDepth;
  1052. _STK--;
  1053. }
  1054. goto execFinished;
  1055. }
  1056. case OP_RETURN_FLT:
  1057. returnValue.setFloat(stack[_STK].getFloat());
  1058. _STK--;
  1059. // Clear iterator state.
  1060. while (iterDepth > 0)
  1061. {
  1062. iterStack[--_ITER].mIsStringIter = false;
  1063. --iterDepth;
  1064. _STK--;
  1065. }
  1066. goto execFinished;
  1067. case OP_RETURN_UINT:
  1068. returnValue.setInt(stack[_STK].getInt());
  1069. _STK--;
  1070. // Clear iterator state.
  1071. while (iterDepth > 0)
  1072. {
  1073. iterStack[--_ITER].mIsStringIter = false;
  1074. --iterDepth;
  1075. _STK--;
  1076. }
  1077. goto execFinished;
  1078. case OP_CMPEQ:
  1079. doFloatMathOperation<FloatOperation::EQ>();
  1080. break;
  1081. case OP_CMPGR:
  1082. doFloatMathOperation<FloatOperation::GR>();
  1083. break;
  1084. case OP_CMPGE:
  1085. doFloatMathOperation<FloatOperation::GE>();
  1086. break;
  1087. case OP_CMPLT:
  1088. doFloatMathOperation<FloatOperation::LT>();
  1089. break;
  1090. case OP_CMPLE:
  1091. doFloatMathOperation<FloatOperation::LE>();
  1092. break;
  1093. case OP_CMPNE:
  1094. doFloatMathOperation<FloatOperation::NE>();
  1095. break;
  1096. case OP_XOR:
  1097. doIntOperation<IntegerOperation::Xor>();
  1098. break;
  1099. case OP_BITAND:
  1100. doIntOperation<IntegerOperation::BitAnd>();
  1101. break;
  1102. case OP_BITOR:
  1103. doIntOperation<IntegerOperation::BitOr>();
  1104. break;
  1105. case OP_NOT:
  1106. stack[_STK].setBool(!stack[_STK].getInt());
  1107. break;
  1108. case OP_NOTF:
  1109. stack[_STK].setInt(!stack[_STK].getFloat());
  1110. break;
  1111. case OP_ONESCOMPLEMENT:
  1112. stack[_STK].setInt(~stack[_STK].getInt());
  1113. break;
  1114. case OP_SHR:
  1115. doIntOperation<IntegerOperation::RShift>();
  1116. break;
  1117. case OP_SHL:
  1118. doIntOperation<IntegerOperation::LShift>();
  1119. break;
  1120. case OP_AND:
  1121. doIntOperation<IntegerOperation::LogicalAnd>();
  1122. break;
  1123. case OP_OR:
  1124. doIntOperation<IntegerOperation::LogicalOr>();
  1125. break;
  1126. case OP_ADD:
  1127. doFloatMathOperation<FloatOperation::Add>();
  1128. break;
  1129. case OP_SUB:
  1130. doFloatMathOperation<FloatOperation::Sub>();
  1131. break;
  1132. case OP_MUL:
  1133. doFloatMathOperation<FloatOperation::Mul>();
  1134. break;
  1135. case OP_DIV:
  1136. doFloatMathOperation<FloatOperation::Div>();
  1137. break;
  1138. case OP_MOD:
  1139. {
  1140. S64 divisor = stack[_STK - 1].getInt();
  1141. if (divisor != 0)
  1142. stack[_STK - 1].setInt(stack[_STK].getInt() % divisor);
  1143. else
  1144. stack[_STK - 1].setInt(0);
  1145. _STK--;
  1146. break;
  1147. }
  1148. case OP_NEG:
  1149. stack[_STK].setFloat(-stack[_STK].getFloat());
  1150. break;
  1151. case OP_INC:
  1152. reg = code[ip++];
  1153. currentRegister = reg;
  1154. Script::gEvalState.setLocalFloatVariable(reg, Script::gEvalState.getLocalFloatVariable(reg) + 1.0);
  1155. break;
  1156. case OP_SETCURVAR:
  1157. var = CodeToSTE(code, ip);
  1158. ip += 2;
  1159. // If a variable is set, then these must be NULL. It is necessary
  1160. // to set this here so that the vector parser can appropriately
  1161. // identify whether it's dealing with a vector.
  1162. prevField = NULL;
  1163. prevObject = NULL;
  1164. curObject = NULL;
  1165. // Used for local variable caching of what is active...when we
  1166. // set a global, we aren't active
  1167. currentRegister = -1;
  1168. Script::gEvalState.setCurVarName(var);
  1169. // In order to let docblocks work properly with variables, we have
  1170. // clear the current docblock when we do an assign. This way it
  1171. // won't inappropriately carry forward to following function decls.
  1172. curFNDocBlock = NULL;
  1173. curNSDocBlock = NULL;
  1174. break;
  1175. case OP_SETCURVAR_CREATE:
  1176. var = CodeToSTE(code, ip);
  1177. ip += 2;
  1178. // See OP_SETCURVAR
  1179. prevField = NULL;
  1180. prevObject = NULL;
  1181. curObject = NULL;
  1182. // Used for local variable caching of what is active...when we
  1183. // set a global, we aren't active
  1184. currentRegister = -1;
  1185. Script::gEvalState.setCurVarNameCreate(var);
  1186. // See OP_SETCURVAR for why we do this.
  1187. curFNDocBlock = NULL;
  1188. curNSDocBlock = NULL;
  1189. break;
  1190. case OP_SETCURVAR_ARRAY:
  1191. var = StringTable->insert(stack[_STK].getString());
  1192. // See OP_SETCURVAR
  1193. prevField = NULL;
  1194. prevObject = NULL;
  1195. curObject = NULL;
  1196. // Used for local variable caching of what is active...when we
  1197. // set a global, we aren't active
  1198. currentRegister = -1;
  1199. Script::gEvalState.setCurVarName(var);
  1200. // See OP_SETCURVAR for why we do this.
  1201. curFNDocBlock = NULL;
  1202. curNSDocBlock = NULL;
  1203. break;
  1204. case OP_SETCURVAR_ARRAY_CREATE:
  1205. var = StringTable->insert(stack[_STK].getString());
  1206. // See OP_SETCURVAR
  1207. prevField = NULL;
  1208. prevObject = NULL;
  1209. curObject = NULL;
  1210. // Used for local variable caching of what is active...when we
  1211. // set a global, we aren't active
  1212. currentRegister = -1;
  1213. Script::gEvalState.setCurVarNameCreate(var);
  1214. // See OP_SETCURVAR for why we do this.
  1215. curFNDocBlock = NULL;
  1216. curNSDocBlock = NULL;
  1217. break;
  1218. case OP_LOADVAR_UINT:
  1219. currentRegister = -1;
  1220. stack[_STK + 1].setInt(Script::gEvalState.getIntVariable());
  1221. _STK++;
  1222. break;
  1223. case OP_LOADVAR_FLT:
  1224. currentRegister = -1;
  1225. stack[_STK + 1].setFloat(Script::gEvalState.getFloatVariable());
  1226. _STK++;
  1227. break;
  1228. case OP_LOADVAR_STR:
  1229. currentRegister = -1;
  1230. stack[_STK + 1].setString(Script::gEvalState.getStringVariable());
  1231. _STK++;
  1232. break;
  1233. case OP_SAVEVAR_UINT:
  1234. Script::gEvalState.setIntVariable(stack[_STK].getInt());
  1235. break;
  1236. case OP_SAVEVAR_FLT:
  1237. Script::gEvalState.setFloatVariable(stack[_STK].getFloat());
  1238. break;
  1239. case OP_SAVEVAR_STR:
  1240. Script::gEvalState.setStringVariable(stack[_STK].getString());
  1241. break;
  1242. case OP_LOAD_LOCAL_VAR_UINT:
  1243. reg = code[ip++];
  1244. currentRegister = reg;
  1245. // See OP_SETCURVAR
  1246. prevField = NULL;
  1247. prevObject = NULL;
  1248. curObject = NULL;
  1249. stack[_STK + 1].setInt(Script::gEvalState.getLocalIntVariable(reg));
  1250. _STK++;
  1251. break;
  1252. case OP_LOAD_LOCAL_VAR_FLT:
  1253. reg = code[ip++];
  1254. currentRegister = reg;
  1255. // See OP_SETCURVAR
  1256. prevField = NULL;
  1257. prevObject = NULL;
  1258. curObject = NULL;
  1259. stack[_STK + 1].setFloat(Script::gEvalState.getLocalFloatVariable(reg));
  1260. _STK++;
  1261. break;
  1262. case OP_LOAD_LOCAL_VAR_STR:
  1263. reg = code[ip++];
  1264. currentRegister = reg;
  1265. // See OP_SETCURVAR
  1266. prevField = NULL;
  1267. prevObject = NULL;
  1268. curObject = NULL;
  1269. val = Script::gEvalState.getLocalStringVariable(reg);
  1270. stack[_STK + 1].setString(val);
  1271. _STK++;
  1272. break;
  1273. case OP_SAVE_LOCAL_VAR_UINT:
  1274. reg = code[ip++];
  1275. currentRegister = reg;
  1276. // See OP_SETCURVAR
  1277. prevField = NULL;
  1278. prevObject = NULL;
  1279. curObject = NULL;
  1280. Script::gEvalState.setLocalIntVariable(reg, stack[_STK].getInt());
  1281. break;
  1282. case OP_SAVE_LOCAL_VAR_FLT:
  1283. reg = code[ip++];
  1284. currentRegister = reg;
  1285. // See OP_SETCURVAR
  1286. prevField = NULL;
  1287. prevObject = NULL;
  1288. curObject = NULL;
  1289. Script::gEvalState.setLocalFloatVariable(reg, stack[_STK].getFloat());
  1290. break;
  1291. case OP_SAVE_LOCAL_VAR_STR:
  1292. reg = code[ip++];
  1293. val = stack[_STK].getString();
  1294. currentRegister = reg;
  1295. // See OP_SETCURVAR
  1296. prevField = NULL;
  1297. prevObject = NULL;
  1298. curObject = NULL;
  1299. Script::gEvalState.setLocalStringVariable(reg, val, (S32)dStrlen(val));
  1300. break;
  1301. case OP_SETCUROBJECT:
  1302. // Save the previous object for parsing vector fields.
  1303. prevObject = curObject;
  1304. val = stack[_STK].getString();
  1305. // Sim::findObject will sometimes find valid objects from
  1306. // multi-component strings. This makes sure that doesn't
  1307. // happen.
  1308. for (const char* check = val; *check; check++)
  1309. {
  1310. if (*check == ' ')
  1311. {
  1312. val = "";
  1313. break;
  1314. }
  1315. }
  1316. curObject = Sim::findObject(val);
  1317. break;
  1318. case OP_SETCUROBJECT_INTERNAL:
  1319. ++ip; // To skip the recurse flag if the object wasnt found
  1320. if (curObject)
  1321. {
  1322. SimSet* set = dynamic_cast<SimSet*>(curObject);
  1323. if (set)
  1324. {
  1325. StringTableEntry intName = StringTable->insert(stack[_STK].getString());
  1326. bool recurse = code[ip - 1];
  1327. SimObject* obj = set->findObjectByInternalName(intName, recurse);
  1328. stack[_STK].setInt(obj ? obj->getId() : 0);
  1329. }
  1330. else
  1331. {
  1332. Con::errorf(ConsoleLogEntry::Script, "%s: Attempt to use -> on non-set %s of class %s.", getFileLine(ip - 2), curObject->getName(), curObject->getClassName());
  1333. stack[_STK].setInt(0);
  1334. }
  1335. }
  1336. else
  1337. {
  1338. Con::errorf(ConsoleLogEntry::Script, "%s: Attempt to use ->, but the group object wasn't found.", getFileLine(ip - 2));
  1339. stack[_STK].setInt(0);
  1340. }
  1341. break;
  1342. case OP_SETCUROBJECT_NEW:
  1343. curObject = currentNewObject;
  1344. break;
  1345. case OP_SETCURFIELD:
  1346. // Save the previous field for parsing vector fields.
  1347. prevField = curField;
  1348. dStrcpy(prevFieldArray, curFieldArray, 256);
  1349. curField = CodeToSTE(code, ip);
  1350. curFieldArray[0] = 0;
  1351. ip += 2;
  1352. break;
  1353. case OP_SETCURFIELD_ARRAY:
  1354. dStrcpy(curFieldArray, stack[_STK].getString(), 256);
  1355. break;
  1356. case OP_SETCURFIELD_TYPE:
  1357. if(curObject)
  1358. curObject->setDataFieldType(code[ip], curField, curFieldArray);
  1359. ip++;
  1360. break;
  1361. case OP_LOADFIELD_UINT:
  1362. if (curObject)
  1363. stack[_STK + 1].setInt(dAtol(curObject->getDataField(curField, curFieldArray)));
  1364. else
  1365. {
  1366. // The field is not being retrieved from an object. Maybe it's
  1367. // a special accessor?
  1368. char buff[FieldBufferSizeNumeric];
  1369. memset(buff, 0, sizeof(buff));
  1370. getFieldComponent(prevObject, prevField, prevFieldArray, curField, buff, currentRegister);
  1371. stack[_STK + 1].setInt(dAtol(buff));
  1372. }
  1373. _STK++;
  1374. break;
  1375. case OP_LOADFIELD_FLT:
  1376. if (curObject)
  1377. stack[_STK + 1].setFloat(dAtod(curObject->getDataField(curField, curFieldArray)));
  1378. else
  1379. {
  1380. // The field is not being retrieved from an object. Maybe it's
  1381. // a special accessor?
  1382. char buff[FieldBufferSizeNumeric];
  1383. memset(buff, 0, sizeof(buff));
  1384. getFieldComponent(prevObject, prevField, prevFieldArray, curField, buff, currentRegister);
  1385. stack[_STK + 1].setFloat(dAtod(buff));
  1386. }
  1387. _STK++;
  1388. break;
  1389. case OP_LOADFIELD_STR:
  1390. if (curObject)
  1391. {
  1392. val = curObject->getDataField(curField, curFieldArray);
  1393. stack[_STK + 1].setString(val);
  1394. }
  1395. else
  1396. {
  1397. // The field is not being retrieved from an object. Maybe it's
  1398. // a special accessor?
  1399. char buff[FieldBufferSizeString];
  1400. memset(buff, 0, sizeof(buff));
  1401. getFieldComponent(prevObject, prevField, prevFieldArray, curField, buff, currentRegister);
  1402. stack[_STK + 1].setString(buff);
  1403. }
  1404. _STK++;
  1405. break;
  1406. case OP_SAVEFIELD_UINT:
  1407. if (curObject)
  1408. curObject->setDataField(curField, curFieldArray, stack[_STK].getString());
  1409. else
  1410. {
  1411. // The field is not being set on an object. Maybe it's a special accessor?
  1412. setFieldComponent(prevObject, prevField, prevFieldArray, curField, currentRegister);
  1413. prevObject = NULL;
  1414. }
  1415. break;
  1416. case OP_SAVEFIELD_FLT:
  1417. if (curObject)
  1418. curObject->setDataField(curField, curFieldArray, stack[_STK].getString());
  1419. else
  1420. {
  1421. // The field is not being set on an object. Maybe it's a special accessor?
  1422. setFieldComponent(prevObject, prevField, prevFieldArray, curField, currentRegister);
  1423. prevObject = NULL;
  1424. }
  1425. break;
  1426. case OP_SAVEFIELD_STR:
  1427. if (curObject)
  1428. curObject->setDataField(curField, curFieldArray, stack[_STK].getString());
  1429. else
  1430. {
  1431. // The field is not being set on an object. Maybe it's a special accessor?
  1432. setFieldComponent(prevObject, prevField, prevFieldArray, curField, currentRegister);
  1433. prevObject = NULL;
  1434. }
  1435. break;
  1436. case OP_POP_STK:
  1437. _STK--;
  1438. break;
  1439. case OP_LOADIMMED_UINT:
  1440. stack[_STK + 1].setInt(code[ip++]);
  1441. _STK++;
  1442. break;
  1443. case OP_LOADIMMED_FLT:
  1444. stack[_STK + 1].setFloat(curFloatTable[code[ip++]]);
  1445. _STK++;
  1446. break;
  1447. case OP_TAG_TO_STR:
  1448. code[ip - 1] = OP_LOADIMMED_STR;
  1449. // it's possible the string has already been converted
  1450. if (U8(curStringTable[code[ip]]) != StringTagPrefixByte)
  1451. {
  1452. U32 id = GameAddTaggedString(curStringTable + code[ip]);
  1453. dSprintf(curStringTable + code[ip] + 1, 7, "%d", id);
  1454. *(curStringTable + code[ip]) = StringTagPrefixByte;
  1455. }
  1456. TORQUE_CASE_FALLTHROUGH;
  1457. case OP_LOADIMMED_STR:
  1458. stack[_STK + 1].setString(curStringTable + code[ip++]);
  1459. _STK ++;
  1460. break;
  1461. case OP_DOCBLOCK_STR:
  1462. {
  1463. // If the first word of the doc is '\class' or '@class', then this
  1464. // is a namespace doc block, otherwise it is a function doc block.
  1465. const char* docblock = curStringTable + code[ip++];
  1466. const char* sansClass = dStrstr(docblock, "@class");
  1467. if (!sansClass)
  1468. sansClass = dStrstr(docblock, "\\class");
  1469. if (sansClass)
  1470. {
  1471. // Don't save the class declaration. Scan past the 'class'
  1472. // keyword and up to the first whitespace.
  1473. sansClass += 7;
  1474. S32 index = 0;
  1475. while ((*sansClass != ' ') && (*sansClass != '\n') && *sansClass && (index < (nsDocLength - 1)))
  1476. {
  1477. nsDocBlockClass[index++] = *sansClass;
  1478. sansClass++;
  1479. }
  1480. nsDocBlockClass[index] = '\0';
  1481. curNSDocBlock = sansClass + 1;
  1482. }
  1483. else
  1484. curFNDocBlock = docblock;
  1485. }
  1486. break;
  1487. case OP_LOADIMMED_IDENT:
  1488. stack[_STK + 1].setStringTableEntry(CodeToSTE(code, ip));
  1489. _STK++;
  1490. ip += 2;
  1491. break;
  1492. case OP_CALLFUNC:
  1493. {
  1494. // This routingId is set when we query the object as to whether
  1495. // it handles this method. It is set to an enum from the table
  1496. // above indicating whether it handles it on a component it owns
  1497. // or just on the object.
  1498. fnName = CodeToSTE(code, ip);
  1499. fnNamespace = CodeToSTE(code, ip + 2);
  1500. U32 callType = code[ip + 4];
  1501. //if this is called from inside a function, append the ip and codeptr
  1502. if (!Script::gEvalState.stack.empty())
  1503. {
  1504. Script::gEvalState.getCurrentFrame().module = this;
  1505. Script::gEvalState.getCurrentFrame().ip = ip - 1;
  1506. }
  1507. ip += 5;
  1508. gCallStack.argvc(fnName, callArgc, &callArgv);
  1509. if (callType == FuncCallExprNode::FunctionCall)
  1510. {
  1511. // Note: This works even if the function was in a package. Reason being is when
  1512. // activatePackage() is called, it swaps the namespaceEntry into the global namespace
  1513. // (and reverts it when deactivatePackage is called). Method or Static related ones work
  1514. // as expected, as the namespace is resolved on the fly.
  1515. nsEntry = Namespace::global()->lookup(fnName);
  1516. if (!nsEntry)
  1517. {
  1518. Con::warnf(ConsoleLogEntry::General,
  1519. "%s: Unable to find function %s",
  1520. getFileLine(ip - 4), fnName);
  1521. gCallStack.popFrame();
  1522. stack[_STK + 1].setEmptyString();
  1523. _STK++;
  1524. break;
  1525. }
  1526. }
  1527. else if (callType == FuncCallExprNode::StaticCall)
  1528. {
  1529. // Try to look it up.
  1530. ns = Namespace::find(fnNamespace);
  1531. nsEntry = ns->lookup(fnName);
  1532. if (!nsEntry)
  1533. {
  1534. Con::warnf(ConsoleLogEntry::General,
  1535. "%s: Unable to find function %s%s%s",
  1536. getFileLine(ip - 4), fnNamespace ? fnNamespace : "",
  1537. fnNamespace ? "::" : "", fnName);
  1538. gCallStack.popFrame();
  1539. stack[_STK + 1].setEmptyString();
  1540. _STK++;
  1541. break;
  1542. }
  1543. }
  1544. else if (callType == FuncCallExprNode::MethodCall)
  1545. {
  1546. ConsoleValue& simObjectLookupValue = callArgv[1];
  1547. thisObject = getThisObject(simObjectLookupValue);
  1548. if (thisObject == NULL)
  1549. {
  1550. Con::warnf(
  1551. ConsoleLogEntry::General,
  1552. "%s: Unable to find object: '%s' attempting to call function '%s'",
  1553. getFileLine(ip - 6),
  1554. simObjectLookupValue.getString(),
  1555. fnName
  1556. );
  1557. gCallStack.popFrame();
  1558. stack[_STK + 1].setEmptyString();
  1559. _STK++;
  1560. break;
  1561. }
  1562. ns = thisObject->getNamespace();
  1563. if (ns)
  1564. nsEntry = ns->lookup(fnName);
  1565. else
  1566. nsEntry = NULL;
  1567. }
  1568. else // it's a ParentCall
  1569. {
  1570. ConsoleValue& simObjectLookupValue = callArgv[1];
  1571. thisObject = getThisObject(simObjectLookupValue);
  1572. if (thisObject == NULL)
  1573. {
  1574. Con::warnf(
  1575. ConsoleLogEntry::General,
  1576. "%s: Unable to find object: '%s' attempting to call function '%s'",
  1577. getFileLine(ip - 6),
  1578. simObjectLookupValue.getString(),
  1579. fnName
  1580. );
  1581. gCallStack.popFrame();
  1582. stack[_STK + 1].setEmptyString();
  1583. _STK++;
  1584. break;
  1585. }
  1586. if (thisNamespace)
  1587. {
  1588. ns = thisNamespace->mParent;
  1589. if (ns)
  1590. nsEntry = ns->lookup(fnName);
  1591. else
  1592. nsEntry = NULL;
  1593. }
  1594. else
  1595. {
  1596. ns = NULL;
  1597. nsEntry = NULL;
  1598. }
  1599. }
  1600. if (!nsEntry || noCalls)
  1601. {
  1602. if (!noCalls)
  1603. {
  1604. Con::warnf(ConsoleLogEntry::General, "%s: Unknown command %s.", getFileLine(ip - 4), fnName);
  1605. if (callType == FuncCallExprNode::MethodCall)
  1606. {
  1607. Con::warnf(ConsoleLogEntry::General, " Object %s(%d) %s",
  1608. thisObject->getName() ? thisObject->getName() : "",
  1609. thisObject->getId(), Con::getNamespaceList(ns));
  1610. }
  1611. }
  1612. gCallStack.popFrame();
  1613. stack[_STK + 1].setEmptyString();
  1614. _STK++;
  1615. break;
  1616. }
  1617. if (nsEntry->mType == Namespace::Entry::ConsoleFunctionType)
  1618. {
  1619. if (nsEntry->mFunctionOffset)
  1620. {
  1621. ConsoleValue returnFromFn = nsEntry->mModule->exec(nsEntry->mFunctionOffset, fnName, nsEntry->mNamespace, callArgc, callArgv, false, nsEntry->mPackage).value;
  1622. stack[_STK + 1] = (returnFromFn);
  1623. }
  1624. else // no body
  1625. stack[_STK + 1].setEmptyString();
  1626. _STK++;
  1627. gCallStack.popFrame();
  1628. }
  1629. else
  1630. {
  1631. if ((nsEntry->mMinArgs && S32(callArgc) < nsEntry->mMinArgs) || (nsEntry->mMaxArgs && S32(callArgc) > nsEntry->mMaxArgs))
  1632. {
  1633. const char* nsName = ns ? ns->mName : "";
  1634. Con::warnf(ConsoleLogEntry::Script, "%s: %s::%s - wrong number of arguments. got %d, expected %d to %d", getFileLine(ip - 4), nsName, fnName, S32(callArgc), nsEntry->mMinArgs, nsEntry->mMaxArgs);
  1635. Con::warnf(ConsoleLogEntry::Script, "%s: usage: %s", getFileLine(ip - 4), nsEntry->mUsage);
  1636. gCallStack.popFrame();
  1637. stack[_STK + 1].setEmptyString();
  1638. _STK++;
  1639. }
  1640. else
  1641. {
  1642. switch (nsEntry->mType)
  1643. {
  1644. case Namespace::Entry::StringCallbackType:
  1645. {
  1646. const char* result = nsEntry->cb.mStringCallbackFunc(thisObject, callArgc, callArgv);
  1647. gCallStack.popFrame();
  1648. stack[_STK + 1].setString(result);
  1649. _STK++;
  1650. break;
  1651. }
  1652. case Namespace::Entry::IntCallbackType:
  1653. {
  1654. S64 result = nsEntry->cb.mIntCallbackFunc(thisObject, callArgc, callArgv);
  1655. gCallStack.popFrame();
  1656. if (code[ip] == OP_POP_STK)
  1657. {
  1658. ip++;
  1659. break;
  1660. }
  1661. stack[_STK + 1].setInt(result);
  1662. _STK++;
  1663. break;
  1664. }
  1665. case Namespace::Entry::FloatCallbackType:
  1666. {
  1667. F64 result = nsEntry->cb.mFloatCallbackFunc(thisObject, callArgc, callArgv);
  1668. gCallStack.popFrame();
  1669. if (code[ip] == OP_POP_STK)
  1670. {
  1671. ip++;
  1672. break;
  1673. }
  1674. stack[_STK + 1].setFloat(result);
  1675. _STK++;
  1676. break;
  1677. }
  1678. case Namespace::Entry::VoidCallbackType:
  1679. {
  1680. nsEntry->cb.mVoidCallbackFunc(thisObject, callArgc, callArgv);
  1681. gCallStack.popFrame();
  1682. if (code[ip] == OP_POP_STK)
  1683. {
  1684. ip++;
  1685. break;
  1686. }
  1687. if (Con::getBoolVariable("$Con::warnVoidAssignment", true))
  1688. {
  1689. Con::warnf(ConsoleLogEntry::General, "%s: Call to %s in %s uses result of void function call.", getFileLine(ip - 4), fnName, functionName);
  1690. }
  1691. stack[_STK + 1].setEmptyString();
  1692. _STK++;
  1693. break;
  1694. }
  1695. case Namespace::Entry::BoolCallbackType:
  1696. {
  1697. bool result = nsEntry->cb.mBoolCallbackFunc(thisObject, callArgc, callArgv);
  1698. gCallStack.popFrame();
  1699. if (code[ip] == OP_POP_STK)
  1700. {
  1701. ip++;
  1702. break;
  1703. }
  1704. stack[_STK + 1].setBool(result);
  1705. _STK++;
  1706. break;
  1707. }
  1708. }
  1709. }
  1710. }
  1711. break;
  1712. }
  1713. case OP_ADVANCE_STR_APPENDCHAR:
  1714. {
  1715. char buff[2];
  1716. buff[0] = (char)code[ip++];
  1717. buff[1] = '\0';
  1718. S32 len;
  1719. const char* concat = tsconcat(stack[_STK].getString(), buff, len);
  1720. stack[_STK].setStringRef(concat, len);
  1721. break;
  1722. }
  1723. case OP_REWIND_STR:
  1724. TORQUE_CASE_FALLTHROUGH;
  1725. case OP_TERMINATE_REWIND_STR:
  1726. {
  1727. S32 len;
  1728. const char* concat = tsconcat(stack[_STK - 1].getString(), stack[_STK].getString(), len);
  1729. stack[_STK - 1].setStringRef(concat, len);
  1730. _STK--;
  1731. break;
  1732. }
  1733. case OP_COMPARE_STR:
  1734. stack[_STK - 1].setBool(!dStricmp(stack[_STK].getString(), stack[_STK - 1].getString()));
  1735. _STK--;
  1736. break;
  1737. case OP_PUSH:
  1738. gCallStack.push((stack[_STK--]));
  1739. break;
  1740. case OP_PUSH_FRAME:
  1741. gCallStack.pushFrame(code[ip++]);
  1742. break;
  1743. case OP_ASSERT:
  1744. {
  1745. if (!stack[_STK--].getBool())
  1746. {
  1747. const char* message = curStringTable + code[ip];
  1748. U32 breakLine, inst;
  1749. findBreakLine(ip - 1, breakLine, inst);
  1750. if (PlatformAssert::processAssert(PlatformAssert::Fatal,
  1751. name ? name : "eval",
  1752. breakLine,
  1753. message))
  1754. {
  1755. if (TelDebugger && TelDebugger->isConnected() && breakLine > 0)
  1756. {
  1757. TelDebugger->breakProcess();
  1758. }
  1759. else
  1760. Platform::debugBreak();
  1761. }
  1762. }
  1763. ip++;
  1764. break;
  1765. }
  1766. case OP_BREAK:
  1767. {
  1768. //append the ip and codeptr before managing the breakpoint!
  1769. AssertFatal(!Script::gEvalState.stack.empty(), "Empty eval stack on break!");
  1770. Script::gEvalState.getCurrentFrame().module = this;
  1771. Script::gEvalState.getCurrentFrame().ip = ip - 1;
  1772. U32 breakLine;
  1773. findBreakLine(ip - 1, breakLine, instruction);
  1774. if (!breakLine)
  1775. goto breakContinue;
  1776. TelDebugger->executionStopped(this, breakLine);
  1777. goto breakContinue;
  1778. }
  1779. case OP_ITER_BEGIN_STR:
  1780. {
  1781. iterStack[_ITER].mIsStringIter = true;
  1782. TORQUE_CASE_FALLTHROUGH;
  1783. }
  1784. case OP_ITER_BEGIN:
  1785. {
  1786. bool isGlobal = code[ip];
  1787. U32 failIp = code[ip + (isGlobal ? 3 : 2)];
  1788. IterStackRecord& iter = iterStack[_ITER];
  1789. iter.mIsGlobalVariable = isGlobal;
  1790. if (isGlobal)
  1791. {
  1792. StringTableEntry varName = CodeToSTE(code, ip + 1);
  1793. iter.mVar.mVariable = Con::gGlobalVars.add(varName);
  1794. }
  1795. else
  1796. {
  1797. iter.mVar.mRegister = code[ip + 1];
  1798. }
  1799. if (iter.mIsStringIter)
  1800. {
  1801. iter.mData.mStr.mString = stack[_STK].getString();
  1802. iter.mData.mStr.mIndex = 0;
  1803. }
  1804. else
  1805. {
  1806. // Look up the object.
  1807. SimSet* set;
  1808. if (!Sim::findObject(stack[_STK].getString(), set))
  1809. {
  1810. Con::errorf(ConsoleLogEntry::General, "No SimSet object '%s'", stack[_STK].getString());
  1811. Con::errorf(ConsoleLogEntry::General, "Did you mean to use 'foreach$' instead of 'foreach'?");
  1812. ip = failIp;
  1813. // Pop the iterated value
  1814. _STK--;
  1815. continue;
  1816. }
  1817. // Set up.
  1818. iter.mData.mObj.mSet = set;
  1819. iter.mData.mObj.mIndex = 0;
  1820. }
  1821. _ITER++;
  1822. iterDepth++;
  1823. ip += isGlobal ? 4 : 3;
  1824. break;
  1825. }
  1826. case OP_ITER:
  1827. {
  1828. U32 breakIp = code[ip];
  1829. IterStackRecord& iter = iterStack[_ITER - 1];
  1830. if (iter.mIsStringIter)
  1831. {
  1832. const char* str = iter.mData.mStr.mString;
  1833. U32 startIndex = iter.mData.mStr.mIndex;
  1834. U32 endIndex = startIndex;
  1835. // Break if at end.
  1836. if (!str[startIndex])
  1837. {
  1838. ip = breakIp;
  1839. continue;
  1840. }
  1841. // Find right end of current component.
  1842. if (!dIsspace(str[endIndex]))
  1843. do ++endIndex;
  1844. while (str[endIndex] && !dIsspace(str[endIndex]));
  1845. // Extract component.
  1846. if (endIndex != startIndex)
  1847. {
  1848. char savedChar = str[endIndex];
  1849. const_cast<char*>(str)[endIndex] = '\0'; // We are on the string stack so this is okay.
  1850. if (iter.mIsGlobalVariable)
  1851. iter.mVar.mVariable->setStringValue(&str[startIndex]);
  1852. else
  1853. Script::gEvalState.setLocalStringVariable(iter.mVar.mRegister, &str[startIndex], endIndex - startIndex);
  1854. const_cast<char*>(str)[endIndex] = savedChar;
  1855. }
  1856. else
  1857. {
  1858. if (iter.mIsGlobalVariable)
  1859. iter.mVar.mVariable->setStringValue("");
  1860. else
  1861. Script::gEvalState.setLocalStringVariable(iter.mVar.mRegister, "", 0);
  1862. }
  1863. // Skip separator.
  1864. if (str[endIndex] != '\0')
  1865. ++endIndex;
  1866. iter.mData.mStr.mIndex = endIndex;
  1867. }
  1868. else
  1869. {
  1870. U32 index = iter.mData.mObj.mIndex;
  1871. SimSet* set = iter.mData.mObj.mSet;
  1872. if (index >= set->size())
  1873. {
  1874. ip = breakIp;
  1875. continue;
  1876. }
  1877. SimObjectId id = set->at(index)->getId();
  1878. if (iter.mIsGlobalVariable)
  1879. iter.mVar.mVariable->setIntValue(id);
  1880. else
  1881. Script::gEvalState.setLocalIntVariable(iter.mVar.mRegister, id);
  1882. iter.mData.mObj.mIndex = index + 1;
  1883. }
  1884. ++ip;
  1885. break;
  1886. }
  1887. case OP_ITER_END:
  1888. {
  1889. --_ITER;
  1890. --iterDepth;
  1891. _STK--;
  1892. iterStack[_ITER].mIsStringIter = false;
  1893. break;
  1894. }
  1895. case OP_INVALID:
  1896. TORQUE_CASE_FALLTHROUGH;
  1897. default:
  1898. // error!
  1899. AssertISV(false, "Invalid OPCode Processed!");
  1900. goto execFinished;
  1901. }
  1902. }
  1903. execFinished:
  1904. if (telDebuggerOn && setFrame < 0)
  1905. TelDebugger->popStackFrame();
  1906. if (popFrame)
  1907. {
  1908. Script::gEvalState.popFrame();
  1909. }
  1910. if (argv)
  1911. {
  1912. if (Con::gTraceOn)
  1913. {
  1914. traceBuffer[0] = 0;
  1915. dStrcat(traceBuffer, "Leaving ", TRACE_BUFFER_SIZE);
  1916. if (packageName)
  1917. {
  1918. dStrcat(traceBuffer, "[", TRACE_BUFFER_SIZE);
  1919. dStrcat(traceBuffer, packageName, TRACE_BUFFER_SIZE);
  1920. dStrcat(traceBuffer, "]", TRACE_BUFFER_SIZE);
  1921. }
  1922. if (thisNamespace && thisNamespace->mName)
  1923. {
  1924. dSprintf(traceBuffer + (U32)dStrlen(traceBuffer), sizeof(traceBuffer) - (U32)dStrlen(traceBuffer),
  1925. "%s::%s() - return %s", thisNamespace->mName, thisFunctionName, returnValue.getString());
  1926. }
  1927. else
  1928. {
  1929. dSprintf(traceBuffer + (U32)dStrlen(traceBuffer), sizeof(traceBuffer) - (U32)dStrlen(traceBuffer),
  1930. "%s() - return %s", thisFunctionName, returnValue.getString());
  1931. }
  1932. Con::printf("%s", traceBuffer);
  1933. }
  1934. }
  1935. else
  1936. {
  1937. delete[] const_cast<char*>(globalStrings);
  1938. delete[] globalFloats;
  1939. globalStrings = NULL;
  1940. globalFloats = NULL;
  1941. }
  1942. if (Con::getCurrentScriptModuleName())
  1943. {
  1944. Con::gCurrentFile = Con::getCurrentScriptModuleName();
  1945. Con::gCurrentRoot = Con::getModNameFromPath(Con::getCurrentScriptModulePath());
  1946. }
  1947. decRefCount();
  1948. #ifdef TORQUE_DEBUG
  1949. AssertFatal(!(_STK > stackStart), "String stack not popped enough in script exec");
  1950. AssertFatal(!(_STK < stackStart), "String stack popped too much in script exec");
  1951. #endif
  1952. return Con::EvalResult((returnValue));
  1953. }
  1954. //------------------------------------------------------------