compiledEval.cpp 68 KB

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