Forráskód Böngészése

MessageHandler实现Source Generator生成

tanghai 2 éve
szülő
commit
c323f33bf2

+ 40 - 10
Share/Share.SourceGenerator/Generator/ETSystemGenerator/AttributeTemplate.cs

@@ -10,16 +10,41 @@ namespace ET.Generator
 
 
         public AttributeTemplate()
         public AttributeTemplate()
         {
         {
-            this.templates.Add("EntitySystem", $$"""
-        $attribute$
-                public class $argsTypesUnderLine$_$methodName$System: $methodName$System<$argsTypes$>
-                {   
-                    protected override void $methodName$($argsTypeVars$)
-                    {
-                        self.$methodName$($argsVars$);
-                    }
-                }
-        """);
+            this.templates.Add("EntitySystem", 
+                $$"""
+                        $attribute$
+                        public class $argsTypesUnderLine$_$methodName$System: $methodName$System<$argsTypes$>
+                        {   
+                            protected override void $methodName$($argsTypesVars$)
+                            {
+                                $argsVars0$.$methodName$($argsVarsWithout0$);
+                            }
+                        }
+                """);
+            
+            this.templates.Add("MessageHandler", 
+                $$"""
+                        $attribute$
+                	    public class $className$_$methodName$_Handler: AMHandler<$argsTypes1$>
+                	    {
+                	    	protected override async ETTask Run($argsTypesVars$)
+                	    	{
+                                await $className$.$methodName$($argsVars$);
+                            }
+                        }
+                """);
+            
+            this.templates.Add("MessageRpcHandler", 
+                $$"""
+                        $attribute$
+                	    public class $className$_$methodName$_Handler: AMRpcHandler<$argsTypes1$, $argsTypes2$>
+                	    {
+                	    	protected override async ETTask Run($argsTypesVars$)
+                	    	{
+                                await $className$.$methodName$($argsVars$);
+                            }
+                        }
+                """);
         }
         }
 
 
         public string Get(string attributeType)
         public string Get(string attributeType)
@@ -36,5 +61,10 @@ namespace ET.Generator
 
 
             return template;
             return template;
         }
         }
+
+        public bool Contains(string attributeType)
+        {
+            return this.templates.ContainsKey(attributeType);
+        }
     }
     }
 }
 }

+ 66 - 27
Share/Share.SourceGenerator/Generator/ETSystemGenerator/ETSystemGenerator.cs

@@ -16,7 +16,7 @@ public class ETSystemGenerator: ISourceGenerator
     public void Initialize(GeneratorInitializationContext context)
     public void Initialize(GeneratorInitializationContext context)
     {
     {
         this.templates = new AttributeTemplate();
         this.templates = new AttributeTemplate();
-        context.RegisterForSyntaxNotifications(SyntaxContextReceiver.Create);
+        context.RegisterForSyntaxNotifications(()=> SyntaxContextReceiver.Create(this.templates));
     }
     }
 
 
     public void Execute(GeneratorExecutionContext context)
     public void Execute(GeneratorExecutionContext context)
@@ -103,27 +103,32 @@ public class ETSystemGenerator: ISourceGenerator
             string methodName = methodDeclarationSyntax.Identifier.Text;
             string methodName = methodDeclarationSyntax.Identifier.Text;
             string? componentName = componentParam.Type?.ToString();
             string? componentName = componentParam.Type?.ToString();
 
 
-            StringBuilder argsTypes = new StringBuilder();
+            List<string> argsTypesList = new List<string>();
+            List<string> argsTypeVarsList = new List<string>();
+            List<string> argsVarsList = new List<string>();
+            List<string> argsVarsWithout0List = new List<string>();
             for (int i = 0; i < methodSymbol.Parameters.Length; i++)
             for (int i = 0; i < methodSymbol.Parameters.Length; i++)
             {
             {
-                argsTypes.Append(i == 0? $"{methodSymbol.Parameters[i].Type}" : $",{methodSymbol.Parameters[i].Type}");
-            }
+                string type = methodSymbol.Parameters[i].Type.ToString();
+                type = type.Trim();
+                if (type == "")
+                {
+                    continue;
+                }
+                string name = $"{methodSymbol.Parameters[i].Name}";
+                
 
 
-            StringBuilder argsTypeVars = new StringBuilder();
-            for (int i = 0; i < methodSymbol.Parameters.Length; i++)
-            {
-                argsTypeVars.Append(i == 0? $"{methodSymbol.Parameters[i].Type} self" : $",{methodSymbol.Parameters[i].Type} args{i}");
-            }
+                
+                argsTypesList.Add(type);
+                argsVarsList.Add(name);
+                argsTypeVarsList.Add($"{type} {name}");
 
 
-            StringBuilder argsVars = new StringBuilder();
-            if (methodSymbol.Parameters.Length > 1)
-            {
-                for (int i = 1; i < methodSymbol.Parameters.Length; i++)
+                if (i != 0)
                 {
                 {
-                    argsVars.Append(i == 1? $"args1" : $",args{i}");
+                    argsVarsWithout0List.Add(name);
                 }
                 }
             }
             }
-
+            
             foreach (AttributeListSyntax attributeListSyntax in methodDeclarationSyntax.AttributeLists)
             foreach (AttributeListSyntax attributeListSyntax in methodDeclarationSyntax.AttributeLists)
             {
             {
                 AttributeSyntax? attribute = attributeListSyntax.Attributes.FirstOrDefault();
                 AttributeSyntax? attribute = attributeListSyntax.Attributes.FirstOrDefault();
@@ -147,17 +152,29 @@ namespace {{namespaceName}}
 }
 }
 """;
 """;
 
 
-                string argsTypesString = argsTypes.ToString();
-                string argsTypesUnderLine = argsTypesString.Replace(",", "_").Replace(".", "_");
+                string argsVars = string.Join(",", argsVarsList);
+                string argsTypes = string.Join(",", argsTypesList);
+                string argsTypesVars = string.Join(",", argsTypeVarsList);
+                string argsTypesUnderLine = argsTypes.Replace(",", "_").Replace(".", "_");
+                string argsVarsWithout0 = string.Join(",", argsVarsWithout0List);
+
                 code = code.Replace("$attribute$", attributeString);
                 code = code.Replace("$attribute$", attributeString);
                 code = code.Replace("$attributeType$", attributeType);
                 code = code.Replace("$attributeType$", attributeType);
                 code = code.Replace("$methodName$", methodName);
                 code = code.Replace("$methodName$", methodName);
-                code = code.Replace("entityType", componentName);
-                code = code.Replace("$argsTypes$", argsTypesString);
+                code = code.Replace("$className$", className);
+                code = code.Replace("$entityType$", componentName);
+                code = code.Replace("$argsTypes$", argsTypes);
                 code = code.Replace("$argsTypesUnderLine$", argsTypesUnderLine);
                 code = code.Replace("$argsTypesUnderLine$", argsTypesUnderLine);
-                code = code.Replace("$argsVars$", argsVars.ToString());
-                code = code.Replace("$argsTypeVars$", argsTypeVars.ToString());
-                
+                code = code.Replace("$argsTypesVars$", argsTypesVars);
+                code = code.Replace("$argsVars$", argsVars);
+                code = code.Replace("$argsVarsWithout0$", argsVarsWithout0);
+
+                for (int i = 0; i < argsTypesList.Count; ++i)
+                {
+                    code = code.Replace($"$argsTypes{i}$", argsTypesList[i]);
+                    code = code.Replace($"$argsVars{i}$", argsVarsList[i]);
+                }
+
                 string fileName = $"{namespaceName}.{className}.{methodName}.{argsTypesUnderLine}.g.cs";
                 string fileName = $"{namespaceName}.{className}.{methodName}.{argsTypesUnderLine}.g.cs";
                 
                 
                 context.AddSource(fileName, code);
                 context.AddSource(fileName, code);
@@ -167,9 +184,16 @@ namespace {{namespaceName}}
 
 
     class SyntaxContextReceiver: ISyntaxContextReceiver
     class SyntaxContextReceiver: ISyntaxContextReceiver
     {
     {
-        internal static ISyntaxContextReceiver Create()
+        internal static ISyntaxContextReceiver Create(AttributeTemplate attributeTemplate)
         {
         {
-            return new SyntaxContextReceiver();
+            return new SyntaxContextReceiver(attributeTemplate);
+        }
+
+        private AttributeTemplate attributeTemplate;
+
+        SyntaxContextReceiver(AttributeTemplate attributeTemplate)
+        {
+            this.attributeTemplate = attributeTemplate;
         }
         }
 
 
         public Dictionary<ClassDeclarationSyntax, HashSet<MethodDeclarationSyntax>> MethodDeclarations { get; } = new();
         public Dictionary<ClassDeclarationSyntax, HashSet<MethodDeclarationSyntax>> MethodDeclarations { get; } = new();
@@ -187,9 +211,24 @@ namespace {{namespaceName}}
                 return;
                 return;
             }
             }
 
 
-            AttributeSyntax? attr = methodDeclarationSyntax.AttributeLists.SelectMany(x => x.Attributes)
-                    .FirstOrDefault(x => x.Name.ToString() == "EntitySystem");
-            if (attr == null)
+            bool found = false;
+            foreach (AttributeListSyntax attributeListSyntax in methodDeclarationSyntax.AttributeLists)
+            {
+                AttributeSyntax? attribute = attributeListSyntax.Attributes.FirstOrDefault();
+                if (attribute == null)
+                {
+                    return;
+                }
+
+                string attributeName = attribute.Name.ToString();
+
+                if (this.attributeTemplate.Contains(attributeName))
+                {
+                    found = true;
+                }
+            }
+
+            if (!found)
             {
             {
                 return;
                 return;
             }
             }

+ 4 - 0
Share/Share.SourceGenerator/Share.SourceGenerator.csproj

@@ -26,4 +26,8 @@
         </PackageReference>
         </PackageReference>
     </ItemGroup>
     </ItemGroup>
 
 
+    <Target Name="AfterBuild">
+        <Copy SourceFiles="$(TargetDir)/$(TargetName).dll" DestinationFolder="$(ProjectDir)/../../Unity/Assets/Plugins/" ContinueOnError="false" />
+    </Target>
+
 </Project>
 </Project>

BIN
Unity/Assets/Plugins/Share.SourceGenerator.dll


+ 16 - 3
Unity/Assets/Scripts/Hotfix/Client/Demo/Move/M2C_PathfindingResultHandler.cs

@@ -2,10 +2,10 @@
 
 
 namespace ET.Client
 namespace ET.Client
 {
 {
-	[MessageHandler(SceneType.Demo)]
-	public class M2C_PathfindingResultHandler : AMHandler<M2C_PathfindingResult>
+	public static partial class M2C_PathfindingResultHandler
 	{
 	{
-		protected override async ETTask Run(Session session, M2C_PathfindingResult message)
+		[MessageHandler(SceneType.Demo)]
+		private static async ETTask Run(Session session, M2C_PathfindingResult message)
 		{
 		{
 			Unit unit = session.DomainScene().CurrentScene().GetComponent<UnitComponent>().Get(message.Id);
 			Unit unit = session.DomainScene().CurrentScene().GetComponent<UnitComponent>().Get(message.Id);
 
 
@@ -14,4 +14,17 @@ namespace ET.Client
 			await unit.GetComponent<MoveComponent>().MoveToAsync(message.Points, speed);
 			await unit.GetComponent<MoveComponent>().MoveToAsync(message.Points, speed);
 		}
 		}
 	}
 	}
+	
+	//[MessageHandler(SceneType.Demo)]
+	//public class M2C_PathfindingResultHandler : AMHandler<M2C_PathfindingResult>
+	//{
+	//	protected override async ETTask Run(Session session, M2C_PathfindingResult message)
+	//	{
+	//		Unit unit = session.DomainScene().CurrentScene().GetComponent<UnitComponent>().Get(message.Id);
+//
+	//		float speed = unit.GetComponent<NumericComponent>().GetAsFloat(NumericType.Speed);
+//
+	//		await unit.GetComponent<MoveComponent>().MoveToAsync(message.Points, speed);
+	//	}
+	//}
 }
 }

+ 4 - 4
Unity/Assets/Scripts/Hotfix/Server/Demo/Scenes/Benchmark/C2G_BenchmarkHandler.cs

@@ -2,11 +2,11 @@
 
 
 namespace ET.Server
 namespace ET.Server
 {
 {
-    [MessageHandler(SceneType.BenchmarkServer)]
-    public class C2G_BenchmarkHandler: AMRpcHandler<C2G_Benchmark, G2C_Benchmark>
+    public static partial class C2G_BenchmarkHandler
     {
     {
-        protected override async ETTask Run(Session session, C2G_Benchmark request, G2C_Benchmark response)
-        {            
+        [MessageRpcHandler(SceneType.BenchmarkServer)]
+        private static async ETTask Run(Session session, C2G_Benchmark request, G2C_Benchmark response)
+        {
             BenchmarkServerComponent benchmarkServerComponent = session.DomainScene().GetComponent<BenchmarkServerComponent>();
             BenchmarkServerComponent benchmarkServerComponent = session.DomainScene().GetComponent<BenchmarkServerComponent>();
             if (benchmarkServerComponent.Count++ % 1000000 == 0)
             if (benchmarkServerComponent.Count++ % 1000000 == 0)
             {
             {

+ 1 - 1
Unity/Assets/Scripts/Hotfix/Share/Module/Message/MessageDispatcherComponentSystem.cs

@@ -39,7 +39,7 @@ namespace ET
                     continue;
                     continue;
                 }
                 }
 
 
-                object[] attrs = type.GetCustomAttributes(typeof(MessageHandlerAttribute), false);
+                object[] attrs = type.GetCustomAttributes(typeof(MessageHandlerAttribute), true);
                 
                 
                 foreach (object attr in attrs)
                 foreach (object attr in attrs)
                 {
                 {

+ 7 - 1
Unity/Assets/Scripts/Model/Share/Module/Message/MessageHandlerAttribute.cs

@@ -2,7 +2,6 @@
 
 
 namespace ET
 namespace ET
 {
 {
-    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
     public class MessageHandlerAttribute: BaseAttribute
     public class MessageHandlerAttribute: BaseAttribute
     {
     {
         public SceneType SceneType { get; }
         public SceneType SceneType { get; }
@@ -12,4 +11,11 @@ namespace ET
             this.SceneType = sceneType;
             this.SceneType = sceneType;
         }
         }
     }
     }
+    
+    public class MessageRpcHandlerAttribute: MessageHandlerAttribute
+    {
+        public MessageRpcHandlerAttribute(SceneType sceneType): base(sceneType)
+        {
+        }
+    }
 }
 }