BasicLibrary.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  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. GC.Collect();
  72. return new(context.Return());
  73. }
  74. public async ValueTask<int> DoFile(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  75. {
  76. var arg0 = context.GetArgument<string>(0);
  77. context.Thread.Stack.PopUntil(context.ReturnFrameBase);
  78. var bytes = File.ReadAllBytes(arg0);
  79. var fileName = "@" + arg0;
  80. var closure = context.State.Load(bytes, fileName);
  81. return await context.Access.RunAsync(closure, cancellationToken);
  82. }
  83. public ValueTask<int> Error(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  84. {
  85. var value = context.ArgumentCount == 0
  86. ? LuaValue.Nil
  87. : context.Arguments[0];
  88. throw new LuaRuntimeException(context.Thread, value);
  89. }
  90. public ValueTask<int> GetMetatable(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  91. {
  92. var arg0 = context.GetArgument(0);
  93. if (context.State.TryGetMetatable(arg0, out var metatable))
  94. {
  95. if (metatable.TryGetValue(Metamethods.Metatable, out var metaMetatable))
  96. {
  97. context.Return(metaMetatable);
  98. }
  99. else
  100. {
  101. context.Return(metatable);
  102. }
  103. }
  104. else
  105. {
  106. context.Return(LuaValue.Nil);
  107. }
  108. return default;
  109. }
  110. public async ValueTask<int> IPairs(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  111. {
  112. var arg0 = context.GetArgument<LuaTable>(0);
  113. // If table has a metamethod __ipairs, calls it with table as argument and returns the first three results from the call.
  114. if (arg0.Metatable != null && arg0.Metatable.TryGetValue(Metamethods.IPairs, out var metamethod))
  115. {
  116. var stack = context.Thread.Stack;
  117. var top = stack.Count;
  118. stack.Push(metamethod);
  119. stack.Push(arg0);
  120. await LuaVirtualMachine.Call(context.Access.Thread, top, context.ReturnFrameBase, cancellationToken);
  121. stack.SetTop(context.ReturnFrameBase + 3);
  122. return 3;
  123. }
  124. return context.Return(IPairsIterator, arg0, 0);
  125. }
  126. public ValueTask<int> LoadFile(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  127. {
  128. var arg0 = context.GetArgument<string>(0);
  129. var mode = context.HasArgument(1)
  130. ? context.GetArgument<string>(1)
  131. : "bt";
  132. var arg2 = context.HasArgument(2)
  133. ? context.GetArgument<LuaTable>(2)
  134. : null;
  135. // do not use LuaState.DoFileAsync as it uses the newExecutionContext
  136. try
  137. {
  138. var bytes = File.ReadAllBytes(arg0);
  139. var fileName = "@" + arg0;
  140. return new(context.Return(context.State.Load(bytes, fileName, mode, arg2)));
  141. }
  142. catch (Exception ex)
  143. {
  144. return new(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, "load");
  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. luaEx.Forget();
  232. return context.Return(false, luaEx.ErrorObject);
  233. default:
  234. return context.Return(false, ex.Message);
  235. }
  236. }
  237. }
  238. public async ValueTask<int> Print(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  239. {
  240. for (int i = 0; i < context.ArgumentCount; i++)
  241. {
  242. await context.Arguments[i].CallToStringAsync(context, cancellationToken);
  243. Console.Write(context.Thread.Stack.Pop().Read<string>());
  244. Console.Write('\t');
  245. }
  246. Console.WriteLine();
  247. return context.Return();
  248. }
  249. public ValueTask<int> RawEqual(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  250. {
  251. var arg0 = context.GetArgument(0);
  252. var arg1 = context.GetArgument(1);
  253. return new(context.Return(arg0 == arg1));
  254. }
  255. public ValueTask<int> RawGet(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  256. {
  257. var arg0 = context.GetArgument<LuaTable>(0);
  258. var arg1 = context.GetArgument(1);
  259. return new(context.Return(arg0[arg1]));
  260. }
  261. public ValueTask<int> RawLen(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  262. {
  263. var arg0 = context.GetArgument(0);
  264. if (arg0.TryRead<LuaTable>(out var table))
  265. {
  266. return new(context.Return(table.ArrayLength));
  267. }
  268. else if (arg0.TryRead<string>(out var str))
  269. {
  270. return new(context.Return(str.Length));
  271. }
  272. else
  273. {
  274. LuaRuntimeException.BadArgument(context.Thread, 2, "rawlen", [LuaValueType.String, LuaValueType.Table]);
  275. return default;
  276. }
  277. }
  278. public ValueTask<int> RawSet(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  279. {
  280. var arg0 = context.GetArgument<LuaTable>(0);
  281. var arg1 = context.GetArgument(1);
  282. var arg2 = context.GetArgument(2);
  283. arg0[arg1] = arg2;
  284. return new(context.Return());
  285. }
  286. public ValueTask<int> Select(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  287. {
  288. var arg0 = context.GetArgument(0);
  289. if (arg0.TryRead<int>(out var index))
  290. {
  291. if (Math.Abs(index) > context.ArgumentCount)
  292. {
  293. throw new LuaRuntimeException(context.Thread, "bad argument #1 to 'select' (index out of range)");
  294. }
  295. var span = index >= 0
  296. ? context.Arguments[index..]
  297. : context.Arguments[(context.ArgumentCount + index)..];
  298. return new(context.Return(span));
  299. }
  300. else if (arg0.TryRead<string>(out var str) && str == "#")
  301. {
  302. return new(context.Return(context.ArgumentCount - 1));
  303. }
  304. else
  305. {
  306. LuaRuntimeException.BadArgument(context.Thread, 1, "select", "number", arg0.Type.ToString());
  307. return default;
  308. }
  309. }
  310. public ValueTask<int> SetMetatable(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  311. {
  312. var arg0 = context.GetArgument<LuaTable>(0);
  313. var arg1 = context.GetArgument(1);
  314. if (arg1.Type is not (LuaValueType.Nil or LuaValueType.Table))
  315. {
  316. LuaRuntimeException.BadArgument(context.Thread, 2, "setmetatable", [LuaValueType.Nil, LuaValueType.Table]);
  317. }
  318. if (arg0.Metatable != null && arg0.Metatable.TryGetValue(Metamethods.Metatable, out _))
  319. {
  320. throw new LuaRuntimeException(context.Thread, "cannot change a protected metatable");
  321. }
  322. else if (arg1.Type is LuaValueType.Nil)
  323. {
  324. arg0.Metatable = null;
  325. }
  326. else
  327. {
  328. arg0.Metatable = arg1.Read<LuaTable>();
  329. }
  330. return new(context.Return(arg0));
  331. }
  332. public ValueTask<int> ToNumber(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  333. {
  334. var e = context.GetArgument(0);
  335. int? toBase = context.HasArgument(1)
  336. ? (int)context.GetArgument<double>(1)
  337. : null;
  338. if (toBase != null && (toBase < 2 || toBase > 36))
  339. {
  340. throw new LuaRuntimeException(context.Thread, "bad argument #2 to 'tonumber' (base out of range)");
  341. }
  342. double? value = null;
  343. if (e.Type is LuaValueType.Number)
  344. {
  345. value = e.UnsafeRead<double>();
  346. }
  347. else if (e.TryRead<string>(out var str))
  348. {
  349. if (toBase == null)
  350. {
  351. if (e.TryRead<double>(out var result))
  352. {
  353. value = result;
  354. }
  355. }
  356. else if (toBase == 10)
  357. {
  358. if (double.TryParse(str, NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
  359. {
  360. value = result;
  361. }
  362. }
  363. else
  364. {
  365. try
  366. {
  367. // if the base is not 10, str cannot contain a minus sign
  368. var span = str.AsSpan().Trim();
  369. if (span.Length == 0) goto END;
  370. var first = span[0];
  371. var sign = first == '-' ? -1 : 1;
  372. if (first is '+' or '-')
  373. {
  374. span = span[1..];
  375. }
  376. if (span.Length == 0) goto END;
  377. if (toBase == 16 && span.Length > 2 && span[0] is '0' && span[1] is 'x' or 'X')
  378. {
  379. value = sign * HexConverter.ToDouble(span);
  380. }
  381. else
  382. {
  383. value = sign * StringToDouble(span, toBase.Value);
  384. }
  385. }
  386. catch (FormatException)
  387. {
  388. goto END;
  389. }
  390. }
  391. }
  392. else
  393. {
  394. goto END;
  395. }
  396. END:
  397. if (value is double.NaN)
  398. {
  399. value = null;
  400. }
  401. return new(context.Return(value ?? LuaValue.Nil));
  402. }
  403. static double StringToDouble(ReadOnlySpan<char> text, int toBase)
  404. {
  405. var value = 0.0;
  406. for (int i = 0; i < text.Length; i++)
  407. {
  408. var v = text[i] switch
  409. {
  410. '0' => 0,
  411. '1' => 1,
  412. '2' => 2,
  413. '3' => 3,
  414. '4' => 4,
  415. '5' => 5,
  416. '6' => 6,
  417. '7' => 7,
  418. '8' => 8,
  419. '9' => 9,
  420. 'a' or 'A' => 10,
  421. 'b' or 'B' => 11,
  422. 'c' or 'C' => 12,
  423. 'd' or 'D' => 13,
  424. 'e' or 'E' => 14,
  425. 'f' or 'F' => 15,
  426. 'g' or 'G' => 16,
  427. 'h' or 'H' => 17,
  428. 'i' or 'I' => 18,
  429. 'j' or 'J' => 19,
  430. 'k' or 'K' => 20,
  431. 'l' or 'L' => 21,
  432. 'm' or 'M' => 22,
  433. 'n' or 'N' => 23,
  434. 'o' or 'O' => 24,
  435. 'p' or 'P' => 25,
  436. 'q' or 'Q' => 26,
  437. 'r' or 'R' => 27,
  438. 's' or 'S' => 28,
  439. 't' or 'T' => 29,
  440. 'u' or 'U' => 30,
  441. 'v' or 'V' => 31,
  442. 'w' or 'W' => 32,
  443. 'x' or 'X' => 33,
  444. 'y' or 'Y' => 34,
  445. 'z' or 'Z' => 35,
  446. _ => 0,
  447. };
  448. if (v >= toBase)
  449. {
  450. throw new FormatException();
  451. }
  452. value += v * Math.Pow(toBase, text.Length - i - 1);
  453. }
  454. return value;
  455. }
  456. public ValueTask<int> ToString(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  457. {
  458. var arg0 = context.GetArgument(0);
  459. context.Return();
  460. return arg0.CallToStringAsync(context, cancellationToken);
  461. }
  462. public ValueTask<int> Type(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  463. {
  464. var arg0 = context.GetArgument(0);
  465. return new(context.Return(arg0.Type switch
  466. {
  467. LuaValueType.Nil => "nil",
  468. LuaValueType.Boolean => "boolean",
  469. LuaValueType.String => "string",
  470. LuaValueType.Number => "number",
  471. LuaValueType.Function => "function",
  472. LuaValueType.Thread => "thread",
  473. LuaValueType.LightUserData => "userdata",
  474. LuaValueType.UserData => "userdata",
  475. LuaValueType.Table => "table",
  476. _ => throw new NotImplementedException(),
  477. }));
  478. }
  479. public async ValueTask<int> XPCall(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  480. {
  481. var frameCount = context.Thread.CallStackFrameCount;
  482. var arg0 = context.GetArgument(0);
  483. var arg1 = context.GetArgument<LuaFunction>(1);
  484. try
  485. {
  486. var stack = context.Thread.Stack;
  487. stack.Get(context.FrameBase + 1) = arg0;
  488. var count = await LuaVirtualMachine.Call(context.Access.Thread, context.FrameBase + 1, context.ReturnFrameBase + 1, cancellationToken);
  489. context.Thread.Stack.Get(context.ReturnFrameBase) = true;
  490. return count + 1;
  491. }
  492. catch (Exception ex)
  493. {
  494. var thread = context.Thread;
  495. thread.PopCallStackFrameUntil(frameCount);
  496. cancellationToken.ThrowIfCancellationRequested();
  497. var access = thread.CurrentAccess;
  498. if (ex is LuaRuntimeException luaEx)
  499. {
  500. luaEx.Forget();
  501. access.Push(luaEx.ErrorObject);
  502. }
  503. else
  504. {
  505. access.Push(ex.Message);
  506. }
  507. // invoke error handler
  508. var count = await access.RunAsync(arg1, 1, context.ReturnFrameBase + 1, cancellationToken);
  509. context.Thread.Stack.Get(context.ReturnFrameBase) = false;
  510. return count + 1;
  511. }
  512. }
  513. }