compiledEval.cpp 70 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331
  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. }
  1088. _STK--; // this is a pop from foreach()
  1089. }
  1090. returnValue.setEmptyString();
  1091. goto execFinished;
  1092. }
  1093. case OP_RETURN:
  1094. {
  1095. if (iterDepth > 0)
  1096. {
  1097. // Clear iterator state.
  1098. while (iterDepth > 0)
  1099. {
  1100. iterStack[--_ITER].mIsStringIter = false;
  1101. --iterDepth;
  1102. }
  1103. const char* retVal = stack[_STK].getString();
  1104. _STK--;
  1105. _STK--;
  1106. stack[_STK + 1].setString(retVal);
  1107. _STK++; // Not nice but works.
  1108. }
  1109. returnValue = std::move(stack[_STK]);
  1110. _STK--;
  1111. goto execFinished;
  1112. }
  1113. case OP_RETURN_FLT:
  1114. if (iterDepth > 0)
  1115. {
  1116. // Clear iterator state.
  1117. while (iterDepth > 0)
  1118. {
  1119. iterStack[--_ITER].mIsStringIter = false;
  1120. --iterDepth;
  1121. }
  1122. }
  1123. returnValue.setFloat(stack[_STK].getFloat());
  1124. _STK--;
  1125. goto execFinished;
  1126. case OP_RETURN_UINT:
  1127. if (iterDepth > 0)
  1128. {
  1129. // Clear iterator state.
  1130. while (iterDepth > 0)
  1131. {
  1132. iterStack[--_ITER].mIsStringIter = false;
  1133. --iterDepth;
  1134. }
  1135. }
  1136. returnValue.setInt(stack[_STK].getInt());
  1137. _STK--;
  1138. goto execFinished;
  1139. case OP_CMPEQ:
  1140. doFloatMathOperation<FloatOperation::EQ>();
  1141. break;
  1142. case OP_CMPGR:
  1143. doFloatMathOperation<FloatOperation::GR>();
  1144. break;
  1145. case OP_CMPGE:
  1146. doFloatMathOperation<FloatOperation::GE>();
  1147. break;
  1148. case OP_CMPLT:
  1149. doFloatMathOperation<FloatOperation::LT>();
  1150. break;
  1151. case OP_CMPLE:
  1152. doFloatMathOperation<FloatOperation::LE>();
  1153. break;
  1154. case OP_CMPNE:
  1155. doFloatMathOperation<FloatOperation::NE>();
  1156. break;
  1157. case OP_XOR:
  1158. doIntOperation<IntegerOperation::Xor>();
  1159. break;
  1160. case OP_BITAND:
  1161. doIntOperation<IntegerOperation::BitAnd>();
  1162. break;
  1163. case OP_BITOR:
  1164. doIntOperation<IntegerOperation::BitOr>();
  1165. break;
  1166. case OP_NOT:
  1167. stack[_STK].setInt(!stack[_STK].getInt());
  1168. break;
  1169. case OP_NOTF:
  1170. stack[_STK].setInt(!stack[_STK].getFloat());
  1171. break;
  1172. case OP_ONESCOMPLEMENT:
  1173. stack[_STK].setInt(~stack[_STK].getInt());
  1174. break;
  1175. case OP_SHR:
  1176. doIntOperation<IntegerOperation::RShift>();
  1177. break;
  1178. case OP_SHL:
  1179. doIntOperation<IntegerOperation::LShift>();
  1180. break;
  1181. case OP_AND:
  1182. doIntOperation<IntegerOperation::LogicalAnd>();
  1183. break;
  1184. case OP_OR:
  1185. doIntOperation<IntegerOperation::LogicalOr>();
  1186. break;
  1187. case OP_ADD:
  1188. doFloatMathOperation<FloatOperation::Add>();
  1189. break;
  1190. case OP_SUB:
  1191. doFloatMathOperation<FloatOperation::Sub>();
  1192. break;
  1193. case OP_MUL:
  1194. doFloatMathOperation<FloatOperation::Mul>();
  1195. break;
  1196. case OP_DIV:
  1197. doFloatMathOperation<FloatOperation::Div>();
  1198. break;
  1199. case OP_MOD:
  1200. {
  1201. S64 divisor = stack[_STK - 1].getInt();
  1202. if (divisor != 0)
  1203. stack[_STK - 1].setInt(stack[_STK].getInt() % divisor);
  1204. else
  1205. stack[_STK - 1].setInt(0);
  1206. _STK--;
  1207. break;
  1208. }
  1209. case OP_NEG:
  1210. stack[_STK].setFloat(-stack[_STK].getFloat());
  1211. break;
  1212. case OP_INC:
  1213. reg = code[ip++];
  1214. gEvalState.setLocalFloatVariable(reg, gEvalState.getLocalFloatVariable(reg) + 1.0);
  1215. break;
  1216. case OP_SETCURVAR:
  1217. var = CodeToSTE(code, ip);
  1218. ip += 2;
  1219. // If a variable is set, then these must be NULL. It is necessary
  1220. // to set this here so that the vector parser can appropriately
  1221. // identify whether it's dealing with a vector.
  1222. prevField = NULL;
  1223. prevObject = NULL;
  1224. curObject = NULL;
  1225. // Used for local variable caching of what is active...when we
  1226. // set a global, we aren't active
  1227. currentRegister = -1;
  1228. gEvalState.setCurVarName(var);
  1229. // In order to let docblocks work properly with variables, we have
  1230. // clear the current docblock when we do an assign. This way it
  1231. // won't inappropriately carry forward to following function decls.
  1232. curFNDocBlock = NULL;
  1233. curNSDocBlock = NULL;
  1234. break;
  1235. case OP_SETCURVAR_CREATE:
  1236. var = CodeToSTE(code, ip);
  1237. ip += 2;
  1238. // See OP_SETCURVAR
  1239. prevField = NULL;
  1240. prevObject = NULL;
  1241. curObject = NULL;
  1242. // Used for local variable caching of what is active...when we
  1243. // set a global, we aren't active
  1244. currentRegister = -1;
  1245. gEvalState.setCurVarNameCreate(var);
  1246. // See OP_SETCURVAR for why we do this.
  1247. curFNDocBlock = NULL;
  1248. curNSDocBlock = NULL;
  1249. break;
  1250. case OP_SETCURVAR_ARRAY:
  1251. var = StringTable->insert(stack[_STK].getString());
  1252. // See OP_SETCURVAR
  1253. prevField = NULL;
  1254. prevObject = NULL;
  1255. curObject = NULL;
  1256. // Used for local variable caching of what is active...when we
  1257. // set a global, we aren't active
  1258. currentRegister = -1;
  1259. gEvalState.setCurVarName(var);
  1260. // See OP_SETCURVAR for why we do this.
  1261. curFNDocBlock = NULL;
  1262. curNSDocBlock = NULL;
  1263. break;
  1264. case OP_SETCURVAR_ARRAY_CREATE:
  1265. var = StringTable->insert(stack[_STK].getString());
  1266. // See OP_SETCURVAR
  1267. prevField = NULL;
  1268. prevObject = NULL;
  1269. curObject = NULL;
  1270. // Used for local variable caching of what is active...when we
  1271. // set a global, we aren't active
  1272. currentRegister = -1;
  1273. gEvalState.setCurVarNameCreate(var);
  1274. // See OP_SETCURVAR for why we do this.
  1275. curFNDocBlock = NULL;
  1276. curNSDocBlock = NULL;
  1277. break;
  1278. case OP_LOADVAR_UINT:
  1279. currentRegister = -1;
  1280. stack[_STK + 1].setInt(gEvalState.getIntVariable());
  1281. _STK++;
  1282. break;
  1283. case OP_LOADVAR_FLT:
  1284. currentRegister = -1;
  1285. stack[_STK + 1].setFloat(gEvalState.getFloatVariable());
  1286. _STK++;
  1287. break;
  1288. case OP_LOADVAR_STR:
  1289. currentRegister = -1;
  1290. stack[_STK + 1].setString(gEvalState.getStringVariable());
  1291. _STK++;
  1292. break;
  1293. case OP_SAVEVAR_UINT:
  1294. gEvalState.setIntVariable(stack[_STK].getInt());
  1295. break;
  1296. case OP_SAVEVAR_FLT:
  1297. gEvalState.setFloatVariable(stack[_STK].getFloat());
  1298. break;
  1299. case OP_SAVEVAR_STR:
  1300. gEvalState.setStringVariable(stack[_STK].getString());
  1301. break;
  1302. case OP_LOAD_LOCAL_VAR_UINT:
  1303. reg = code[ip++];
  1304. currentRegister = reg;
  1305. stack[_STK + 1].setInt(gEvalState.getLocalIntVariable(reg));
  1306. _STK++;
  1307. break;
  1308. case OP_LOAD_LOCAL_VAR_FLT:
  1309. reg = code[ip++];
  1310. currentRegister = reg;
  1311. stack[_STK + 1].setFloat(gEvalState.getLocalFloatVariable(reg));
  1312. _STK++;
  1313. break;
  1314. case OP_LOAD_LOCAL_VAR_STR:
  1315. reg = code[ip++];
  1316. currentRegister = reg;
  1317. val = gEvalState.getLocalStringVariable(reg);
  1318. stack[_STK + 1].setString(val);
  1319. _STK++;
  1320. break;
  1321. case OP_SAVE_LOCAL_VAR_UINT:
  1322. reg = code[ip++];
  1323. gEvalState.setLocalIntVariable(reg, stack[_STK].getInt());
  1324. break;
  1325. case OP_SAVE_LOCAL_VAR_FLT:
  1326. reg = code[ip++];
  1327. gEvalState.setLocalFloatVariable(reg, stack[_STK].getFloat());
  1328. break;
  1329. case OP_SAVE_LOCAL_VAR_STR:
  1330. reg = code[ip++];
  1331. val = stack[_STK].getString();
  1332. gEvalState.setLocalStringVariable(reg, val, (S32)dStrlen(val));
  1333. break;
  1334. case OP_SETCUROBJECT:
  1335. // Save the previous object for parsing vector fields.
  1336. prevObject = curObject;
  1337. val = stack[_STK].getString();
  1338. //_STK--;
  1339. // Sim::findObject will sometimes find valid objects from
  1340. // multi-component strings. This makes sure that doesn't
  1341. // happen.
  1342. for (const char* check = val; *check; check++)
  1343. {
  1344. if (*check == ' ')
  1345. {
  1346. val = "";
  1347. break;
  1348. }
  1349. }
  1350. curObject = Sim::findObject(val);
  1351. break;
  1352. case OP_SETCUROBJECT_INTERNAL:
  1353. ++ip; // To skip the recurse flag if the object wasnt found
  1354. if (curObject)
  1355. {
  1356. SimGroup* group = dynamic_cast<SimGroup*>(curObject);
  1357. if (group)
  1358. {
  1359. StringTableEntry intName = StringTable->insert(stack[_STK].getString());
  1360. bool recurse = code[ip - 1];
  1361. SimObject* obj = group->findObjectByInternalName(intName, recurse);
  1362. stack[_STK].setInt(obj ? obj->getId() : 0);
  1363. }
  1364. else
  1365. {
  1366. Con::errorf(ConsoleLogEntry::Script, "%s: Attempt to use -> on non-group %s of class %s.", getFileLine(ip - 2), curObject->getName(), curObject->getClassName());
  1367. stack[_STK].setInt(0);
  1368. }
  1369. }
  1370. break;
  1371. case OP_SETCUROBJECT_NEW:
  1372. curObject = currentNewObject;
  1373. break;
  1374. case OP_SETCURFIELD:
  1375. // Save the previous field for parsing vector fields.
  1376. prevField = curField;
  1377. dStrcpy(prevFieldArray, curFieldArray, 256);
  1378. curField = CodeToSTE(code, ip);
  1379. curFieldArray[0] = 0;
  1380. ip += 2;
  1381. break;
  1382. case OP_SETCURFIELD_ARRAY:
  1383. dStrcpy(curFieldArray, stack[_STK].getString(), 256);
  1384. break;
  1385. case OP_SETCURFIELD_TYPE:
  1386. if(curObject)
  1387. curObject->setDataFieldType(code[ip], curField, curFieldArray);
  1388. ip++;
  1389. break;
  1390. case OP_LOADFIELD_UINT:
  1391. if (curObject)
  1392. stack[_STK + 1].setInt(dAtol(curObject->getDataField(curField, curFieldArray)));
  1393. else
  1394. {
  1395. // The field is not being retrieved from an object. Maybe it's
  1396. // a special accessor?
  1397. char buff[FieldBufferSizeNumeric];
  1398. memset(buff, 0, sizeof(buff));
  1399. getFieldComponent(prevObject, prevField, prevFieldArray, curField, buff, currentRegister);
  1400. stack[_STK + 1].setInt(dAtol(buff));
  1401. }
  1402. _STK++;
  1403. break;
  1404. case OP_LOADFIELD_FLT:
  1405. if (curObject)
  1406. stack[_STK + 1].setFloat(dAtod(curObject->getDataField(curField, curFieldArray)));
  1407. else
  1408. {
  1409. // The field is not being retrieved from an object. Maybe it's
  1410. // a special accessor?
  1411. char buff[FieldBufferSizeNumeric];
  1412. memset(buff, 0, sizeof(buff));
  1413. getFieldComponent(prevObject, prevField, prevFieldArray, curField, buff, currentRegister);
  1414. stack[_STK + 1].setFloat(dAtod(buff));
  1415. }
  1416. _STK++;
  1417. break;
  1418. case OP_LOADFIELD_STR:
  1419. if (curObject)
  1420. {
  1421. val = curObject->getDataField(curField, curFieldArray);
  1422. stack[_STK + 1].setString(val);
  1423. }
  1424. else
  1425. {
  1426. // The field is not being retrieved from an object. Maybe it's
  1427. // a special accessor?
  1428. char buff[FieldBufferSizeString];
  1429. memset(buff, 0, sizeof(buff));
  1430. getFieldComponent(prevObject, prevField, prevFieldArray, curField, buff, currentRegister);
  1431. stack[_STK + 1].setString(buff);
  1432. }
  1433. _STK++;
  1434. break;
  1435. case OP_SAVEFIELD_UINT:
  1436. if (curObject)
  1437. curObject->setDataField(curField, curFieldArray, stack[_STK].getString());
  1438. else
  1439. {
  1440. // The field is not being set on an object. Maybe it's
  1441. // a special accessor?
  1442. setFieldComponent( prevObject, prevField, prevFieldArray, curField, currentRegister );
  1443. prevObject = NULL;
  1444. }
  1445. break;
  1446. case OP_SAVEFIELD_FLT:
  1447. if (curObject)
  1448. curObject->setDataField(curField, curFieldArray, stack[_STK].getString());
  1449. else
  1450. {
  1451. // The field is not being set on an object. Maybe it's
  1452. // a special accessor?
  1453. setFieldComponent( prevObject, prevField, prevFieldArray, curField, currentRegister );
  1454. prevObject = NULL;
  1455. }
  1456. break;
  1457. case OP_SAVEFIELD_STR:
  1458. if (curObject)
  1459. curObject->setDataField(curField, curFieldArray, stack[_STK].getString());
  1460. else
  1461. {
  1462. // The field is not being set on an object. Maybe it's
  1463. // a special accessor?
  1464. setFieldComponent( prevObject, prevField, prevFieldArray, curField, currentRegister );
  1465. prevObject = NULL;
  1466. }
  1467. break;
  1468. case OP_POP_STK:
  1469. _STK--;
  1470. break;
  1471. case OP_LOADIMMED_UINT:
  1472. stack[_STK + 1].setInt(code[ip++]);
  1473. _STK++;
  1474. break;
  1475. case OP_LOADIMMED_FLT:
  1476. stack[_STK + 1].setFloat(curFloatTable[code[ip++]]);
  1477. _STK++;
  1478. break;
  1479. case OP_TAG_TO_STR:
  1480. code[ip - 1] = OP_LOADIMMED_STR;
  1481. // it's possible the string has already been converted
  1482. if (U8(curStringTable[code[ip]]) != StringTagPrefixByte)
  1483. {
  1484. U32 id = GameAddTaggedString(curStringTable + code[ip]);
  1485. dSprintf(curStringTable + code[ip] + 1, 7, "%d", id);
  1486. *(curStringTable + code[ip]) = StringTagPrefixByte;
  1487. }
  1488. TORQUE_CASE_FALLTHROUGH;
  1489. case OP_LOADIMMED_STR:
  1490. stack[_STK + 1].setString(curStringTable + code[ip++]);
  1491. _STK ++;
  1492. break;
  1493. case OP_DOCBLOCK_STR:
  1494. {
  1495. // If the first word of the doc is '\class' or '@class', then this
  1496. // is a namespace doc block, otherwise it is a function doc block.
  1497. const char* docblock = curStringTable + code[ip++];
  1498. const char* sansClass = dStrstr(docblock, "@class");
  1499. if (!sansClass)
  1500. sansClass = dStrstr(docblock, "\\class");
  1501. if (sansClass)
  1502. {
  1503. // Don't save the class declaration. Scan past the 'class'
  1504. // keyword and up to the first whitespace.
  1505. sansClass += 7;
  1506. S32 index = 0;
  1507. while ((*sansClass != ' ') && (*sansClass != '\n') && *sansClass && (index < (nsDocLength - 1)))
  1508. {
  1509. nsDocBlockClass[index++] = *sansClass;
  1510. sansClass++;
  1511. }
  1512. nsDocBlockClass[index] = '\0';
  1513. curNSDocBlock = sansClass + 1;
  1514. }
  1515. else
  1516. curFNDocBlock = docblock;
  1517. }
  1518. break;
  1519. case OP_LOADIMMED_IDENT:
  1520. stack[_STK + 1].setString(CodeToSTE(code, ip));
  1521. _STK++;
  1522. ip += 2;
  1523. break;
  1524. case OP_CALLFUNC:
  1525. {
  1526. // This routingId is set when we query the object as to whether
  1527. // it handles this method. It is set to an enum from the table
  1528. // above indicating whether it handles it on a component it owns
  1529. // or just on the object.
  1530. S32 routingId = 0;
  1531. fnName = CodeToSTE(code, ip);
  1532. fnNamespace = CodeToSTE(code, ip + 2);
  1533. U32 callType = code[ip + 4];
  1534. //if this is called from inside a function, append the ip and codeptr
  1535. if (!gEvalState.stack.empty())
  1536. {
  1537. gEvalState.getCurrentFrame().code = this;
  1538. gEvalState.getCurrentFrame().ip = ip - 1;
  1539. }
  1540. ip += 5;
  1541. gCallStack.argvc(fnName, callArgc, &callArgv);
  1542. if (callType == FuncCallExprNode::FunctionCall)
  1543. {
  1544. // Note: This works even if the function was in a package. Reason being is when
  1545. // activatePackage() is called, it swaps the namespaceEntry into the global namespace
  1546. // (and reverts it when deactivatePackage is called). Method or Static related ones work
  1547. // as expected, as the namespace is resolved on the fly.
  1548. nsEntry = Namespace::global()->lookup(fnName);
  1549. if (!nsEntry)
  1550. {
  1551. Con::warnf(ConsoleLogEntry::General,
  1552. "%s: Unable to find function %s",
  1553. getFileLine(ip - 4), fnName);
  1554. gCallStack.popFrame();
  1555. stack[_STK + 1].setEmptyString();
  1556. _STK++;
  1557. break;
  1558. }
  1559. }
  1560. else if (callType == FuncCallExprNode::StaticCall)
  1561. {
  1562. // Try to look it up.
  1563. ns = Namespace::find(fnNamespace);
  1564. nsEntry = ns->lookup(fnName);
  1565. if (!nsEntry)
  1566. {
  1567. Con::warnf(ConsoleLogEntry::General,
  1568. "%s: Unable to find function %s%s%s",
  1569. getFileLine(ip - 4), fnNamespace ? fnNamespace : "",
  1570. fnNamespace ? "::" : "", fnName);
  1571. gCallStack.popFrame();
  1572. stack[_STK + 1].setEmptyString();
  1573. _STK++;
  1574. break;
  1575. }
  1576. }
  1577. else if (callType == FuncCallExprNode::MethodCall)
  1578. {
  1579. saveObject = gEvalState.thisObject;
  1580. // Optimization: If we're an integer, we can lookup the value by SimObjectId
  1581. const ConsoleValue& simObjectLookupValue = callArgv[1];
  1582. if (simObjectLookupValue.getType() == ConsoleValueType::cvInteger)
  1583. gEvalState.thisObject = Sim::findObject(static_cast<SimObjectId>(simObjectLookupValue.getFastInt()));
  1584. else
  1585. {
  1586. SimObject *foundObject = Sim::findObject(simObjectLookupValue.getString());
  1587. // Optimization: If we're not an integer, let's make it so that the fast path exists
  1588. // on the first argument of the method call (speeds up future usage of %this, for example)
  1589. if (foundObject != NULL)
  1590. callArgv[1].setInt(static_cast<S64>(foundObject->getId()));
  1591. gEvalState.thisObject = foundObject;
  1592. }
  1593. if (gEvalState.thisObject == NULL)
  1594. {
  1595. Con::warnf(
  1596. ConsoleLogEntry::General,
  1597. "%s: Unable to find object: '%s' attempting to call function '%s'",
  1598. getFileLine(ip - 6),
  1599. simObjectLookupValue.getString(),
  1600. fnName
  1601. );
  1602. gCallStack.popFrame();
  1603. stack[_STK + 1].setEmptyString();
  1604. _STK++;
  1605. break;
  1606. }
  1607. ns = gEvalState.thisObject->getNamespace();
  1608. if (ns)
  1609. nsEntry = ns->lookup(fnName);
  1610. else
  1611. nsEntry = NULL;
  1612. }
  1613. else // it's a ParentCall
  1614. {
  1615. if (thisNamespace)
  1616. {
  1617. ns = thisNamespace->mParent;
  1618. if (ns)
  1619. nsEntry = ns->lookup(fnName);
  1620. else
  1621. nsEntry = NULL;
  1622. }
  1623. else
  1624. {
  1625. ns = NULL;
  1626. nsEntry = NULL;
  1627. }
  1628. }
  1629. if (!nsEntry || noCalls)
  1630. {
  1631. if (!noCalls)
  1632. {
  1633. Con::warnf(ConsoleLogEntry::General, "%s: Unknown command %s.", getFileLine(ip - 4), fnName);
  1634. if (callType == FuncCallExprNode::MethodCall)
  1635. {
  1636. Con::warnf(ConsoleLogEntry::General, " Object %s(%d) %s",
  1637. gEvalState.thisObject->getName() ? gEvalState.thisObject->getName() : "",
  1638. gEvalState.thisObject->getId(), Con::getNamespaceList(ns));
  1639. }
  1640. }
  1641. gCallStack.popFrame();
  1642. stack[_STK + 1].setEmptyString();
  1643. _STK++;
  1644. break;
  1645. }
  1646. if (nsEntry->mType == Namespace::Entry::ConsoleFunctionType)
  1647. {
  1648. if (nsEntry->mFunctionOffset)
  1649. {
  1650. ConsoleValue returnFromFn = nsEntry->mCode->exec(nsEntry->mFunctionOffset, fnName, nsEntry->mNamespace, callArgc, callArgv, false, nsEntry->mPackage);
  1651. stack[_STK + 1] = std::move(returnFromFn);
  1652. }
  1653. else // no body
  1654. stack[_STK + 1].setEmptyString();
  1655. _STK++;
  1656. gCallStack.popFrame();
  1657. }
  1658. else
  1659. {
  1660. if ((nsEntry->mMinArgs && S32(callArgc) < nsEntry->mMinArgs) || (nsEntry->mMaxArgs && S32(callArgc) > nsEntry->mMaxArgs))
  1661. {
  1662. const char* nsName = ns ? ns->mName : "";
  1663. Con::warnf(ConsoleLogEntry::Script, "%s: %s::%s - wrong number of arguments.", getFileLine(ip - 4), nsName, fnName);
  1664. Con::warnf(ConsoleLogEntry::Script, "%s: usage: %s", getFileLine(ip - 4), nsEntry->mUsage);
  1665. gCallStack.popFrame();
  1666. stack[_STK + 1].setEmptyString();
  1667. _STK++;
  1668. }
  1669. else
  1670. {
  1671. switch (nsEntry->mType)
  1672. {
  1673. case Namespace::Entry::StringCallbackType:
  1674. {
  1675. const char* result = nsEntry->cb.mStringCallbackFunc(gEvalState.thisObject, callArgc, callArgv);
  1676. gCallStack.popFrame();
  1677. stack[_STK + 1].setString(result);
  1678. _STK++;
  1679. break;
  1680. }
  1681. case Namespace::Entry::IntCallbackType:
  1682. {
  1683. S64 result = nsEntry->cb.mIntCallbackFunc(gEvalState.thisObject, callArgc, callArgv);
  1684. gCallStack.popFrame();
  1685. if (code[ip] == OP_POP_STK)
  1686. {
  1687. ip++;
  1688. break;
  1689. }
  1690. stack[_STK + 1].setInt(result);
  1691. _STK++;
  1692. break;
  1693. }
  1694. case Namespace::Entry::FloatCallbackType:
  1695. {
  1696. F64 result = nsEntry->cb.mFloatCallbackFunc(gEvalState.thisObject, callArgc, callArgv);
  1697. gCallStack.popFrame();
  1698. if (code[ip] == OP_POP_STK)
  1699. {
  1700. ip++;
  1701. break;
  1702. }
  1703. stack[_STK + 1].setInt(result);
  1704. _STK++;
  1705. break;
  1706. }
  1707. case Namespace::Entry::VoidCallbackType:
  1708. {
  1709. nsEntry->cb.mVoidCallbackFunc(gEvalState.thisObject, callArgc, callArgv);
  1710. gCallStack.popFrame();
  1711. if (code[ip] == OP_POP_STK)
  1712. {
  1713. ip++;
  1714. break;
  1715. }
  1716. Con::warnf(ConsoleLogEntry::General, "%s: Call to %s in %s uses result of void function call.", getFileLine(ip - 4), fnName, functionName);
  1717. stack[_STK + 1].setEmptyString();
  1718. _STK++;
  1719. break;
  1720. }
  1721. case Namespace::Entry::BoolCallbackType:
  1722. {
  1723. bool result = nsEntry->cb.mBoolCallbackFunc(gEvalState.thisObject, callArgc, callArgv);
  1724. gCallStack.popFrame();
  1725. if (code[ip] == OP_POP_STK)
  1726. {
  1727. ip++;
  1728. break;
  1729. }
  1730. stack[_STK + 1].setBool(result);
  1731. _STK++;
  1732. break;
  1733. }
  1734. }
  1735. }
  1736. }
  1737. if (callType == FuncCallExprNode::MethodCall)
  1738. gEvalState.thisObject = saveObject;
  1739. break;
  1740. }
  1741. case OP_ADVANCE_STR_APPENDCHAR:
  1742. {
  1743. char buff[2];
  1744. buff[0] = (char)code[ip++];
  1745. buff[1] = '\0';
  1746. S32 len;
  1747. const char* concat = tsconcat(stack[_STK].getString(), buff, len);
  1748. stack[_STK].setStringRef(concat, len);
  1749. break;
  1750. }
  1751. case OP_REWIND_STR:
  1752. TORQUE_CASE_FALLTHROUGH;
  1753. case OP_TERMINATE_REWIND_STR:
  1754. {
  1755. S32 len;
  1756. const char* concat = tsconcat(stack[_STK - 1].getString(), stack[_STK].getString(), len);
  1757. stack[_STK - 1].setStringRef(concat, len);
  1758. _STK--;
  1759. break;
  1760. }
  1761. case OP_COMPARE_STR:
  1762. stack[_STK - 1].setBool(!dStricmp(stack[_STK].getString(), stack[_STK - 1].getString()));
  1763. _STK--;
  1764. break;
  1765. case OP_PUSH:
  1766. gCallStack.push(std::move(stack[_STK--]));
  1767. break;
  1768. case OP_PUSH_FRAME:
  1769. gCallStack.pushFrame(code[ip++]);
  1770. break;
  1771. case OP_ASSERT:
  1772. {
  1773. if (!stack[_STK--].getBool())
  1774. {
  1775. const char* message = curStringTable + code[ip];
  1776. U32 breakLine, inst;
  1777. findBreakLine(ip - 1, breakLine, inst);
  1778. if (PlatformAssert::processAssert(PlatformAssert::Fatal,
  1779. name ? name : "eval",
  1780. breakLine,
  1781. message))
  1782. {
  1783. if (TelDebugger && TelDebugger->isConnected() && breakLine > 0)
  1784. {
  1785. TelDebugger->breakProcess();
  1786. }
  1787. else
  1788. Platform::debugBreak();
  1789. }
  1790. }
  1791. ip++;
  1792. break;
  1793. }
  1794. case OP_BREAK:
  1795. {
  1796. //append the ip and codeptr before managing the breakpoint!
  1797. AssertFatal(!gEvalState.stack.empty(), "Empty eval stack on break!");
  1798. gEvalState.getCurrentFrame().code = this;
  1799. gEvalState.getCurrentFrame().ip = ip - 1;
  1800. U32 breakLine;
  1801. findBreakLine(ip - 1, breakLine, instruction);
  1802. if (!breakLine)
  1803. goto breakContinue;
  1804. TelDebugger->executionStopped(this, breakLine);
  1805. goto breakContinue;
  1806. }
  1807. case OP_ITER_BEGIN_STR:
  1808. {
  1809. iterStack[_ITER].mIsStringIter = true;
  1810. TORQUE_CASE_FALLTHROUGH;
  1811. }
  1812. case OP_ITER_BEGIN:
  1813. {
  1814. bool isGlobal = code[ip];
  1815. U32 failIp = code[ip + isGlobal ? 3 : 2];
  1816. IterStackRecord& iter = iterStack[_ITER];
  1817. iter.mIsGlobalVariable = isGlobal;
  1818. if (isGlobal)
  1819. {
  1820. StringTableEntry varName = CodeToSTE(code, ip + 1);
  1821. iter.mVar.mVariable = gEvalState.globalVars.add(varName);
  1822. }
  1823. else
  1824. {
  1825. iter.mVar.mRegister = code[ip + 1];
  1826. }
  1827. if (iter.mIsStringIter)
  1828. {
  1829. iter.mData.mStr.mString = stack[_STK].getString();
  1830. iter.mData.mStr.mIndex = 0;
  1831. }
  1832. else
  1833. {
  1834. // Look up the object.
  1835. SimSet* set;
  1836. if (!Sim::findObject(stack[_STK].getString(), set))
  1837. {
  1838. Con::errorf(ConsoleLogEntry::General, "No SimSet object '%s'", stack[_STK].getString());
  1839. Con::errorf(ConsoleLogEntry::General, "Did you mean to use 'foreach$' instead of 'foreach'?");
  1840. ip = failIp;
  1841. continue;
  1842. }
  1843. // Set up.
  1844. iter.mData.mObj.mSet = set;
  1845. iter.mData.mObj.mIndex = 0;
  1846. }
  1847. _ITER++;
  1848. iterDepth++;
  1849. ip += isGlobal ? 4 : 3;
  1850. break;
  1851. }
  1852. case OP_ITER:
  1853. {
  1854. U32 breakIp = code[ip];
  1855. IterStackRecord& iter = iterStack[_ITER - 1];
  1856. if (iter.mIsStringIter)
  1857. {
  1858. const char* str = iter.mData.mStr.mString;
  1859. U32 startIndex = iter.mData.mStr.mIndex;
  1860. U32 endIndex = startIndex;
  1861. // Break if at end.
  1862. if (!str[startIndex])
  1863. {
  1864. ip = breakIp;
  1865. continue;
  1866. }
  1867. // Find right end of current component.
  1868. if (!dIsspace(str[endIndex]))
  1869. do ++endIndex;
  1870. while (str[endIndex] && !dIsspace(str[endIndex]));
  1871. // Extract component.
  1872. if (endIndex != startIndex)
  1873. {
  1874. char savedChar = str[endIndex];
  1875. const_cast<char*>(str)[endIndex] = '\0'; // We are on the string stack so this is okay.
  1876. if (iter.mIsGlobalVariable)
  1877. iter.mVar.mVariable->setStringValue(&str[startIndex]);
  1878. else
  1879. gEvalState.setLocalStringVariable(iter.mVar.mRegister, &str[startIndex], endIndex - startIndex);
  1880. const_cast<char*>(str)[endIndex] = savedChar;
  1881. }
  1882. else
  1883. {
  1884. if (iter.mIsGlobalVariable)
  1885. iter.mVar.mVariable->setStringValue("");
  1886. else
  1887. gEvalState.setLocalStringVariable(iter.mVar.mRegister, "", 0);
  1888. }
  1889. // Skip separator.
  1890. if (str[endIndex] != '\0')
  1891. ++endIndex;
  1892. iter.mData.mStr.mIndex = endIndex;
  1893. }
  1894. else
  1895. {
  1896. U32 index = iter.mData.mObj.mIndex;
  1897. SimSet* set = iter.mData.mObj.mSet;
  1898. if (index >= set->size())
  1899. {
  1900. ip = breakIp;
  1901. continue;
  1902. }
  1903. SimObjectId id = set->at(index)->getId();
  1904. if (iter.mIsGlobalVariable)
  1905. iter.mVar.mVariable->setIntValue(id);
  1906. else
  1907. gEvalState.setLocalIntVariable(iter.mVar.mRegister, id);
  1908. iter.mData.mObj.mIndex = index + 1;
  1909. }
  1910. ++ip;
  1911. break;
  1912. }
  1913. case OP_ITER_END:
  1914. {
  1915. --_ITER;
  1916. --iterDepth;
  1917. _STK--;
  1918. iterStack[_ITER].mIsStringIter = false;
  1919. break;
  1920. }
  1921. case OP_INVALID:
  1922. TORQUE_CASE_FALLTHROUGH;
  1923. default:
  1924. // error!
  1925. AssertISV(false, "Invalid OPCode Processed!");
  1926. goto execFinished;
  1927. }
  1928. }
  1929. execFinished:
  1930. if (telDebuggerOn && setFrame < 0)
  1931. TelDebugger->popStackFrame();
  1932. if (popFrame)
  1933. {
  1934. gEvalState.popFrame();
  1935. }
  1936. if (argv)
  1937. {
  1938. if (gEvalState.traceOn)
  1939. {
  1940. traceBuffer[0] = 0;
  1941. dStrcat(traceBuffer, "Leaving ", TRACE_BUFFER_SIZE);
  1942. if (packageName)
  1943. {
  1944. dStrcat(traceBuffer, "[", TRACE_BUFFER_SIZE);
  1945. dStrcat(traceBuffer, packageName, TRACE_BUFFER_SIZE);
  1946. dStrcat(traceBuffer, "]", TRACE_BUFFER_SIZE);
  1947. }
  1948. if (thisNamespace && thisNamespace->mName)
  1949. {
  1950. dSprintf(traceBuffer + dStrlen(traceBuffer), sizeof(traceBuffer) - dStrlen(traceBuffer),
  1951. "%s::%s() - return %s", thisNamespace->mName, thisFunctionName, returnValue.getString());
  1952. }
  1953. else
  1954. {
  1955. dSprintf(traceBuffer + dStrlen(traceBuffer), sizeof(traceBuffer) - dStrlen(traceBuffer),
  1956. "%s() - return %s", thisFunctionName, returnValue.getString());
  1957. }
  1958. Con::printf("%s", traceBuffer);
  1959. }
  1960. }
  1961. else
  1962. {
  1963. delete[] const_cast<char*>(globalStrings);
  1964. delete[] globalFloats;
  1965. globalStrings = NULL;
  1966. globalFloats = NULL;
  1967. }
  1968. smCurrentCodeBlock = saveCodeBlock;
  1969. if (saveCodeBlock && saveCodeBlock->name)
  1970. {
  1971. Con::gCurrentFile = saveCodeBlock->name;
  1972. Con::gCurrentRoot = saveCodeBlock->modPath;
  1973. }
  1974. decRefCount();
  1975. #ifdef TORQUE_DEBUG
  1976. AssertFatal(!(_STK > stackStart), "String stack not popped enough in script exec");
  1977. AssertFatal(!(_STK < stackStart), "String stack popped too much in script exec");
  1978. #endif
  1979. return std::move(returnValue);
  1980. }
  1981. //------------------------------------------------------------