consoleInternal.cpp 48 KB

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