compiledEval.cpp 69 KB

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