Browse Source

Update: support async and void

AnnulusGames 1 year ago
parent
commit
7d698383c1

+ 12 - 4
src/Lua.SourceGenerator/DiagnosticDescriptors.cs

@@ -38,16 +38,24 @@ public static class DiagnosticDescriptors
         defaultSeverity: DiagnosticSeverity.Error,
         isEnabledByDefault: true);
 
-    public static readonly DiagnosticDescriptor InvalidMethodType = new(
+    public static readonly DiagnosticDescriptor InvalidReturnType = new(
         id: "LUAC005",
-        title: "The arguments and return types must be LuaValue or types that can be converted to LuaValue.",
-        messageFormat: "The arguments and return types must be LuaValue or types that can be converted to LuaValue.",
+        title: "The return type must be LuaValue or types that can be converted to LuaValue.",
+        messageFormat: "The return type '{0}' must be LuaValue or types that can be converted to LuaValue.",
         category: Category,
         defaultSeverity: DiagnosticSeverity.Error,
         isEnabledByDefault: true);
 
-    public static readonly DiagnosticDescriptor DuplicateMetamethod = new(
+    public static readonly DiagnosticDescriptor InvalidParameterType = new(
         id: "LUAC006",
+        title: "The parameters must be LuaValue or types that can be converted to LuaValue.",
+        messageFormat: "The parameter '{0}' must be LuaValue or types that can be converted to LuaValue.",
+        category: Category,
+        defaultSeverity: DiagnosticSeverity.Error,
+        isEnabledByDefault: true);
+
+    public static readonly DiagnosticDescriptor DuplicateMetamethod = new(
+        id: "LUAC007",
         title: "The type already contains same metamethod.",
         messageFormat: "Type '{0}' already contains a '{1}' metamethod.,",
         category: Category,

+ 91 - 48
src/Lua.SourceGenerator/LuaObjectGenerator.Emit.cs

@@ -127,7 +127,7 @@ partial class LuaObjectGenerator
 
     static bool ValidateMembers(TypeMetadata typeMetadata, Compilation compilation, SymbolReferences references, in SourceProductionContext context)
     {
-        var error = true;
+        var isValid = true;
 
         foreach (var property in typeMetadata.Properties)
         {
@@ -142,15 +142,42 @@ partial class LuaObjectGenerator
                     property.Symbol.Locations.FirstOrDefault(),
                     property.Type.Name));
 
-                error = false;
+                isValid = false;
             }
         }
 
         foreach (var method in typeMetadata.Methods)
         {
+            if (!method.Symbol.ReturnsVoid)
+            {
+                var typeSymbol = method.Symbol.ReturnType;
+
+                if (method.IsAsync)
+                {
+                    var namedType = (INamedTypeSymbol)typeSymbol;
+                    if (namedType.TypeArguments.Length == 0) goto PARAMETERS;
+
+                    typeSymbol = namedType.TypeArguments[0];
+                }
+
+                if (SymbolEqualityComparer.Default.Equals(typeSymbol, references.LuaValue)) goto PARAMETERS;
+                if (SymbolEqualityComparer.Default.Equals(typeSymbol, typeMetadata.Symbol)) goto PARAMETERS;
+
+                var conversion = compilation.ClassifyConversion(typeSymbol, references.LuaValue);
+                if (!conversion.Exists)
+                {
+                    context.ReportDiagnostic(Diagnostic.Create(
+                        DiagnosticDescriptors.InvalidReturnType,
+                        typeSymbol.Locations.FirstOrDefault(),
+                        typeSymbol.Name));
+
+                    isValid = false;
+                }
+            }
+
+        PARAMETERS:
             foreach (var typeSymbol in method.Symbol.Parameters
-                .Select(x => x.Type)
-                .Append(method.Symbol.ReturnType))
+                .Select(x => x.Type))
             {
                 if (SymbolEqualityComparer.Default.Equals(typeSymbol, references.LuaValue)) continue;
                 if (SymbolEqualityComparer.Default.Equals(typeSymbol, typeMetadata.Symbol)) continue;
@@ -159,16 +186,16 @@ partial class LuaObjectGenerator
                 if (!conversion.Exists)
                 {
                     context.ReportDiagnostic(Diagnostic.Create(
-                        DiagnosticDescriptors.InvalidMethodType,
+                        DiagnosticDescriptors.InvalidParameterType,
                         typeSymbol.Locations.FirstOrDefault(),
                         typeSymbol.Name));
 
-                    error = false;
+                    isValid = false;
                 }
             }
         }
 
-        return error;
+        return isValid;
     }
 
     static bool TryEmitIndexMetamethod(TypeMetadata typeMetadata, CodeBuilder builder, in SourceProductionContext context)
@@ -278,47 +305,6 @@ partial class LuaObjectGenerator
 
     static bool TryEmitMethods(TypeMetadata typeMetadata, CodeBuilder builder, HashSet<LuaObjectMetamethod> metamethodSet, in SourceProductionContext context)
     {
-        static void EmitMethodFunction(string functionName, TypeMetadata typeMetadata, MethodMetadata methodMetadata, CodeBuilder builder)
-        {
-            builder.AppendLine($"static readonly global::Lua.LuaFunction {functionName} = new global::Lua.LuaFunction((context, buffer, ct) =>");
-
-            using (builder.BeginBlockScope())
-            {
-                var index = 0;
-
-                if (!methodMetadata.IsStatic)
-                {
-                    builder.AppendLine($"var userData = context.GetArgument<{typeMetadata.FullTypeName}>(0);");
-                    index++;
-                }
-
-                foreach (var parameter in methodMetadata.Symbol.Parameters)
-                {
-                    builder.AppendLine($"var arg{index} = context.GetArgument<{parameter.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)}>({index});");
-                    index++;
-                }
-
-                if (methodMetadata.IsStatic)
-                {
-                    builder.Append($"var result = {typeMetadata.FullTypeName}.{methodMetadata.Symbol.Name}(");
-                    builder.Append(string.Join(",", Enumerable.Range(0, index).Select(x => $"arg{x}")), false);
-                    builder.AppendLine(");", false);
-                }
-                else
-                {
-
-                    builder.Append($"var result = userData.{methodMetadata.Symbol.Name}(");
-                    builder.Append(string.Join(",", Enumerable.Range(1, index - 1).Select(x => $"arg{x}")), false);
-                    builder.AppendLine(");", false);
-                }
-
-                builder.AppendLine("buffer.Span[0] = new global::Lua.LuaValue(result);");
-                builder.AppendLine("return new(1);");
-            }
-            builder.AppendLine(");");
-            builder.AppendLine();
-        }
-
         builder.AppendLine();
 
         foreach (var methodMetadata in typeMetadata.Methods)
@@ -359,6 +345,63 @@ partial class LuaObjectGenerator
         return true;
     }
 
+    static void EmitMethodFunction(string functionName, TypeMetadata typeMetadata, MethodMetadata methodMetadata, CodeBuilder builder)
+    {
+        builder.AppendLine($"static readonly global::Lua.LuaFunction {functionName} = new global::Lua.LuaFunction({(methodMetadata.IsAsync ? "async" : "")} (context, buffer, ct) =>");
+
+        using (builder.BeginBlockScope())
+        {
+            var index = 0;
+
+            if (!methodMetadata.IsStatic)
+            {
+                builder.AppendLine($"var userData = context.GetArgument<{typeMetadata.FullTypeName}>(0);");
+                index++;
+            }
+
+            foreach (var parameter in methodMetadata.Symbol.Parameters)
+            {
+                builder.AppendLine($"var arg{index} = context.GetArgument<{parameter.Type.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)}>({index});");
+                index++;
+            }
+
+            if (methodMetadata.HasReturnValue)
+            {
+                builder.Append("var result = ");
+            }
+
+            if (methodMetadata.IsAsync)
+            {
+                builder.Append("await ", false);
+            }
+
+            if (methodMetadata.IsStatic)
+            {
+                builder.Append($"{typeMetadata.FullTypeName}.{methodMetadata.Symbol.Name}(", false);
+                builder.Append(string.Join(",", Enumerable.Range(0, index).Select(x => $"arg{x}")), false);
+                builder.AppendLine(");", false);
+            }
+            else
+            {
+                builder.Append($"userData.{methodMetadata.Symbol.Name}(");
+                builder.Append(string.Join(",", Enumerable.Range(1, index - 1).Select(x => $"arg{x}")), false);
+                builder.AppendLine(");", false);
+            }
+
+            if (methodMetadata.HasReturnValue)
+            {
+                builder.AppendLine("buffer.Span[0] = new global::Lua.LuaValue(result);");
+                builder.AppendLine($"return {(methodMetadata.IsAsync ? "1" : "new(1)")};");
+            }
+            else
+            {
+                builder.AppendLine($"return {(methodMetadata.IsAsync ? "0" : "new(0)")};");
+            }
+        }
+        builder.AppendLine(");");
+        builder.AppendLine();
+    }
+
     static bool TryEmitMetatable(CodeBuilder builder, IEnumerable<LuaObjectMetamethod> metamethods, in SourceProductionContext context)
     {
         builder.AppendLine("global::Lua.LuaTable? global::Lua.ILuaUserData.Metatable");

+ 11 - 0
src/Lua.SourceGenerator/MethodMetadata.cs

@@ -6,6 +6,8 @@ internal class MethodMetadata
 {
     public IMethodSymbol Symbol { get; }
     public bool IsStatic { get; }
+    public bool IsAsync { get; }
+    public bool HasReturnValue { get; }
     public bool HasMemberAttribute { get; }
     public bool HasMetamethodAttribute { get; }
     public string LuaMemberName { get; }
@@ -16,6 +18,15 @@ internal class MethodMetadata
         Symbol = symbol;
         IsStatic = symbol.IsStatic;
 
+        var returnType = symbol.ReturnType;
+        var fullName = (returnType.ContainingNamespace.IsGlobalNamespace ? "" : (returnType.ContainingNamespace + ".")) + returnType.Name;
+        IsAsync = fullName is "System.Threading.Tasks.Task"
+            or "System.Threading.Tasks.ValueTask"
+            or "Cysharp.Threading.Tasks.UniTask"
+            or "UnityEngine.Awaitable";
+
+        HasReturnValue = !symbol.ReturnsVoid && !(IsAsync && returnType is INamedTypeSymbol n && !n.IsGenericType);
+
         LuaMemberName = symbol.Name;
 
         var memberAttribute = symbol.GetAttribute(references.LuaMemberAttribute);

+ 1 - 1
src/Lua.SourceGenerator/SymbolReferences.cs

@@ -23,5 +23,5 @@ public sealed class SymbolReferences
     public INamedTypeSymbol LuaMemberAttribute { get; private set; } = default!;
     public INamedTypeSymbol LuaIgnoreMemberAttribute { get; private set; } = default!;
     public INamedTypeSymbol LuaMetamethodAttribute { get; private set; } = default!;
-    public INamedTypeSymbol LuaValue { get; private set; } = default!; 
+    public INamedTypeSymbol LuaValue { get; private set; } = default!;
 }