BasicLibrary.cs 20 KB

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