FunctionCompilationContext.cs 15 KB

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