I have a library that has both an API and an analyzer. To function as an analyzer, it targets netstadard2.0
. To support the usage of the new language possibilities in the consumers, I have set <langversion>latest</langversion>
in the library. I have quite a few attribute classes with generic parameters, available from C#11. So far so good, the consumers can use them as expected. But I have issues with them in the analyzer, I get lots of these:
CSC : warning AD0001: Analyzer 'ApplicableOnConstraintAnalyzer' threw an exception of type 'System.NotSupportedException' with the message 'Generic types are not valid.'.
I am confused because I have created a test project for the analyzer, having such an initializer:
private CSharpAnalyzerTest<ApplicableOnConstraintAnalyzer, DefaultVerifier> context;
[TestInitialize]
public void TestInitialize()
{
var nugetConfig = Path.GetFullPath(Path.Join(AppDomain.CurrentDomain.BaseDirectory, @"........NuGet.config"));
context = new CSharpAnalyzerTest<ApplicableOnConstraintAnalyzer, DefaultVerifier>
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net80.WithNuGetConfigFilePath(nugetConfig),
TestState =
{
AdditionalReferences = { MetadataReference.CreateFromFile(typeof(sometypefromtheanalyzerproject).Assembly.Location) },
},
MarkupOptions = MarkupOptions.UseFirstDescriptor
};
}
If the analyzer throws any exception, a test method will fail. And this one does not fail.
[TestMethod("Simple property OK")]
public async Task TestSimpleOk()
{
context.TestCode =
"""
using System;
using Test.Attributes;
public class TestClass
{
[ValueRange<int>(0, 10)]
public int NumericProperty1 {get ; set; }
}
""";
await context.RunAsync();
}
Nevertheless, the exception is more than likely because of the attributes with the generic parameters.
But why only when the analyzer is running and only during build? Is the runtime environment provided by the builder more restrictive/older? The netstandard2.0
itself seems not to be an issue. Is there any workaround?
I could only debug the analyzer by adding the test. But there it is not throwing that exception. Is there any other way to debug an analyzer? At least to see where it is thrown…
[Update: 2024.09.04]
I see the cause: CSC.EXE
is targeting .NET Framework:
// C:Program FilesMicrosoft Visual Studio2022CommunityMsbuildCurrentBinRoslyncsc.exe
// csc, Version=4.12.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35
// Global type: <Module>
// Entry point: Microsoft.CodeAnalysis.CSharp.CommandLine.Program.Main
// Architecture: AnyCPU (64-bit preferred)
// Runtime: v4.0.30319
// This assembly is signed with a strong name key.
// This assembly was compiled using the /deterministic option.
// Hash algorithm: SHA1
And I am trying to actually read attributes from the type, which makes the runtime try to instantiate them, resulting in that exception in System.RuntimeTypeHandle.CreateCaInstance(RuntimeType type, IRuntimeMethodInfo ctor)
… Sad… I will have to stick to the semantic context…