123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019 |
- //-----------------------------------------------------------------------------
- // Copyright (c) 2012 GarageGames, LLC
- //
- // Permission is hereby granted, free of charge, to any person obtaining a copy
- // of this software and associated documentation files (the "Software"), to
- // deal in the Software without restriction, including without limitation the
- // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
- // sell copies of the Software, and to permit persons to whom the Software is
- // furnished to do so, subject to the following conditions:
- //
- // The above copyright notice and this permission notice shall be included in
- // all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
- // IN THE SOFTWARE.
- //-----------------------------------------------------------------------------
- #include <unordered_map>
- #include "platform/platform.h"
- #include "console/console.h"
- #include "console/ast.h"
- #include "core/tAlgorithm.h"
- #include "core/strings/findMatch.h"
- #include "console/consoleInternal.h"
- #include "core/stream/fileStream.h"
- #include "console/compiler.h"
- #include "console/engineAPI.h"
- //#define DEBUG_SPEW
- #define ST_INIT_SIZE 15
- static char scratchBuffer[1024];
- U32 Namespace::mCacheSequence = 0;
- DataChunker Namespace::mCacheAllocator;
- DataChunker Namespace::mAllocator;
- Namespace *Namespace::mNamespaceList = NULL;
- Namespace *Namespace::mGlobalNamespace = NULL;
- namespace std
- {
- template<> struct hash<std::pair<StringTableEntry, StringTableEntry>>
- {
- typedef std::pair<StringTableEntry, StringTableEntry> argument_type;
- typedef size_t result_type;
- result_type operator()(argument_type const& s) const
- {
- return HashPointer(s.first) ^ (HashPointer(s.second) << 1);
- }
- };
- };
- std::unordered_map<std::pair<StringTableEntry, StringTableEntry>, Namespace*> gNamespaceCache;
- bool canTabComplete(const char *prevText, const char *bestMatch,
- const char *newText, S32 baseLen, bool fForward)
- {
- // test if it matches the first baseLen chars:
- if (dStrnicmp(newText, prevText, baseLen))
- return false;
- if (fForward)
- {
- if (!bestMatch)
- return dStricmp(newText, prevText) > 0;
- else
- return (dStricmp(newText, prevText) > 0) &&
- (dStricmp(newText, bestMatch) < 0);
- }
- else
- {
- if (dStrlen(prevText) == (U32)baseLen)
- {
- // look for the 'worst match'
- if (!bestMatch)
- return dStricmp(newText, prevText) > 0;
- else
- return dStricmp(newText, bestMatch) > 0;
- }
- else
- {
- if (!bestMatch)
- return (dStricmp(newText, prevText) < 0);
- else
- return (dStricmp(newText, prevText) < 0) &&
- (dStricmp(newText, bestMatch) > 0);
- }
- }
- }
- //---------------------------------------------------------------
- //
- // Dictionary functions
- //
- //---------------------------------------------------------------
- struct StringValue
- {
- S32 size;
- char *val;
- operator char *() { return val; }
- StringValue &operator=(const char *string);
- StringValue() { size = 0; val = NULL; }
- ~StringValue() { dFree(val); }
- };
- StringValue & StringValue::operator=(const char *string)
- {
- if (!val)
- {
- val = dStrdup(string);
- size = dStrlen(val);
- }
- else
- {
- S32 len = dStrlen(string);
- if (len < size)
- dStrcpy(val, string, size);
- else
- {
- size = len;
- dFree(val);
- val = dStrdup(string);
- }
- }
- return *this;
- }
- static S32 QSORT_CALLBACK varCompare(const void* a, const void* b)
- {
- return dStricmp((*((Dictionary::Entry **) a))->name, (*((Dictionary::Entry **) b))->name);
- }
- void Dictionary::exportVariables(const char *varString, const char *fileName, bool append)
- {
- const char *searchStr = varString;
- Vector<Entry *> sortList(__FILE__, __LINE__);
- for (S32 i = 0; i < hashTable->size; i++)
- {
- Entry *walk = hashTable->data[i];
- while (walk)
- {
- if (FindMatch::isMatch((char *)searchStr, (char *)walk->name))
- sortList.push_back(walk);
- walk = walk->nextEntry;
- }
- }
- if (!sortList.size())
- return;
- dQsort((void *)&sortList[0], sortList.size(), sizeof(Entry *), varCompare);
- Vector<Entry *>::iterator s;
- char expandBuffer[1024];
- FileStream *strm = NULL;
- if (fileName)
- {
- if ((strm = FileStream::createAndOpen(fileName, append ? Torque::FS::File::ReadWrite : Torque::FS::File::Write)) == NULL)
- {
- Con::errorf(ConsoleLogEntry::General, "Unable to open file '%s for writing.", fileName);
- return;
- }
- if (append)
- strm->setPosition(strm->getStreamSize());
- }
- char buffer[1024];
- const char *cat = fileName ? "\r\n" : "";
- for (s = sortList.begin(); s != sortList.end(); s++)
- {
- switch ((*s)->value.type)
- {
- case ConsoleValue::TypeInternalInt:
- dSprintf(buffer, sizeof(buffer), "%s = %d;%s", (*s)->name, (*s)->value.ival, cat);
- break;
- case ConsoleValue::TypeInternalFloat:
- dSprintf(buffer, sizeof(buffer), "%s = %g;%s", (*s)->name, (*s)->value.fval, cat);
- break;
- default:
- expandEscape(expandBuffer, (*s)->getStringValue());
- dSprintf(buffer, sizeof(buffer), "%s = \"%s\";%s", (*s)->name, expandBuffer, cat);
- break;
- }
- if (strm)
- strm->write(dStrlen(buffer), buffer);
- else
- Con::printf("%s", buffer);
- }
- if (strm)
- delete strm;
- }
- void Dictionary::exportVariables(const char *varString, Vector<String> *names, Vector<String> *values)
- {
- const char *searchStr = varString;
- Vector<Entry *> sortList(__FILE__, __LINE__);
- for (S32 i = 0; i < hashTable->size; i++)
- {
- Entry *walk = hashTable->data[i];
- while (walk)
- {
- if (FindMatch::isMatch((char*)searchStr, (char*)walk->name))
- sortList.push_back(walk);
- walk = walk->nextEntry;
- }
- }
- if (!sortList.size())
- return;
- dQsort((void *)&sortList[0], sortList.size(), sizeof(Entry *), varCompare);
- if (names)
- names->reserve(sortList.size());
- if (values)
- values->reserve(sortList.size());
- char expandBuffer[1024];
- Vector<Entry *>::iterator s;
- for (s = sortList.begin(); s != sortList.end(); s++)
- {
- if (names)
- names->push_back(String((*s)->name));
- if (values)
- {
- switch ((*s)->value.type)
- {
- case ConsoleValue::TypeInternalInt:
- values->push_back(String::ToString((*s)->value.ival));
- break;
- case ConsoleValue::TypeInternalFloat:
- values->push_back(String::ToString((*s)->value.fval));
- break;
- default:
- expandEscape(expandBuffer, (*s)->getStringValue());
- values->push_back(expandBuffer);
- break;
- }
- }
- }
- }
- void Dictionary::deleteVariables(const char *varString)
- {
- const char *searchStr = varString;
- for (S32 i = 0; i < hashTable->size; i++)
- {
- Entry *walk = hashTable->data[i];
- while (walk)
- {
- Entry *matchedEntry = (FindMatch::isMatch((char *)searchStr, (char *)walk->name)) ? walk : NULL;
- walk = walk->nextEntry;
- if (matchedEntry)
- remove(matchedEntry); // assumes remove() is a stable remove (will not reorder entries on remove)
- }
- }
- }
- U32 HashPointer(StringTableEntry ptr)
- {
- return (U32)(((dsize_t)ptr) >> 2);
- }
- Dictionary::Entry *Dictionary::lookup(StringTableEntry name)
- {
- Entry *walk = hashTable->data[HashPointer(name) % hashTable->size];
- while (walk)
- {
- if (walk->name == name)
- return walk;
- else
- walk = walk->nextEntry;
- }
- return NULL;
- }
- Dictionary::Entry *Dictionary::add(StringTableEntry name)
- {
- // Try to find an existing match.
- //printf("Add Variable %s\n", name);
- Entry* ret = lookup(name);
- if (ret)
- return ret;
- // Rehash if the table get's too crowded. Be aware that this might
- // modify a table that we don't own.
- hashTable->count++;
- if (hashTable->count > hashTable->size * 2)
- {
- // Allocate a new table.
- const U32 newTableSize = hashTable->size * 4 - 1;
- Entry** newTableData = new Entry*[newTableSize];
- dMemset(newTableData, 0, newTableSize * sizeof(Entry*));
- // Move the entries over.
- for (U32 i = 0; i < hashTable->size; ++i)
- for (Entry* entry = hashTable->data[i]; entry != NULL; )
- {
- Entry* next = entry->nextEntry;
- U32 index = HashPointer(entry->name) % newTableSize;
- entry->nextEntry = newTableData[index];
- newTableData[index] = entry;
- entry = next;
- }
- // Switch the tables.
- delete[] hashTable->data;
- hashTable->data = newTableData;
- hashTable->size = newTableSize;
- }
- #ifdef DEBUG_SPEW
- Platform::outputDebugString("[ConsoleInternal] Adding entry '%s'", name);
- #endif
- // Add the new entry.
- ret = hashTable->mChunker.alloc();
- constructInPlace(ret, name);
- U32 idx = HashPointer(name) % hashTable->size;
- ret->nextEntry = hashTable->data[idx];
- hashTable->data[idx] = ret;
- return ret;
- }
- // deleteVariables() assumes remove() is a stable remove (will not reorder entries on remove)
- void Dictionary::remove(Dictionary::Entry *ent)
- {
- Entry **walk = &hashTable->data[HashPointer(ent->name) % hashTable->size];
- while (*walk != ent)
- walk = &((*walk)->nextEntry);
- #ifdef DEBUG_SPEW
- Platform::outputDebugString("[ConsoleInternal] Removing entry '%s'", ent->name);
- #endif
- *walk = (ent->nextEntry);
- destructInPlace(ent);
- hashTable->mChunker.free(ent);
- hashTable->count--;
- }
- Dictionary::Dictionary()
- : hashTable(NULL),
- #pragma warning( disable : 4355 )
- ownHashTable(this), // Warning with VC++ but this is safe.
- #pragma warning( default : 4355 )
- exprState(NULL),
- scopeName(NULL),
- scopeNamespace(NULL),
- code(NULL),
- ip(0)
- {
- }
- void Dictionary::setState(ExprEvalState *state, Dictionary* ref)
- {
- exprState = state;
- if (ref)
- {
- hashTable = ref->hashTable;
- return;
- }
- if (!ownHashTable.data)
- {
- ownHashTable.count = 0;
- ownHashTable.size = ST_INIT_SIZE;
- ownHashTable.data = new Entry *[ownHashTable.size];
- dMemset(ownHashTable.data, 0, ownHashTable.size * sizeof(Entry*));
- }
- hashTable = &ownHashTable;
- }
- Dictionary::~Dictionary()
- {
- reset();
- if (ownHashTable.data)
- delete[] ownHashTable.data;
- }
- void Dictionary::reset()
- {
- if (hashTable && hashTable->owner != this)
- {
- hashTable = NULL;
- return;
- }
- for (U32 i = 0; i < ownHashTable.size; ++i)
- {
- Entry* walk = ownHashTable.data[i];
- while (walk)
- {
- Entry* temp = walk->nextEntry;
- destructInPlace(walk);
- walk = temp;
- }
- }
- dMemset(ownHashTable.data, 0, ownHashTable.size * sizeof(Entry*));
- ownHashTable.mChunker.freeBlocks(true);
- ownHashTable.count = 0;
- hashTable = NULL;
- scopeName = NULL;
- scopeNamespace = NULL;
- code = NULL;
- ip = 0;
- }
- const char *Dictionary::tabComplete(const char *prevText, S32 baseLen, bool fForward)
- {
- S32 i;
- const char *bestMatch = NULL;
- for (i = 0; i < hashTable->size; i++)
- {
- Entry *walk = hashTable->data[i];
- while (walk)
- {
- if (canTabComplete(prevText, bestMatch, walk->name, baseLen, fForward))
- bestMatch = walk->name;
- walk = walk->nextEntry;
- }
- }
- return bestMatch;
- }
- char *typeValueEmpty = "";
- Dictionary::Entry::Entry(StringTableEntry in_name)
- {
- name = in_name;
- value.type = ConsoleValue::TypeInternalString;
- notify = NULL;
- nextEntry = NULL;
- mUsage = NULL;
- mIsConstant = false;
- mNext = NULL;
- // NOTE: This is data inside a nameless
- // union, so we don't need to init the rest.
- value.init();
- }
- Dictionary::Entry::~Entry()
- {
- value.cleanup();
- if (notify)
- delete notify;
- }
- const char *Dictionary::getVariable(StringTableEntry name, bool *entValid)
- {
- Entry *ent = lookup(name);
- if (ent)
- {
- if (entValid)
- *entValid = true;
- return ent->getStringValue();
- }
- if (entValid)
- *entValid = false;
- // Warn users when they access a variable that isn't defined.
- if (gWarnUndefinedScriptVariables)
- Con::warnf(" *** Accessed undefined variable '%s'", name);
- return "";
- }
- void ConsoleValue::setStringValue(const char * value)
- {
- if (value == NULL) value = typeValueEmpty;
- if (type <= ConsoleValue::TypeInternalString)
- {
- // Let's not remove empty-string-valued global vars from the dict.
- // If we remove them, then they won't be exported, and sometimes
- // it could be necessary to export such a global. There are very
- // few empty-string global vars so there's no performance-related
- // need to remove them from the dict.
- /*
- if(!value[0] && name[0] == '$')
- {
- gEvalState.globalVars.remove(this);
- return;
- }
- */
- if (value == typeValueEmpty)
- {
- if (bufferLen > 0)
- {
- dFree(sval);
- bufferLen = 0;
- }
- sval = typeValueEmpty;
- fval = 0.f;
- ival = 0;
- type = TypeInternalString;
- return;
- }
- U32 stringLen = dStrlen(value);
- // If it's longer than 256 bytes, it's certainly not a number.
- //
- // (This decision may come back to haunt you. Shame on you if it
- // does.)
- if (stringLen < 256)
- {
- fval = dAtof(value);
- ival = dAtoi(value);
- }
- else
- {
- fval = 0.f;
- ival = 0;
- }
- // may as well pad to the next cache line
- U32 newLen = ((stringLen + 1) + 15) & ~15;
- if (bufferLen == 0)
- sval = (char *)dMalloc(newLen);
- else if (newLen > bufferLen)
- sval = (char *)dRealloc(sval, newLen);
- type = TypeInternalString;
- bufferLen = newLen;
- dStrcpy(sval, value, newLen);
- }
- else
- Con::setData(type, dataPtr, 0, 1, &value, enumTable);
- }
- void ConsoleValue::setStackStringValue(const char *value)
- {
- if (value == NULL) value = typeValueEmpty;
- if (type <= ConsoleValue::TypeInternalString)
- {
- // sval might still be temporarily present so we need to check and free it
- if (bufferLen > 0)
- {
- dFree(sval);
- bufferLen = 0;
- }
- if (value == typeValueEmpty)
- {
- sval = typeValueEmpty;
- fval = 0.f;
- ival = 0;
- type = TypeInternalString;
- return;
- }
- U32 stringLen = dStrlen(value);
- if (stringLen < 256)
- {
- fval = dAtof(value);
- ival = dAtoi(value);
- }
- else
- {
- fval = 0.f;
- ival = 0;
- }
- type = TypeInternalStackString;
- sval = (char*)value;
- bufferLen = 0;
- }
- else
- Con::setData(type, dataPtr, 0, 1, &value, enumTable);
- }
- void ConsoleValue::setStringStackPtrValue(StringStackPtr ptrValue)
- {
- if (type <= ConsoleValue::TypeInternalString)
- {
- const char *value = StringStackPtrRef(ptrValue).getPtr(&STR);
- if (bufferLen > 0)
- {
- dFree(sval);
- bufferLen = 0;
- }
- U32 stringLen = dStrlen(value);
- if (stringLen < 256)
- {
- fval = dAtof(value);
- ival = dAtoi(value);
- }
- else
- {
- fval = 0.f;
- ival = 0;
- }
- type = TypeInternalStringStackPtr;
- sval = (char*)(value - STR.mBuffer);
- bufferLen = 0;
- }
- else
- {
- const char *value = StringStackPtrRef(ptrValue).getPtr(&STR);
- Con::setData(type, dataPtr, 0, 1, &value, enumTable);
- }
- }
- S32 Dictionary::getIntVariable(StringTableEntry name, bool *entValid)
- {
- Entry *ent = lookup(name);
- if (ent)
- {
- if (entValid)
- *entValid = true;
- return ent->getIntValue();
- }
- if (entValid)
- *entValid = false;
- return 0;
- }
- F32 Dictionary::getFloatVariable(StringTableEntry name, bool *entValid)
- {
- Entry *ent = lookup(name);
- if (ent)
- {
- if (entValid)
- *entValid = true;
- return ent->getFloatValue();
- }
- if (entValid)
- *entValid = false;
- return 0;
- }
- void Dictionary::setVariable(StringTableEntry name, const char *value)
- {
- Entry *ent = add(name);
- if (!value)
- value = "";
- ent->setStringValue(value);
- }
- Dictionary::Entry* Dictionary::addVariable(const char *name,
- S32 type,
- void *dataPtr,
- const char* usage)
- {
- AssertFatal(type >= 0, "Dictionary::addVariable - Got bad type!");
- if (name[0] != '$')
- {
- scratchBuffer[0] = '$';
- dStrcpy(scratchBuffer + 1, name, 1023);
- name = scratchBuffer;
- }
- Entry *ent = add(StringTable->insert(name));
- if (ent->value.type <= ConsoleValue::TypeInternalString &&
- ent->value.bufferLen > 0)
- dFree(ent->value.sval);
- ent->value.type = type;
- ent->value.dataPtr = dataPtr;
- ent->mUsage = usage;
- // Fetch enum table, if any.
- ConsoleBaseType* conType = ConsoleBaseType::getType(type);
- AssertFatal(conType, "Dictionary::addVariable - invalid console type");
- ent->value.enumTable = conType->getEnumTable();
- return ent;
- }
- bool Dictionary::removeVariable(StringTableEntry name)
- {
- if (Entry *ent = lookup(name))
- {
- remove(ent);
- return true;
- }
- return false;
- }
- void Dictionary::addVariableNotify(const char *name, const Con::NotifyDelegate &callback)
- {
- Entry *ent = lookup(StringTable->insert(name));
- if (!ent)
- return;
- if (!ent->notify)
- ent->notify = new Entry::NotifySignal();
- ent->notify->notify(callback);
- }
- void Dictionary::removeVariableNotify(const char *name, const Con::NotifyDelegate &callback)
- {
- Entry *ent = lookup(StringTable->insert(name));
- if (ent && ent->notify)
- ent->notify->remove(callback);
- }
- void Dictionary::validate()
- {
- AssertFatal(ownHashTable.owner == this,
- "Dictionary::validate() - Dictionary not owner of own hashtable!");
- }
- void ExprEvalState::pushFrame(StringTableEntry frameName, Namespace *ns)
- {
- #ifdef DEBUG_SPEW
- validate();
- Platform::outputDebugString("[ConsoleInternal] Pushing new frame for '%s' at %i",
- frameName, mStackDepth);
- #endif
- if (mStackDepth + 1 > stack.size())
- {
- #ifdef DEBUG_SPEW
- Platform::outputDebugString("[ConsoleInternal] Growing stack by one frame");
- #endif
- stack.push_back(new Dictionary);
- }
- Dictionary& newFrame = *(stack[mStackDepth]);
- newFrame.setState(this);
- newFrame.scopeName = frameName;
- newFrame.scopeNamespace = ns;
- mStackDepth++;
- currentVariable = NULL;
- AssertFatal(!newFrame.getCount(), "ExprEvalState::pushFrame - Dictionary not empty!");
- #ifdef DEBUG_SPEW
- validate();
- #endif
- }
- void ExprEvalState::popFrame()
- {
- AssertFatal(mStackDepth > 0, "ExprEvalState::popFrame - Stack Underflow!");
- #ifdef DEBUG_SPEW
- validate();
- Platform::outputDebugString("[ConsoleInternal] Popping %sframe at %i",
- getCurrentFrame().isOwner() ? "" : "shared ", mStackDepth - 1);
- #endif
- mStackDepth--;
- stack[mStackDepth]->reset();
- currentVariable = NULL;
- #ifdef DEBUG_SPEW
- validate();
- #endif
- }
- void ExprEvalState::pushFrameRef(S32 stackIndex)
- {
- AssertFatal(stackIndex >= 0 && stackIndex < stack.size(), "You must be asking for a valid frame!");
- #ifdef DEBUG_SPEW
- validate();
- Platform::outputDebugString("[ConsoleInternal] Cloning frame from %i to %i",
- stackIndex, mStackDepth);
- #endif
- if (mStackDepth + 1 > stack.size())
- {
- #ifdef DEBUG_SPEW
- Platform::outputDebugString("[ConsoleInternal] Growing stack by one frame");
- #endif
- stack.push_back(new Dictionary);
- }
- Dictionary& newFrame = *(stack[mStackDepth]);
- newFrame.setState(this, stack[stackIndex]);
- mStackDepth++;
- currentVariable = NULL;
- #ifdef DEBUG_SPEW
- validate();
- #endif
- }
- ExprEvalState::ExprEvalState()
- {
- VECTOR_SET_ASSOCIATION(stack);
- globalVars.setState(this);
- thisObject = NULL;
- traceOn = false;
- currentVariable = NULL;
- mStackDepth = 0;
- stack.reserve(64);
- mShouldReset = false;
- mResetLocked = false;
- copyVariable = NULL;
- }
- ExprEvalState::~ExprEvalState()
- {
- // Delete callframes.
- while (!stack.empty())
- {
- delete stack.last();
- stack.decrement();
- }
- }
- void ExprEvalState::validate()
- {
- AssertFatal(mStackDepth <= stack.size(),
- "ExprEvalState::validate() - Stack depth pointing beyond last stack frame!");
- for (U32 i = 0; i < stack.size(); ++i)
- stack[i]->validate();
- }
- DefineEngineFunction(backtrace, void, (), ,
- "@brief Prints the scripting call stack to the console log.\n\n"
- "Used to trace functions called from within functions. Can help discover what functions were called "
- "(and not yet exited) before the current point in scripts.\n\n"
- "@ingroup Debugging")
- {
- U32 totalSize = 1;
- for (U32 i = 0; i < gEvalState.getStackDepth(); i++)
- {
- if (gEvalState.stack[i]->scopeNamespace && gEvalState.stack[i]->scopeNamespace->mEntryList->mPackage)
- totalSize += dStrlen(gEvalState.stack[i]->scopeNamespace->mEntryList->mPackage) + 2;
- if (gEvalState.stack[i]->scopeName)
- totalSize += dStrlen(gEvalState.stack[i]->scopeName) + 3;
- if (gEvalState.stack[i]->scopeNamespace && gEvalState.stack[i]->scopeNamespace->mName)
- totalSize += dStrlen(gEvalState.stack[i]->scopeNamespace->mName) + 2;
- }
- char *buf = Con::getReturnBuffer(totalSize);
- buf[0] = 0;
- for (U32 i = 0; i < gEvalState.getStackDepth(); i++)
- {
- dStrcat(buf, "->", totalSize);
- if (gEvalState.stack[i]->scopeNamespace && gEvalState.stack[i]->scopeNamespace->mEntryList->mPackage)
- {
- dStrcat(buf, "[", totalSize);
- dStrcat(buf, gEvalState.stack[i]->scopeNamespace->mEntryList->mPackage, totalSize);
- dStrcat(buf, "]", totalSize);
- }
- if (gEvalState.stack[i]->scopeNamespace && gEvalState.stack[i]->scopeNamespace->mName)
- {
- dStrcat(buf, gEvalState.stack[i]->scopeNamespace->mName, totalSize);
- dStrcat(buf, "::", totalSize);
- }
- if (gEvalState.stack[i]->scopeName)
- dStrcat(buf, gEvalState.stack[i]->scopeName, totalSize);
- }
- Con::printf("BackTrace: %s", buf);
- }
- Namespace::Entry::Entry()
- {
- mCode = NULL;
- mType = InvalidFunctionType;
- mUsage = NULL;
- mHeader = NULL;
- mNamespace = NULL;
- cb.mStringCallbackFunc = NULL;
- mFunctionLineNumber = 0;
- mFunctionName = StringTable->EmptyString();
- mFunctionOffset = 0;
- mMinArgs = 0;
- mMaxArgs = 0;
- mNext = NULL;
- mPackage = StringTable->EmptyString();
- mToolOnly = false;
- }
- void Namespace::Entry::clear()
- {
- if (mCode)
- {
- mCode->decRefCount();
- mCode = NULL;
- }
- // Clean up usage strings generated for script functions.
- if ((mType == Namespace::Entry::ConsoleFunctionType) && mUsage)
- {
- dFree(mUsage);
- mUsage = NULL;
- }
- }
- Namespace::Namespace()
- {
- mPackage = NULL;
- mUsage = NULL;
- mCleanUpUsage = false;
- mName = NULL;
- mParent = NULL;
- mNext = NULL;
- mEntryList = NULL;
- mHashSize = 0;
- mHashTable = 0;
- mHashSequence = 0;
- mRefCountToParent = 0;
- mClassRep = 0;
- lastUsage = NULL;
- }
- Namespace::~Namespace()
- {
- clearEntries();
- if (mUsage && mCleanUpUsage)
- {
- dFree(mUsage);
- mUsage = NULL;
- mCleanUpUsage = false;
- }
- }
- void Namespace::clearEntries()
- {
- for (Entry *walk = mEntryList; walk; walk = walk->mNext)
- walk->clear();
- }
- Namespace *Namespace::find(StringTableEntry name, StringTableEntry package)
- {
- if (name == NULL && package == NULL)
- return mGlobalNamespace;
- auto pair = std::make_pair(name, package);
- auto pos = gNamespaceCache.find(pair);
- if (pos != gNamespaceCache.end())
- return pos->second;
- Namespace *ret = (Namespace *)mAllocator.alloc(sizeof(Namespace));
- constructInPlace(ret);
- ret->mPackage = package;
- ret->mName = name;
- ret->mNext = mNamespaceList;
- mNamespaceList = ret;
- // insert into namespace cache.
- gNamespaceCache[pair] = ret;
- return ret;
- }
- bool Namespace::unlinkClass(Namespace *parent)
- {
- AssertFatal(mPackage == NULL, "Namespace::unlinkClass - Must not be called on a namespace coming from a package!");
- // Skip additions to this namespace coming from packages.
- Namespace* walk = getPackageRoot();
- // Make sure "parent" is the direct parent namespace.
- if (parent != NULL && walk->mParent && walk->mParent != parent)
- {
- Con::errorf(ConsoleLogEntry::General, "Namespace::unlinkClass - cannot unlink namespace parent linkage for %s for %s.",
- walk->mName, walk->mParent->mName);
- return false;
- }
- // Decrease the reference count. Note that we do this on
- // the bottom-most namespace, i.e. the one guaranteed not
- // to come from a package.
- mRefCountToParent--;
- AssertFatal(mRefCountToParent >= 0, "Namespace::unlinkClass - reference count to parent is less than 0");
- // Unlink if the count dropped to zero.
- if (mRefCountToParent == 0)
- {
- walk->mParent = NULL;
- trashCache();
- }
- return true;
- }
- bool Namespace::classLinkTo(Namespace *parent)
- {
- Namespace* walk = getPackageRoot();
- if (walk->mParent && walk->mParent != parent)
- {
- Con::errorf(ConsoleLogEntry::General, "Error: cannot change namespace parent linkage of %s from %s to %s.",
- walk->mName, walk->mParent->mName, parent->mName);
- return false;
- }
- trashCache();
- walk->mParent = parent;
- mRefCountToParent++;
- return true;
- }
- void Namespace::buildHashTable()
- {
- if (mHashSequence == mCacheSequence)
- return;
- if (!mEntryList && mParent)
- {
- mParent->buildHashTable();
- mHashTable = mParent->mHashTable;
- mHashSize = mParent->mHashSize;
- mHashSequence = mCacheSequence;
- return;
- }
- U32 entryCount = 0;
- Namespace * ns;
- for (ns = this; ns; ns = ns->mParent)
- for (Entry *walk = ns->mEntryList; walk; walk = walk->mNext)
- if (lookupRecursive(walk->mFunctionName) == walk)
- entryCount++;
- mHashSize = entryCount + (entryCount >> 1) + 1;
- if (!(mHashSize & 1))
- mHashSize++;
- mHashTable = (Entry **)mCacheAllocator.alloc(sizeof(Entry *) * mHashSize);
- for (U32 i = 0; i < mHashSize; i++)
- mHashTable[i] = NULL;
- for (ns = this; ns; ns = ns->mParent)
- {
- for (Entry *walk = ns->mEntryList; walk; walk = walk->mNext)
- {
- U32 index = HashPointer(walk->mFunctionName) % mHashSize;
- while (mHashTable[index] && mHashTable[index]->mFunctionName != walk->mFunctionName)
- {
- index++;
- if (index >= mHashSize)
- index = 0;
- }
- if (!mHashTable[index])
- mHashTable[index] = walk;
- }
- }
- mHashSequence = mCacheSequence;
- }
- void Namespace::getUniqueEntryLists(Namespace *other, VectorPtr<Entry *> *outThisList, VectorPtr<Entry *> *outOtherList)
- {
- // All namespace entries in the common ACR should be
- // ignored when checking for duplicate entry names.
- static VectorPtr<Namespace::Entry *> commonEntries;
- commonEntries.clear();
- AbstractClassRep *commonACR = mClassRep->getCommonParent(other->mClassRep);
- commonACR->getNameSpace()->getEntryList(&commonEntries);
- // Make life easier
- VectorPtr<Namespace::Entry *> &thisEntries = *outThisList;
- VectorPtr<Namespace::Entry *> &compEntries = *outOtherList;
- // Clear, just in case they aren't
- thisEntries.clear();
- compEntries.clear();
- getEntryList(&thisEntries);
- other->getEntryList(&compEntries);
- // Run through all of the entries in the common ACR, and remove them from
- // the other two entry lists
- for (NamespaceEntryListIterator itr = commonEntries.begin(); itr != commonEntries.end(); itr++)
- {
- // Check this entry list
- for (NamespaceEntryListIterator thisItr = thisEntries.begin(); thisItr != thisEntries.end(); thisItr++)
- {
- if (*thisItr == *itr)
- {
- thisEntries.erase(thisItr);
- break;
- }
- }
- // Same check for component entry list
- for (NamespaceEntryListIterator compItr = compEntries.begin(); compItr != compEntries.end(); compItr++)
- {
- if (*compItr == *itr)
- {
- compEntries.erase(compItr);
- break;
- }
- }
- }
- }
- void Namespace::init()
- {
- // create the global namespace
- mGlobalNamespace = (Namespace *)mAllocator.alloc(sizeof(Namespace));
- constructInPlace(mGlobalNamespace);
- mGlobalNamespace->mPackage = NULL;
- mGlobalNamespace->mName = NULL;
- mGlobalNamespace->mNext = NULL;
- mNamespaceList = mGlobalNamespace;
- // Insert into namespace cache.
- gNamespaceCache[std::make_pair(mGlobalNamespace->mName, mGlobalNamespace->mPackage)] = mGlobalNamespace;
- }
- Namespace *Namespace::global()
- {
- return mGlobalNamespace;
- }
- void Namespace::shutdown()
- {
- // The data chunker will release all memory in one go
- // without calling destructors, so we do this manually here.
- for (Namespace *walk = mNamespaceList; walk; walk = walk->mNext)
- walk->~Namespace();
- }
- void Namespace::trashCache()
- {
- mCacheSequence++;
- mCacheAllocator.freeBlocks();
- }
- const char *Namespace::tabComplete(const char *prevText, S32 baseLen, bool fForward)
- {
- if (mHashSequence != mCacheSequence)
- buildHashTable();
- const char *bestMatch = NULL;
- for (U32 i = 0; i < mHashSize; i++)
- if (mHashTable[i] && canTabComplete(prevText, bestMatch, mHashTable[i]->mFunctionName, baseLen, fForward))
- bestMatch = mHashTable[i]->mFunctionName;
- return bestMatch;
- }
- Namespace::Entry *Namespace::lookupRecursive(StringTableEntry name)
- {
- for (Namespace *ns = this; ns; ns = ns->mParent)
- for (Entry *walk = ns->mEntryList; walk; walk = walk->mNext)
- if (walk->mFunctionName == name)
- return walk;
- return NULL;
- }
- Namespace::Entry *Namespace::lookup(StringTableEntry name)
- {
- if (mHashSequence != mCacheSequence)
- buildHashTable();
- U32 index = HashPointer(name) % mHashSize;
- while (mHashTable[index] && mHashTable[index]->mFunctionName != name)
- {
- index++;
- if (index >= mHashSize)
- index = 0;
- }
- return mHashTable[index];
- }
- static S32 QSORT_CALLBACK compareEntries(const void* a, const void* b)
- {
- const Namespace::Entry* fa = *((Namespace::Entry**)a);
- const Namespace::Entry* fb = *((Namespace::Entry**)b);
- return dStricmp(fa->mFunctionName, fb->mFunctionName);
- }
- void Namespace::getEntryList(VectorPtr<Entry *> *vec)
- {
- if (mHashSequence != mCacheSequence)
- buildHashTable();
- for (U32 i = 0; i < mHashSize; i++)
- if (mHashTable[i])
- vec->push_back(mHashTable[i]);
- dQsort(vec->address(), vec->size(), sizeof(Namespace::Entry *), compareEntries);
- }
- Namespace::Entry *Namespace::createLocalEntry(StringTableEntry name)
- {
- for (Entry *walk = mEntryList; walk; walk = walk->mNext)
- {
- if (walk->mFunctionName == name)
- {
- walk->clear();
- return walk;
- }
- }
- Entry *ent = (Entry *)mAllocator.alloc(sizeof(Entry));
- constructInPlace(ent);
- ent->mNamespace = this;
- ent->mFunctionName = name;
- ent->mNext = mEntryList;
- ent->mPackage = mPackage;
- ent->mToolOnly = false;
- mEntryList = ent;
- return ent;
- }
- void Namespace::addFunction(StringTableEntry name, CodeBlock *cb, U32 functionOffset, const char* usage, U32 lineNumber)
- {
- Entry *ent = createLocalEntry(name);
- trashCache();
- ent->mUsage = usage;
- ent->mCode = cb;
- ent->mFunctionOffset = functionOffset;
- ent->mCode->incRefCount();
- ent->mType = Entry::ConsoleFunctionType;
- ent->mFunctionLineNumber = lineNumber;
- }
- void Namespace::addCommand(StringTableEntry name, StringCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header)
- {
- Entry *ent = createLocalEntry(name);
- trashCache();
- ent->mUsage = usage;
- ent->mHeader = header;
- ent->mMinArgs = minArgs;
- ent->mMaxArgs = maxArgs;
- ent->mToolOnly = isToolOnly;
- ent->mType = Entry::StringCallbackType;
- ent->cb.mStringCallbackFunc = cb;
- }
- void Namespace::addCommand(StringTableEntry name, IntCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header)
- {
- Entry *ent = createLocalEntry(name);
- trashCache();
- ent->mUsage = usage;
- ent->mHeader = header;
- ent->mMinArgs = minArgs;
- ent->mMaxArgs = maxArgs;
- ent->mToolOnly = isToolOnly;
- ent->mType = Entry::IntCallbackType;
- ent->cb.mIntCallbackFunc = cb;
- }
- void Namespace::addCommand(StringTableEntry name, VoidCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header)
- {
- Entry *ent = createLocalEntry(name);
- trashCache();
- ent->mUsage = usage;
- ent->mHeader = header;
- ent->mMinArgs = minArgs;
- ent->mMaxArgs = maxArgs;
- ent->mToolOnly = isToolOnly;
- ent->mType = Entry::VoidCallbackType;
- ent->cb.mVoidCallbackFunc = cb;
- }
- void Namespace::addCommand(StringTableEntry name, FloatCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header)
- {
- Entry *ent = createLocalEntry(name);
- trashCache();
- ent->mUsage = usage;
- ent->mHeader = header;
- ent->mMinArgs = minArgs;
- ent->mMaxArgs = maxArgs;
- ent->mToolOnly = isToolOnly;
- ent->mType = Entry::FloatCallbackType;
- ent->cb.mFloatCallbackFunc = cb;
- }
- void Namespace::addCommand(StringTableEntry name, BoolCallback cb, const char *usage, S32 minArgs, S32 maxArgs, bool isToolOnly, ConsoleFunctionHeader* header)
- {
- Entry *ent = createLocalEntry(name);
- trashCache();
- ent->mUsage = usage;
- ent->mHeader = header;
- ent->mMinArgs = minArgs;
- ent->mMaxArgs = maxArgs;
- ent->mToolOnly = isToolOnly;
- ent->mType = Entry::BoolCallbackType;
- ent->cb.mBoolCallbackFunc = cb;
- }
- void Namespace::addScriptCallback(const char *funcName, const char *usage, ConsoleFunctionHeader* header)
- {
- static U32 uid = 0;
- char buffer[1024];
- char lilBuffer[32];
- dStrcpy(buffer, funcName, 1024);
- dSprintf(lilBuffer, 32, "_%d_cb", uid++);
- dStrcat(buffer, lilBuffer, 1024);
- Entry *ent = createLocalEntry(StringTable->insert(buffer));
- trashCache();
- ent->mUsage = usage;
- ent->mHeader = header;
- ent->mMinArgs = -2;
- ent->mMaxArgs = -3;
- ent->mType = Entry::ScriptCallbackType;
- ent->cb.mCallbackName = funcName;
- }
- void Namespace::markGroup(const char* name, const char* usage)
- {
- static U32 uid = 0;
- char buffer[1024];
- char lilBuffer[32];
- dStrcpy(buffer, name, 1024);
- dSprintf(lilBuffer, 32, "_%d", uid++);
- dStrcat(buffer, lilBuffer, 1024);
- Entry *ent = createLocalEntry(StringTable->insert(buffer));
- trashCache();
- if (usage != NULL)
- lastUsage = (char*)(ent->mUsage = usage);
- else
- ent->mUsage = lastUsage;
- ent->mMinArgs = -1; // Make sure it explodes if somehow we run this entry.
- ent->mMaxArgs = -2;
- ent->mType = Entry::GroupMarker;
- ent->cb.mGroupName = name;
- }
- extern S32 executeBlock(StmtNode *block, ExprEvalState *state);
- ConsoleValueRef Namespace::Entry::execute(S32 argc, ConsoleValueRef *argv, ExprEvalState *state)
- {
- STR.clearFunctionOffset();
- if (mType == ConsoleFunctionType)
- {
- if (mFunctionOffset)
- {
- return mCode->exec(mFunctionOffset, argv[0], mNamespace, argc, argv, false, mPackage);
- }
- else
- {
- return ConsoleValueRef();
- }
- }
- #ifndef TORQUE_DEBUG
- // [tom, 12/13/2006] This stops tools functions from working in the console,
- // which is useful behavior when debugging so I'm ifdefing this out for debug builds.
- if (mToolOnly && !Con::isCurrentScriptToolScript())
- {
- Con::errorf(ConsoleLogEntry::Script, "%s::%s - attempting to call tools only function from outside of tools", mNamespace->mName, mFunctionName);
- return ConsoleValueRef();
- }
- #endif
- if ((mMinArgs && argc < mMinArgs) || (mMaxArgs && argc > mMaxArgs))
- {
- Con::warnf(ConsoleLogEntry::Script, "%s::%s - wrong number of arguments.", mNamespace->mName, mFunctionName);
- Con::warnf(ConsoleLogEntry::Script, "usage: %s", mUsage);
- return ConsoleValueRef();
- }
- switch (mType)
- {
- case StringCallbackType:
- return ConsoleValueRef::fromValue(CSTK.pushStackString(cb.mStringCallbackFunc(state->thisObject, argc, argv)));
- case IntCallbackType:
- return ConsoleValueRef::fromValue(CSTK.pushUINT((U32)cb.mBoolCallbackFunc(state->thisObject, argc, argv)));
- case FloatCallbackType:
- return ConsoleValueRef::fromValue(CSTK.pushFLT((U32)cb.mBoolCallbackFunc(state->thisObject, argc, argv)));
- case VoidCallbackType:
- cb.mVoidCallbackFunc(state->thisObject, argc, argv);
- return ConsoleValueRef();
- case BoolCallbackType:
- return ConsoleValueRef::fromValue(CSTK.pushUINT((U32)cb.mBoolCallbackFunc(state->thisObject, argc, argv)));
- }
- return ConsoleValueRef();
- }
- //-----------------------------------------------------------------------------
- // Doc string code.
- namespace {
- /// Scan the given usage string for an argument list description. With the
- /// old console macros, these were usually included as the first part of the
- /// usage string.
- bool sFindArgumentListSubstring(const char* usage, const char*& start, const char*& end)
- {
- if (!usage)
- return false;
- const char* ptr = usage;
- while (*ptr && *ptr != '(' && *ptr != '\n') // Only scan first line of usage string.
- {
- // Stop on the first alphanumeric character as we expect
- // argument lists to precede descriptions.
- if (dIsalnum(*ptr))
- return false;
- ptr++;
- }
- if (*ptr != '(')
- return false;
- start = ptr;
- ptr++;
- bool inString = false;
- U32 nestingCount = 0;
- while (*ptr && (*ptr != ')' || nestingCount > 0 || inString))
- {
- if (*ptr == '(')
- nestingCount++;
- else if (*ptr == ')')
- nestingCount--;
- else if (*ptr == '"')
- inString = !inString;
- else if (*ptr == '\\' && ptr[1] == '"')
- ptr++;
- ptr++;
- }
- if (*ptr)
- ptr++;
- end = ptr;
- return true;
- }
- ///
- void sParseList(const char* str, Vector< String >& outList)
- {
- // Skip the initial '( '.
- const char* ptr = str;
- while (*ptr && dIsspace(*ptr))
- ptr++;
- if (*ptr == '(')
- {
- ptr++;
- while (*ptr && dIsspace(*ptr))
- ptr++;
- }
- // Parse out list items.
- while (*ptr && *ptr != ')')
- {
- // Find end of element.
- const char* start = ptr;
- bool inString = false;
- U32 nestingCount = 0;
- while (*ptr && ((*ptr != ')' && *ptr != ',') || nestingCount > 0 || inString))
- {
- if (*ptr == '(')
- nestingCount++;
- else if (*ptr == ')')
- nestingCount--;
- else if (*ptr == '"')
- inString = !inString;
- else if (*ptr == '\\' && ptr[1] == '"')
- ptr++;
- ptr++;
- }
- // Backtrack to remove trailing whitespace.
- const char* end = ptr;
- if (*end == ',' || *end == ')')
- end--;
- while (end > start && dIsspace(*end))
- end--;
- if (*end)
- end++;
- // Add to list.
- if (start != end)
- outList.push_back(String(start, end - start));
- // Skip comma and whitespace.
- if (*ptr == ',')
- ptr++;
- while (*ptr && dIsspace(*ptr))
- ptr++;
- }
- }
- ///
- void sGetArgNameAndType(const String& str, String& outType, String& outName)
- {
- if (!str.length())
- {
- outType = String::EmptyString;
- outName = String::EmptyString;
- return;
- }
- // Find first non-ID character from right.
- S32 index = str.length() - 1;
- while (index >= 0 && (dIsalnum(str[index]) || str[index] == '_'))
- index--;
- const U32 nameStartIndex = index + 1;
- // Find end of type name by skipping rightmost whitespace inwards.
- while (index >= 0 && dIsspace(str[index]))
- index--;
- //
- outName = String(&((const char*)str)[nameStartIndex]);
- outType = String(str, index + 1);
- }
- /// Return the type name to show in documentation for the given C++ type.
- const char* sGetDocTypeString(const char* nativeType)
- {
- if (dStrncmp(nativeType, "const ", 6) == 0)
- nativeType += 6;
- if (String::compare(nativeType, "char*") == 0 || String::compare(nativeType, "char *") == 0)
- return "string";
- else if (String::compare(nativeType, "S32") == 0)
- return "int";
- else if (String::compare(nativeType, "U32") == 0)
- return "uint";
- else if (String::compare(nativeType, "F32") == 0)
- return "float";
- const U32 length = dStrlen(nativeType);
- if (nativeType[length - 1] == '&' || nativeType[length - 1] == '*')
- return StringTable->insertn(nativeType, length - 1);
- return nativeType;
- }
- }
- String Namespace::Entry::getBriefDescription(String* outRemainingDocText) const
- {
- String docString = getDocString();
- S32 newline = docString.find('\n');
- if (newline == -1)
- {
- if (outRemainingDocText)
- *outRemainingDocText = String();
- return docString;
- }
- String brief = docString.substr(0, newline);
- if (outRemainingDocText)
- *outRemainingDocText = docString.substr(newline + 1);
- return brief;
- }
- String Namespace::Entry::getDocString() const
- {
- const char* argListStart;
- const char* argListEnd;
- if (sFindArgumentListSubstring(mUsage, argListStart, argListEnd))
- {
- // Skip the " - " part present in some old doc strings.
- const char* ptr = argListEnd;
- while (*ptr && dIsspace(*ptr))
- ptr++;
- if (*ptr == '-')
- {
- ptr++;
- while (*ptr && dIsspace(*ptr))
- ptr++;
- }
- return ptr;
- }
- return mUsage;
- }
- String Namespace::Entry::getArgumentsString() const
- {
- StringBuilder str;
- if (mHeader)
- {
- // Parse out the argument list string supplied with the extended
- // function header and add default arguments as we go.
- Vector< String > argList;
- Vector< String > defaultArgList;
- sParseList(mHeader->mArgString, argList);
- sParseList(mHeader->mDefaultArgString, defaultArgList);
- str.append('(');
- const U32 numArgs = argList.size();
- const U32 numDefaultArgs = defaultArgList.size();
- const U32 firstDefaultArgIndex = numArgs - numDefaultArgs;
- for (U32 i = 0; i < numArgs; ++i)
- {
- // Add separator if not first arg.
- if (i > 0)
- str.append(',');
- // Add type and name.
- String name;
- String type;
- sGetArgNameAndType(argList[i], type, name);
- str.append(' ');
- str.append(sGetDocTypeString(type));
- str.append(' ');
- str.append(name);
- // Add default value, if any.
- if (i >= firstDefaultArgIndex)
- {
- str.append('=');
- str.append(defaultArgList[i - firstDefaultArgIndex]);
- }
- }
- if (numArgs > 0)
- str.append(' ');
- str.append(')');
- }
- else
- {
- // No extended function header. Try to parse out the argument
- // list from the usage string.
- const char* argListStart;
- const char* argListEnd;
- if (sFindArgumentListSubstring(mUsage, argListStart, argListEnd))
- str.append(argListStart, argListEnd - argListStart);
- else if (mType == ConsoleFunctionType && mCode)
- {
- // This isn't correct but the nonsense console stuff is set up such that all
- // functions that have no function bodies are keyed to offset 0 to indicate "no code."
- // This loses the association with the original function definition so we can't really
- // tell here what the actual prototype is except if we searched though the entire opcode
- // stream for the corresponding OP_FUNC_DECL (which would require dealing with the
- // variable-size instructions).
- if (!mFunctionOffset)
- return "()";
- String args = mCode->getFunctionArgs(mFunctionOffset);
- if (args.isEmpty())
- return "()";
- str.append("( ");
- str.append(args);
- str.append(" )");
- }
- }
- return str.end();
- }
- String Namespace::Entry::getPrototypeString() const
- {
- StringBuilder str;
- // Start with return type.
- if (mHeader && mHeader->mReturnString)
- {
- str.append(sGetDocTypeString(mHeader->mReturnString));
- str.append(' ');
- }
- else
- switch (mType)
- {
- case StringCallbackType:
- str.append("string ");
- break;
- case IntCallbackType:
- str.append("int ");
- break;
- case FloatCallbackType:
- str.append("float ");
- break;
- case VoidCallbackType:
- str.append("void ");
- break;
- case BoolCallbackType:
- str.append("bool ");
- break;
- case ScriptCallbackType:
- break;
- }
- // Add function name and arguments.
- if (mType == ScriptCallbackType)
- str.append(cb.mCallbackName);
- else
- str.append(mFunctionName);
- str.append(getArgumentsString());
- return str.end();
- }
- //-----------------------------------------------------------------------------
- StringTableEntry Namespace::mActivePackages[Namespace::MaxActivePackages];
- U32 Namespace::mNumActivePackages = 0;
- U32 Namespace::mOldNumActivePackages = 0;
- bool Namespace::isPackage(StringTableEntry name)
- {
- for (Namespace *walk = mNamespaceList; walk; walk = walk->mNext)
- if (walk->mPackage == name)
- return true;
- return false;
- }
- U32 Namespace::getActivePackagesCount()
- {
- return mNumActivePackages;
- }
- StringTableEntry Namespace::getActivePackage(U32 index)
- {
- if (index >= mNumActivePackages)
- return StringTable->EmptyString();
- return mActivePackages[index];
- }
- void Namespace::activatePackage(StringTableEntry name)
- {
- if (mNumActivePackages == MaxActivePackages)
- {
- Con::printf("ActivatePackage(%s) failed - Max package limit reached: %d", name, MaxActivePackages);
- return;
- }
- if (!name)
- return;
- // see if this one's already active
- for (U32 i = 0; i < mNumActivePackages; i++)
- if (mActivePackages[i] == name)
- return;
- // kill the cache
- trashCache();
- // find all the package namespaces...
- for (Namespace *walk = mNamespaceList; walk; walk = walk->mNext)
- {
- if (walk->mPackage == name)
- {
- Namespace *parent = Namespace::find(walk->mName);
- // hook the parent
- walk->mParent = parent->mParent;
- parent->mParent = walk;
- // now swap the entries:
- Entry *ew;
- for (ew = parent->mEntryList; ew; ew = ew->mNext)
- ew->mNamespace = walk;
- for (ew = walk->mEntryList; ew; ew = ew->mNext)
- ew->mNamespace = parent;
- ew = walk->mEntryList;
- walk->mEntryList = parent->mEntryList;
- parent->mEntryList = ew;
- }
- }
- mActivePackages[mNumActivePackages++] = name;
- }
- void Namespace::deactivatePackage(StringTableEntry name)
- {
- U32 oldNumActivePackages = mNumActivePackages;
- // Remove all packages down to the given one
- deactivatePackageStack(name);
- // Now add back all packages that followed the given one
- if (!oldNumActivePackages)
- return;
- for (U32 i = mNumActivePackages + 1; i < oldNumActivePackages; i++)
- activatePackage(mActivePackages[i]);
- }
- void Namespace::deactivatePackageStack(StringTableEntry name)
- {
- S32 i, j;
- for (i = 0; i < mNumActivePackages; i++)
- if (mActivePackages[i] == name)
- break;
- if (i == mNumActivePackages)
- return;
- trashCache();
- // Remove all packages down to the given one
- for (j = mNumActivePackages - 1; j >= i; j--)
- {
- // gotta unlink em in reverse order...
- for (Namespace *walk = mNamespaceList; walk; walk = walk->mNext)
- {
- if (walk->mPackage == mActivePackages[j])
- {
- Namespace *parent = Namespace::find(walk->mName);
- // hook the parent
- parent->mParent = walk->mParent;
- walk->mParent = NULL;
- // now swap the entries:
- Entry *ew;
- for (ew = parent->mEntryList; ew; ew = ew->mNext)
- ew->mNamespace = walk;
- for (ew = walk->mEntryList; ew; ew = ew->mNext)
- ew->mNamespace = parent;
- ew = walk->mEntryList;
- walk->mEntryList = parent->mEntryList;
- parent->mEntryList = ew;
- }
- }
- }
- mNumActivePackages = i;
- }
- void Namespace::unlinkPackages()
- {
- mOldNumActivePackages = mNumActivePackages;
- if (!mNumActivePackages)
- return;
- deactivatePackageStack(mActivePackages[0]);
- }
- void Namespace::relinkPackages()
- {
- if (!mOldNumActivePackages)
- return;
- for (U32 i = 0; i < mOldNumActivePackages; i++)
- activatePackage(mActivePackages[i]);
- }
- DefineEngineFunction(isPackage, bool, (String identifier), ,
- "@brief Returns true if the identifier is the name of a declared package.\n\n"
- "@ingroup Packages\n")
- {
- StringTableEntry name = StringTable->insert(identifier.c_str());
- return Namespace::isPackage(name);
- }
- DefineEngineFunction(activatePackage, void, (String packageName), ,
- "@brief Activates an existing package.\n\n"
- "The activation occurs by updating the namespace linkage of existing functions and methods. "
- "If the package is already activated the function does nothing.\n"
- "@ingroup Packages\n")
- {
- StringTableEntry name = StringTable->insert(packageName.c_str());
- Namespace::activatePackage(name);
- }
- DefineEngineFunction(deactivatePackage, void, (String packageName), ,
- "@brief Deactivates a previously activated package.\n\n"
- "The package is deactivated by removing its namespace linkages to any function or method. "
- "If there are any packages above this one in the stack they are deactivated as well. "
- "If the package is not on the stack this function does nothing.\n"
- "@ingroup Packages\n")
- {
- StringTableEntry name = StringTable->insert(packageName.c_str());
- Namespace::deactivatePackage(name);
- }
- DefineEngineFunction(getPackageList, const char*, (), ,
- "@brief Returns a space delimited list of the active packages in stack order.\n\n"
- "@ingroup Packages\n")
- {
- if (Namespace::getActivePackagesCount() == 0)
- return "";
- // Determine size of return buffer
- dsize_t buffersize = 0;
- for (U32 i = 0; i < Namespace::getActivePackagesCount(); ++i)
- {
- buffersize += dStrlen(Namespace::getActivePackage(i)) + 1;
- }
- U32 maxBufferSize = buffersize + 1;
- char* returnBuffer = Con::getReturnBuffer(maxBufferSize);
- U32 returnLen = 0;
- for (U32 i = 0; i < Namespace::getActivePackagesCount(); ++i)
- {
- dSprintf(returnBuffer + returnLen, maxBufferSize - returnLen, "%s ", Namespace::getActivePackage(i));
- returnLen = dStrlen(returnBuffer);
- }
- // Trim off the last extra space
- if (returnLen > 0 && returnBuffer[returnLen - 1] == ' ')
- returnBuffer[returnLen - 1] = '\0';
- return returnBuffer;
- }
|