consoleInternal.cpp 49 KB

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