phmonte / Buildalyzer

A utility to perform design-time builds of .NET projects without having to think too hard about it.
MIT License
605 stars 95 forks source link

PreprocessorSymbolNames are missing for .NET 5+ projects #191

Closed richardwerkman closed 2 years ago

richardwerkman commented 2 years ago

As mentioned on this page https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/preprocessor-directives I can use new symobols in preprocessor if like NETCOREAPP3_1_OR_GREATER which should be added if the targetframework is greater than 3.1.

If I use this in a project and build with Visual Studio the code is included. But when I analyse that same project with buildalyzer the preprocessor symbols are not added. Only the default symbols.

Reproduction

Reference .NET 6 and add to a file

    public int Bit()
    {
#if NETCOREAPP3_1_OR_GREATER
        return 1 ^ 2;
#endif
    }

This will compile in VS and dotnet build, but not in buildalyzer

Context

I'm not sure yet why they are missing in Buildalyzer. They should be added on SDK style projects. But there is a message saying: For traditional, non-SDK-style projects, you have to manually configure the conditional compilation symbols for the different target frameworks in Visual Studio via the project's properties pages.

So it might just be the case some SDK assembly is not loaded? Or if we have bad luck this is custom logic in MSBuild thats used in VS and the dotnet CLI.

Either way I can't compile the project that builalyzer returns... I also see no workaround as the symbols are added at parse time and can't be changed once the syntax tree has been parsed.

Issue was found in https://github.com/stryker-mutator/stryker-net/issues/1828

richardwerkman commented 2 years ago

I think I found where the preprocessor symbols are added in MSbuild: https://github.com/dotnet/sdk/blob/997376c6bc798af22633a8eb36074a0acec8a200/src/Tasks/Microsoft.NET.Build.Tasks/targets/Microsoft.NET.Sdk.BeforeCommon.targets

richardwerkman commented 2 years ago

I have found the issue. We create our syntax trees with ParseOptions based on what Buildalyzer tells us. I see Builalyzer does the same internally here https://github.com/daveaglick/Buildalyzer/blob/b2bd62140b2073d8a1ef4b30cecd1a2ce34038b5/src/Buildalyzer.Workspaces/AnalyzerResultExtensions.cs#L174

The issue is that the DefineConstants property is lacking the *_OR_GREATER constants. But I have found a property that contains all constants we need. It's private so we can't access it.

image

I'll try to create a PR that makes this public and will also fix the internal usage so Buildalyzer support the new preprocessor symbols from now on.