dotnet / roslyn

The Roslyn .NET compiler provides C# and Visual Basic languages with rich code analysis APIs.
https://docs.microsoft.com/dotnet/csharp/roslyn-sdk/
MIT License
19.11k stars 4.04k forks source link

Could not load System.Collections.Immutable #63780

Closed SoftStoneDevelop closed 2 years ago

SoftStoneDevelop commented 2 years ago

Version Used: Microsoft.CodeAnalysis.CSharp 4.3.0 for .NET 6

Steps to Reproduce:

  1. Get compilation var c = (CSharpCompilation)context.Compilation;
  2. Get globalnamespace and cast him as INamespaceOrTypeSymbol var n = (INamespaceOrTypeSymbol)c.Assembly.GlobalNamespace;
  3. Get members var members = n.GetMembers();

Expected Behavior: No error.

Actual Behavior: Failed to generate source.

error

The error appeared only in version 4.3.0. Connecting nuget System.Collections.Immutable directly does not help. If you comment out this line, then there will be no error:

//var members = n.GetMembers();

Example code for reproduce error Generator code:


using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;

namespace SourceGenerator
{
    [Generator]
    public class HelloSourceGenerator : ISourceGenerator
    {
        public void Execute(GeneratorExecutionContext context)
        {
            // Find the main method
            var mainMethod = context.Compilation.GetEntryPoint(context.CancellationToken);

            var c = (CSharpCompilation)context.Compilation;
            var n = (INamespaceOrTypeSymbol)c.Assembly.GlobalNamespace;
            var members = n.GetMembers();

            // Build up the source code
            string source = $@"// <auto-generated/>
using System;

namespace {mainMethod.ContainingNamespace.ToDisplayString()}
{{
    public static partial class {mainMethod.ContainingType.Name}
    {{
        static partial void HelloFrom(string name) =>
            Console.WriteLine($""Generator says: Hi from '{{name}}'"");
    }}
}}
";
            var typeName = mainMethod.ContainingType.Name;

            // Add the source code to the compilation
            context.AddSource($"{typeName}.g.cs", source);
        }

        public void Initialize(GeneratorInitializationContext context)
        {
            // No initialization required for this one
        }
    }
}
SoftStoneDevelop commented 2 years ago

Or maybe this is not a bug and someone knows how to fix it?

bdovaz commented 2 years ago

Same problem here! It started to happen when upgrading to 4.3.0

I can't compile on latest VS 2022 (17.3.3)

StijnOostdam commented 2 years ago

Same error here. I have upgraded to the latest .NET 6 version available, 6.0.400

AndrzejKroczynski commented 2 years ago

Same issue here - latest VS 2022 + .Net6

mattleibow commented 2 years ago

I tried this with an internal build of VS using .NET 7 and building a net6.0 app. Same result.

[Uploading Maui.Controls.Sample_Debug_AnyCPU_net6.0-android_Build_2022-09-06T12_29_29.4650495+02_00.zip…]()

jaredpar commented 2 years ago

@RikkiGibson can you take a look here. Suspect it's a case where the NuPkg is pushing a new version of S.C.I that doesn't match what we ship with our binaries.

RikkiGibson commented 2 years ago

I see that in PR #63599 we updated the reference to System.Collections.Immutable to 6.0.0. But in the main branch it is still at 5.0.0, and last modified 3 months ago, which means the PR in 17.3 never flowed forward. Also, a package containing PR #63599 has not yet been inserted to VS, but it looks like the version on NuGet does include PR #63599.

When we load the analyzer in the VS 17.4 preview (and probably in VS 17.3 as well, but I haven't tested), the compiler ends up trying to load this version, which fails. TBH, I don't have a lot of insight into why this is happening except that our Resolve event is returning null via this code path.

cc @chsienki @JoeRobich @jaredpar in case you can provide any insight.

RikkiGibson commented 2 years ago

For now we think the workaround for users who want to adopt APIs added in 4.3 is to reference version 4.3.0-3.final, which was released to match 17.3 preview 3. Apologies for the inconvenience.

Eli-Black-Work commented 2 years ago

Hi @jaredpar 🙂

I know this isn't your department, but I figured it might be worth asking:

I reported this same bug three months ago: https://developercommunity.visualstudio.com/t/MetadataCommandExtractMetadata-Could/10077182 . Do you have any insight on what happened to that bug? Was it ever reported to the Roslyn team?

Thanks, and sorry for the distraction 🙂

jaredpar commented 2 years ago

@Bosch-Eli-Black

That is a different bug. Yes both bugs are issues building due to a bad version of System.Collections.Immutable but the circumstances are different:

  1. This bug: Our 4.3.0 NuPkg advertised a dependency on 6.0.0 while the compiler actually deployed 5.0.0. That means anaylzers / generators that compiled against 4.3.0 ended up with a SCI dependency of 6.0.0. When deployed only 5.0.0 would be there , the analyzer wouldn't load and it would result in a compilation error.
  2. The linked bug: This is the MSBuildSdkResolver failing because it can't SCI at 5.0.0. That is essentially failing very early in the MSBuild process, way before ti gets to compilation.

My suspicion would be that installation was corrupted in (2). But it's not my area so I'd defer to MSBuild team.

kzu commented 2 years ago

My workaround for now was to downgrade to:

    <PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.2.0" Pack="false" />

Since I'm not using anything in 4.3 for my incremental generator, this works for now.

Eli-Black-Work commented 2 years ago

Ah, thanks, @jaredpar! Sorry for the confusion 🙂

knoxi commented 2 years ago

There is a new release of VS 2022, V17.3.5, it solved the issue for me.

UnleashMayhem commented 2 years ago

I still have the same issue, on JetBrains Rider 2022.2.3

Nirmal4G commented 2 years ago

You can now use the released version 4.3.1 for both compilers and libraries. This has been released to NuGet.

angularsen commented 2 years ago

I'm having similar trouble with all 4.x versions.

Repro on master branch: https://github.com/angularsen/roslyn-analyzers/

Rider 2022.2.3 VS2022 17.3.4 dotnet SDK 6.0.401

Microsoft.CodeAnalysis.Analyzers: 3.3.3 Microsoft.CodeAnalysis.CSharp.Workspaces: below versions

Repro

dotnet clean Samples.ConsoleNet6/; dotnet build Samples.ConsoleNet6/

Microsoft.CodeAnalysis.CSharp.Workspaces versions

This was tested with nuget reference to AssignAll. I seem to get slightly different behavior with project reference to AssignAll, where 4.1.0 does work as normal.

3.11.0 and below:

4.1.0, 4.2.0:

Note: After switching to project reference, 4.1.0 does work with both msbuild versions. 4.2.0 still does not work.

4.3.0, 4.3.1:

4.4.0-2.final: Not sure how to make this compile, it says it references a newer compiler than my current that is 4.3.3.

The dotnet SDK 6.0.401 is able to list the diagnostics correctly for all versions, but Rider and VS fail slightly differently each.

Why Rider is only able to list diagnostics, but not show tooltips for 4.x versions is odd and may be a separate bug on their end.

Seems relevant: https://youtrack.jetbrains.com/issue/RIDER-81137/CodeFixProviders-dont-work

References

CS8032 An instance of analyzer AssignAll.AssignAllAnalyzer cannot be created from C:\Users\andre\.nuget\packages\assignall\1.20.10-beta\analyzers\dotnet\cs\AssignAll.dll : 
Could not load file or assembly 'System.Collections.Immutable, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
jaredpar commented 2 years ago

Closing as this is resolved with NuPkg 4.3.1 and VS 17.3.5

tomrus88 commented 2 years ago

Still have this issue in VS 17.4.0 Preview 2.1, so not fixed all... Why close when its not fixed?

craigktreasure commented 2 years ago

We've begun to hit this as well in our build agent as of .NET SDK 6.0.402. I can't reproduce locally. Possibly because I've got an updated version of VS 2022 (17.3.6). The build agent is currently on VS 17.3.2.

BertanAygun commented 2 years ago

We started to hit this issue as well. The compiler toolset for 4.4.0-2.final (or earlier) ships with 5.0.0 of the assembly in "....nuget\packages\microsoft.net.compilers.toolset\4.4.0-2.final\tasks\net472\System.Collections.Immutable.dll, however Microsoft.CodeAnalysis.Common nuget package dependencies state "System.Collections.Immutable >= 5.0.0" nuget version.

Our generator recently started relying on a package that depends on System.Collections.Immutable >=6.0.0 which is causing conflicts because at runtime 6.0.0 is actually not available. Packaging 6.0.0 with our source generator doesn't work either since Roslyn APIs do return Immutable types causing type mismatches.

jaredpar commented 2 years ago

"....nuget\packages\microsoft.net.compilers.toolset\4.4.0-2.final\tasks\net472\System.Collections.Immutable.dll, however Microsoft.CodeAnalysis.Common nuget package dependencies state "System.Collections.Immutable >= 5.0.0" nuget versio

This package is not supported as a long term build tool. From the README on the NuPkg

This package is primarily intended as a method for rapidly shipping hotfixes to customers. Using it as a long term solution for providing newer compilers on older MSBuild installations is explicitly not supported. That can and will break on a regular basis.

The official toolset with 17.3.5 is patched for this problem.