Skip to content

[ComInterfaceGenerator] Trailing trivia after GeneratedComInterfaceAttribute included in generated files #88798

@lordmilko

Description

@lordmilko

Consider the following declaration of an interface designed to be multi-targeted against .NET 8 and earlier versions of .NET

    [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
    [Guid("7DAC8207-D3AE-4C75-9B67-92801A497D44")]
#if !GENERATED_MARSHALLING
    [ComImport]
#else
    [GeneratedComInterface]
#endif
    public partial interface IFoo
    {
        void Foo();
    }

Attempting to compile this results in the following error:

error CS1028: Unexpected preprocessor directive

In the generated source code, we can see the #ifdef directive has erroneously been carried over to two locations

// MyProject.IFoo.cs
namespace MyProject
{
    [System.Runtime.InteropServices.Marshalling.IUnknownDerivedAttribute<InterfaceInformation, InterfaceImplementation>]
#endif
    public partial interface IFoo
    {
    }
}

namespace MyProject
{
#endif
    public partial interface IFoo
    {
    }
}

If we flip our #if directive around to the following

#if GENERATED_MARSHALLING
    [GeneratedComInterface]
#else
    [ComImport]
#endif
    public partial interface IFoo

then the #else, [ComImport] and #endif lines are all copied over to the generated source file.

You can "work around" this by moving the interface header into the #if statement, as follows

#if !GENERATED_MARSHALLING
    [ComImport]
    public partial interface IFoo
#else
    [GeneratedComInterface]
    public partial interface IFoo
#endif

However I would present that users attempting to multi-target by applying an #if around which attribute to use is a reasonable scenario; I would imagine upon reading the GeneratedComInterfaceAttribute AttributeSyntax the source generator should just trim all trailing trivia

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions