consoleInternal.cpp 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872
  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)->value.getType())
  161. {
  162. case ConsoleValueType::cvInteger:
  163. dSprintf(buffer, sizeof(buffer), "%s = %d;%s", (*s)->name, (*s)->value.getInt(), cat);
  164. break;
  165. case ConsoleValueType::cvFloat:
  166. dSprintf(buffer, sizeof(buffer), "%s = %g;%s", (*s)->name, (*s)->value.getFloat(), 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)->value.getType())
  211. {
  212. case ConsoleValueType::cvInteger:
  213. case ConsoleValueType::cvFloat:
  214. values->push_back(String((*s)->value.getString()));
  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. // NOTE: This is data inside a nameless
  398. // union, so we don't need to init the rest.
  399. value.init();
  400. }
  401. Dictionary::Entry::~Entry()
  402. {
  403. value.cleanup();
  404. if (notify)
  405. delete notify;
  406. }
  407. const char *Dictionary::getVariable(StringTableEntry name, bool *entValid)
  408. {
  409. Entry *ent = lookup(name);
  410. if (ent)
  411. {
  412. if (entValid)
  413. *entValid = true;
  414. return ent->getStringValue();
  415. }
  416. if (entValid)
  417. *entValid = false;
  418. // Warn users when they access a variable that isn't defined.
  419. if (gWarnUndefinedScriptVariables)
  420. Con::warnf(" *** Accessed undefined variable '%s'", name);
  421. return "";
  422. }
  423. S32 Dictionary::getIntVariable(StringTableEntry name, bool *entValid)
  424. {
  425. Entry *ent = lookup(name);
  426. if (ent)
  427. {
  428. if (entValid)
  429. *entValid = true;
  430. return ent->getIntValue();
  431. }
  432. if (entValid)
  433. *entValid = false;
  434. return 0;
  435. }
  436. F32 Dictionary::getFloatVariable(StringTableEntry name, bool *entValid)
  437. {
  438. Entry *ent = lookup(name);
  439. if (ent)
  440. {
  441. if (entValid)
  442. *entValid = true;
  443. return ent->getFloatValue();
  444. }
  445. if (entValid)
  446. *entValid = false;
  447. return 0;
  448. }
  449. void Dictionary::setVariable(StringTableEntry name, const char *value)
  450. {
  451. Entry *ent = add(name);
  452. if (!value)
  453. value = "";
  454. ent->setStringValue(value);
  455. }
  456. Dictionary::Entry* Dictionary::addVariable(const char *name,
  457. S32 type,
  458. void *dataPtr,
  459. const char* usage)
  460. {
  461. AssertFatal(type >= 0, "Dictionary::addVariable - Got bad type!");
  462. if (name[0] != '$')
  463. {
  464. scratchBuffer[0] = '$';
  465. dStrcpy(scratchBuffer + 1, name, 1023);
  466. name = scratchBuffer;
  467. }
  468. Entry *ent = add(StringTable->insert(name));
  469. if (ent->value.type <= ConsoleValue::TypeInternalString &&
  470. ent->value.bufferLen > 0)
  471. dFree(ent->value.sval);
  472. ent->value.type = type;
  473. ent->value.dataPtr = dataPtr;
  474. ent->mUsage = usage;
  475. // Fetch enum table, if any.
  476. ConsoleBaseType* conType = ConsoleBaseType::getType(type);
  477. AssertFatal(conType, "Dictionary::addVariable - invalid console type");
  478. ent->value.enumTable = conType->getEnumTable();
  479. return ent;
  480. }
  481. bool Dictionary::removeVariable(StringTableEntry name)
  482. {
  483. if (Entry *ent = lookup(name))
  484. {
  485. remove(ent);
  486. return true;
  487. }
  488. return false;
  489. }
  490. void Dictionary::addVariableNotify(const char *name, const Con::NotifyDelegate &callback)
  491. {
  492. Entry *ent = lookup(StringTable->insert(name));
  493. if (!ent)
  494. return;
  495. if (!ent->notify)
  496. ent->notify = new Entry::NotifySignal();
  497. ent->notify->notify(callback);
  498. }
  499. void Dictionary::removeVariableNotify(const char *name, const Con::NotifyDelegate &callback)
  500. {
  501. Entry *ent = lookup(StringTable->insert(name));
  502. if (ent && ent->notify)
  503. ent->notify->remove(callback);
  504. }
  505. void Dictionary::validate()
  506. {
  507. AssertFatal(ownHashTable.owner == this,
  508. "Dictionary::validate() - Dictionary not owner of own hashtable!");
  509. }
  510. void ExprEvalState::pushFrame(StringTableEntry frameName, Namespace *ns)
  511. {
  512. #ifdef DEBUG_SPEW
  513. validate();
  514. Platform::outputDebugString("[ConsoleInternal] Pushing new frame for '%s' at %i",
  515. frameName, mStackDepth);
  516. #endif
  517. if (mStackDepth + 1 > stack.size())
  518. {
  519. #ifdef DEBUG_SPEW
  520. Platform::outputDebugString("[ConsoleInternal] Growing stack by one frame");
  521. #endif
  522. stack.push_back(new Dictionary);
  523. }
  524. Dictionary& newFrame = *(stack[mStackDepth]);
  525. newFrame.setState(this);
  526. newFrame.scopeName = frameName;
  527. newFrame.scopeNamespace = ns;
  528. mStackDepth++;
  529. currentVariable = NULL;
  530. AssertFatal(!newFrame.getCount(), "ExprEvalState::pushFrame - Dictionary not empty!");
  531. #ifdef DEBUG_SPEW
  532. validate();
  533. #endif
  534. }
  535. void ExprEvalState::popFrame()
  536. {
  537. AssertFatal(mStackDepth > 0, "ExprEvalState::popFrame - Stack Underflow!");
  538. #ifdef DEBUG_SPEW
  539. validate();
  540. Platform::outputDebugString("[ConsoleInternal] Popping %sframe at %i",
  541. getCurrentFrame().isOwner() ? "" : "shared ", mStackDepth - 1);
  542. #endif
  543. mStackDepth--;
  544. stack[mStackDepth]->reset();
  545. currentVariable = NULL;
  546. #ifdef DEBUG_SPEW
  547. validate();
  548. #endif
  549. }
  550. void ExprEvalState::pushFrameRef(S32 stackIndex)
  551. {
  552. AssertFatal(stackIndex >= 0 && stackIndex < stack.size(), "You must be asking for a valid frame!");
  553. #ifdef DEBUG_SPEW
  554. validate();
  555. Platform::outputDebugString("[ConsoleInternal] Cloning frame from %i to %i",
  556. stackIndex, mStackDepth);
  557. #endif
  558. if (mStackDepth + 1 > stack.size())
  559. {
  560. #ifdef DEBUG_SPEW
  561. Platform::outputDebugString("[ConsoleInternal] Growing stack by one frame");
  562. #endif
  563. stack.push_back(new Dictionary);
  564. }
  565. Dictionary& newFrame = *(stack[mStackDepth]);
  566. newFrame.setState(this, stack[stackIndex]);
  567. mStackDepth++;
  568. currentVariable = NULL;
  569. #ifdef DEBUG_SPEW
  570. validate();
  571. #endif
  572. }
  573. ExprEvalState::ExprEvalState()
  574. {
  575. VECTOR_SET_ASSOCIATION(stack);
  576. globalVars.setState(this);
  577. thisObject = NULL;
  578. traceOn = false;
  579. currentVariable = NULL;
  580. mStackDepth = 0;
  581. stack.reserve(64);
  582. mShouldReset = false;
  583. mResetLocked = false;
  584. copyVariable = NULL;
  585. }
  586. ExprEvalState::~ExprEvalState()
  587. {
  588. // Delete callframes.
  589. while (!stack.empty())
  590. {
  591. delete stack.last();
  592. stack.decrement();
  593. }
  594. }
  595. void ExprEvalState::validate()
  596. {
  597. AssertFatal(mStackDepth <= stack.size(),
  598. "ExprEvalState::validate() - Stack depth pointing beyond last stack frame!");
  599. for (U32 i = 0; i < stack.size(); ++i)
  600. stack[i]->validate();
  601. }
  602. DefineEngineFunction(backtrace, void, (), ,
  603. "@brief Prints the scripting call stack to the console log.\n\n"
  604. "Used to trace functions called from within functions. Can help discover what functions were called "
  605. "(and not yet exited) before the current point in scripts.\n\n"
  606. "@ingroup Debugging")
  607. {
  608. U32 totalSize = 1;
  609. for (U32 i = 0; i < gEvalState.getStackDepth(); i++)
  610. {
  611. if (gEvalState.stack[i]->scopeNamespace && gEvalState.stack[i]->scopeNamespace->mEntryList->mPackage)
  612. totalSize += dStrlen(gEvalState.stack[i]->scopeNamespace->mEntryList->mPackage) + 2;
  613. if (gEvalState.stack[i]->scopeName)
  614. totalSize += dStrlen(gEvalState.stack[i]->scopeName) + 3;
  615. if (gEvalState.stack[i]->scopeNamespace && gEvalState.stack[i]->scopeNamespace->mName)
  616. totalSize += dStrlen(gEvalState.stack[i]->scopeNamespace->mName) + 2;
  617. }
  618. char *buf = Con::getReturnBuffer(totalSize);
  619. buf[0] = 0;
  620. for (U32 i = 0; i < gEvalState.getStackDepth(); i++)
  621. {
  622. dStrcat(buf, "->", totalSize);
  623. if (gEvalState.stack[i]->scopeNamespace && gEvalState.stack[i]->scopeNamespace->mEntryList->mPackage)
  624. {
  625. dStrcat(buf, "[", totalSize);
  626. dStrcat(buf, gEvalState.stack[i]->scopeNamespace->mEntryList->mPackage, totalSize);
  627. dStrcat(buf, "]", totalSize);
  628. }
  629. if (gEvalState.stack[i]->scopeNamespace && gEvalState.stack[i]->scopeNamespace->mName)
  630. {
  631. dStrcat(buf, gEvalState.stack[i]->scopeNamespace->mName, totalSize);
  632. dStrcat(buf, "::", totalSize);
  633. }
  634. if (gEvalState.stack[i]->scopeName)
  635. dStrcat(buf, gEvalState.stack[i]->scopeName, totalSize);
  636. }
  637. Con::printf("BackTrace: %s", buf);
  638. }
  639. Namespace::Entry::Entry()
  640. {
  641. mCode = NULL;
  642. mType = InvalidFunctionType;
  643. mUsage = NULL;
  644. mHeader = NULL;
  645. mNamespace = NULL;
  646. cb.mStringCallbackFunc = NULL;
  647. mFunctionLineNumber = 0;
  648. mFunctionName = StringTable->EmptyString();
  649. mFunctionOffset = 0;
  650. mMinArgs = 0;
  651. mMaxArgs = 0;
  652. mNext = NULL;
  653. mPackage = StringTable->EmptyString();
  654. mToolOnly = false;
  655. }
  656. void Namespace::Entry::clear()
  657. {
  658. if (mCode)
  659. {
  660. mCode->decRefCount();
  661. mCode = NULL;
  662. }
  663. // Clean up usage strings generated for script functions.
  664. if ((mType == Namespace::Entry::ConsoleFunctionType) && mUsage)
  665. {
  666. dFree(mUsage);
  667. mUsage = NULL;
  668. }
  669. }
  670. Namespace::Namespace()
  671. {
  672. mPackage = NULL;
  673. mUsage = NULL;
  674. mCleanUpUsage = false;
  675. mName = NULL;
  676. mParent = NULL;
  677. mNext = NULL;
  678. mEntryList = NULL;
  679. mHashSize = 0;
  680. mHashTable = 0;
  681. mHashSequence = 0;
  682. mRefCountToParent = 0;
  683. mClassRep = 0;
  684. lastUsage = NULL;
  685. }
  686. Namespace::~Namespace()
  687. {
  688. clearEntries();
  689. if (mUsage && mCleanUpUsage)
  690. {
  691. dFree(mUsage);
  692. mUsage = NULL;
  693. mCleanUpUsage = false;
  694. }
  695. }
  696. void Namespace::clearEntries()
  697. {
  698. for (Entry *walk = mEntryList; walk; walk = walk->mNext)
  699. walk->clear();
  700. }
  701. Namespace *Namespace::find(StringTableEntry name, StringTableEntry package)
  702. {
  703. if (name == NULL && package == NULL)
  704. return mGlobalNamespace;
  705. auto pair = std::make_pair(name, package);
  706. auto pos = gNamespaceCache.find(pair);
  707. if (pos != gNamespaceCache.end())
  708. return pos->second;
  709. Namespace *ret = (Namespace *)mAllocator.alloc(sizeof(Namespace));
  710. constructInPlace(ret);
  711. ret->mPackage = package;
  712. ret->mName = name;
  713. ret->mNext = mNamespaceList;
  714. mNamespaceList = ret;
  715. // insert into namespace cache.
  716. gNamespaceCache[pair] = ret;
  717. return ret;
  718. }
  719. bool Namespace::unlinkClass(Namespace *parent)
  720. {
  721. AssertFatal(mPackage == NULL, "Namespace::unlinkClass - Must not be called on a namespace coming from a package!");
  722. // Skip additions to this namespace coming from packages.
  723. Namespace* walk = getPackageRoot();
  724. // Make sure "parent" is the direct parent namespace.
  725. if (parent != NULL && walk->mParent && walk->mParent != parent)
  726. {
  727. Con::errorf(ConsoleLogEntry::General, "Namespace::unlinkClass - cannot unlink namespace parent linkage for %s for %s.",
  728. walk->mName, walk->mParent->mName);
  729. return false;
  730. }
  731. // Decrease the reference count. Note that we do this on
  732. // the bottom-most namespace, i.e. the one guaranteed not
  733. // to come from a package.
  734. mRefCountToParent--;
  735. AssertFatal(mRefCountToParent >= 0, "Namespace::unlinkClass - reference count to parent is less than 0");
  736. // Unlink if the count dropped to zero.
  737. if (mRefCountToParent == 0)
  738. {
  739. walk->mParent = NULL;
  740. trashCache();
  741. }
  742. return true;
  743. }
  744. bool Namespace::classLinkTo(Namespace *parent)
  745. {
  746. Namespace* walk = getPackageRoot();
  747. if (walk->mParent && walk->mParent != parent)
  748. {
  749. Con::errorf(ConsoleLogEntry::General, "Error: cannot change namespace parent linkage of %s from %s to %s.",
  750. walk->mName, walk->mParent->mName, parent->mName);
  751. return false;
  752. }
  753. trashCache();
  754. walk->mParent = parent;
  755. mRefCountToParent++;
  756. return true;
  757. }
  758. void Namespace::buildHashTable()
  759. {
  760. if (mHashSequence == mCacheSequence)
  761. return;
  762. if (!mEntryList && mParent)
  763. {
  764. mParent->buildHashTable();
  765. mHashTable = mParent->mHashTable;
  766. mHashSize = mParent->mHashSize;
  767. mHashSequence = mCacheSequence;
  768. return;
  769. }
  770. U32 entryCount = 0;
  771. Namespace * ns;
  772. for (ns = this; ns; ns = ns->mParent)
  773. for (Entry *walk = ns->mEntryList; walk; walk = walk->mNext)
  774. if (lookupRecursive(walk->mFunctionName) == walk)
  775. entryCount++;
  776. mHashSize = entryCount + (entryCount >> 1) + 1;
  777. if (!(mHashSize & 1))
  778. mHashSize++;
  779. mHashTable = (Entry **)mCacheAllocator.alloc(sizeof(Entry *) * mHashSize);
  780. for (U32 i = 0; i < mHashSize; i++)
  781. mHashTable[i] = NULL;
  782. for (ns = this; ns; ns = ns->mParent)
  783. {
  784. for (Entry *walk = ns->mEntryList; walk; walk = walk->mNext)
  785. {
  786. U32 index = HashPointer(walk->mFunctionName) % mHashSize;
  787. while (mHashTable[index] && mHashTable[index]->mFunctionName != walk->mFunctionName)
  788. {
  789. index++;
  790. if (index >= mHashSize)
  791. index = 0;
  792. }
  793. if (!mHashTable[index])
  794. mHashTable[index] = walk;
  795. }
  796. }
  797. mHashSequence = mCacheSequence;
  798. }
  799. void Namespace::getUniqueEntryLists(Namespace *other, VectorPtr<Entry *> *outThisList, VectorPtr<Entry *> *outOtherList)
  800. {
  801. // All namespace entries in the common ACR should be
  802. // ignored when checking for duplicate entry names.
  803. static VectorPtr<Namespace::Entry *> commonEntries;
  804. commonEntries.clear();
  805. AbstractClassRep *commonACR = mClassRep->getCommonParent(other->mClassRep);
  806. commonACR->getNameSpace()->getEntryList(&commonEntries);
  807. // Make life easier
  808. VectorPtr<Namespace::Entry *> &thisEntries = *outThisList;
  809. VectorPtr<Namespace::Entry *> &compEntries = *outOtherList;
  810. // Clear, just in case they aren't
  811. thisEntries.clear();
  812. compEntries.clear();
  813. getEntryList(&thisEntries);
  814. other->getEntryList(&compEntries);
  815. // Run through all of the entries in the common ACR, and remove them from
  816. // the other two entry lists
  817. for (NamespaceEntryListIterator itr = commonEntries.begin(); itr != commonEntries.end(); itr++)
  818. {
  819. // Check this entry list
  820. for (NamespaceEntryListIterator thisItr = thisEntries.begin(); thisItr != thisEntries.end(); thisItr++)
  821. {
  822. if (*thisItr == *itr)
  823. {
  824. thisEntries.erase(thisItr);
  825. break;
  826. }
  827. }
  828. // Same check for component entry list
  829. for (NamespaceEntryListIterator compItr = compEntries.begin(); compItr != compEntries.end(); compItr++)
  830. {
  831. if (*compItr == *itr)
  832. {
  833. compEntries.erase(compItr);
  834. break;
  835. }
  836. }
  837. }
  838. }
  839. void Namespace::init()
  840. {
  841. // create the global namespace
  842. mGlobalNamespace = (Namespace *)mAllocator.alloc(sizeof(Namespace));
  843. constructInPlace(mGlobalNamespace);
  844. mGlobalNamespace->mPackage = NULL;
  845. mGlobalNamespace->mName = NULL;
  846. mGlobalNamespace->mNext = NULL;
  847. mNamespaceList = mGlobalNamespace;
  848. // Insert into namespace cache.
  849. gNamespaceCache[std::make_pair(mGlobalNamespace->mName, mGlobalNamespace->mPackage)] = mGlobalNamespace;
  850. }
  851. Namespace *Namespace::global()
  852. {
  853. return mGlobalNamespace;
  854. }
  855. void Namespace::shutdown()
  856. {
  857. // The data chunker will release all memory in one go
  858. // without calling destructors, so we do this manually here.
  859. for (Namespace *walk = mNamespaceList; walk; walk = walk->mNext)
  860. walk->~Namespace();
  861. }
  862. void Namespace::trashCache()
  863. {
  864. mCacheSequence++;
  865. mCacheAllocator.freeBlocks();
  866. }
  867. const char *Namespace::tabComplete(const char *prevText, S32 baseLen, bool fForward)
  868. {
  869. if (mHashSequence != mCacheSequence)
  870. buildHashTable();
  871. const char *bestMatch = NULL;
  872. for (U32 i = 0; i < mHashSize; i++)
  873. if (mHashTable[i] && canTabComplete(prevText, bestMatch, mHashTable[i]->mFunctionName, baseLen, fForward))
  874. bestMatch = mHashTable[i]->mFunctionName;
  875. return bestMatch;
  876. }
  877. Namespace::Entry *Namespace::lookupRecursive(StringTableEntry name)
  878. {
  879. for (Namespace *ns = this; ns; ns = ns->mParent)
  880. for (Entry *walk = ns->mEntryList; walk; walk = walk->mNext)
  881. if (walk->mFunctionName == name)
  882. return walk;
  883. return NULL;
  884. }
  885. Namespace::Entry *Namespace::lookup(StringTableEntry name)
  886. {
  887. if (mHashSequence != mCacheSequence)
  888. buildHashTable();
  889. U32 index = HashPointer(name) % mHashSize;
  890. while (mHashTable[index] && mHashTable[index]->mFunctionName != name)
  891. {
  892. index++;
  893. if (index >= mHashSize)
  894. index = 0;
  895. }
  896. return mHashTable[index];
  897. }
  898. static S32 QSORT_CALLBACK compareEntries(const void* a, const void* b)
  899. {
  900. const Namespace::Entry* fa = *((Namespace::Entry**)a);
  901. const Namespace::Entry* fb = *((Namespace::Entry**)b);
  902. return dStricmp(fa->mFunctionName, fb->mFunctionName);
  903. }
  904. void Namespace::getEntryList(VectorPtr<Entry *> *vec)
  905. {
  906. if (mHashSequence != mCacheSequence)
  907. buildHashTable();
  908. for (U32 i = 0; i < mHashSize; i++)
  909. if (mHashTable[i])
  910. vec->push_back(mHashTable[i]);
  911. dQsort(vec->address(), vec->size(), sizeof(Namespace::Entry *), compareEntries);
  912. }
  913. Namespace::Entry *Namespace::createLocalEntry(StringTableEntry name)
  914. {
  915. for (Entry *walk = mEntryList; walk; walk = walk->mNext)
  916. {
  917. if (walk->mFunctionName == name)
  918. {
  919. walk->clear();
  920. return walk;
  921. }
  922. }
  923. Entry *ent = (Entry *)mAllocator.alloc(sizeof(Entry));
  924. constructInPlace(ent);
  925. ent->mNamespace = this;
  926. ent->mFunctionName = name;
  927. ent->mNext = mEntryList;
  928. ent->mPackage = mPackage;
  929. ent->mToolOnly = false;
  930. mEntryList = ent;
  931. return ent;
  932. }
  933. void Namespace::addFunction(StringTableEntry name, CodeBlock *cb, U32 functionOffset, const char* usage, U32 lineNumber)
  934. {
  935. Entry *ent = createLocalEntry(name);
  936. trashCache();
  937. ent->mUsage = usage;
  938. ent->mCode = cb;
  939. ent->mFunctionOffset = functionOffset;
  940. ent->mCode->incRefCount();
  941. ent->mType = Entry::ConsoleFunctionType;
  942. ent->mFunctionLineNumber = lineNumber;
  943. }
  944. void Namespace::addCommand(StringTableEntry name, StringCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header)
  945. {
  946. Entry *ent = createLocalEntry(name);
  947. trashCache();
  948. ent->mUsage = usage;
  949. ent->mHeader = header;
  950. ent->mMinArgs = minArgs;
  951. ent->mMaxArgs = maxArgs;
  952. ent->mToolOnly = isToolOnly;
  953. ent->mType = Entry::StringCallbackType;
  954. ent->cb.mStringCallbackFunc = cb;
  955. }
  956. void Namespace::addCommand(StringTableEntry name, IntCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header)
  957. {
  958. Entry *ent = createLocalEntry(name);
  959. trashCache();
  960. ent->mUsage = usage;
  961. ent->mHeader = header;
  962. ent->mMinArgs = minArgs;
  963. ent->mMaxArgs = maxArgs;
  964. ent->mToolOnly = isToolOnly;
  965. ent->mType = Entry::IntCallbackType;
  966. ent->cb.mIntCallbackFunc = cb;
  967. }
  968. void Namespace::addCommand(StringTableEntry name, VoidCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header)
  969. {
  970. Entry *ent = createLocalEntry(name);
  971. trashCache();
  972. ent->mUsage = usage;
  973. ent->mHeader = header;
  974. ent->mMinArgs = minArgs;
  975. ent->mMaxArgs = maxArgs;
  976. ent->mToolOnly = isToolOnly;
  977. ent->mType = Entry::VoidCallbackType;
  978. ent->cb.mVoidCallbackFunc = cb;
  979. }
  980. void Namespace::addCommand(StringTableEntry name, FloatCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header)
  981. {
  982. Entry *ent = createLocalEntry(name);
  983. trashCache();
  984. ent->mUsage = usage;
  985. ent->mHeader = header;
  986. ent->mMinArgs = minArgs;
  987. ent->mMaxArgs = maxArgs;
  988. ent->mToolOnly = isToolOnly;
  989. ent->mType = Entry::FloatCallbackType;
  990. ent->cb.mFloatCallbackFunc = cb;
  991. }
  992. void Namespace::addCommand(StringTableEntry name, BoolCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header)
  993. {
  994. Entry *ent = createLocalEntry(name);
  995. trashCache();
  996. ent->mUsage = usage;
  997. ent->mHeader = header;
  998. ent->mMinArgs = minArgs;
  999. ent->mMaxArgs = maxArgs;
  1000. ent->mToolOnly = isToolOnly;
  1001. ent->mType = Entry::BoolCallbackType;
  1002. ent->cb.mBoolCallbackFunc = cb;
  1003. }
  1004. void Namespace::addScriptCallback(const char *funcName, const char *usage, ConsoleFunctionHeader* header)
  1005. {
  1006. static U32 uid = 0;
  1007. char buffer[1024];
  1008. char lilBuffer[32];
  1009. dStrcpy(buffer, funcName, 1024);
  1010. dSprintf(lilBuffer, 32, "_%d_cb", uid++);
  1011. dStrcat(buffer, lilBuffer, 1024);
  1012. Entry *ent = createLocalEntry(StringTable->insert(buffer));
  1013. trashCache();
  1014. ent->mUsage = usage;
  1015. ent->mHeader = header;
  1016. ent->mMinArgs = -2;
  1017. ent->mMaxArgs = -3;
  1018. ent->mType = Entry::ScriptCallbackType;
  1019. ent->cb.mCallbackName = funcName;
  1020. }
  1021. void Namespace::markGroup(const char* name, const char* usage)
  1022. {
  1023. static U32 uid = 0;
  1024. char buffer[1024];
  1025. char lilBuffer[32];
  1026. dStrcpy(buffer, name, 1024);
  1027. dSprintf(lilBuffer, 32, "_%d", uid++);
  1028. dStrcat(buffer, lilBuffer, 1024);
  1029. Entry *ent = createLocalEntry(StringTable->insert(buffer));
  1030. trashCache();
  1031. if (usage != NULL)
  1032. lastUsage = (char*)(ent->mUsage = usage);
  1033. else
  1034. ent->mUsage = lastUsage;
  1035. ent->mMinArgs = -1; // Make sure it explodes if somehow we run this entry.
  1036. ent->mMaxArgs = -2;
  1037. ent->mType = Entry::GroupMarker;
  1038. ent->cb.mGroupName = name;
  1039. }
  1040. extern S32 executeBlock(StmtNode *block, ExprEvalState *state);
  1041. ConsoleValueRef Namespace::Entry::execute(S32 argc, ConsoleValueRef *argv, ExprEvalState *state)
  1042. {
  1043. STR.clearFunctionOffset();
  1044. if (mType == ConsoleFunctionType)
  1045. {
  1046. if (mFunctionOffset)
  1047. {
  1048. return mCode->exec(mFunctionOffset, argv[0], mNamespace, argc, argv, false, mPackage);
  1049. }
  1050. else
  1051. {
  1052. return ConsoleValueRef();
  1053. }
  1054. }
  1055. #ifndef TORQUE_DEBUG
  1056. // [tom, 12/13/2006] This stops tools functions from working in the console,
  1057. // which is useful behavior when debugging so I'm ifdefing this out for debug builds.
  1058. if (mToolOnly && !Con::isCurrentScriptToolScript())
  1059. {
  1060. Con::errorf(ConsoleLogEntry::Script, "%s::%s - attempting to call tools only function from outside of tools", mNamespace->mName, mFunctionName);
  1061. return ConsoleValueRef();
  1062. }
  1063. #endif
  1064. if ((mMinArgs && argc < mMinArgs) || (mMaxArgs && argc > mMaxArgs))
  1065. {
  1066. Con::warnf(ConsoleLogEntry::Script, "%s::%s - wrong number of arguments.", mNamespace->mName, mFunctionName);
  1067. Con::warnf(ConsoleLogEntry::Script, "usage: %s", mUsage);
  1068. return ConsoleValueRef();
  1069. }
  1070. switch (mType)
  1071. {
  1072. case StringCallbackType:
  1073. return ConsoleValueRef::fromValue(CSTK.pushStackString(cb.mStringCallbackFunc(state->thisObject, argc, argv)));
  1074. case IntCallbackType:
  1075. return ConsoleValueRef::fromValue(CSTK.pushUINT((U32)cb.mBoolCallbackFunc(state->thisObject, argc, argv)));
  1076. case FloatCallbackType:
  1077. return ConsoleValueRef::fromValue(CSTK.pushFLT((U32)cb.mBoolCallbackFunc(state->thisObject, argc, argv)));
  1078. case VoidCallbackType:
  1079. cb.mVoidCallbackFunc(state->thisObject, argc, argv);
  1080. return ConsoleValueRef();
  1081. case BoolCallbackType:
  1082. return ConsoleValueRef::fromValue(CSTK.pushUINT((U32)cb.mBoolCallbackFunc(state->thisObject, argc, argv)));
  1083. }
  1084. return ConsoleValueRef();
  1085. }
  1086. //-----------------------------------------------------------------------------
  1087. // Doc string code.
  1088. namespace {
  1089. /// Scan the given usage string for an argument list description. With the
  1090. /// old console macros, these were usually included as the first part of the
  1091. /// usage string.
  1092. bool sFindArgumentListSubstring(const char* usage, const char*& start, const char*& end)
  1093. {
  1094. if (!usage)
  1095. return false;
  1096. const char* ptr = usage;
  1097. while (*ptr && *ptr != '(' && *ptr != '\n') // Only scan first line of usage string.
  1098. {
  1099. // Stop on the first alphanumeric character as we expect
  1100. // argument lists to precede descriptions.
  1101. if (dIsalnum(*ptr))
  1102. return false;
  1103. ptr++;
  1104. }
  1105. if (*ptr != '(')
  1106. return false;
  1107. start = ptr;
  1108. ptr++;
  1109. bool inString = false;
  1110. U32 nestingCount = 0;
  1111. while (*ptr && (*ptr != ')' || nestingCount > 0 || inString))
  1112. {
  1113. if (*ptr == '(')
  1114. nestingCount++;
  1115. else if (*ptr == ')')
  1116. nestingCount--;
  1117. else if (*ptr == '"')
  1118. inString = !inString;
  1119. else if (*ptr == '\\' && ptr[1] == '"')
  1120. ptr++;
  1121. ptr++;
  1122. }
  1123. if (*ptr)
  1124. ptr++;
  1125. end = ptr;
  1126. return true;
  1127. }
  1128. ///
  1129. void sParseList(const char* str, Vector< String >& outList)
  1130. {
  1131. // Skip the initial '( '.
  1132. const char* ptr = str;
  1133. while (*ptr && dIsspace(*ptr))
  1134. ptr++;
  1135. if (*ptr == '(')
  1136. {
  1137. ptr++;
  1138. while (*ptr && dIsspace(*ptr))
  1139. ptr++;
  1140. }
  1141. // Parse out list items.
  1142. while (*ptr && *ptr != ')')
  1143. {
  1144. // Find end of element.
  1145. const char* start = ptr;
  1146. bool inString = false;
  1147. U32 nestingCount = 0;
  1148. while (*ptr && ((*ptr != ')' && *ptr != ',') || nestingCount > 0 || inString))
  1149. {
  1150. if (*ptr == '(')
  1151. nestingCount++;
  1152. else if (*ptr == ')')
  1153. nestingCount--;
  1154. else if (*ptr == '"')
  1155. inString = !inString;
  1156. else if (*ptr == '\\' && ptr[1] == '"')
  1157. ptr++;
  1158. ptr++;
  1159. }
  1160. // Backtrack to remove trailing whitespace.
  1161. const char* end = ptr;
  1162. if (*end == ',' || *end == ')')
  1163. end--;
  1164. while (end > start && dIsspace(*end))
  1165. end--;
  1166. if (*end)
  1167. end++;
  1168. // Add to list.
  1169. if (start != end)
  1170. outList.push_back(String(start, end - start));
  1171. // Skip comma and whitespace.
  1172. if (*ptr == ',')
  1173. ptr++;
  1174. while (*ptr && dIsspace(*ptr))
  1175. ptr++;
  1176. }
  1177. }
  1178. ///
  1179. void sGetArgNameAndType(const String& str, String& outType, String& outName)
  1180. {
  1181. if (!str.length())
  1182. {
  1183. outType = String::EmptyString;
  1184. outName = String::EmptyString;
  1185. return;
  1186. }
  1187. // Find first non-ID character from right.
  1188. S32 index = str.length() - 1;
  1189. while (index >= 0 && (dIsalnum(str[index]) || str[index] == '_'))
  1190. index--;
  1191. const U32 nameStartIndex = index + 1;
  1192. // Find end of type name by skipping rightmost whitespace inwards.
  1193. while (index >= 0 && dIsspace(str[index]))
  1194. index--;
  1195. //
  1196. outName = String(&((const char*)str)[nameStartIndex]);
  1197. outType = String(str, index + 1);
  1198. }
  1199. /// Return the type name to show in documentation for the given C++ type.
  1200. const char* sGetDocTypeString(const char* nativeType)
  1201. {
  1202. if (dStrncmp(nativeType, "const ", 6) == 0)
  1203. nativeType += 6;
  1204. if (String::compare(nativeType, "char*") == 0 || String::compare(nativeType, "char *") == 0)
  1205. return "string";
  1206. else if (String::compare(nativeType, "S32") == 0)
  1207. return "int";
  1208. else if (String::compare(nativeType, "U32") == 0)
  1209. return "uint";
  1210. else if (String::compare(nativeType, "F32") == 0)
  1211. return "float";
  1212. const U32 length = dStrlen(nativeType);
  1213. if (nativeType[length - 1] == '&' || nativeType[length - 1] == '*')
  1214. return StringTable->insertn(nativeType, length - 1);
  1215. return nativeType;
  1216. }
  1217. }
  1218. String Namespace::Entry::getBriefDescription(String* outRemainingDocText) const
  1219. {
  1220. String docString = getDocString();
  1221. S32 newline = docString.find('\n');
  1222. if (newline == -1)
  1223. {
  1224. if (outRemainingDocText)
  1225. *outRemainingDocText = String();
  1226. return docString;
  1227. }
  1228. String brief = docString.substr(0, newline);
  1229. if (outRemainingDocText)
  1230. *outRemainingDocText = docString.substr(newline + 1);
  1231. return brief;
  1232. }
  1233. String Namespace::Entry::getDocString() const
  1234. {
  1235. const char* argListStart;
  1236. const char* argListEnd;
  1237. if (sFindArgumentListSubstring(mUsage, argListStart, argListEnd))
  1238. {
  1239. // Skip the " - " part present in some old doc strings.
  1240. const char* ptr = argListEnd;
  1241. while (*ptr && dIsspace(*ptr))
  1242. ptr++;
  1243. if (*ptr == '-')
  1244. {
  1245. ptr++;
  1246. while (*ptr && dIsspace(*ptr))
  1247. ptr++;
  1248. }
  1249. return ptr;
  1250. }
  1251. return mUsage;
  1252. }
  1253. String Namespace::Entry::getArgumentsString() const
  1254. {
  1255. StringBuilder str;
  1256. if (mHeader)
  1257. {
  1258. // Parse out the argument list string supplied with the extended
  1259. // function header and add default arguments as we go.
  1260. Vector< String > argList;
  1261. Vector< String > defaultArgList;
  1262. sParseList(mHeader->mArgString, argList);
  1263. sParseList(mHeader->mDefaultArgString, defaultArgList);
  1264. str.append('(');
  1265. const U32 numArgs = argList.size();
  1266. const U32 numDefaultArgs = defaultArgList.size();
  1267. const U32 firstDefaultArgIndex = numArgs - numDefaultArgs;
  1268. for (U32 i = 0; i < numArgs; ++i)
  1269. {
  1270. // Add separator if not first arg.
  1271. if (i > 0)
  1272. str.append(',');
  1273. // Add type and name.
  1274. String name;
  1275. String type;
  1276. sGetArgNameAndType(argList[i], type, name);
  1277. str.append(' ');
  1278. str.append(sGetDocTypeString(type));
  1279. str.append(' ');
  1280. str.append(name);
  1281. // Add default value, if any.
  1282. if (i >= firstDefaultArgIndex)
  1283. {
  1284. str.append('=');
  1285. str.append(defaultArgList[i - firstDefaultArgIndex]);
  1286. }
  1287. }
  1288. if (numArgs > 0)
  1289. str.append(' ');
  1290. str.append(')');
  1291. }
  1292. else
  1293. {
  1294. // No extended function header. Try to parse out the argument
  1295. // list from the usage string.
  1296. const char* argListStart;
  1297. const char* argListEnd;
  1298. if (sFindArgumentListSubstring(mUsage, argListStart, argListEnd))
  1299. str.append(argListStart, argListEnd - argListStart);
  1300. else if (mType == ConsoleFunctionType && mCode)
  1301. {
  1302. // This isn't correct but the nonsense console stuff is set up such that all
  1303. // functions that have no function bodies are keyed to offset 0 to indicate "no code."
  1304. // This loses the association with the original function definition so we can't really
  1305. // tell here what the actual prototype is except if we searched though the entire opcode
  1306. // stream for the corresponding OP_FUNC_DECL (which would require dealing with the
  1307. // variable-size instructions).
  1308. if (!mFunctionOffset)
  1309. return "()";
  1310. String args = mCode->getFunctionArgs(mFunctionOffset);
  1311. if (args.isEmpty())
  1312. return "()";
  1313. str.append("( ");
  1314. str.append(args);
  1315. str.append(" )");
  1316. }
  1317. }
  1318. return str.end();
  1319. }
  1320. String Namespace::Entry::getPrototypeString() const
  1321. {
  1322. StringBuilder str;
  1323. // Start with return type.
  1324. if (mHeader && mHeader->mReturnString)
  1325. {
  1326. str.append(sGetDocTypeString(mHeader->mReturnString));
  1327. str.append(' ');
  1328. }
  1329. else
  1330. switch (mType)
  1331. {
  1332. case StringCallbackType:
  1333. str.append("string ");
  1334. break;
  1335. case IntCallbackType:
  1336. str.append("int ");
  1337. break;
  1338. case FloatCallbackType:
  1339. str.append("float ");
  1340. break;
  1341. case VoidCallbackType:
  1342. str.append("void ");
  1343. break;
  1344. case BoolCallbackType:
  1345. str.append("bool ");
  1346. break;
  1347. case ScriptCallbackType:
  1348. break;
  1349. }
  1350. // Add function name and arguments.
  1351. if (mType == ScriptCallbackType)
  1352. str.append(cb.mCallbackName);
  1353. else
  1354. str.append(mFunctionName);
  1355. str.append(getArgumentsString());
  1356. return str.end();
  1357. }
  1358. //-----------------------------------------------------------------------------
  1359. StringTableEntry Namespace::mActivePackages[Namespace::MaxActivePackages];
  1360. U32 Namespace::mNumActivePackages = 0;
  1361. U32 Namespace::mOldNumActivePackages = 0;
  1362. bool Namespace::isPackage(StringTableEntry name)
  1363. {
  1364. for (Namespace *walk = mNamespaceList; walk; walk = walk->mNext)
  1365. if (walk->mPackage == name)
  1366. return true;
  1367. return false;
  1368. }
  1369. U32 Namespace::getActivePackagesCount()
  1370. {
  1371. return mNumActivePackages;
  1372. }
  1373. StringTableEntry Namespace::getActivePackage(U32 index)
  1374. {
  1375. if (index >= mNumActivePackages)
  1376. return StringTable->EmptyString();
  1377. return mActivePackages[index];
  1378. }
  1379. void Namespace::activatePackage(StringTableEntry name)
  1380. {
  1381. if (mNumActivePackages == MaxActivePackages)
  1382. {
  1383. Con::printf("ActivatePackage(%s) failed - Max package limit reached: %d", name, MaxActivePackages);
  1384. return;
  1385. }
  1386. if (!name)
  1387. return;
  1388. // see if this one's already active
  1389. for (U32 i = 0; i < mNumActivePackages; i++)
  1390. if (mActivePackages[i] == name)
  1391. return;
  1392. // kill the cache
  1393. trashCache();
  1394. // find all the package namespaces...
  1395. for (Namespace *walk = mNamespaceList; walk; walk = walk->mNext)
  1396. {
  1397. if (walk->mPackage == name)
  1398. {
  1399. Namespace *parent = Namespace::find(walk->mName);
  1400. // hook the parent
  1401. walk->mParent = parent->mParent;
  1402. parent->mParent = walk;
  1403. // now swap the entries:
  1404. Entry *ew;
  1405. for (ew = parent->mEntryList; ew; ew = ew->mNext)
  1406. ew->mNamespace = walk;
  1407. for (ew = walk->mEntryList; ew; ew = ew->mNext)
  1408. ew->mNamespace = parent;
  1409. ew = walk->mEntryList;
  1410. walk->mEntryList = parent->mEntryList;
  1411. parent->mEntryList = ew;
  1412. }
  1413. }
  1414. mActivePackages[mNumActivePackages++] = name;
  1415. }
  1416. void Namespace::deactivatePackage(StringTableEntry name)
  1417. {
  1418. U32 oldNumActivePackages = mNumActivePackages;
  1419. // Remove all packages down to the given one
  1420. deactivatePackageStack(name);
  1421. // Now add back all packages that followed the given one
  1422. if (!oldNumActivePackages)
  1423. return;
  1424. for (U32 i = mNumActivePackages + 1; i < oldNumActivePackages; i++)
  1425. activatePackage(mActivePackages[i]);
  1426. }
  1427. void Namespace::deactivatePackageStack(StringTableEntry name)
  1428. {
  1429. S32 i, j;
  1430. for (i = 0; i < mNumActivePackages; i++)
  1431. if (mActivePackages[i] == name)
  1432. break;
  1433. if (i == mNumActivePackages)
  1434. return;
  1435. trashCache();
  1436. // Remove all packages down to the given one
  1437. for (j = mNumActivePackages - 1; j >= i; j--)
  1438. {
  1439. // gotta unlink em in reverse order...
  1440. for (Namespace *walk = mNamespaceList; walk; walk = walk->mNext)
  1441. {
  1442. if (walk->mPackage == mActivePackages[j])
  1443. {
  1444. Namespace *parent = Namespace::find(walk->mName);
  1445. // hook the parent
  1446. parent->mParent = walk->mParent;
  1447. walk->mParent = NULL;
  1448. // now swap the entries:
  1449. Entry *ew;
  1450. for (ew = parent->mEntryList; ew; ew = ew->mNext)
  1451. ew->mNamespace = walk;
  1452. for (ew = walk->mEntryList; ew; ew = ew->mNext)
  1453. ew->mNamespace = parent;
  1454. ew = walk->mEntryList;
  1455. walk->mEntryList = parent->mEntryList;
  1456. parent->mEntryList = ew;
  1457. }
  1458. }
  1459. }
  1460. mNumActivePackages = i;
  1461. }
  1462. void Namespace::unlinkPackages()
  1463. {
  1464. mOldNumActivePackages = mNumActivePackages;
  1465. if (!mNumActivePackages)
  1466. return;
  1467. deactivatePackageStack(mActivePackages[0]);
  1468. }
  1469. void Namespace::relinkPackages()
  1470. {
  1471. if (!mOldNumActivePackages)
  1472. return;
  1473. for (U32 i = 0; i < mOldNumActivePackages; i++)
  1474. activatePackage(mActivePackages[i]);
  1475. }
  1476. DefineEngineFunction(isPackage, bool, (String identifier), ,
  1477. "@brief Returns true if the identifier is the name of a declared package.\n\n"
  1478. "@ingroup Packages\n")
  1479. {
  1480. StringTableEntry name = StringTable->insert(identifier.c_str());
  1481. return Namespace::isPackage(name);
  1482. }
  1483. DefineEngineFunction(activatePackage, void, (String packageName), ,
  1484. "@brief Activates an existing package.\n\n"
  1485. "The activation occurs by updating the namespace linkage of existing functions and methods. "
  1486. "If the package is already activated the function does nothing.\n"
  1487. "@ingroup Packages\n")
  1488. {
  1489. StringTableEntry name = StringTable->insert(packageName.c_str());
  1490. Namespace::activatePackage(name);
  1491. }
  1492. DefineEngineFunction(deactivatePackage, void, (String packageName), ,
  1493. "@brief Deactivates a previously activated package.\n\n"
  1494. "The package is deactivated by removing its namespace linkages to any function or method. "
  1495. "If there are any packages above this one in the stack they are deactivated as well. "
  1496. "If the package is not on the stack this function does nothing.\n"
  1497. "@ingroup Packages\n")
  1498. {
  1499. StringTableEntry name = StringTable->insert(packageName.c_str());
  1500. Namespace::deactivatePackage(name);
  1501. }
  1502. DefineEngineFunction(getPackageList, const char*, (), ,
  1503. "@brief Returns a space delimited list of the active packages in stack order.\n\n"
  1504. "@ingroup Packages\n")
  1505. {
  1506. if (Namespace::getActivePackagesCount() == 0)
  1507. return "";
  1508. // Determine size of return buffer
  1509. dsize_t buffersize = 0;
  1510. for (U32 i = 0; i < Namespace::getActivePackagesCount(); ++i)
  1511. {
  1512. buffersize += dStrlen(Namespace::getActivePackage(i)) + 1;
  1513. }
  1514. U32 maxBufferSize = buffersize + 1;
  1515. char* returnBuffer = Con::getReturnBuffer(maxBufferSize);
  1516. U32 returnLen = 0;
  1517. for (U32 i = 0; i < Namespace::getActivePackagesCount(); ++i)
  1518. {
  1519. dSprintf(returnBuffer + returnLen, maxBufferSize - returnLen, "%s ", Namespace::getActivePackage(i));
  1520. returnLen = dStrlen(returnBuffer);
  1521. }
  1522. // Trim off the last extra space
  1523. if (returnLen > 0 && returnBuffer[returnLen - 1] == ' ')
  1524. returnBuffer[returnLen - 1] = '\0';
  1525. return returnBuffer;
  1526. }