consoleInternal.cpp 51 KB

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