2
0

consoleInternal.cpp 51 KB

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