2
0

compiler.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563
  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 "compiler.h"
  25. #include "console/simBase.h"
  26. extern FuncVars gEvalFuncVars;
  27. extern FuncVars gGlobalScopeFuncVars;
  28. extern FuncVars *gFuncVars;
  29. namespace Con
  30. {
  31. extern bool scriptWarningsAsAsserts;
  32. };
  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. gGlobalScopeFuncVars.clear();
  104. gFuncVars = gIsEvalCompile ? &gEvalFuncVars : &gGlobalScopeFuncVars;
  105. }
  106. void *consoleAlloc(U32 size) { return gConsoleAllocator.alloc(size); }
  107. void consoleAllocReset() { gConsoleAllocator.freeBlocks(); }
  108. void scriptErrorHandler(const char* str)
  109. {
  110. if (Con::scriptWarningsAsAsserts)
  111. {
  112. AssertISV(false, str);
  113. }
  114. else
  115. {
  116. Con::warnf(ConsoleLogEntry::Type::Script, "%s", str);
  117. }
  118. }
  119. }
  120. //-------------------------------------------------------------------------
  121. using namespace Compiler;
  122. S32 FuncVars::assign(StringTableEntry var, TypeReq currentType, S32 lineNumber, bool isConstant)
  123. {
  124. std::unordered_map<StringTableEntry, Var>::iterator found = vars.find(var);
  125. if (found != vars.end())
  126. {
  127. // if we are calling assign more than once AND it changes type, we don't know what the variable type is as this is a
  128. // dynamically typed language. So we will assign to None and bail. None will be taken care of by the code to always
  129. // load what the default type is (What Globals and arrays use, type None).
  130. if (currentType != found->second.currentType && found->second.currentType != TypeReqNone)
  131. found->second.currentType = TypeReqNone;
  132. if (found->second.isConstant)
  133. {
  134. const char* str = avar("Script Warning: Reassigning variable %s when it is a constant. File: %s Line : %d", var, CodeBlock::smCurrentParser->getCurrentFile(), lineNumber);
  135. scriptErrorHandler(str);
  136. }
  137. return found->second.reg;
  138. }
  139. S32 id = counter++;
  140. vars[var] = { id, currentType, var, isConstant };
  141. variableNameMap[id] = var;
  142. return id;
  143. }
  144. S32 FuncVars::lookup(StringTableEntry var, S32 lineNumber)
  145. {
  146. std::unordered_map<StringTableEntry, Var>::iterator found = vars.find(var);
  147. if (found == vars.end())
  148. {
  149. const char* str = avar("Script Warning: Variable %s referenced before used when compiling script. File: %s Line: %d", var, CodeBlock::smCurrentParser->getCurrentFile(), lineNumber);
  150. scriptErrorHandler(str);
  151. return assign(var, TypeReqString, lineNumber, false);
  152. }
  153. return found->second.reg;
  154. }
  155. TypeReq FuncVars::lookupType(StringTableEntry var, S32 lineNumber)
  156. {
  157. std::unordered_map<StringTableEntry, Var>::iterator found = vars.find(var);
  158. if (found == vars.end())
  159. {
  160. const char* str = avar("Script Warning: Variable %s referenced before used when compiling script. File: %s Line: %d", var, CodeBlock::smCurrentParser->getCurrentFile(), lineNumber);
  161. scriptErrorHandler(str);
  162. assign(var, TypeReqString, lineNumber, false);
  163. return vars.find(var)->second.currentType;
  164. }
  165. return found->second.currentType;
  166. }
  167. void FuncVars::clear()
  168. {
  169. vars.clear();
  170. variableNameMap.clear();
  171. counter = 0;
  172. }
  173. //-------------------------------------------------------------------------
  174. U32 CompilerStringTable::add(const char *str, bool caseSens, bool tag)
  175. {
  176. // Is it already in?
  177. Entry **walk;
  178. for (walk = &list; *walk; walk = &((*walk)->next))
  179. {
  180. if ((*walk)->tag != tag)
  181. continue;
  182. if (caseSens)
  183. {
  184. if (!String::compare((*walk)->string, str))
  185. return (*walk)->start;
  186. }
  187. else
  188. {
  189. if (!dStricmp((*walk)->string, str))
  190. return (*walk)->start;
  191. }
  192. }
  193. // Write it out.
  194. Entry *newStr = (Entry *)consoleAlloc(sizeof(Entry));
  195. *walk = newStr;
  196. newStr->next = NULL;
  197. newStr->start = totalLen;
  198. U32 len = dStrlen(str) + 1;
  199. if (tag && len < 7) // alloc space for the numeric tag 1 for tag, 5 for # and 1 for nul
  200. len = 7;
  201. totalLen += len;
  202. newStr->string = (char *)consoleAlloc(len);
  203. newStr->len = len;
  204. newStr->tag = tag;
  205. dStrcpy(newStr->string, str, len);
  206. // Put into the hash table.
  207. hashTable[str] = newStr;
  208. return newStr->start;
  209. }
  210. U32 CompilerStringTable::addIntString(U32 value)
  211. {
  212. dSprintf(buf, sizeof(buf), "%d", value);
  213. return add(buf);
  214. }
  215. U32 CompilerStringTable::addFloatString(F64 value)
  216. {
  217. dSprintf(buf, sizeof(buf), "%g", value);
  218. return add(buf);
  219. }
  220. void CompilerStringTable::reset()
  221. {
  222. // Reset list and associated variables
  223. list = nullptr;
  224. totalLen = 0;
  225. hashTable.clear(); // Clear the lookup table too
  226. }
  227. char *CompilerStringTable::build()
  228. {
  229. char *ret = new char[totalLen];
  230. dMemset(ret, 0, totalLen);
  231. for (Entry *walk = list; walk; walk = walk->next)
  232. dStrcpy(ret + walk->start, walk->string, totalLen - walk->start);
  233. return ret;
  234. }
  235. void CompilerStringTable::write(Stream &st)
  236. {
  237. st.write(totalLen);
  238. for (Entry *walk = list; walk; walk = walk->next)
  239. st.write(walk->len, walk->string);
  240. }
  241. //------------------------------------------------------------
  242. void CompilerLocalVariableToRegisterMappingTable::add(StringTableEntry functionName, StringTableEntry namespaceName, StringTableEntry varName)
  243. {
  244. StringTableEntry funcLookupTableName = StringTable->insert(avar("%s::%s", namespaceName, functionName));
  245. localVarToRegister[funcLookupTableName].varList.push_back(varName);;
  246. }
  247. S32 CompilerLocalVariableToRegisterMappingTable::lookup(StringTableEntry namespaceName, StringTableEntry functionName, StringTableEntry varName)
  248. {
  249. StringTableEntry funcLookupTableName = StringTable->insert(avar("%s::%s", namespaceName, functionName));
  250. auto functionPosition = localVarToRegister.find(funcLookupTableName);
  251. if (functionPosition != localVarToRegister.end())
  252. {
  253. const auto& table = localVarToRegister[funcLookupTableName].varList;
  254. auto varPosition = std::find(table.begin(), table.end(), varName);
  255. if (varPosition != table.end())
  256. {
  257. return std::distance(table.begin(), varPosition);
  258. }
  259. }
  260. Con::errorf("Unable to find local variable %s in function name %s", varName, funcLookupTableName);
  261. return -1;
  262. }
  263. CompilerLocalVariableToRegisterMappingTable CompilerLocalVariableToRegisterMappingTable::copy()
  264. {
  265. // Trivilly copyable as its all plain old data and using STL containers... (We want a deep copy though!)
  266. CompilerLocalVariableToRegisterMappingTable table;
  267. table.localVarToRegister = localVarToRegister;
  268. return table;
  269. }
  270. void CompilerLocalVariableToRegisterMappingTable::reset()
  271. {
  272. localVarToRegister.clear();
  273. }
  274. void CompilerLocalVariableToRegisterMappingTable::write(Stream& stream)
  275. {
  276. stream.write((U32)localVarToRegister.size());
  277. for (const auto& pair : localVarToRegister)
  278. {
  279. StringTableEntry functionName = pair.first;
  280. stream.writeString(functionName);
  281. const auto& localVariableTableForFunction = localVarToRegister[functionName].varList;
  282. stream.write((U32)localVariableTableForFunction.size());
  283. for (const StringTableEntry& varName : localVariableTableForFunction)
  284. {
  285. stream.writeString(varName);
  286. }
  287. }
  288. }
  289. //------------------------------------------------------------
  290. U32 CompilerFloatTable::add(F64 value)
  291. {
  292. Entry **walk;
  293. U32 i = 0;
  294. for (walk = &list; *walk; walk = &((*walk)->next), i++)
  295. if (value == (*walk)->val)
  296. return i;
  297. Entry *newFloat = (Entry *)consoleAlloc(sizeof(Entry));
  298. newFloat->val = value;
  299. newFloat->next = NULL;
  300. count++;
  301. *walk = newFloat;
  302. return count - 1;
  303. }
  304. void CompilerFloatTable::reset()
  305. {
  306. list = NULL;
  307. count = 0;
  308. }
  309. F64 *CompilerFloatTable::build()
  310. {
  311. F64 *ret = new F64[count];
  312. U32 i = 0;
  313. for (Entry *walk = list; walk; walk = walk->next, i++)
  314. ret[i] = walk->val;
  315. return ret;
  316. }
  317. void CompilerFloatTable::write(Stream &st)
  318. {
  319. st.write(count);
  320. for (Entry *walk = list; walk; walk = walk->next)
  321. st.write(walk->val);
  322. }
  323. //------------------------------------------------------------
  324. void CompilerIdentTable::reset()
  325. {
  326. list = NULL;
  327. }
  328. void CompilerIdentTable::add(StringTableEntry ste, U32 ip)
  329. {
  330. U32 index = gGlobalStringTable.add(ste, false);
  331. Entry *newEntry = (Entry *)consoleAlloc(sizeof(Entry));
  332. newEntry->offset = index;
  333. newEntry->ip = ip;
  334. for (Entry *walk = list; walk; walk = walk->next)
  335. {
  336. if (walk->offset == index)
  337. {
  338. newEntry->nextIdent = walk->nextIdent;
  339. walk->nextIdent = newEntry;
  340. return;
  341. }
  342. }
  343. newEntry->next = list;
  344. list = newEntry;
  345. newEntry->nextIdent = NULL;
  346. }
  347. void CompilerIdentTable::write(Stream &st)
  348. {
  349. U32 count = 0;
  350. Entry * walk;
  351. for (walk = list; walk; walk = walk->next)
  352. count++;
  353. st.write(count);
  354. for (walk = list; walk; walk = walk->next)
  355. {
  356. U32 ec = 0;
  357. Entry * el;
  358. for (el = walk; el; el = el->nextIdent)
  359. ec++;
  360. st.write(walk->offset);
  361. st.write(ec);
  362. for (el = walk; el; el = el->nextIdent)
  363. st.write(el->ip);
  364. }
  365. }
  366. //-------------------------------------------------------------------------
  367. U8 *CodeStream::allocCode(U32 sz)
  368. {
  369. U8 *ptr = NULL;
  370. if (mCodeHead)
  371. {
  372. const U32 bytesLeft = BlockSize - mCodeHead->size;
  373. if (bytesLeft > sz)
  374. {
  375. ptr = mCodeHead->data + mCodeHead->size;
  376. mCodeHead->size += sz;
  377. return ptr;
  378. }
  379. }
  380. CodeData *data = new CodeData;
  381. data->data = (U8*)dMalloc(BlockSize);
  382. data->size = sz;
  383. data->next = NULL;
  384. if (mCodeHead)
  385. mCodeHead->next = data;
  386. mCodeHead = data;
  387. if (mCode == NULL)
  388. mCode = data;
  389. return data->data;
  390. }
  391. //-------------------------------------------------------------------------
  392. void CodeStream::fixLoop(U32 loopBlockStart, U32 breakPoint, U32 continuePoint)
  393. {
  394. AssertFatal(mFixStack.size() > 0, "Fix stack mismatch");
  395. U32 fixStart = mFixStack[mFixStack.size() - 1];
  396. for (U32 i = fixStart; i<mFixList.size(); i += 2)
  397. {
  398. FixType type = (FixType)mFixList[i + 1];
  399. U32 fixedIp = 0;
  400. bool valid = true;
  401. switch (type)
  402. {
  403. case FIXTYPE_LOOPBLOCKSTART:
  404. fixedIp = loopBlockStart;
  405. break;
  406. case FIXTYPE_BREAK:
  407. fixedIp = breakPoint;
  408. break;
  409. case FIXTYPE_CONTINUE:
  410. fixedIp = continuePoint;
  411. break;
  412. default:
  413. //Con::warnf("Address %u fixed as %u", mFixList[i], mFixList[i+1]);
  414. valid = false;
  415. break;
  416. }
  417. if (valid)
  418. {
  419. patch(mFixList[i], fixedIp);
  420. }
  421. }
  422. }
  423. //-------------------------------------------------------------------------
  424. void CodeStream::emitCodeStream(U32 *size, U32 **stream, U32 **lineBreaks)
  425. {
  426. // Alloc stream
  427. U32 numLineBreaks = getNumLineBreaks();
  428. *stream = new U32[mCodePos + (numLineBreaks * 2)];
  429. dMemset(*stream, '\0', mCodePos + (numLineBreaks * 2));
  430. *size = mCodePos;
  431. // Dump chunks & line breaks
  432. U32 outBytes = mCodePos * sizeof(U32);
  433. U8 *outPtr = *((U8**)stream);
  434. for (CodeData *itr = mCode; itr != NULL; itr = itr->next)
  435. {
  436. U32 bytesToCopy = itr->size > outBytes ? outBytes : itr->size;
  437. dMemcpy(outPtr, itr->data, bytesToCopy);
  438. outPtr += bytesToCopy;
  439. outBytes -= bytesToCopy;
  440. }
  441. *lineBreaks = *stream + mCodePos;
  442. dMemcpy(*lineBreaks, mBreakLines.address(), sizeof(U32) * mBreakLines.size());
  443. // Apply patches on top
  444. for (U32 i = 0; i<mPatchList.size(); i++)
  445. {
  446. PatchEntry &e = mPatchList[i];
  447. (*stream)[e.addr] = e.value;
  448. }
  449. }
  450. //-------------------------------------------------------------------------
  451. void CodeStream::reset()
  452. {
  453. mCodePos = 0;
  454. mFixStack.clear();
  455. mFixLoopStack.clear();
  456. mFixList.clear();
  457. mBreakLines.clear();
  458. // Pop down to one code block
  459. CodeData *itr = mCode ? mCode->next : NULL;
  460. while (itr != NULL)
  461. {
  462. CodeData *next = itr->next;
  463. dFree(itr->data);
  464. delete(itr);
  465. itr = next;
  466. }
  467. if (mCode)
  468. {
  469. mCode->size = 0;
  470. mCode->next = NULL;
  471. mCodeHead = mCode;
  472. }
  473. }