BasicLibrary.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. using Lua.CodeAnalysis.Compilation;
  2. using Lua.Internal;
  3. using Lua.Runtime;
  4. namespace Lua.Standard;
  5. public sealed class BasicLibrary
  6. {
  7. public static readonly BasicLibrary Instance = new();
  8. public BasicLibrary()
  9. {
  10. Functions = [
  11. new("assert", Assert),
  12. new("collectgarbage", CollectGarbage),
  13. new("dofile", DoFile),
  14. new("error", Error),
  15. new("getmetatable", GetMetatable),
  16. new("ipairs", IPairs),
  17. new("loadfile", LoadFile),
  18. new("load", Load),
  19. new("next", Next),
  20. new("pairs", Pairs),
  21. new("pcall", PCall),
  22. new("print", Print),
  23. new("rawequal", RawEqual),
  24. new("rawget", RawGet),
  25. new("rawlen", RawLen),
  26. new("rawset", RawSet),
  27. new("select", Select),
  28. new("setmetatable", SetMetatable),
  29. new("tonumber", ToNumber),
  30. new("tostring", ToString),
  31. new("type", Type),
  32. new("xpcall", XPCall),
  33. ];
  34. IPairsIterator = new("iterator", (context, buffer, cancellationToken) =>
  35. {
  36. var table = context.GetArgument<LuaTable>(0);
  37. var i = context.GetArgument<double>(1);
  38. i++;
  39. if (table.TryGetValue(i, out var value))
  40. {
  41. buffer.Span[0] = i;
  42. buffer.Span[1] = value;
  43. }
  44. else
  45. {
  46. buffer.Span[0] = LuaValue.Nil;
  47. buffer.Span[1] = LuaValue.Nil;
  48. }
  49. return new(2);
  50. });
  51. PairsIterator = new("iterator", Next);
  52. }
  53. public readonly LuaFunction[] Functions;
  54. readonly LuaFunction IPairsIterator;
  55. readonly LuaFunction PairsIterator;
  56. public ValueTask<int> Assert(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken cancellationToken)
  57. {
  58. var arg0 = context.GetArgument(0);
  59. if (!arg0.ToBoolean())
  60. {
  61. var message = "assertion failed!";
  62. if (context.HasArgument(1))
  63. {
  64. message = context.GetArgument<string>(1);
  65. }
  66. throw new LuaAssertionException(context.State.GetTraceback(), message);
  67. }
  68. context.Arguments.CopyTo(buffer.Span);
  69. return new(context.ArgumentCount);
  70. }
  71. public ValueTask<int> CollectGarbage(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken cancellationToken)
  72. {
  73. GC.Collect();
  74. return new(0);
  75. }
  76. public async ValueTask<int> DoFile(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken cancellationToken)
  77. {
  78. var arg0 = context.GetArgument<string>(0);
  79. // do not use LuaState.DoFileAsync as it uses the newExecutionContext
  80. var text = await File.ReadAllTextAsync(arg0, cancellationToken);
  81. var fileName = Path.GetFileName(arg0);
  82. var chunk = LuaCompiler.Default.Compile(text, fileName);
  83. return await new Closure(context.State, chunk).InvokeAsync(context, buffer, cancellationToken);
  84. }
  85. public ValueTask<int> Error(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken cancellationToken)
  86. {
  87. var obj = context.ArgumentCount == 0 || context.Arguments[0].Type is LuaValueType.Nil
  88. ? "(error object is a nil value)"
  89. : context.Arguments[0].ToString();
  90. throw new LuaRuntimeException(context.State.GetTraceback(), obj!);
  91. }
  92. public ValueTask<int> GetMetatable(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken cancellationToken)
  93. {
  94. var arg0 = context.GetArgument(0);
  95. if (arg0.TryRead<LuaTable>(out var table))
  96. {
  97. if (table.Metatable == null)
  98. {
  99. buffer.Span[0] = LuaValue.Nil;
  100. }
  101. else if (table.Metatable.TryGetValue(Metamethods.Metatable, out var metatable))
  102. {
  103. buffer.Span[0] = metatable;
  104. }
  105. else
  106. {
  107. buffer.Span[0] = table.Metatable;
  108. }
  109. }
  110. else
  111. {
  112. buffer.Span[0] = LuaValue.Nil;
  113. }
  114. return new(1);
  115. }
  116. public ValueTask<int> IPairs(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken cancellationToken)
  117. {
  118. var arg0 = context.GetArgument<LuaTable>(0);
  119. // If table has a metamethod __ipairs, calls it with table as argument and returns the first three results from the call.
  120. if (arg0.Metatable != null && arg0.Metatable.TryGetValue(Metamethods.IPairs, out var metamethod))
  121. {
  122. if (!metamethod.TryRead<LuaFunction>(out var function))
  123. {
  124. LuaRuntimeException.AttemptInvalidOperation(context.State.GetTraceback(), "call", metamethod);
  125. }
  126. return function.InvokeAsync(context, buffer, cancellationToken);
  127. }
  128. buffer.Span[0] = IPairsIterator;
  129. buffer.Span[1] = arg0;
  130. buffer.Span[2] = 0;
  131. return new(3);
  132. }
  133. public async ValueTask<int> LoadFile(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken cancellationToken)
  134. {
  135. // Lua-CSharp does not support binary chunks, the mode argument is ignored.
  136. var arg0 = context.GetArgument<string>(0);
  137. var arg2 = context.HasArgument(2)
  138. ? context.GetArgument<LuaTable>(2)
  139. : null;
  140. // do not use LuaState.DoFileAsync as it uses the newExecutionContext
  141. try
  142. {
  143. var text = await File.ReadAllTextAsync(arg0, cancellationToken);
  144. var fileName = Path.GetFileName(arg0);
  145. var chunk = LuaCompiler.Default.Compile(text, fileName);
  146. buffer.Span[0] = new Closure(context.State, chunk, arg2);
  147. return 1;
  148. }
  149. catch (Exception ex)
  150. {
  151. buffer.Span[0] = LuaValue.Nil;
  152. buffer.Span[1] = ex.Message;
  153. return 2;
  154. }
  155. }
  156. public ValueTask<int> Load(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken cancellationToken)
  157. {
  158. // Lua-CSharp does not support binary chunks, the mode argument is ignored.
  159. var arg0 = context.GetArgument(0);
  160. var arg1 = context.HasArgument(1)
  161. ? context.GetArgument<string>(1)
  162. : null;
  163. var arg3 = context.HasArgument(3)
  164. ? context.GetArgument<LuaTable>(3)
  165. : null;
  166. // do not use LuaState.DoFileAsync as it uses the newExecutionContext
  167. try
  168. {
  169. if (arg0.TryRead<string>(out var str))
  170. {
  171. var chunk = LuaCompiler.Default.Compile(str, arg1 ?? "chunk");
  172. buffer.Span[0] = new Closure(context.State, chunk, arg3);
  173. return new(1);
  174. }
  175. else if (arg0.TryRead<LuaFunction>(out var function))
  176. {
  177. // TODO:
  178. throw new NotImplementedException();
  179. }
  180. else
  181. {
  182. LuaRuntimeException.BadArgument(context.State.GetTraceback(), 1, "load");
  183. return default; // dummy
  184. }
  185. }
  186. catch (Exception ex)
  187. {
  188. buffer.Span[0] = LuaValue.Nil;
  189. buffer.Span[1] = ex.Message;
  190. return new(2);
  191. }
  192. }
  193. public ValueTask<int> Next(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken cancellationToken)
  194. {
  195. var arg0 = context.GetArgument<LuaTable>(0);
  196. var arg1 = context.HasArgument(1) ? context.Arguments[1] : LuaValue.Nil;
  197. if (arg0.TryGetNext(arg1, out var kv))
  198. {
  199. buffer.Span[0] = kv.Key;
  200. buffer.Span[1] = kv.Value;
  201. return new(2);
  202. }
  203. else
  204. {
  205. buffer.Span[0] = LuaValue.Nil;
  206. return new(1);
  207. }
  208. }
  209. public ValueTask<int> Pairs(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken cancellationToken)
  210. {
  211. var arg0 = context.GetArgument<LuaTable>(0);
  212. // If table has a metamethod __pairs, calls it with table as argument and returns the first three results from the call.
  213. if (arg0.Metatable != null && arg0.Metatable.TryGetValue(Metamethods.Pairs, out var metamethod))
  214. {
  215. if (!metamethod.TryRead<LuaFunction>(out var function))
  216. {
  217. LuaRuntimeException.AttemptInvalidOperation(context.State.GetTraceback(), "call", metamethod);
  218. }
  219. return function.InvokeAsync(context, buffer, cancellationToken);
  220. }
  221. buffer.Span[0] = PairsIterator;
  222. buffer.Span[1] = arg0;
  223. buffer.Span[2] = LuaValue.Nil;
  224. return new(3);
  225. }
  226. public async ValueTask<int> PCall(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken cancellationToken)
  227. {
  228. var arg0 = context.GetArgument<LuaFunction>(0);
  229. try
  230. {
  231. using var methodBuffer = new PooledArray<LuaValue>(1024);
  232. var resultCount = await arg0.InvokeAsync(context with
  233. {
  234. State = context.State,
  235. ArgumentCount = context.ArgumentCount - 1,
  236. FrameBase = context.FrameBase + 1,
  237. }, methodBuffer.AsMemory(), cancellationToken);
  238. buffer.Span[0] = true;
  239. methodBuffer.AsSpan()[..resultCount].CopyTo(buffer.Span[1..]);
  240. return resultCount + 1;
  241. }
  242. catch (Exception ex)
  243. {
  244. buffer.Span[0] = false;
  245. buffer.Span[1] = ex.Message;
  246. return 2;
  247. }
  248. }
  249. public async ValueTask<int> Print(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken cancellationToken)
  250. {
  251. using var methodBuffer = new PooledArray<LuaValue>(1);
  252. for (int i = 0; i < context.ArgumentCount; i++)
  253. {
  254. await context.Arguments[i].CallToStringAsync(context, methodBuffer.AsMemory(), cancellationToken);
  255. Console.Write(methodBuffer[0]);
  256. Console.Write('\t');
  257. }
  258. Console.WriteLine();
  259. return 0;
  260. }
  261. public ValueTask<int> RawEqual(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken cancellationToken)
  262. {
  263. var arg0 = context.GetArgument(0);
  264. var arg1 = context.GetArgument(1);
  265. buffer.Span[0] = arg0 == arg1;
  266. return new(1);
  267. }
  268. public ValueTask<int> RawGet(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken cancellationToken)
  269. {
  270. var arg0 = context.GetArgument<LuaTable>(0);
  271. var arg1 = context.GetArgument(1);
  272. buffer.Span[0] = arg0[arg1];
  273. return new(1);
  274. }
  275. public ValueTask<int> RawLen(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken cancellationToken)
  276. {
  277. var arg0 = context.GetArgument(0);
  278. if (arg0.TryRead<LuaTable>(out var table))
  279. {
  280. buffer.Span[0] = table.ArrayLength;
  281. }
  282. else if (arg0.TryRead<string>(out var str))
  283. {
  284. buffer.Span[0] = str.Length;
  285. }
  286. else
  287. {
  288. LuaRuntimeException.BadArgument(context.State.GetTraceback(), 2, "rawlen", [LuaValueType.String, LuaValueType.Table]);
  289. }
  290. return new(1);
  291. }
  292. public ValueTask<int> RawSet(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken cancellationToken)
  293. {
  294. var arg0 = context.GetArgument<LuaTable>(0);
  295. var arg1 = context.GetArgument(1);
  296. var arg2 = context.GetArgument(2);
  297. arg0[arg1] = arg2;
  298. return new(0);
  299. }
  300. public ValueTask<int> Select(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken cancellationToken)
  301. {
  302. var arg0 = context.GetArgument(0);
  303. if (arg0.TryRead<double>(out var d))
  304. {
  305. if (!MathEx.IsInteger(d))
  306. {
  307. throw new LuaRuntimeException(context.State.GetTraceback(), "bad argument #1 to 'select' (number has no integer representation)");
  308. }
  309. var index = (int)d;
  310. if (Math.Abs(index) > context.ArgumentCount)
  311. {
  312. throw new LuaRuntimeException(context.State.GetTraceback(), "bad argument #1 to 'select' (index out of range)");
  313. }
  314. var span = index >= 0
  315. ? context.Arguments[index..]
  316. : context.Arguments[(context.ArgumentCount + index)..];
  317. span.CopyTo(buffer.Span);
  318. return new(span.Length);
  319. }
  320. else if (arg0.TryRead<string>(out var str) && str == "#")
  321. {
  322. buffer.Span[0] = context.ArgumentCount - 1;
  323. return new(1);
  324. }
  325. else
  326. {
  327. LuaRuntimeException.BadArgument(context.State.GetTraceback(), 1, "select", "number", arg0.Type.ToString());
  328. return default;
  329. }
  330. }
  331. public ValueTask<int> SetMetatable(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken cancellationToken)
  332. {
  333. var arg0 = context.GetArgument<LuaTable>(0);
  334. var arg1 = context.GetArgument(1);
  335. if (arg1.Type is not (LuaValueType.Nil or LuaValueType.Table))
  336. {
  337. LuaRuntimeException.BadArgument(context.State.GetTraceback(), 2, "setmetatable", [LuaValueType.Nil, LuaValueType.Table]);
  338. }
  339. if (arg0.Metatable != null && arg0.Metatable.TryGetValue(Metamethods.Metatable, out _))
  340. {
  341. throw new LuaRuntimeException(context.State.GetTraceback(), "cannot change a protected metatable");
  342. }
  343. else if (arg1.Type is LuaValueType.Nil)
  344. {
  345. arg0.Metatable = null;
  346. }
  347. else
  348. {
  349. arg0.Metatable = arg1.Read<LuaTable>();
  350. }
  351. buffer.Span[0] = arg0;
  352. return new(1);
  353. }
  354. public ValueTask<int> ToNumber(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken cancellationToken)
  355. {
  356. var e = context.GetArgument(0);
  357. int? toBase = context.HasArgument(1)
  358. ? (int)context.GetArgument<double>(1)
  359. : null;
  360. if (toBase != null && (toBase < 2 || toBase > 36))
  361. {
  362. throw new LuaRuntimeException(context.State.GetTraceback(), "bad argument #2 to 'tonumber' (base out of range)");
  363. }
  364. double? value = null;
  365. if (e.Type is LuaValueType.Number)
  366. {
  367. value = e.UnsafeRead<double>();
  368. }
  369. else if (e.TryRead<string>(out var str))
  370. {
  371. if (toBase == null)
  372. {
  373. if (e.TryRead<double>(out var result))
  374. {
  375. value = result;
  376. }
  377. }
  378. else if (toBase == 10)
  379. {
  380. if (double.TryParse(str, out var result))
  381. {
  382. value = result;
  383. }
  384. }
  385. else
  386. {
  387. try
  388. {
  389. // if the base is not 10, str cannot contain a minus sign
  390. var span = str.AsSpan().Trim();
  391. if (span.Length == 0) goto END;
  392. var first = span[0];
  393. var sign = first == '-' ? -1 : 1;
  394. if (first is '+' or '-')
  395. {
  396. span = span[1..];
  397. }
  398. if (span.Length == 0) goto END;
  399. if (toBase == 16 && span.Length > 2 && span[0] is '0' && span[1] is 'x' or 'X')
  400. {
  401. value = sign * HexConverter.ToDouble(span);
  402. }
  403. else
  404. {
  405. value = sign * StringToDouble(span, toBase.Value);
  406. }
  407. }
  408. catch (FormatException)
  409. {
  410. goto END;
  411. }
  412. }
  413. }
  414. else
  415. {
  416. goto END;
  417. }
  418. END:
  419. if (value != null && double.IsNaN(value.Value))
  420. {
  421. value = null;
  422. }
  423. buffer.Span[0] = value == null ? LuaValue.Nil : value.Value;
  424. return new(1);
  425. }
  426. static double StringToDouble(ReadOnlySpan<char> text, int toBase)
  427. {
  428. var value = 0.0;
  429. for (int i = 0; i < text.Length; i++)
  430. {
  431. var v = text[i] switch
  432. {
  433. '0' => 0,
  434. '1' => 1,
  435. '2' => 2,
  436. '3' => 3,
  437. '4' => 4,
  438. '5' => 5,
  439. '6' => 6,
  440. '7' => 7,
  441. '8' => 8,
  442. '9' => 9,
  443. 'a' or 'A' => 10,
  444. 'b' or 'B' => 11,
  445. 'c' or 'C' => 12,
  446. 'd' or 'D' => 13,
  447. 'e' or 'E' => 14,
  448. 'f' or 'F' => 15,
  449. 'g' or 'G' => 16,
  450. 'h' or 'H' => 17,
  451. 'i' or 'I' => 18,
  452. 'j' or 'J' => 19,
  453. 'k' or 'K' => 20,
  454. 'l' or 'L' => 21,
  455. 'm' or 'M' => 22,
  456. 'n' or 'N' => 23,
  457. 'o' or 'O' => 24,
  458. 'p' or 'P' => 25,
  459. 'q' or 'Q' => 26,
  460. 'r' or 'R' => 27,
  461. 's' or 'S' => 28,
  462. 't' or 'T' => 29,
  463. 'u' or 'U' => 30,
  464. 'v' or 'V' => 31,
  465. 'w' or 'W' => 32,
  466. 'x' or 'X' => 33,
  467. 'y' or 'Y' => 34,
  468. 'z' or 'Z' => 35,
  469. _ => 0,
  470. };
  471. if (v >= toBase)
  472. {
  473. throw new FormatException();
  474. }
  475. value += v * Math.Pow(toBase, text.Length - i - 1);
  476. }
  477. return value;
  478. }
  479. public ValueTask<int> ToString(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken cancellationToken)
  480. {
  481. var arg0 = context.GetArgument(0);
  482. return arg0.CallToStringAsync(context, buffer, cancellationToken);
  483. }
  484. public ValueTask<int> Type(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken cancellationToken)
  485. {
  486. var arg0 = context.GetArgument(0);
  487. buffer.Span[0] = arg0.Type switch
  488. {
  489. LuaValueType.Nil => "nil",
  490. LuaValueType.Boolean => "boolean",
  491. LuaValueType.String => "string",
  492. LuaValueType.Number => "number",
  493. LuaValueType.Function => "function",
  494. LuaValueType.Thread => "thread",
  495. LuaValueType.UserData => "userdata",
  496. LuaValueType.Table => "table",
  497. _ => throw new NotImplementedException(),
  498. };
  499. return new(1);
  500. }
  501. public async ValueTask<int> XPCall(LuaFunctionExecutionContext context, Memory<LuaValue> buffer, CancellationToken cancellationToken)
  502. {
  503. var arg0 = context.GetArgument<LuaFunction>(0);
  504. var arg1 = context.GetArgument<LuaFunction>(1);
  505. using var methodBuffer = new PooledArray<LuaValue>(1024);
  506. methodBuffer.AsSpan().Clear();
  507. try
  508. {
  509. var resultCount = await arg0.InvokeAsync(context with
  510. {
  511. State = context.State,
  512. ArgumentCount = context.ArgumentCount - 2,
  513. FrameBase = context.FrameBase + 2,
  514. }, methodBuffer.AsMemory(), cancellationToken);
  515. buffer.Span[0] = true;
  516. methodBuffer.AsSpan()[..resultCount].CopyTo(buffer.Span[1..]);
  517. return resultCount + 1;
  518. }
  519. catch (Exception ex)
  520. {
  521. methodBuffer.AsSpan().Clear();
  522. context.State.Push(ex.Message);
  523. // invoke error handler
  524. await arg1.InvokeAsync(context with
  525. {
  526. State = context.State,
  527. ArgumentCount = 1,
  528. FrameBase = context.Thread.Stack.Count - context.ArgumentCount,
  529. }, methodBuffer.AsMemory(), cancellationToken);
  530. buffer.Span[0] = false;
  531. buffer.Span[1] = ex.Message;
  532. return 2;
  533. }
  534. }
  535. }