consoleInternal.cpp 51 KB

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