consoleInternal.cpp 52 KB

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