Exemplo n.º 1
0
        /// <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>
        /// <param name="hasEntrypoint"><c>true</c> to set the compiler in a mode as if it were compiling an exe (as opposed to a dll).</param>
        /// <returns>A Project created out of the Documents created from the source strings</returns>
        protected static Project CreateProject(string[] sources, string language = LanguageNames.CSharp, bool hasEntrypoint = false)
        {
            string fileNamePrefix = DefaultFilePathPrefix;
            string fileExt        = language == LanguageNames.CSharp ? CSharpDefaultFileExt : VisualBasicDefaultExt;

            var projectId = ProjectId.CreateNewId(debugName: TestProjectName);

            var solution = new AdhocWorkspace()
                           .CurrentSolution
                           .AddProject(projectId, TestProjectName, TestProjectName, language)
                           .AddMetadataReference(projectId, CorlibReference)
                           .AddMetadataReference(projectId, SystemReference)
                           .AddMetadataReference(projectId, SystemCoreReference)
                           .AddMetadataReference(projectId, CSharpSymbolsReference)
                           .AddMetadataReference(projectId, CodeAnalysisReference)
                           .AddMetadataReference(projectId, ThreadingReference)
                           .AddMetadataReference(projectId, WindowsBaseReference)
                           .AddMetadataReference(projectId, OleInteropReference)
                           .WithProjectCompilationOptions(projectId, new CSharpCompilationOptions(hasEntrypoint ? OutputKind.ConsoleApplication : OutputKind.DynamicallyLinkedLibrary))
                           .WithProjectParseOptions(projectId, new CSharpParseOptions(LanguageVersion.Latest));

            var pathToLibs = ToolLocationHelper.GetPathToStandardLibraries(".NETFramework", "v4.5.1", string.Empty);

            if (!string.IsNullOrEmpty(pathToLibs))
            {
                var facades = Path.Combine(pathToLibs, "Facades");
                if (Directory.Exists(facades))
                {
                    var facadesAssemblies = new List <MetadataReference>();
                    foreach (var path in Directory.EnumerateFiles(facades, "*.dll"))
                    {
                        facadesAssemblies.Add(MetadataReference.CreateFromFile(path));
                    }

                    solution = solution.AddMetadataReferences(projectId, facadesAssemblies);
                }
            }

            string nugetPackageRoot = Path.Combine(
                Environment.GetEnvironmentVariable("USERPROFILE"),
                ".nuget",
                "packages");
            var vssdkReferences = VSSDKPackageReferences.Select(e =>
                                                                MetadataReference.CreateFromFile(Path.Combine(nugetPackageRoot, e)));

            solution = solution.AddMetadataReferences(projectId, vssdkReferences);

            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));
        }
        /// <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, string language = LanguageNames.CSharp, IEnumerable <MetadataReference> references = null)
        {
            string fileNamePrefix = DefaultFilePathPrefix;
            string fileExt        = language == LanguageNames.CSharp ? CSharpDefaultFileExt : VisualBasicDefaultExt;

            var projectId = ProjectId.CreateNewId(debugName: TestProjectName);

            var solution = new AdhocWorkspace()
                           .CurrentSolution
                           .AddProject(projectId, TestProjectName, TestProjectName, language)
                           .AddMetadataReference(projectId, CorlibReference)
                           .AddMetadataReference(projectId, SystemCoreReference)
                           .AddMetadataReference(projectId, CSharpSymbolsReference)
                           .AddMetadataReference(projectId, CodeAnalysisReference)
                           .AddMetadataReference(projectId, SystemDiagReference);

            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 static Solution CreateSolutionWithSingleProject(string[] sources, MetadataReference[] references, FakeFileInfo fakeFileInfo)
        {
            fakeFileInfo = fakeFileInfo ?? DefaultFileInfo;
            var projectId = ProjectId.CreateNewId(debugName: TestProjectName);

            var solution = new AdhocWorkspace()
                           .CurrentSolution
                           .AddProject(projectId, TestProjectName, TestProjectName, LanguageNames.CSharp)
                           .WithProjectCompilationOptions(projectId, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
                           .AddMetadataReferences(projectId, ReferencesHelper.CoreDotNetReferences);

            if (references != null)
            {
                solution = solution.AddMetadataReferences(projectId, references.Distinct());
            }

            var count = 0;

            foreach (var source in sources)
            {
                var newFileName = fakeFileInfo.GetFullFilePath(count++);
                var documentId  = DocumentId.CreateNewId(projectId, debugName: newFileName);
                var sourceText  = SourceText.From(source);

                solution = solution.AddDocument(documentId, newFileName, sourceText);
            }

            return(solution);
        }
        /// <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);
        }
Exemplo n.º 5
0
        public void Test1()
        {
            var file = $"{TestContext.CurrentContext.TestDirectory}/../../../TestRoslyn.cs";
            var assemblies = new[] { typeof(object), typeof(Enumerable), typeof(TestAttribute) }.Select(x => x.Assembly.Location).ToArray();

            var project = new AdhocWorkspace().AddProject("test", LanguageNames.CSharp);

            project = project.AddDocument(Path.GetFileName(file), File.ReadAllText(file)).Project;
            project = project.AddMetadataReferences(assemblies.Select(x => MetadataReference.CreateFromFile(x)));

            var compilation = project.GetCompilationAsync().GetAwaiter().GetResult();
            var c           = compilation.WithAnalyzers(ImmutableArray.Create((DiagnosticAnalyzer) new AssertEqualsAnalyzer()));
            var diagnostics = c.GetAnalyzerDiagnosticsAsync().GetAwaiter().GetResult();
        }
Exemplo n.º 6
0
        public async Task FindReferences_DifferingAssemblies()
        {
            var solution = new AdhocWorkspace().CurrentSolution;

            solution = AddProjectWithMetadataReferences(solution, "NetStandardProject", LanguageNames.CSharp, @"
namespace N
{
    public interface I
    {
        System.Uri Get();
    }
}", NetStandard20Ref);

            solution = AddProjectWithMetadataReferences(solution, "DesktopProject", LanguageNames.CSharp, @"
using N;

namespace N2 
{
    public class Impl : I
    {
        public System.Uri Get()
        {
            return null;
        }
    }
}", SystemRef_v46, solution.Projects.Single(pid => pid.Name == "NetStandardProject").Id);

            var desktopProject = solution.Projects.First(p => p.Name == "DesktopProject");

            solution = solution.AddMetadataReferences(desktopProject.Id, new[] { MscorlibRef_v46, Net46StandardFacade });

            desktopProject = solution.GetProject(desktopProject.Id);
            var netStandardProject = solution.Projects.First(p => p.Name == "NetStandardProject");

            var interfaceMethod = (IMethodSymbol)(await netStandardProject.GetCompilationAsync()).GetTypeByMetadataName("N.I").GetMembers("Get").First();

            var references = (await SymbolFinder.FindReferencesAsync(interfaceMethod, solution)).ToList();

            Assert.Equal(2, references.Count);

            var projectIds = new HashSet <ProjectId>();

            foreach (var r in references)
            {
                projectIds.Add(solution.GetOriginatingProjectId(r.Definition));
            }

            Assert.True(projectIds.Contains(desktopProject.Id));
        }
Exemplo n.º 7
0
        /// <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 async Task <Project> CreateProject(
            string[]                           sources,
            Version dotNetVersion,
            CancellationToken cancellationToken,
            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 = await GetReferenceAssemblies(dotNetVersion).ResolveAsync(language, cancellationToken).ConfigureAwait(false);

            var solution = new AdhocWorkspace()
                           .CurrentSolution
                           .AddProject(projectId, TestProjectName, TestProjectName, language)
                           .AddMetadataReferences(projectId, refAssemblies)
                           .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);
        }
        /// <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));
        }
Exemplo n.º 9
0
        /// <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>
        public static Project CreateProject(this string[] sources, IEnumerable <MetadataReference> additionalReferences, string language = LanguageNames.CSharp)
        {
            string fileNamePrefix = DefaultFilePathPrefix;
            string fileExt        = language == LanguageNames.CSharp ? CSharpDefaultFileExt : VisualBasicDefaultExt;

            var projectId = ProjectId.CreateNewId(debugName: TestProjectName);

            var solution = new AdhocWorkspace()
                           .CurrentSolution
                           .AddProject(projectId, TestProjectName, TestProjectName, language)
                           .AddMetadataReference(projectId, CorlibReference)
                           .AddMetadataReference(projectId, SystemCoreReference)
                           .AddMetadataReference(projectId, DataReference)
                           .AddMetadataReference(projectId, NetStandardReference)
                           .AddMetadataReference(projectId, SystemRuntimeReference)
                           .AddMetadataReference(projectId, SystemLinqExpressionsReference);

            if (additionalReferences != null)
            {
                foreach (var additionalReference in additionalReferences)
                {
                    solution = solution.AddMetadataReferences(projectId, additionalReferences);
                }
            }

            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));
        }
Exemplo n.º 10
0
        /// <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>
        /// <param name="hasEntrypoint"><c>true</c> to set the compiler in a mode as if it were compiling an exe (as opposed to a dll).</param>
        /// <param name="includeSDKReferences"><c>true</c> to include VS SDK reference assemblies in the project.</param>
        /// <returns>A Project created out of the Documents created from the source strings</returns>
        protected static Project CreateProject(string[] sources, string language = LanguageNames.CSharp, bool hasEntrypoint = false, bool includeSDKReferences = true)
        {
            string fileNamePrefix = DefaultFilePathPrefix;
            string fileExt        = language == LanguageNames.CSharp ? CSharpDefaultFileExt : throw new NotSupportedException();

            var projectId = ProjectId.CreateNewId(debugName: TestProjectName);

            var solution = new AdhocWorkspace()
                           .CurrentSolution
                           .AddProject(projectId, TestProjectName, TestProjectName, language)
                           .AddMetadataReference(projectId, CorlibReference)
                           .AddMetadataReference(projectId, SystemReference)
                           .AddMetadataReference(projectId, PresentationFrameworkReference)
                           .AddMetadataReference(projectId, SystemCoreReference)
                           .AddMetadataReference(projectId, MPFReference)
                           .WithProjectCompilationOptions(projectId, new CSharpCompilationOptions(
                                                              hasEntrypoint ? OutputKind.ConsoleApplication : OutputKind.DynamicallyLinkedLibrary,
                                                              specificDiagnosticOptions: new Dictionary <string, ReportDiagnostic>
            {
                { "CS1701", ReportDiagnostic.Suppress },         // we don't reference mscorlib, which can cause assembly reference ambiguities
            }))
                           .WithProjectParseOptions(projectId, new CSharpParseOptions(LanguageVersion.CSharp6));

            var pathToLibs = ToolLocationHelper.GetPathToStandardLibraries(".NETFramework", "v4.5.1", string.Empty);

            if (!string.IsNullOrEmpty(pathToLibs))
            {
                var facades = Path.Combine(pathToLibs, "Facades");
                if (Directory.Exists(facades))
                {
                    var facadesAssemblies = new List <MetadataReference>();
                    foreach (var path in Directory.EnumerateFiles(facades, "*.dll"))
                    {
                        facadesAssemblies.Add(MetadataReference.CreateFromFile(path));
                    }

                    solution = solution.AddMetadataReferences(projectId, facadesAssemblies);
                }
            }

            if (includeSDKReferences)
            {
                string globalPackagesFolder = Environment.GetEnvironmentVariable("NuGetGlobalPackagesFolder");
                string nugetPackageRoot     = string.IsNullOrEmpty(globalPackagesFolder)
                    ? Path.Combine(
                    Environment.GetEnvironmentVariable("USERPROFILE"),
                    ".nuget",
                    "packages")
                    : globalPackagesFolder;
                var vssdkReferences = VSSDKPackageReferences.Select(e =>
                                                                    MetadataReference.CreateFromFile(Path.Combine(nugetPackageRoot, e)));
                solution = solution.AddMetadataReferences(projectId, vssdkReferences);
            }

            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));
        }
Exemplo n.º 11
0
        static async Task <Diagnostic[]> GetSortedDiagnostics(string[] sources, DiagnosticAnalyzer analyzer, CancellationToken cancellationToken)
        {
            var projectId = ProjectId.CreateNewId("TestProject");

            var solution = new AdhocWorkspace()
                           .CurrentSolution
                           .AddProject(projectId, "TestProject", "TestProject", LanguageNames.CSharp)
                           .AddMetadataReference(projectId, CorlibReference)
                           .AddMetadataReference(projectId, SystemCoreReference)
                           .AddMetadataReference(projectId, CSharpSymbolsReference)
                           .AddMetadataReference(projectId, CodeAnalysisReference)
                           .AddMetadataReference(projectId, TestLib)
                           .AddMetadataReference(projectId, NServiceBusReference);

#if NETCOREAPP
            var netstandard   = MetadataReference.CreateFromFile(System.Reflection.Assembly.Load("netstandard").Location);
            var systemTasks   = MetadataReference.CreateFromFile(System.Reflection.Assembly.Load("System.Threading.Tasks").Location);
            var systemRuntime = MetadataReference.CreateFromFile(System.Reflection.Assembly.Load("System.Runtime").Location);
            solution = solution.AddMetadataReferences(projectId, new[]
            {
                netstandard,
                systemRuntime,
                systemTasks
            });
#endif

            var documentIndex = 0;
            foreach (var source in sources)
            {
                var fileName = "Test" + documentIndex + ".cs";
                solution = solution.AddDocument(DocumentId.CreateNewId(projectId, fileName), fileName, SourceText.From(source));
                documentIndex++;
            }

            var documents = solution.GetProject(projectId).Documents.ToList();

            if (sources.Length != documents.Count)
            {
                throw new InvalidOperationException("The number of documents created does not match the number of sources.");
            }

            var diagnostics = new List <Diagnostic>();
            foreach (var project in new HashSet <Project>(documents.Select(document => document.Project)))
            {
                var compilationWithAnalyzers = (await project.GetCompilationAsync(cancellationToken)).WithAnalyzers(ImmutableArray.Create(analyzer), cancellationToken: cancellationToken);

                foreach (var diagnostic in await compilationWithAnalyzers.GetAnalyzerDiagnosticsAsync(cancellationToken))
                {
                    if (diagnostic.Location == Location.None || diagnostic.Location.IsInMetadata)
                    {
                        diagnostics.Add(diagnostic);
                    }
                    else
                    {
                        foreach (var document in documents)
                        {
                            if (await document.GetSyntaxTreeAsync(cancellationToken) == diagnostic.Location.SourceTree)
                            {
                                diagnostics.Add(diagnostic);
                            }
                        }
                    }
                }
            }

            return(diagnostics.OrderBy(diagnostic => diagnostic.Location.SourceSpan.Start).ToArray());
        }