consoleInternal.cpp 51 KB

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