FunctionCompilationContext.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457
  1. using System.Collections.Concurrent;
  2. using System.Diagnostics.CodeAnalysis;
  3. using System.Runtime.CompilerServices;
  4. using Lua.Runtime;
  5. using Lua.Internal;
  6. namespace Lua.CodeAnalysis.Compilation;
  7. public class FunctionCompilationContext : IDisposable
  8. {
  9. static class Pool
  10. {
  11. static readonly ConcurrentStack<FunctionCompilationContext> stack = new();
  12. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  13. public static FunctionCompilationContext Rent()
  14. {
  15. if (!stack.TryPop(out var context))
  16. {
  17. context = new();
  18. }
  19. return context;
  20. }
  21. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  22. public static void Return(FunctionCompilationContext context)
  23. {
  24. context.Reset();
  25. stack.Push(context);
  26. }
  27. }
  28. internal static FunctionCompilationContext Create(ScopeCompilationContext? parentScope)
  29. {
  30. var context = Pool.Rent();
  31. context.ParentScope = parentScope;
  32. return context;
  33. }
  34. FunctionCompilationContext()
  35. {
  36. Scope = new()
  37. {
  38. Function = this
  39. };
  40. }
  41. // instructions
  42. FastListCore<Instruction> instructions;
  43. FastListCore<SourcePosition> instructionPositions;
  44. // constants
  45. Dictionary<LuaValue, int> constantIndexMap = new(16);
  46. FastListCore<LuaValue> constants;
  47. // functions
  48. Dictionary<ReadOnlyMemory<char>, int> functionMap = new(32, Utf16StringMemoryComparer.Default);
  49. FastListCore<Chunk> functions;
  50. // upvalues
  51. FastListCore<UpValueInfo> upvalues;
  52. // loop
  53. FastListCore<BreakDescription> breakQueue;
  54. FastListCore<GotoDescription> gotoQueue;
  55. /// <summary>
  56. /// Chunk name (for debug)
  57. /// </summary>
  58. public string? ChunkName { get; set; }
  59. /// <summary>
  60. /// Level of nesting of while, repeat, and for loops
  61. /// </summary>
  62. public int LoopLevel { get; set; }
  63. /// <summary>
  64. /// Number of parameters
  65. /// </summary>
  66. public int ParameterCount { get; set; }
  67. /// <summary>
  68. /// Weather the function has variable arguments
  69. /// </summary>
  70. public bool HasVariableArguments { get; set; }
  71. /// <summary>
  72. /// Parent scope context
  73. /// </summary>
  74. public ScopeCompilationContext? ParentScope { get; private set; }
  75. /// <summary>
  76. /// Top-level scope context
  77. /// </summary>
  78. public ScopeCompilationContext Scope { get; }
  79. /// <summary>
  80. /// Instructions
  81. /// </summary>
  82. public Span<Instruction> Instructions => instructions.AsSpan();
  83. /// <summary>
  84. /// Push the new instruction.
  85. /// </summary>
  86. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  87. public void PushInstruction(in Instruction instruction, in SourcePosition position)
  88. {
  89. instructions.Add(instruction);
  90. instructionPositions.Add(position);
  91. }
  92. /// <summary>
  93. /// Push or merge the new instruction.
  94. /// </summary>
  95. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  96. public void PushOrMergeInstruction(int lastLocal, in Instruction instruction, in SourcePosition position, ref bool incrementStackPosition)
  97. {
  98. if (instructions.Length == 0)
  99. {
  100. instructions.Add(instruction);
  101. instructionPositions.Add(position);
  102. return;
  103. }
  104. ref var lastInstruction = ref instructions.AsSpan()[^1];
  105. var opcode = instruction.OpCode;
  106. switch (opcode)
  107. {
  108. case OpCode.Move:
  109. // last A is not local variable
  110. if (lastInstruction.A != lastLocal &&
  111. // available to merge
  112. lastInstruction.A == instruction.B &&
  113. // not already merged
  114. lastInstruction.A != lastInstruction.B)
  115. {
  116. switch (lastInstruction.OpCode)
  117. {
  118. case OpCode.GetTable:
  119. case OpCode.Add:
  120. case OpCode.Sub:
  121. case OpCode.Mul:
  122. case OpCode.Div:
  123. case OpCode.Mod:
  124. case OpCode.Pow:
  125. case OpCode.Concat:
  126. {
  127. lastInstruction.A = instruction.A;
  128. incrementStackPosition = false;
  129. return;
  130. }
  131. }
  132. }
  133. break;
  134. case OpCode.GetTable:
  135. {
  136. // Merge MOVE GetTable
  137. if (lastInstruction.OpCode == OpCode.Move && lastLocal != lastInstruction.A)
  138. {
  139. if (lastInstruction.A == instruction.B)
  140. {
  141. lastInstruction = Instruction.GetTable(instruction.A, lastInstruction.B, instruction.C);
  142. instructionPositions[^1] = position;
  143. incrementStackPosition = false;
  144. return;
  145. }
  146. }
  147. break;
  148. }
  149. case OpCode.SetTable:
  150. {
  151. // Merge MOVE SETTABLE
  152. if (lastInstruction.OpCode == OpCode.Move && lastLocal != lastInstruction.A)
  153. {
  154. var lastB = lastInstruction.B;
  155. var lastA = lastInstruction.A;
  156. if (lastB < 255 && lastA == instruction.A)
  157. {
  158. // Merge MOVE MOVE SETTABLE
  159. if (instructions.Length > 2)
  160. {
  161. ref var last2Instruction = ref instructions.AsSpan()[^2];
  162. var last2A = last2Instruction.A;
  163. if (last2Instruction.OpCode == OpCode.Move && lastLocal != last2A && instruction.C == last2A)
  164. {
  165. last2Instruction = Instruction.SetTable((byte)(lastB), instruction.B, last2Instruction.B);
  166. instructions.RemoveAtSwapback(instructions.Length - 1);
  167. instructionPositions.RemoveAtSwapback(instructionPositions.Length - 1);
  168. instructionPositions[^1] = position;
  169. incrementStackPosition = false;
  170. return;
  171. }
  172. }
  173. lastInstruction = Instruction.SetTable((byte)(lastB), instruction.B, instruction.C);
  174. instructionPositions[^1] = position;
  175. incrementStackPosition = false;
  176. return;
  177. }
  178. if (lastA == instruction.C)
  179. {
  180. lastInstruction = Instruction.SetTable(instruction.A, instruction.B, lastB);
  181. instructionPositions[^1] = position;
  182. incrementStackPosition = false;
  183. return;
  184. }
  185. }
  186. else if (lastInstruction.OpCode == OpCode.GetTabUp && instructions.Length >= 2)
  187. {
  188. ref var last2Instruction = ref instructions[^2];
  189. var last2OpCode = last2Instruction.OpCode;
  190. if (last2OpCode is OpCode.LoadK or OpCode.Move)
  191. {
  192. var last2A = last2Instruction.A;
  193. if (last2A != lastLocal && instruction.C == last2A)
  194. {
  195. var c = last2OpCode == OpCode.LoadK ? last2Instruction.Bx + 256 : last2Instruction.B;
  196. last2Instruction = lastInstruction;
  197. lastInstruction = instruction with { C = (ushort)c };
  198. instructionPositions[^2] = instructionPositions[^1];
  199. instructionPositions[^1] = position;
  200. incrementStackPosition = false;
  201. return;
  202. }
  203. }
  204. }
  205. break;
  206. }
  207. case OpCode.Unm:
  208. case OpCode.Not:
  209. case OpCode.Len:
  210. if (lastInstruction.OpCode == OpCode.Move && lastLocal != lastInstruction.A && lastInstruction.A == instruction.B)
  211. {
  212. lastInstruction = instruction with { B = lastInstruction.B }; ;
  213. instructionPositions[^1] = position;
  214. incrementStackPosition = false;
  215. return;
  216. }
  217. break;
  218. case OpCode.Return:
  219. if (lastInstruction.OpCode == OpCode.Move && instruction.B == 2 && lastInstruction.B < 256)
  220. {
  221. lastInstruction = instruction with { A = (byte)lastInstruction.B };
  222. instructionPositions[^1] = position;
  223. incrementStackPosition = false;
  224. return;
  225. }
  226. break;
  227. }
  228. instructions.Add(instruction);
  229. instructionPositions.Add(position);
  230. }
  231. /// <summary>
  232. /// Gets the index of the constant from the value, or if the constant is not registered it is added and its index is returned.
  233. /// </summary>
  234. public uint GetConstantIndex(in LuaValue value)
  235. {
  236. if (!constantIndexMap.TryGetValue(value, out var index))
  237. {
  238. index = constants.Length;
  239. constants.Add(value);
  240. constantIndexMap.Add(value, index);
  241. }
  242. return (uint)index;
  243. }
  244. public void AddOrSetFunctionProto(ReadOnlyMemory<char> name, Chunk chunk, out int index)
  245. {
  246. index = functions.Length;
  247. functionMap[name] = functions.Length;
  248. functions.Add(chunk);
  249. }
  250. public void AddFunctionProto(Chunk chunk, out int index)
  251. {
  252. index = functions.Length;
  253. functions.Add(chunk);
  254. }
  255. public bool TryGetFunctionProto(ReadOnlyMemory<char> name, [NotNullWhen(true)] out Chunk? proto)
  256. {
  257. if (functionMap.TryGetValue(name, out var index))
  258. {
  259. proto = functions[index];
  260. return true;
  261. }
  262. else
  263. {
  264. proto = null;
  265. return false;
  266. }
  267. }
  268. public void AddUpValue(UpValueInfo upValue)
  269. {
  270. upvalues.Add(upValue);
  271. }
  272. public bool TryGetUpValue(ReadOnlyMemory<char> name, out UpValueInfo description)
  273. {
  274. var span = upvalues.AsSpan();
  275. for (int i = 0; i < span.Length; i++)
  276. {
  277. var info = span[i];
  278. if (info.Name.Span.SequenceEqual(name.Span))
  279. {
  280. description = info;
  281. return true;
  282. }
  283. }
  284. if (ParentScope == null)
  285. {
  286. description = default;
  287. return false;
  288. }
  289. if (ParentScope.TryGetLocalVariable(name, out var localVariable))
  290. {
  291. ParentScope.HasCapturedLocalVariables = true;
  292. description = new()
  293. {
  294. Name = name,
  295. Index = localVariable.RegisterIndex,
  296. Id = upvalues.Length,
  297. IsInRegister = true,
  298. };
  299. upvalues.Add(description);
  300. return true;
  301. }
  302. else if (ParentScope.Function.TryGetUpValue(name, out var parentUpValue))
  303. {
  304. description = new()
  305. {
  306. Name = name,
  307. Index = parentUpValue.Id,
  308. Id = upvalues.Length,
  309. IsInRegister = false,
  310. };
  311. upvalues.Add(description);
  312. return true;
  313. }
  314. description = default;
  315. return false;
  316. }
  317. public void AddUnresolvedBreak(BreakDescription description, SourcePosition sourcePosition)
  318. {
  319. if (LoopLevel == 0)
  320. {
  321. LuaParseException.BreakNotInsideALoop(ChunkName, sourcePosition);
  322. }
  323. breakQueue.Add(description);
  324. }
  325. public void ResolveAllBreaks(byte startPosition, int endPosition, ScopeCompilationContext loopScope)
  326. {
  327. foreach (var description in breakQueue.AsSpan())
  328. {
  329. ref var instruction = ref Instructions[description.Index];
  330. if (loopScope.HasCapturedLocalVariables)
  331. {
  332. instruction.A = startPosition;
  333. }
  334. instruction.SBx = endPosition - description.Index;
  335. }
  336. breakQueue.Clear();
  337. }
  338. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  339. public void AddUnresolvedGoto(GotoDescription description)
  340. {
  341. gotoQueue.Add(description);
  342. }
  343. public void ResolveGoto(LabelDescription labelDescription)
  344. {
  345. for (int i = 0; i < gotoQueue.Length; i++)
  346. {
  347. var gotoDesc = gotoQueue[i];
  348. if (gotoDesc.Name.Span.SequenceEqual(labelDescription.Name.Span))
  349. {
  350. instructions[gotoDesc.JumpInstructionIndex] = Instruction.Jmp(labelDescription.RegisterIndex, labelDescription.Index - gotoDesc.JumpInstructionIndex - 1);
  351. gotoQueue.RemoveAtSwapback(i);
  352. i--;
  353. }
  354. }
  355. }
  356. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  357. public Chunk ToChunk()
  358. {
  359. // add return
  360. instructions.Add(Instruction.Return(0, 1));
  361. instructionPositions.Add(instructionPositions.Length == 0 ? default : instructionPositions[^1]);
  362. var chunk = new Chunk()
  363. {
  364. Name = ChunkName ?? "chunk",
  365. Instructions = instructions.AsSpan().ToArray(),
  366. SourcePositions = instructionPositions.AsSpan().ToArray(),
  367. Constants = constants.AsSpan().ToArray(),
  368. UpValues = upvalues.AsSpan().ToArray(),
  369. Functions = functions.AsSpan().ToArray(),
  370. ParameterCount = ParameterCount,
  371. };
  372. foreach (var function in functions.AsSpan())
  373. {
  374. function.Parent = chunk;
  375. }
  376. return chunk;
  377. }
  378. /// <summary>
  379. /// Resets the values ​​held in the context.
  380. /// </summary>
  381. public void Reset()
  382. {
  383. Scope.Reset();
  384. instructions.Clear();
  385. instructionPositions.Clear();
  386. constantIndexMap.Clear();
  387. constants.Clear();
  388. upvalues.Clear();
  389. functionMap.Clear();
  390. functions.Clear();
  391. breakQueue.Clear();
  392. gotoQueue.Clear();
  393. ChunkName = null;
  394. LoopLevel = 0;
  395. ParameterCount = 0;
  396. HasVariableArguments = false;
  397. }
  398. /// <summary>
  399. /// Returns the context object to the pool.
  400. /// </summary>
  401. public void Dispose()
  402. {
  403. ParentScope = null;
  404. Pool.Return(this);
  405. }
  406. }