public async Task SkipLocalsInitOnDownlevelTargetFrameworks(ReferenceAssemblies referenceAssemblies, bool expectSkipLocalsInit) { string source = @" using System.Runtime.InteropServices; namespace System.Runtime.InteropServices { sealed class GeneratedDllImportAttribute : System.Attribute { public GeneratedDllImportAttribute(string a) { } } }partial class C { [GeneratedDllImportAttribute(""DoesNotExist"")] public static partial void Method(); }"; Compilation comp = await TestUtils.CreateCompilationWithReferenceAssemblies(source, referenceAssemblies); Compilation newComp = TestUtils.RunGenerators(comp, out _, new Microsoft.Interop.DllImportGenerator()); ITypeSymbol c = newComp.GetTypeByMetadataName("C") !; IMethodSymbol stubMethod = c.GetMembers().OfType <IMethodSymbol>().Single(m => m.Name == "Method"); if (expectSkipLocalsInit) { Assert.Contains(stubMethod.GetAttributes(), attr => attr.AttributeClass !.ToDisplayString() == typeof(SkipLocalsInitAttribute).FullName); } else { Assert.DoesNotContain(stubMethod.GetAttributes(), attr => attr.AttributeClass !.ToDisplayString() == typeof(SkipLocalsInitAttribute).FullName); } }
static CodeAnalyzerHelper() { CurrentXunit = ReferenceAssemblies.Default.AddPackages(ImmutableArray.Create( new PackageIdentity("System.Collections.Immutable", "1.6.0"), new PackageIdentity("xunit.assert", "2.4.1"), new PackageIdentity("xunit.core", "2.4.1"))); }
public Test(ReferenceAssemblies?references, bool usePreviewLanguageVersion, int numberOfIterations) { // Code Fixer generates partial methods that will need to use the source generator to be filled. this.CompilerDiagnostics = CompilerDiagnostics.None; if (references != null) { ReferenceAssemblies = references; } else { // Clear out the default reference assemblies. We explicitly add references from the live ref pack, // so we don't want the Roslyn test infrastructure to resolve/add any default reference assemblies ReferenceAssemblies = new ReferenceAssemblies(string.Empty); TestState.AdditionalReferences.AddRange(RegexGeneratorHelper.References); } NumberOfFixAllIterations = numberOfIterations; SolutionTransforms.Add((solution, projectId) => { if (usePreviewLanguageVersion) { CSharpParseOptions parseOptions = solution.GetProject(projectId).ParseOptions as CSharpParseOptions; parseOptions = parseOptions.WithLanguageVersion(LanguageVersion.Preview); solution = solution.WithProjectParseOptions(projectId, parseOptions); } return(solution); }); }
static GenericAnalyzerTest() { string codeAnalysisTestVersion = typeof(Compilation).Assembly.GetName().Version.Major switch { 1 => "1.2.1", 2 => "2.8.2", 3 => "3.3.1", _ => throw new InvalidOperationException("Unknown version."), }; ReferenceAssemblies = ReferenceAssemblies.Default.AddPackages(ImmutableArray.Create( new PackageIdentity("Microsoft.CodeAnalysis.CSharp", codeAnalysisTestVersion), new PackageIdentity("System.ValueTuple", "4.5.0"))); ExportProviderFactory = new Lazy <IExportProviderFactory>( () => { var discovery = new AttributedPartDiscovery(Resolver.DefaultInstance, isNonPublicSupported: true); var parts = Task.Run(() => discovery.CreatePartsAsync(MefHostServices.DefaultAssemblies)).GetAwaiter().GetResult(); var catalog = ComposableCatalog.Create(Resolver.DefaultInstance).AddParts(parts); var configuration = CompositionConfiguration.Create(catalog); var runtimeComposition = RuntimeComposition.CreateRuntimeComposition(configuration); return(runtimeComposition.CreateExportProviderFactory()); }, LazyThreadSafetyMode.ExecutionAndPublication); }
public void AllCanCompile() { var source = @" using System; public class C { public Exception Exception; static void Main() { Console.WriteLine(""Hello World""); } }"; foreach (var kind in Enum.GetValues <ReferenceAssemblyKind>()) { var compilation = CSharpCompilation.Create( "Example", new[] { CSharpSyntaxTree.ParseText(source) }, references: ReferenceAssemblies.Get(kind)); Assert.Empty(compilation.GetDiagnostics()); using var stream = new MemoryStream(); var emitResult = compilation.Emit(stream); Assert.True(emitResult.Success); Assert.Empty(emitResult.Diagnostics); } }
public static T WithReferenceAssemblies <T>(this T compilation, ReferenceAssemblyKind kind) where T : Compilation { var references = ReferenceAssemblies.Get(kind); return((T)(compilation.WithReferences(references))); }
// Add a range of reference files by full path public static void AddReferencesByFullPath(string[] refAsms) { foreach (string asm in refAsms) { ReferenceAssemblies.Add(asm); } }
public EasyEndpointCodeFixTest() { var refs = new ReferenceAssemblies("net6.0", new PackageIdentity("Microsoft.NETCore.App.Ref", "6.0.0"), Path.Combine("ref", "net6.0")); var package = System.Collections.Immutable.ImmutableArray.Create(new PackageIdentity("Easy.Endpoints.Core", "3.1.0")); refs = refs.AddPackages(package); ReferenceAssemblies = refs; }
private EvaluatedProjectState( string name, string assemblyName, string language, ReferenceAssemblies referenceAssemblies, OutputKind outputKind, DocumentationMode documentationMode, ImmutableArray <(string filename, SourceText content)> sources,
// Add a range of reference files by assembly name only public static void AddReferencesByAssemblyName(string[] refAsms) { foreach (string asm in refAsms) { if (FindReferenceAssemblyPath(asm, out string asmFullPath)) { ReferenceAssemblies.Add(asmFullPath); } } }
private static async Task <ImmutableArray <MetadataReference> > CreateReferenceAssembliesAsync() { ReferenceAssemblies referenceAssemblies = ReferenceAssemblies.Net.Net50; ImmutableArray <MetadataReference> references = await referenceAssemblies.ResolveAsync(LanguageNames.CSharp, CancellationToken.None); PortableExecutableReference xunit = MetadataReference.CreateFromFile(typeof(FactAttribute).Assembly.Location); PortableExecutableReference assert = MetadataReference.CreateFromFile(typeof(Assert).Assembly.Location); return(references.AddRange(new[] { xunit, assert })); }
private static Task AnalyzeVBForVersionAsync(string source, ReferenceAssemblies version, params DiagnosticResult[] expected) { var test = new VerifyVB.Test { TestCode = source, ReferenceAssemblies = version, }; test.ExpectedDiagnostics.AddRange(expected); return(test.RunAsync()); }
/// <summary> /// Create a project using the inputted strings as sources. /// </summary> /// <param name="sources">Classes in the form of strings</param> /// <param name="language">The language the source code is in</param> /// <returns>A Project created out of the Documents created from the source strings</returns> private static Project CreateProject(string[] sources, Version dotNetVersion, string language = LanguageNames.CSharp, IEnumerable <MetadataReference> references = null) { string fileNamePrefix = DefaultFilePathPrefix; string fileExt = language == LanguageNames.CSharp ? CSharpDefaultFileExt : VisualBasicDefaultExt; var options = language == LanguageNames.CSharp ? CSharpDefaultOptions : VisualBasicDefaultOptions; var projectId = ProjectId.CreateNewId(debugName: TestProjectName); var refAssemblies = ReferenceAssemblies.GetCache(dotNetVersion ?? new Version(4, 5, 2)); var solution = new AdhocWorkspace() .CurrentSolution .AddProject(projectId, TestProjectName, TestProjectName, language) // Todo: rework assembly references for .NET Core, because currently mscorlib is always referenced // need to reference nuget packages like .AddPackages in https://github.com/dotnet/roslyn-analyzers/blob/master/src/Test.Utilities/AdditionalMetadataReferences.cs .AddMetadataReference(projectId, refAssemblies.GetMetadata("mscorlib.dll")) .AddMetadataReference(projectId, refAssemblies.GetMetadata("System.Core.dll")) .AddMetadataReference(projectId, refAssemblies.GetMetadata("System.dll")) .AddMetadataReference(projectId, refAssemblies.GetMetadata("System.Xml.dll")) .AddMetadataReference(projectId, refAssemblies.GetMetadata("System.Data.dll")) .AddMetadataReference(projectId, CodeAnalysisReference) .WithProjectCompilationOptions(projectId, options); if (references != null) { solution = solution.AddMetadataReferences(projectId, references); } int count = 0; foreach (var source in sources) { var newFileName = $"{fileNamePrefix}{count}.{fileExt}"; var documentId = DocumentId.CreateNewId(projectId, debugName: newFileName); solution = solution.AddDocument(documentId, newFileName, SourceText.From(source)); count++; } var newProject = solution.GetProject(projectId); return(newProject); //var parseOptions = newProject.ParseOptions.WithFeatures( // newProject.ParseOptions.Features.Concat( // new[] { new KeyValuePair<string, string>("flow-analysis", "true") })); //return newProject.WithParseOptions(parseOptions); }
public Test() { ReferenceAssemblies = ReferenceAssemblies.WithPackages(ReferencesHelper.Packages); SolutionTransforms.Add((solution, projectId) => { var compilationOptions = solution.GetProject(projectId).CompilationOptions; compilationOptions = compilationOptions.WithSpecificDiagnosticOptions( compilationOptions.SpecificDiagnosticOptions.SetItems(CSharpVerifierHelper.NullableWarnings)); solution = solution.WithProjectCompilationOptions(projectId, compilationOptions); return(solution); }); }
/// <summary> /// Returns a list of libraries that references the assemblies in <see cref="ReferenceAssemblies"/>. /// By default it returns all assemblies that reference any of the primary MVC assemblies /// while ignoring MVC assemblies. /// </summary> /// <returns>A set of <see cref="Library"/>.</returns> protected virtual IEnumerable <Library> GetCandidateLibraries() { if (ReferenceAssemblies == null) { return(Enumerable.Empty <Library>()); } // GetReferencingLibraries returns the transitive closure of referencing assemblies // for a given assembly. return(ReferenceAssemblies.SelectMany(_libraryManager.GetReferencingLibraries) .Distinct() .Where(IsCandidateLibrary)); }
internal string CompileVisualBasicSource() { var sources = new List <ITaskItem>(); sources.Add(new TaskItem(GeneratedCodeFile)); // If client has added extra user code into the // compile request, add it in now string userCodeFile = UserCodeFile; if (!string.IsNullOrEmpty(userCodeFile)) { sources.Add(new TaskItem(userCodeFile)); } // Transform references into a list of ITaskItems. // Here, we skip over mscorlib explicitly because this is already included as a project reference. var references = ReferenceAssemblies .Where(reference => !reference.EndsWith("mscorlib.dll", StringComparison.Ordinal)) .Select(reference => new TaskItem(reference) as ITaskItem) .ToList(); var buildEngine = MockBuildEngine; var vbc = new Vbc { BuildEngine = buildEngine, NoStandardLib = true, NoConfig = true, TargetType = "library", Sources = sources.ToArray(), References = references.ToArray(), RootNamespace = "TestRootNS", OutputAssembly = new TaskItem(OutputAssemblyName) }; //vbc.SdkPath = @"C:\Windows\Microsoft.NET\Framework\v4.0.30319\"; bool result = false; try { result = vbc.Execute(); } catch (Exception ex) { Assert.Fail("Exception occurred invoking VBC task on " + sources[0].ItemSpec + ":\r\n" + ex); } Assert.IsTrue(result, "VBC failed to compile " + sources[0].ItemSpec + ":\r\n" + buildEngine.ConsoleLogger.Errors); return(vbc.OutputAssembly.ItemSpec); }
public static async Task VerifyAnalyzerAsync( ReferenceAssemblies referenceAssemblies, string source, params DiagnosticResult[] expected) { var test = new Test { TestCode = source, ReferenceAssemblies = referenceAssemblies, }; test.ExpectedDiagnostics.AddRange(expected); await test.RunAsync(); }
public Test(ReferenceAssemblies?references = null) { if (references != null) { ReferenceAssemblies = references; } else { // Clear out the default reference assemblies. We explicitly add references from the live ref pack, // so we don't want the Roslyn test infrastructure to resolve/add any default reference assemblies ReferenceAssemblies = new ReferenceAssemblies(string.Empty); TestState.AdditionalReferences.AddRange(RegexGeneratorHelper.References); } }
public Test() { // Clear out the default reference assemblies. We explicitly add references from the live ref pack, // so we don't want the Roslyn test infrastructure to resolve/add any default reference assemblies ReferenceAssemblies = new ReferenceAssemblies(string.Empty); TestState.AdditionalReferences.AddRange(SourceGenerators.Tests.LiveReferencePack.GetMetadataReferences()); TestState.AdditionalReferences.Add(TestUtils.GetAncillaryReference()); SolutionTransforms.Add((solution, projectId) => { var project = solution.GetProject(projectId) !; var compilationOptions = project.CompilationOptions !; var diagnosticOptions = compilationOptions.SpecificDiagnosticOptions.SetItems(CSharpVerifierHelper.NullableWarnings); // Explicitly enable diagnostics that are not enabled by default var enableAnalyzersOptions = new System.Collections.Generic.Dictionary <string, ReportDiagnostic>(); foreach (var analyzer in GetDiagnosticAnalyzers().ToImmutableArray()) { foreach (var diagnostic in analyzer.SupportedDiagnostics) { if (diagnostic.IsEnabledByDefault) { continue; } // Map the default severity to the reporting behaviour. // We cannot simply use ReportDiagnostic.Default here, as diagnostics that are not enabled by default // are treated as suppressed (regardless of their default severity). var report = diagnostic.DefaultSeverity switch { DiagnosticSeverity.Error => ReportDiagnostic.Error, DiagnosticSeverity.Warning => ReportDiagnostic.Warn, DiagnosticSeverity.Info => ReportDiagnostic.Info, DiagnosticSeverity.Hidden => ReportDiagnostic.Hidden, _ => ReportDiagnostic.Default }; enableAnalyzersOptions.Add(diagnostic.Id, report); } } compilationOptions = compilationOptions.WithSpecificDiagnosticOptions( compilationOptions.SpecificDiagnosticOptions .SetItems(CSharpVerifierHelper.NullableWarnings) .AddRange(enableAnalyzersOptions) .AddRange(TestUtils.BindingRedirectWarnings)); solution = solution.WithProjectCompilationOptions(projectId, compilationOptions); solution = solution.WithProjectParseOptions(projectId, ((CSharpParseOptions)project.ParseOptions !).WithLanguageVersion(LanguageVersion.Preview)); return(solution); }); }
public EvaluatedProjectState(ProjectState state, ReferenceAssemblies defaultReferenceAssemblies) : this( state.Name, state.AssemblyName, state.Language, state.ReferenceAssemblies ?? defaultReferenceAssemblies, state.OutputKind ?? OutputKind.DynamicallyLinkedLibrary, state.DocumentationMode ?? DocumentationMode.Diagnose, state.Sources.ToImmutableArray(), state.AdditionalFiles.ToImmutableArray(), state.AdditionalProjectReferences.ToImmutableArray(), state.AdditionalReferences.ToImmutableArray()) { }
static InterfaceStubGeneratorTests() { #if NET5_0 ReferenceAssemblies = ReferenceAssemblies.Net.Net50; #else ReferenceAssemblies = ReferenceAssemblies.Default .AddPackages(ImmutableArray.Create(new PackageIdentity("System.Text.Json", "5.0.1"))); #endif #if NET461 ReferenceAssemblies = ReferenceAssemblies .AddAssemblies(ImmutableArray.Create("System.Web")) .AddPackages(ImmutableArray.Create(new PackageIdentity("System.Net.Http", "4.3.4"))); #endif }
public static ReferenceAssemblies GetCache(Version dotNetVersion) { ReferenceAssemblies ret; lock (Cache) { if (Cache.TryGetValue(dotNetVersion, out ret)) { return(ret); } ret = new ReferenceAssemblies(dotNetVersion); Cache.Add(dotNetVersion, ret); } return(ret); }
static void BuildAssembly(bool wait) { AssemblyBuilder assemblyBuilder = new AssemblyBuilder(OutputDirectory + OutputFile, SourceFiles.ToArray()); assemblyBuilder.additionalReferences = ReferenceAssemblies.ToArray(); if (AllowUnsafe) { assemblyBuilder.compilerOptions.AllowUnsafeCode = true; } assemblyBuilder.buildStarted += delegate(string assemblyPath) { //Debug.LogFormat("Assembly build started for {0}", assemblyPath); }; assemblyBuilder.buildFinished += delegate(string assemblyPath, CompilerMessage[] compilerMessages) { CompilerMessages.AddRange(compilerMessages); foreach (CompilerMessage cm in compilerMessages) { if (cm.type == CompilerMessageType.Warning) { //Debug.LogWarningFormat("{0}:{1} -- {2}", cm.file, cm.line, cm.message); } else if (cm.type == CompilerMessageType.Error) { Debug.LogErrorFormat("{0}:{1} -- {2}", cm.file, cm.line, cm.message); CompilerErrors = true; } } }; // Start build of assembly if (!assemblyBuilder.Build()) { Debug.LogErrorFormat("Failed to start build of assembly {0}", assemblyBuilder.assemblyPath); return; } if (wait) { while (assemblyBuilder.status != AssemblyBuilderStatus.Finished) { System.Threading.Thread.Sleep(10); } } }
public static (ReferenceAssemblies, MetadataReference) GetReferenceAssemblies() { // TODO: When .NET 6.0 releases, we can simplify this. var referenceAssemblies = new ReferenceAssemblies( "net6.0", new PackageIdentity( "Microsoft.NETCore.App.Ref", "6.0.0-preview.7.21377.19"), Path.Combine("ref", "net6.0")) .WithNuGetConfigFilePath(Path.Combine(Path.GetDirectoryName(typeof(TestUtils).Assembly.Location) !, "NuGet.config")); // Include the assembly containing the new attribute and all of its references. // [TODO] Remove once the attribute has been added to the BCL var attrAssem = typeof(GeneratedDllImportAttribute).GetTypeInfo().Assembly; return(referenceAssemblies, MetadataReference.CreateFromFile(attrAssem.Location)); }
/// <summary> /// Given an array of strings as sources and a language, turn them into a project and return the documents and spans of it. /// </summary> /// <param name="sources">Classes in the form of strings</param> /// <param name="language">The language the source code is in</param> /// <returns>A Tuple containing the Documents produced from the sources and their TextSpans if relevant</returns> private static Document[] GetDocuments(string[] sources, string language, ReferenceAssemblies referenceAssemblies) { if (language != LanguageNames.CSharp && language != LanguageNames.VisualBasic) { throw new ArgumentException("Unsupported Language"); } var project = CreateProject(sources, language, referenceAssemblies); var documents = project.Documents.ToArray(); if (sources.Length != documents.Length) { throw new InvalidOperationException("Amount of sources did not match amount of Documents created"); } return(documents); }
private static async Task VerifyVisualBasicAnalyzerAsync( ReferenceAssemblies referenceAssemblies, string source, params DiagnosticResult[] expected) { var visualBasicTest = new VerifyVB.Test { ReferenceAssemblies = referenceAssemblies, TestState = { Sources = { source }, } }; visualBasicTest.ExpectedDiagnostics.AddRange(expected); await visualBasicTest.RunAsync(); }
private static async Task VerifyCSharpAnalyzerAsync( ReferenceAssemblies referenceAssemblies, string source, params DiagnosticResult[] expected) { var csharpTest = new VerifyCS.Test { ReferenceAssemblies = referenceAssemblies, TestState = { Sources = { source }, } }; csharpTest.ExpectedDiagnostics.AddRange(expected); await csharpTest.RunAsync(); }
public async Task InitializeAsync() { ReferenceAssemblies references = ReferenceAssemblies.NetStandard.NetStandard20 .AddPackages(ImmutableArray.Create( new PackageIdentity("System.Memory", "4.5.4"), new PackageIdentity("Microsoft.Windows.SDK.Contracts", "10.0.19041.1"))); ImmutableArray <MetadataReference> metadataReferences = await references.ResolveAsync(LanguageNames.CSharp, default); // Workaround for https://github.com/dotnet/roslyn-sdk/issues/699 metadataReferences = metadataReferences.AddRange( Directory.GetFiles(Path.Combine(Path.GetTempPath(), "test-packages", "Microsoft.Windows.SDK.Contracts.10.0.19041.1", "ref", "netstandard2.0"), "*.winmd").Select(p => MetadataReference.CreateFromFile(p))); // CONSIDER: How can I pass in the source generator itself, with AdditionalFiles, so I'm exercising that code too? this.compilation = CSharpCompilation.Create( assemblyName: "test", references: metadataReferences, options: new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, allowUnsafe: true)); }
/// <summary> /// Create a project using the inputted strings as sources. /// </summary> /// <param name="sources">Classes in the form of strings</param> /// <param name="language">The language the source code is in</param> /// <returns>A Project created out of the Documents created from the source strings</returns> private static Project CreateProject(string[] sources, Version dotNetVersion, string language = LanguageNames.CSharp, IEnumerable <MetadataReference> references = null) { string fileNamePrefix = DefaultFilePathPrefix; string fileExt = language == LanguageNames.CSharp ? CSharpDefaultFileExt : VisualBasicDefaultExt; var options = language == LanguageNames.CSharp ? CSharpDefaultOptions : VisualBasicDefaultOptions; var projectId = ProjectId.CreateNewId(debugName: TestProjectName); var refAssemblies = ReferenceAssemblies.GetCache(dotNetVersion ?? new Version(4, 5, 2)); var solution = new AdhocWorkspace() .CurrentSolution .AddProject(projectId, TestProjectName, TestProjectName, language) .AddMetadataReference(projectId, refAssemblies.GetMetadata("mscorlib.dll")) .AddMetadataReference(projectId, refAssemblies.GetMetadata("System.Core.dll")) .AddMetadataReference(projectId, refAssemblies.GetMetadata("System.dll")) .AddMetadataReference(projectId, refAssemblies.GetMetadata("System.Xml.dll")) .AddMetadataReference(projectId, refAssemblies.GetMetadata("System.Data.dll")) .AddMetadataReference(projectId, CodeAnalysisReference) .WithProjectCompilationOptions(projectId, options); if (references != null) { solution = solution.AddMetadataReferences(projectId, references); } int count = 0; foreach (var source in sources) { var newFileName = fileNamePrefix + count + "." + fileExt; var documentId = DocumentId.CreateNewId(projectId, debugName: newFileName); solution = solution.AddDocument(documentId, newFileName, SourceText.From(source)); count++; } return(solution.GetProject(projectId)); }
public AnalyzerTest( string source, IEnumerable <Assembly> additionalReferences, params DiagnosticResult[] expected) { TestCode = source; ExpectedDiagnostics.AddRange(expected); #if NET6_0 ReferenceAssemblies = new ReferenceAssemblies("net6.0", new PackageIdentity("Microsoft.NETCore.App.Ref", "6.0.0"), Path.Combine("ref", "net6.0")); #else ReferenceAssemblies = ReferenceAssemblies.Net.Net50; #endif foreach (var additionalReference in additionalReferences) { TestState.AdditionalReferences.Add(additionalReference); } this.DisableNullableReferenceWarnings(); }