compiledEval.cpp 70 KB

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