Helpers.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using System.Text;
  4. using System.Threading;
  5. using Microsoft.CodeAnalysis;
  6. using Microsoft.CodeAnalysis.CSharp.Syntax;
  7. namespace PixiEditor.ChangeableDocument.Gen;
  8. internal static class Helpers
  9. {
  10. private static SymbolDisplayFormat typeWithGenerics =
  11. new SymbolDisplayFormat(genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters | SymbolDisplayGenericsOptions.IncludeTypeConstraints);
  12. public static string CreateMakeChangeAction(MethodInfo changeConstructorInfo)
  13. {
  14. string actionName = changeConstructorInfo.ContainingClass.Name.Split('_')[0] + "_Action";
  15. List<TypeWithName> constructorArgs = changeConstructorInfo.Arguments;
  16. List<TypeWithName> properties = constructorArgs.Select(static typeWithName =>
  17. {
  18. return new TypeWithName(typeWithName.Type, typeWithName.FullNamespace, VariableNameIntoPropertyName(typeWithName.Name), typeWithName.Nullable);
  19. }).ToList();
  20. var propToVar = MatchMembers(properties, constructorArgs);
  21. StringBuilder sb = new();
  22. sb.AppendLine("namespace PixiEditor.ChangeableDocument.Actions.Generated;\n");
  23. sb.AppendLine("[System.Runtime.CompilerServices.CompilerGenerated]");
  24. sb.AppendLine($"public record class {actionName} : PixiEditor.ChangeableDocument.Actions.IMakeChangeAction");
  25. sb.AppendLine("{");
  26. sb.Append($"public {actionName}");
  27. AppendArgumentList(sb, constructorArgs);
  28. AppendConstructorBody(sb, propToVar);
  29. sb.AppendLine("// Properties");
  30. AppendProperties(sb, properties);
  31. sb.AppendLine("// Changes");
  32. AppendCreateCorrespondingChange(sb, changeConstructorInfo.ContainingClass, properties);
  33. sb.AppendLine("}");
  34. return sb.ToString();
  35. }
  36. public static Result<string> CreateStartUpdateChangeAction
  37. (MethodInfo changeConstructorInfo, MethodInfo updateMethodInfo, ClassDeclarationSyntax containingClass, bool isCancelable)
  38. {
  39. string actionName = changeConstructorInfo.ContainingClass.Name.Split('_')[0] + "_Action";
  40. List<TypeWithName> constructorArgs = changeConstructorInfo.Arguments;
  41. List<TypeWithName> properties = constructorArgs.Select(static typeWithName =>
  42. {
  43. return new TypeWithName(typeWithName.Type, typeWithName.FullNamespace, VariableNameIntoPropertyName(typeWithName.Name), typeWithName.Nullable);
  44. }).ToList();
  45. var constructorAssignments = MatchMembers(properties, constructorArgs);
  46. var updatePropsToPass = MatchMembers(updateMethodInfo.Arguments, properties).Select(pair => pair.Item2).ToList();
  47. if (updatePropsToPass.Count != updateMethodInfo.Arguments.Count)
  48. return Result<string>.Error("Couldn't match update method arguments with constructor arguments", containingClass.SyntaxTree, containingClass.Span);
  49. StringBuilder sb = new();
  50. sb.AppendLine("namespace PixiEditor.ChangeableDocument.Actions.Generated;");
  51. sb.AppendLine($"public record class {actionName} : PixiEditor.ChangeableDocument.Actions.IStartOrUpdateChangeAction" + (isCancelable ? ", PixiEditor.ChangeableDocument.Actions.ICancelableAction" : ""));
  52. sb.AppendLine("{");
  53. sb.Append($"public {actionName}");
  54. AppendArgumentList(sb, constructorArgs);
  55. AppendConstructorBody(sb, constructorAssignments);
  56. AppendProperties(sb, properties);
  57. AppendCreateUpdateableCorrespondingChange(sb, changeConstructorInfo.ContainingClass, properties);
  58. AppendUpdateCorrespondingChange(sb, updateMethodInfo.Name, changeConstructorInfo.ContainingClass, updatePropsToPass);
  59. sb.AppendLine($@"
  60. bool PixiEditor.ChangeableDocument.Actions.IStartOrUpdateChangeAction.IsChangeTypeMatching(PixiEditor.ChangeableDocument.Changes.Change change)
  61. {{
  62. return change is {changeConstructorInfo.ContainingClass.NameWithNamespace};
  63. }}
  64. ");
  65. sb.AppendLine("}");
  66. return sb.ToString();
  67. }
  68. public static string CreateEndChangeAction(MethodInfo changeConstructorInfo)
  69. {
  70. string actionName = "End" + changeConstructorInfo.ContainingClass.Name.Split('_')[0] + "_Action";
  71. return
  72. $@"namespace PixiEditor.ChangeableDocument.Actions.Generated;
  73. public record class {actionName} : PixiEditor.ChangeableDocument.Actions.IEndChangeAction
  74. {{
  75. bool PixiEditor.ChangeableDocument.Actions.IEndChangeAction.IsChangeTypeMatching(PixiEditor.ChangeableDocument.Changes.Change change)
  76. {{
  77. return change is {changeConstructorInfo.ContainingClass.NameWithNamespace};
  78. }}
  79. }}
  80. ";
  81. }
  82. public static MethodInfo ExtractMethodInfo(IMethodSymbol method)
  83. {
  84. List<TypeWithName> variables = method.Parameters.Select(static parameter =>
  85. {
  86. return new TypeWithName(
  87. parameter.Type.ToDisplayString(typeWithGenerics),
  88. parameter.Type.ContainingNamespace.ToDisplayString(),
  89. parameter.Name,
  90. parameter.NullableAnnotation is NullableAnnotation.Annotated
  91. );
  92. }).ToList();
  93. string changeName = method.ContainingType.Name;
  94. string changeFullNamespace = method.ContainingNamespace.ToDisplayString();
  95. return new MethodInfo(method.Name, variables, new NamespacedType(changeName, changeFullNamespace));
  96. }
  97. private static void AppendConstructorBody(StringBuilder sb, List<(TypeWithName, TypeWithName)> assignments)
  98. {
  99. sb.AppendLine("{");
  100. foreach (var (property, variable) in assignments)
  101. {
  102. sb.Append("this.").Append(property.Name).Append(" = ").Append(variable.Name).AppendLine(";");
  103. }
  104. sb.AppendLine("}");
  105. }
  106. private static List<(TypeWithName, TypeWithName)> MatchMembers(List<TypeWithName> list1, List<TypeWithName> list2)
  107. {
  108. List<(TypeWithName, TypeWithName)> paired = new();
  109. for (int i = list1.Count - 1; i >= 0; i--)
  110. {
  111. for (int j = list2.Count - 1; j >= 0; j--)
  112. {
  113. if (list1[i].TypeWithNamespace == list2[j].TypeWithNamespace &&
  114. list1[i].Name.ToLower() == list2[j].Name.ToLower())
  115. {
  116. paired.Add((list1[i], list2[j]));
  117. }
  118. }
  119. }
  120. paired.Reverse();
  121. return paired;
  122. }
  123. private static void AppendArgumentList(StringBuilder sb, List<TypeWithName> variables)
  124. {
  125. sb.Append("(");
  126. for (int i = 0; i < variables.Count; i++)
  127. {
  128. sb.Append(variables[i].TypeWithNamespace);
  129. if (variables[i].Nullable)
  130. {
  131. sb.Append("?");
  132. }
  133. sb.Append(" ").Append(variables[i].Name);
  134. if (i != variables.Count - 1)
  135. sb.Append(", ");
  136. }
  137. sb.AppendLine(")");
  138. }
  139. private static void AppendUpdateCorrespondingChange
  140. (StringBuilder sb, string updateMethodName, NamespacedType corrChangeType, List<TypeWithName> propertiesToPass)
  141. {
  142. sb.AppendLine("void PixiEditor.ChangeableDocument.Actions.IStartOrUpdateChangeAction.UpdateCorrespodingChange(PixiEditor.ChangeableDocument.Changes.UpdateableChange change)");
  143. sb.AppendLine("{");
  144. sb.Append($"(({corrChangeType.NameWithNamespace})change).{updateMethodName}(");
  145. for (int i = 0; i < propertiesToPass.Count; i++)
  146. {
  147. sb.Append(propertiesToPass[i].Name);
  148. if (i != propertiesToPass.Count - 1)
  149. sb.Append(", ");
  150. }
  151. sb.AppendLine(");");
  152. sb.AppendLine("}");
  153. }
  154. private static void AppendCreateUpdateableCorrespondingChange
  155. (StringBuilder sb, NamespacedType corrChangeType, List<TypeWithName> propertiesToPass)
  156. {
  157. sb.AppendLine("PixiEditor.ChangeableDocument.Changes.UpdateableChange PixiEditor.ChangeableDocument.Actions.IStartOrUpdateChangeAction.CreateCorrespondingChange()");
  158. sb.AppendLine("{");
  159. sb.Append($"return new {corrChangeType.NameWithNamespace}(");
  160. for (int i = 0; i < propertiesToPass.Count; i++)
  161. {
  162. sb.Append(propertiesToPass[i].Name);
  163. if (i != propertiesToPass.Count - 1)
  164. sb.Append(", ");
  165. }
  166. sb.AppendLine(");");
  167. sb.AppendLine("}");
  168. }
  169. private static void AppendCreateCorrespondingChange
  170. (StringBuilder sb, NamespacedType corrChangeType, List<TypeWithName> propertiesToPass)
  171. {
  172. sb.AppendLine("PixiEditor.ChangeableDocument.Changes.Change PixiEditor.ChangeableDocument.Actions.IMakeChangeAction.CreateCorrespondingChange()");
  173. sb.AppendLine("{");
  174. sb.Append($"return new {corrChangeType.NameWithNamespace}(");
  175. for (int i = 0; i < propertiesToPass.Count; i++)
  176. {
  177. sb.Append(propertiesToPass[i].Name);
  178. if (i != propertiesToPass.Count - 1)
  179. sb.Append(", ");
  180. }
  181. sb.AppendLine(");");
  182. sb.AppendLine("}");
  183. }
  184. private static void AppendProperties(StringBuilder sb, List<TypeWithName> properties)
  185. {
  186. foreach (var typeWithName in properties)
  187. {
  188. sb.AppendLine($"public {typeWithName.TypeWithNamespace}{(typeWithName.Nullable ? "?" : "")} {typeWithName.Name} {{ get; init; }}");
  189. }
  190. }
  191. private static string VariableNameIntoPropertyName(string varName)
  192. {
  193. string lowerCaseName = varName.Substring(0, 1).ToUpperInvariant() + varName.Substring(1);
  194. return lowerCaseName;
  195. }
  196. public static bool IsConstructorWithAttribute(SyntaxNode node, CancellationToken token)
  197. {
  198. return node is ConstructorDeclarationSyntax constructor && constructor.AttributeLists.Count > 0;
  199. }
  200. public static bool IsMethodWithAttribute(SyntaxNode node, CancellationToken token)
  201. {
  202. return node is MethodDeclarationSyntax method && method.AttributeLists.Count > 0;
  203. }
  204. public static bool IsInheritedFrom(INamedTypeSymbol classSymbol, NamespacedType type)
  205. {
  206. while (classSymbol.BaseType is not null)
  207. {
  208. if (classSymbol.BaseType.ToDisplayString() == type.NameWithNamespace)
  209. return true;
  210. classSymbol = classSymbol.BaseType;
  211. }
  212. return false;
  213. }
  214. public static bool MethodHasAttribute
  215. (GeneratorSyntaxContext context, CancellationToken cancelToken, BaseMethodDeclarationSyntax method, NamespacedType attributeType)
  216. {
  217. foreach (var attrList in method.AttributeLists)
  218. {
  219. foreach (var attribute in attrList.Attributes)
  220. {
  221. cancelToken.ThrowIfCancellationRequested();
  222. var symbol = context.SemanticModel.GetSymbolInfo(attribute, cancelToken);
  223. if (symbol.Symbol is not IMethodSymbol methodSymbol)
  224. continue;
  225. if (methodSymbol.ContainingType.ToDisplayString() != attributeType.NameWithNamespace)
  226. continue;
  227. return true;
  228. }
  229. }
  230. return false;
  231. }
  232. }