ExtensionMethods.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.Immutable;
  4. using System.Linq;
  5. using System.Text;
  6. using Microsoft.CodeAnalysis;
  7. using Microsoft.CodeAnalysis.CSharp;
  8. using Microsoft.CodeAnalysis.CSharp.Syntax;
  9. namespace Godot.SourceGenerators
  10. {
  11. static class ExtensionMethods
  12. {
  13. public static bool TryGetGlobalAnalyzerProperty(
  14. this GeneratorExecutionContext context, string property, out string? value
  15. ) => context.AnalyzerConfigOptions.GlobalOptions
  16. .TryGetValue("build_property." + property, out value);
  17. public static bool AreGodotSourceGeneratorsDisabled(this GeneratorExecutionContext context)
  18. => context.TryGetGlobalAnalyzerProperty("GodotSourceGenerators", out string? toggle) &&
  19. toggle != null &&
  20. toggle.Equals("disabled", StringComparison.OrdinalIgnoreCase);
  21. public static bool IsGodotToolsProject(this GeneratorExecutionContext context)
  22. => context.TryGetGlobalAnalyzerProperty("IsGodotToolsProject", out string? toggle) &&
  23. toggle != null &&
  24. toggle.Equals("true", StringComparison.OrdinalIgnoreCase);
  25. public static bool InheritsFrom(this INamedTypeSymbol? symbol, string assemblyName, string typeFullName)
  26. {
  27. while (symbol != null)
  28. {
  29. if (symbol.ContainingAssembly?.Name == assemblyName &&
  30. symbol.ToString() == typeFullName)
  31. {
  32. return true;
  33. }
  34. symbol = symbol.BaseType;
  35. }
  36. return false;
  37. }
  38. public static INamedTypeSymbol? GetGodotScriptNativeClass(this INamedTypeSymbol classTypeSymbol)
  39. {
  40. var symbol = classTypeSymbol;
  41. while (symbol != null)
  42. {
  43. if (symbol.ContainingAssembly?.Name == "GodotSharp")
  44. return symbol;
  45. symbol = symbol.BaseType;
  46. }
  47. return null;
  48. }
  49. public static string? GetGodotScriptNativeClassName(this INamedTypeSymbol classTypeSymbol)
  50. {
  51. var nativeType = classTypeSymbol.GetGodotScriptNativeClass();
  52. if (nativeType == null)
  53. return null;
  54. var godotClassNameAttr = nativeType.GetAttributes()
  55. .FirstOrDefault(a => a.AttributeClass?.IsGodotClassNameAttribute() ?? false);
  56. string? godotClassName = null;
  57. if (godotClassNameAttr is { ConstructorArguments: { Length: > 0 } })
  58. godotClassName = godotClassNameAttr.ConstructorArguments[0].Value?.ToString();
  59. return godotClassName ?? nativeType.Name;
  60. }
  61. private static bool IsGodotScriptClass(
  62. this ClassDeclarationSyntax cds, Compilation compilation,
  63. out INamedTypeSymbol? symbol
  64. )
  65. {
  66. var sm = compilation.GetSemanticModel(cds.SyntaxTree);
  67. var classTypeSymbol = sm.GetDeclaredSymbol(cds);
  68. if (classTypeSymbol?.BaseType == null
  69. || !classTypeSymbol.BaseType.InheritsFrom("GodotSharp", GodotClasses.Object))
  70. {
  71. symbol = null;
  72. return false;
  73. }
  74. symbol = classTypeSymbol;
  75. return true;
  76. }
  77. public static IEnumerable<(ClassDeclarationSyntax cds, INamedTypeSymbol symbol)> SelectGodotScriptClasses(
  78. this IEnumerable<ClassDeclarationSyntax> source,
  79. Compilation compilation
  80. )
  81. {
  82. foreach (var cds in source)
  83. {
  84. if (cds.IsGodotScriptClass(compilation, out var symbol))
  85. yield return (cds, symbol!);
  86. }
  87. }
  88. public static bool IsNested(this TypeDeclarationSyntax cds)
  89. => cds.Parent is TypeDeclarationSyntax;
  90. public static bool IsPartial(this TypeDeclarationSyntax cds)
  91. => cds.Modifiers.Any(SyntaxKind.PartialKeyword);
  92. public static bool AreAllOuterTypesPartial(
  93. this TypeDeclarationSyntax cds,
  94. out TypeDeclarationSyntax? typeMissingPartial
  95. )
  96. {
  97. SyntaxNode? outerSyntaxNode = cds.Parent;
  98. while (outerSyntaxNode is TypeDeclarationSyntax outerTypeDeclSyntax)
  99. {
  100. if (!outerTypeDeclSyntax.IsPartial())
  101. {
  102. typeMissingPartial = outerTypeDeclSyntax;
  103. return false;
  104. }
  105. outerSyntaxNode = outerSyntaxNode.Parent;
  106. }
  107. typeMissingPartial = null;
  108. return true;
  109. }
  110. public static string GetDeclarationKeyword(this INamedTypeSymbol namedTypeSymbol)
  111. {
  112. string? keyword = namedTypeSymbol.DeclaringSyntaxReferences
  113. .OfType<TypeDeclarationSyntax>().FirstOrDefault()?
  114. .Keyword.Text;
  115. return keyword ?? namedTypeSymbol.TypeKind switch
  116. {
  117. TypeKind.Interface => "interface",
  118. TypeKind.Struct => "struct",
  119. _ => "class"
  120. };
  121. }
  122. private static SymbolDisplayFormat FullyQualifiedFormatOmitGlobal { get; } =
  123. SymbolDisplayFormat.FullyQualifiedFormat
  124. .WithGlobalNamespaceStyle(SymbolDisplayGlobalNamespaceStyle.Omitted);
  125. public static string FullQualifiedName(this ITypeSymbol symbol)
  126. => symbol.ToDisplayString(NullableFlowState.NotNull, FullyQualifiedFormatOmitGlobal);
  127. public static string NameWithTypeParameters(this INamedTypeSymbol symbol)
  128. {
  129. return symbol.IsGenericType ?
  130. string.Concat(symbol.Name, "<", string.Join(", ", symbol.TypeParameters), ">") :
  131. symbol.Name;
  132. }
  133. public static string FullQualifiedName(this INamespaceSymbol namespaceSymbol)
  134. => namespaceSymbol.ToDisplayString(FullyQualifiedFormatOmitGlobal);
  135. public static string FullQualifiedName(this ISymbol symbol)
  136. => symbol.ToDisplayString(FullyQualifiedFormatOmitGlobal);
  137. public static string FullQualifiedSyntax(this SyntaxNode node, SemanticModel sm)
  138. {
  139. StringBuilder sb = new();
  140. FullQualifiedSyntax_(node, sm, sb, true);
  141. return sb.ToString();
  142. }
  143. private static void FullQualifiedSyntax_(SyntaxNode node, SemanticModel sm, StringBuilder sb, bool isFirstNode)
  144. {
  145. if (node is NameSyntax ns && isFirstNode)
  146. {
  147. SymbolInfo nameInfo = sm.GetSymbolInfo(ns);
  148. sb.Append(nameInfo.Symbol?.FullQualifiedName() ?? ns.ToString());
  149. return;
  150. }
  151. bool innerIsFirstNode = true;
  152. foreach (var child in node.ChildNodesAndTokens())
  153. {
  154. if (child.HasLeadingTrivia)
  155. {
  156. sb.Append(child.GetLeadingTrivia());
  157. }
  158. if (child.IsNode)
  159. {
  160. FullQualifiedSyntax_(child.AsNode()!, sm, sb, isFirstNode: innerIsFirstNode);
  161. innerIsFirstNode = false;
  162. }
  163. else
  164. {
  165. sb.Append(child);
  166. }
  167. if (child.HasTrailingTrivia)
  168. {
  169. sb.Append(child.GetTrailingTrivia());
  170. }
  171. }
  172. }
  173. public static string SanitizeQualifiedNameForUniqueHint(this string qualifiedName)
  174. => qualifiedName
  175. // AddSource() doesn't support angle brackets
  176. .Replace("<", "(Of ")
  177. .Replace(">", ")");
  178. public static bool IsGodotExportAttribute(this INamedTypeSymbol symbol)
  179. => symbol.ToString() == GodotClasses.ExportAttr;
  180. public static bool IsGodotSignalAttribute(this INamedTypeSymbol symbol)
  181. => symbol.ToString() == GodotClasses.SignalAttr;
  182. public static bool IsGodotMustBeVariantAttribute(this INamedTypeSymbol symbol)
  183. => symbol.ToString() == GodotClasses.MustBeVariantAttr;
  184. public static bool IsGodotClassNameAttribute(this INamedTypeSymbol symbol)
  185. => symbol.ToString() == GodotClasses.GodotClassNameAttr;
  186. public static bool IsSystemFlagsAttribute(this INamedTypeSymbol symbol)
  187. => symbol.ToString() == GodotClasses.SystemFlagsAttr;
  188. public static GodotMethodData? HasGodotCompatibleSignature(
  189. this IMethodSymbol method,
  190. MarshalUtils.TypeCache typeCache
  191. )
  192. {
  193. if (method.IsGenericMethod)
  194. return null;
  195. var retSymbol = method.ReturnType;
  196. var retType = method.ReturnsVoid ?
  197. null :
  198. MarshalUtils.ConvertManagedTypeToMarshalType(method.ReturnType, typeCache);
  199. if (retType == null && !method.ReturnsVoid)
  200. return null;
  201. var parameters = method.Parameters;
  202. var paramTypes = parameters
  203. // Currently we don't support `ref`, `out`, `in`, `ref readonly` parameters (and we never may)
  204. .Where(p => p.RefKind == RefKind.None)
  205. // Attempt to determine the variant type
  206. .Select(p => MarshalUtils.ConvertManagedTypeToMarshalType(p.Type, typeCache))
  207. // Discard parameter types that couldn't be determined (null entries)
  208. .Where(t => t != null).Cast<MarshalType>().ToImmutableArray();
  209. // If any parameter type was incompatible, it was discarded so the length won't match
  210. if (parameters.Length > paramTypes.Length)
  211. return null; // Ignore incompatible method
  212. return new GodotMethodData(method, paramTypes, parameters
  213. .Select(p => p.Type).ToImmutableArray(), retType, retSymbol);
  214. }
  215. public static IEnumerable<GodotMethodData> WhereHasGodotCompatibleSignature(
  216. this IEnumerable<IMethodSymbol> methods,
  217. MarshalUtils.TypeCache typeCache
  218. )
  219. {
  220. foreach (var method in methods)
  221. {
  222. var methodData = HasGodotCompatibleSignature(method, typeCache);
  223. if (methodData != null)
  224. yield return methodData.Value;
  225. }
  226. }
  227. public static IEnumerable<GodotPropertyData> WhereIsGodotCompatibleType(
  228. this IEnumerable<IPropertySymbol> properties,
  229. MarshalUtils.TypeCache typeCache
  230. )
  231. {
  232. foreach (var property in properties)
  233. {
  234. // TODO: We should still restore read-only properties after reloading assembly. Two possible ways: reflection or turn RestoreGodotObjectData into a constructor overload.
  235. // Ignore properties without a getter or without a setter. Godot properties must be both readable and writable.
  236. if (property.IsWriteOnly || property.IsReadOnly)
  237. continue;
  238. var marshalType = MarshalUtils.ConvertManagedTypeToMarshalType(property.Type, typeCache);
  239. if (marshalType == null)
  240. continue;
  241. yield return new GodotPropertyData(property, marshalType.Value);
  242. }
  243. }
  244. public static IEnumerable<GodotFieldData> WhereIsGodotCompatibleType(
  245. this IEnumerable<IFieldSymbol> fields,
  246. MarshalUtils.TypeCache typeCache
  247. )
  248. {
  249. foreach (var field in fields)
  250. {
  251. // TODO: We should still restore read-only fields after reloading assembly. Two possible ways: reflection or turn RestoreGodotObjectData into a constructor overload.
  252. // Ignore properties without a getter or without a setter. Godot properties must be both readable and writable.
  253. if (field.IsReadOnly)
  254. continue;
  255. var marshalType = MarshalUtils.ConvertManagedTypeToMarshalType(field.Type, typeCache);
  256. if (marshalType == null)
  257. continue;
  258. yield return new GodotFieldData(field, marshalType.Value);
  259. }
  260. }
  261. public static string Path(this Location location)
  262. => location.SourceTree?.GetLineSpan(location.SourceSpan).Path
  263. ?? location.GetLineSpan().Path;
  264. public static int StartLine(this Location location)
  265. => location.SourceTree?.GetLineSpan(location.SourceSpan).StartLinePosition.Line
  266. ?? location.GetLineSpan().StartLinePosition.Line;
  267. }
  268. }