ExtensionMethods.cs 13 KB

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