- 
                Notifications
    You must be signed in to change notification settings 
- Fork 5.2k
Add analyzers and code-fixes to help adoption of source-generated COM #87223
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
          
     Merged
      
      
            jkoritzinsky
  merged 21 commits into
  dotnet:main
from
jkoritzinsky:com-migration-analyzer
  
      
      
   
  Jun 9, 2023 
      
    
  
     Merged
                    Changes from all 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 287c48d
              
                Get all analyzer-specific components of the "convert" tests passing.
              
              
                jkoritzinsky 9131f47
              
                Implement all interface-attribute-level changes in the code fixer.
              
              
                jkoritzinsky 400966f
              
                Add bool marshalling insertion logic to the fixer.
              
              
                jkoritzinsky c85ef8d
              
                Add support for removing shadowing members from interfaces.
              
              
                jkoritzinsky b5a2411
              
                Rename fixer
              
              
                jkoritzinsky 91668ad
              
                ActiveIssue the new tests
              
              
                jkoritzinsky dc28c33
              
                Implement basic AddGeneratedComClass analyzer/fixer
              
              
                jkoritzinsky fc28b83
              
                Add ComHosting + GeneratedComInterface analyzer implementation.
              
              
                jkoritzinsky 43b0ca8
              
                Implement the "runtime COM APIs with source-generated COM types" anal…
              
              
                jkoritzinsky af8caa3
              
                Factor out a base class from the ConvertToLibraryImportFixer so we ca…
              
              
                jkoritzinsky 0371d11
              
                Move more of the ConvertToLibraryImportFixer to use SyntaxGenerator A…
              
              
                jkoritzinsky d0e3ddc
              
                Move support for specifying explicit boolean marshalling rules up to …
              
              
                jkoritzinsky 64e6dd7
              
                Move the code fixes in ComInterfaceGenerator over to using the Conver…
              
              
                jkoritzinsky 8e0774a
              
                Remove use of multicasted delegates and use a more traditional "array…
              
              
                jkoritzinsky 20cc59a
              
                Do some refactoring to move more into the new fixer base class.
              
              
                jkoritzinsky 45bff1a
              
                Remove custom CodeAction-derived types now that we have a record type…
              
              
                jkoritzinsky dd678fd
              
                Make sure we make types and containing types partial
              
              
                jkoritzinsky c437b43
              
                Fix negative test.
              
              
                jkoritzinsky dee446d
              
                Add tests for transitive interface inheritance and add iids.
              
              
                jkoritzinsky ebd93c5
              
                Change bool parsing for internal parsing and add warning annotation t…
              
              
                jkoritzinsky File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
        
          
          
            59 changes: 59 additions & 0 deletions
          
          59 
        
  ...ntime.InteropServices/gen/ComInterfaceGenerator/Analyzers/AddGeneratedComClassAnalyzer.cs
  
  
      
      
   
        
      
      
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,59 @@ | ||
| // 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; | ||
| } | ||
|  | ||
| // Only direct people to put the GeneratedComClassAttribute on classes. | ||
| if (type.TypeKind != TypeKind.Class) | ||
| { | ||
| 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); | ||
| }); | ||
| } | ||
| } | ||
| } | 
        
          
          
            62 changes: 62 additions & 0 deletions
          
          62 
        
  ....Runtime.InteropServices/gen/ComInterfaceGenerator/Analyzers/AddGeneratedComClassFixer.cs
  
  
      
      
   
        
      
      
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | 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; | ||
| } | ||
| } | ||
| } | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
        
          
          
            71 changes: 71 additions & 0 deletions
          
          71 
        
  .../ComInterfaceGenerator/Analyzers/ComHostingDoesNotSupportGeneratedComInterfaceAnalyzer.cs
  
  
      
      
   
        
      
      
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
              | 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); | ||
| }); | ||
| } | ||
| } | ||
| } | ||
      
      Oops, something went wrong.
        
    
  
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
Uh oh!
There was an error while loading. Please reload this page.