MustBeVariantAnalyzer.cs 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. using System.Collections.Immutable;
  2. using System.Linq;
  3. using Microsoft.CodeAnalysis;
  4. using Microsoft.CodeAnalysis.CSharp;
  5. using Microsoft.CodeAnalysis.CSharp.Syntax;
  6. using Microsoft.CodeAnalysis.Diagnostics;
  7. namespace Godot.SourceGenerators
  8. {
  9. [DiagnosticAnalyzer(LanguageNames.CSharp)]
  10. public sealed class MustBeVariantAnalyzer : DiagnosticAnalyzer
  11. {
  12. public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics
  13. => ImmutableArray.Create(
  14. Common.GenericTypeArgumentMustBeVariantRule,
  15. Common.GenericTypeParameterMustBeVariantAnnotatedRule,
  16. Common.TypeArgumentParentSymbolUnhandledRule);
  17. public override void Initialize(AnalysisContext context)
  18. {
  19. context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
  20. context.EnableConcurrentExecution();
  21. context.RegisterSyntaxNodeAction(AnalyzeNode, SyntaxKind.TypeArgumentList);
  22. }
  23. private void AnalyzeNode(SyntaxNodeAnalysisContext context)
  24. {
  25. // Ignore syntax inside comments
  26. if (IsInsideDocumentation(context.Node))
  27. return;
  28. var typeArgListSyntax = (TypeArgumentListSyntax)context.Node;
  29. // Method invocation or variable declaration that contained the type arguments
  30. var parentSyntax = context.Node.Parent;
  31. Helper.ThrowIfNull(parentSyntax);
  32. var sm = context.SemanticModel;
  33. var typeCache = new MarshalUtils.TypeCache(context.Compilation);
  34. for (int i = 0; i < typeArgListSyntax.Arguments.Count; i++)
  35. {
  36. var typeSyntax = typeArgListSyntax.Arguments[i];
  37. // Ignore omitted type arguments, e.g.: List<>, Dictionary<,>, etc
  38. if (typeSyntax is OmittedTypeArgumentSyntax)
  39. continue;
  40. var typeSymbol = sm.GetSymbolInfo(typeSyntax).Symbol as ITypeSymbol;
  41. Helper.ThrowIfNull(typeSymbol);
  42. var parentSymbolInfo = sm.GetSymbolInfo(parentSyntax);
  43. var parentSymbol = parentSymbolInfo.Symbol;
  44. if (parentSymbol == null)
  45. {
  46. if (parentSymbolInfo.CandidateReason == CandidateReason.LateBound)
  47. {
  48. // Invocations on dynamic are late bound so we can't retrieve the symbol.
  49. continue;
  50. }
  51. Helper.ThrowIfNull(parentSymbol);
  52. }
  53. if (!ShouldCheckTypeArgument(context, parentSyntax, parentSymbol, typeSyntax, typeSymbol, i))
  54. {
  55. return;
  56. }
  57. if (typeSymbol is ITypeParameterSymbol typeParamSymbol)
  58. {
  59. if (!typeParamSymbol.GetAttributes().Any(a => a.AttributeClass?.IsGodotMustBeVariantAttribute() ?? false))
  60. {
  61. context.ReportDiagnostic(Diagnostic.Create(
  62. Common.GenericTypeParameterMustBeVariantAnnotatedRule,
  63. typeSyntax.GetLocation(),
  64. typeSymbol.ToDisplayString()
  65. ));
  66. }
  67. continue;
  68. }
  69. var marshalType = MarshalUtils.ConvertManagedTypeToMarshalType(typeSymbol, typeCache);
  70. if (marshalType is null)
  71. {
  72. context.ReportDiagnostic(Diagnostic.Create(
  73. Common.GenericTypeArgumentMustBeVariantRule,
  74. typeSyntax.GetLocation(),
  75. typeSymbol.ToDisplayString()
  76. ));
  77. }
  78. }
  79. }
  80. /// <summary>
  81. /// Check if the syntax node is inside a documentation syntax.
  82. /// </summary>
  83. /// <param name="syntax">Syntax node to check.</param>
  84. /// <returns><see langword="true"/> if the syntax node is inside a documentation syntax.</returns>
  85. private bool IsInsideDocumentation(SyntaxNode? syntax)
  86. {
  87. while (syntax != null)
  88. {
  89. if (syntax is DocumentationCommentTriviaSyntax)
  90. {
  91. return true;
  92. }
  93. syntax = syntax.Parent;
  94. }
  95. return false;
  96. }
  97. /// <summary>
  98. /// Check if the given type argument is being used in a type parameter that contains
  99. /// the <c>MustBeVariantAttribute</c>; otherwise, we ignore the attribute.
  100. /// </summary>
  101. /// <param name="context">Context for a syntax node action.</param>
  102. /// <param name="parentSyntax">The parent node syntax that contains the type node syntax.</param>
  103. /// <param name="parentSymbol">The symbol retrieved for the parent node syntax.</param>
  104. /// <param name="typeArgumentSyntax">The type node syntax of the argument type to check.</param>
  105. /// <param name="typeArgumentSymbol">The symbol retrieved for the type node syntax.</param>
  106. /// <param name="typeArgumentIndex"></param>
  107. /// <returns><see langword="true"/> if the type must be variant and must be analyzed.</returns>
  108. private bool ShouldCheckTypeArgument(
  109. SyntaxNodeAnalysisContext context,
  110. SyntaxNode parentSyntax,
  111. ISymbol parentSymbol,
  112. TypeSyntax typeArgumentSyntax,
  113. ITypeSymbol typeArgumentSymbol,
  114. int typeArgumentIndex)
  115. {
  116. ITypeParameterSymbol? typeParamSymbol = parentSymbol switch
  117. {
  118. IMethodSymbol methodSymbol when parentSyntax.Ancestors().Any(s => s is AttributeSyntax) &&
  119. methodSymbol.ContainingType.TypeParameters.Length > 0
  120. => methodSymbol.ContainingType.TypeParameters[typeArgumentIndex],
  121. IMethodSymbol { TypeParameters.Length: > 0 } methodSymbol
  122. => methodSymbol.TypeParameters[typeArgumentIndex],
  123. INamedTypeSymbol { TypeParameters.Length: > 0 } typeSymbol
  124. => typeSymbol.TypeParameters[typeArgumentIndex],
  125. _
  126. => null
  127. };
  128. if (typeParamSymbol != null)
  129. {
  130. return typeParamSymbol.GetAttributes()
  131. .Any(a => a.AttributeClass?.IsGodotMustBeVariantAttribute() ?? false);
  132. }
  133. context.ReportDiagnostic(Diagnostic.Create(
  134. Common.TypeArgumentParentSymbolUnhandledRule,
  135. typeArgumentSyntax.GetLocation(),
  136. parentSymbol.ToDisplayString()
  137. ));
  138. return false;
  139. }
  140. }
  141. }