consoleInternal.cpp 46 KB

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