compiledEval.cpp 69 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298
  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, std::move(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. U32 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. else
  785. ++Con::gObjectCopyFailures;
  786. delete object;
  787. currentNewObject = NULL;
  788. ip = failJump;
  789. break;
  790. }
  791. }
  792. // If a name was passed, assign it.
  793. if (objectName[0])
  794. {
  795. if (!isInternal)
  796. currentNewObject->assignName(objectName);
  797. else
  798. currentNewObject->setInternalName(objectName);
  799. // Set the original name
  800. currentNewObject->setOriginalName( objectName );
  801. }
  802. // Do the constructor parameters.
  803. if (!currentNewObject->processArguments(callArgc - 3, callArgv + 3))
  804. {
  805. delete currentNewObject;
  806. currentNewObject = NULL;
  807. ip = failJump;
  808. break;
  809. }
  810. // If it's not a datablock, allow people to modify bits of it.
  811. if (!isDataBlock)
  812. {
  813. currentNewObject->setModStaticFields(true);
  814. currentNewObject->setModDynamicFields(true);
  815. }
  816. }
  817. else
  818. {
  819. currentNewObject->reloadReset(); // AFX (reload-reset)
  820. // Does it have a parent object? (ie, the copy constructor : syntax, not inheriance)
  821. if (*objParent)
  822. {
  823. // Find it!
  824. SimObject* parent;
  825. if (Sim::findObject(objParent, parent))
  826. {
  827. // Con::printf(" - Parent object found: %s", parent->getClassName());
  828. // temporarily block name change
  829. SimObject::preventNameChanging = true;
  830. currentNewObject->setCopySource(parent);
  831. currentNewObject->assignFieldsFrom(parent);
  832. // restore name changing
  833. SimObject::preventNameChanging = false;
  834. // copy any substitution statements
  835. SimDataBlock* parent_db = dynamic_cast<SimDataBlock*>(parent);
  836. if (parent_db)
  837. {
  838. SimDataBlock* currentNewObject_db = dynamic_cast<SimDataBlock*>(currentNewObject);
  839. if (currentNewObject_db)
  840. currentNewObject_db->copySubstitutionsFrom(parent_db);
  841. }
  842. }
  843. else
  844. {
  845. Con::errorf(ConsoleLogEntry::General, "%d: Unable to find parent object %s for %s.", lineNumber, objParent, callArgv[1].getString());
  846. }
  847. }
  848. }
  849. // Advance the IP past the create info...
  850. ip += 7;
  851. break;
  852. }
  853. case OP_ADD_OBJECT:
  854. {
  855. // See OP_SETCURVAR for why we do this.
  856. curFNDocBlock = NULL;
  857. curNSDocBlock = NULL;
  858. // Do we place this object at the root?
  859. bool placeAtRoot = code[ip++];
  860. // Con::printf("Adding object %s", currentNewObject->getName());
  861. // Make sure it wasn't already added, then add it.
  862. if (currentNewObject == NULL)
  863. {
  864. break;
  865. }
  866. bool isMessage = dynamic_cast<Message*>(currentNewObject) != NULL;
  867. if (currentNewObject->isProperlyAdded() == false)
  868. {
  869. bool ret = false;
  870. if (isMessage)
  871. {
  872. SimObjectId id = Message::getNextMessageID();
  873. if (id != 0xffffffff)
  874. ret = currentNewObject->registerObject(id);
  875. else
  876. Con::errorf("%s: No more object IDs available for messages", getFileLine(ip));
  877. }
  878. else
  879. ret = currentNewObject->registerObject();
  880. if (!ret)
  881. {
  882. // This error is usually caused by failing to call Parent::initPersistFields in the class' initPersistFields().
  883. Con::warnf(ConsoleLogEntry::General, "%s: Register object failed for object %s of class %s.", getFileLine(ip - 2), currentNewObject->getName(), currentNewObject->getClassName());
  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. dataBlock->deleteObject();
  899. currentNewObject = NULL;
  900. ip = failJump;
  901. break;
  902. }
  903. // What group will we be added to, if any?
  904. U32 groupAddId = (U32)stack[_STK].getInt();
  905. SimGroup* grp = NULL;
  906. SimSet* set = NULL;
  907. if (!placeAtRoot || !currentNewObject->getGroup())
  908. {
  909. if (!isMessage)
  910. {
  911. if (!placeAtRoot)
  912. {
  913. // Otherwise just add to the requested group or set.
  914. if (!Sim::findObject(groupAddId, grp))
  915. Sim::findObject(groupAddId, set);
  916. }
  917. if (placeAtRoot)
  918. {
  919. // Deal with the instantGroup if we're being put at the root or we're adding to a component.
  920. if (Con::gInstantGroup.isEmpty() || !Sim::findObject(Con::gInstantGroup, grp))
  921. grp = Sim::getRootGroup();
  922. }
  923. }
  924. // If we didn't get a group, then make sure we have a pointer to
  925. // the rootgroup.
  926. if (!grp)
  927. grp = Sim::getRootGroup();
  928. // add to the parent group
  929. grp->addObject(currentNewObject);
  930. // If for some reason the add failed, add the object to the
  931. // root group so it won't leak.
  932. if (currentNewObject->getGroup() == NULL)
  933. Sim::getRootGroup()->addObject(currentNewObject);
  934. // add to any set we might be in
  935. if (set)
  936. set->addObject(currentNewObject);
  937. }
  938. // store the new object's ID on the stack (overwriting the group/set
  939. // id, if one was given, otherwise getting pushed)
  940. S32 id = currentNewObject->getId();
  941. if (placeAtRoot)
  942. stack[_STK].setInt(id);
  943. else
  944. stack[++_STK].setInt(id);
  945. break;
  946. }
  947. case OP_END_OBJECT:
  948. {
  949. // If we're not to be placed at the root, make sure we clean up
  950. // our group reference.
  951. bool placeAtRoot = code[ip++];
  952. if (!placeAtRoot)
  953. _STK--;
  954. break;
  955. }
  956. case OP_FINISH_OBJECT:
  957. {
  958. if (currentNewObject)
  959. currentNewObject->onPostAdd();
  960. AssertFatal( objectCreationStackIndex >= 0, "Object Stack is empty." );
  961. // Restore the object info from the stack [7/9/2007 Black]
  962. currentNewObject = objectCreationStack[--objectCreationStackIndex].newObject;
  963. failJump = objectCreationStack[objectCreationStackIndex].failJump;
  964. break;
  965. }
  966. case OP_JMPIFFNOT:
  967. if (stack[_STK--].getFloat())
  968. {
  969. ip++;
  970. break;
  971. }
  972. ip = code[ip];
  973. break;
  974. case OP_JMPIFNOT:
  975. if (stack[_STK--].getInt())
  976. {
  977. ip++;
  978. break;
  979. }
  980. ip = code[ip];
  981. break;
  982. case OP_JMPIFF:
  983. if (!stack[_STK--].getFloat())
  984. {
  985. ip++;
  986. break;
  987. }
  988. ip = code[ip];
  989. break;
  990. case OP_JMPIF:
  991. if (!stack[_STK--].getFloat())
  992. {
  993. ip++;
  994. break;
  995. }
  996. ip = code[ip];
  997. break;
  998. case OP_JMPIFNOT_NP:
  999. if (stack[_STK].getInt())
  1000. {
  1001. _STK--;
  1002. ip++;
  1003. break;
  1004. }
  1005. ip = code[ip];
  1006. break;
  1007. case OP_JMPIF_NP:
  1008. if (!stack[_STK].getInt())
  1009. {
  1010. _STK--;
  1011. ip++;
  1012. break;
  1013. }
  1014. ip = code[ip];
  1015. break;
  1016. case OP_JMP:
  1017. ip = code[ip];
  1018. break;
  1019. case OP_RETURN_VOID:
  1020. {
  1021. if (iterDepth > 0)
  1022. {
  1023. // Clear iterator state.
  1024. while (iterDepth > 0)
  1025. {
  1026. iterStack[--_ITER].mIsStringIter = false;
  1027. --iterDepth;
  1028. _STK--; // this is a pop from foreach()
  1029. }
  1030. }
  1031. returnValue.setEmptyString();
  1032. goto execFinished;
  1033. }
  1034. case OP_RETURN:
  1035. {
  1036. returnValue = std::move(stack[_STK]);
  1037. _STK--;
  1038. // Clear iterator state.
  1039. while (iterDepth > 0)
  1040. {
  1041. iterStack[--_ITER].mIsStringIter = false;
  1042. --iterDepth;
  1043. _STK--;
  1044. }
  1045. goto execFinished;
  1046. }
  1047. case OP_RETURN_FLT:
  1048. returnValue.setFloat(stack[_STK].getFloat());
  1049. _STK--;
  1050. // Clear iterator state.
  1051. while (iterDepth > 0)
  1052. {
  1053. iterStack[--_ITER].mIsStringIter = false;
  1054. --iterDepth;
  1055. _STK--;
  1056. }
  1057. goto execFinished;
  1058. case OP_RETURN_UINT:
  1059. returnValue.setInt(stack[_STK].getInt());
  1060. _STK--;
  1061. // Clear iterator state.
  1062. while (iterDepth > 0)
  1063. {
  1064. iterStack[--_ITER].mIsStringIter = false;
  1065. --iterDepth;
  1066. _STK--;
  1067. }
  1068. goto execFinished;
  1069. case OP_CMPEQ:
  1070. doFloatMathOperation<FloatOperation::EQ>();
  1071. break;
  1072. case OP_CMPGR:
  1073. doFloatMathOperation<FloatOperation::GR>();
  1074. break;
  1075. case OP_CMPGE:
  1076. doFloatMathOperation<FloatOperation::GE>();
  1077. break;
  1078. case OP_CMPLT:
  1079. doFloatMathOperation<FloatOperation::LT>();
  1080. break;
  1081. case OP_CMPLE:
  1082. doFloatMathOperation<FloatOperation::LE>();
  1083. break;
  1084. case OP_CMPNE:
  1085. doFloatMathOperation<FloatOperation::NE>();
  1086. break;
  1087. case OP_XOR:
  1088. doIntOperation<IntegerOperation::Xor>();
  1089. break;
  1090. case OP_BITAND:
  1091. doIntOperation<IntegerOperation::BitAnd>();
  1092. break;
  1093. case OP_BITOR:
  1094. doIntOperation<IntegerOperation::BitOr>();
  1095. break;
  1096. case OP_NOT:
  1097. stack[_STK].setBool(!stack[_STK].getInt());
  1098. break;
  1099. case OP_NOTF:
  1100. stack[_STK].setInt(!stack[_STK].getFloat());
  1101. break;
  1102. case OP_ONESCOMPLEMENT:
  1103. stack[_STK].setInt(~stack[_STK].getInt());
  1104. break;
  1105. case OP_SHR:
  1106. doIntOperation<IntegerOperation::RShift>();
  1107. break;
  1108. case OP_SHL:
  1109. doIntOperation<IntegerOperation::LShift>();
  1110. break;
  1111. case OP_AND:
  1112. doIntOperation<IntegerOperation::LogicalAnd>();
  1113. break;
  1114. case OP_OR:
  1115. doIntOperation<IntegerOperation::LogicalOr>();
  1116. break;
  1117. case OP_ADD:
  1118. doFloatMathOperation<FloatOperation::Add>();
  1119. break;
  1120. case OP_SUB:
  1121. doFloatMathOperation<FloatOperation::Sub>();
  1122. break;
  1123. case OP_MUL:
  1124. doFloatMathOperation<FloatOperation::Mul>();
  1125. break;
  1126. case OP_DIV:
  1127. doFloatMathOperation<FloatOperation::Div>();
  1128. break;
  1129. case OP_MOD:
  1130. {
  1131. S64 divisor = stack[_STK - 1].getInt();
  1132. if (divisor != 0)
  1133. stack[_STK - 1].setInt(stack[_STK].getInt() % divisor);
  1134. else
  1135. stack[_STK - 1].setInt(0);
  1136. _STK--;
  1137. break;
  1138. }
  1139. case OP_NEG:
  1140. stack[_STK].setFloat(-stack[_STK].getFloat());
  1141. break;
  1142. case OP_INC:
  1143. reg = code[ip++];
  1144. currentRegister = reg;
  1145. Script::gEvalState.setLocalFloatVariable(reg, Script::gEvalState.getLocalFloatVariable(reg) + 1.0);
  1146. break;
  1147. case OP_SETCURVAR:
  1148. var = CodeToSTE(code, ip);
  1149. ip += 2;
  1150. // If a variable is set, then these must be NULL. It is necessary
  1151. // to set this here so that the vector parser can appropriately
  1152. // identify whether it's dealing with a vector.
  1153. prevField = NULL;
  1154. prevObject = NULL;
  1155. curObject = NULL;
  1156. // Used for local variable caching of what is active...when we
  1157. // set a global, we aren't active
  1158. currentRegister = -1;
  1159. Script::gEvalState.setCurVarName(var);
  1160. // In order to let docblocks work properly with variables, we have
  1161. // clear the current docblock when we do an assign. This way it
  1162. // won't inappropriately carry forward to following function decls.
  1163. curFNDocBlock = NULL;
  1164. curNSDocBlock = NULL;
  1165. break;
  1166. case OP_SETCURVAR_CREATE:
  1167. var = CodeToSTE(code, ip);
  1168. ip += 2;
  1169. // See OP_SETCURVAR
  1170. prevField = NULL;
  1171. prevObject = NULL;
  1172. curObject = NULL;
  1173. // Used for local variable caching of what is active...when we
  1174. // set a global, we aren't active
  1175. currentRegister = -1;
  1176. Script::gEvalState.setCurVarNameCreate(var);
  1177. // See OP_SETCURVAR for why we do this.
  1178. curFNDocBlock = NULL;
  1179. curNSDocBlock = NULL;
  1180. break;
  1181. case OP_SETCURVAR_ARRAY:
  1182. var = StringTable->insert(stack[_STK].getString());
  1183. // See OP_SETCURVAR
  1184. prevField = NULL;
  1185. prevObject = NULL;
  1186. curObject = NULL;
  1187. // Used for local variable caching of what is active...when we
  1188. // set a global, we aren't active
  1189. currentRegister = -1;
  1190. Script::gEvalState.setCurVarName(var);
  1191. // See OP_SETCURVAR for why we do this.
  1192. curFNDocBlock = NULL;
  1193. curNSDocBlock = NULL;
  1194. break;
  1195. case OP_SETCURVAR_ARRAY_CREATE:
  1196. var = StringTable->insert(stack[_STK].getString());
  1197. // See OP_SETCURVAR
  1198. prevField = NULL;
  1199. prevObject = NULL;
  1200. curObject = NULL;
  1201. // Used for local variable caching of what is active...when we
  1202. // set a global, we aren't active
  1203. currentRegister = -1;
  1204. Script::gEvalState.setCurVarNameCreate(var);
  1205. // See OP_SETCURVAR for why we do this.
  1206. curFNDocBlock = NULL;
  1207. curNSDocBlock = NULL;
  1208. break;
  1209. case OP_LOADVAR_UINT:
  1210. currentRegister = -1;
  1211. stack[_STK + 1].setInt(Script::gEvalState.getIntVariable());
  1212. _STK++;
  1213. break;
  1214. case OP_LOADVAR_FLT:
  1215. currentRegister = -1;
  1216. stack[_STK + 1].setFloat(Script::gEvalState.getFloatVariable());
  1217. _STK++;
  1218. break;
  1219. case OP_LOADVAR_STR:
  1220. currentRegister = -1;
  1221. stack[_STK + 1].setString(Script::gEvalState.getStringVariable());
  1222. _STK++;
  1223. break;
  1224. case OP_SAVEVAR_UINT:
  1225. Script::gEvalState.setIntVariable(stack[_STK].getInt());
  1226. break;
  1227. case OP_SAVEVAR_FLT:
  1228. Script::gEvalState.setFloatVariable(stack[_STK].getFloat());
  1229. break;
  1230. case OP_SAVEVAR_STR:
  1231. Script::gEvalState.setStringVariable(stack[_STK].getString());
  1232. break;
  1233. case OP_LOAD_LOCAL_VAR_UINT:
  1234. reg = code[ip++];
  1235. currentRegister = reg;
  1236. // See OP_SETCURVAR
  1237. prevField = NULL;
  1238. prevObject = NULL;
  1239. curObject = NULL;
  1240. stack[_STK + 1].setInt(Script::gEvalState.getLocalIntVariable(reg));
  1241. _STK++;
  1242. break;
  1243. case OP_LOAD_LOCAL_VAR_FLT:
  1244. reg = code[ip++];
  1245. currentRegister = reg;
  1246. // See OP_SETCURVAR
  1247. prevField = NULL;
  1248. prevObject = NULL;
  1249. curObject = NULL;
  1250. stack[_STK + 1].setFloat(Script::gEvalState.getLocalFloatVariable(reg));
  1251. _STK++;
  1252. break;
  1253. case OP_LOAD_LOCAL_VAR_STR:
  1254. reg = code[ip++];
  1255. currentRegister = reg;
  1256. // See OP_SETCURVAR
  1257. prevField = NULL;
  1258. prevObject = NULL;
  1259. curObject = NULL;
  1260. val = Script::gEvalState.getLocalStringVariable(reg);
  1261. stack[_STK + 1].setString(val);
  1262. _STK++;
  1263. break;
  1264. case OP_SAVE_LOCAL_VAR_UINT:
  1265. reg = code[ip++];
  1266. currentRegister = reg;
  1267. // See OP_SETCURVAR
  1268. prevField = NULL;
  1269. prevObject = NULL;
  1270. curObject = NULL;
  1271. Script::gEvalState.setLocalIntVariable(reg, stack[_STK].getInt());
  1272. break;
  1273. case OP_SAVE_LOCAL_VAR_FLT:
  1274. reg = code[ip++];
  1275. currentRegister = reg;
  1276. // See OP_SETCURVAR
  1277. prevField = NULL;
  1278. prevObject = NULL;
  1279. curObject = NULL;
  1280. Script::gEvalState.setLocalFloatVariable(reg, stack[_STK].getFloat());
  1281. break;
  1282. case OP_SAVE_LOCAL_VAR_STR:
  1283. reg = code[ip++];
  1284. val = stack[_STK].getString();
  1285. currentRegister = reg;
  1286. // See OP_SETCURVAR
  1287. prevField = NULL;
  1288. prevObject = NULL;
  1289. curObject = NULL;
  1290. Script::gEvalState.setLocalStringVariable(reg, val, (S32)dStrlen(val));
  1291. break;
  1292. case OP_SETCUROBJECT:
  1293. // Save the previous object for parsing vector fields.
  1294. prevObject = curObject;
  1295. val = stack[_STK].getString();
  1296. // Sim::findObject will sometimes find valid objects from
  1297. // multi-component strings. This makes sure that doesn't
  1298. // happen.
  1299. for (const char* check = val; *check; check++)
  1300. {
  1301. if (*check == ' ')
  1302. {
  1303. val = "";
  1304. break;
  1305. }
  1306. }
  1307. curObject = Sim::findObject(val);
  1308. break;
  1309. case OP_SETCUROBJECT_INTERNAL:
  1310. ++ip; // To skip the recurse flag if the object wasnt found
  1311. if (curObject)
  1312. {
  1313. SimSet* set = dynamic_cast<SimSet*>(curObject);
  1314. if (set)
  1315. {
  1316. StringTableEntry intName = StringTable->insert(stack[_STK].getString());
  1317. bool recurse = code[ip - 1];
  1318. SimObject* obj = set->findObjectByInternalName(intName, recurse);
  1319. stack[_STK].setInt(obj ? obj->getId() : 0);
  1320. }
  1321. else
  1322. {
  1323. Con::errorf(ConsoleLogEntry::Script, "%s: Attempt to use -> on non-set %s of class %s.", getFileLine(ip - 2), curObject->getName(), curObject->getClassName());
  1324. stack[_STK].setInt(0);
  1325. }
  1326. }
  1327. else
  1328. {
  1329. Con::errorf(ConsoleLogEntry::Script, "%s: Attempt to use ->, but the group object wasn't found.", getFileLine(ip - 2));
  1330. stack[_STK].setInt(0);
  1331. }
  1332. break;
  1333. case OP_SETCUROBJECT_NEW:
  1334. curObject = currentNewObject;
  1335. break;
  1336. case OP_SETCURFIELD:
  1337. // Save the previous field for parsing vector fields.
  1338. prevField = curField;
  1339. dStrcpy(prevFieldArray, curFieldArray, 256);
  1340. curField = CodeToSTE(code, ip);
  1341. curFieldArray[0] = 0;
  1342. ip += 2;
  1343. break;
  1344. case OP_SETCURFIELD_ARRAY:
  1345. dStrcpy(curFieldArray, stack[_STK].getString(), 256);
  1346. break;
  1347. case OP_SETCURFIELD_TYPE:
  1348. if(curObject)
  1349. curObject->setDataFieldType(code[ip], curField, curFieldArray);
  1350. ip++;
  1351. break;
  1352. case OP_LOADFIELD_UINT:
  1353. if (curObject)
  1354. stack[_STK + 1].setInt(dAtol(curObject->getDataField(curField, curFieldArray)));
  1355. else
  1356. {
  1357. // The field is not being retrieved from an object. Maybe it's
  1358. // a special accessor?
  1359. char buff[FieldBufferSizeNumeric];
  1360. memset(buff, 0, sizeof(buff));
  1361. getFieldComponent(prevObject, prevField, prevFieldArray, curField, buff, currentRegister);
  1362. stack[_STK + 1].setInt(dAtol(buff));
  1363. }
  1364. _STK++;
  1365. break;
  1366. case OP_LOADFIELD_FLT:
  1367. if (curObject)
  1368. stack[_STK + 1].setFloat(dAtod(curObject->getDataField(curField, curFieldArray)));
  1369. else
  1370. {
  1371. // The field is not being retrieved from an object. Maybe it's
  1372. // a special accessor?
  1373. char buff[FieldBufferSizeNumeric];
  1374. memset(buff, 0, sizeof(buff));
  1375. getFieldComponent(prevObject, prevField, prevFieldArray, curField, buff, currentRegister);
  1376. stack[_STK + 1].setFloat(dAtod(buff));
  1377. }
  1378. _STK++;
  1379. break;
  1380. case OP_LOADFIELD_STR:
  1381. if (curObject)
  1382. {
  1383. val = curObject->getDataField(curField, curFieldArray);
  1384. stack[_STK + 1].setString(val);
  1385. }
  1386. else
  1387. {
  1388. // The field is not being retrieved from an object. Maybe it's
  1389. // a special accessor?
  1390. char buff[FieldBufferSizeString];
  1391. memset(buff, 0, sizeof(buff));
  1392. getFieldComponent(prevObject, prevField, prevFieldArray, curField, buff, currentRegister);
  1393. stack[_STK + 1].setString(buff);
  1394. }
  1395. _STK++;
  1396. break;
  1397. case OP_SAVEFIELD_UINT:
  1398. if (curObject)
  1399. curObject->setDataField(curField, curFieldArray, stack[_STK].getString());
  1400. else
  1401. {
  1402. // The field is not being set on an object. Maybe it's a special accessor?
  1403. setFieldComponent(prevObject, prevField, prevFieldArray, curField, currentRegister);
  1404. prevObject = NULL;
  1405. }
  1406. break;
  1407. case OP_SAVEFIELD_FLT:
  1408. if (curObject)
  1409. curObject->setDataField(curField, curFieldArray, stack[_STK].getString());
  1410. else
  1411. {
  1412. // The field is not being set on an object. Maybe it's a special accessor?
  1413. setFieldComponent(prevObject, prevField, prevFieldArray, curField, currentRegister);
  1414. prevObject = NULL;
  1415. }
  1416. break;
  1417. case OP_SAVEFIELD_STR:
  1418. if (curObject)
  1419. curObject->setDataField(curField, curFieldArray, stack[_STK].getString());
  1420. else
  1421. {
  1422. // The field is not being set on an object. Maybe it's a special accessor?
  1423. setFieldComponent(prevObject, prevField, prevFieldArray, curField, currentRegister);
  1424. prevObject = NULL;
  1425. }
  1426. break;
  1427. case OP_POP_STK:
  1428. _STK--;
  1429. break;
  1430. case OP_LOADIMMED_UINT:
  1431. stack[_STK + 1].setInt(code[ip++]);
  1432. _STK++;
  1433. break;
  1434. case OP_LOADIMMED_FLT:
  1435. stack[_STK + 1].setFloat(curFloatTable[code[ip++]]);
  1436. _STK++;
  1437. break;
  1438. case OP_TAG_TO_STR:
  1439. code[ip - 1] = OP_LOADIMMED_STR;
  1440. // it's possible the string has already been converted
  1441. if (U8(curStringTable[code[ip]]) != StringTagPrefixByte)
  1442. {
  1443. U32 id = GameAddTaggedString(curStringTable + code[ip]);
  1444. dSprintf(curStringTable + code[ip] + 1, 7, "%d", id);
  1445. *(curStringTable + code[ip]) = StringTagPrefixByte;
  1446. }
  1447. TORQUE_CASE_FALLTHROUGH;
  1448. case OP_LOADIMMED_STR:
  1449. stack[_STK + 1].setString(curStringTable + code[ip++]);
  1450. _STK ++;
  1451. break;
  1452. case OP_DOCBLOCK_STR:
  1453. {
  1454. // If the first word of the doc is '\class' or '@class', then this
  1455. // is a namespace doc block, otherwise it is a function doc block.
  1456. const char* docblock = curStringTable + code[ip++];
  1457. const char* sansClass = dStrstr(docblock, "@class");
  1458. if (!sansClass)
  1459. sansClass = dStrstr(docblock, "\\class");
  1460. if (sansClass)
  1461. {
  1462. // Don't save the class declaration. Scan past the 'class'
  1463. // keyword and up to the first whitespace.
  1464. sansClass += 7;
  1465. S32 index = 0;
  1466. while ((*sansClass != ' ') && (*sansClass != '\n') && *sansClass && (index < (nsDocLength - 1)))
  1467. {
  1468. nsDocBlockClass[index++] = *sansClass;
  1469. sansClass++;
  1470. }
  1471. nsDocBlockClass[index] = '\0';
  1472. curNSDocBlock = sansClass + 1;
  1473. }
  1474. else
  1475. curFNDocBlock = docblock;
  1476. }
  1477. break;
  1478. case OP_LOADIMMED_IDENT:
  1479. stack[_STK + 1].setString(CodeToSTE(code, ip));
  1480. _STK++;
  1481. ip += 2;
  1482. break;
  1483. case OP_CALLFUNC:
  1484. {
  1485. // This routingId is set when we query the object as to whether
  1486. // it handles this method. It is set to an enum from the table
  1487. // above indicating whether it handles it on a component it owns
  1488. // or just on the object.
  1489. fnName = CodeToSTE(code, ip);
  1490. fnNamespace = CodeToSTE(code, ip + 2);
  1491. U32 callType = code[ip + 4];
  1492. //if this is called from inside a function, append the ip and codeptr
  1493. if (!Script::gEvalState.stack.empty())
  1494. {
  1495. Script::gEvalState.getCurrentFrame().module = this;
  1496. Script::gEvalState.getCurrentFrame().ip = ip - 1;
  1497. }
  1498. ip += 5;
  1499. gCallStack.argvc(fnName, callArgc, &callArgv);
  1500. if (callType == FuncCallExprNode::FunctionCall)
  1501. {
  1502. // Note: This works even if the function was in a package. Reason being is when
  1503. // activatePackage() is called, it swaps the namespaceEntry into the global namespace
  1504. // (and reverts it when deactivatePackage is called). Method or Static related ones work
  1505. // as expected, as the namespace is resolved on the fly.
  1506. nsEntry = Namespace::global()->lookup(fnName);
  1507. if (!nsEntry)
  1508. {
  1509. Con::warnf(ConsoleLogEntry::General,
  1510. "%s: Unable to find function %s",
  1511. getFileLine(ip - 4), fnName);
  1512. gCallStack.popFrame();
  1513. stack[_STK + 1].setEmptyString();
  1514. _STK++;
  1515. break;
  1516. }
  1517. }
  1518. else if (callType == FuncCallExprNode::StaticCall)
  1519. {
  1520. // Try to look it up.
  1521. ns = Namespace::find(fnNamespace);
  1522. nsEntry = ns->lookup(fnName);
  1523. if (!nsEntry)
  1524. {
  1525. Con::warnf(ConsoleLogEntry::General,
  1526. "%s: Unable to find function %s%s%s",
  1527. getFileLine(ip - 4), fnNamespace ? fnNamespace : "",
  1528. fnNamespace ? "::" : "", fnName);
  1529. gCallStack.popFrame();
  1530. stack[_STK + 1].setEmptyString();
  1531. _STK++;
  1532. break;
  1533. }
  1534. }
  1535. else if (callType == FuncCallExprNode::MethodCall)
  1536. {
  1537. ConsoleValue& simObjectLookupValue = callArgv[1];
  1538. thisObject = getThisObject(simObjectLookupValue);
  1539. if (thisObject == NULL)
  1540. {
  1541. Con::warnf(
  1542. ConsoleLogEntry::General,
  1543. "%s: Unable to find object: '%s' attempting to call function '%s'",
  1544. getFileLine(ip - 6),
  1545. simObjectLookupValue.getString(),
  1546. fnName
  1547. );
  1548. gCallStack.popFrame();
  1549. stack[_STK + 1].setEmptyString();
  1550. _STK++;
  1551. break;
  1552. }
  1553. ns = thisObject->getNamespace();
  1554. if (ns)
  1555. nsEntry = ns->lookup(fnName);
  1556. else
  1557. nsEntry = NULL;
  1558. }
  1559. else // it's a ParentCall
  1560. {
  1561. ConsoleValue& simObjectLookupValue = callArgv[1];
  1562. thisObject = getThisObject(simObjectLookupValue);
  1563. if (thisObject == NULL)
  1564. {
  1565. Con::warnf(
  1566. ConsoleLogEntry::General,
  1567. "%s: Unable to find object: '%s' attempting to call function '%s'",
  1568. getFileLine(ip - 6),
  1569. simObjectLookupValue.getString(),
  1570. fnName
  1571. );
  1572. gCallStack.popFrame();
  1573. stack[_STK + 1].setEmptyString();
  1574. _STK++;
  1575. break;
  1576. }
  1577. if (thisNamespace)
  1578. {
  1579. ns = thisNamespace->mParent;
  1580. if (ns)
  1581. nsEntry = ns->lookup(fnName);
  1582. else
  1583. nsEntry = NULL;
  1584. }
  1585. else
  1586. {
  1587. ns = NULL;
  1588. nsEntry = NULL;
  1589. }
  1590. }
  1591. if (!nsEntry || noCalls)
  1592. {
  1593. if (!noCalls)
  1594. {
  1595. Con::warnf(ConsoleLogEntry::General, "%s: Unknown command %s.", getFileLine(ip - 4), fnName);
  1596. if (callType == FuncCallExprNode::MethodCall)
  1597. {
  1598. Con::warnf(ConsoleLogEntry::General, " Object %s(%d) %s",
  1599. thisObject->getName() ? thisObject->getName() : "",
  1600. thisObject->getId(), Con::getNamespaceList(ns));
  1601. }
  1602. }
  1603. gCallStack.popFrame();
  1604. stack[_STK + 1].setEmptyString();
  1605. _STK++;
  1606. break;
  1607. }
  1608. if (nsEntry->mType == Namespace::Entry::ConsoleFunctionType)
  1609. {
  1610. if (nsEntry->mFunctionOffset)
  1611. {
  1612. ConsoleValue returnFromFn = nsEntry->mModule->exec(nsEntry->mFunctionOffset, fnName, nsEntry->mNamespace, callArgc, callArgv, false, nsEntry->mPackage).value;
  1613. stack[_STK + 1] = std::move(returnFromFn);
  1614. }
  1615. else // no body
  1616. stack[_STK + 1].setEmptyString();
  1617. _STK++;
  1618. gCallStack.popFrame();
  1619. }
  1620. else
  1621. {
  1622. if ((nsEntry->mMinArgs && S32(callArgc) < nsEntry->mMinArgs) || (nsEntry->mMaxArgs && S32(callArgc) > nsEntry->mMaxArgs))
  1623. {
  1624. const char* nsName = ns ? ns->mName : "";
  1625. Con::warnf(ConsoleLogEntry::Script, "%s: %s::%s - wrong number of arguments.", getFileLine(ip - 4), nsName, fnName);
  1626. Con::warnf(ConsoleLogEntry::Script, "%s: usage: %s", getFileLine(ip - 4), nsEntry->mUsage);
  1627. gCallStack.popFrame();
  1628. stack[_STK + 1].setEmptyString();
  1629. _STK++;
  1630. }
  1631. else
  1632. {
  1633. switch (nsEntry->mType)
  1634. {
  1635. case Namespace::Entry::StringCallbackType:
  1636. {
  1637. const char* result = nsEntry->cb.mStringCallbackFunc(thisObject, callArgc, callArgv);
  1638. gCallStack.popFrame();
  1639. stack[_STK + 1].setString(result);
  1640. _STK++;
  1641. break;
  1642. }
  1643. case Namespace::Entry::IntCallbackType:
  1644. {
  1645. S64 result = nsEntry->cb.mIntCallbackFunc(thisObject, callArgc, callArgv);
  1646. gCallStack.popFrame();
  1647. if (code[ip] == OP_POP_STK)
  1648. {
  1649. ip++;
  1650. break;
  1651. }
  1652. stack[_STK + 1].setInt(result);
  1653. _STK++;
  1654. break;
  1655. }
  1656. case Namespace::Entry::FloatCallbackType:
  1657. {
  1658. F64 result = nsEntry->cb.mFloatCallbackFunc(thisObject, callArgc, callArgv);
  1659. gCallStack.popFrame();
  1660. if (code[ip] == OP_POP_STK)
  1661. {
  1662. ip++;
  1663. break;
  1664. }
  1665. stack[_STK + 1].setFloat(result);
  1666. _STK++;
  1667. break;
  1668. }
  1669. case Namespace::Entry::VoidCallbackType:
  1670. {
  1671. nsEntry->cb.mVoidCallbackFunc(thisObject, callArgc, callArgv);
  1672. gCallStack.popFrame();
  1673. if (code[ip] == OP_POP_STK)
  1674. {
  1675. ip++;
  1676. break;
  1677. }
  1678. if (Con::getBoolVariable("$Con::warnVoidAssignment", true))
  1679. {
  1680. Con::warnf(ConsoleLogEntry::General, "%s: Call to %s in %s uses result of void function call.", getFileLine(ip - 4), fnName, functionName);
  1681. }
  1682. stack[_STK + 1].setEmptyString();
  1683. _STK++;
  1684. break;
  1685. }
  1686. case Namespace::Entry::BoolCallbackType:
  1687. {
  1688. bool result = nsEntry->cb.mBoolCallbackFunc(thisObject, callArgc, callArgv);
  1689. gCallStack.popFrame();
  1690. if (code[ip] == OP_POP_STK)
  1691. {
  1692. ip++;
  1693. break;
  1694. }
  1695. stack[_STK + 1].setBool(result);
  1696. _STK++;
  1697. break;
  1698. }
  1699. }
  1700. }
  1701. }
  1702. break;
  1703. }
  1704. case OP_ADVANCE_STR_APPENDCHAR:
  1705. {
  1706. char buff[2];
  1707. buff[0] = (char)code[ip++];
  1708. buff[1] = '\0';
  1709. S32 len;
  1710. const char* concat = tsconcat(stack[_STK].getString(), buff, len);
  1711. stack[_STK].setStringRef(concat, len);
  1712. break;
  1713. }
  1714. case OP_REWIND_STR:
  1715. TORQUE_CASE_FALLTHROUGH;
  1716. case OP_TERMINATE_REWIND_STR:
  1717. {
  1718. S32 len;
  1719. const char* concat = tsconcat(stack[_STK - 1].getString(), stack[_STK].getString(), len);
  1720. stack[_STK - 1].setStringRef(concat, len);
  1721. _STK--;
  1722. break;
  1723. }
  1724. case OP_COMPARE_STR:
  1725. stack[_STK - 1].setBool(!dStricmp(stack[_STK].getString(), stack[_STK - 1].getString()));
  1726. _STK--;
  1727. break;
  1728. case OP_PUSH:
  1729. gCallStack.push(std::move(stack[_STK--]));
  1730. break;
  1731. case OP_PUSH_FRAME:
  1732. gCallStack.pushFrame(code[ip++]);
  1733. break;
  1734. case OP_ASSERT:
  1735. {
  1736. if (!stack[_STK--].getBool())
  1737. {
  1738. const char* message = curStringTable + code[ip];
  1739. U32 breakLine, inst;
  1740. findBreakLine(ip - 1, breakLine, inst);
  1741. if (PlatformAssert::processAssert(PlatformAssert::Fatal,
  1742. name ? name : "eval",
  1743. breakLine,
  1744. message))
  1745. {
  1746. if (TelDebugger && TelDebugger->isConnected() && breakLine > 0)
  1747. {
  1748. TelDebugger->breakProcess();
  1749. }
  1750. else
  1751. Platform::debugBreak();
  1752. }
  1753. }
  1754. ip++;
  1755. break;
  1756. }
  1757. case OP_BREAK:
  1758. {
  1759. //append the ip and codeptr before managing the breakpoint!
  1760. AssertFatal(!Script::gEvalState.stack.empty(), "Empty eval stack on break!");
  1761. Script::gEvalState.getCurrentFrame().module = this;
  1762. Script::gEvalState.getCurrentFrame().ip = ip - 1;
  1763. U32 breakLine;
  1764. findBreakLine(ip - 1, breakLine, instruction);
  1765. if (!breakLine)
  1766. goto breakContinue;
  1767. TelDebugger->executionStopped(this, breakLine);
  1768. goto breakContinue;
  1769. }
  1770. case OP_ITER_BEGIN_STR:
  1771. {
  1772. iterStack[_ITER].mIsStringIter = true;
  1773. TORQUE_CASE_FALLTHROUGH;
  1774. }
  1775. case OP_ITER_BEGIN:
  1776. {
  1777. bool isGlobal = code[ip];
  1778. U32 failIp = code[ip + (isGlobal ? 3 : 2)];
  1779. IterStackRecord& iter = iterStack[_ITER];
  1780. iter.mIsGlobalVariable = isGlobal;
  1781. if (isGlobal)
  1782. {
  1783. StringTableEntry varName = CodeToSTE(code, ip + 1);
  1784. iter.mVar.mVariable = Con::gGlobalVars.add(varName);
  1785. }
  1786. else
  1787. {
  1788. iter.mVar.mRegister = code[ip + 1];
  1789. }
  1790. if (iter.mIsStringIter)
  1791. {
  1792. iter.mData.mStr.mString = stack[_STK].getString();
  1793. iter.mData.mStr.mIndex = 0;
  1794. }
  1795. else
  1796. {
  1797. // Look up the object.
  1798. SimSet* set;
  1799. if (!Sim::findObject(stack[_STK].getString(), set))
  1800. {
  1801. Con::errorf(ConsoleLogEntry::General, "No SimSet object '%s'", stack[_STK].getString());
  1802. Con::errorf(ConsoleLogEntry::General, "Did you mean to use 'foreach$' instead of 'foreach'?");
  1803. ip = failIp;
  1804. continue;
  1805. }
  1806. // Set up.
  1807. iter.mData.mObj.mSet = set;
  1808. iter.mData.mObj.mIndex = 0;
  1809. }
  1810. _ITER++;
  1811. iterDepth++;
  1812. ip += isGlobal ? 4 : 3;
  1813. break;
  1814. }
  1815. case OP_ITER:
  1816. {
  1817. U32 breakIp = code[ip];
  1818. IterStackRecord& iter = iterStack[_ITER - 1];
  1819. if (iter.mIsStringIter)
  1820. {
  1821. const char* str = iter.mData.mStr.mString;
  1822. U32 startIndex = iter.mData.mStr.mIndex;
  1823. U32 endIndex = startIndex;
  1824. // Break if at end.
  1825. if (!str[startIndex])
  1826. {
  1827. ip = breakIp;
  1828. continue;
  1829. }
  1830. // Find right end of current component.
  1831. if (!dIsspace(str[endIndex]))
  1832. do ++endIndex;
  1833. while (str[endIndex] && !dIsspace(str[endIndex]));
  1834. // Extract component.
  1835. if (endIndex != startIndex)
  1836. {
  1837. char savedChar = str[endIndex];
  1838. const_cast<char*>(str)[endIndex] = '\0'; // We are on the string stack so this is okay.
  1839. if (iter.mIsGlobalVariable)
  1840. iter.mVar.mVariable->setStringValue(&str[startIndex]);
  1841. else
  1842. Script::gEvalState.setLocalStringVariable(iter.mVar.mRegister, &str[startIndex], endIndex - startIndex);
  1843. const_cast<char*>(str)[endIndex] = savedChar;
  1844. }
  1845. else
  1846. {
  1847. if (iter.mIsGlobalVariable)
  1848. iter.mVar.mVariable->setStringValue("");
  1849. else
  1850. Script::gEvalState.setLocalStringVariable(iter.mVar.mRegister, "", 0);
  1851. }
  1852. // Skip separator.
  1853. if (str[endIndex] != '\0')
  1854. ++endIndex;
  1855. iter.mData.mStr.mIndex = endIndex;
  1856. }
  1857. else
  1858. {
  1859. U32 index = iter.mData.mObj.mIndex;
  1860. SimSet* set = iter.mData.mObj.mSet;
  1861. if (index >= set->size())
  1862. {
  1863. ip = breakIp;
  1864. continue;
  1865. }
  1866. SimObjectId id = set->at(index)->getId();
  1867. if (iter.mIsGlobalVariable)
  1868. iter.mVar.mVariable->setIntValue(id);
  1869. else
  1870. Script::gEvalState.setLocalIntVariable(iter.mVar.mRegister, id);
  1871. iter.mData.mObj.mIndex = index + 1;
  1872. }
  1873. ++ip;
  1874. break;
  1875. }
  1876. case OP_ITER_END:
  1877. {
  1878. --_ITER;
  1879. --iterDepth;
  1880. _STK--;
  1881. iterStack[_ITER].mIsStringIter = false;
  1882. break;
  1883. }
  1884. case OP_INVALID:
  1885. TORQUE_CASE_FALLTHROUGH;
  1886. default:
  1887. // error!
  1888. AssertISV(false, "Invalid OPCode Processed!");
  1889. goto execFinished;
  1890. }
  1891. }
  1892. execFinished:
  1893. if (telDebuggerOn && setFrame < 0)
  1894. TelDebugger->popStackFrame();
  1895. if (popFrame)
  1896. {
  1897. Script::gEvalState.popFrame();
  1898. }
  1899. if (argv)
  1900. {
  1901. if (Con::gTraceOn)
  1902. {
  1903. traceBuffer[0] = 0;
  1904. dStrcat(traceBuffer, "Leaving ", TRACE_BUFFER_SIZE);
  1905. if (packageName)
  1906. {
  1907. dStrcat(traceBuffer, "[", TRACE_BUFFER_SIZE);
  1908. dStrcat(traceBuffer, packageName, TRACE_BUFFER_SIZE);
  1909. dStrcat(traceBuffer, "]", TRACE_BUFFER_SIZE);
  1910. }
  1911. if (thisNamespace && thisNamespace->mName)
  1912. {
  1913. dSprintf(traceBuffer + (U32)dStrlen(traceBuffer), sizeof(traceBuffer) - (U32)dStrlen(traceBuffer),
  1914. "%s::%s() - return %s", thisNamespace->mName, thisFunctionName, returnValue.getString());
  1915. }
  1916. else
  1917. {
  1918. dSprintf(traceBuffer + (U32)dStrlen(traceBuffer), sizeof(traceBuffer) - (U32)dStrlen(traceBuffer),
  1919. "%s() - return %s", thisFunctionName, returnValue.getString());
  1920. }
  1921. Con::printf("%s", traceBuffer);
  1922. }
  1923. }
  1924. else
  1925. {
  1926. delete[] const_cast<char*>(globalStrings);
  1927. delete[] globalFloats;
  1928. globalStrings = NULL;
  1929. globalFloats = NULL;
  1930. }
  1931. if (Con::getCurrentScriptModuleName())
  1932. {
  1933. Con::gCurrentFile = Con::getCurrentScriptModuleName();
  1934. Con::gCurrentRoot = Con::getModNameFromPath(Con::getCurrentScriptModulePath());
  1935. }
  1936. decRefCount();
  1937. #ifdef TORQUE_DEBUG
  1938. AssertFatal(!(_STK > stackStart), "String stack not popped enough in script exec");
  1939. AssertFatal(!(_STK < stackStart), "String stack popped too much in script exec");
  1940. #endif
  1941. return Con::EvalResult(std::move(returnValue));
  1942. }
  1943. //------------------------------------------------------------