BasicLibrary.cs 19 KB

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