Exemplo n.º 1
0
		internal static Document CreateDocument(string code, string fileName,
			Func<Solution, ProjectId, Solution> modifySolution)
		{
			var projectName = "Test";
			var projectId = ProjectId.CreateNewId(projectName);

			var solution = new AdhocWorkspace()
				 .CurrentSolution
				 .AddProject(projectId, projectName, projectName, LanguageNames.CSharp)
				 .AddMetadataReference(projectId,
					MetadataReference.CreateFromFile(typeof(object).Assembly.Location))
				 .AddMetadataReference(projectId,
					MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location))
				 .AddMetadataReference(projectId,
					MetadataReference.CreateFromFile(typeof(CSharpCompilation).Assembly.Location))
				 .AddMetadataReference(projectId,
					MetadataReference.CreateFromFile(typeof(Compilation).Assembly.Location));

			var documentId = DocumentId.CreateNewId(projectId);
			solution = solution.AddDocument(documentId, fileName, SourceText.From(code));

			if(modifySolution != null)
			{
				solution = modifySolution(solution, projectId);
			}

			return solution.GetProject(projectId).Documents.First();
		}
Exemplo n.º 2
0
        private static Project CreateProject(string filePath)
        {
            var projectId = ProjectId.CreateNewId(TestProjectName);
            var source = File.ReadAllText(filePath);
            var fileName = Path.GetFileName(filePath);
            var documentId = DocumentId.CreateNewId(projectId, fileName);

            var solution = new AdhocWorkspace()
                .CurrentSolution
                .AddProject(projectId, TestProjectName, TestProjectName, LanguageNames.CSharp)
                .AddMetadataReference(projectId, CorlibReference)
                .AddMetadataReference(projectId, SystemCoreReference)
                .AddDocument(documentId, fileName, SourceText.From(source));

            return solution.GetProject(projectId);
        }
Exemplo n.º 3
0
        static Project CreateProject(string source)
        {
            var assemblyPath = Path.GetDirectoryName(typeof(object).Assembly.Location);

            var projectId = ProjectId.CreateNewId();
            var solution = new AdhocWorkspace()
                .CurrentSolution
                .AddProject(projectId, "TestProject", "TestProject", LanguageNames.CSharp)
                .WithProjectCompilationOptions(projectId, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
                .AddMetadataReference(projectId, MetadataReference.CreateFromFile(typeof(object).Assembly.Location))
                .AddMetadataReference(projectId, MetadataReference.CreateFromFile(typeof(Enumerable).Assembly.Location))
                .AddMetadataReference(projectId, MetadataReference.CreateFromFile(Path.Combine(assemblyPath, "System.Runtime.dll")))
                .AddMetadataReference(projectId, MetadataReference.CreateFromFile(typeof(ConstAttribute).Assembly.Location));
            var documentId = DocumentId.CreateNewId(projectId);
            solution = solution.AddDocument(documentId, "Test.cs", SourceText.From(source));
            return solution.GetProject(projectId);
        }
Exemplo n.º 4
0
    internal static Document Create(string code)
    {
      var projectName = "Test";
      var projectId = ProjectId.CreateNewId(projectName);

      var solution = new AdhocWorkspace()
         .CurrentSolution
         .AddProject(projectId, projectName, projectName, LanguageNames.CSharp)
         .WithProjectCompilationOptions(projectId, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
         .AddMetadataReference(projectId, MetadataReference.CreateFromAssembly(typeof(object).Assembly))
         .AddMetadataReference(projectId, MetadataReference.CreateFromAssembly(typeof(Enumerable).Assembly))
         .AddMetadataReference(projectId, MetadataReference.CreateFromAssembly(typeof(CSharpCompilation).Assembly))
         .AddMetadataReference(projectId, MetadataReference.CreateFromAssembly(typeof(Compilation).Assembly))
         .AddMetadataReference(projectId, MetadataReference.CreateFromAssembly(typeof(BusinessBase<>).Assembly));

      var documentId = DocumentId.CreateNewId(projectId);
      solution = solution.AddDocument(documentId, "Test.cs", SourceText.From(code));

      return solution.GetProject(projectId).Documents.First();
    }
        private Project CreateSolution(string source)
        {
            var testProjectName = "Test";
            var projectId = ProjectId.CreateNewId(testProjectName);

            var references = new[]
                {
                    s_CorlibReference,
                    s_SystemCoreReference,
                    s_MSTestReference,
                    s_XunitReference
                };

            var solution = new AdhocWorkspace()
                .CurrentSolution
                .AddProject(projectId, testProjectName, testProjectName, LanguageNames.CSharp)
                .AddMetadataReferences(projectId, references);

            var fileName = "File.cs";
            var documentId = DocumentId.CreateNewId(projectId, fileName);
            solution = solution.AddDocument(documentId, fileName, SourceText.From(source));
            return solution.GetProject(projectId);
        }
Exemplo n.º 6
0
        public void TestGetProjectForAssemblySymbol()
        {
            var pid1 = ProjectId.CreateNewId("p1");
            var pid2 = ProjectId.CreateNewId("p2");
            var pid3 = ProjectId.CreateNewId("p3");
            var did1 = DocumentId.CreateNewId(pid1);
            var did2 = DocumentId.CreateNewId(pid2);
            var did3 = DocumentId.CreateNewId(pid3);

            var text1 = @"
Public Class A
End Class";

            var text2 = @"
Public Class B
End Class
";

            var text3 = @"
public class C : B {
}
";

            var text4 = @"
public class C : A {
}
";

            var solution = new AdhocWorkspace().CurrentSolution
                .AddProject(pid1, "FooA", "Foo.dll", LanguageNames.VisualBasic)
                .AddDocument(did1, "A.vb", text1)
                .AddMetadataReference(pid1, s_mscorlib)
                .AddProject(pid2, "FooB", "Foo2.dll", LanguageNames.VisualBasic)
                .AddDocument(did2, "B.vb", text2)
                .AddMetadataReference(pid2, s_mscorlib)
                .AddProject(pid3, "Bar", "Bar.dll", LanguageNames.CSharp)
                .AddDocument(did3, "C.cs", text3)
                .AddMetadataReference(pid3, s_mscorlib)
                .AddProjectReference(pid3, new ProjectReference(pid1))
                .AddProjectReference(pid3, new ProjectReference(pid2));

            var project3 = solution.GetProject(pid3);
            var comp3 = project3.GetCompilationAsync().Result;
            var classC = comp3.GetTypeByMetadataName("C");
            var projectForBaseType = solution.GetProject(classC.BaseType.ContainingAssembly);
            Assert.Equal(pid2, projectForBaseType.Id);

            // switch base type to A then try again
            var solution2 = solution.WithDocumentText(did3, SourceText.From(text4));
            project3 = solution2.GetProject(pid3);
            comp3 = project3.GetCompilationAsync().Result;
            classC = comp3.GetTypeByMetadataName("C");
            projectForBaseType = solution2.GetProject(classC.BaseType.ContainingAssembly);
            Assert.Equal(pid1, projectForBaseType.Id);
        }
        private static Project CreateProject(string[] sources, string language = LanguageNames.VisualBasic)
#endif
        {
            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)
#if CSHARP
                .WithProjectCompilationOptions(projectId, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
#elif VISUAL_BASIC
                .WithProjectCompilationOptions(projectId, new VisualBasicCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
#endif
                .AddMetadataReference(projectId, CorlibReference)
                .AddMetadataReference(projectId, SystemCoreReference)
#if CSHARP
                .AddMetadataReference(projectId, CSharpSymbolsReference)
#elif VISUAL_BASIC
                .AddMetadataReference(projectId, VisualBasicSymbolsReference)
#endif
                .AddMetadataReference(projectId, CodeAnalysisReference)
                .AddMetadataReference(projectId, FakeItEasyReference);

            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>
        /// Creates a solution that will be used as parent for the sources that need to be checked.
        /// </summary>
        /// <param name="projectId">The project identifier to use.</param>
        /// <param name="language">The language for which the solution is being created.</param>
        /// <returns>The created solution.</returns>
        protected virtual Solution CreateSolution(ProjectId projectId, string language)
        {
            var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, allowUnsafe: true);

            var additionalDiagnosticOptions = this.GetDisabledDiagnostics().Select(id => new KeyValuePair<string, ReportDiagnostic>(id, ReportDiagnostic.Suppress));
            var newSpecificOptions = compilationOptions.SpecificDiagnosticOptions.AddRange(additionalDiagnosticOptions);
            compilationOptions = compilationOptions.WithSpecificDiagnosticOptions(newSpecificOptions);

            Solution solution = new AdhocWorkspace()
                .CurrentSolution
                .AddProject(projectId, TestProjectName, TestProjectName, language)
                .WithProjectCompilationOptions(projectId, compilationOptions)
                .AddMetadataReference(projectId, MetadataReferences.CorlibReference)
                .AddMetadataReference(projectId, MetadataReferences.SystemReference)
                .AddMetadataReference(projectId, MetadataReferences.SystemCoreReference)
                .AddMetadataReference(projectId, MetadataReferences.CSharpSymbolsReference)
                .AddMetadataReference(projectId, MetadataReferences.CodeAnalysisReference);

            var settings = this.GetSettings();
            if (!string.IsNullOrEmpty(settings))
            {
                var documentId = DocumentId.CreateNewId(projectId);
                solution = solution.AddAdditionalDocument(documentId, SettingsFileName, settings);
            }

            ParseOptions parseOptions = solution.GetProject(projectId).ParseOptions;
            return solution.WithProjectParseOptions(projectId, parseOptions.WithDocumentationMode(DocumentationMode.Diagnose));
        }
        /// <summary>
        /// Creates a solution that will be used as parent for the sources that need to be checked.
        /// </summary>
        /// <param name="projectId">The project identifier to use.</param>
        /// <param name="language">The language for which the solution is being created.</param>
        /// <returns>The created solution.</returns>
        protected virtual Solution CreateSolution(ProjectId projectId, string language)
        {
            Solution solution = new AdhocWorkspace()
                .CurrentSolution
                .AddProject(projectId, TestProjectName, TestProjectName, language)
                .WithProjectCompilationOptions(projectId, new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, allowUnsafe: true))
                .AddMetadataReference(projectId, CorlibReference)
                .AddMetadataReference(projectId, SystemReference)
                .AddMetadataReference(projectId, SystemCoreReference)
                .AddMetadataReference(projectId, CSharpSymbolsReference)
                .AddMetadataReference(projectId, CodeAnalysisReference);

            ParseOptions parseOptions = solution.GetProject(projectId).ParseOptions;
            return solution.WithProjectParseOptions(projectId, parseOptions.WithDocumentationMode(DocumentationMode.Diagnose));
        }
        protected Project CreateProject(Dictionary<string, string> sources)
        {
            string fileNamePrefix = DefaultFilePathPrefix;
            string fileExt = CSharpDefaultFileExt;

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

            var solution = new AdhocWorkspace()
                .CurrentSolution
                .AddProject(projectId, TestProjectName, TestProjectName, LanguageNames.CSharp);

            foreach (var reference in References)
            {
                solution = solution.AddMetadataReference(projectId, reference);
            }

            int count = 0;
            foreach (var source in sources)
            {
                var newFileName = source.Key;
                var documentId = DocumentId.CreateNewId(projectId, debugName: newFileName);
                solution = solution.AddDocument(documentId, newFileName, SourceText.From(source.Value));
                count++;
            }

            var project = solution.GetProject(projectId)
                .WithCompilationOptions(CompilationOptions);
            return project;
        }
        private Project CreateProject(IEnumerable<string> sourceCodes)
        {
            ProjectId projectId = ProjectId.CreateNewId(debugName: ADHOC_PROJECT_NAME);
            Solution solution = new AdhocWorkspace()
                .CurrentSolution
                .AddProject(projectId, ADHOC_PROJECT_NAME, ADHOC_PROJECT_NAME, LanguageNames.CSharp)
                .AddMetadataReferences(projectId, new[]
                {
                    CorlibReference,
                    SystemCoreReference,
                    CSharpSymbolsReference,
                    CodeAnalysisReference
                });

            string sourceFileName;
            DocumentId documentId;
            int index = 0;
            foreach (string sourceCode in sourceCodes)
            {
                sourceFileName = $"Test{index++}.cs";
                documentId = DocumentId.CreateNewId(projectId, debugName: sourceFileName);
                solution = solution.AddDocument(documentId, sourceFileName, SourceText.From(sourceCode));
            }

            return solution.GetProject(projectId);
        }
Exemplo n.º 12
0
		private static Project CreateProject(string[] sources, string language)
		{
			var fileExt = language == LanguageNames.CSharp ? CSharpDefaultFileExt : VisualBasicDefaultExt;
			var projectId = ProjectId.CreateNewId(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, OpenTKReference);

			for (int i = 0; i < sources.Length; i++)
			{
				var newFileName = DefaultFilePathPrefix + i + "." + fileExt;
				var documentId = DocumentId.CreateNewId(projectId, newFileName);
				solution = solution.AddDocument(documentId, newFileName, SourceText.From(sources[i]));
			}
			return solution.GetProject(projectId);
		}
Exemplo n.º 13
0
        public void PinvokeMethodReferences_VB()
        {
            var tree = Microsoft.CodeAnalysis.VisualBasic.VisualBasicSyntaxTree.ParseText(
                @"
Module Module1
        Declare Function CreateDirectory Lib ""kernel32"" Alias ""CreateDirectoryA"" (ByVal lpPathName As String) As Integer
 
        Private prop As Integer
        Property Prop1 As Integer
            Get
                Return prop
            End Get
            Set(value As Integer)
                CreateDirectory(""T"")  ' Method Call 1
                prop = value
                prop = Nothing
            End Set
        End Property

        Sub Main()
          CreateDirectory(""T"") 'Method Call 2            
          NormalMethod() ' Method Call 1
          NormalMethod() ' Method Call 2
       End Sub

       Sub NormalMethod()
       End Sub
 End Module
            ");

            ProjectId prj1Id = ProjectId.CreateNewId();
            DocumentId docId = DocumentId.CreateNewId(prj1Id);

            Microsoft.CodeAnalysis.Solution sln = new AdhocWorkspace().CurrentSolution
                .AddProject(prj1Id, "testDeclareReferences", "testAssembly", LanguageNames.VisualBasic)
                .AddMetadataReference(prj1Id, MscorlibRef)
                .AddDocument(docId, "testFile", tree.GetText());

            Microsoft.CodeAnalysis.Project prj = sln.GetProject(prj1Id).WithCompilationOptions(new VisualBasic.VisualBasicCompilationOptions(OutputKind.ConsoleApplication, embedVbCoreRuntime: true));
            tree = (SyntaxTree)prj.GetDocument(docId).GetSyntaxTreeAsync().Result;
            Compilation comp = prj.GetCompilationAsync().Result;

            SemanticModel semanticModel = comp.GetSemanticModel(tree);

            SyntaxNode declareMethod = tree.GetRoot().DescendantNodes().OfType<Microsoft.CodeAnalysis.VisualBasic.Syntax.DeclareStatementSyntax>().FirstOrDefault();
            SyntaxNode normalMethod = tree.GetRoot().DescendantNodes().OfType<Microsoft.CodeAnalysis.VisualBasic.Syntax.MethodStatementSyntax>().ToList()[1];

            // declared method calls
            var symbol = semanticModel.GetDeclaredSymbol(declareMethod);
            var references = SymbolFinder.FindReferencesAsync(symbol, prj.Solution).Result;
            Assert.Equal(expected: 2, actual: references.ElementAt(0).Locations.Count());

            // normal method calls
            symbol = semanticModel.GetDeclaredSymbol(normalMethod);
            references = SymbolFinder.FindReferencesAsync(symbol, prj.Solution).Result;
            Assert.Equal(expected: 2, actual: references.ElementAt(0).Locations.Count());
        }
        /// <summary>
        /// Creates a solution that will be used as parent for the sources that need to be checked.
        /// </summary>
        /// <param name="projectId">The project identifier to use.</param>
        /// <param name="language">The language for which the solution is being created.</param>
        /// <returns>The created solution.</returns>
        protected virtual Solution CreateSolution(ProjectId projectId, string language)
        {
            var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, allowUnsafe: true);

            Solution solution = new AdhocWorkspace()
                .CurrentSolution
                .AddProject(projectId, TestProjectName, TestProjectName, language)
                .WithProjectCompilationOptions(projectId, compilationOptions)
                .AddMetadataReference(projectId, MetadataReferences.CorlibReference)
                .AddMetadataReference(projectId, MetadataReferences.SystemReference)
                .AddMetadataReference(projectId, MetadataReferences.SystemCoreReference)
                .AddMetadataReference(projectId, MetadataReferences.CSharpSymbolsReference)
                .AddMetadataReference(projectId, MetadataReferences.CodeAnalysisReference);

            var settings = this.GetSettings();
            if (!string.IsNullOrEmpty(settings))
            {
                var documentId = DocumentId.CreateNewId(projectId);
                solution = solution.AddAdditionalDocument(documentId, SettingsHelper.PublicApiFileName, settings);
            }

            ParseOptions parseOptions = solution.GetProject(projectId).ParseOptions;
            return solution.WithProjectParseOptions(projectId, parseOptions.WithDocumentationMode(DocumentationMode.Diagnose));
        }
Exemplo n.º 15
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 Project CreateProject(string[] sources)
        {
            string TestProjectName = "TestProject";

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

            var solution = new AdhocWorkspace()
                    .CurrentSolution
                    .AddProject(projectId, TestProjectName, TestProjectName, LanguageNames.CSharp)
                    .AddMetadataReference(projectId, CorlibReference)
                    .AddMetadataReference(projectId, SystemCoreReference)
                    .AddMetadataReference(projectId, CSharpSymbolsReference)
                    .AddMetadataReference(projectId, CodeAnalysisReference)
                    .AddMetadataReference(projectId, EntityReference)
                    .AddMetadataReference(projectId, UtilitiesReference);

            int count = 0;
            foreach (var source in sources)
            {
                var newFileName = "Test" + count + ".cs";
                var documentId = DocumentId.CreateNewId(projectId, debugName: newFileName);
                solution = solution.AddDocument(documentId, newFileName, SourceText.From(source));
                count++;
            }
            return solution.GetProject(projectId);
        }
Exemplo n.º 16
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 Douments created from the source strings</returns>
        private static Project CreateProject(IEnumerable<string> sources, string language = LanguageNames.CSharp)
        {
            var extension = language == LanguageNames.CSharp ? CSharpFileExtension : VisualBasicFileExtension;
            var projectId = ProjectId.CreateNewId(ProjectName);

            var solution = new AdhocWorkspace()
                .CurrentSolution
                .AddProject(projectId, ProjectName, ProjectName, language)
                .AddMetadataReferences(projectId, new[] { CorlibReference, SystemCoreReference, CSharpSymbolsReference, CodeAnalysisReference });

            var count = 0;
            foreach (var source in sources)
            {
                var newFileName = string.Format(FileNameTemplate, count, extension);
                var documentId = DocumentId.CreateNewId(projectId, newFileName);
                solution = solution.AddDocument(documentId, newFileName, SourceText.From(source));
                count++;
            }

            return solution.GetProject(projectId);
        }
        /// <summary>
        /// Creates a solution that will be used as parent for the sources that need to be checked.
        /// </summary>
        /// <param name="projectId">The project identifier to use.</param>
        /// <param name="language">The language for which the solution is being created.</param>
        /// <returns>The created solution.</returns>
        protected virtual Solution CreateSolution(ProjectId projectId, string language)
        {
            var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, allowUnsafe: true);

            Solution solution = new AdhocWorkspace()
                .CurrentSolution
                .AddProject(projectId, TestProjectName, TestProjectName, language)
                .WithProjectCompilationOptions(projectId, compilationOptions)
                .AddMetadataReference(projectId, MetadataReferences.CorlibReference)
                .AddMetadataReference(projectId, MetadataReferences.SystemReference)
                .AddMetadataReference(projectId, MetadataReferences.SystemCoreReference)
                .AddMetadataReference(projectId, MetadataReferences.CSharpSymbolsReference)
                .AddMetadataReference(projectId, MetadataReferences.CodeAnalysisReference);

            var publicApi = this.GetUnshippedPublicApi();
            if (publicApi != null)
            {
                var documentId = DocumentId.CreateNewId(projectId);
                solution = solution.AddAdditionalDocument(documentId, DeclarePublicAPIAnalyzer.UnshippedFileName, publicApi);
            }

            publicApi = this.GetShippedPublicApi();
            if (publicApi != null)
            {
                var documentId = DocumentId.CreateNewId(projectId);
                solution = solution.AddAdditionalDocument(documentId, DeclarePublicAPIAnalyzer.ShippedFileName, publicApi);
            }

            ParseOptions parseOptions = solution.GetProject(projectId).ParseOptions;
            return solution.WithProjectParseOptions(projectId, parseOptions.WithDocumentationMode(DocumentationMode.Diagnose));
        }
Exemplo n.º 18
0
        public void PinvokeMethodReferences_CS()
        {
            var tree = Microsoft.CodeAnalysis.CSharp.CSharpSyntaxTree.ParseText(
                @"

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Runtime.InteropServices;
static class Module1
{
	[DllImport(""kernel32"", EntryPoint = ""CreateDirectoryA"", CharSet = CharSet.Ansi, SetLastError = true, ExactSpelling = true)]
    public static extern int CreateDirectory(string lpPathName);

        private static int prop;
        public static int Prop1
        {
            get { return prop; }
            set
            {
                CreateDirectory(""T"");
                // Method Call 1
                prop = value;
                prop = null;
            }
        }

        public static void Main()
        {
            CreateDirectory(""T""); // Method Call 2            
            NormalMethod(); // Method Call 1
            NormalMethod(); // Method Call 2
        }

        public static void NormalMethod()
        {
        }
    }
                ");

            ProjectId prj1Id = ProjectId.CreateNewId();
            DocumentId docId = DocumentId.CreateNewId(prj1Id);

            var sln = new AdhocWorkspace().CurrentSolution
                .AddProject(prj1Id, "testDeclareReferences", "testAssembly", LanguageNames.CSharp)
                .AddMetadataReference(prj1Id, MscorlibRef)
                .AddDocument(docId, "testFile", tree.GetText());

            Microsoft.CodeAnalysis.Project prj = sln.GetProject(prj1Id).WithCompilationOptions(new CSharp.CSharpCompilationOptions(OutputKind.ConsoleApplication));
            tree = (SyntaxTree)prj.GetDocument(docId).GetSyntaxTreeAsync().Result;
            Compilation comp = prj.GetCompilationAsync().Result;

            SemanticModel semanticModel = comp.GetSemanticModel(tree);

            List<Microsoft.CodeAnalysis.CSharp.Syntax.MethodDeclarationSyntax> methodlist = tree.GetRoot().DescendantNodes().OfType<Microsoft.CodeAnalysis.CSharp.Syntax.MethodDeclarationSyntax>().ToList();
            SyntaxNode declareMethod = methodlist.ElementAt(0);
            SyntaxNode normalMethod = methodlist.ElementAt(2);

            // pinvoke method calls
            var symbol = semanticModel.GetDeclaredSymbol(declareMethod);
            var references = SymbolFinder.FindReferencesAsync(symbol, prj.Solution).Result;
            Assert.Equal(2, references.ElementAt(0).Locations.Count());

            // normal method calls
            symbol = semanticModel.GetDeclaredSymbol(normalMethod);
            references = SymbolFinder.FindReferencesAsync(symbol, prj.Solution).Result;
            Assert.Equal(2, references.ElementAt(0).Locations.Count());
        }
        /// <summary>
        /// Creates a solution that will be used as parent for the sources that need to be checked.
        /// </summary>
        /// <param name="projectId">The project identifier to use.</param>
        /// <param name="language">The language for which the solution is being created.</param>
        /// <returns>The created solution.</returns>
        protected virtual Solution CreateSolution(ProjectId projectId, string language)
        {
            var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, allowUnsafe: true);

            Solution solution = new AdhocWorkspace()
                .CurrentSolution
                .AddProject(projectId, TestProjectName, TestProjectName, language)
                .WithProjectCompilationOptions(projectId, compilationOptions)
                .AddMetadataReference(projectId, MetadataReferences.CorlibReference)
                .AddMetadataReference(projectId, MetadataReferences.SystemReference)
                .AddMetadataReference(projectId, MetadataReferences.SystemCoreReference)
                .AddMetadataReference(projectId, MetadataReferences.CSharpSymbolsReference)
                .AddMetadataReference(projectId, MetadataReferences.CodeAnalysisReference);

            solution.Workspace.Options =
                solution.Workspace.Options
                .WithChangedOption(FormattingOptions.IndentationSize, language, this.IndentationSize)
                .WithChangedOption(FormattingOptions.TabSize, language, this.TabSize)
                .WithChangedOption(FormattingOptions.UseTabs, language, this.UseTabs);

            var settings = this.GetSettings();

            StyleCopSettings defaultSettings = new StyleCopSettings();
            if (this.IndentationSize != defaultSettings.Indentation.IndentationSize
                || this.UseTabs != defaultSettings.Indentation.UseTabs
                || this.TabSize != defaultSettings.Indentation.TabSize)
            {
                var indentationSettings = $@"
{{
  ""settings"": {{
    ""indentation"": {{
      ""indentationSize"": {this.IndentationSize},
      ""useTabs"": {this.UseTabs.ToString().ToLowerInvariant()},
      ""tabSize"": {this.TabSize}
    }}
  }}
}}
";

                if (string.IsNullOrEmpty(settings))
                {
                    settings = indentationSettings;
                }
                else
                {
                    JObject mergedSettings = JsonConvert.DeserializeObject<JObject>(settings);
                    mergedSettings.Merge(JsonConvert.DeserializeObject<JObject>(indentationSettings));
                    settings = JsonConvert.SerializeObject(mergedSettings);
                }
            }

            if (!string.IsNullOrEmpty(settings))
            {
                var documentId = DocumentId.CreateNewId(projectId);
                solution = solution.AddAdditionalDocument(documentId, SettingsHelper.SettingsFileName, settings);
            }

            ParseOptions parseOptions = solution.GetProject(projectId).ParseOptions;
            return solution.WithProjectParseOptions(projectId, parseOptions.WithDocumentationMode(DocumentationMode.Diagnose));
        }
        /// <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)
        {
            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);

            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.º 21
0
        public void FindAllReferencesToAMethodInASolution()
        {
            var source1 = @"
namespace NS
{
    public class C
    {
        public void MethodThatWeAreTryingToFind()
        {
        }
        public void AnotherMethod()
        {
            MethodThatWeAreTryingToFind(); // First Reference.
        }
    }
}";
            var source2 = @"
using NS;
using Alias=NS.C;
class Program
{
    static void Main()
    {
        var c1 = new C();
        c1.MethodThatWeAreTryingToFind(); // Second Reference.
        c1.AnotherMethod();
        var c2 = new Alias();
        c2.MethodThatWeAreTryingToFind(); // Third Reference.
    }
}";
            var project1Id = ProjectId.CreateNewId();
            var project2Id = ProjectId.CreateNewId();
            var document1Id = DocumentId.CreateNewId(project1Id);
            var document2Id = DocumentId.CreateNewId(project2Id);

            var solution = new AdhocWorkspace().CurrentSolution
                .AddProject(project1Id, "Project1", "Project1", LanguageNames.CSharp)
                .AddMetadataReference(project1Id, Mscorlib)
                .AddDocument(document1Id, "File1.cs", source1)
                .WithProjectCompilationOptions(project1Id, 
                    new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary))
                .AddProject(project2Id, "Project2", "Project2", LanguageNames.CSharp)
                .AddMetadataReference(project2Id, Mscorlib)
                .AddProjectReference(project2Id, new ProjectReference(project1Id))
                .AddDocument(document2Id, "File2.cs", source2);
            
            // If you wish to try against a real solution you could use code like
            // var solution = Solution.Load("<Path>");
            // OR var solution = Workspace.LoadSolution("<Path>").CurrentSolution;

            var project1 = solution.GetProject(project1Id);
            var document1 = project1.GetDocument(document1Id);
            
            // Get MethodDeclarationSyntax corresponding to the 'MethodThatWeAreTryingToFind'.
            MethodDeclarationSyntax methodDeclaration = document1.GetSyntaxRootAsync().Result
                .DescendantNodes().OfType<MethodDeclarationSyntax>()
                .Single(m => m.Identifier.ValueText == "MethodThatWeAreTryingToFind");

            // Get MethodSymbol corresponding to the 'MethodThatWeAreTryingToFind'.
            var method = (IMethodSymbol)document1.GetSemanticModelAsync().Result
                .GetDeclaredSymbol(methodDeclaration);

            // Find all references to the 'MethodThatWeAreTryingToFind' in the solution.
            IEnumerable<ReferencedSymbol> methodReferences = SymbolFinder.FindReferencesAsync(method, solution).Result;
            Assert.Equal(1, methodReferences.Count());
            ReferencedSymbol methodReference = methodReferences.Single();
            Assert.Equal(3, methodReference.Locations.Count());

            var methodDefinition = (IMethodSymbol)methodReference.Definition;
            Assert.Equal("MethodThatWeAreTryingToFind", methodDefinition.Name);
            Assert.True(methodReference.Definition.Locations.Single().IsInSource);
            Assert.Equal("File1.cs", methodReference.Definition.Locations.Single().SourceTree.FilePath);

            Assert.True(methodReference.Locations
                .All(referenceLocation => referenceLocation.Location.IsInSource));
            Assert.Equal(1, methodReference.Locations
                .Count(referenceLocation => referenceLocation.Document.Name == "File1.cs"));
            Assert.Equal(2, methodReference.Locations
                .Count(referenceLocation => referenceLocation.Document.Name == "File2.cs"));
        }