BasicLibrary.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. using System.Globalization;
  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. [
  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, 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. return new(context.Return(i, value));
  43. }
  44. else
  45. {
  46. return new(context.Return(LuaValue.Nil, LuaValue.Nil));
  47. }
  48. });
  49. PairsIterator = new("iterator", Next);
  50. }
  51. public readonly LuaFunction[] Functions;
  52. readonly LuaFunction IPairsIterator;
  53. readonly LuaFunction PairsIterator;
  54. public ValueTask<int> Assert(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  55. {
  56. var arg0 = context.GetArgument(0);
  57. if (!arg0.ToBoolean())
  58. {
  59. var message = "assertion failed!";
  60. if (context.HasArgument(1))
  61. {
  62. message = context.GetArgument<string>(1);
  63. }
  64. throw new LuaAssertionException(context.Thread, message);
  65. }
  66. return new(context.Return(context.Arguments));
  67. }
  68. public ValueTask<int> CollectGarbage(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  69. {
  70. GC.Collect();
  71. return new(context.Return());
  72. }
  73. public async ValueTask<int> DoFile(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  74. {
  75. var arg0 = context.GetArgument<string>(0);
  76. context.Thread.Stack.PopUntil(context.ReturnFrameBase);
  77. // do not use LuaState.DoFileAsync as it uses the newExecutionContext
  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 async 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 = await File.ReadAllBytesAsync(arg0, cancellationToken);
  139. var fileName = "@" + arg0;
  140. return context.Return(context.State.Load(bytes, fileName, mode, arg2));
  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, "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. if (ex is LuaRuntimeException luaEx)
  225. {
  226. luaEx.Forget();
  227. return context.Return(false, luaEx.ErrorObject);
  228. }
  229. else
  230. {
  231. return context.Return(false, ex.Message);
  232. }
  233. }
  234. }
  235. public async ValueTask<int> Print(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  236. {
  237. for (int i = 0; i < context.ArgumentCount; i++)
  238. {
  239. await context.Arguments[i].CallToStringAsync(context, cancellationToken);
  240. Console.Write(context.Thread.Stack.Pop().Read<string>());
  241. Console.Write('\t');
  242. }
  243. Console.WriteLine();
  244. return context.Return();
  245. }
  246. public ValueTask<int> RawEqual(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  247. {
  248. var arg0 = context.GetArgument(0);
  249. var arg1 = context.GetArgument(1);
  250. return new(context.Return(arg0 == arg1));
  251. }
  252. public ValueTask<int> RawGet(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  253. {
  254. var arg0 = context.GetArgument<LuaTable>(0);
  255. var arg1 = context.GetArgument(1);
  256. return new(context.Return(arg0[arg1]));
  257. }
  258. public ValueTask<int> RawLen(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  259. {
  260. var arg0 = context.GetArgument(0);
  261. if (arg0.TryRead<LuaTable>(out var table))
  262. {
  263. return new(context.Return(table.ArrayLength));
  264. }
  265. else if (arg0.TryRead<string>(out var str))
  266. {
  267. return new(context.Return(str.Length));
  268. }
  269. else
  270. {
  271. LuaRuntimeException.BadArgument(context.Thread, 2, "rawlen", [LuaValueType.String, LuaValueType.Table]);
  272. return default;
  273. }
  274. }
  275. public ValueTask<int> RawSet(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  276. {
  277. var arg0 = context.GetArgument<LuaTable>(0);
  278. var arg1 = context.GetArgument(1);
  279. var arg2 = context.GetArgument(2);
  280. arg0[arg1] = arg2;
  281. return new(context.Return());
  282. }
  283. public ValueTask<int> Select(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  284. {
  285. var arg0 = context.GetArgument(0);
  286. if (arg0.TryRead<int>(out var index))
  287. {
  288. if (Math.Abs(index) > context.ArgumentCount)
  289. {
  290. throw new LuaRuntimeException(context.Thread, "bad argument #1 to 'select' (index out of range)");
  291. }
  292. var span = index >= 0
  293. ? context.Arguments[index..]
  294. : context.Arguments[(context.ArgumentCount + index)..];
  295. return new(context.Return(span));
  296. }
  297. else if (arg0.TryRead<string>(out var str) && str == "#")
  298. {
  299. return new(context.Return(context.ArgumentCount - 1));
  300. }
  301. else
  302. {
  303. LuaRuntimeException.BadArgument(context.Thread, 1, "select", "number", arg0.Type.ToString());
  304. return default;
  305. }
  306. }
  307. public ValueTask<int> SetMetatable(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  308. {
  309. var arg0 = context.GetArgument<LuaTable>(0);
  310. var arg1 = context.GetArgument(1);
  311. if (arg1.Type is not (LuaValueType.Nil or LuaValueType.Table))
  312. {
  313. LuaRuntimeException.BadArgument(context.Thread, 2, "setmetatable", [LuaValueType.Nil, LuaValueType.Table]);
  314. }
  315. if (arg0.Metatable != null && arg0.Metatable.TryGetValue(Metamethods.Metatable, out _))
  316. {
  317. throw new LuaRuntimeException(context.Thread, "cannot change a protected metatable");
  318. }
  319. else if (arg1.Type is LuaValueType.Nil)
  320. {
  321. arg0.Metatable = null;
  322. }
  323. else
  324. {
  325. arg0.Metatable = arg1.Read<LuaTable>();
  326. }
  327. return new(context.Return(arg0));
  328. }
  329. public ValueTask<int> ToNumber(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  330. {
  331. var e = context.GetArgument(0);
  332. int? toBase = context.HasArgument(1)
  333. ? (int)context.GetArgument<double>(1)
  334. : null;
  335. if (toBase != null && (toBase < 2 || toBase > 36))
  336. {
  337. throw new LuaRuntimeException(context.Thread, "bad argument #2 to 'tonumber' (base out of range)");
  338. }
  339. double? value = null;
  340. if (e.Type is LuaValueType.Number)
  341. {
  342. value = e.UnsafeRead<double>();
  343. }
  344. else if (e.TryRead<string>(out var str))
  345. {
  346. if (toBase == null)
  347. {
  348. if (e.TryRead<double>(out var result))
  349. {
  350. value = result;
  351. }
  352. }
  353. else if (toBase == 10)
  354. {
  355. if (double.TryParse(str, NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
  356. {
  357. value = result;
  358. }
  359. }
  360. else
  361. {
  362. try
  363. {
  364. // if the base is not 10, str cannot contain a minus sign
  365. var span = str.AsSpan().Trim();
  366. if (span.Length == 0) goto END;
  367. var first = span[0];
  368. var sign = first == '-' ? -1 : 1;
  369. if (first is '+' or '-')
  370. {
  371. span = span[1..];
  372. }
  373. if (span.Length == 0) goto END;
  374. if (toBase == 16 && span.Length > 2 && span[0] is '0' && span[1] is 'x' or 'X')
  375. {
  376. value = sign * HexConverter.ToDouble(span);
  377. }
  378. else
  379. {
  380. value = sign * StringToDouble(span, toBase.Value);
  381. }
  382. }
  383. catch (FormatException)
  384. {
  385. goto END;
  386. }
  387. }
  388. }
  389. else
  390. {
  391. goto END;
  392. }
  393. END:
  394. if (value is double.NaN)
  395. {
  396. value = null;
  397. }
  398. return new(context.Return(value ?? LuaValue.Nil));
  399. }
  400. static double StringToDouble(ReadOnlySpan<char> text, int toBase)
  401. {
  402. var value = 0.0;
  403. for (int i = 0; i < text.Length; i++)
  404. {
  405. var v = text[i] switch
  406. {
  407. '0' => 0,
  408. '1' => 1,
  409. '2' => 2,
  410. '3' => 3,
  411. '4' => 4,
  412. '5' => 5,
  413. '6' => 6,
  414. '7' => 7,
  415. '8' => 8,
  416. '9' => 9,
  417. 'a' or 'A' => 10,
  418. 'b' or 'B' => 11,
  419. 'c' or 'C' => 12,
  420. 'd' or 'D' => 13,
  421. 'e' or 'E' => 14,
  422. 'f' or 'F' => 15,
  423. 'g' or 'G' => 16,
  424. 'h' or 'H' => 17,
  425. 'i' or 'I' => 18,
  426. 'j' or 'J' => 19,
  427. 'k' or 'K' => 20,
  428. 'l' or 'L' => 21,
  429. 'm' or 'M' => 22,
  430. 'n' or 'N' => 23,
  431. 'o' or 'O' => 24,
  432. 'p' or 'P' => 25,
  433. 'q' or 'Q' => 26,
  434. 'r' or 'R' => 27,
  435. 's' or 'S' => 28,
  436. 't' or 'T' => 29,
  437. 'u' or 'U' => 30,
  438. 'v' or 'V' => 31,
  439. 'w' or 'W' => 32,
  440. 'x' or 'X' => 33,
  441. 'y' or 'Y' => 34,
  442. 'z' or 'Z' => 35,
  443. _ => 0,
  444. };
  445. if (v >= toBase)
  446. {
  447. throw new FormatException();
  448. }
  449. value += v * Math.Pow(toBase, text.Length - i - 1);
  450. }
  451. return value;
  452. }
  453. public ValueTask<int> ToString(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  454. {
  455. var arg0 = context.GetArgument(0);
  456. context.Return();
  457. return arg0.CallToStringAsync(context, cancellationToken);
  458. }
  459. public ValueTask<int> Type(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  460. {
  461. var arg0 = context.GetArgument(0);
  462. return new(context.Return(arg0.Type switch
  463. {
  464. LuaValueType.Nil => "nil",
  465. LuaValueType.Boolean => "boolean",
  466. LuaValueType.String => "string",
  467. LuaValueType.Number => "number",
  468. LuaValueType.Function => "function",
  469. LuaValueType.Thread => "thread",
  470. LuaValueType.LightUserData => "userdata",
  471. LuaValueType.UserData => "userdata",
  472. LuaValueType.Table => "table",
  473. _ => throw new NotImplementedException(),
  474. }));
  475. }
  476. public async ValueTask<int> XPCall(LuaFunctionExecutionContext context, CancellationToken cancellationToken)
  477. {
  478. var frameCount = context.Thread.CallStackFrameCount;
  479. var arg0 = context.GetArgument(0);
  480. var arg1 = context.GetArgument<LuaFunction>(1);
  481. try
  482. {
  483. var stack = context.Thread.Stack;
  484. stack.Get(context.FrameBase+1) = arg0;
  485. var count = await LuaVirtualMachine.Call(context.Access.Thread,context.FrameBase + 1,context.ReturnFrameBase+1,cancellationToken);
  486. context.Thread.Stack.Get(context.ReturnFrameBase) = true;
  487. return count + 1;
  488. }
  489. catch (Exception ex)
  490. {
  491. var thread = context.Thread;
  492. thread.PopCallStackFrameUntil(frameCount);
  493. var access = thread.CurrentAccess;
  494. if (ex is LuaRuntimeException luaEx)
  495. {
  496. luaEx.Forget();
  497. access.Push(luaEx.ErrorObject);
  498. }
  499. else
  500. {
  501. access.Push(ex.Message);
  502. }
  503. // invoke error handler
  504. var count = await access.RunAsync(arg1, 1,context.ReturnFrameBase+1, cancellationToken);
  505. context.Thread.Stack.Get(context.ReturnFrameBase) = false;
  506. return count + 1;
  507. }
  508. }
  509. }