consoleInternal.cpp 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969
  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. ExprEvalState::ExprEvalState()
  647. {
  648. VECTOR_SET_ASSOCIATION(stack);
  649. globalVars.setState(this);
  650. thisObject = NULL;
  651. traceOn = false;
  652. currentVariable = NULL;
  653. mStackDepth = 0;
  654. stack.reserve(64);
  655. mShouldReset = false;
  656. mResetLocked = false;
  657. copyVariable = NULL;
  658. }
  659. ExprEvalState::~ExprEvalState()
  660. {
  661. // Delete callframes.
  662. while (!stack.empty())
  663. {
  664. delete stack.last();
  665. stack.decrement();
  666. }
  667. }
  668. void ExprEvalState::validate()
  669. {
  670. AssertFatal(mStackDepth <= stack.size(),
  671. "ExprEvalState::validate() - Stack depth pointing beyond last stack frame!");
  672. for (U32 i = 0; i < stack.size(); ++i)
  673. stack[i]->validate();
  674. }
  675. DefineEngineFunction(backtrace, void, (), ,
  676. "@brief Prints the scripting call stack to the console log.\n\n"
  677. "Used to trace functions called from within functions. Can help discover what functions were called "
  678. "(and not yet exited) before the current point in scripts.\n\n"
  679. "@ingroup Debugging")
  680. {
  681. U32 totalSize = 1;
  682. for (U32 i = 0; i < gEvalState.getStackDepth(); i++)
  683. {
  684. if (gEvalState.stack[i]->scopeNamespace && gEvalState.stack[i]->scopeNamespace->mEntryList->mPackage)
  685. totalSize += dStrlen(gEvalState.stack[i]->scopeNamespace->mEntryList->mPackage) + 2;
  686. if (gEvalState.stack[i]->scopeName)
  687. totalSize += dStrlen(gEvalState.stack[i]->scopeName) + 3;
  688. if (gEvalState.stack[i]->scopeNamespace && gEvalState.stack[i]->scopeNamespace->mName)
  689. totalSize += dStrlen(gEvalState.stack[i]->scopeNamespace->mName) + 2;
  690. }
  691. char *buf = Con::getReturnBuffer(totalSize);
  692. buf[0] = 0;
  693. for (U32 i = 0; i < gEvalState.getStackDepth(); i++)
  694. {
  695. dStrcat(buf, "->", totalSize);
  696. if (gEvalState.stack[i]->scopeNamespace && gEvalState.stack[i]->scopeNamespace->mEntryList->mPackage)
  697. {
  698. dStrcat(buf, "[", totalSize);
  699. dStrcat(buf, gEvalState.stack[i]->scopeNamespace->mEntryList->mPackage, totalSize);
  700. dStrcat(buf, "]", totalSize);
  701. }
  702. if (gEvalState.stack[i]->scopeNamespace && gEvalState.stack[i]->scopeNamespace->mName)
  703. {
  704. dStrcat(buf, gEvalState.stack[i]->scopeNamespace->mName, totalSize);
  705. dStrcat(buf, "::", totalSize);
  706. }
  707. if (gEvalState.stack[i]->scopeName)
  708. dStrcat(buf, gEvalState.stack[i]->scopeName, totalSize);
  709. }
  710. Con::printf("BackTrace: %s", buf);
  711. }
  712. Namespace::Entry::Entry()
  713. {
  714. mCode = NULL;
  715. mType = InvalidFunctionType;
  716. mUsage = NULL;
  717. mHeader = NULL;
  718. mNamespace = NULL;
  719. cb.mStringCallbackFunc = NULL;
  720. mFunctionLineNumber = 0;
  721. mFunctionName = StringTable->EmptyString();
  722. mFunctionOffset = 0;
  723. mMinArgs = 0;
  724. mMaxArgs = 0;
  725. mNext = NULL;
  726. mPackage = StringTable->EmptyString();
  727. mToolOnly = false;
  728. }
  729. void Namespace::Entry::clear()
  730. {
  731. if (mCode)
  732. {
  733. mCode->decRefCount();
  734. mCode = NULL;
  735. }
  736. // Clean up usage strings generated for script functions.
  737. if ((mType == Namespace::Entry::ConsoleFunctionType) && mUsage)
  738. {
  739. dFree(mUsage);
  740. mUsage = NULL;
  741. }
  742. }
  743. Namespace::Namespace()
  744. {
  745. mPackage = NULL;
  746. mUsage = NULL;
  747. mCleanUpUsage = false;
  748. mName = NULL;
  749. mParent = NULL;
  750. mNext = NULL;
  751. mEntryList = NULL;
  752. mHashSize = 0;
  753. mHashTable = 0;
  754. mHashSequence = 0;
  755. mRefCountToParent = 0;
  756. mClassRep = 0;
  757. lastUsage = NULL;
  758. }
  759. Namespace::~Namespace()
  760. {
  761. clearEntries();
  762. if (mUsage && mCleanUpUsage)
  763. {
  764. dFree(mUsage);
  765. mUsage = NULL;
  766. mCleanUpUsage = false;
  767. }
  768. }
  769. void Namespace::clearEntries()
  770. {
  771. for (Entry *walk = mEntryList; walk; walk = walk->mNext)
  772. walk->clear();
  773. }
  774. Namespace *Namespace::find(StringTableEntry name, StringTableEntry package)
  775. {
  776. if (name == NULL && package == NULL)
  777. return mGlobalNamespace;
  778. auto pair = std::make_pair(name, package);
  779. auto pos = gNamespaceCache.find(pair);
  780. if (pos != gNamespaceCache.end())
  781. return pos->second;
  782. Namespace *ret = (Namespace *)mAllocator.alloc(sizeof(Namespace));
  783. constructInPlace(ret);
  784. ret->mPackage = package;
  785. ret->mName = name;
  786. ret->mNext = mNamespaceList;
  787. mNamespaceList = ret;
  788. // insert into namespace cache.
  789. gNamespaceCache[pair] = ret;
  790. return ret;
  791. }
  792. bool Namespace::unlinkClass(Namespace *parent)
  793. {
  794. AssertFatal(mPackage == NULL, "Namespace::unlinkClass - Must not be called on a namespace coming from a package!");
  795. // Skip additions to this namespace coming from packages.
  796. Namespace* walk = getPackageRoot();
  797. // Make sure "parent" is the direct parent namespace.
  798. if (parent != NULL && walk->mParent && walk->mParent != parent)
  799. {
  800. Con::errorf(ConsoleLogEntry::General, "Namespace::unlinkClass - cannot unlink namespace parent linkage for %s for %s.",
  801. walk->mName, walk->mParent->mName);
  802. return false;
  803. }
  804. // Decrease the reference count. Note that we do this on
  805. // the bottom-most namespace, i.e. the one guaranteed not
  806. // to come from a package.
  807. mRefCountToParent--;
  808. AssertFatal(mRefCountToParent >= 0, "Namespace::unlinkClass - reference count to parent is less than 0");
  809. // Unlink if the count dropped to zero.
  810. if (mRefCountToParent == 0)
  811. {
  812. walk->mParent = NULL;
  813. trashCache();
  814. }
  815. return true;
  816. }
  817. bool Namespace::classLinkTo(Namespace *parent)
  818. {
  819. Namespace* walk = getPackageRoot();
  820. if (walk->mParent && walk->mParent != parent)
  821. {
  822. Con::errorf(ConsoleLogEntry::General, "Error: cannot change namespace parent linkage of %s from %s to %s.",
  823. walk->mName, walk->mParent->mName, parent->mName);
  824. return false;
  825. }
  826. trashCache();
  827. walk->mParent = parent;
  828. mRefCountToParent++;
  829. return true;
  830. }
  831. void Namespace::buildHashTable()
  832. {
  833. if (mHashSequence == mCacheSequence)
  834. return;
  835. if (!mEntryList && mParent)
  836. {
  837. mParent->buildHashTable();
  838. mHashTable = mParent->mHashTable;
  839. mHashSize = mParent->mHashSize;
  840. mHashSequence = mCacheSequence;
  841. return;
  842. }
  843. U32 entryCount = 0;
  844. Namespace * ns;
  845. for (ns = this; ns; ns = ns->mParent)
  846. for (Entry *walk = ns->mEntryList; walk; walk = walk->mNext)
  847. if (lookupRecursive(walk->mFunctionName) == walk)
  848. entryCount++;
  849. mHashSize = entryCount + (entryCount >> 1) + 1;
  850. if (!(mHashSize & 1))
  851. mHashSize++;
  852. mHashTable = (Entry **)mCacheAllocator.alloc(sizeof(Entry *) * mHashSize);
  853. for (U32 i = 0; i < mHashSize; i++)
  854. mHashTable[i] = NULL;
  855. for (ns = this; ns; ns = ns->mParent)
  856. {
  857. for (Entry *walk = ns->mEntryList; walk; walk = walk->mNext)
  858. {
  859. U32 index = HashPointer(walk->mFunctionName) % mHashSize;
  860. while (mHashTable[index] && mHashTable[index]->mFunctionName != walk->mFunctionName)
  861. {
  862. index++;
  863. if (index >= mHashSize)
  864. index = 0;
  865. }
  866. if (!mHashTable[index])
  867. mHashTable[index] = walk;
  868. }
  869. }
  870. mHashSequence = mCacheSequence;
  871. }
  872. void Namespace::getUniqueEntryLists(Namespace *other, VectorPtr<Entry *> *outThisList, VectorPtr<Entry *> *outOtherList)
  873. {
  874. // All namespace entries in the common ACR should be
  875. // ignored when checking for duplicate entry names.
  876. static VectorPtr<Namespace::Entry *> commonEntries;
  877. commonEntries.clear();
  878. AbstractClassRep *commonACR = mClassRep->getCommonParent(other->mClassRep);
  879. commonACR->getNameSpace()->getEntryList(&commonEntries);
  880. // Make life easier
  881. VectorPtr<Namespace::Entry *> &thisEntries = *outThisList;
  882. VectorPtr<Namespace::Entry *> &compEntries = *outOtherList;
  883. // Clear, just in case they aren't
  884. thisEntries.clear();
  885. compEntries.clear();
  886. getEntryList(&thisEntries);
  887. other->getEntryList(&compEntries);
  888. // Run through all of the entries in the common ACR, and remove them from
  889. // the other two entry lists
  890. for (NamespaceEntryListIterator itr = commonEntries.begin(); itr != commonEntries.end(); itr++)
  891. {
  892. // Check this entry list
  893. for (NamespaceEntryListIterator thisItr = thisEntries.begin(); thisItr != thisEntries.end(); thisItr++)
  894. {
  895. if (*thisItr == *itr)
  896. {
  897. thisEntries.erase(thisItr);
  898. break;
  899. }
  900. }
  901. // Same check for component entry list
  902. for (NamespaceEntryListIterator compItr = compEntries.begin(); compItr != compEntries.end(); compItr++)
  903. {
  904. if (*compItr == *itr)
  905. {
  906. compEntries.erase(compItr);
  907. break;
  908. }
  909. }
  910. }
  911. }
  912. void Namespace::init()
  913. {
  914. // create the global namespace
  915. mGlobalNamespace = (Namespace *)mAllocator.alloc(sizeof(Namespace));
  916. constructInPlace(mGlobalNamespace);
  917. mGlobalNamespace->mPackage = NULL;
  918. mGlobalNamespace->mName = NULL;
  919. mGlobalNamespace->mNext = NULL;
  920. mNamespaceList = mGlobalNamespace;
  921. // Insert into namespace cache.
  922. gNamespaceCache[std::make_pair(mGlobalNamespace->mName, mGlobalNamespace->mPackage)] = mGlobalNamespace;
  923. }
  924. Namespace *Namespace::global()
  925. {
  926. return mGlobalNamespace;
  927. }
  928. void Namespace::shutdown()
  929. {
  930. // The data chunker will release all memory in one go
  931. // without calling destructors, so we do this manually here.
  932. for (Namespace *walk = mNamespaceList; walk; walk = walk->mNext)
  933. walk->~Namespace();
  934. }
  935. void Namespace::trashCache()
  936. {
  937. mCacheSequence++;
  938. mCacheAllocator.freeBlocks();
  939. }
  940. const char *Namespace::tabComplete(const char *prevText, S32 baseLen, bool fForward)
  941. {
  942. if (mHashSequence != mCacheSequence)
  943. buildHashTable();
  944. const char *bestMatch = NULL;
  945. for (U32 i = 0; i < mHashSize; i++)
  946. if (mHashTable[i] && canTabComplete(prevText, bestMatch, mHashTable[i]->mFunctionName, baseLen, fForward))
  947. bestMatch = mHashTable[i]->mFunctionName;
  948. return bestMatch;
  949. }
  950. Namespace::Entry *Namespace::lookupRecursive(StringTableEntry name)
  951. {
  952. for (Namespace *ns = this; ns; ns = ns->mParent)
  953. for (Entry *walk = ns->mEntryList; walk; walk = walk->mNext)
  954. if (walk->mFunctionName == name)
  955. return walk;
  956. return NULL;
  957. }
  958. Namespace::Entry *Namespace::lookup(StringTableEntry name)
  959. {
  960. if (mHashSequence != mCacheSequence)
  961. buildHashTable();
  962. U32 index = HashPointer(name) % mHashSize;
  963. while (mHashTable[index] && mHashTable[index]->mFunctionName != name)
  964. {
  965. index++;
  966. if (index >= mHashSize)
  967. index = 0;
  968. }
  969. return mHashTable[index];
  970. }
  971. static S32 QSORT_CALLBACK compareEntries(const void* a, const void* b)
  972. {
  973. const Namespace::Entry* fa = *((Namespace::Entry**)a);
  974. const Namespace::Entry* fb = *((Namespace::Entry**)b);
  975. return dStricmp(fa->mFunctionName, fb->mFunctionName);
  976. }
  977. void Namespace::getEntryList(VectorPtr<Entry *> *vec)
  978. {
  979. if (mHashSequence != mCacheSequence)
  980. buildHashTable();
  981. for (U32 i = 0; i < mHashSize; i++)
  982. if (mHashTable[i])
  983. vec->push_back(mHashTable[i]);
  984. dQsort(vec->address(), vec->size(), sizeof(Namespace::Entry *), compareEntries);
  985. }
  986. Namespace::Entry *Namespace::createLocalEntry(StringTableEntry name)
  987. {
  988. for (Entry *walk = mEntryList; walk; walk = walk->mNext)
  989. {
  990. if (walk->mFunctionName == name)
  991. {
  992. walk->clear();
  993. return walk;
  994. }
  995. }
  996. Entry *ent = (Entry *)mAllocator.alloc(sizeof(Entry));
  997. constructInPlace(ent);
  998. ent->mNamespace = this;
  999. ent->mFunctionName = name;
  1000. ent->mNext = mEntryList;
  1001. ent->mPackage = mPackage;
  1002. ent->mToolOnly = false;
  1003. mEntryList = ent;
  1004. return ent;
  1005. }
  1006. void Namespace::addFunction(StringTableEntry name, CodeBlock *cb, U32 functionOffset, const char* usage, U32 lineNumber)
  1007. {
  1008. Entry *ent = createLocalEntry(name);
  1009. trashCache();
  1010. ent->mUsage = usage;
  1011. ent->mCode = cb;
  1012. ent->mFunctionOffset = functionOffset;
  1013. ent->mCode->incRefCount();
  1014. ent->mType = Entry::ConsoleFunctionType;
  1015. ent->mFunctionLineNumber = lineNumber;
  1016. }
  1017. void Namespace::addCommand(StringTableEntry name, StringCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header)
  1018. {
  1019. Entry *ent = createLocalEntry(name);
  1020. trashCache();
  1021. ent->mUsage = usage;
  1022. ent->mHeader = header;
  1023. ent->mMinArgs = minArgs;
  1024. ent->mMaxArgs = maxArgs;
  1025. ent->mToolOnly = isToolOnly;
  1026. ent->mType = Entry::StringCallbackType;
  1027. ent->cb.mStringCallbackFunc = cb;
  1028. }
  1029. void Namespace::addCommand(StringTableEntry name, IntCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header)
  1030. {
  1031. Entry *ent = createLocalEntry(name);
  1032. trashCache();
  1033. ent->mUsage = usage;
  1034. ent->mHeader = header;
  1035. ent->mMinArgs = minArgs;
  1036. ent->mMaxArgs = maxArgs;
  1037. ent->mToolOnly = isToolOnly;
  1038. ent->mType = Entry::IntCallbackType;
  1039. ent->cb.mIntCallbackFunc = cb;
  1040. }
  1041. void Namespace::addCommand(StringTableEntry name, VoidCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header)
  1042. {
  1043. Entry *ent = createLocalEntry(name);
  1044. trashCache();
  1045. ent->mUsage = usage;
  1046. ent->mHeader = header;
  1047. ent->mMinArgs = minArgs;
  1048. ent->mMaxArgs = maxArgs;
  1049. ent->mToolOnly = isToolOnly;
  1050. ent->mType = Entry::VoidCallbackType;
  1051. ent->cb.mVoidCallbackFunc = cb;
  1052. }
  1053. void Namespace::addCommand(StringTableEntry name, FloatCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header)
  1054. {
  1055. Entry *ent = createLocalEntry(name);
  1056. trashCache();
  1057. ent->mUsage = usage;
  1058. ent->mHeader = header;
  1059. ent->mMinArgs = minArgs;
  1060. ent->mMaxArgs = maxArgs;
  1061. ent->mToolOnly = isToolOnly;
  1062. ent->mType = Entry::FloatCallbackType;
  1063. ent->cb.mFloatCallbackFunc = cb;
  1064. }
  1065. void Namespace::addCommand(StringTableEntry name, BoolCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header)
  1066. {
  1067. Entry *ent = createLocalEntry(name);
  1068. trashCache();
  1069. ent->mUsage = usage;
  1070. ent->mHeader = header;
  1071. ent->mMinArgs = minArgs;
  1072. ent->mMaxArgs = maxArgs;
  1073. ent->mToolOnly = isToolOnly;
  1074. ent->mType = Entry::BoolCallbackType;
  1075. ent->cb.mBoolCallbackFunc = cb;
  1076. }
  1077. void Namespace::addScriptCallback(const char *funcName, const char *usage, ConsoleFunctionHeader* header)
  1078. {
  1079. static U32 uid = 0;
  1080. char buffer[1024];
  1081. char lilBuffer[32];
  1082. dStrcpy(buffer, funcName, 1024);
  1083. dSprintf(lilBuffer, 32, "_%d_cb", uid++);
  1084. dStrcat(buffer, lilBuffer, 1024);
  1085. Entry *ent = createLocalEntry(StringTable->insert(buffer));
  1086. trashCache();
  1087. ent->mUsage = usage;
  1088. ent->mHeader = header;
  1089. ent->mMinArgs = -2;
  1090. ent->mMaxArgs = -3;
  1091. ent->mType = Entry::ScriptCallbackType;
  1092. ent->cb.mCallbackName = funcName;
  1093. }
  1094. void Namespace::markGroup(const char* name, const char* usage)
  1095. {
  1096. static U32 uid = 0;
  1097. char buffer[1024];
  1098. char lilBuffer[32];
  1099. dStrcpy(buffer, name, 1024);
  1100. dSprintf(lilBuffer, 32, "_%d", uid++);
  1101. dStrcat(buffer, lilBuffer, 1024);
  1102. Entry *ent = createLocalEntry(StringTable->insert(buffer));
  1103. trashCache();
  1104. if (usage != NULL)
  1105. lastUsage = (char*)(ent->mUsage = usage);
  1106. else
  1107. ent->mUsage = lastUsage;
  1108. ent->mMinArgs = -1; // Make sure it explodes if somehow we run this entry.
  1109. ent->mMaxArgs = -2;
  1110. ent->mType = Entry::GroupMarker;
  1111. ent->cb.mGroupName = name;
  1112. }
  1113. extern S32 executeBlock(StmtNode *block, ExprEvalState *state);
  1114. ConsoleValue Namespace::Entry::execute(S32 argc, ConsoleValue *argv, ExprEvalState *state)
  1115. {
  1116. STR.clearFunctionOffset();
  1117. if (mType == ConsoleFunctionType)
  1118. {
  1119. if (mFunctionOffset)
  1120. {
  1121. return std::move(mCode->exec(mFunctionOffset, argv[0].getString(), mNamespace, argc, argv, false, mPackage));
  1122. }
  1123. else
  1124. {
  1125. return std::move(ConsoleValue());
  1126. }
  1127. }
  1128. #ifndef TORQUE_DEBUG
  1129. // [tom, 12/13/2006] This stops tools functions from working in the console,
  1130. // which is useful behavior when debugging so I'm ifdefing this out for debug builds.
  1131. if (mToolOnly && !Con::isCurrentScriptToolScript())
  1132. {
  1133. Con::errorf(ConsoleLogEntry::Script, "%s::%s - attempting to call tools only function from outside of tools", mNamespace->mName, mFunctionName);
  1134. return std::move(ConsoleValue());
  1135. }
  1136. #endif
  1137. if ((mMinArgs && argc < mMinArgs) || (mMaxArgs && argc > mMaxArgs))
  1138. {
  1139. Con::warnf(ConsoleLogEntry::Script, "%s::%s - wrong number of arguments.", mNamespace->mName, mFunctionName);
  1140. Con::warnf(ConsoleLogEntry::Script, "usage: %s", mUsage);
  1141. return std::move(ConsoleValue());
  1142. }
  1143. ConsoleValue result;
  1144. switch (mType)
  1145. {
  1146. case StringCallbackType:
  1147. {
  1148. const char* str = cb.mStringCallbackFunc(state->thisObject, argc, argv);
  1149. result.setString(str);
  1150. break;
  1151. }
  1152. case IntCallbackType:
  1153. result.setInt(cb.mIntCallbackFunc(state->thisObject, argc, argv));
  1154. break;
  1155. case FloatCallbackType:
  1156. result.setFloat(cb.mFloatCallbackFunc(state->thisObject, argc, argv));
  1157. break;
  1158. case VoidCallbackType:
  1159. cb.mVoidCallbackFunc(state->thisObject, argc, argv);
  1160. break;
  1161. case BoolCallbackType:
  1162. result.setBool(cb.mBoolCallbackFunc(state->thisObject, argc, argv));
  1163. break;
  1164. }
  1165. return std::move(result);
  1166. }
  1167. //-----------------------------------------------------------------------------
  1168. // Doc string code.
  1169. namespace {
  1170. /// Scan the given usage string for an argument list description. With the
  1171. /// old console macros, these were usually included as the first part of the
  1172. /// usage string.
  1173. bool sFindArgumentListSubstring(const char* usage, const char*& start, const char*& end)
  1174. {
  1175. if (!usage)
  1176. return false;
  1177. const char* ptr = usage;
  1178. while (*ptr && *ptr != '(' && *ptr != '\n') // Only scan first line of usage string.
  1179. {
  1180. // Stop on the first alphanumeric character as we expect
  1181. // argument lists to precede descriptions.
  1182. if (dIsalnum(*ptr))
  1183. return false;
  1184. ptr++;
  1185. }
  1186. if (*ptr != '(')
  1187. return false;
  1188. start = ptr;
  1189. ptr++;
  1190. bool inString = false;
  1191. U32 nestingCount = 0;
  1192. while (*ptr && (*ptr != ')' || nestingCount > 0 || inString))
  1193. {
  1194. if (*ptr == '(')
  1195. nestingCount++;
  1196. else if (*ptr == ')')
  1197. nestingCount--;
  1198. else if (*ptr == '"')
  1199. inString = !inString;
  1200. else if (*ptr == '\\' && ptr[1] == '"')
  1201. ptr++;
  1202. ptr++;
  1203. }
  1204. if (*ptr)
  1205. ptr++;
  1206. end = ptr;
  1207. return true;
  1208. }
  1209. ///
  1210. void sParseList(const char* str, Vector< String >& outList)
  1211. {
  1212. // Skip the initial '( '.
  1213. const char* ptr = str;
  1214. while (*ptr && dIsspace(*ptr))
  1215. ptr++;
  1216. if (*ptr == '(')
  1217. {
  1218. ptr++;
  1219. while (*ptr && dIsspace(*ptr))
  1220. ptr++;
  1221. }
  1222. // Parse out list items.
  1223. while (*ptr && *ptr != ')')
  1224. {
  1225. // Find end of element.
  1226. const char* start = ptr;
  1227. bool inString = false;
  1228. U32 nestingCount = 0;
  1229. while (*ptr && ((*ptr != ')' && *ptr != ',') || nestingCount > 0 || inString))
  1230. {
  1231. if (*ptr == '(')
  1232. nestingCount++;
  1233. else if (*ptr == ')')
  1234. nestingCount--;
  1235. else if (*ptr == '"')
  1236. inString = !inString;
  1237. else if (*ptr == '\\' && ptr[1] == '"')
  1238. ptr++;
  1239. ptr++;
  1240. }
  1241. // Backtrack to remove trailing whitespace.
  1242. const char* end = ptr;
  1243. if (*end == ',' || *end == ')')
  1244. end--;
  1245. while (end > start && dIsspace(*end))
  1246. end--;
  1247. if (*end)
  1248. end++;
  1249. // Add to list.
  1250. if (start != end)
  1251. outList.push_back(String(start, end - start));
  1252. // Skip comma and whitespace.
  1253. if (*ptr == ',')
  1254. ptr++;
  1255. while (*ptr && dIsspace(*ptr))
  1256. ptr++;
  1257. }
  1258. }
  1259. ///
  1260. void sGetArgNameAndType(const String& str, String& outType, String& outName)
  1261. {
  1262. if (!str.length())
  1263. {
  1264. outType = String::EmptyString;
  1265. outName = String::EmptyString;
  1266. return;
  1267. }
  1268. // Find first non-ID character from right.
  1269. S32 index = str.length() - 1;
  1270. while (index >= 0 && (dIsalnum(str[index]) || str[index] == '_'))
  1271. index--;
  1272. const U32 nameStartIndex = index + 1;
  1273. // Find end of type name by skipping rightmost whitespace inwards.
  1274. while (index >= 0 && dIsspace(str[index]))
  1275. index--;
  1276. //
  1277. outName = String(&((const char*)str)[nameStartIndex]);
  1278. outType = String(str, index + 1);
  1279. }
  1280. /// Return the type name to show in documentation for the given C++ type.
  1281. const char* sGetDocTypeString(const char* nativeType)
  1282. {
  1283. if (dStrncmp(nativeType, "const ", 6) == 0)
  1284. nativeType += 6;
  1285. if (String::compare(nativeType, "char*") == 0 || String::compare(nativeType, "char *") == 0)
  1286. return "string";
  1287. else if (String::compare(nativeType, "S32") == 0)
  1288. return "int";
  1289. else if (String::compare(nativeType, "U32") == 0)
  1290. return "uint";
  1291. else if (String::compare(nativeType, "F32") == 0)
  1292. return "float";
  1293. const U32 length = dStrlen(nativeType);
  1294. if (nativeType[length - 1] == '&' || nativeType[length - 1] == '*')
  1295. return StringTable->insertn(nativeType, length - 1);
  1296. return nativeType;
  1297. }
  1298. }
  1299. String Namespace::Entry::getBriefDescription(String* outRemainingDocText) const
  1300. {
  1301. String docString = getDocString();
  1302. S32 newline = docString.find('\n');
  1303. if (newline == -1)
  1304. {
  1305. if (outRemainingDocText)
  1306. *outRemainingDocText = String();
  1307. return docString;
  1308. }
  1309. String brief = docString.substr(0, newline);
  1310. if (outRemainingDocText)
  1311. *outRemainingDocText = docString.substr(newline + 1);
  1312. return brief;
  1313. }
  1314. String Namespace::Entry::getDocString() const
  1315. {
  1316. const char* argListStart;
  1317. const char* argListEnd;
  1318. if (sFindArgumentListSubstring(mUsage, argListStart, argListEnd))
  1319. {
  1320. // Skip the " - " part present in some old doc strings.
  1321. const char* ptr = argListEnd;
  1322. while (*ptr && dIsspace(*ptr))
  1323. ptr++;
  1324. if (*ptr == '-')
  1325. {
  1326. ptr++;
  1327. while (*ptr && dIsspace(*ptr))
  1328. ptr++;
  1329. }
  1330. return ptr;
  1331. }
  1332. return mUsage;
  1333. }
  1334. String Namespace::Entry::getArgumentsString() const
  1335. {
  1336. StringBuilder str;
  1337. if (mHeader)
  1338. {
  1339. // Parse out the argument list string supplied with the extended
  1340. // function header and add default arguments as we go.
  1341. Vector< String > argList;
  1342. Vector< String > defaultArgList;
  1343. sParseList(mHeader->mArgString, argList);
  1344. sParseList(mHeader->mDefaultArgString, defaultArgList);
  1345. str.append('(');
  1346. const U32 numArgs = argList.size();
  1347. const U32 numDefaultArgs = defaultArgList.size();
  1348. const U32 firstDefaultArgIndex = numArgs - numDefaultArgs;
  1349. for (U32 i = 0; i < numArgs; ++i)
  1350. {
  1351. // Add separator if not first arg.
  1352. if (i > 0)
  1353. str.append(',');
  1354. // Add type and name.
  1355. String name;
  1356. String type;
  1357. sGetArgNameAndType(argList[i], type, name);
  1358. str.append(' ');
  1359. str.append(sGetDocTypeString(type));
  1360. str.append(' ');
  1361. str.append(name);
  1362. // Add default value, if any.
  1363. if (i >= firstDefaultArgIndex)
  1364. {
  1365. str.append('=');
  1366. str.append(defaultArgList[i - firstDefaultArgIndex]);
  1367. }
  1368. }
  1369. if (numArgs > 0)
  1370. str.append(' ');
  1371. str.append(')');
  1372. }
  1373. else
  1374. {
  1375. // No extended function header. Try to parse out the argument
  1376. // list from the usage string.
  1377. const char* argListStart;
  1378. const char* argListEnd;
  1379. if (sFindArgumentListSubstring(mUsage, argListStart, argListEnd))
  1380. str.append(argListStart, argListEnd - argListStart);
  1381. else if (mType == ConsoleFunctionType && mCode)
  1382. {
  1383. // This isn't correct but the nonsense console stuff is set up such that all
  1384. // functions that have no function bodies are keyed to offset 0 to indicate "no code."
  1385. // This loses the association with the original function definition so we can't really
  1386. // tell here what the actual prototype is except if we searched though the entire opcode
  1387. // stream for the corresponding OP_FUNC_DECL (which would require dealing with the
  1388. // variable-size instructions).
  1389. if (!mFunctionOffset)
  1390. return "()";
  1391. String args = mCode->getFunctionArgs(mFunctionOffset);
  1392. if (args.isEmpty())
  1393. return "()";
  1394. str.append("( ");
  1395. str.append(args);
  1396. str.append(" )");
  1397. }
  1398. }
  1399. return str.end();
  1400. }
  1401. String Namespace::Entry::getPrototypeString() const
  1402. {
  1403. StringBuilder str;
  1404. // Start with return type.
  1405. if (mHeader && mHeader->mReturnString)
  1406. {
  1407. str.append(sGetDocTypeString(mHeader->mReturnString));
  1408. str.append(' ');
  1409. }
  1410. else
  1411. switch (mType)
  1412. {
  1413. case StringCallbackType:
  1414. str.append("string ");
  1415. break;
  1416. case IntCallbackType:
  1417. str.append("int ");
  1418. break;
  1419. case FloatCallbackType:
  1420. str.append("float ");
  1421. break;
  1422. case VoidCallbackType:
  1423. str.append("void ");
  1424. break;
  1425. case BoolCallbackType:
  1426. str.append("bool ");
  1427. break;
  1428. case ScriptCallbackType:
  1429. break;
  1430. }
  1431. // Add function name and arguments.
  1432. if (mType == ScriptCallbackType)
  1433. str.append(cb.mCallbackName);
  1434. else
  1435. str.append(mFunctionName);
  1436. str.append(getArgumentsString());
  1437. return str.end();
  1438. }
  1439. //-----------------------------------------------------------------------------
  1440. StringTableEntry Namespace::mActivePackages[Namespace::MaxActivePackages];
  1441. U32 Namespace::mNumActivePackages = 0;
  1442. U32 Namespace::mOldNumActivePackages = 0;
  1443. bool Namespace::isPackage(StringTableEntry name)
  1444. {
  1445. for (Namespace *walk = mNamespaceList; walk; walk = walk->mNext)
  1446. if (walk->mPackage == name)
  1447. return true;
  1448. return false;
  1449. }
  1450. U32 Namespace::getActivePackagesCount()
  1451. {
  1452. return mNumActivePackages;
  1453. }
  1454. StringTableEntry Namespace::getActivePackage(U32 index)
  1455. {
  1456. if (index >= mNumActivePackages)
  1457. return StringTable->EmptyString();
  1458. return mActivePackages[index];
  1459. }
  1460. void Namespace::activatePackage(StringTableEntry name)
  1461. {
  1462. if (mNumActivePackages == MaxActivePackages)
  1463. {
  1464. Con::printf("ActivatePackage(%s) failed - Max package limit reached: %d", name, MaxActivePackages);
  1465. return;
  1466. }
  1467. if (!name)
  1468. return;
  1469. // see if this one's already active
  1470. for (U32 i = 0; i < mNumActivePackages; i++)
  1471. if (mActivePackages[i] == name)
  1472. return;
  1473. // kill the cache
  1474. trashCache();
  1475. // find all the package namespaces...
  1476. for (Namespace *walk = mNamespaceList; walk; walk = walk->mNext)
  1477. {
  1478. if (walk->mPackage == name)
  1479. {
  1480. Namespace *parent = Namespace::find(walk->mName);
  1481. // hook the parent
  1482. walk->mParent = parent->mParent;
  1483. parent->mParent = walk;
  1484. // now swap the entries:
  1485. Entry *ew;
  1486. for (ew = parent->mEntryList; ew; ew = ew->mNext)
  1487. ew->mNamespace = walk;
  1488. for (ew = walk->mEntryList; ew; ew = ew->mNext)
  1489. ew->mNamespace = parent;
  1490. ew = walk->mEntryList;
  1491. walk->mEntryList = parent->mEntryList;
  1492. parent->mEntryList = ew;
  1493. }
  1494. }
  1495. mActivePackages[mNumActivePackages++] = name;
  1496. }
  1497. void Namespace::deactivatePackage(StringTableEntry name)
  1498. {
  1499. U32 oldNumActivePackages = mNumActivePackages;
  1500. // Remove all packages down to the given one
  1501. deactivatePackageStack(name);
  1502. // Now add back all packages that followed the given one
  1503. if (!oldNumActivePackages)
  1504. return;
  1505. for (U32 i = mNumActivePackages + 1; i < oldNumActivePackages; i++)
  1506. activatePackage(mActivePackages[i]);
  1507. }
  1508. void Namespace::deactivatePackageStack(StringTableEntry name)
  1509. {
  1510. S32 i, j;
  1511. for (i = 0; i < mNumActivePackages; i++)
  1512. if (mActivePackages[i] == name)
  1513. break;
  1514. if (i == mNumActivePackages)
  1515. return;
  1516. trashCache();
  1517. // Remove all packages down to the given one
  1518. for (j = mNumActivePackages - 1; j >= i; j--)
  1519. {
  1520. // gotta unlink em in reverse order...
  1521. for (Namespace *walk = mNamespaceList; walk; walk = walk->mNext)
  1522. {
  1523. if (walk->mPackage == mActivePackages[j])
  1524. {
  1525. Namespace *parent = Namespace::find(walk->mName);
  1526. // hook the parent
  1527. parent->mParent = walk->mParent;
  1528. walk->mParent = NULL;
  1529. // now swap the entries:
  1530. Entry *ew;
  1531. for (ew = parent->mEntryList; ew; ew = ew->mNext)
  1532. ew->mNamespace = walk;
  1533. for (ew = walk->mEntryList; ew; ew = ew->mNext)
  1534. ew->mNamespace = parent;
  1535. ew = walk->mEntryList;
  1536. walk->mEntryList = parent->mEntryList;
  1537. parent->mEntryList = ew;
  1538. }
  1539. }
  1540. }
  1541. mNumActivePackages = i;
  1542. }
  1543. void Namespace::unlinkPackages()
  1544. {
  1545. mOldNumActivePackages = mNumActivePackages;
  1546. if (!mNumActivePackages)
  1547. return;
  1548. deactivatePackageStack(mActivePackages[0]);
  1549. }
  1550. void Namespace::relinkPackages()
  1551. {
  1552. if (!mOldNumActivePackages)
  1553. return;
  1554. for (U32 i = 0; i < mOldNumActivePackages; i++)
  1555. activatePackage(mActivePackages[i]);
  1556. }
  1557. DefineEngineFunction(isPackage, bool, (String identifier), ,
  1558. "@brief Returns true if the identifier is the name of a declared package.\n\n"
  1559. "@ingroup Packages\n")
  1560. {
  1561. StringTableEntry name = StringTable->insert(identifier.c_str());
  1562. return Namespace::isPackage(name);
  1563. }
  1564. DefineEngineFunction(activatePackage, void, (String packageName), ,
  1565. "@brief Activates an existing package.\n\n"
  1566. "The activation occurs by updating the namespace linkage of existing functions and methods. "
  1567. "If the package is already activated the function does nothing.\n"
  1568. "@ingroup Packages\n")
  1569. {
  1570. StringTableEntry name = StringTable->insert(packageName.c_str());
  1571. Namespace::activatePackage(name);
  1572. }
  1573. DefineEngineFunction(deactivatePackage, void, (String packageName), ,
  1574. "@brief Deactivates a previously activated package.\n\n"
  1575. "The package is deactivated by removing its namespace linkages to any function or method. "
  1576. "If there are any packages above this one in the stack they are deactivated as well. "
  1577. "If the package is not on the stack this function does nothing.\n"
  1578. "@ingroup Packages\n")
  1579. {
  1580. StringTableEntry name = StringTable->insert(packageName.c_str());
  1581. Namespace::deactivatePackage(name);
  1582. }
  1583. DefineEngineFunction(getPackageList, const char*, (), ,
  1584. "@brief Returns a space delimited list of the active packages in stack order.\n\n"
  1585. "@ingroup Packages\n")
  1586. {
  1587. if (Namespace::getActivePackagesCount() == 0)
  1588. return "";
  1589. // Determine size of return buffer
  1590. dsize_t buffersize = 0;
  1591. for (U32 i = 0; i < Namespace::getActivePackagesCount(); ++i)
  1592. {
  1593. buffersize += dStrlen(Namespace::getActivePackage(i)) + 1;
  1594. }
  1595. U32 maxBufferSize = buffersize + 1;
  1596. char* returnBuffer = Con::getReturnBuffer(maxBufferSize);
  1597. U32 returnLen = 0;
  1598. for (U32 i = 0; i < Namespace::getActivePackagesCount(); ++i)
  1599. {
  1600. dSprintf(returnBuffer + returnLen, maxBufferSize - returnLen, "%s ", Namespace::getActivePackage(i));
  1601. returnLen = dStrlen(returnBuffer);
  1602. }
  1603. // Trim off the last extra space
  1604. if (returnLen > 0 && returnBuffer[returnLen - 1] == ' ')
  1605. returnBuffer[returnLen - 1] = '\0';
  1606. return returnBuffer;
  1607. }