compiler.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. //-----------------------------------------------------------------------------
  2. // Copyright (c) 2012 GarageGames, LLC
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to
  6. // deal in the Software without restriction, including without limitation the
  7. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  8. // sell copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
  19. // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
  20. // IN THE SOFTWARE.
  21. //-----------------------------------------------------------------------------
  22. #include "platform/platform.h"
  23. #include "console/console.h"
  24. #include "console/telnetDebugger.h"
  25. #include "console/ast.h"
  26. #include "core/tAlgorithm.h"
  27. #include "core/strings/findMatch.h"
  28. #include "console/consoleInternal.h"
  29. #include "core/stream/fileStream.h"
  30. #include "console/compiler.h"
  31. #include "console/simBase.h"
  32. extern FuncVars gEvalFuncVars;
  33. extern FuncVars gGlobalScopeFuncVars;
  34. extern FuncVars *gFuncVars;
  35. namespace Con
  36. {
  37. extern bool scriptWarningsAsAsserts;
  38. };
  39. namespace Compiler
  40. {
  41. F64 consoleStringToNumber(const char *str, StringTableEntry file, U32 line)
  42. {
  43. F64 val = dAtof(str);
  44. if (val != 0)
  45. return val;
  46. else if (!dStricmp(str, "true"))
  47. return 1;
  48. else if (!dStricmp(str, "false"))
  49. return 0;
  50. else if (file)
  51. {
  52. Con::warnf(ConsoleLogEntry::General, "%s (%d): string always evaluates to 0.", file, line);
  53. return 0;
  54. }
  55. return 0;
  56. }
  57. //------------------------------------------------------------
  58. CompilerStringTable *gCurrentStringTable, gGlobalStringTable, gFunctionStringTable;
  59. CompilerFloatTable *gCurrentFloatTable, gGlobalFloatTable, gFunctionFloatTable;
  60. DataChunker gConsoleAllocator;
  61. CompilerIdentTable gIdentTable;
  62. CompilerLocalVariableToRegisterMappingTable gFunctionVariableMappingTable;
  63. //------------------------------------------------------------
  64. void evalSTEtoCode(StringTableEntry ste, U32 ip, U32 *ptr)
  65. {
  66. #if defined(TORQUE_CPU_X64) || defined(TORQUE_CPU_ARM64)
  67. *(U64*)(ptr) = (U64)ste;
  68. #else
  69. *ptr = (U32)ste;
  70. #endif
  71. }
  72. void compileSTEtoCode(StringTableEntry ste, U32 ip, U32 *ptr)
  73. {
  74. if (ste)
  75. getIdentTable().add(ste, ip);
  76. *ptr = 0;
  77. *(ptr + 1) = 0;
  78. }
  79. void(*STEtoCode)(StringTableEntry ste, U32 ip, U32 *ptr) = evalSTEtoCode;
  80. //------------------------------------------------------------
  81. bool gSyntaxError = false;
  82. bool gIsEvalCompile = false;
  83. //------------------------------------------------------------
  84. CompilerStringTable *getCurrentStringTable() { return gCurrentStringTable; }
  85. CompilerStringTable &getGlobalStringTable() { return gGlobalStringTable; }
  86. CompilerStringTable &getFunctionStringTable() { return gFunctionStringTable; }
  87. CompilerLocalVariableToRegisterMappingTable& getFunctionVariableMappingTable() { return gFunctionVariableMappingTable; }
  88. void setCurrentStringTable(CompilerStringTable* cst) { gCurrentStringTable = cst; }
  89. CompilerFloatTable *getCurrentFloatTable() { return gCurrentFloatTable; }
  90. CompilerFloatTable &getGlobalFloatTable() { return gGlobalFloatTable; }
  91. CompilerFloatTable &getFunctionFloatTable() { return gFunctionFloatTable; }
  92. void setCurrentFloatTable(CompilerFloatTable* cst) { gCurrentFloatTable = cst; }
  93. CompilerIdentTable &getIdentTable() { return gIdentTable; }
  94. void precompileIdent(StringTableEntry ident)
  95. {
  96. if (ident)
  97. gGlobalStringTable.add(ident);
  98. }
  99. void resetTables()
  100. {
  101. setCurrentStringTable(&gGlobalStringTable);
  102. setCurrentFloatTable(&gGlobalFloatTable);
  103. getGlobalFloatTable().reset();
  104. getGlobalStringTable().reset();
  105. getFunctionFloatTable().reset();
  106. getFunctionStringTable().reset();
  107. getIdentTable().reset();
  108. getFunctionVariableMappingTable().reset();
  109. gGlobalScopeFuncVars.clear();
  110. gFuncVars = gIsEvalCompile ? &gEvalFuncVars : &gGlobalScopeFuncVars;
  111. }
  112. void *consoleAlloc(U32 size) { return gConsoleAllocator.alloc(size); }
  113. void consoleAllocReset() { gConsoleAllocator.freeBlocks(); }
  114. void scriptErrorHandler(const char* str)
  115. {
  116. if (Con::scriptWarningsAsAsserts)
  117. {
  118. AssertISV(false, str);
  119. }
  120. else
  121. {
  122. Con::warnf(ConsoleLogEntry::Type::Script, "%s", str);
  123. }
  124. }
  125. }
  126. //-------------------------------------------------------------------------
  127. using namespace Compiler;
  128. S32 FuncVars::assign(StringTableEntry var, TypeReq currentType, S32 lineNumber, bool isConstant)
  129. {
  130. std::unordered_map<StringTableEntry, Var>::iterator found = vars.find(var);
  131. if (found != vars.end())
  132. {
  133. if (found->second.isConstant)
  134. {
  135. const char* str = avar("Script Warning: Reassigning variable %s when it is a constant. File: %s Line : %d", var, CodeBlock::smCurrentParser->getCurrentFile(), lineNumber);
  136. scriptErrorHandler(str);
  137. }
  138. return found->second.reg;
  139. }
  140. S32 id = counter++;
  141. vars[var] = { id, currentType, var, isConstant };
  142. variableNameMap[id] = var;
  143. return id;
  144. }
  145. S32 FuncVars::lookup(StringTableEntry var, S32 lineNumber)
  146. {
  147. std::unordered_map<StringTableEntry, Var>::iterator found = vars.find(var);
  148. if (found == vars.end())
  149. {
  150. const char* str = avar("Script Warning: Variable %s referenced before used when compiling script. File: %s Line: %d", var, CodeBlock::smCurrentParser->getCurrentFile(), lineNumber);
  151. scriptErrorHandler(str);
  152. return assign(var, TypeReqString, lineNumber, false);
  153. }
  154. return found->second.reg;
  155. }
  156. TypeReq FuncVars::lookupType(StringTableEntry var, S32 lineNumber)
  157. {
  158. std::unordered_map<StringTableEntry, Var>::iterator found = vars.find(var);
  159. if (found == vars.end())
  160. {
  161. const char* str = avar("Script Warning: Variable %s referenced before used when compiling script. File: %s Line: %d", var, CodeBlock::smCurrentParser->getCurrentFile(), lineNumber);
  162. scriptErrorHandler(str);
  163. assign(var, TypeReqString, lineNumber, false);
  164. return vars.find(var)->second.currentType;
  165. }
  166. return found->second.currentType;
  167. }
  168. void FuncVars::clear()
  169. {
  170. vars.clear();
  171. variableNameMap.clear();
  172. counter = 0;
  173. }
  174. //-------------------------------------------------------------------------
  175. U32 CompilerStringTable::add(const char *str, bool caseSens, bool tag)
  176. {
  177. // Is it already in?
  178. Entry **walk;
  179. for (walk = &list; *walk; walk = &((*walk)->next))
  180. {
  181. if ((*walk)->tag != tag)
  182. continue;
  183. if (caseSens)
  184. {
  185. if (!String::compare((*walk)->string, str))
  186. return (*walk)->start;
  187. }
  188. else
  189. {
  190. if (!dStricmp((*walk)->string, str))
  191. return (*walk)->start;
  192. }
  193. }
  194. // Write it out.
  195. Entry *newStr = (Entry *)consoleAlloc(sizeof(Entry));
  196. *walk = newStr;
  197. newStr->next = NULL;
  198. newStr->start = totalLen;
  199. U32 len = dStrlen(str) + 1;
  200. if (tag && len < 7) // alloc space for the numeric tag 1 for tag, 5 for # and 1 for nul
  201. len = 7;
  202. totalLen += len;
  203. newStr->string = (char *)consoleAlloc(len);
  204. newStr->len = len;
  205. newStr->tag = tag;
  206. dStrcpy(newStr->string, str, len);
  207. // Put into the hash table.
  208. hashTable[str] = newStr;
  209. return newStr->start;
  210. }
  211. U32 CompilerStringTable::addIntString(U32 value)
  212. {
  213. dSprintf(buf, sizeof(buf), "%d", value);
  214. return add(buf);
  215. }
  216. U32 CompilerStringTable::addFloatString(F64 value)
  217. {
  218. dSprintf(buf, sizeof(buf), "%g", value);
  219. return add(buf);
  220. }
  221. void CompilerStringTable::reset()
  222. {
  223. list = NULL;
  224. totalLen = 0;
  225. }
  226. char *CompilerStringTable::build()
  227. {
  228. char *ret = new char[totalLen];
  229. dMemset(ret, 0, totalLen);
  230. for (Entry *walk = list; walk; walk = walk->next)
  231. dStrcpy(ret + walk->start, walk->string, totalLen - walk->start);
  232. return ret;
  233. }
  234. void CompilerStringTable::write(Stream &st)
  235. {
  236. st.write(totalLen);
  237. for (Entry *walk = list; walk; walk = walk->next)
  238. st.write(walk->len, walk->string);
  239. }
  240. //------------------------------------------------------------
  241. void CompilerLocalVariableToRegisterMappingTable::add(StringTableEntry functionName, StringTableEntry namespaceName, StringTableEntry varName)
  242. {
  243. StringTableEntry funcLookupTableName = StringTable->insert(avar("%s::%s", namespaceName, functionName));
  244. localVarToRegister[funcLookupTableName].varList.push_back(varName);;
  245. }
  246. S32 CompilerLocalVariableToRegisterMappingTable::lookup(StringTableEntry namespaceName, StringTableEntry functionName, StringTableEntry varName)
  247. {
  248. StringTableEntry funcLookupTableName = StringTable->insert(avar("%s::%s", namespaceName, functionName));
  249. auto functionPosition = localVarToRegister.find(funcLookupTableName);
  250. if (functionPosition != localVarToRegister.end())
  251. {
  252. const auto& table = localVarToRegister[funcLookupTableName].varList;
  253. auto varPosition = std::find(table.begin(), table.end(), varName);
  254. if (varPosition != table.end())
  255. {
  256. return std::distance(table.begin(), varPosition);
  257. }
  258. }
  259. Con::errorf("Unable to find local variable %s in function name %s", varName, funcLookupTableName);
  260. return -1;
  261. }
  262. CompilerLocalVariableToRegisterMappingTable CompilerLocalVariableToRegisterMappingTable::copy()
  263. {
  264. // Trivilly copyable as its all plain old data and using STL containers... (We want a deep copy though!)
  265. CompilerLocalVariableToRegisterMappingTable table;
  266. table.localVarToRegister = localVarToRegister;
  267. return table;
  268. }
  269. void CompilerLocalVariableToRegisterMappingTable::reset()
  270. {
  271. localVarToRegister.clear();
  272. }
  273. void CompilerLocalVariableToRegisterMappingTable::write(Stream& stream)
  274. {
  275. stream.write((U32)localVarToRegister.size());
  276. for (const auto& pair : localVarToRegister)
  277. {
  278. StringTableEntry functionName = pair.first;
  279. stream.writeString(functionName);
  280. const auto& localVariableTableForFunction = localVarToRegister[functionName].varList;
  281. stream.write((U32)localVariableTableForFunction.size());
  282. for (const StringTableEntry& varName : localVariableTableForFunction)
  283. {
  284. stream.writeString(varName);
  285. }
  286. }
  287. }
  288. //------------------------------------------------------------
  289. U32 CompilerFloatTable::add(F64 value)
  290. {
  291. Entry **walk;
  292. U32 i = 0;
  293. for (walk = &list; *walk; walk = &((*walk)->next), i++)
  294. if (value == (*walk)->val)
  295. return i;
  296. Entry *newFloat = (Entry *)consoleAlloc(sizeof(Entry));
  297. newFloat->val = value;
  298. newFloat->next = NULL;
  299. count++;
  300. *walk = newFloat;
  301. return count - 1;
  302. }
  303. void CompilerFloatTable::reset()
  304. {
  305. list = NULL;
  306. count = 0;
  307. }
  308. F64 *CompilerFloatTable::build()
  309. {
  310. F64 *ret = new F64[count];
  311. U32 i = 0;
  312. for (Entry *walk = list; walk; walk = walk->next, i++)
  313. ret[i] = walk->val;
  314. return ret;
  315. }
  316. void CompilerFloatTable::write(Stream &st)
  317. {
  318. st.write(count);
  319. for (Entry *walk = list; walk; walk = walk->next)
  320. st.write(walk->val);
  321. }
  322. //------------------------------------------------------------
  323. void CompilerIdentTable::reset()
  324. {
  325. list = NULL;
  326. }
  327. void CompilerIdentTable::add(StringTableEntry ste, U32 ip)
  328. {
  329. U32 index = gGlobalStringTable.add(ste, false);
  330. Entry *newEntry = (Entry *)consoleAlloc(sizeof(Entry));
  331. newEntry->offset = index;
  332. newEntry->ip = ip;
  333. for (Entry *walk = list; walk; walk = walk->next)
  334. {
  335. if (walk->offset == index)
  336. {
  337. newEntry->nextIdent = walk->nextIdent;
  338. walk->nextIdent = newEntry;
  339. return;
  340. }
  341. }
  342. newEntry->next = list;
  343. list = newEntry;
  344. newEntry->nextIdent = NULL;
  345. }
  346. void CompilerIdentTable::write(Stream &st)
  347. {
  348. U32 count = 0;
  349. Entry * walk;
  350. for (walk = list; walk; walk = walk->next)
  351. count++;
  352. st.write(count);
  353. for (walk = list; walk; walk = walk->next)
  354. {
  355. U32 ec = 0;
  356. Entry * el;
  357. for (el = walk; el; el = el->nextIdent)
  358. ec++;
  359. st.write(walk->offset);
  360. st.write(ec);
  361. for (el = walk; el; el = el->nextIdent)
  362. st.write(el->ip);
  363. }
  364. }
  365. //-------------------------------------------------------------------------
  366. U8 *CodeStream::allocCode(U32 sz)
  367. {
  368. U8 *ptr = NULL;
  369. if (mCodeHead)
  370. {
  371. const U32 bytesLeft = BlockSize - mCodeHead->size;
  372. if (bytesLeft > sz)
  373. {
  374. ptr = mCodeHead->data + mCodeHead->size;
  375. mCodeHead->size += sz;
  376. return ptr;
  377. }
  378. }
  379. CodeData *data = new CodeData;
  380. data->data = (U8*)dMalloc(BlockSize);
  381. data->size = sz;
  382. data->next = NULL;
  383. if (mCodeHead)
  384. mCodeHead->next = data;
  385. mCodeHead = data;
  386. if (mCode == NULL)
  387. mCode = data;
  388. return data->data;
  389. }
  390. //-------------------------------------------------------------------------
  391. void CodeStream::fixLoop(U32 loopBlockStart, U32 breakPoint, U32 continuePoint)
  392. {
  393. AssertFatal(mFixStack.size() > 0, "Fix stack mismatch");
  394. U32 fixStart = mFixStack[mFixStack.size() - 1];
  395. for (U32 i = fixStart; i<mFixList.size(); i += 2)
  396. {
  397. FixType type = (FixType)mFixList[i + 1];
  398. U32 fixedIp = 0;
  399. bool valid = true;
  400. switch (type)
  401. {
  402. case FIXTYPE_LOOPBLOCKSTART:
  403. fixedIp = loopBlockStart;
  404. break;
  405. case FIXTYPE_BREAK:
  406. fixedIp = breakPoint;
  407. break;
  408. case FIXTYPE_CONTINUE:
  409. fixedIp = continuePoint;
  410. break;
  411. default:
  412. //Con::warnf("Address %u fixed as %u", mFixList[i], mFixList[i+1]);
  413. valid = false;
  414. break;
  415. }
  416. if (valid)
  417. {
  418. patch(mFixList[i], fixedIp);
  419. }
  420. }
  421. }
  422. //-------------------------------------------------------------------------
  423. void CodeStream::emitCodeStream(U32 *size, U32 **stream, U32 **lineBreaks)
  424. {
  425. // Alloc stream
  426. U32 numLineBreaks = getNumLineBreaks();
  427. *stream = new U32[mCodePos + (numLineBreaks * 2)];
  428. dMemset(*stream, '\0', mCodePos + (numLineBreaks * 2));
  429. *size = mCodePos;
  430. // Dump chunks & line breaks
  431. U32 outBytes = mCodePos * sizeof(U32);
  432. U8 *outPtr = *((U8**)stream);
  433. for (CodeData *itr = mCode; itr != NULL; itr = itr->next)
  434. {
  435. U32 bytesToCopy = itr->size > outBytes ? outBytes : itr->size;
  436. dMemcpy(outPtr, itr->data, bytesToCopy);
  437. outPtr += bytesToCopy;
  438. outBytes -= bytesToCopy;
  439. }
  440. *lineBreaks = *stream + mCodePos;
  441. dMemcpy(*lineBreaks, mBreakLines.address(), sizeof(U32) * mBreakLines.size());
  442. // Apply patches on top
  443. for (U32 i = 0; i<mPatchList.size(); i++)
  444. {
  445. PatchEntry &e = mPatchList[i];
  446. (*stream)[e.addr] = e.value;
  447. }
  448. }
  449. //-------------------------------------------------------------------------
  450. void CodeStream::reset()
  451. {
  452. mCodePos = 0;
  453. mFixStack.clear();
  454. mFixLoopStack.clear();
  455. mFixList.clear();
  456. mBreakLines.clear();
  457. // Pop down to one code block
  458. CodeData *itr = mCode ? mCode->next : NULL;
  459. while (itr != NULL)
  460. {
  461. CodeData *next = itr->next;
  462. dFree(itr->data);
  463. delete(itr);
  464. itr = next;
  465. }
  466. if (mCode)
  467. {
  468. mCode->size = 0;
  469. mCode->next = NULL;
  470. mCodeHead = mCode;
  471. }
  472. }