ExtensionMethods.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  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. internal 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 ITypeSymbol? 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. var childNode = child.AsNode()!;
  171. if (node is InterpolationSyntax && childNode is ExpressionSyntax)
  172. {
  173. ParenEnclosedFullQualifiedSyntax(childNode, sm, sb, isFirstNode: innerIsFirstNode);
  174. }
  175. else
  176. {
  177. FullQualifiedSyntax(childNode, sm, sb, isFirstNode: innerIsFirstNode);
  178. }
  179. innerIsFirstNode = false;
  180. }
  181. else
  182. {
  183. sb.Append(child);
  184. }
  185. if (child.HasTrailingTrivia)
  186. {
  187. sb.Append(child.GetTrailingTrivia());
  188. }
  189. }
  190. static void ParenEnclosedFullQualifiedSyntax(SyntaxNode node, SemanticModel sm, StringBuilder sb, bool isFirstNode)
  191. {
  192. sb.Append(SyntaxFactory.Token(SyntaxKind.OpenParenToken));
  193. FullQualifiedSyntax(node, sm, sb, isFirstNode);
  194. sb.Append(SyntaxFactory.Token(SyntaxKind.CloseParenToken));
  195. }
  196. }
  197. public static string SanitizeQualifiedNameForUniqueHint(this string qualifiedName)
  198. => qualifiedName
  199. // AddSource() doesn't support angle brackets
  200. .Replace("<", "(Of ")
  201. .Replace(">", ")");
  202. public static bool IsGodotExportAttribute(this INamedTypeSymbol symbol)
  203. => symbol.FullQualifiedNameOmitGlobal() == GodotClasses.ExportAttr;
  204. public static bool IsGodotSignalAttribute(this INamedTypeSymbol symbol)
  205. => symbol.FullQualifiedNameOmitGlobal() == GodotClasses.SignalAttr;
  206. public static bool IsGodotMustBeVariantAttribute(this INamedTypeSymbol symbol)
  207. => symbol.FullQualifiedNameOmitGlobal() == GodotClasses.MustBeVariantAttr;
  208. public static bool IsGodotClassNameAttribute(this INamedTypeSymbol symbol)
  209. => symbol.FullQualifiedNameOmitGlobal() == GodotClasses.GodotClassNameAttr;
  210. public static bool IsGodotGlobalClassAttribute(this INamedTypeSymbol symbol)
  211. => symbol.FullQualifiedNameOmitGlobal() == GodotClasses.GlobalClassAttr;
  212. public static bool IsSystemFlagsAttribute(this INamedTypeSymbol symbol)
  213. => symbol.FullQualifiedNameOmitGlobal() == GodotClasses.SystemFlagsAttr;
  214. public static GodotMethodData? HasGodotCompatibleSignature(
  215. this IMethodSymbol method,
  216. MarshalUtils.TypeCache typeCache
  217. )
  218. {
  219. if (method.IsGenericMethod)
  220. return null;
  221. var retSymbol = method.ReturnType;
  222. var retType = method.ReturnsVoid ?
  223. null :
  224. MarshalUtils.ConvertManagedTypeToMarshalType(method.ReturnType, typeCache);
  225. if (retType == null && !method.ReturnsVoid)
  226. return null;
  227. var parameters = method.Parameters;
  228. var paramTypes = parameters
  229. // Currently we don't support `ref`, `out`, `in`, `ref readonly` parameters (and we never may)
  230. .Where(p => p.RefKind == RefKind.None)
  231. // Attempt to determine the variant type
  232. .Select(p => MarshalUtils.ConvertManagedTypeToMarshalType(p.Type, typeCache))
  233. // Discard parameter types that couldn't be determined (null entries)
  234. .Where(t => t != null).Cast<MarshalType>().ToImmutableArray();
  235. // If any parameter type was incompatible, it was discarded so the length won't match
  236. if (parameters.Length > paramTypes.Length)
  237. return null; // Ignore incompatible method
  238. return new GodotMethodData(method, paramTypes,
  239. parameters.Select(p => p.Type).ToImmutableArray(),
  240. retType != null ? (retType.Value, retSymbol) : null);
  241. }
  242. public static IEnumerable<GodotMethodData> WhereHasGodotCompatibleSignature(
  243. this IEnumerable<IMethodSymbol> methods,
  244. MarshalUtils.TypeCache typeCache
  245. )
  246. {
  247. foreach (var method in methods)
  248. {
  249. var methodData = HasGodotCompatibleSignature(method, typeCache);
  250. if (methodData != null)
  251. yield return methodData.Value;
  252. }
  253. }
  254. public static IEnumerable<GodotPropertyData> WhereIsGodotCompatibleType(
  255. this IEnumerable<IPropertySymbol> properties,
  256. MarshalUtils.TypeCache typeCache
  257. )
  258. {
  259. foreach (var property in properties)
  260. {
  261. var marshalType = MarshalUtils.ConvertManagedTypeToMarshalType(property.Type, typeCache);
  262. if (marshalType == null)
  263. continue;
  264. yield return new GodotPropertyData(property, marshalType.Value);
  265. }
  266. }
  267. public static IEnumerable<GodotFieldData> WhereIsGodotCompatibleType(
  268. this IEnumerable<IFieldSymbol> fields,
  269. MarshalUtils.TypeCache typeCache
  270. )
  271. {
  272. foreach (var field in fields)
  273. {
  274. // TODO: We should still restore read-only fields after reloading assembly. Two possible ways: reflection or turn RestoreGodotObjectData into a constructor overload.
  275. var marshalType = MarshalUtils.ConvertManagedTypeToMarshalType(field.Type, typeCache);
  276. if (marshalType == null)
  277. continue;
  278. yield return new GodotFieldData(field, marshalType.Value);
  279. }
  280. }
  281. public static Location? FirstLocationWithSourceTreeOrDefault(this IEnumerable<Location> locations)
  282. {
  283. return locations.FirstOrDefault(location => location.SourceTree != null) ?? locations.FirstOrDefault();
  284. }
  285. public static string Path(this Location location)
  286. => location.SourceTree?.GetLineSpan(location.SourceSpan).Path
  287. ?? location.GetLineSpan().Path;
  288. public static int StartLine(this Location location)
  289. => location.SourceTree?.GetLineSpan(location.SourceSpan).StartLinePosition.Line
  290. ?? location.GetLineSpan().StartLinePosition.Line;
  291. }
  292. }