consoleInternal.cpp 48 KB

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