consoleInternal.cpp 46 KB

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