consoleInternal.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  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. #ifndef _CONSOLEINTERNAL_H_
  23. #define _CONSOLEINTERNAL_H_
  24. #ifndef _STRINGFUNCTIONS_H_
  25. #include "core/strings/stringFunctions.h"
  26. #endif
  27. #ifndef _STRINGTABLE_H_
  28. #include "core/stringTable.h"
  29. #endif
  30. #ifndef _CONSOLETYPES_H
  31. #include "console/consoleTypes.h"
  32. #endif
  33. #ifndef _CONSOLEOBJECT_H_
  34. #include "console/simObject.h"
  35. #endif
  36. #ifndef _DATACHUNKER_H_
  37. #include "core/dataChunker.h"
  38. #endif
  39. /// @ingroup console_system Console System
  40. /// @{
  41. class ExprEvalState;
  42. struct FunctionDecl;
  43. class CodeBlock;
  44. class AbstractClassRep;
  45. /// A dictionary of function entries.
  46. ///
  47. /// Namespaces are used for dispatching calls in the console system.
  48. class Namespace
  49. {
  50. enum {
  51. MaxActivePackages = 512,
  52. };
  53. static U32 mNumActivePackages;
  54. static U32 mOldNumActivePackages;
  55. static StringTableEntry mActivePackages[MaxActivePackages];
  56. public:
  57. StringTableEntry mName;
  58. StringTableEntry mPackage;
  59. Namespace *mParent;
  60. Namespace *mNext;
  61. AbstractClassRep *mClassRep;
  62. U32 mRefCountToParent;
  63. const char* mUsage;
  64. /// Script defined usage strings need to be cleaned up. This
  65. /// field indicates whether or not the usage was set from script.
  66. bool mCleanUpUsage;
  67. /// A function entry in the namespace.
  68. struct Entry
  69. {
  70. enum
  71. {
  72. ScriptCallbackType = -3,
  73. GroupMarker = -2,
  74. InvalidFunctionType = -1,
  75. ConsoleFunctionType,
  76. StringCallbackType,
  77. IntCallbackType,
  78. FloatCallbackType,
  79. VoidCallbackType,
  80. BoolCallbackType
  81. };
  82. /// Link back to the namespace to which the entry belongs.
  83. Namespace* mNamespace;
  84. /// Next function entry in the hashtable link chain of the namespace.
  85. Entry* mNext;
  86. /// Name of this function.
  87. StringTableEntry mFunctionName;
  88. ///
  89. S32 mType;
  90. /// Min number of arguments expected by this function.
  91. S32 mMinArgs;
  92. /// Max number of arguments expected by this function. If zero,
  93. /// function takes an arbitrary number of arguments.
  94. S32 mMaxArgs;
  95. /// Name of the package to which this function belongs.
  96. StringTableEntry mPackage;
  97. /// Whether this function is included only in TORQUE_TOOLS builds.
  98. bool mToolOnly;
  99. /// Usage string for documentation.
  100. const char* mUsage;
  101. /// Extended console function information.
  102. ConsoleFunctionHeader* mHeader;
  103. /// The compiled script code if this is a script function.
  104. CodeBlock* mCode;
  105. /// The offset in the compiled script code at which this function begins.
  106. U32 mFunctionOffset;
  107. /// If it's a script function, this is the line of the declaration in code.
  108. /// @note 0 for functions read from legacy DSOs that have no line number information.
  109. U32 mFunctionLineNumber;
  110. union CallbackUnion {
  111. StringCallback mStringCallbackFunc;
  112. IntCallback mIntCallbackFunc;
  113. VoidCallback mVoidCallbackFunc;
  114. FloatCallback mFloatCallbackFunc;
  115. BoolCallback mBoolCallbackFunc;
  116. const char *mGroupName;
  117. const char *mCallbackName;
  118. } cb;
  119. Entry();
  120. ///
  121. void clear();
  122. ///
  123. ConsoleValue execute(S32 argc, ConsoleValue* argv, ExprEvalState* state);
  124. /// Return a one-line documentation text string for the function.
  125. String getBriefDescription(String* outRemainingDocText = NULL) const;
  126. /// Get the auto-doc string for this function. This string does not included prototype information.
  127. String getDocString() const;
  128. /// Return a string describing the arguments the function takes including default argument values.
  129. String getArgumentsString() const;
  130. /// Return a full prototype string for the function including return type, function name,
  131. /// and arguments.
  132. String getPrototypeString() const;
  133. };
  134. Entry* mEntryList;
  135. Entry** mHashTable;
  136. U32 mHashSize;
  137. U32 mHashSequence; ///< @note The hash sequence is used by the autodoc console facility
  138. /// as a means of testing reference state.
  139. Namespace();
  140. ~Namespace();
  141. void addFunction(StringTableEntry name, CodeBlock* cb, U32 functionOffset, const char* usage = NULL, U32 lineNumber = 0);
  142. void addCommand(StringTableEntry name, StringCallback, const char *usage, S32 minArgs, S32 maxArgs, bool toolOnly = false, ConsoleFunctionHeader* header = NULL);
  143. void addCommand(StringTableEntry name, IntCallback, const char *usage, S32 minArgs, S32 maxArgs, bool toolOnly = false, ConsoleFunctionHeader* header = NULL);
  144. void addCommand(StringTableEntry name, FloatCallback, const char *usage, S32 minArgs, S32 maxArgs, bool toolOnly = false, ConsoleFunctionHeader* header = NULL);
  145. void addCommand(StringTableEntry name, VoidCallback, const char *usage, S32 minArgs, S32 maxArgs, bool toolOnly = false, ConsoleFunctionHeader* header = NULL);
  146. void addCommand(StringTableEntry name, BoolCallback, const char *usage, S32 minArgs, S32 maxArgs, bool toolOnly = false, ConsoleFunctionHeader* header = NULL);
  147. void addScriptCallback(const char *funcName, const char *usage, ConsoleFunctionHeader* header = NULL);
  148. void markGroup(const char* name, const char* usage);
  149. char * lastUsage;
  150. /// Returns true if this namespace represents an engine defined
  151. /// class and is not just a script defined class namespace.
  152. bool isClass() const { return mClassRep && mClassRep->getNameSpace() == this; }
  153. void getEntryList(VectorPtr<Entry *> *);
  154. /// Return the name of this namespace.
  155. StringTableEntry getName() const { return mName; }
  156. /// Return the superordinate namespace to this namespace. Symbols are inherited from
  157. /// this namespace.
  158. Namespace* getParent() const { return mParent; }
  159. /// Return the topmost package in the parent hierarchy of this namespace
  160. /// that still refers to the same namespace. If packages are active and
  161. /// adding to this namespace, then they will be linked in-between the namespace
  162. /// they are adding to and its real parent namespace.
  163. Namespace* getPackageRoot()
  164. {
  165. Namespace* walk = this;
  166. while (walk->mParent && walk->mParent->mName == mName)
  167. walk = walk->mParent;
  168. return walk;
  169. }
  170. /// Return the package in which this namespace is defined.
  171. StringTableEntry getPackage() const { return mPackage; }
  172. /// Increase the count on the reference that this namespace
  173. /// holds to its parent.
  174. /// @note Must not be called on namespaces coming from packages.
  175. void incRefCountToParent()
  176. {
  177. AssertFatal(mPackage == NULL, "Namespace::incRefCountToParent - Must not be called on a namespace coming from a package!");
  178. mRefCountToParent++;
  179. }
  180. /// Decrease the count on the reference that this namespace
  181. /// holds to its parent.
  182. /// @note Must not be called on namespaces coming from packages.
  183. void decRefCountToParent()
  184. {
  185. unlinkClass(NULL);
  186. }
  187. Entry *lookup(StringTableEntry name);
  188. Entry *lookupRecursive(StringTableEntry name);
  189. Entry *createLocalEntry(StringTableEntry name);
  190. void buildHashTable();
  191. void clearEntries();
  192. bool classLinkTo(Namespace *parent);
  193. bool unlinkClass(Namespace *parent);
  194. void getUniqueEntryLists(Namespace *other, VectorPtr<Entry *> *outThisList, VectorPtr<Entry *> *outOtherList);
  195. const char *tabComplete(const char *prevText, S32 baseLen, bool fForward);
  196. static U32 mCacheSequence;
  197. static DataChunker mCacheAllocator;
  198. static DataChunker mAllocator;
  199. static void trashCache();
  200. static Namespace *mNamespaceList;
  201. static Namespace *mGlobalNamespace;
  202. static void init();
  203. static void shutdown();
  204. static Namespace *global();
  205. static Namespace *find(StringTableEntry name, StringTableEntry package = NULL);
  206. static void activatePackage(StringTableEntry name);
  207. static void deactivatePackage(StringTableEntry name);
  208. static void deactivatePackageStack(StringTableEntry name);
  209. static void dumpClasses(bool dumpScript = true, bool dumpEngine = true);
  210. static void dumpFunctions(bool dumpScript = true, bool dumpEngine = true);
  211. static void printNamespaceEntries(Namespace * g, bool dumpScript = true, bool dumpEngine = true);
  212. static void unlinkPackages();
  213. static void relinkPackages();
  214. static bool isPackage(StringTableEntry name);
  215. static U32 getActivePackagesCount();
  216. static StringTableEntry getActivePackage(U32 index);
  217. };
  218. typedef VectorPtr<Namespace::Entry *>::iterator NamespaceEntryListIterator;
  219. class Dictionary
  220. {
  221. public:
  222. struct Entry
  223. {
  224. friend class Dictionary;
  225. enum
  226. {
  227. TypeInternalInt = -3,
  228. TypeInternalFloat = -2,
  229. TypeInternalString = -1,
  230. };
  231. StringTableEntry name;
  232. Entry *nextEntry;
  233. S32 type;
  234. typedef Signal<void()> NotifySignal;
  235. /// The optional notification signal called when
  236. /// a value is assigned to this variable.
  237. NotifySignal *notify;
  238. /// Usage doc string.
  239. const char* mUsage;
  240. /// Whether this is a constant that cannot be assigned to.
  241. bool mIsConstant;
  242. protected:
  243. // NOTE: This is protected to ensure no one outside
  244. // of this structure is messing with it.
  245. #pragma warning( push )
  246. #pragma warning( disable : 4201 ) // warning C4201: nonstandard extension used : nameless struct/union
  247. // An variable is either a real dynamic type or
  248. // its one exposed from C++ using a data pointer.
  249. //
  250. // We use this nameless union and struct setup
  251. // to optimize the memory usage.
  252. union
  253. {
  254. struct
  255. {
  256. char* sval;
  257. U32 ival; // doubles as strlen when type is TypeInternalString
  258. F32 fval;
  259. U32 bufferLen;
  260. };
  261. struct
  262. {
  263. /// The real data pointer.
  264. void* dataPtr;
  265. /// The enum lookup table for enumerated types.
  266. const EnumTable* enumTable;
  267. };
  268. };
  269. #pragma warning( pop ) // C4201
  270. public:
  271. Entry() {
  272. name = NULL;
  273. notify = NULL;
  274. nextEntry = NULL;
  275. mUsage = NULL;
  276. mIsConstant = false;
  277. mNext = NULL;
  278. }
  279. Entry(StringTableEntry name);
  280. ~Entry();
  281. Entry *mNext;
  282. void reset();
  283. inline U32 getIntValue()
  284. {
  285. if (type <= TypeInternalString)
  286. return ival;
  287. else
  288. return dAtoi(Con::getData(type, dataPtr, 0, enumTable));
  289. }
  290. inline F32 getFloatValue()
  291. {
  292. if (type <= TypeInternalString)
  293. return fval;
  294. else
  295. return dAtof(Con::getData(type, dataPtr, 0, enumTable));
  296. }
  297. inline const char *getStringValue()
  298. {
  299. if (type == TypeInternalString)
  300. return sval;
  301. if (type == TypeInternalFloat)
  302. return Con::getData(TypeF32, &fval, 0);
  303. else if (type == TypeInternalInt)
  304. return Con::getData(TypeS32, &ival, 0);
  305. else
  306. return Con::getData(type, dataPtr, 0, enumTable);
  307. }
  308. void setIntValue(U32 val)
  309. {
  310. if (mIsConstant)
  311. {
  312. Con::errorf("Cannot assign value to constant '%s'.", name);
  313. return;
  314. }
  315. if (type <= TypeInternalString)
  316. {
  317. fval = (F32)val;
  318. ival = val;
  319. if (sval != typeValueEmpty)
  320. {
  321. dFree(sval);
  322. sval = typeValueEmpty;
  323. }
  324. type = TypeInternalInt;
  325. }
  326. else
  327. {
  328. const char* dptr = Con::getData(TypeS32, &val, 0);
  329. Con::setData(type, dataPtr, 0, 1, &dptr, enumTable);
  330. }
  331. // Fire off the notification if we have one.
  332. if (notify)
  333. notify->trigger();
  334. }
  335. void setFloatValue(F32 val)
  336. {
  337. if (mIsConstant)
  338. {
  339. Con::errorf("Cannot assign value to constant '%s'.", name);
  340. return;
  341. }
  342. if (type <= TypeInternalString)
  343. {
  344. fval = val;
  345. ival = static_cast<U32>(val);
  346. if (sval != typeValueEmpty)
  347. {
  348. dFree(sval);
  349. sval = typeValueEmpty;
  350. }
  351. type = TypeInternalFloat;
  352. }
  353. else
  354. {
  355. const char* dptr = Con::getData(TypeF32, &val, 0);
  356. Con::setData(type, dataPtr, 0, 1, &dptr, enumTable);
  357. }
  358. // Fire off the notification if we have one.
  359. if (notify)
  360. notify->trigger();
  361. }
  362. void setStringValue(const char* value);
  363. };
  364. struct HashTableData
  365. {
  366. Dictionary* owner;
  367. S32 size;
  368. S32 count;
  369. Entry **data;
  370. FreeListChunker< Entry > mChunker;
  371. HashTableData(Dictionary* owner)
  372. : owner(owner), size(0), count(0), data(NULL) {}
  373. };
  374. HashTableData* hashTable;
  375. HashTableData ownHashTable;
  376. ExprEvalState *exprState;
  377. StringTableEntry scopeName;
  378. Namespace *scopeNamespace;
  379. CodeBlock *code;
  380. U32 ip;
  381. Dictionary();
  382. ~Dictionary();
  383. Entry *lookup(StringTableEntry name);
  384. Entry *add(StringTableEntry name);
  385. void setState(ExprEvalState *state, Dictionary* ref = NULL);
  386. void remove(Entry *);
  387. void reset();
  388. void exportVariables(const char *varString, const char *fileName, bool append);
  389. void exportVariables(const char *varString, Vector<String> *names, Vector<String> *values);
  390. void deleteVariables(const char *varString);
  391. void setVariable(StringTableEntry name, const char *value);
  392. const char *getVariable(StringTableEntry name, bool *valid = NULL);
  393. S32 getIntVariable(StringTableEntry name, bool *valid = NULL);
  394. F32 getFloatVariable(StringTableEntry name, bool *entValid = NULL);
  395. U32 getCount() const
  396. {
  397. return hashTable->count;
  398. }
  399. bool isOwner() const
  400. {
  401. return hashTable->owner;
  402. }
  403. /// @see Con::addVariable
  404. Entry* addVariable(const char *name,
  405. S32 type,
  406. void *dataPtr,
  407. const char* usage);
  408. /// @see Con::removeVariable
  409. bool removeVariable(StringTableEntry name);
  410. /// @see Con::addVariableNotify
  411. void addVariableNotify(const char *name, const Con::NotifyDelegate &callback);
  412. /// @see Con::removeVariableNotify
  413. void removeVariableNotify(const char *name, const Con::NotifyDelegate &callback);
  414. /// Return the best tab completion for prevText, with the length
  415. /// of the pre-tab string in baseLen.
  416. const char *tabComplete(const char *prevText, S32 baseLen, bool);
  417. /// Run integrity checks for debugging.
  418. void validate();
  419. };
  420. struct ConsoleValueFrame
  421. {
  422. ConsoleValue* values;
  423. bool isReference;
  424. ConsoleValueFrame() : values(NULL), isReference(false)
  425. {}
  426. ConsoleValueFrame(ConsoleValue* vals, bool isRef)
  427. {
  428. values = vals;
  429. isReference = isRef;
  430. }
  431. };
  432. class ExprEvalState
  433. {
  434. public:
  435. /// @name Expression Evaluation
  436. /// @{
  437. ///
  438. SimObject *thisObject;
  439. Dictionary::Entry *currentVariable;
  440. Dictionary::Entry *copyVariable;
  441. bool traceOn;
  442. U32 mStackDepth;
  443. bool mShouldReset; ///< Designates if the value stack should be reset
  444. bool mResetLocked; ///< mShouldReset will be set at the end
  445. ExprEvalState();
  446. ~ExprEvalState();
  447. /// @}
  448. /// @name Stack Management
  449. /// @{
  450. /// The stack of callframes. The extra redirection is necessary since Dictionary holds
  451. /// an interior pointer that will become invalid when the object changes address.
  452. Vector< Dictionary* > stack;
  453. S32 getTopOfStack() { return (S32)mStackDepth; }
  454. Vector< ConsoleValueFrame > localStack;
  455. ConsoleValueFrame* currentRegisterArray; // contains array at to top of localStack
  456. ///
  457. Dictionary globalVars;
  458. void setCurVarName(StringTableEntry name);
  459. void setCurVarNameCreate(StringTableEntry name);
  460. S32 getIntVariable();
  461. F64 getFloatVariable();
  462. const char *getStringVariable();
  463. void setIntVariable(S32 val);
  464. void setFloatVariable(F64 val);
  465. void setStringVariable(const char *str);
  466. TORQUE_FORCEINLINE S32 getLocalIntVariable(S32 reg)
  467. {
  468. return currentRegisterArray->values[reg].getInt();
  469. }
  470. TORQUE_FORCEINLINE F64 getLocalFloatVariable(S32 reg)
  471. {
  472. return currentRegisterArray->values[reg].getFloat();
  473. }
  474. TORQUE_FORCEINLINE const char* getLocalStringVariable(S32 reg)
  475. {
  476. return currentRegisterArray->values[reg].getString();
  477. }
  478. TORQUE_FORCEINLINE void setLocalIntVariable(S32 reg, S64 val)
  479. {
  480. currentRegisterArray->values[reg].setInt(val);
  481. }
  482. TORQUE_FORCEINLINE void setLocalFloatVariable(S32 reg, F64 val)
  483. {
  484. currentRegisterArray->values[reg].setFloat(val);
  485. }
  486. TORQUE_FORCEINLINE void setLocalStringVariable(S32 reg, const char* val, S32 len)
  487. {
  488. currentRegisterArray->values[reg].setString(val, len);
  489. }
  490. TORQUE_FORCEINLINE void setLocalStringTableEntryVariable(S32 reg, StringTableEntry val)
  491. {
  492. currentRegisterArray->values[reg].setStringTableEntry(val);
  493. }
  494. void pushFrame(StringTableEntry frameName, Namespace *ns, S32 regCount);
  495. void popFrame();
  496. /// Puts a reference to an existing stack frame
  497. /// on the top of the stack.
  498. void pushFrameRef(S32 stackIndex);
  499. U32 getStackDepth() const
  500. {
  501. return mStackDepth;
  502. }
  503. Dictionary& getCurrentFrame()
  504. {
  505. return *(stack[mStackDepth - 1]);
  506. }
  507. /// @}
  508. /// Run integrity checks for debugging.
  509. void validate();
  510. };
  511. namespace Con
  512. {
  513. /// The current $instantGroup setting.
  514. extern String gInstantGroup;
  515. }
  516. /// @}
  517. #endif