consoleInternal.cpp 50 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include <unordered_map>
  23. #include "platform/platform.h"
  24. #include "console/console.h"
  25. #include "console/ast.h"
  26. #include "core/tAlgorithm.h"
  27. #include "core/strings/findMatch.h"
  28. #include "console/consoleInternal.h"
  29. #include "core/stream/fileStream.h"
  30. #include "console/compiler.h"
  31. #include "console/engineAPI.h"
  32. //#define DEBUG_SPEW
  33. #define ST_INIT_SIZE 15
  34. static char scratchBuffer[1024];
  35. U32 Namespace::mCacheSequence = 0;
  36. DataChunker Namespace::mCacheAllocator;
  37. DataChunker Namespace::mAllocator;
  38. Namespace *Namespace::mNamespaceList = NULL;
  39. Namespace *Namespace::mGlobalNamespace = NULL;
  40. namespace std
  41. {
  42. template<> struct hash<std::pair<StringTableEntry, StringTableEntry>>
  43. {
  44. typedef std::pair<StringTableEntry, StringTableEntry> argument_type;
  45. typedef size_t result_type;
  46. result_type operator()(argument_type const& s) const
  47. {
  48. return HashPointer(s.first) ^ (HashPointer(s.second) << 1);
  49. }
  50. };
  51. };
  52. std::unordered_map<std::pair<StringTableEntry, StringTableEntry>, Namespace*> gNamespaceCache;
  53. bool canTabComplete(const char *prevText, const char *bestMatch,
  54. const char *newText, S32 baseLen, bool fForward)
  55. {
  56. // test if it matches the first baseLen chars:
  57. if (dStrnicmp(newText, prevText, baseLen))
  58. return false;
  59. if (fForward)
  60. {
  61. if (!bestMatch)
  62. return dStricmp(newText, prevText) > 0;
  63. else
  64. return (dStricmp(newText, prevText) > 0) &&
  65. (dStricmp(newText, bestMatch) < 0);
  66. }
  67. else
  68. {
  69. if (dStrlen(prevText) == (U32)baseLen)
  70. {
  71. // look for the 'worst match'
  72. if (!bestMatch)
  73. return dStricmp(newText, prevText) > 0;
  74. else
  75. return dStricmp(newText, bestMatch) > 0;
  76. }
  77. else
  78. {
  79. if (!bestMatch)
  80. return (dStricmp(newText, prevText) < 0);
  81. else
  82. return (dStricmp(newText, prevText) < 0) &&
  83. (dStricmp(newText, bestMatch) > 0);
  84. }
  85. }
  86. }
  87. //---------------------------------------------------------------
  88. //
  89. // Dictionary functions
  90. //
  91. //---------------------------------------------------------------
  92. struct StringValue
  93. {
  94. S32 size;
  95. char *val;
  96. operator char *() { return val; }
  97. StringValue &operator=(const char *string);
  98. StringValue() { size = 0; val = NULL; }
  99. ~StringValue() { dFree(val); }
  100. };
  101. StringValue & StringValue::operator=(const char *string)
  102. {
  103. if (!val)
  104. {
  105. val = dStrdup(string);
  106. size = dStrlen(val);
  107. }
  108. else
  109. {
  110. S32 len = dStrlen(string);
  111. if (len < size)
  112. dStrcpy(val, string, size);
  113. else
  114. {
  115. size = len;
  116. dFree(val);
  117. val = dStrdup(string);
  118. }
  119. }
  120. return *this;
  121. }
  122. static S32 QSORT_CALLBACK varCompare(const void* a, const void* b)
  123. {
  124. return dStricmp((*((Dictionary::Entry **) a))->name, (*((Dictionary::Entry **) b))->name);
  125. }
  126. void Dictionary::exportVariables(const char *varString, const char *fileName, bool append)
  127. {
  128. const char *searchStr = varString;
  129. Vector<Entry *> sortList(__FILE__, __LINE__);
  130. for (S32 i = 0; i < hashTable->size; i++)
  131. {
  132. Entry *walk = hashTable->data[i];
  133. while (walk)
  134. {
  135. if (FindMatch::isMatch((char *)searchStr, (char *)walk->name))
  136. sortList.push_back(walk);
  137. walk = walk->nextEntry;
  138. }
  139. }
  140. if (!sortList.size())
  141. return;
  142. dQsort((void *)&sortList[0], sortList.size(), sizeof(Entry *), varCompare);
  143. Vector<Entry *>::iterator s;
  144. char expandBuffer[1024];
  145. FileStream *strm = NULL;
  146. if (fileName)
  147. {
  148. if ((strm = FileStream::createAndOpen(fileName, append ? Torque::FS::File::ReadWrite : Torque::FS::File::Write)) == NULL)
  149. {
  150. Con::errorf(ConsoleLogEntry::General, "Unable to open file '%s for writing.", fileName);
  151. return;
  152. }
  153. if (append)
  154. strm->setPosition(strm->getStreamSize());
  155. }
  156. char buffer[1024];
  157. const char *cat = fileName ? "\r\n" : "";
  158. for (s = sortList.begin(); s != sortList.end(); s++)
  159. {
  160. switch ((*s)->type)
  161. {
  162. case Entry::TypeInternalInt:
  163. dSprintf(buffer, sizeof(buffer), "%s = %d;%s", (*s)->name, (*s)->ival, cat);
  164. break;
  165. case Entry::TypeInternalFloat:
  166. dSprintf(buffer, sizeof(buffer), "%s = %g;%s", (*s)->name, (*s)->fval, cat);
  167. break;
  168. default:
  169. expandEscape(expandBuffer, (*s)->getStringValue());
  170. dSprintf(buffer, sizeof(buffer), "%s = \"%s\";%s", (*s)->name, expandBuffer, cat);
  171. break;
  172. }
  173. if (strm)
  174. strm->write(dStrlen(buffer), buffer);
  175. else
  176. Con::printf("%s", buffer);
  177. }
  178. if (strm)
  179. delete strm;
  180. }
  181. void Dictionary::exportVariables(const char *varString, Vector<String> *names, Vector<String> *values)
  182. {
  183. const char *searchStr = varString;
  184. Vector<Entry *> sortList(__FILE__, __LINE__);
  185. for (S32 i = 0; i < hashTable->size; i++)
  186. {
  187. Entry *walk = hashTable->data[i];
  188. while (walk)
  189. {
  190. if (FindMatch::isMatch((char*)searchStr, (char*)walk->name))
  191. sortList.push_back(walk);
  192. walk = walk->nextEntry;
  193. }
  194. }
  195. if (!sortList.size())
  196. return;
  197. dQsort((void *)&sortList[0], sortList.size(), sizeof(Entry *), varCompare);
  198. if (names)
  199. names->reserve(sortList.size());
  200. if (values)
  201. values->reserve(sortList.size());
  202. char expandBuffer[1024];
  203. Vector<Entry *>::iterator s;
  204. for (s = sortList.begin(); s != sortList.end(); s++)
  205. {
  206. if (names)
  207. names->push_back(String((*s)->name));
  208. if (values)
  209. {
  210. switch ((*s)->type)
  211. {
  212. case ConsoleValueType::cvInteger:
  213. case ConsoleValueType::cvFloat:
  214. values->push_back(String((*s)->getStringValue()));
  215. break;
  216. default:
  217. expandEscape(expandBuffer, (*s)->getStringValue());
  218. values->push_back(expandBuffer);
  219. break;
  220. }
  221. }
  222. }
  223. }
  224. void Dictionary::deleteVariables(const char *varString)
  225. {
  226. const char *searchStr = varString;
  227. for (S32 i = 0; i < hashTable->size; i++)
  228. {
  229. Entry *walk = hashTable->data[i];
  230. while (walk)
  231. {
  232. Entry *matchedEntry = (FindMatch::isMatch((char *)searchStr, (char *)walk->name)) ? walk : NULL;
  233. walk = walk->nextEntry;
  234. if (matchedEntry)
  235. remove(matchedEntry); // assumes remove() is a stable remove (will not reorder entries on remove)
  236. }
  237. }
  238. }
  239. U32 HashPointer(StringTableEntry ptr)
  240. {
  241. return (U32)(((dsize_t)ptr) >> 2);
  242. }
  243. Dictionary::Entry *Dictionary::lookup(StringTableEntry name)
  244. {
  245. Entry *walk = hashTable->data[HashPointer(name) % hashTable->size];
  246. while (walk)
  247. {
  248. if (walk->name == name)
  249. return walk;
  250. else
  251. walk = walk->nextEntry;
  252. }
  253. return NULL;
  254. }
  255. Dictionary::Entry *Dictionary::add(StringTableEntry name)
  256. {
  257. // Try to find an existing match.
  258. //printf("Add Variable %s\n", name);
  259. Entry* ret = lookup(name);
  260. if (ret)
  261. return ret;
  262. // Rehash if the table get's too crowded. Be aware that this might
  263. // modify a table that we don't own.
  264. hashTable->count++;
  265. if (hashTable->count > hashTable->size * 2)
  266. {
  267. // Allocate a new table.
  268. const U32 newTableSize = hashTable->size * 4 - 1;
  269. Entry** newTableData = new Entry*[newTableSize];
  270. dMemset(newTableData, 0, newTableSize * sizeof(Entry*));
  271. // Move the entries over.
  272. for (U32 i = 0; i < hashTable->size; ++i)
  273. for (Entry* entry = hashTable->data[i]; entry != NULL; )
  274. {
  275. Entry* next = entry->nextEntry;
  276. U32 index = HashPointer(entry->name) % newTableSize;
  277. entry->nextEntry = newTableData[index];
  278. newTableData[index] = entry;
  279. entry = next;
  280. }
  281. // Switch the tables.
  282. delete[] hashTable->data;
  283. hashTable->data = newTableData;
  284. hashTable->size = newTableSize;
  285. }
  286. #ifdef DEBUG_SPEW
  287. Platform::outputDebugString("[ConsoleInternal] Adding entry '%s'", name);
  288. #endif
  289. // Add the new entry.
  290. ret = hashTable->mChunker.alloc();
  291. constructInPlace(ret, name);
  292. U32 idx = HashPointer(name) % hashTable->size;
  293. ret->nextEntry = hashTable->data[idx];
  294. hashTable->data[idx] = ret;
  295. return ret;
  296. }
  297. // deleteVariables() assumes remove() is a stable remove (will not reorder entries on remove)
  298. void Dictionary::remove(Dictionary::Entry *ent)
  299. {
  300. Entry **walk = &hashTable->data[HashPointer(ent->name) % hashTable->size];
  301. while (*walk != ent)
  302. walk = &((*walk)->nextEntry);
  303. #ifdef DEBUG_SPEW
  304. Platform::outputDebugString("[ConsoleInternal] Removing entry '%s'", ent->name);
  305. #endif
  306. *walk = (ent->nextEntry);
  307. destructInPlace(ent);
  308. hashTable->mChunker.free(ent);
  309. hashTable->count--;
  310. }
  311. Dictionary::Dictionary()
  312. : hashTable(NULL),
  313. #pragma warning( disable : 4355 )
  314. ownHashTable(this), // Warning with VC++ but this is safe.
  315. #pragma warning( default : 4355 )
  316. exprState(NULL),
  317. scopeName(NULL),
  318. scopeNamespace(NULL),
  319. code(NULL),
  320. ip(0)
  321. {
  322. }
  323. void Dictionary::setState(ExprEvalState *state, Dictionary* ref)
  324. {
  325. exprState = state;
  326. if (ref)
  327. {
  328. hashTable = ref->hashTable;
  329. return;
  330. }
  331. if (!ownHashTable.data)
  332. {
  333. ownHashTable.count = 0;
  334. ownHashTable.size = ST_INIT_SIZE;
  335. ownHashTable.data = new Entry *[ownHashTable.size];
  336. dMemset(ownHashTable.data, 0, ownHashTable.size * sizeof(Entry*));
  337. }
  338. hashTable = &ownHashTable;
  339. }
  340. Dictionary::~Dictionary()
  341. {
  342. reset();
  343. if (ownHashTable.data)
  344. delete[] ownHashTable.data;
  345. }
  346. void Dictionary::reset()
  347. {
  348. if (hashTable && hashTable->owner != this)
  349. {
  350. hashTable = NULL;
  351. return;
  352. }
  353. for (U32 i = 0; i < ownHashTable.size; ++i)
  354. {
  355. Entry* walk = ownHashTable.data[i];
  356. while (walk)
  357. {
  358. Entry* temp = walk->nextEntry;
  359. destructInPlace(walk);
  360. walk = temp;
  361. }
  362. }
  363. dMemset(ownHashTable.data, 0, ownHashTable.size * sizeof(Entry*));
  364. ownHashTable.mChunker.freeBlocks(true);
  365. ownHashTable.count = 0;
  366. hashTable = NULL;
  367. scopeName = NULL;
  368. scopeNamespace = NULL;
  369. code = NULL;
  370. ip = 0;
  371. }
  372. const char *Dictionary::tabComplete(const char *prevText, S32 baseLen, bool fForward)
  373. {
  374. S32 i;
  375. const char *bestMatch = NULL;
  376. for (i = 0; i < hashTable->size; i++)
  377. {
  378. Entry *walk = hashTable->data[i];
  379. while (walk)
  380. {
  381. if (canTabComplete(prevText, bestMatch, walk->name, baseLen, fForward))
  382. bestMatch = walk->name;
  383. walk = walk->nextEntry;
  384. }
  385. }
  386. return bestMatch;
  387. }
  388. char *typeValueEmpty = "";
  389. Dictionary::Entry::Entry(StringTableEntry in_name)
  390. {
  391. name = in_name;
  392. notify = NULL;
  393. nextEntry = NULL;
  394. mUsage = NULL;
  395. mIsConstant = false;
  396. mNext = NULL;
  397. ival = 0;
  398. fval = 0;
  399. sval = typeValueEmpty;
  400. bufferLen = 0;
  401. }
  402. Dictionary::Entry::~Entry()
  403. {
  404. reset();
  405. }
  406. void Dictionary::Entry::reset()
  407. {
  408. name = NULL;
  409. if (type <= TypeInternalString && sval != typeValueEmpty)
  410. dFree(sval);
  411. if (notify)
  412. delete notify;
  413. }
  414. void Dictionary::Entry::setStringValue(const char* value)
  415. {
  416. if (mIsConstant)
  417. {
  418. Con::errorf("Cannot assign value to constant '%s'.", name);
  419. return;
  420. }
  421. if (type <= TypeInternalString)
  422. {
  423. // Let's not remove empty-string-valued global vars from the dict.
  424. // If we remove them, then they won't be exported, and sometimes
  425. // it could be necessary to export such a global. There are very
  426. // few empty-string global vars so there's no performance-related
  427. // need to remove them from the dict.
  428. /*
  429. if(!value[0] && name[0] == '$')
  430. {
  431. gEvalState.globalVars.remove(this);
  432. return;
  433. }
  434. */
  435. U32 stringLen = dStrlen(value);
  436. // If it's longer than 256 bytes, it's certainly not a number.
  437. //
  438. // (This decision may come back to haunt you. Shame on you if it
  439. // does.)
  440. if (stringLen < 256)
  441. {
  442. fval = dAtof(value);
  443. ival = dAtoi(value);
  444. }
  445. else
  446. {
  447. fval = 0.f;
  448. ival = 0;
  449. }
  450. type = TypeInternalString;
  451. // may as well pad to the next cache line
  452. U32 newLen = ((stringLen + 1) + 15) & ~15;
  453. if (sval == typeValueEmpty)
  454. sval = (char*)dMalloc(newLen);
  455. else if (newLen > bufferLen)
  456. sval = (char*)dRealloc(sval, newLen);
  457. bufferLen = newLen;
  458. dStrcpy(sval, value, newLen);
  459. }
  460. else
  461. Con::setData(type, dataPtr, 0, 1, &value, enumTable);
  462. // Fire off the notification if we have one.
  463. if (notify)
  464. notify->trigger();
  465. }
  466. const char *Dictionary::getVariable(StringTableEntry name, bool *entValid)
  467. {
  468. Entry *ent = lookup(name);
  469. if (ent)
  470. {
  471. if (entValid)
  472. *entValid = true;
  473. return ent->getStringValue();
  474. }
  475. if (entValid)
  476. *entValid = false;
  477. // Warn users when they access a variable that isn't defined.
  478. if (gWarnUndefinedScriptVariables)
  479. Con::warnf(" *** Accessed undefined variable '%s'", name);
  480. return "";
  481. }
  482. S32 Dictionary::getIntVariable(StringTableEntry name, bool *entValid)
  483. {
  484. Entry *ent = lookup(name);
  485. if (ent)
  486. {
  487. if (entValid)
  488. *entValid = true;
  489. return ent->getIntValue();
  490. }
  491. if (entValid)
  492. *entValid = false;
  493. return 0;
  494. }
  495. F32 Dictionary::getFloatVariable(StringTableEntry name, bool *entValid)
  496. {
  497. Entry *ent = lookup(name);
  498. if (ent)
  499. {
  500. if (entValid)
  501. *entValid = true;
  502. return ent->getFloatValue();
  503. }
  504. if (entValid)
  505. *entValid = false;
  506. return 0;
  507. }
  508. void Dictionary::setVariable(StringTableEntry name, const char *value)
  509. {
  510. Entry *ent = add(name);
  511. if (!value)
  512. value = "";
  513. ent->setStringValue(value);
  514. }
  515. Dictionary::Entry* Dictionary::addVariable(const char *name,
  516. S32 type,
  517. void *dataPtr,
  518. const char* usage)
  519. {
  520. AssertFatal(type >= 0, "Dictionary::addVariable - Got bad type!");
  521. if (name[0] != '$')
  522. {
  523. scratchBuffer[0] = '$';
  524. dStrcpy(scratchBuffer + 1, name, 1023);
  525. name = scratchBuffer;
  526. }
  527. Entry *ent = add(StringTable->insert(name));
  528. if (ent->type <= Entry::TypeInternalString && ent->sval != typeValueEmpty)
  529. dFree(ent->sval);
  530. ent->mUsage = usage;
  531. ent->type = type;
  532. ent->dataPtr = dataPtr;
  533. // Fetch enum table, if any.
  534. ConsoleBaseType* conType = ConsoleBaseType::getType(type);
  535. AssertFatal(conType, "Dictionary::addVariable - invalid console type");
  536. ent->enumTable = conType->getEnumTable();
  537. return ent;
  538. }
  539. bool Dictionary::removeVariable(StringTableEntry name)
  540. {
  541. if (Entry *ent = lookup(name))
  542. {
  543. remove(ent);
  544. return true;
  545. }
  546. return false;
  547. }
  548. void Dictionary::addVariableNotify(const char *name, const Con::NotifyDelegate &callback)
  549. {
  550. Entry *ent = lookup(StringTable->insert(name));
  551. if (!ent)
  552. return;
  553. if (!ent->notify)
  554. ent->notify = new Entry::NotifySignal();
  555. ent->notify->notify(callback);
  556. }
  557. void Dictionary::removeVariableNotify(const char *name, const Con::NotifyDelegate &callback)
  558. {
  559. Entry *ent = lookup(StringTable->insert(name));
  560. if (ent && ent->notify)
  561. ent->notify->remove(callback);
  562. }
  563. void Dictionary::validate()
  564. {
  565. AssertFatal(ownHashTable.owner == this,
  566. "Dictionary::validate() - Dictionary not owner of own hashtable!");
  567. }
  568. void ExprEvalState::pushFrame(StringTableEntry frameName, Namespace *ns, S32 registerCount)
  569. {
  570. #ifdef DEBUG_SPEW
  571. validate();
  572. Platform::outputDebugString("[ConsoleInternal] Pushing new frame for '%s' at %i",
  573. frameName, mStackDepth);
  574. #endif
  575. if (mStackDepth + 1 > stack.size())
  576. {
  577. #ifdef DEBUG_SPEW
  578. Platform::outputDebugString("[ConsoleInternal] Growing stack by one frame");
  579. #endif
  580. stack.push_back(new Dictionary);
  581. }
  582. Dictionary& newFrame = *(stack[mStackDepth]);
  583. newFrame.setState(this);
  584. newFrame.scopeName = frameName;
  585. newFrame.scopeNamespace = ns;
  586. mStackDepth++;
  587. currentVariable = NULL;
  588. AssertFatal(!newFrame.getCount(), "ExprEvalState::pushFrame - Dictionary not empty!");
  589. ConsoleValue* consoleValArray = new ConsoleValue[registerCount];
  590. localStack.push_back(ConsoleValueFrame(consoleValArray, false));
  591. currentRegisterArray = &localStack.last();
  592. AssertFatal(mStackDepth == localStack.size(), avar("Stack sizes do not match. mStackDepth = %d, localStack = %d", mStackDepth, localStack.size()));
  593. #ifdef DEBUG_SPEW
  594. validate();
  595. #endif
  596. }
  597. void ExprEvalState::popFrame()
  598. {
  599. AssertFatal(mStackDepth > 0, "ExprEvalState::popFrame - Stack Underflow!");
  600. #ifdef DEBUG_SPEW
  601. validate();
  602. Platform::outputDebugString("[ConsoleInternal] Popping %sframe at %i",
  603. getCurrentFrame().isOwner() ? "" : "shared ", mStackDepth - 1);
  604. #endif
  605. mStackDepth--;
  606. stack[mStackDepth]->reset();
  607. currentVariable = NULL;
  608. const ConsoleValueFrame& frame = localStack.last();
  609. localStack.pop_back();
  610. if (!frame.isReference)
  611. delete[] frame.values;
  612. currentRegisterArray = localStack.size() ? &localStack.last() : NULL;
  613. AssertFatal(mStackDepth == localStack.size(), avar("Stack sizes do not match. mStackDepth = %d, localStack = %d", mStackDepth, localStack.size()));
  614. #ifdef DEBUG_SPEW
  615. validate();
  616. #endif
  617. }
  618. void ExprEvalState::pushFrameRef(S32 stackIndex)
  619. {
  620. AssertFatal(stackIndex >= 0 && stackIndex < mStackDepth, "You must be asking for a valid frame!");
  621. #ifdef DEBUG_SPEW
  622. validate();
  623. Platform::outputDebugString("[ConsoleInternal] Cloning frame from %i to %i",
  624. stackIndex, mStackDepth);
  625. #endif
  626. if (mStackDepth + 1 > stack.size())
  627. {
  628. #ifdef DEBUG_SPEW
  629. Platform::outputDebugString("[ConsoleInternal] Growing stack by one frame");
  630. #endif
  631. stack.push_back(new Dictionary);
  632. }
  633. Dictionary& newFrame = *(stack[mStackDepth]);
  634. newFrame.setState(this, stack[stackIndex]);
  635. mStackDepth++;
  636. currentVariable = NULL;
  637. ConsoleValue* values = localStack[stackIndex].values;
  638. localStack.push_back(ConsoleValueFrame(values, true));
  639. currentRegisterArray = &localStack.last();
  640. AssertFatal(mStackDepth == localStack.size(), avar("Stack sizes do not match. mStackDepth = %d, localStack = %d", mStackDepth, localStack.size()));
  641. #ifdef DEBUG_SPEW
  642. validate();
  643. #endif
  644. }
  645. ExprEvalState::ExprEvalState()
  646. {
  647. VECTOR_SET_ASSOCIATION(stack);
  648. globalVars.setState(this);
  649. thisObject = NULL;
  650. traceOn = false;
  651. currentVariable = NULL;
  652. mStackDepth = 0;
  653. stack.reserve(64);
  654. mShouldReset = false;
  655. mResetLocked = false;
  656. copyVariable = NULL;
  657. }
  658. ExprEvalState::~ExprEvalState()
  659. {
  660. // Delete callframes.
  661. while (!stack.empty())
  662. {
  663. delete stack.last();
  664. stack.decrement();
  665. }
  666. }
  667. void ExprEvalState::validate()
  668. {
  669. AssertFatal(mStackDepth <= stack.size(),
  670. "ExprEvalState::validate() - Stack depth pointing beyond last stack frame!");
  671. for (U32 i = 0; i < stack.size(); ++i)
  672. stack[i]->validate();
  673. }
  674. DefineEngineFunction(backtrace, void, (), ,
  675. "@brief Prints the scripting call stack to the console log.\n\n"
  676. "Used to trace functions called from within functions. Can help discover what functions were called "
  677. "(and not yet exited) before the current point in scripts.\n\n"
  678. "@ingroup Debugging")
  679. {
  680. U32 totalSize = 1;
  681. for (U32 i = 0; i < gEvalState.getStackDepth(); i++)
  682. {
  683. if (gEvalState.stack[i]->scopeNamespace && gEvalState.stack[i]->scopeNamespace->mEntryList->mPackage)
  684. totalSize += dStrlen(gEvalState.stack[i]->scopeNamespace->mEntryList->mPackage) + 2;
  685. if (gEvalState.stack[i]->scopeName)
  686. totalSize += dStrlen(gEvalState.stack[i]->scopeName) + 3;
  687. if (gEvalState.stack[i]->scopeNamespace && gEvalState.stack[i]->scopeNamespace->mName)
  688. totalSize += dStrlen(gEvalState.stack[i]->scopeNamespace->mName) + 2;
  689. }
  690. char *buf = Con::getReturnBuffer(totalSize);
  691. buf[0] = 0;
  692. for (U32 i = 0; i < gEvalState.getStackDepth(); i++)
  693. {
  694. dStrcat(buf, "->", totalSize);
  695. if (gEvalState.stack[i]->scopeNamespace && gEvalState.stack[i]->scopeNamespace->mEntryList->mPackage)
  696. {
  697. dStrcat(buf, "[", totalSize);
  698. dStrcat(buf, gEvalState.stack[i]->scopeNamespace->mEntryList->mPackage, totalSize);
  699. dStrcat(buf, "]", totalSize);
  700. }
  701. if (gEvalState.stack[i]->scopeNamespace && gEvalState.stack[i]->scopeNamespace->mName)
  702. {
  703. dStrcat(buf, gEvalState.stack[i]->scopeNamespace->mName, totalSize);
  704. dStrcat(buf, "::", totalSize);
  705. }
  706. if (gEvalState.stack[i]->scopeName)
  707. dStrcat(buf, gEvalState.stack[i]->scopeName, totalSize);
  708. }
  709. Con::printf("BackTrace: %s", buf);
  710. }
  711. Namespace::Entry::Entry()
  712. {
  713. mCode = NULL;
  714. mType = InvalidFunctionType;
  715. mUsage = NULL;
  716. mHeader = NULL;
  717. mNamespace = NULL;
  718. cb.mStringCallbackFunc = NULL;
  719. mFunctionLineNumber = 0;
  720. mFunctionName = StringTable->EmptyString();
  721. mFunctionOffset = 0;
  722. mMinArgs = 0;
  723. mMaxArgs = 0;
  724. mNext = NULL;
  725. mPackage = StringTable->EmptyString();
  726. mToolOnly = false;
  727. }
  728. void Namespace::Entry::clear()
  729. {
  730. if (mCode)
  731. {
  732. mCode->decRefCount();
  733. mCode = NULL;
  734. }
  735. // Clean up usage strings generated for script functions.
  736. if ((mType == Namespace::Entry::ConsoleFunctionType) && mUsage)
  737. {
  738. dFree(mUsage);
  739. mUsage = NULL;
  740. }
  741. }
  742. Namespace::Namespace()
  743. {
  744. mPackage = NULL;
  745. mUsage = NULL;
  746. mCleanUpUsage = false;
  747. mName = NULL;
  748. mParent = NULL;
  749. mNext = NULL;
  750. mEntryList = NULL;
  751. mHashSize = 0;
  752. mHashTable = 0;
  753. mHashSequence = 0;
  754. mRefCountToParent = 0;
  755. mClassRep = 0;
  756. lastUsage = NULL;
  757. }
  758. Namespace::~Namespace()
  759. {
  760. clearEntries();
  761. if (mUsage && mCleanUpUsage)
  762. {
  763. dFree(mUsage);
  764. mUsage = NULL;
  765. mCleanUpUsage = false;
  766. }
  767. }
  768. void Namespace::clearEntries()
  769. {
  770. for (Entry *walk = mEntryList; walk; walk = walk->mNext)
  771. walk->clear();
  772. }
  773. Namespace *Namespace::find(StringTableEntry name, StringTableEntry package)
  774. {
  775. if (name == NULL && package == NULL)
  776. return mGlobalNamespace;
  777. auto pair = std::make_pair(name, package);
  778. auto pos = gNamespaceCache.find(pair);
  779. if (pos != gNamespaceCache.end())
  780. return pos->second;
  781. Namespace *ret = (Namespace *)mAllocator.alloc(sizeof(Namespace));
  782. constructInPlace(ret);
  783. ret->mPackage = package;
  784. ret->mName = name;
  785. ret->mNext = mNamespaceList;
  786. mNamespaceList = ret;
  787. // insert into namespace cache.
  788. gNamespaceCache[pair] = ret;
  789. return ret;
  790. }
  791. bool Namespace::unlinkClass(Namespace *parent)
  792. {
  793. AssertFatal(mPackage == NULL, "Namespace::unlinkClass - Must not be called on a namespace coming from a package!");
  794. // Skip additions to this namespace coming from packages.
  795. Namespace* walk = getPackageRoot();
  796. // Make sure "parent" is the direct parent namespace.
  797. if (parent != NULL && walk->mParent && walk->mParent != parent)
  798. {
  799. Con::errorf(ConsoleLogEntry::General, "Namespace::unlinkClass - cannot unlink namespace parent linkage for %s for %s.",
  800. walk->mName, walk->mParent->mName);
  801. return false;
  802. }
  803. // Decrease the reference count. Note that we do this on
  804. // the bottom-most namespace, i.e. the one guaranteed not
  805. // to come from a package.
  806. mRefCountToParent--;
  807. AssertFatal(mRefCountToParent >= 0, "Namespace::unlinkClass - reference count to parent is less than 0");
  808. // Unlink if the count dropped to zero.
  809. if (mRefCountToParent == 0)
  810. {
  811. walk->mParent = NULL;
  812. trashCache();
  813. }
  814. return true;
  815. }
  816. bool Namespace::classLinkTo(Namespace *parent)
  817. {
  818. Namespace* walk = getPackageRoot();
  819. if (walk->mParent && walk->mParent != parent)
  820. {
  821. Con::errorf(ConsoleLogEntry::General, "Error: cannot change namespace parent linkage of %s from %s to %s.",
  822. walk->mName, walk->mParent->mName, parent->mName);
  823. return false;
  824. }
  825. trashCache();
  826. walk->mParent = parent;
  827. mRefCountToParent++;
  828. return true;
  829. }
  830. void Namespace::buildHashTable()
  831. {
  832. if (mHashSequence == mCacheSequence)
  833. return;
  834. if (!mEntryList && mParent)
  835. {
  836. mParent->buildHashTable();
  837. mHashTable = mParent->mHashTable;
  838. mHashSize = mParent->mHashSize;
  839. mHashSequence = mCacheSequence;
  840. return;
  841. }
  842. U32 entryCount = 0;
  843. Namespace * ns;
  844. for (ns = this; ns; ns = ns->mParent)
  845. for (Entry *walk = ns->mEntryList; walk; walk = walk->mNext)
  846. if (lookupRecursive(walk->mFunctionName) == walk)
  847. entryCount++;
  848. mHashSize = entryCount + (entryCount >> 1) + 1;
  849. if (!(mHashSize & 1))
  850. mHashSize++;
  851. mHashTable = (Entry **)mCacheAllocator.alloc(sizeof(Entry *) * mHashSize);
  852. for (U32 i = 0; i < mHashSize; i++)
  853. mHashTable[i] = NULL;
  854. for (ns = this; ns; ns = ns->mParent)
  855. {
  856. for (Entry *walk = ns->mEntryList; walk; walk = walk->mNext)
  857. {
  858. U32 index = HashPointer(walk->mFunctionName) % mHashSize;
  859. while (mHashTable[index] && mHashTable[index]->mFunctionName != walk->mFunctionName)
  860. {
  861. index++;
  862. if (index >= mHashSize)
  863. index = 0;
  864. }
  865. if (!mHashTable[index])
  866. mHashTable[index] = walk;
  867. }
  868. }
  869. mHashSequence = mCacheSequence;
  870. }
  871. void Namespace::getUniqueEntryLists(Namespace *other, VectorPtr<Entry *> *outThisList, VectorPtr<Entry *> *outOtherList)
  872. {
  873. // All namespace entries in the common ACR should be
  874. // ignored when checking for duplicate entry names.
  875. static VectorPtr<Namespace::Entry *> commonEntries;
  876. commonEntries.clear();
  877. AbstractClassRep *commonACR = mClassRep->getCommonParent(other->mClassRep);
  878. commonACR->getNameSpace()->getEntryList(&commonEntries);
  879. // Make life easier
  880. VectorPtr<Namespace::Entry *> &thisEntries = *outThisList;
  881. VectorPtr<Namespace::Entry *> &compEntries = *outOtherList;
  882. // Clear, just in case they aren't
  883. thisEntries.clear();
  884. compEntries.clear();
  885. getEntryList(&thisEntries);
  886. other->getEntryList(&compEntries);
  887. // Run through all of the entries in the common ACR, and remove them from
  888. // the other two entry lists
  889. for (NamespaceEntryListIterator itr = commonEntries.begin(); itr != commonEntries.end(); itr++)
  890. {
  891. // Check this entry list
  892. for (NamespaceEntryListIterator thisItr = thisEntries.begin(); thisItr != thisEntries.end(); thisItr++)
  893. {
  894. if (*thisItr == *itr)
  895. {
  896. thisEntries.erase(thisItr);
  897. break;
  898. }
  899. }
  900. // Same check for component entry list
  901. for (NamespaceEntryListIterator compItr = compEntries.begin(); compItr != compEntries.end(); compItr++)
  902. {
  903. if (*compItr == *itr)
  904. {
  905. compEntries.erase(compItr);
  906. break;
  907. }
  908. }
  909. }
  910. }
  911. void Namespace::init()
  912. {
  913. // create the global namespace
  914. mGlobalNamespace = (Namespace *)mAllocator.alloc(sizeof(Namespace));
  915. constructInPlace(mGlobalNamespace);
  916. mGlobalNamespace->mPackage = NULL;
  917. mGlobalNamespace->mName = NULL;
  918. mGlobalNamespace->mNext = NULL;
  919. mNamespaceList = mGlobalNamespace;
  920. // Insert into namespace cache.
  921. gNamespaceCache[std::make_pair(mGlobalNamespace->mName, mGlobalNamespace->mPackage)] = mGlobalNamespace;
  922. }
  923. Namespace *Namespace::global()
  924. {
  925. return mGlobalNamespace;
  926. }
  927. void Namespace::shutdown()
  928. {
  929. // The data chunker will release all memory in one go
  930. // without calling destructors, so we do this manually here.
  931. for (Namespace *walk = mNamespaceList; walk; walk = walk->mNext)
  932. walk->~Namespace();
  933. }
  934. void Namespace::trashCache()
  935. {
  936. mCacheSequence++;
  937. mCacheAllocator.freeBlocks();
  938. }
  939. const char *Namespace::tabComplete(const char *prevText, S32 baseLen, bool fForward)
  940. {
  941. if (mHashSequence != mCacheSequence)
  942. buildHashTable();
  943. const char *bestMatch = NULL;
  944. for (U32 i = 0; i < mHashSize; i++)
  945. if (mHashTable[i] && canTabComplete(prevText, bestMatch, mHashTable[i]->mFunctionName, baseLen, fForward))
  946. bestMatch = mHashTable[i]->mFunctionName;
  947. return bestMatch;
  948. }
  949. Namespace::Entry *Namespace::lookupRecursive(StringTableEntry name)
  950. {
  951. for (Namespace *ns = this; ns; ns = ns->mParent)
  952. for (Entry *walk = ns->mEntryList; walk; walk = walk->mNext)
  953. if (walk->mFunctionName == name)
  954. return walk;
  955. return NULL;
  956. }
  957. Namespace::Entry *Namespace::lookup(StringTableEntry name)
  958. {
  959. if (mHashSequence != mCacheSequence)
  960. buildHashTable();
  961. U32 index = HashPointer(name) % mHashSize;
  962. while (mHashTable[index] && mHashTable[index]->mFunctionName != name)
  963. {
  964. index++;
  965. if (index >= mHashSize)
  966. index = 0;
  967. }
  968. return mHashTable[index];
  969. }
  970. static S32 QSORT_CALLBACK compareEntries(const void* a, const void* b)
  971. {
  972. const Namespace::Entry* fa = *((Namespace::Entry**)a);
  973. const Namespace::Entry* fb = *((Namespace::Entry**)b);
  974. return dStricmp(fa->mFunctionName, fb->mFunctionName);
  975. }
  976. void Namespace::getEntryList(VectorPtr<Entry *> *vec)
  977. {
  978. if (mHashSequence != mCacheSequence)
  979. buildHashTable();
  980. for (U32 i = 0; i < mHashSize; i++)
  981. if (mHashTable[i])
  982. vec->push_back(mHashTable[i]);
  983. dQsort(vec->address(), vec->size(), sizeof(Namespace::Entry *), compareEntries);
  984. }
  985. Namespace::Entry *Namespace::createLocalEntry(StringTableEntry name)
  986. {
  987. for (Entry *walk = mEntryList; walk; walk = walk->mNext)
  988. {
  989. if (walk->mFunctionName == name)
  990. {
  991. walk->clear();
  992. return walk;
  993. }
  994. }
  995. Entry *ent = (Entry *)mAllocator.alloc(sizeof(Entry));
  996. constructInPlace(ent);
  997. ent->mNamespace = this;
  998. ent->mFunctionName = name;
  999. ent->mNext = mEntryList;
  1000. ent->mPackage = mPackage;
  1001. ent->mToolOnly = false;
  1002. mEntryList = ent;
  1003. return ent;
  1004. }
  1005. void Namespace::addFunction(StringTableEntry name, CodeBlock *cb, U32 functionOffset, const char* usage, U32 lineNumber)
  1006. {
  1007. Entry *ent = createLocalEntry(name);
  1008. trashCache();
  1009. ent->mUsage = usage;
  1010. ent->mCode = cb;
  1011. ent->mFunctionOffset = functionOffset;
  1012. ent->mCode->incRefCount();
  1013. ent->mType = Entry::ConsoleFunctionType;
  1014. ent->mFunctionLineNumber = lineNumber;
  1015. }
  1016. void Namespace::addCommand(StringTableEntry name, StringCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header)
  1017. {
  1018. Entry *ent = createLocalEntry(name);
  1019. trashCache();
  1020. ent->mUsage = usage;
  1021. ent->mHeader = header;
  1022. ent->mMinArgs = minArgs;
  1023. ent->mMaxArgs = maxArgs;
  1024. ent->mToolOnly = isToolOnly;
  1025. ent->mType = Entry::StringCallbackType;
  1026. ent->cb.mStringCallbackFunc = cb;
  1027. }
  1028. void Namespace::addCommand(StringTableEntry name, IntCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header)
  1029. {
  1030. Entry *ent = createLocalEntry(name);
  1031. trashCache();
  1032. ent->mUsage = usage;
  1033. ent->mHeader = header;
  1034. ent->mMinArgs = minArgs;
  1035. ent->mMaxArgs = maxArgs;
  1036. ent->mToolOnly = isToolOnly;
  1037. ent->mType = Entry::IntCallbackType;
  1038. ent->cb.mIntCallbackFunc = cb;
  1039. }
  1040. void Namespace::addCommand(StringTableEntry name, VoidCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header)
  1041. {
  1042. Entry *ent = createLocalEntry(name);
  1043. trashCache();
  1044. ent->mUsage = usage;
  1045. ent->mHeader = header;
  1046. ent->mMinArgs = minArgs;
  1047. ent->mMaxArgs = maxArgs;
  1048. ent->mToolOnly = isToolOnly;
  1049. ent->mType = Entry::VoidCallbackType;
  1050. ent->cb.mVoidCallbackFunc = cb;
  1051. }
  1052. void Namespace::addCommand(StringTableEntry name, FloatCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header)
  1053. {
  1054. Entry *ent = createLocalEntry(name);
  1055. trashCache();
  1056. ent->mUsage = usage;
  1057. ent->mHeader = header;
  1058. ent->mMinArgs = minArgs;
  1059. ent->mMaxArgs = maxArgs;
  1060. ent->mToolOnly = isToolOnly;
  1061. ent->mType = Entry::FloatCallbackType;
  1062. ent->cb.mFloatCallbackFunc = cb;
  1063. }
  1064. void Namespace::addCommand(StringTableEntry name, BoolCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header)
  1065. {
  1066. Entry *ent = createLocalEntry(name);
  1067. trashCache();
  1068. ent->mUsage = usage;
  1069. ent->mHeader = header;
  1070. ent->mMinArgs = minArgs;
  1071. ent->mMaxArgs = maxArgs;
  1072. ent->mToolOnly = isToolOnly;
  1073. ent->mType = Entry::BoolCallbackType;
  1074. ent->cb.mBoolCallbackFunc = cb;
  1075. }
  1076. void Namespace::addScriptCallback(const char *funcName, const char *usage, ConsoleFunctionHeader* header)
  1077. {
  1078. static U32 uid = 0;
  1079. char buffer[1024];
  1080. char lilBuffer[32];
  1081. dStrcpy(buffer, funcName, 1024);
  1082. dSprintf(lilBuffer, 32, "_%d_cb", uid++);
  1083. dStrcat(buffer, lilBuffer, 1024);
  1084. Entry *ent = createLocalEntry(StringTable->insert(buffer));
  1085. trashCache();
  1086. ent->mUsage = usage;
  1087. ent->mHeader = header;
  1088. ent->mMinArgs = -2;
  1089. ent->mMaxArgs = -3;
  1090. ent->mType = Entry::ScriptCallbackType;
  1091. ent->cb.mCallbackName = funcName;
  1092. }
  1093. void Namespace::markGroup(const char* name, const char* usage)
  1094. {
  1095. static U32 uid = 0;
  1096. char buffer[1024];
  1097. char lilBuffer[32];
  1098. dStrcpy(buffer, name, 1024);
  1099. dSprintf(lilBuffer, 32, "_%d", uid++);
  1100. dStrcat(buffer, lilBuffer, 1024);
  1101. Entry *ent = createLocalEntry(StringTable->insert(buffer));
  1102. trashCache();
  1103. if (usage != NULL)
  1104. lastUsage = (char*)(ent->mUsage = usage);
  1105. else
  1106. ent->mUsage = lastUsage;
  1107. ent->mMinArgs = -1; // Make sure it explodes if somehow we run this entry.
  1108. ent->mMaxArgs = -2;
  1109. ent->mType = Entry::GroupMarker;
  1110. ent->cb.mGroupName = name;
  1111. }
  1112. extern S32 executeBlock(StmtNode *block, ExprEvalState *state);
  1113. ConsoleValue Namespace::Entry::execute(S32 argc, ConsoleValue *argv, ExprEvalState *state)
  1114. {
  1115. STR.clearFunctionOffset();
  1116. if (mType == ConsoleFunctionType)
  1117. {
  1118. if (mFunctionOffset)
  1119. {
  1120. return std::move(mCode->exec(mFunctionOffset, argv[0].getString(), mNamespace, argc, argv, false, mPackage));
  1121. }
  1122. else
  1123. {
  1124. return std::move(ConsoleValue());
  1125. }
  1126. }
  1127. #ifndef TORQUE_DEBUG
  1128. // [tom, 12/13/2006] This stops tools functions from working in the console,
  1129. // which is useful behavior when debugging so I'm ifdefing this out for debug builds.
  1130. if (mToolOnly && !Con::isCurrentScriptToolScript())
  1131. {
  1132. Con::errorf(ConsoleLogEntry::Script, "%s::%s - attempting to call tools only function from outside of tools", mNamespace->mName, mFunctionName);
  1133. return std::move(ConsoleValue());
  1134. }
  1135. #endif
  1136. if ((mMinArgs && argc < mMinArgs) || (mMaxArgs && argc > mMaxArgs))
  1137. {
  1138. Con::warnf(ConsoleLogEntry::Script, "%s::%s - wrong number of arguments.", mNamespace->mName, mFunctionName);
  1139. Con::warnf(ConsoleLogEntry::Script, "usage: %s", mUsage);
  1140. return std::move(ConsoleValue());
  1141. }
  1142. ConsoleValue result;
  1143. switch (mType)
  1144. {
  1145. case StringCallbackType:
  1146. {
  1147. const char* str = cb.mStringCallbackFunc(state->thisObject, argc, argv);
  1148. result.setString(str);
  1149. break;
  1150. }
  1151. case IntCallbackType:
  1152. result.setInt(cb.mIntCallbackFunc(state->thisObject, argc, argv));
  1153. break;
  1154. case FloatCallbackType:
  1155. result.setFloat(cb.mBoolCallbackFunc(state->thisObject, argc, argv));
  1156. break;
  1157. case VoidCallbackType:
  1158. cb.mVoidCallbackFunc(state->thisObject, argc, argv);
  1159. break;
  1160. case BoolCallbackType:
  1161. result.setBool(cb.mBoolCallbackFunc(state->thisObject, argc, argv));
  1162. break;
  1163. }
  1164. return std::move(result);
  1165. }
  1166. //-----------------------------------------------------------------------------
  1167. // Doc string code.
  1168. namespace {
  1169. /// Scan the given usage string for an argument list description. With the
  1170. /// old console macros, these were usually included as the first part of the
  1171. /// usage string.
  1172. bool sFindArgumentListSubstring(const char* usage, const char*& start, const char*& end)
  1173. {
  1174. if (!usage)
  1175. return false;
  1176. const char* ptr = usage;
  1177. while (*ptr && *ptr != '(' && *ptr != '\n') // Only scan first line of usage string.
  1178. {
  1179. // Stop on the first alphanumeric character as we expect
  1180. // argument lists to precede descriptions.
  1181. if (dIsalnum(*ptr))
  1182. return false;
  1183. ptr++;
  1184. }
  1185. if (*ptr != '(')
  1186. return false;
  1187. start = ptr;
  1188. ptr++;
  1189. bool inString = false;
  1190. U32 nestingCount = 0;
  1191. while (*ptr && (*ptr != ')' || nestingCount > 0 || inString))
  1192. {
  1193. if (*ptr == '(')
  1194. nestingCount++;
  1195. else if (*ptr == ')')
  1196. nestingCount--;
  1197. else if (*ptr == '"')
  1198. inString = !inString;
  1199. else if (*ptr == '\\' && ptr[1] == '"')
  1200. ptr++;
  1201. ptr++;
  1202. }
  1203. if (*ptr)
  1204. ptr++;
  1205. end = ptr;
  1206. return true;
  1207. }
  1208. ///
  1209. void sParseList(const char* str, Vector< String >& outList)
  1210. {
  1211. // Skip the initial '( '.
  1212. const char* ptr = str;
  1213. while (*ptr && dIsspace(*ptr))
  1214. ptr++;
  1215. if (*ptr == '(')
  1216. {
  1217. ptr++;
  1218. while (*ptr && dIsspace(*ptr))
  1219. ptr++;
  1220. }
  1221. // Parse out list items.
  1222. while (*ptr && *ptr != ')')
  1223. {
  1224. // Find end of element.
  1225. const char* start = ptr;
  1226. bool inString = false;
  1227. U32 nestingCount = 0;
  1228. while (*ptr && ((*ptr != ')' && *ptr != ',') || nestingCount > 0 || inString))
  1229. {
  1230. if (*ptr == '(')
  1231. nestingCount++;
  1232. else if (*ptr == ')')
  1233. nestingCount--;
  1234. else if (*ptr == '"')
  1235. inString = !inString;
  1236. else if (*ptr == '\\' && ptr[1] == '"')
  1237. ptr++;
  1238. ptr++;
  1239. }
  1240. // Backtrack to remove trailing whitespace.
  1241. const char* end = ptr;
  1242. if (*end == ',' || *end == ')')
  1243. end--;
  1244. while (end > start && dIsspace(*end))
  1245. end--;
  1246. if (*end)
  1247. end++;
  1248. // Add to list.
  1249. if (start != end)
  1250. outList.push_back(String(start, end - start));
  1251. // Skip comma and whitespace.
  1252. if (*ptr == ',')
  1253. ptr++;
  1254. while (*ptr && dIsspace(*ptr))
  1255. ptr++;
  1256. }
  1257. }
  1258. ///
  1259. void sGetArgNameAndType(const String& str, String& outType, String& outName)
  1260. {
  1261. if (!str.length())
  1262. {
  1263. outType = String::EmptyString;
  1264. outName = String::EmptyString;
  1265. return;
  1266. }
  1267. // Find first non-ID character from right.
  1268. S32 index = str.length() - 1;
  1269. while (index >= 0 && (dIsalnum(str[index]) || str[index] == '_'))
  1270. index--;
  1271. const U32 nameStartIndex = index + 1;
  1272. // Find end of type name by skipping rightmost whitespace inwards.
  1273. while (index >= 0 && dIsspace(str[index]))
  1274. index--;
  1275. //
  1276. outName = String(&((const char*)str)[nameStartIndex]);
  1277. outType = String(str, index + 1);
  1278. }
  1279. /// Return the type name to show in documentation for the given C++ type.
  1280. const char* sGetDocTypeString(const char* nativeType)
  1281. {
  1282. if (dStrncmp(nativeType, "const ", 6) == 0)
  1283. nativeType += 6;
  1284. if (String::compare(nativeType, "char*") == 0 || String::compare(nativeType, "char *") == 0)
  1285. return "string";
  1286. else if (String::compare(nativeType, "S32") == 0)
  1287. return "int";
  1288. else if (String::compare(nativeType, "U32") == 0)
  1289. return "uint";
  1290. else if (String::compare(nativeType, "F32") == 0)
  1291. return "float";
  1292. const U32 length = dStrlen(nativeType);
  1293. if (nativeType[length - 1] == '&' || nativeType[length - 1] == '*')
  1294. return StringTable->insertn(nativeType, length - 1);
  1295. return nativeType;
  1296. }
  1297. }
  1298. String Namespace::Entry::getBriefDescription(String* outRemainingDocText) const
  1299. {
  1300. String docString = getDocString();
  1301. S32 newline = docString.find('\n');
  1302. if (newline == -1)
  1303. {
  1304. if (outRemainingDocText)
  1305. *outRemainingDocText = String();
  1306. return docString;
  1307. }
  1308. String brief = docString.substr(0, newline);
  1309. if (outRemainingDocText)
  1310. *outRemainingDocText = docString.substr(newline + 1);
  1311. return brief;
  1312. }
  1313. String Namespace::Entry::getDocString() const
  1314. {
  1315. const char* argListStart;
  1316. const char* argListEnd;
  1317. if (sFindArgumentListSubstring(mUsage, argListStart, argListEnd))
  1318. {
  1319. // Skip the " - " part present in some old doc strings.
  1320. const char* ptr = argListEnd;
  1321. while (*ptr && dIsspace(*ptr))
  1322. ptr++;
  1323. if (*ptr == '-')
  1324. {
  1325. ptr++;
  1326. while (*ptr && dIsspace(*ptr))
  1327. ptr++;
  1328. }
  1329. return ptr;
  1330. }
  1331. return mUsage;
  1332. }
  1333. String Namespace::Entry::getArgumentsString() const
  1334. {
  1335. StringBuilder str;
  1336. if (mHeader)
  1337. {
  1338. // Parse out the argument list string supplied with the extended
  1339. // function header and add default arguments as we go.
  1340. Vector< String > argList;
  1341. Vector< String > defaultArgList;
  1342. sParseList(mHeader->mArgString, argList);
  1343. sParseList(mHeader->mDefaultArgString, defaultArgList);
  1344. str.append('(');
  1345. const U32 numArgs = argList.size();
  1346. const U32 numDefaultArgs = defaultArgList.size();
  1347. const U32 firstDefaultArgIndex = numArgs - numDefaultArgs;
  1348. for (U32 i = 0; i < numArgs; ++i)
  1349. {
  1350. // Add separator if not first arg.
  1351. if (i > 0)
  1352. str.append(',');
  1353. // Add type and name.
  1354. String name;
  1355. String type;
  1356. sGetArgNameAndType(argList[i], type, name);
  1357. str.append(' ');
  1358. str.append(sGetDocTypeString(type));
  1359. str.append(' ');
  1360. str.append(name);
  1361. // Add default value, if any.
  1362. if (i >= firstDefaultArgIndex)
  1363. {
  1364. str.append('=');
  1365. str.append(defaultArgList[i - firstDefaultArgIndex]);
  1366. }
  1367. }
  1368. if (numArgs > 0)
  1369. str.append(' ');
  1370. str.append(')');
  1371. }
  1372. else
  1373. {
  1374. // No extended function header. Try to parse out the argument
  1375. // list from the usage string.
  1376. const char* argListStart;
  1377. const char* argListEnd;
  1378. if (sFindArgumentListSubstring(mUsage, argListStart, argListEnd))
  1379. str.append(argListStart, argListEnd - argListStart);
  1380. else if (mType == ConsoleFunctionType && mCode)
  1381. {
  1382. // This isn't correct but the nonsense console stuff is set up such that all
  1383. // functions that have no function bodies are keyed to offset 0 to indicate "no code."
  1384. // This loses the association with the original function definition so we can't really
  1385. // tell here what the actual prototype is except if we searched though the entire opcode
  1386. // stream for the corresponding OP_FUNC_DECL (which would require dealing with the
  1387. // variable-size instructions).
  1388. if (!mFunctionOffset)
  1389. return "()";
  1390. String args = mCode->getFunctionArgs(mFunctionOffset);
  1391. if (args.isEmpty())
  1392. return "()";
  1393. str.append("( ");
  1394. str.append(args);
  1395. str.append(" )");
  1396. }
  1397. }
  1398. return str.end();
  1399. }
  1400. String Namespace::Entry::getPrototypeString() const
  1401. {
  1402. StringBuilder str;
  1403. // Start with return type.
  1404. if (mHeader && mHeader->mReturnString)
  1405. {
  1406. str.append(sGetDocTypeString(mHeader->mReturnString));
  1407. str.append(' ');
  1408. }
  1409. else
  1410. switch (mType)
  1411. {
  1412. case StringCallbackType:
  1413. str.append("string ");
  1414. break;
  1415. case IntCallbackType:
  1416. str.append("int ");
  1417. break;
  1418. case FloatCallbackType:
  1419. str.append("float ");
  1420. break;
  1421. case VoidCallbackType:
  1422. str.append("void ");
  1423. break;
  1424. case BoolCallbackType:
  1425. str.append("bool ");
  1426. break;
  1427. case ScriptCallbackType:
  1428. break;
  1429. }
  1430. // Add function name and arguments.
  1431. if (mType == ScriptCallbackType)
  1432. str.append(cb.mCallbackName);
  1433. else
  1434. str.append(mFunctionName);
  1435. str.append(getArgumentsString());
  1436. return str.end();
  1437. }
  1438. //-----------------------------------------------------------------------------
  1439. StringTableEntry Namespace::mActivePackages[Namespace::MaxActivePackages];
  1440. U32 Namespace::mNumActivePackages = 0;
  1441. U32 Namespace::mOldNumActivePackages = 0;
  1442. bool Namespace::isPackage(StringTableEntry name)
  1443. {
  1444. for (Namespace *walk = mNamespaceList; walk; walk = walk->mNext)
  1445. if (walk->mPackage == name)
  1446. return true;
  1447. return false;
  1448. }
  1449. U32 Namespace::getActivePackagesCount()
  1450. {
  1451. return mNumActivePackages;
  1452. }
  1453. StringTableEntry Namespace::getActivePackage(U32 index)
  1454. {
  1455. if (index >= mNumActivePackages)
  1456. return StringTable->EmptyString();
  1457. return mActivePackages[index];
  1458. }
  1459. void Namespace::activatePackage(StringTableEntry name)
  1460. {
  1461. if (mNumActivePackages == MaxActivePackages)
  1462. {
  1463. Con::printf("ActivatePackage(%s) failed - Max package limit reached: %d", name, MaxActivePackages);
  1464. return;
  1465. }
  1466. if (!name)
  1467. return;
  1468. // see if this one's already active
  1469. for (U32 i = 0; i < mNumActivePackages; i++)
  1470. if (mActivePackages[i] == name)
  1471. return;
  1472. // kill the cache
  1473. trashCache();
  1474. // find all the package namespaces...
  1475. for (Namespace *walk = mNamespaceList; walk; walk = walk->mNext)
  1476. {
  1477. if (walk->mPackage == name)
  1478. {
  1479. Namespace *parent = Namespace::find(walk->mName);
  1480. // hook the parent
  1481. walk->mParent = parent->mParent;
  1482. parent->mParent = walk;
  1483. // now swap the entries:
  1484. Entry *ew;
  1485. for (ew = parent->mEntryList; ew; ew = ew->mNext)
  1486. ew->mNamespace = walk;
  1487. for (ew = walk->mEntryList; ew; ew = ew->mNext)
  1488. ew->mNamespace = parent;
  1489. ew = walk->mEntryList;
  1490. walk->mEntryList = parent->mEntryList;
  1491. parent->mEntryList = ew;
  1492. }
  1493. }
  1494. mActivePackages[mNumActivePackages++] = name;
  1495. }
  1496. void Namespace::deactivatePackage(StringTableEntry name)
  1497. {
  1498. U32 oldNumActivePackages = mNumActivePackages;
  1499. // Remove all packages down to the given one
  1500. deactivatePackageStack(name);
  1501. // Now add back all packages that followed the given one
  1502. if (!oldNumActivePackages)
  1503. return;
  1504. for (U32 i = mNumActivePackages + 1; i < oldNumActivePackages; i++)
  1505. activatePackage(mActivePackages[i]);
  1506. }
  1507. void Namespace::deactivatePackageStack(StringTableEntry name)
  1508. {
  1509. S32 i, j;
  1510. for (i = 0; i < mNumActivePackages; i++)
  1511. if (mActivePackages[i] == name)
  1512. break;
  1513. if (i == mNumActivePackages)
  1514. return;
  1515. trashCache();
  1516. // Remove all packages down to the given one
  1517. for (j = mNumActivePackages - 1; j >= i; j--)
  1518. {
  1519. // gotta unlink em in reverse order...
  1520. for (Namespace *walk = mNamespaceList; walk; walk = walk->mNext)
  1521. {
  1522. if (walk->mPackage == mActivePackages[j])
  1523. {
  1524. Namespace *parent = Namespace::find(walk->mName);
  1525. // hook the parent
  1526. parent->mParent = walk->mParent;
  1527. walk->mParent = NULL;
  1528. // now swap the entries:
  1529. Entry *ew;
  1530. for (ew = parent->mEntryList; ew; ew = ew->mNext)
  1531. ew->mNamespace = walk;
  1532. for (ew = walk->mEntryList; ew; ew = ew->mNext)
  1533. ew->mNamespace = parent;
  1534. ew = walk->mEntryList;
  1535. walk->mEntryList = parent->mEntryList;
  1536. parent->mEntryList = ew;
  1537. }
  1538. }
  1539. }
  1540. mNumActivePackages = i;
  1541. }
  1542. void Namespace::unlinkPackages()
  1543. {
  1544. mOldNumActivePackages = mNumActivePackages;
  1545. if (!mNumActivePackages)
  1546. return;
  1547. deactivatePackageStack(mActivePackages[0]);
  1548. }
  1549. void Namespace::relinkPackages()
  1550. {
  1551. if (!mOldNumActivePackages)
  1552. return;
  1553. for (U32 i = 0; i < mOldNumActivePackages; i++)
  1554. activatePackage(mActivePackages[i]);
  1555. }
  1556. DefineEngineFunction(isPackage, bool, (String identifier), ,
  1557. "@brief Returns true if the identifier is the name of a declared package.\n\n"
  1558. "@ingroup Packages\n")
  1559. {
  1560. StringTableEntry name = StringTable->insert(identifier.c_str());
  1561. return Namespace::isPackage(name);
  1562. }
  1563. DefineEngineFunction(activatePackage, void, (String packageName), ,
  1564. "@brief Activates an existing package.\n\n"
  1565. "The activation occurs by updating the namespace linkage of existing functions and methods. "
  1566. "If the package is already activated the function does nothing.\n"
  1567. "@ingroup Packages\n")
  1568. {
  1569. StringTableEntry name = StringTable->insert(packageName.c_str());
  1570. Namespace::activatePackage(name);
  1571. }
  1572. DefineEngineFunction(deactivatePackage, void, (String packageName), ,
  1573. "@brief Deactivates a previously activated package.\n\n"
  1574. "The package is deactivated by removing its namespace linkages to any function or method. "
  1575. "If there are any packages above this one in the stack they are deactivated as well. "
  1576. "If the package is not on the stack this function does nothing.\n"
  1577. "@ingroup Packages\n")
  1578. {
  1579. StringTableEntry name = StringTable->insert(packageName.c_str());
  1580. Namespace::deactivatePackage(name);
  1581. }
  1582. DefineEngineFunction(getPackageList, const char*, (), ,
  1583. "@brief Returns a space delimited list of the active packages in stack order.\n\n"
  1584. "@ingroup Packages\n")
  1585. {
  1586. if (Namespace::getActivePackagesCount() == 0)
  1587. return "";
  1588. // Determine size of return buffer
  1589. dsize_t buffersize = 0;
  1590. for (U32 i = 0; i < Namespace::getActivePackagesCount(); ++i)
  1591. {
  1592. buffersize += dStrlen(Namespace::getActivePackage(i)) + 1;
  1593. }
  1594. U32 maxBufferSize = buffersize + 1;
  1595. char* returnBuffer = Con::getReturnBuffer(maxBufferSize);
  1596. U32 returnLen = 0;
  1597. for (U32 i = 0; i < Namespace::getActivePackagesCount(); ++i)
  1598. {
  1599. dSprintf(returnBuffer + returnLen, maxBufferSize - returnLen, "%s ", Namespace::getActivePackage(i));
  1600. returnLen = dStrlen(returnBuffer);
  1601. }
  1602. // Trim off the last extra space
  1603. if (returnLen > 0 && returnBuffer[returnLen - 1] == ' ')
  1604. returnBuffer[returnLen - 1] = '\0';
  1605. return returnBuffer;
  1606. }