ExtensionMethods.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.Immutable;
  4. using System.Linq;
  5. using Microsoft.CodeAnalysis;
  6. using Microsoft.CodeAnalysis.CSharp;
  7. using Microsoft.CodeAnalysis.CSharp.Syntax;
  8. namespace Godot.SourceGenerators
  9. {
  10. static class ExtensionMethods
  11. {
  12. public static bool TryGetGlobalAnalyzerProperty(
  13. this GeneratorExecutionContext context, string property, out string? value
  14. ) => context.AnalyzerConfigOptions.GlobalOptions
  15. .TryGetValue("build_property." + property, out value);
  16. public static bool AreGodotSourceGeneratorsDisabled(this GeneratorExecutionContext context)
  17. => context.TryGetGlobalAnalyzerProperty("GodotSourceGenerators", out string? toggle) &&
  18. toggle != null &&
  19. toggle.Equals("disabled", StringComparison.OrdinalIgnoreCase);
  20. public static bool IsGodotToolsProject(this GeneratorExecutionContext context)
  21. => context.TryGetGlobalAnalyzerProperty("IsGodotToolsProject", out string? toggle) &&
  22. toggle != null &&
  23. toggle.Equals("true", StringComparison.OrdinalIgnoreCase);
  24. public static bool InheritsFrom(this INamedTypeSymbol? symbol, string assemblyName, string typeFullName)
  25. {
  26. while (symbol != null)
  27. {
  28. if (symbol.ContainingAssembly.Name == assemblyName &&
  29. symbol.ToString() == typeFullName)
  30. {
  31. return true;
  32. }
  33. symbol = symbol.BaseType;
  34. }
  35. return false;
  36. }
  37. public static INamedTypeSymbol? GetGodotScriptNativeClass(this INamedTypeSymbol classTypeSymbol)
  38. {
  39. var symbol = classTypeSymbol;
  40. while (symbol != null)
  41. {
  42. if (symbol.ContainingAssembly.Name == "GodotSharp")
  43. return symbol;
  44. symbol = symbol.BaseType;
  45. }
  46. return null;
  47. }
  48. public static string? GetGodotScriptNativeClassName(this INamedTypeSymbol classTypeSymbol)
  49. {
  50. var nativeType = classTypeSymbol.GetGodotScriptNativeClass();
  51. if (nativeType == null)
  52. return null;
  53. var godotClassNameAttr = nativeType.GetAttributes()
  54. .FirstOrDefault(a => a.AttributeClass?.IsGodotClassNameAttribute() ?? false);
  55. string? godotClassName = null;
  56. if (godotClassNameAttr is { ConstructorArguments: { Length: > 0 } })
  57. godotClassName = godotClassNameAttr.ConstructorArguments[0].Value?.ToString();
  58. return godotClassName ?? nativeType.Name;
  59. }
  60. private static bool IsGodotScriptClass(
  61. this ClassDeclarationSyntax cds, Compilation compilation,
  62. out INamedTypeSymbol? symbol
  63. )
  64. {
  65. var sm = compilation.GetSemanticModel(cds.SyntaxTree);
  66. var classTypeSymbol = sm.GetDeclaredSymbol(cds);
  67. if (classTypeSymbol?.BaseType == null
  68. || !classTypeSymbol.BaseType.InheritsFrom("GodotSharp", GodotClasses.Object))
  69. {
  70. symbol = null;
  71. return false;
  72. }
  73. symbol = classTypeSymbol;
  74. return true;
  75. }
  76. public static IEnumerable<(ClassDeclarationSyntax cds, INamedTypeSymbol symbol)> SelectGodotScriptClasses(
  77. this IEnumerable<ClassDeclarationSyntax> source,
  78. Compilation compilation
  79. )
  80. {
  81. foreach (var cds in source)
  82. {
  83. if (cds.IsGodotScriptClass(compilation, out var symbol))
  84. yield return (cds, symbol!);
  85. }
  86. }
  87. public static bool IsNested(this TypeDeclarationSyntax cds)
  88. => cds.Parent is TypeDeclarationSyntax;
  89. public static bool IsPartial(this TypeDeclarationSyntax cds)
  90. => cds.Modifiers.Any(SyntaxKind.PartialKeyword);
  91. public static bool AreAllOuterTypesPartial(
  92. this TypeDeclarationSyntax cds,
  93. out TypeDeclarationSyntax? typeMissingPartial
  94. )
  95. {
  96. SyntaxNode? outerSyntaxNode = cds.Parent;
  97. while (outerSyntaxNode is TypeDeclarationSyntax outerTypeDeclSyntax)
  98. {
  99. if (!outerTypeDeclSyntax.IsPartial())
  100. {
  101. typeMissingPartial = outerTypeDeclSyntax;
  102. return false;
  103. }
  104. outerSyntaxNode = outerSyntaxNode.Parent;
  105. }
  106. typeMissingPartial = null;
  107. return true;
  108. }
  109. public static string GetDeclarationKeyword(this INamedTypeSymbol namedTypeSymbol)
  110. {
  111. string? keyword = namedTypeSymbol.DeclaringSyntaxReferences
  112. .OfType<TypeDeclarationSyntax>().FirstOrDefault()?
  113. .Keyword.Text;
  114. return keyword ?? namedTypeSymbol.TypeKind switch
  115. {
  116. TypeKind.Interface => "interface",
  117. TypeKind.Struct => "struct",
  118. _ => "class"
  119. };
  120. }
  121. private static SymbolDisplayFormat FullyQualifiedFormatOmitGlobal { get; } =
  122. SymbolDisplayFormat.FullyQualifiedFormat
  123. .WithGlobalNamespaceStyle(SymbolDisplayGlobalNamespaceStyle.Omitted);
  124. public static string FullQualifiedName(this ITypeSymbol symbol)
  125. => symbol.ToDisplayString(NullableFlowState.NotNull, FullyQualifiedFormatOmitGlobal);
  126. public static string NameWithTypeParameters(this INamedTypeSymbol symbol)
  127. {
  128. return symbol.IsGenericType ?
  129. string.Concat(symbol.Name, "<", string.Join(", ", symbol.TypeParameters), ">") :
  130. symbol.Name;
  131. }
  132. public static string FullQualifiedName(this INamespaceSymbol namespaceSymbol)
  133. => namespaceSymbol.ToDisplayString(FullyQualifiedFormatOmitGlobal);
  134. public static string SanitizeQualifiedNameForUniqueHint(this string qualifiedName)
  135. => qualifiedName
  136. // AddSource() doesn't support angle brackets
  137. .Replace("<", "(Of ")
  138. .Replace(">", ")");
  139. public static bool IsGodotExportAttribute(this INamedTypeSymbol symbol)
  140. => symbol.ToString() == GodotClasses.ExportAttr;
  141. public static bool IsGodotSignalAttribute(this INamedTypeSymbol symbol)
  142. => symbol.ToString() == GodotClasses.SignalAttr;
  143. public static bool IsGodotMustBeVariantAttribute(this INamedTypeSymbol symbol)
  144. => symbol.ToString() == GodotClasses.MustBeVariantAttr;
  145. public static bool IsGodotClassNameAttribute(this INamedTypeSymbol symbol)
  146. => symbol.ToString() == GodotClasses.GodotClassNameAttr;
  147. public static bool IsSystemFlagsAttribute(this INamedTypeSymbol symbol)
  148. => symbol.ToString() == GodotClasses.SystemFlagsAttr;
  149. public static GodotMethodData? HasGodotCompatibleSignature(
  150. this IMethodSymbol method,
  151. MarshalUtils.TypeCache typeCache
  152. )
  153. {
  154. if (method.IsGenericMethod)
  155. return null;
  156. var retSymbol = method.ReturnType;
  157. var retType = method.ReturnsVoid ?
  158. null :
  159. MarshalUtils.ConvertManagedTypeToMarshalType(method.ReturnType, typeCache);
  160. if (retType == null && !method.ReturnsVoid)
  161. return null;
  162. var parameters = method.Parameters;
  163. var paramTypes = parameters
  164. // Currently we don't support `ref`, `out`, `in`, `ref readonly` parameters (and we never may)
  165. .Where(p => p.RefKind == RefKind.None)
  166. // Attempt to determine the variant type
  167. .Select(p => MarshalUtils.ConvertManagedTypeToMarshalType(p.Type, typeCache))
  168. // Discard parameter types that couldn't be determined (null entries)
  169. .Where(t => t != null).Cast<MarshalType>().ToImmutableArray();
  170. // If any parameter type was incompatible, it was discarded so the length won't match
  171. if (parameters.Length > paramTypes.Length)
  172. return null; // Ignore incompatible method
  173. return new GodotMethodData(method, paramTypes, parameters
  174. .Select(p => p.Type).ToImmutableArray(), retType, retSymbol);
  175. }
  176. public static IEnumerable<GodotMethodData> WhereHasGodotCompatibleSignature(
  177. this IEnumerable<IMethodSymbol> methods,
  178. MarshalUtils.TypeCache typeCache
  179. )
  180. {
  181. foreach (var method in methods)
  182. {
  183. var methodData = HasGodotCompatibleSignature(method, typeCache);
  184. if (methodData != null)
  185. yield return methodData.Value;
  186. }
  187. }
  188. public static IEnumerable<GodotPropertyData> WhereIsGodotCompatibleType(
  189. this IEnumerable<IPropertySymbol> properties,
  190. MarshalUtils.TypeCache typeCache
  191. )
  192. {
  193. foreach (var property in properties)
  194. {
  195. // TODO: We should still restore read-only properties after reloading assembly. Two possible ways: reflection or turn RestoreGodotObjectData into a constructor overload.
  196. // Ignore properties without a getter or without a setter. Godot properties must be both readable and writable.
  197. if (property.IsWriteOnly || property.IsReadOnly)
  198. continue;
  199. var marshalType = MarshalUtils.ConvertManagedTypeToMarshalType(property.Type, typeCache);
  200. if (marshalType == null)
  201. continue;
  202. yield return new GodotPropertyData(property, marshalType.Value);
  203. }
  204. }
  205. public static IEnumerable<GodotFieldData> WhereIsGodotCompatibleType(
  206. this IEnumerable<IFieldSymbol> fields,
  207. MarshalUtils.TypeCache typeCache
  208. )
  209. {
  210. foreach (var field in fields)
  211. {
  212. // TODO: We should still restore read-only fields after reloading assembly. Two possible ways: reflection or turn RestoreGodotObjectData into a constructor overload.
  213. // Ignore properties without a getter or without a setter. Godot properties must be both readable and writable.
  214. if (field.IsReadOnly)
  215. continue;
  216. var marshalType = MarshalUtils.ConvertManagedTypeToMarshalType(field.Type, typeCache);
  217. if (marshalType == null)
  218. continue;
  219. yield return new GodotFieldData(field, marshalType.Value);
  220. }
  221. }
  222. public static string Path(this Location location)
  223. => location.SourceTree?.GetLineSpan(location.SourceSpan).Path
  224. ?? location.GetLineSpan().Path;
  225. public static int StartLine(this Location location)
  226. => location.SourceTree?.GetLineSpan(location.SourceSpan).StartLinePosition.Line
  227. ?? location.GetLineSpan().StartLinePosition.Line;
  228. }
  229. }