compiler.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525
  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. namespace Compiler
  34. {
  35. F64 consoleStringToNumber(const char *str, StringTableEntry file, U32 line)
  36. {
  37. F64 val = dAtof(str);
  38. if (val != 0)
  39. return val;
  40. else if (!dStricmp(str, "true"))
  41. return 1;
  42. else if (!dStricmp(str, "false"))
  43. return 0;
  44. else if (file)
  45. {
  46. Con::warnf(ConsoleLogEntry::General, "%s (%d): string always evaluates to 0.", file, line);
  47. return 0;
  48. }
  49. return 0;
  50. }
  51. //------------------------------------------------------------
  52. CompilerStringTable *gCurrentStringTable, gGlobalStringTable, gFunctionStringTable;
  53. CompilerFloatTable *gCurrentFloatTable, gGlobalFloatTable, gFunctionFloatTable;
  54. DataChunker gConsoleAllocator;
  55. CompilerIdentTable gIdentTable;
  56. CompilerLocalVariableToRegisterMappingTable gFunctionVariableMappingTable;
  57. //------------------------------------------------------------
  58. void evalSTEtoCode(StringTableEntry ste, U32 ip, U32 *ptr)
  59. {
  60. #if defined(TORQUE_CPU_X64) || defined(TORQUE_CPU_ARM64)
  61. *(U64*)(ptr) = (U64)ste;
  62. #else
  63. *ptr = (U32)ste;
  64. #endif
  65. }
  66. void compileSTEtoCode(StringTableEntry ste, U32 ip, U32 *ptr)
  67. {
  68. if (ste)
  69. getIdentTable().add(ste, ip);
  70. *ptr = 0;
  71. *(ptr + 1) = 0;
  72. }
  73. void(*STEtoCode)(StringTableEntry ste, U32 ip, U32 *ptr) = evalSTEtoCode;
  74. //------------------------------------------------------------
  75. bool gSyntaxError = false;
  76. bool gIsEvalCompile = false;
  77. //------------------------------------------------------------
  78. CompilerStringTable *getCurrentStringTable() { return gCurrentStringTable; }
  79. CompilerStringTable &getGlobalStringTable() { return gGlobalStringTable; }
  80. CompilerStringTable &getFunctionStringTable() { return gFunctionStringTable; }
  81. CompilerLocalVariableToRegisterMappingTable& getFunctionVariableMappingTable() { return gFunctionVariableMappingTable; }
  82. void setCurrentStringTable(CompilerStringTable* cst) { gCurrentStringTable = cst; }
  83. CompilerFloatTable *getCurrentFloatTable() { return gCurrentFloatTable; }
  84. CompilerFloatTable &getGlobalFloatTable() { return gGlobalFloatTable; }
  85. CompilerFloatTable &getFunctionFloatTable() { return gFunctionFloatTable; }
  86. void setCurrentFloatTable(CompilerFloatTable* cst) { gCurrentFloatTable = cst; }
  87. CompilerIdentTable &getIdentTable() { return gIdentTable; }
  88. void precompileIdent(StringTableEntry ident)
  89. {
  90. if (ident)
  91. gGlobalStringTable.add(ident);
  92. }
  93. void resetTables()
  94. {
  95. setCurrentStringTable(&gGlobalStringTable);
  96. setCurrentFloatTable(&gGlobalFloatTable);
  97. getGlobalFloatTable().reset();
  98. getGlobalStringTable().reset();
  99. getFunctionFloatTable().reset();
  100. getFunctionStringTable().reset();
  101. getIdentTable().reset();
  102. getFunctionVariableMappingTable().reset();
  103. gEvalFuncVars.clear();
  104. }
  105. void *consoleAlloc(U32 size) { return gConsoleAllocator.alloc(size); }
  106. void consoleAllocReset() { gConsoleAllocator.freeBlocks(); }
  107. }
  108. //-------------------------------------------------------------------------
  109. using namespace Compiler;
  110. S32 FuncVars::assign(StringTableEntry var, TypeReq currentType, S32 lineNumber, bool isConstant)
  111. {
  112. std::unordered_map<StringTableEntry, Var>::iterator found = vars.find(var);
  113. if (found != vars.end())
  114. {
  115. AssertISV(!found->second.isConstant, avar("Reassigning variable %s when it is a constant. File: %s Line : %d", var, CodeBlock::smCurrentParser->getCurrentFile(), lineNumber));
  116. return found->second.reg;
  117. }
  118. S32 id = counter++;
  119. vars[var] = { id, currentType, var, isConstant };
  120. variableNameMap[id] = var;
  121. return id;
  122. }
  123. S32 FuncVars::lookup(StringTableEntry var, S32 lineNumber)
  124. {
  125. std::unordered_map<StringTableEntry, Var>::iterator found = vars.find(var);
  126. AssertISV(found != vars.end(), avar("Variable %s referenced before used when compiling script. File: %s Line: %d", var, CodeBlock::smCurrentParser->getCurrentFile(), lineNumber));
  127. return found->second.reg;
  128. }
  129. TypeReq FuncVars::lookupType(StringTableEntry var, S32 lineNumber)
  130. {
  131. std::unordered_map<StringTableEntry, Var>::iterator found = vars.find(var);
  132. AssertISV(found != vars.end(), avar("Variable %s referenced before used when compiling script. File: %s Line: %d", var, CodeBlock::smCurrentParser->getCurrentFile(), lineNumber));
  133. return found->second.currentType;
  134. }
  135. void FuncVars::clear()
  136. {
  137. vars.clear();
  138. variableNameMap.clear();
  139. counter = 0;
  140. }
  141. //-------------------------------------------------------------------------
  142. U32 CompilerStringTable::add(const char *str, bool caseSens, bool tag)
  143. {
  144. // Is it already in?
  145. Entry **walk;
  146. for (walk = &list; *walk; walk = &((*walk)->next))
  147. {
  148. if ((*walk)->tag != tag)
  149. continue;
  150. if (caseSens)
  151. {
  152. if (!String::compare((*walk)->string, str))
  153. return (*walk)->start;
  154. }
  155. else
  156. {
  157. if (!dStricmp((*walk)->string, str))
  158. return (*walk)->start;
  159. }
  160. }
  161. // Write it out.
  162. Entry *newStr = (Entry *)consoleAlloc(sizeof(Entry));
  163. *walk = newStr;
  164. newStr->next = NULL;
  165. newStr->start = totalLen;
  166. U32 len = dStrlen(str) + 1;
  167. if (tag && len < 7) // alloc space for the numeric tag 1 for tag, 5 for # and 1 for nul
  168. len = 7;
  169. totalLen += len;
  170. newStr->string = (char *)consoleAlloc(len);
  171. newStr->len = len;
  172. newStr->tag = tag;
  173. dStrcpy(newStr->string, str, len);
  174. // Put into the hash table.
  175. hashTable[str] = newStr;
  176. return newStr->start;
  177. }
  178. U32 CompilerStringTable::addIntString(U32 value)
  179. {
  180. dSprintf(buf, sizeof(buf), "%d", value);
  181. return add(buf);
  182. }
  183. U32 CompilerStringTable::addFloatString(F64 value)
  184. {
  185. dSprintf(buf, sizeof(buf), "%g", value);
  186. return add(buf);
  187. }
  188. void CompilerStringTable::reset()
  189. {
  190. list = NULL;
  191. totalLen = 0;
  192. }
  193. char *CompilerStringTable::build()
  194. {
  195. char *ret = new char[totalLen];
  196. dMemset(ret, 0, totalLen);
  197. for (Entry *walk = list; walk; walk = walk->next)
  198. dStrcpy(ret + walk->start, walk->string, totalLen - walk->start);
  199. return ret;
  200. }
  201. void CompilerStringTable::write(Stream &st)
  202. {
  203. st.write(totalLen);
  204. for (Entry *walk = list; walk; walk = walk->next)
  205. st.write(walk->len, walk->string);
  206. }
  207. //------------------------------------------------------------
  208. void CompilerLocalVariableToRegisterMappingTable::add(StringTableEntry functionName, StringTableEntry namespaceName, StringTableEntry varName)
  209. {
  210. StringTableEntry funcLookupTableName = StringTable->insert(avar("%s::%s", namespaceName, functionName));
  211. localVarToRegister[funcLookupTableName].varList.push_back(varName);;
  212. }
  213. S32 CompilerLocalVariableToRegisterMappingTable::lookup(StringTableEntry namespaceName, StringTableEntry functionName, StringTableEntry varName)
  214. {
  215. StringTableEntry funcLookupTableName = StringTable->insert(avar("%s::%s", namespaceName, functionName));
  216. auto functionPosition = localVarToRegister.find(funcLookupTableName);
  217. if (functionPosition != localVarToRegister.end())
  218. {
  219. const auto& table = localVarToRegister[funcLookupTableName].varList;
  220. auto varPosition = std::find(table.begin(), table.end(), varName);
  221. if (varPosition != table.end())
  222. {
  223. return std::distance(table.begin(), varPosition);
  224. }
  225. }
  226. Con::errorf("Unable to find local variable %s in function name %s", varName, funcLookupTableName);
  227. return -1;
  228. }
  229. CompilerLocalVariableToRegisterMappingTable CompilerLocalVariableToRegisterMappingTable::copy()
  230. {
  231. // Trivilly copyable as its all plain old data and using STL containers... (We want a deep copy though!)
  232. CompilerLocalVariableToRegisterMappingTable table;
  233. table.localVarToRegister = localVarToRegister;
  234. return table;
  235. }
  236. void CompilerLocalVariableToRegisterMappingTable::reset()
  237. {
  238. localVarToRegister.clear();
  239. }
  240. void CompilerLocalVariableToRegisterMappingTable::write(Stream& stream)
  241. {
  242. stream.write((U32)localVarToRegister.size());
  243. for (const auto& pair : localVarToRegister)
  244. {
  245. StringTableEntry functionName = pair.first;
  246. stream.writeString(functionName);
  247. const auto& localVariableTableForFunction = localVarToRegister[functionName].varList;
  248. stream.write((U32)localVariableTableForFunction.size());
  249. for (const StringTableEntry& varName : localVariableTableForFunction)
  250. {
  251. stream.writeString(varName);
  252. }
  253. }
  254. }
  255. //------------------------------------------------------------
  256. U32 CompilerFloatTable::add(F64 value)
  257. {
  258. Entry **walk;
  259. U32 i = 0;
  260. for (walk = &list; *walk; walk = &((*walk)->next), i++)
  261. if (value == (*walk)->val)
  262. return i;
  263. Entry *newFloat = (Entry *)consoleAlloc(sizeof(Entry));
  264. newFloat->val = value;
  265. newFloat->next = NULL;
  266. count++;
  267. *walk = newFloat;
  268. return count - 1;
  269. }
  270. void CompilerFloatTable::reset()
  271. {
  272. list = NULL;
  273. count = 0;
  274. }
  275. F64 *CompilerFloatTable::build()
  276. {
  277. F64 *ret = new F64[count];
  278. U32 i = 0;
  279. for (Entry *walk = list; walk; walk = walk->next, i++)
  280. ret[i] = walk->val;
  281. return ret;
  282. }
  283. void CompilerFloatTable::write(Stream &st)
  284. {
  285. st.write(count);
  286. for (Entry *walk = list; walk; walk = walk->next)
  287. st.write(walk->val);
  288. }
  289. //------------------------------------------------------------
  290. void CompilerIdentTable::reset()
  291. {
  292. list = NULL;
  293. }
  294. void CompilerIdentTable::add(StringTableEntry ste, U32 ip)
  295. {
  296. U32 index = gGlobalStringTable.add(ste, false);
  297. Entry *newEntry = (Entry *)consoleAlloc(sizeof(Entry));
  298. newEntry->offset = index;
  299. newEntry->ip = ip;
  300. for (Entry *walk = list; walk; walk = walk->next)
  301. {
  302. if (walk->offset == index)
  303. {
  304. newEntry->nextIdent = walk->nextIdent;
  305. walk->nextIdent = newEntry;
  306. return;
  307. }
  308. }
  309. newEntry->next = list;
  310. list = newEntry;
  311. newEntry->nextIdent = NULL;
  312. }
  313. void CompilerIdentTable::write(Stream &st)
  314. {
  315. U32 count = 0;
  316. Entry * walk;
  317. for (walk = list; walk; walk = walk->next)
  318. count++;
  319. st.write(count);
  320. for (walk = list; walk; walk = walk->next)
  321. {
  322. U32 ec = 0;
  323. Entry * el;
  324. for (el = walk; el; el = el->nextIdent)
  325. ec++;
  326. st.write(walk->offset);
  327. st.write(ec);
  328. for (el = walk; el; el = el->nextIdent)
  329. st.write(el->ip);
  330. }
  331. }
  332. //-------------------------------------------------------------------------
  333. U8 *CodeStream::allocCode(U32 sz)
  334. {
  335. U8 *ptr = NULL;
  336. if (mCodeHead)
  337. {
  338. const U32 bytesLeft = BlockSize - mCodeHead->size;
  339. if (bytesLeft > sz)
  340. {
  341. ptr = mCodeHead->data + mCodeHead->size;
  342. mCodeHead->size += sz;
  343. return ptr;
  344. }
  345. }
  346. CodeData *data = new CodeData;
  347. data->data = (U8*)dMalloc(BlockSize);
  348. data->size = sz;
  349. data->next = NULL;
  350. if (mCodeHead)
  351. mCodeHead->next = data;
  352. mCodeHead = data;
  353. if (mCode == NULL)
  354. mCode = data;
  355. return data->data;
  356. }
  357. //-------------------------------------------------------------------------
  358. void CodeStream::fixLoop(U32 loopBlockStart, U32 breakPoint, U32 continuePoint)
  359. {
  360. AssertFatal(mFixStack.size() > 0, "Fix stack mismatch");
  361. U32 fixStart = mFixStack[mFixStack.size() - 1];
  362. for (U32 i = fixStart; i<mFixList.size(); i += 2)
  363. {
  364. FixType type = (FixType)mFixList[i + 1];
  365. U32 fixedIp = 0;
  366. bool valid = true;
  367. switch (type)
  368. {
  369. case FIXTYPE_LOOPBLOCKSTART:
  370. fixedIp = loopBlockStart;
  371. break;
  372. case FIXTYPE_BREAK:
  373. fixedIp = breakPoint;
  374. break;
  375. case FIXTYPE_CONTINUE:
  376. fixedIp = continuePoint;
  377. break;
  378. default:
  379. //Con::warnf("Address %u fixed as %u", mFixList[i], mFixList[i+1]);
  380. valid = false;
  381. break;
  382. }
  383. if (valid)
  384. {
  385. patch(mFixList[i], fixedIp);
  386. }
  387. }
  388. }
  389. //-------------------------------------------------------------------------
  390. void CodeStream::emitCodeStream(U32 *size, U32 **stream, U32 **lineBreaks)
  391. {
  392. // Alloc stream
  393. U32 numLineBreaks = getNumLineBreaks();
  394. *stream = new U32[mCodePos + (numLineBreaks * 2)];
  395. dMemset(*stream, '\0', mCodePos + (numLineBreaks * 2));
  396. *size = mCodePos;
  397. // Dump chunks & line breaks
  398. U32 outBytes = mCodePos * sizeof(U32);
  399. U8 *outPtr = *((U8**)stream);
  400. for (CodeData *itr = mCode; itr != NULL; itr = itr->next)
  401. {
  402. U32 bytesToCopy = itr->size > outBytes ? outBytes : itr->size;
  403. dMemcpy(outPtr, itr->data, bytesToCopy);
  404. outPtr += bytesToCopy;
  405. outBytes -= bytesToCopy;
  406. }
  407. *lineBreaks = *stream + mCodePos;
  408. dMemcpy(*lineBreaks, mBreakLines.address(), sizeof(U32) * mBreakLines.size());
  409. // Apply patches on top
  410. for (U32 i = 0; i<mPatchList.size(); i++)
  411. {
  412. PatchEntry &e = mPatchList[i];
  413. (*stream)[e.addr] = e.value;
  414. }
  415. }
  416. //-------------------------------------------------------------------------
  417. void CodeStream::reset()
  418. {
  419. mCodePos = 0;
  420. mFixStack.clear();
  421. mFixLoopStack.clear();
  422. mFixList.clear();
  423. mBreakLines.clear();
  424. // Pop down to one code block
  425. CodeData *itr = mCode ? mCode->next : NULL;
  426. while (itr != NULL)
  427. {
  428. CodeData *next = itr->next;
  429. dFree(itr->data);
  430. delete(itr);
  431. itr = next;
  432. }
  433. if (mCode)
  434. {
  435. mCode->size = 0;
  436. mCode->next = NULL;
  437. mCodeHead = mCode;
  438. }
  439. }