consoleInternal.cpp 48 KB

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