consoleInternal.cpp 51 KB

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