ExtensionMethods.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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 GetAccessibilityKeyword(this INamedTypeSymbol namedTypeSymbol)
  128. {
  129. if (namedTypeSymbol.DeclaredAccessibility == Accessibility.NotApplicable)
  130. {
  131. // Accessibility not specified. Get the default accessibility.
  132. return namedTypeSymbol.ContainingSymbol switch
  133. {
  134. null or INamespaceSymbol => "internal",
  135. ITypeSymbol { TypeKind: TypeKind.Class or TypeKind.Struct } => "private",
  136. ITypeSymbol { TypeKind: TypeKind.Interface } => "public",
  137. _ => "",
  138. };
  139. }
  140. return namedTypeSymbol.DeclaredAccessibility switch
  141. {
  142. Accessibility.Private => "private",
  143. Accessibility.Protected => "protected",
  144. Accessibility.Internal => "internal",
  145. Accessibility.ProtectedAndInternal => "private",
  146. Accessibility.ProtectedOrInternal => "private",
  147. Accessibility.Public => "public",
  148. _ => "",
  149. };
  150. }
  151. private static SymbolDisplayFormat FullyQualifiedFormatOmitGlobal { get; } =
  152. SymbolDisplayFormat.FullyQualifiedFormat
  153. .WithGlobalNamespaceStyle(SymbolDisplayGlobalNamespaceStyle.Omitted)
  154. .WithMemberOptions(SymbolDisplayMemberOptions.IncludeContainingType);
  155. private static SymbolDisplayFormat FullyQualifiedFormatIncludeGlobal { get; } =
  156. SymbolDisplayFormat.FullyQualifiedFormat
  157. .WithGlobalNamespaceStyle(SymbolDisplayGlobalNamespaceStyle.Included)
  158. .WithMemberOptions(SymbolDisplayMemberOptions.IncludeContainingType);
  159. public static string FullQualifiedNameOmitGlobal(this ITypeSymbol symbol)
  160. => symbol.ToDisplayString(NullableFlowState.NotNull, FullyQualifiedFormatOmitGlobal);
  161. public static string FullQualifiedNameOmitGlobal(this INamespaceSymbol namespaceSymbol)
  162. => namespaceSymbol.ToDisplayString(FullyQualifiedFormatOmitGlobal);
  163. public static string FullQualifiedNameIncludeGlobal(this ITypeSymbol symbol)
  164. => symbol.ToDisplayString(NullableFlowState.NotNull, FullyQualifiedFormatIncludeGlobal);
  165. public static string FullQualifiedNameIncludeGlobal(this INamespaceSymbol namespaceSymbol)
  166. => namespaceSymbol.ToDisplayString(FullyQualifiedFormatIncludeGlobal);
  167. public static string FullQualifiedSyntax(this SyntaxNode node, SemanticModel sm)
  168. {
  169. StringBuilder sb = new();
  170. FullQualifiedSyntax(node, sm, sb, true);
  171. return sb.ToString();
  172. }
  173. private static void FullQualifiedSyntax(SyntaxNode node, SemanticModel sm, StringBuilder sb, bool isFirstNode)
  174. {
  175. if (node is NameSyntax ns)
  176. {
  177. bool isMemberAccess = !isFirstNode && node.Parent is MemberAccessExpressionSyntax;
  178. bool isInitializer = isFirstNode && node.Parent is AssignmentExpressionSyntax { Parent: InitializerExpressionSyntax };
  179. if (!isMemberAccess && !isInitializer)
  180. {
  181. SymbolInfo nameInfo = sm.GetSymbolInfo(ns);
  182. sb.Append(nameInfo.Symbol?.ToDisplayString(FullyQualifiedFormatIncludeGlobal) ?? ns.ToString());
  183. return;
  184. }
  185. }
  186. bool innerIsFirstNode = true;
  187. foreach (var child in node.ChildNodesAndTokens())
  188. {
  189. if (child.HasLeadingTrivia)
  190. {
  191. sb.Append(child.GetLeadingTrivia());
  192. }
  193. if (child.IsNode)
  194. {
  195. var childNode = child.AsNode()!;
  196. if (node is InterpolationSyntax && childNode is ExpressionSyntax)
  197. {
  198. ParenEnclosedFullQualifiedSyntax(childNode, sm, sb, isFirstNode: innerIsFirstNode);
  199. }
  200. else
  201. {
  202. FullQualifiedSyntax(childNode, sm, sb, isFirstNode: innerIsFirstNode);
  203. }
  204. innerIsFirstNode = false;
  205. }
  206. else
  207. {
  208. sb.Append(child);
  209. }
  210. if (child.HasTrailingTrivia)
  211. {
  212. sb.Append(child.GetTrailingTrivia());
  213. }
  214. }
  215. static void ParenEnclosedFullQualifiedSyntax(SyntaxNode node, SemanticModel sm, StringBuilder sb, bool isFirstNode)
  216. {
  217. sb.Append(SyntaxFactory.Token(SyntaxKind.OpenParenToken));
  218. FullQualifiedSyntax(node, sm, sb, isFirstNode);
  219. sb.Append(SyntaxFactory.Token(SyntaxKind.CloseParenToken));
  220. }
  221. }
  222. public static string SanitizeQualifiedNameForUniqueHint(this string qualifiedName)
  223. => qualifiedName
  224. // AddSource() doesn't support @ prefix
  225. .Replace("@", "")
  226. // AddSource() doesn't support angle brackets
  227. .Replace("<", "(Of ")
  228. .Replace(">", ")");
  229. public static bool IsGodotExportAttribute(this INamedTypeSymbol symbol)
  230. => symbol.FullQualifiedNameOmitGlobal() == GodotClasses.ExportAttr;
  231. public static bool IsGodotSignalAttribute(this INamedTypeSymbol symbol)
  232. => symbol.FullQualifiedNameOmitGlobal() == GodotClasses.SignalAttr;
  233. public static bool IsGodotMustBeVariantAttribute(this INamedTypeSymbol symbol)
  234. => symbol.FullQualifiedNameOmitGlobal() == GodotClasses.MustBeVariantAttr;
  235. public static bool IsGodotClassNameAttribute(this INamedTypeSymbol symbol)
  236. => symbol.FullQualifiedNameOmitGlobal() == GodotClasses.GodotClassNameAttr;
  237. public static bool IsGodotGlobalClassAttribute(this INamedTypeSymbol symbol)
  238. => symbol.FullQualifiedNameOmitGlobal() == GodotClasses.GlobalClassAttr;
  239. public static bool IsGodotExportToolButtonAttribute(this INamedTypeSymbol symbol)
  240. => symbol.FullQualifiedNameOmitGlobal() == GodotClasses.ExportToolButtonAttr;
  241. public static bool IsGodotToolAttribute(this INamedTypeSymbol symbol)
  242. => symbol.FullQualifiedNameOmitGlobal() == GodotClasses.ToolAttr;
  243. public static bool IsSystemFlagsAttribute(this INamedTypeSymbol symbol)
  244. => symbol.FullQualifiedNameOmitGlobal() == GodotClasses.SystemFlagsAttr;
  245. public static GodotMethodData? HasGodotCompatibleSignature(
  246. this IMethodSymbol method,
  247. MarshalUtils.TypeCache typeCache
  248. )
  249. {
  250. if (method.IsGenericMethod)
  251. return null;
  252. var retSymbol = method.ReturnType;
  253. var retType = method.ReturnsVoid ?
  254. null :
  255. MarshalUtils.ConvertManagedTypeToMarshalType(method.ReturnType, typeCache);
  256. if (retType == null && !method.ReturnsVoid)
  257. return null;
  258. var parameters = method.Parameters;
  259. var paramTypes = parameters
  260. // Currently we don't support `ref`, `out`, `in`, `ref readonly` parameters (and we never may)
  261. .Where(p => p.RefKind == RefKind.None)
  262. // Attempt to determine the variant type
  263. .Select(p => MarshalUtils.ConvertManagedTypeToMarshalType(p.Type, typeCache))
  264. // Discard parameter types that couldn't be determined (null entries)
  265. .Where(t => t != null).Cast<MarshalType>().ToImmutableArray();
  266. // If any parameter type was incompatible, it was discarded so the length won't match
  267. if (parameters.Length > paramTypes.Length)
  268. return null; // Ignore incompatible method
  269. return new GodotMethodData(method, paramTypes,
  270. parameters.Select(p => p.Type).ToImmutableArray(),
  271. retType != null ? (retType.Value, retSymbol) : null);
  272. }
  273. public static IEnumerable<GodotMethodData> WhereHasGodotCompatibleSignature(
  274. this IEnumerable<IMethodSymbol> methods,
  275. MarshalUtils.TypeCache typeCache
  276. )
  277. {
  278. foreach (var method in methods)
  279. {
  280. var methodData = HasGodotCompatibleSignature(method, typeCache);
  281. if (methodData != null)
  282. yield return methodData.Value;
  283. }
  284. }
  285. public static IEnumerable<GodotPropertyData> WhereIsGodotCompatibleType(
  286. this IEnumerable<IPropertySymbol> properties,
  287. MarshalUtils.TypeCache typeCache
  288. )
  289. {
  290. foreach (var property in properties)
  291. {
  292. var marshalType = MarshalUtils.ConvertManagedTypeToMarshalType(property.Type, typeCache);
  293. if (marshalType == null)
  294. continue;
  295. yield return new GodotPropertyData(property, marshalType.Value);
  296. }
  297. }
  298. public static IEnumerable<GodotFieldData> WhereIsGodotCompatibleType(
  299. this IEnumerable<IFieldSymbol> fields,
  300. MarshalUtils.TypeCache typeCache
  301. )
  302. {
  303. foreach (var field in fields)
  304. {
  305. // TODO: We should still restore read-only fields after reloading assembly. Two possible ways: reflection or turn RestoreGodotObjectData into a constructor overload.
  306. var marshalType = MarshalUtils.ConvertManagedTypeToMarshalType(field.Type, typeCache);
  307. if (marshalType == null)
  308. continue;
  309. yield return new GodotFieldData(field, marshalType.Value);
  310. }
  311. }
  312. public static Location? FirstLocationWithSourceTreeOrDefault(this IEnumerable<Location> locations)
  313. {
  314. return locations.FirstOrDefault(location => location.SourceTree != null) ?? locations.FirstOrDefault();
  315. }
  316. public static string Path(this Location location)
  317. => location.SourceTree?.GetLineSpan(location.SourceSpan).Path
  318. ?? location.GetLineSpan().Path;
  319. public static int StartLine(this Location location)
  320. => location.SourceTree?.GetLineSpan(location.SourceSpan).StartLinePosition.Line
  321. ?? location.GetLineSpan().StartLinePosition.Line;
  322. }
  323. }