consoleInternal.cpp 52 KB

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