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