compiler.cpp 16 KB

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