|
| 1 | +// Copyright (c) Microsoft Corporation. All rights reserved. |
| 2 | +// Licensed under the MIT license. See LICENSE file in the project root for full license information. |
| 3 | + |
| 4 | +namespace Microsoft.VisualStudio.Composition.Analyzers; |
| 5 | + |
| 6 | +/// <summary> |
| 7 | +/// Creates a diagnostic when `[Export(typeof(T))]` is applied to a class that does not implement T, |
| 8 | +/// or to a property whose type is not compatible with T. |
| 9 | +/// </summary> |
| 10 | +[DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] |
| 11 | +public class VSMEF003ExportTypeMismatchAnalyzer : DiagnosticAnalyzer |
| 12 | +{ |
| 13 | + /// <summary> |
| 14 | + /// The ID for diagnostics reported by this analyzer. |
| 15 | + /// </summary> |
| 16 | + public const string Id = "VSMEF003"; |
| 17 | + |
| 18 | + /// <summary> |
| 19 | + /// The descriptor used for diagnostics created by this rule. |
| 20 | + /// </summary> |
| 21 | + internal static readonly DiagnosticDescriptor Descriptor = new( |
| 22 | + id: Id, |
| 23 | + title: Strings.VSMEF003_Title, |
| 24 | + messageFormat: Strings.VSMEF003_MessageFormat, |
| 25 | + helpLinkUri: Utils.GetHelpLink(Id), |
| 26 | + category: "Usage", |
| 27 | + defaultSeverity: DiagnosticSeverity.Warning, |
| 28 | + isEnabledByDefault: true); |
| 29 | + |
| 30 | + /// <inheritdoc/> |
| 31 | + public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(Descriptor); |
| 32 | + |
| 33 | + /// <inheritdoc/> |
| 34 | + public override void Initialize(AnalysisContext context) |
| 35 | + { |
| 36 | + context.EnableConcurrentExecution(); |
| 37 | + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); |
| 38 | + |
| 39 | + context.RegisterCompilationStartAction(context => |
| 40 | + { |
| 41 | + // Only scan further if the compilation references the assemblies that define the attributes we'll be looking for. |
| 42 | + if (context.Compilation.ReferencedAssemblyNames.Any(i => |
| 43 | + string.Equals(i.Name, "System.ComponentModel.Composition", StringComparison.OrdinalIgnoreCase) || |
| 44 | + string.Equals(i.Name, "System.Composition.AttributedModel", StringComparison.OrdinalIgnoreCase))) |
| 45 | + { |
| 46 | + INamedTypeSymbol? mefV1ExportAttribute = context.Compilation.GetTypeByMetadataName("System.ComponentModel.Composition.ExportAttribute"); |
| 47 | + INamedTypeSymbol? mefV2ExportAttribute = context.Compilation.GetTypeByMetadataName("System.Composition.ExportAttribute"); |
| 48 | + context.RegisterSymbolAction( |
| 49 | + context => AnalyzeTypeDeclaration(context, mefV1ExportAttribute, mefV2ExportAttribute), |
| 50 | + SymbolKind.NamedType); |
| 51 | + context.RegisterSymbolAction( |
| 52 | + context => AnalyzePropertyDeclaration(context, mefV1ExportAttribute, mefV2ExportAttribute), |
| 53 | + SymbolKind.Property); |
| 54 | + } |
| 55 | + }); |
| 56 | + } |
| 57 | + |
| 58 | + private static void AnalyzeTypeDeclaration(SymbolAnalysisContext context, INamedTypeSymbol? mefV1ExportAttribute, INamedTypeSymbol? mefV2ExportAttribute) |
| 59 | + { |
| 60 | + var namedType = (INamedTypeSymbol)context.Symbol; |
| 61 | + |
| 62 | + // Skip interfaces, enums, delegates - only analyze classes |
| 63 | + if (namedType.TypeKind != TypeKind.Class) |
| 64 | + { |
| 65 | + return; |
| 66 | + } |
| 67 | + |
| 68 | + Location? location = namedType.Locations.FirstOrDefault(); |
| 69 | + if (location is null) |
| 70 | + { |
| 71 | + // We won't have anywhere to publish a diagnostic anyway. |
| 72 | + return; |
| 73 | + } |
| 74 | + |
| 75 | + foreach (var attributeData in namedType.GetAttributes()) |
| 76 | + { |
| 77 | + // Check if this is an Export attribute |
| 78 | + if (SymbolEqualityComparer.Default.Equals(attributeData.AttributeClass, mefV1ExportAttribute) || |
| 79 | + SymbolEqualityComparer.Default.Equals(attributeData.AttributeClass, mefV2ExportAttribute)) |
| 80 | + { |
| 81 | + // Check if the export attribute has a type argument |
| 82 | + if (attributeData.ConstructorArguments is [{ Kind: TypedConstantKind.Type, Value: INamedTypeSymbol exportedType }, ..]) |
| 83 | + { |
| 84 | + // Check if the exporting type implements or inherits from the exported type |
| 85 | + if (!IsTypeCompatible(namedType, exportedType)) |
| 86 | + { |
| 87 | + context.ReportDiagnostic(Diagnostic.Create( |
| 88 | + Descriptor, |
| 89 | + location, |
| 90 | + namedType.Name, |
| 91 | + exportedType.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat))); |
| 92 | + } |
| 93 | + } |
| 94 | + } |
| 95 | + } |
| 96 | + } |
| 97 | + |
| 98 | + private static void AnalyzePropertyDeclaration(SymbolAnalysisContext context, INamedTypeSymbol? mefV1ExportAttribute, INamedTypeSymbol? mefV2ExportAttribute) |
| 99 | + { |
| 100 | + var property = (IPropertySymbol)context.Symbol; |
| 101 | + |
| 102 | + Location? location = property.Locations.FirstOrDefault(); |
| 103 | + if (location is null) |
| 104 | + { |
| 105 | + // We won't have anywhere to publish a diagnostic anyway. |
| 106 | + return; |
| 107 | + } |
| 108 | + |
| 109 | + foreach (var attributeData in property.GetAttributes()) |
| 110 | + { |
| 111 | + // Check if this is an Export attribute |
| 112 | + if (SymbolEqualityComparer.Default.Equals(attributeData.AttributeClass, mefV1ExportAttribute) || |
| 113 | + SymbolEqualityComparer.Default.Equals(attributeData.AttributeClass, mefV2ExportAttribute)) |
| 114 | + { |
| 115 | + // Check if the export attribute has a type argument |
| 116 | + if (attributeData.ConstructorArguments is [{ Kind: TypedConstantKind.Type, Value: INamedTypeSymbol exportedType }, ..]) |
| 117 | + { |
| 118 | + // Check if the property type is compatible with the exported type |
| 119 | + if (!IsPropertyTypeCompatible(property.Type, exportedType)) |
| 120 | + { |
| 121 | + context.ReportDiagnostic(Diagnostic.Create( |
| 122 | + Descriptor, |
| 123 | + location, |
| 124 | + property.Name, |
| 125 | + exportedType.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat))); |
| 126 | + } |
| 127 | + } |
| 128 | + } |
| 129 | + } |
| 130 | + } |
| 131 | + |
| 132 | + private static bool IsTypeCompatible(INamedTypeSymbol implementingType, INamedTypeSymbol exportedType) |
| 133 | + { |
| 134 | + // If they're the same type, it's compatible |
| 135 | + if (SymbolEqualityComparer.Default.Equals(implementingType, exportedType)) |
| 136 | + { |
| 137 | + return true; |
| 138 | + } |
| 139 | + |
| 140 | + // Check if implementing type inherits from exported type (for classes) |
| 141 | + if (exportedType.TypeKind == TypeKind.Class) |
| 142 | + { |
| 143 | + var currentType = implementingType.BaseType; |
| 144 | + while (currentType != null) |
| 145 | + { |
| 146 | + if (SymbolEqualityComparer.Default.Equals(currentType, exportedType)) |
| 147 | + { |
| 148 | + return true; |
| 149 | + } |
| 150 | + |
| 151 | + currentType = currentType.BaseType; |
| 152 | + } |
| 153 | + } |
| 154 | + |
| 155 | + // Check if implementing type implements exported interface |
| 156 | + if (exportedType.TypeKind == TypeKind.Interface) |
| 157 | + { |
| 158 | + return implementingType.AllInterfaces.Any(i => SymbolEqualityComparer.Default.Equals(i, exportedType)); |
| 159 | + } |
| 160 | + |
| 161 | + return false; |
| 162 | + } |
| 163 | + |
| 164 | + private static bool IsPropertyTypeCompatible(ITypeSymbol propertyType, INamedTypeSymbol exportedType) |
| 165 | + { |
| 166 | + // If they're the same type, it's compatible |
| 167 | + if (SymbolEqualityComparer.Default.Equals(propertyType, exportedType)) |
| 168 | + { |
| 169 | + return true; |
| 170 | + } |
| 171 | + |
| 172 | + // If property type is a named type, use the same logic as for classes |
| 173 | + if (propertyType is INamedTypeSymbol namedPropertyType) |
| 174 | + { |
| 175 | + return IsTypeCompatible(namedPropertyType, exportedType); |
| 176 | + } |
| 177 | + |
| 178 | + return false; |
| 179 | + } |
| 180 | +} |
0 commit comments