consoleInternal.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  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. /// Return a minimalized prototype string for the function including return type, function name,
  134. /// and arguments.
  135. String getPrototypeSig() const;
  136. };
  137. Entry* mEntryList;
  138. Entry** mHashTable;
  139. U32 mHashSize;
  140. U32 mHashSequence; ///< @note The hash sequence is used by the autodoc console facility
  141. /// as a means of testing reference state.
  142. Namespace();
  143. ~Namespace();
  144. void addFunction(StringTableEntry name, CodeBlock* cb, U32 functionOffset, const char* usage = NULL, U32 lineNumber = 0);
  145. void addCommand(StringTableEntry name, StringCallback, const char *usage, S32 minArgs, S32 maxArgs, bool toolOnly = false, ConsoleFunctionHeader* header = NULL);
  146. void addCommand(StringTableEntry name, IntCallback, const char *usage, S32 minArgs, S32 maxArgs, bool toolOnly = false, ConsoleFunctionHeader* header = NULL);
  147. void addCommand(StringTableEntry name, FloatCallback, const char *usage, S32 minArgs, S32 maxArgs, bool toolOnly = false, ConsoleFunctionHeader* header = NULL);
  148. void addCommand(StringTableEntry name, VoidCallback, const char *usage, S32 minArgs, S32 maxArgs, bool toolOnly = false, ConsoleFunctionHeader* header = NULL);
  149. void addCommand(StringTableEntry name, BoolCallback, const char *usage, S32 minArgs, S32 maxArgs, bool toolOnly = false, ConsoleFunctionHeader* header = NULL);
  150. void addScriptCallback(const char *funcName, const char *usage, ConsoleFunctionHeader* header = NULL);
  151. void markGroup(const char* name, const char* usage);
  152. char * lastUsage;
  153. /// Returns true if this namespace represents an engine defined
  154. /// class and is not just a script defined class namespace.
  155. bool isClass() const { return mClassRep && mClassRep->getNameSpace() == this; }
  156. void getEntryList(VectorPtr<Entry *> *);
  157. /// Return the name of this namespace.
  158. StringTableEntry getName() const { return mName; }
  159. /// Return the superordinate namespace to this namespace. Symbols are inherited from
  160. /// this namespace.
  161. Namespace* getParent() const { return mParent; }
  162. /// Return the topmost package in the parent hierarchy of this namespace
  163. /// that still refers to the same namespace. If packages are active and
  164. /// adding to this namespace, then they will be linked in-between the namespace
  165. /// they are adding to and its real parent namespace.
  166. Namespace* getPackageRoot()
  167. {
  168. Namespace* walk = this;
  169. while (walk->mParent && walk->mParent->mName == mName)
  170. walk = walk->mParent;
  171. return walk;
  172. }
  173. /// Return the package in which this namespace is defined.
  174. StringTableEntry getPackage() const { return mPackage; }
  175. /// Increase the count on the reference that this namespace
  176. /// holds to its parent.
  177. /// @note Must not be called on namespaces coming from packages.
  178. void incRefCountToParent()
  179. {
  180. AssertFatal(mPackage == NULL, "Namespace::incRefCountToParent - Must not be called on a namespace coming from a package!");
  181. mRefCountToParent++;
  182. }
  183. /// Decrease the count on the reference that this namespace
  184. /// holds to its parent.
  185. /// @note Must not be called on namespaces coming from packages.
  186. void decRefCountToParent()
  187. {
  188. unlinkClass(NULL);
  189. }
  190. Entry *lookup(StringTableEntry name);
  191. Entry *lookupRecursive(StringTableEntry name);
  192. Entry *createLocalEntry(StringTableEntry name);
  193. void buildHashTable();
  194. void clearEntries();
  195. bool classLinkTo(Namespace *parent);
  196. bool unlinkClass(Namespace *parent);
  197. void getUniqueEntryLists(Namespace *other, VectorPtr<Entry *> *outThisList, VectorPtr<Entry *> *outOtherList);
  198. const char *tabComplete(const char *prevText, S32 baseLen, bool fForward);
  199. static U32 mCacheSequence;
  200. static DataChunker mCacheAllocator;
  201. static DataChunker mAllocator;
  202. static void trashCache();
  203. static Namespace *mNamespaceList;
  204. static Namespace *mGlobalNamespace;
  205. static void init();
  206. static void shutdown();
  207. static Namespace *global();
  208. static Namespace *find(StringTableEntry name, StringTableEntry package = NULL);
  209. static void activatePackage(StringTableEntry name);
  210. static void deactivatePackage(StringTableEntry name);
  211. static void deactivatePackageStack(StringTableEntry name);
  212. static void dumpClasses(bool dumpScript = true, bool dumpEngine = true);
  213. static void dumpFunctions(bool dumpScript = true, bool dumpEngine = true);
  214. static void printNamespaceEntries(Namespace * g, bool dumpScript = true, bool dumpEngine = true);
  215. static void unlinkPackages();
  216. static void relinkPackages();
  217. static bool isPackage(StringTableEntry name);
  218. static U32 getActivePackagesCount();
  219. static StringTableEntry getActivePackage(U32 index);
  220. };
  221. typedef VectorPtr<Namespace::Entry *>::iterator NamespaceEntryListIterator;
  222. class Dictionary
  223. {
  224. public:
  225. struct Entry
  226. {
  227. friend class Dictionary;
  228. enum
  229. {
  230. TypeInternalInt = -3,
  231. TypeInternalFloat = -2,
  232. TypeInternalString = -1,
  233. };
  234. StringTableEntry name;
  235. Entry *nextEntry;
  236. S32 type;
  237. typedef Signal<void()> NotifySignal;
  238. /// The optional notification signal called when
  239. /// a value is assigned to this variable.
  240. NotifySignal *notify;
  241. /// Usage doc string.
  242. const char* mUsage;
  243. /// Whether this is a constant that cannot be assigned to.
  244. bool mIsConstant;
  245. protected:
  246. // NOTE: This is protected to ensure no one outside
  247. // of this structure is messing with it.
  248. #pragma warning( push )
  249. #pragma warning( disable : 4201 ) // warning C4201: nonstandard extension used : nameless struct/union
  250. // An variable is either a real dynamic type or
  251. // its one exposed from C++ using a data pointer.
  252. //
  253. // We use this nameless union and struct setup
  254. // to optimize the memory usage.
  255. union
  256. {
  257. struct
  258. {
  259. char* sval;
  260. U32 ival; // doubles as strlen when type is TypeInternalString
  261. F32 fval;
  262. U32 bufferLen;
  263. };
  264. struct
  265. {
  266. /// The real data pointer.
  267. void* dataPtr;
  268. /// The enum lookup table for enumerated types.
  269. const EnumTable* enumTable;
  270. };
  271. };
  272. #pragma warning( pop ) // C4201
  273. public:
  274. Entry() {
  275. name = NULL;
  276. type = TypeInternalString;
  277. notify = NULL;
  278. nextEntry = NULL;
  279. mUsage = NULL;
  280. mIsConstant = false;
  281. mNext = NULL;
  282. ival = 0;
  283. fval = 0;
  284. sval = NULL;
  285. bufferLen = 0;
  286. dataPtr = NULL;
  287. enumTable = NULL;
  288. }
  289. Entry(StringTableEntry name);
  290. ~Entry();
  291. Entry *mNext;
  292. void reset();
  293. inline U32 getIntValue()
  294. {
  295. if (type <= TypeInternalString)
  296. return ival;
  297. else
  298. return dAtoi(Con::getData(type, dataPtr, 0, enumTable));
  299. }
  300. inline F32 getFloatValue()
  301. {
  302. if (type <= TypeInternalString)
  303. return fval;
  304. else
  305. return dAtof(Con::getData(type, dataPtr, 0, enumTable));
  306. }
  307. inline const char *getStringValue()
  308. {
  309. if (type == TypeInternalString)
  310. return sval;
  311. if (type == TypeInternalFloat)
  312. return Con::getData(TypeF32, &fval, 0);
  313. else if (type == TypeInternalInt)
  314. return Con::getData(TypeS32, &ival, 0);
  315. else
  316. return Con::getData(type, dataPtr, 0, enumTable);
  317. }
  318. void setIntValue(U32 val)
  319. {
  320. if (mIsConstant)
  321. {
  322. Con::errorf("Cannot assign value to constant '%s'.", name);
  323. return;
  324. }
  325. if (type <= TypeInternalString)
  326. {
  327. fval = (F32)val;
  328. ival = val;
  329. if (sval != NULL)
  330. {
  331. dFree(sval);
  332. sval = NULL;
  333. }
  334. type = TypeInternalInt;
  335. }
  336. else
  337. {
  338. const char* dptr = Con::getData(TypeS32, &val, 0);
  339. Con::setData(type, dataPtr, 0, 1, &dptr, enumTable);
  340. }
  341. // Fire off the notification if we have one.
  342. if (notify)
  343. notify->trigger();
  344. }
  345. void setFloatValue(F32 val)
  346. {
  347. if (mIsConstant)
  348. {
  349. Con::errorf("Cannot assign value to constant '%s'.", name);
  350. return;
  351. }
  352. if (type <= TypeInternalString)
  353. {
  354. fval = val;
  355. ival = static_cast<U32>(val);
  356. if (sval != NULL)
  357. {
  358. dFree(sval);
  359. sval = NULL;
  360. }
  361. type = TypeInternalFloat;
  362. }
  363. else
  364. {
  365. const char* dptr = Con::getData(TypeF32, &val, 0);
  366. Con::setData(type, dataPtr, 0, 1, &dptr, enumTable);
  367. }
  368. // Fire off the notification if we have one.
  369. if (notify)
  370. notify->trigger();
  371. }
  372. void setStringValue(const char* value);
  373. };
  374. struct HashTableData
  375. {
  376. Dictionary* owner;
  377. S32 size;
  378. S32 count;
  379. Entry **data;
  380. FreeListChunker< Entry > mChunker;
  381. HashTableData(Dictionary* owner)
  382. : owner(owner), size(0), count(0), data(NULL) {}
  383. };
  384. HashTableData* hashTable;
  385. HashTableData ownHashTable;
  386. ExprEvalState *exprState;
  387. StringTableEntry scopeName;
  388. Namespace *scopeNamespace;
  389. CodeBlock *code;
  390. U32 ip;
  391. Dictionary();
  392. ~Dictionary();
  393. Entry *lookup(StringTableEntry name);
  394. Entry *add(StringTableEntry name);
  395. void setState(ExprEvalState *state, Dictionary* ref = NULL);
  396. void remove(Entry *);
  397. void reset();
  398. void exportVariables(const char *varString, const char *fileName, bool append);
  399. void exportVariables(const char *varString, Vector<String> *names, Vector<String> *values);
  400. void deleteVariables(const char *varString);
  401. void setVariable(StringTableEntry name, const char *value);
  402. const char *getVariable(StringTableEntry name, bool *valid = NULL);
  403. S32 getIntVariable(StringTableEntry name, bool *valid = NULL);
  404. F32 getFloatVariable(StringTableEntry name, bool *entValid = NULL);
  405. U32 getCount() const
  406. {
  407. return hashTable->count;
  408. }
  409. bool isOwner() const
  410. {
  411. return hashTable->owner;
  412. }
  413. /// @see Con::addVariable
  414. Entry* addVariable(const char *name,
  415. S32 type,
  416. void *dataPtr,
  417. const char* usage);
  418. /// @see Con::removeVariable
  419. bool removeVariable(StringTableEntry name);
  420. /// @see Con::addVariableNotify
  421. void addVariableNotify(const char *name, const Con::NotifyDelegate &callback);
  422. /// @see Con::removeVariableNotify
  423. void removeVariableNotify(const char *name, const Con::NotifyDelegate &callback);
  424. /// Return the best tab completion for prevText, with the length
  425. /// of the pre-tab string in baseLen.
  426. const char *tabComplete(const char *prevText, S32 baseLen, bool);
  427. /// Run integrity checks for debugging.
  428. void validate();
  429. };
  430. struct ConsoleValueFrame
  431. {
  432. ConsoleValue* values;
  433. bool isReference;
  434. ConsoleValueFrame() : values(NULL), isReference(false)
  435. {}
  436. ConsoleValueFrame(ConsoleValue* vals, bool isRef)
  437. {
  438. values = vals;
  439. isReference = isRef;
  440. }
  441. };
  442. class ExprEvalState
  443. {
  444. public:
  445. /// @name Expression Evaluation
  446. /// @{
  447. ///
  448. SimObject *thisObject;
  449. Dictionary::Entry *currentVariable;
  450. Dictionary::Entry *copyVariable;
  451. bool traceOn;
  452. U32 mStackDepth;
  453. bool mShouldReset; ///< Designates if the value stack should be reset
  454. bool mResetLocked; ///< mShouldReset will be set at the end
  455. ExprEvalState();
  456. ~ExprEvalState();
  457. /// @}
  458. /// @name Stack Management
  459. /// @{
  460. /// The stack of callframes. The extra redirection is necessary since Dictionary holds
  461. /// an interior pointer that will become invalid when the object changes address.
  462. Vector< Dictionary* > stack;
  463. S32 getTopOfStack() { return (S32)mStackDepth; }
  464. Vector< ConsoleValueFrame > localStack;
  465. ConsoleValueFrame* currentRegisterArray; // contains array at to top of localStack
  466. ///
  467. Dictionary globalVars;
  468. void setCurVarName(StringTableEntry name);
  469. void setCurVarNameCreate(StringTableEntry name);
  470. S32 getIntVariable();
  471. F64 getFloatVariable();
  472. const char *getStringVariable();
  473. void setIntVariable(S32 val);
  474. void setFloatVariable(F64 val);
  475. void setStringVariable(const char *str);
  476. TORQUE_FORCEINLINE S32 getLocalIntVariable(S32 reg)
  477. {
  478. return currentRegisterArray->values[reg].getInt();
  479. }
  480. TORQUE_FORCEINLINE F64 getLocalFloatVariable(S32 reg)
  481. {
  482. return currentRegisterArray->values[reg].getFloat();
  483. }
  484. TORQUE_FORCEINLINE const char* getLocalStringVariable(S32 reg)
  485. {
  486. return currentRegisterArray->values[reg].getString();
  487. }
  488. TORQUE_FORCEINLINE void setLocalIntVariable(S32 reg, S64 val)
  489. {
  490. currentRegisterArray->values[reg].setInt(val);
  491. }
  492. TORQUE_FORCEINLINE void setLocalFloatVariable(S32 reg, F64 val)
  493. {
  494. currentRegisterArray->values[reg].setFloat(val);
  495. }
  496. TORQUE_FORCEINLINE void setLocalStringVariable(S32 reg, const char* val, S32 len)
  497. {
  498. currentRegisterArray->values[reg].setString(val, len);
  499. }
  500. TORQUE_FORCEINLINE void setLocalStringTableEntryVariable(S32 reg, StringTableEntry val)
  501. {
  502. currentRegisterArray->values[reg].setStringTableEntry(val);
  503. }
  504. TORQUE_FORCEINLINE void moveConsoleValue(S32 reg, ConsoleValue val)
  505. {
  506. currentRegisterArray->values[reg] = std::move(val);
  507. }
  508. void pushFrame(StringTableEntry frameName, Namespace *ns, S32 regCount);
  509. void popFrame();
  510. /// Puts a reference to an existing stack frame
  511. /// on the top of the stack.
  512. void pushFrameRef(S32 stackIndex);
  513. void pushDebugFrame(S32 stackIndex);
  514. U32 getStackDepth() const
  515. {
  516. return mStackDepth;
  517. }
  518. Dictionary& getCurrentFrame()
  519. {
  520. return *(stack[mStackDepth - 1]);
  521. }
  522. Dictionary& getFrameAt(S32 depth)
  523. {
  524. return *(stack[depth]);
  525. }
  526. /// @}
  527. /// Run integrity checks for debugging.
  528. void validate();
  529. };
  530. namespace Con
  531. {
  532. /// The current $instantGroup setting.
  533. extern String gInstantGroup;
  534. }
  535. /// @}
  536. #endif