consoleInternal.cpp 51 KB

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