ExtensionMethods.cs 15 KB

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