From 12bd10164b0e141162472fcb6a59893a6ebbcd6d Mon Sep 17 00:00:00 2001 From: routersys Date: Sat, 4 Jul 2026 14:42:28 +0900 Subject: [PATCH] =?UTF-8?q?=E3=83=A9=E3=83=A0=E3=83=80=E5=BC=8F=E3=81=AE?= =?UTF-8?q?=E6=A7=8B=E6=96=87=E7=B3=96=E8=A1=A3=E3=82=92=E8=BF=BD=E5=8A=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Scripting/Syntax/Rules/LuaLambdaRule.cs | 74 +++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 LuaScript.Compat/Scripting/Syntax/Rules/LuaLambdaRule.cs diff --git a/LuaScript.Compat/Scripting/Syntax/Rules/LuaLambdaRule.cs b/LuaScript.Compat/Scripting/Syntax/Rules/LuaLambdaRule.cs new file mode 100644 index 0000000..d69b25b --- /dev/null +++ b/LuaScript.Compat/Scripting/Syntax/Rules/LuaLambdaRule.cs @@ -0,0 +1,74 @@ +namespace LuaScript.Compat.Syntax.Rules +{ + [LuaSyntaxRule(35)] + internal sealed class LuaLambdaRule : ILuaSyntaxRule + { + public bool TryApply(LuaRewriteContext context) + { + if (!context.Current.IsOperator("=>")) + return false; + if (!context.TryReadTrailingLvalue(out int start, out string target)) + return false; + if (!TryNormalizeParameters(target, out string parameters)) + return false; + + int body = context.NextSignificant(context.Index + 1); + if (body < 0 || !LuaSyntaxFacts.IsValueStart(context.Input[body])) + return false; + + context.RemoveOutputFrom(start); + context.Advance(); + string expression = context.ReadForwardOrOperand(); + if (expression.Length == 0) + return false; + + context.EmitRaw($"(function({parameters}) return {LuaSyntaxExtensions.Rewrite(expression)} end)"); + return true; + } + + private static bool TryNormalizeParameters(string text, out string parameters) + { + parameters = string.Empty; + text = text.Trim(); + bool wrapped = text.StartsWith("(") && text.EndsWith(")"); + if (wrapped) + text = text.Substring(1, text.Length - 2).Trim(); + + if (text.Length == 0) + return wrapped; + + var names = text.Split(','); + for (int i = 0; i < names.Length; i++) + { + string name = names[i].Trim(); + if (name == "...") + { + if (i != names.Length - 1) + return false; + continue; + } + if (!IsName(name) || LuaKeywords.IsReserved(name)) + return false; + if (!wrapped && names.Length > 1) + return false; + } + + parameters = string.Join(", ", System.Array.ConvertAll(names, static n => n.Trim())); + return true; + } + + private static bool IsName(string text) + { + if (text.Length == 0) + return false; + if (text[0] != '_' && !char.IsLetter(text[0])) + return false; + for (int i = 1; i < text.Length; i++) + { + if (text[i] != '_' && !char.IsLetterOrDigit(text[i])) + return false; + } + return true; + } + } +}