ExtensionMethods.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  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. public static string NameWithTypeParameters(this INamedTypeSymbol symbol)
  123. {
  124. return symbol.IsGenericType ?
  125. string.Concat(symbol.Name, "<", string.Join(", ", symbol.TypeParameters), ">") :
  126. symbol.Name;
  127. }
  128. private static SymbolDisplayFormat FullyQualifiedFormatOmitGlobal { get; } =
  129. SymbolDisplayFormat.FullyQualifiedFormat
  130. .WithGlobalNamespaceStyle(SymbolDisplayGlobalNamespaceStyle.Omitted);
  131. private static SymbolDisplayFormat FullyQualifiedFormatIncludeGlobal { get; } =
  132. SymbolDisplayFormat.FullyQualifiedFormat
  133. .WithGlobalNamespaceStyle(SymbolDisplayGlobalNamespaceStyle.Included);
  134. public static string FullQualifiedNameOmitGlobal(this ITypeSymbol symbol)
  135. => symbol.ToDisplayString(NullableFlowState.NotNull, FullyQualifiedFormatOmitGlobal);
  136. public static string FullQualifiedNameOmitGlobal(this INamespaceSymbol namespaceSymbol)
  137. => namespaceSymbol.ToDisplayString(FullyQualifiedFormatOmitGlobal);
  138. public static string FullQualifiedNameIncludeGlobal(this ITypeSymbol symbol)
  139. => symbol.ToDisplayString(NullableFlowState.NotNull, FullyQualifiedFormatIncludeGlobal);
  140. public static string FullQualifiedNameIncludeGlobal(this INamespaceSymbol namespaceSymbol)
  141. => namespaceSymbol.ToDisplayString(FullyQualifiedFormatIncludeGlobal);
  142. public static string FullQualifiedSyntax(this SyntaxNode node, SemanticModel sm)
  143. {
  144. StringBuilder sb = new();
  145. FullQualifiedSyntax(node, sm, sb, true);
  146. return sb.ToString();
  147. }
  148. private static void FullQualifiedSyntax(SyntaxNode node, SemanticModel sm, StringBuilder sb, bool isFirstNode)
  149. {
  150. if (node is NameSyntax ns && isFirstNode)
  151. {
  152. SymbolInfo nameInfo = sm.GetSymbolInfo(ns);
  153. sb.Append(nameInfo.Symbol?.ToDisplayString(FullyQualifiedFormatIncludeGlobal) ?? ns.ToString());
  154. return;
  155. }
  156. bool innerIsFirstNode = true;
  157. foreach (var child in node.ChildNodesAndTokens())
  158. {
  159. if (child.HasLeadingTrivia)
  160. {
  161. sb.Append(child.GetLeadingTrivia());
  162. }
  163. if (child.IsNode)
  164. {
  165. FullQualifiedSyntax(child.AsNode()!, sm, sb, isFirstNode: innerIsFirstNode);
  166. innerIsFirstNode = false;
  167. }
  168. else
  169. {
  170. sb.Append(child);
  171. }
  172. if (child.HasTrailingTrivia)
  173. {
  174. sb.Append(child.GetTrailingTrivia());
  175. }
  176. }
  177. }
  178. public static string SanitizeQualifiedNameForUniqueHint(this string qualifiedName)
  179. => qualifiedName
  180. // AddSource() doesn't support angle brackets
  181. .Replace("<", "(Of ")
  182. .Replace(">", ")");
  183. public static bool IsGodotExportAttribute(this INamedTypeSymbol symbol)
  184. => symbol.ToString() == GodotClasses.ExportAttr;
  185. public static bool IsGodotSignalAttribute(this INamedTypeSymbol symbol)
  186. => symbol.ToString() == GodotClasses.SignalAttr;
  187. public static bool IsGodotMustBeVariantAttribute(this INamedTypeSymbol symbol)
  188. => symbol.ToString() == GodotClasses.MustBeVariantAttr;
  189. public static bool IsGodotClassNameAttribute(this INamedTypeSymbol symbol)
  190. => symbol.ToString() == GodotClasses.GodotClassNameAttr;
  191. public static bool IsSystemFlagsAttribute(this INamedTypeSymbol symbol)
  192. => symbol.ToString() == GodotClasses.SystemFlagsAttr;
  193. public static GodotMethodData? HasGodotCompatibleSignature(
  194. this IMethodSymbol method,
  195. MarshalUtils.TypeCache typeCache
  196. )
  197. {
  198. if (method.IsGenericMethod)
  199. return null;
  200. var retSymbol = method.ReturnType;
  201. var retType = method.ReturnsVoid ?
  202. null :
  203. MarshalUtils.ConvertManagedTypeToMarshalType(method.ReturnType, typeCache);
  204. if (retType == null && !method.ReturnsVoid)
  205. return null;
  206. var parameters = method.Parameters;
  207. var paramTypes = parameters
  208. // Currently we don't support `ref`, `out`, `in`, `ref readonly` parameters (and we never may)
  209. .Where(p => p.RefKind == RefKind.None)
  210. // Attempt to determine the variant type
  211. .Select(p => MarshalUtils.ConvertManagedTypeToMarshalType(p.Type, typeCache))
  212. // Discard parameter types that couldn't be determined (null entries)
  213. .Where(t => t != null).Cast<MarshalType>().ToImmutableArray();
  214. // If any parameter type was incompatible, it was discarded so the length won't match
  215. if (parameters.Length > paramTypes.Length)
  216. return null; // Ignore incompatible method
  217. return new GodotMethodData(method, paramTypes, parameters
  218. .Select(p => p.Type).ToImmutableArray(), retType, retSymbol);
  219. }
  220. public static IEnumerable<GodotMethodData> WhereHasGodotCompatibleSignature(
  221. this IEnumerable<IMethodSymbol> methods,
  222. MarshalUtils.TypeCache typeCache
  223. )
  224. {
  225. foreach (var method in methods)
  226. {
  227. var methodData = HasGodotCompatibleSignature(method, typeCache);
  228. if (methodData != null)
  229. yield return methodData.Value;
  230. }
  231. }
  232. public static IEnumerable<GodotPropertyData> WhereIsGodotCompatibleType(
  233. this IEnumerable<IPropertySymbol> properties,
  234. MarshalUtils.TypeCache typeCache
  235. )
  236. {
  237. foreach (var property in properties)
  238. {
  239. // TODO: We should still restore read-only properties after reloading assembly. Two possible ways: reflection or turn RestoreGodotObjectData into a constructor overload.
  240. // Ignore properties without a getter or without a setter. Godot properties must be both readable and writable.
  241. if (property.IsWriteOnly || property.IsReadOnly)
  242. continue;
  243. var marshalType = MarshalUtils.ConvertManagedTypeToMarshalType(property.Type, typeCache);
  244. if (marshalType == null)
  245. continue;
  246. yield return new GodotPropertyData(property, marshalType.Value);
  247. }
  248. }
  249. public static IEnumerable<GodotFieldData> WhereIsGodotCompatibleType(
  250. this IEnumerable<IFieldSymbol> fields,
  251. MarshalUtils.TypeCache typeCache
  252. )
  253. {
  254. foreach (var field in fields)
  255. {
  256. // TODO: We should still restore read-only fields after reloading assembly. Two possible ways: reflection or turn RestoreGodotObjectData into a constructor overload.
  257. // Ignore properties without a getter or without a setter. Godot properties must be both readable and writable.
  258. if (field.IsReadOnly)
  259. continue;
  260. var marshalType = MarshalUtils.ConvertManagedTypeToMarshalType(field.Type, typeCache);
  261. if (marshalType == null)
  262. continue;
  263. yield return new GodotFieldData(field, marshalType.Value);
  264. }
  265. }
  266. public static string Path(this Location location)
  267. => location.SourceTree?.GetLineSpan(location.SourceSpan).Path
  268. ?? location.GetLineSpan().Path;
  269. public static int StartLine(this Location location)
  270. => location.SourceTree?.GetLineSpan(location.SourceSpan).StartLinePosition.Line
  271. ?? location.GetLineSpan().StartLinePosition.Line;
  272. }
  273. }