Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add analyzers and code-fixes to help adoption of source-generated COM #87223

Merged
merged 21 commits into from
Jun 9, 2023
Merged
Show file tree
Hide file tree
Changes from 19 commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
7862930
Add first pass of the "convert to generated COM interface" analyzer a…
jkoritzinsky Jun 5, 2023
287c48d
Get all analyzer-specific components of the "convert" tests passing.
jkoritzinsky Jun 5, 2023
9131f47
Implement all interface-attribute-level changes in the code fixer.
jkoritzinsky Jun 5, 2023
400966f
Add bool marshalling insertion logic to the fixer.
jkoritzinsky Jun 5, 2023
c85ef8d
Add support for removing shadowing members from interfaces.
jkoritzinsky Jun 5, 2023
b5a2411
Rename fixer
jkoritzinsky Jun 5, 2023
91668ad
ActiveIssue the new tests
jkoritzinsky Jun 5, 2023
dc28c33
Implement basic AddGeneratedComClass analyzer/fixer
jkoritzinsky Jun 6, 2023
fc28b83
Add ComHosting + GeneratedComInterface analyzer implementation.
jkoritzinsky Jun 6, 2023
43b0ca8
Implement the "runtime COM APIs with source-generated COM types" anal…
jkoritzinsky Jun 6, 2023
af8caa3
Factor out a base class from the ConvertToLibraryImportFixer so we ca…
jkoritzinsky Jun 7, 2023
0371d11
Move more of the ConvertToLibraryImportFixer to use SyntaxGenerator A…
jkoritzinsky Jun 7, 2023
d0e3ddc
Move support for specifying explicit boolean marshalling rules up to …
jkoritzinsky Jun 7, 2023
64e6dd7
Move the code fixes in ComInterfaceGenerator over to using the Conver…
jkoritzinsky Jun 7, 2023
8e0774a
Remove use of multicasted delegates and use a more traditional "array…
jkoritzinsky Jun 7, 2023
20cc59a
Do some refactoring to move more into the new fixer base class.
jkoritzinsky Jun 7, 2023
45bff1a
Remove custom CodeAction-derived types now that we have a record type…
jkoritzinsky Jun 7, 2023
dd678fd
Make sure we make types and containing types partial
jkoritzinsky Jun 7, 2023
c437b43
Fix negative test.
jkoritzinsky Jun 8, 2023
dee446d
Add tests for transitive interface inheritance and add iids.
jkoritzinsky Jun 8, 2023
ebd93c5
Change bool parsing for internal parsing and add warning annotation t…
jkoritzinsky Jun 8, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.DotnetRuntime.Extensions;
using static Microsoft.Interop.Analyzers.AnalyzerDiagnostics;

namespace Microsoft.Interop.Analyzers
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class AddGeneratedComClassAnalyzer : DiagnosticAnalyzer
{
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(AddGeneratedComClassAttribute);

public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);

context.RegisterCompilationStartAction(context =>
{
var generatedComClassAttributeType = context.Compilation.GetBestTypeByMetadataName(TypeNames.GeneratedComClassAttribute);
var generatedComInterfaceAttributeType = context.Compilation.GetBestTypeByMetadataName(TypeNames.GeneratedComInterfaceAttribute);

if (generatedComClassAttributeType is null || generatedComInterfaceAttributeType is null)
{
return;
}

context.RegisterSymbolAction(context =>
{
INamedTypeSymbol type = (INamedTypeSymbol)context.Symbol;
if (type.GetAttributes().Any(attr => generatedComClassAttributeType.Equals(attr.AttributeClass, SymbolEqualityComparer.Default)))
{
return;
}

foreach (var iface in type.AllInterfaces)
{
if (iface.GetAttributes().Any(attr => generatedComInterfaceAttributeType.Equals(attr.AttributeClass, SymbolEqualityComparer.Default)))
{
context.ReportDiagnostic(type.CreateDiagnostic(AddGeneratedComClassAttribute, type.Name));
return;
}
}
}, SymbolKind.NamedType);
});
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System;
using System.Collections.Immutable;
using System.Composition;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.DotnetRuntime.Extensions;
using Microsoft.CodeAnalysis.Editing;
using Microsoft.CodeAnalysis.Simplification;

namespace Microsoft.Interop.Analyzers
{
[ExportCodeFixProvider(LanguageNames.CSharp), Shared]
public class AddGeneratedComClassFixer : ConvertToSourceGeneratedInteropFixer
{
public override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(AnalyzerDiagnostics.Ids.AddGeneratedComClassAttribute);

protected override string BaseEquivalenceKey => nameof(AddGeneratedComClassFixer);

private static Task AddGeneratedComClassAsync(DocumentEditor editor, SyntaxNode node)
{
editor.ReplaceNode(node, (node, gen) =>
{
var attribute = gen.Attribute(gen.TypeExpression(editor.SemanticModel.Compilation.GetBestTypeByMetadataName(TypeNames.GeneratedComClassAttribute)).WithAdditionalAnnotations(Simplifier.AddImportsAnnotation));
var updatedNode = gen.AddAttributes(node, attribute);
var declarationModifiers = gen.GetModifiers(updatedNode);
if (!declarationModifiers.IsPartial)
{
updatedNode = gen.WithModifiers(updatedNode, declarationModifiers.WithPartial(true));
}
return updatedNode;
});

MakeNodeParentsPartial(editor, node);

return Task.CompletedTask;
}

protected override Func<DocumentEditor, CancellationToken, Task> CreateFixForSelectedOptions(SyntaxNode node, ImmutableDictionary<string, Option> selectedOptions)
{
return (editor, _) => AddGeneratedComClassAsync(editor, node);
}

protected override string GetDiagnosticTitle(ImmutableDictionary<string, Option> selectedOptions)
{
bool allowUnsafe = selectedOptions.TryGetValue(Option.AllowUnsafe, out var allowUnsafeOption) && allowUnsafeOption is Option.Bool(true);

return allowUnsafe
? SR.AddGeneratedComClassAttributeTitle
: SR.AddGeneratedComClassAddUnsafe;
}

protected override ImmutableDictionary<string, Option> ParseOptionsFromDiagnostic(Diagnostic diagnostic)
{
return ImmutableDictionary<string, Option>.Empty;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,19 @@ public static class Ids
{
public const string Prefix = "SYSLIB";
public const string InvalidGeneratedComAttributeUsage = Prefix + "1090";
public const string ConvertToGeneratedComInterface = Prefix + "1096";
jkoritzinsky marked this conversation as resolved.
Show resolved Hide resolved
public const string AddGeneratedComClassAttribute = Prefix + "1097";
public const string ComHostingDoesNotSupportGeneratedComInterface = Prefix + "1098";
public const string RuntimeComApisDoNotSupportSourceGeneratedCom = Prefix + "1099";
}

private const string Category = "ComInterfaceGenerator";
public static class Metadata
{
public const string MayRequireAdditionalWork = nameof(MayRequireAdditionalWork);
public const string AddStringMarshalling = nameof(AddStringMarshalling);
}

private const string Category = "Interoperability";

private static LocalizableResourceString GetResourceString(string resourceName)
{
Expand All @@ -29,5 +39,45 @@ private static LocalizableResourceString GetResourceString(string resourceName)
DiagnosticSeverity.Error,
isEnabledByDefault: true,
description: GetResourceString(nameof(SR.InterfaceTypeNotSupportedMessage)));

public static readonly DiagnosticDescriptor ConvertToGeneratedComInterface =
new DiagnosticDescriptor(
Ids.ConvertToGeneratedComInterface,
GetResourceString(nameof(SR.ConvertToGeneratedComInterfaceTitle)),
GetResourceString(nameof(SR.ConvertToGeneratedComInterfaceMessage)),
Category,
DiagnosticSeverity.Info,
isEnabledByDefault: true,
description: GetResourceString(nameof(SR.ConvertToGeneratedComInterfaceDescription)));

public static readonly DiagnosticDescriptor AddGeneratedComClassAttribute =
new DiagnosticDescriptor(
Ids.AddGeneratedComClassAttribute,
GetResourceString(nameof(SR.AddGeneratedComClassAttributeTitle)),
GetResourceString(nameof(SR.AddGeneratedComClassAttributeMessage)),
Category,
DiagnosticSeverity.Info,
isEnabledByDefault: true,
description: GetResourceString(nameof(SR.AddGeneratedComClassAttributeDescription)));

public static readonly DiagnosticDescriptor ComHostingDoesNotSupportGeneratedComInterface =
new DiagnosticDescriptor(
Ids.ComHostingDoesNotSupportGeneratedComInterface,
GetResourceString(nameof(SR.ComHostingDoesNotSupportGeneratedComInterfaceTitle)),
GetResourceString(nameof(SR.ComHostingDoesNotSupportGeneratedComInterfaceMessage)),
Category,
DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description: GetResourceString(nameof(SR.ComHostingDoesNotSupportGeneratedComInterfaceDescription)));

public static readonly DiagnosticDescriptor RuntimeComApisDoNotSupportSourceGeneratedCom =
new DiagnosticDescriptor(
Ids.RuntimeComApisDoNotSupportSourceGeneratedCom,
GetResourceString(nameof(SR.RuntimeComApisDoNotSupportSourceGeneratedComTitle)),
GetResourceString(nameof(SR.RuntimeComApisDoNotSupportSourceGeneratedComMessage)),
Category,
DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description: GetResourceString(nameof(SR.RuntimeComApisDoNotSupportSourceGeneratedComDescription)));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Collections.Immutable;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.DotnetRuntime.Extensions;
using Microsoft.CodeAnalysis.Operations;
using static Microsoft.Interop.Analyzers.AnalyzerDiagnostics;

namespace Microsoft.Interop.Analyzers
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class ComHostingDoesNotSupportGeneratedComInterfaceAnalyzer : DiagnosticAnalyzer
{
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(ComHostingDoesNotSupportGeneratedComInterface);

public override void Initialize(AnalysisContext context)
{
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.EnableConcurrentExecution();
context.RegisterCompilationStartAction(context =>
{
if (!context.Options.AnalyzerConfigOptionsProvider.GlobalOptions.TryGetValue("build_property.EnableComHosting", out string? enableComHosting)
|| !bool.TryParse(enableComHosting, out bool enableComHostingValue)
jkoritzinsky marked this conversation as resolved.
Show resolved Hide resolved
|| !enableComHostingValue)
{
return;
}

INamedTypeSymbol? generatedComClassAttribute = context.Compilation.GetBestTypeByMetadataName(TypeNames.GeneratedComClassAttribute);
INamedTypeSymbol? generatedComInterfaceAttribute = context.Compilation.GetBestTypeByMetadataName(TypeNames.GeneratedComInterfaceAttribute);
INamedTypeSymbol? comVisibleAttribute = context.Compilation.GetBestTypeByMetadataName(TypeNames.System_Runtime_InteropServices_ComVisibleAttribute)!;

if (generatedComClassAttribute is null || generatedComInterfaceAttribute is null || comVisibleAttribute is null)
{
return;
}

context.RegisterOperationAction(context =>
{
IAttributeOperation attr = (IAttributeOperation)context.Operation;
if (attr.Operation is not IObjectCreationOperation ctor
|| !comVisibleAttribute.Equals(ctor.Type, SymbolEqualityComparer.Default)
|| ctor.Arguments[0].Value.ConstantValue.Value is not true)
{
return;
}

INamedTypeSymbol containingType = (INamedTypeSymbol)context.ContainingSymbol;

if (containingType.GetAttributes().Any(attr => generatedComClassAttribute.Equals(attr.AttributeClass, SymbolEqualityComparer.Default)))
{
context.ReportDiagnostic(context.ContainingSymbol.CreateDiagnostic(ComHostingDoesNotSupportGeneratedComInterface, context.ContainingSymbol.Name));
return;
}

foreach (var iface in containingType.AllInterfaces)
{
if (iface.GetAttributes().Any(attr => generatedComInterfaceAttribute.Equals(attr.AttributeClass, SymbolEqualityComparer.Default)))
{
context.ReportDiagnostic(context.ContainingSymbol.CreateDiagnostic(ComHostingDoesNotSupportGeneratedComInterface, context.ContainingSymbol.Name));
return;
}
}
}, OperationKind.Attribute);
});
}
}
}
Loading