consoleInternal.cpp 51 KB

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