public void GlobalSetup() { var roslynRoot = Environment.GetEnvironmentVariable( Program.RoslynRootPathEnvVariableName ); var csFilePath = Path.Combine( roslynRoot, @"src\Compilers\CSharp\Portable\Generated\Syntax.xml.Syntax.Generated.cs" ); if (!File.Exists(csFilePath)) { throw new ArgumentException(); } // Remove some newlines var text = File.ReadAllText(csFilePath) .Replace("<auto-generated />", "") .Replace($"{{{Environment.NewLine}{Environment.NewLine}", "{") .Replace($"}}{Environment.NewLine}{Environment.NewLine}", "}") .Replace($"{{{Environment.NewLine}", "{") .Replace($"}}{Environment.NewLine}", "}") .Replace($";{Environment.NewLine}", ";"); var projectId = ProjectId.CreateNewId(); var documentId = DocumentId.CreateNewId(projectId); var solution = new AdhocWorkspace().CurrentSolution .AddProject(projectId, "ProjectName", "AssemblyName", LanguageNames.CSharp) .AddDocument(documentId, "DocumentName", text); var document = solution.GetDocument(documentId); var root = document .GetSyntaxRootAsync(CancellationToken.None) .Result.WithAdditionalAnnotations(Formatter.Annotation); solution = solution.WithDocumentSyntaxRoot(documentId, root); _document = solution.GetDocument(documentId); _options = _document .GetOptionsAsync() .Result.WithChangedOption(CSharpFormattingOptions.NewLinesForBracesInTypes, true) .WithChangedOption( CSharpFormattingOptions.WrappingKeepStatementsOnSingleLine, false ) .WithChangedOption(CSharpFormattingOptions.WrappingPreserveSingleLine, false); }
/// <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 Dictionary <string, Document> CreateCompilationAndReturnDocuments(IEnumerable <string> filePaths, 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); var documents = new Dictionary <string, Document>(); int count = 0; foreach (var filePath in filePaths) { var newFileName = fileNamePrefix + count + "." + fileExt; var documentId = DocumentId.CreateNewId(projectId, debugName: newFileName); var source = TextFileReader.ReadFile(filePath); solution = solution.AddDocument(documentId, newFileName, SourceText.From(source)); count++; documents.Add(filePath, solution.GetDocument(documentId)); } return(documents); }
public static async Task <(Document, Compilation)> CreateInMemoryProject(string projectName, string code) { var references = ReferenceAssemblies.Net50.ToList(); references.AddRange(new[] { MetadataReference.CreateFromFile(typeof(Throw).Assembly.Location), MetadataReference.CreateFromFile(typeof(BaseMigration).Assembly.Location), }); var projectId = ProjectId.CreateNewId(projectName); var codeFileName = $"{projectName}Source.cs"; var codeFileId = DocumentId.CreateNewId(projectId, codeFileName); var project = new AdhocWorkspace().CurrentSolution .AddProject(projectId, projectName, projectName, LanguageNames.CSharp) .AddMetadataReferences(projectId, references) .AddDocument(codeFileId, codeFileName, SourceText.From(code)) .AddBaseMigrationClass(projectId) .GetProject(projectId) ! .WithCompilationOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); var document = project.GetDocument(codeFileId) !; var compilation = (await project.GetCompilationAsync()) !; return(document, compilation); }
public async Task SingleFieldAssignedByCtorNamespaceAsync() { ProjectId pid = ProjectId.CreateNewId(); DocumentId did = DocumentId.CreateNewId(pid); var workspace = new AdhocWorkspace() .CurrentSolution .AddProject(pid, "GenericTest", "GenericTest", LanguageNames.CSharp) .AddMetadataReference(pid, MetadataReference.CreateFromFile(typeof(object).Assembly.Location)) .AddDocument(did, "GenericDataAccess.cs", SourceText.From(_fieldNamespaceCtor)); var genericDocument = workspace.GetDocument(did); var results = await new CSharpIndexer() .BuildFromDocumentAsync(genericDocument); Assert.NotNull(results); Assert.Single(results.Generics); Assert.Empty(results.Queries); var indexerResult = results.Generics.FirstOrDefault(); Assert.NotNull(indexerResult); Assert.False(indexerResult.IsSolved); Assert.True(indexerResult.CanBeUsedAsQuery); Assert.Equal("T.SelectNumber", indexerResult.TextResult); }
private static async Task <SymbolAnalysisContext> CreateAnalysisContextAsync(string dependencyCopJson, string settingsFileName = SettingsHelper.SettingsFileName) { var projectId = ProjectId.CreateNewId(); var documentId = DocumentId.CreateNewId(projectId); var solution = new AdhocWorkspace() .CurrentSolution .AddProject(projectId, TestProjectName, TestProjectName, LanguageNames.CSharp) .AddDocument(documentId, "Test0.cs", SourceText.From(string.Empty)); var document = solution.GetDocument(documentId); var project = solution.GetProject(projectId); var compilation = await project.GetCompilationAsync().ConfigureAwait(false); var stylecopJSONFile = new AdditionalTextHelper(settingsFileName, dependencyCopJson); var additionalFiles = ImmutableArray.Create <AdditionalText>(stylecopJSONFile); var analyzerOptions = new AnalyzerOptions(additionalFiles); return(new SymbolAnalysisContext( Mock.Of <ISymbol>(), compilation, analyzerOptions, d => { }, d => true, CancellationToken.None)); }
static async Task <int[]> GetSemanticTokensForFilePathAsync(string filePath) { if (!File.Exists(filePath)) { throw new ArgumentException("Invalid file path: " + filePath.ToString()); } var text = File.ReadAllText(filePath); var projectId = ProjectId.CreateNewId(); var documentId = DocumentId.CreateNewId(projectId); var solution = new AdhocWorkspace().CurrentSolution .AddProject(projectId, "ProjectName", "AssemblyName", LanguageNames.CSharp) .AddDocument(documentId, "DocumentName", text); var document = solution.GetDocument(documentId); var(semanticTokens, isFinalized) = await SemanticTokensHelpers.ComputeSemanticTokensDataAsync( document, SemanticTokensCache.TokenTypeToIndex, range : null, CancellationToken.None).ConfigureAwait(false); while (!isFinalized) { (semanticTokens, isFinalized) = await SemanticTokensHelpers.ComputeSemanticTokensDataAsync( document, SemanticTokensCache.TokenTypeToIndex, range : null, CancellationToken.None).ConfigureAwait(false); } solution.Workspace.Dispose(); return(semanticTokens); }
protected void PositionAtStarShouldProduceExpectedUsingAdditonalLibraries(string code, AnalyzerOutput expected, bool isCSharp, Profile profileOverload, params string[] additionalLibraryPaths) { var pos = code.IndexOf("*", StringComparison.Ordinal); var projectId = ProjectId.CreateNewId(); var documentId = DocumentId.CreateNewId(projectId); var language = isCSharp ? LanguageNames.CSharp : LanguageNames.VisualBasic; var fileExt = isCSharp ? "cs" : "vb"; var solution = new AdhocWorkspace().CurrentSolution .AddProject(projectId, "MyProject", "MyProject", language) .AddDocument(documentId, $"MyFile.{fileExt}", code.Replace("*", string.Empty)); foreach (var libPath in additionalLibraryPaths) { var lib = MetadataReference.CreateFromFile(libPath); solution = solution.AddMetadataReference(projectId, lib); } var document = solution.GetDocument(documentId); var semModel = document.GetSemanticModelAsync().Result; var syntaxTree = document.GetSyntaxTreeAsync().Result; var analyzer = isCSharp ? new CSharpAnalyzer(DefaultTestLogger.Create()) as IDocumentAnalyzer : new VisualBasicAnalyzer(DefaultTestLogger.Create()); var actual = analyzer.GetSingleItemOutput(syntaxTree.GetRoot(), semModel, pos, new TestVisualStudioAbstraction().XamlIndent, profileOverload); Assert.AreEqual(expected.OutputType, actual.OutputType); Assert.AreEqual(expected.Name, actual.Name); StringAssert.AreEqual(expected.Output, actual.Output); }
protected void PositionAtStarShouldProduceExpectedUsingAdditonalFiles(string code, AnalyzerOutput expected, bool isCSharp, Profile profileOverload, params string[] additionalCode) { this.EnsureOneStar(code); var(pos, actualCode) = this.GetCodeAndCursorPos(code); var projectId = ProjectId.CreateNewId(); var documentId = DocumentId.CreateNewId(projectId); var language = isCSharp ? LanguageNames.CSharp : LanguageNames.VisualBasic; var fileExt = isCSharp ? "cs" : "vb"; var solution = new AdhocWorkspace().CurrentSolution .AddProject(projectId, "MyProject", "MyProject", language) .AddDocument(documentId, $"MyFile.{fileExt}", actualCode); foreach (var addCode in additionalCode) { solution = solution.AddDocument(DocumentId.CreateNewId(projectId), $"{System.IO.Path.GetRandomFileName()}.{fileExt}", addCode); } var document = solution.GetDocument(documentId); var semModel = document.GetSemanticModelAsync().Result; var syntaxTree = document.GetSyntaxTreeAsync().Result; var indent = new TestVisualStudioAbstraction().XamlIndent; var analyzer = isCSharp ? new CSharpAnalyzer(DefaultTestLogger.Create(), indent) as IDocumentAnalyzer : new VisualBasicAnalyzer(DefaultTestLogger.Create(), indent); var actual = analyzer.GetSingleItemOutput(syntaxTree.GetRoot(), semModel, pos, profileOverload); this.AssertOutput(expected, actual); }
private void PrepareAnalyzeModel(string documentCode, out Document document, out SemanticModel semanticModel, out IEnumerable <SyntaxNode> nodes, out ArgumentSyntax nodeToTest, bool inReturn = false) { var projectId = ProjectId.CreateNewId(); var documentId = DocumentId.CreateNewId(projectId); var solution = new AdhocWorkspace().CurrentSolution .AddProject(projectId, "MyProject", "MyProject", LanguageNames.CSharp) .AddMetadataReference(projectId, MetadataReference.CreateFromFile(typeof(object).Assembly.Location)) .AddDocument(documentId, "MyFile.cs", documentCode); document = solution.GetDocument(documentId); SyntaxTree tree = CSharpSyntaxTree.ParseText(documentCode); var compilation = CSharpCompilation.Create("HelloWorld") .AddReferences( MetadataReference.CreateFromFile( typeof(object).Assembly.Location)) .AddSyntaxTrees(tree); semanticModel = compilation.GetSemanticModel(tree); var treeRoot = (CompilationUnitSyntax)tree.GetRoot(); nodes = treeRoot.DescendantNodesAndSelf(); var sourceText = treeRoot.GetText(); var line = sourceText.Lines[inReturn?21:11]; var span = line.Span; var nodesAtLine = treeRoot.DescendantNodes(span); nodeToTest = nodesAtLine.OfType <ArgumentSyntax>().FirstOrDefault(); }
internal static async Task Main() { const string source = @" using System; using System.Collections.Generic; using System.Linq; class C { void M() { } } "; ProjectId projectId = ProjectId.CreateNewId(); Project project = new AdhocWorkspace() .CurrentSolution .AddProject(projectId, "TestProject", "TestProject", LanguageNames.CSharp) .AddMetadataReferences( projectId, new MetadataReference[] { MetadataReference.CreateFromFile(typeof(object).Assembly.Location), RuntimeMetadataReference.CreateFromAssemblyName("System.Core.dll"), RuntimeMetadataReference.CreateFromAssemblyName("System.Linq.dll"), RuntimeMetadataReference.CreateFromAssemblyName("System.Linq.Expressions.dll"), RuntimeMetadataReference.CreateFromAssemblyName("System.Runtime.dll"), RuntimeMetadataReference.CreateFromAssemblyName("System.Collections.Immutable.dll"), RuntimeMetadataReference.CreateFromAssemblyName("Microsoft.CodeAnalysis.dll"), RuntimeMetadataReference.CreateFromAssemblyName("Microsoft.CodeAnalysis.CSharp.dll"), }) .GetProject(projectId); var parseOptions = (CSharpParseOptions)project.ParseOptions; project = project.WithParseOptions(parseOptions.WithLanguageVersion(LanguageVersion.Latest)); DocumentId documentId = DocumentId.CreateNewId(projectId); project = project .Solution .AddDocument(documentId, "Test.cs", SourceText.From(source)) .GetProject(projectId); Document document = project.GetDocument(documentId); SemanticModel semanticModel = await document.GetSemanticModelAsync().ConfigureAwait(false); SyntaxTree tree = await document.GetSyntaxTreeAsync().ConfigureAwait(false); SyntaxNode root = await tree.GetRootAsync().ConfigureAwait(false); string s = document.GetSyntaxRootAsync().Result.ToFullString(); Console.WriteLine(s); Console.ReadKey(); }
public async Task TestTrackNodesWithDocument() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var sourceText = @"public class C { void M() { } }"; var sol = new AdhocWorkspace().CurrentSolution .AddProject(pid, "proj", "proj", LanguageNames.CSharp) .AddDocument(did, "doc", sourceText); var doc = sol.GetDocument(did); // find initial nodes of interest var root = await doc.GetSyntaxRootAsync(); var classDecl = root.DescendantNodes().OfType <ClassDeclarationSyntax>().First(); var methodDecl = classDecl.DescendantNodes().OfType <MethodDeclarationSyntax>().First(); // track these nodes var trackedRoot = root.TrackNodes(classDecl, methodDecl); // use some fancy document centric rewrites var comp = await doc.Project.GetCompilationAsync(); var gen = SyntaxGenerator.GetGenerator(doc); var cgenField = gen.FieldDeclaration("X", gen.TypeExpression(SpecialType.System_Int32), Accessibility.Private); var currentClassDecl = trackedRoot.GetCurrentNodes(classDecl).First(); var classDeclWithField = gen.InsertMembers(currentClassDecl, 0, new[] { cgenField }); // we can find related bits even from sub-tree fragments var latestMethod = classDeclWithField.GetCurrentNodes(methodDecl).First(); Assert.NotNull(latestMethod); Assert.NotEqual(latestMethod, methodDecl); trackedRoot = trackedRoot.ReplaceNode(currentClassDecl, classDeclWithField); // put back into document (branch solution, etc) doc = doc.WithSyntaxRoot(trackedRoot); // re-get root of new document var root2 = await doc.GetSyntaxRootAsync(); Assert.NotEqual(trackedRoot, root2); // we can still find the tracked node in the new document var finalClassDecl = root2.GetCurrentNodes(classDecl).First(); Assert.Equal("public class C\r\n{\r\n private int X;\r\n void M()\r\n {\r\n }\r\n}", finalClassDecl.NormalizeWhitespace().ToString()); // and other tracked nodes too var finalMethodDecl = root2.GetCurrentNodes(methodDecl).First(); Assert.NotNull(finalMethodDecl); Assert.NotEqual(finalMethodDecl, methodDecl); }
public void GlobalSetup() { var roslynRoot = Environment.GetEnvironmentVariable(Program.RoslynRootPathEnvVariableName); var csFilePath = Path.Combine(roslynRoot, @"src\Compilers\CSharp\Portable\Generated\Syntax.xml.Syntax.Generated.cs"); if (!File.Exists(csFilePath)) { throw new ArgumentException(); } // Remove some newlines var text = File.ReadAllText(csFilePath).Replace("<auto-generated />", "") .Replace($"{{{Environment.NewLine}{Environment.NewLine}", "{") .Replace($"}}{Environment.NewLine}{Environment.NewLine}", "}") .Replace($"{{{Environment.NewLine}", "{") .Replace($"}}{Environment.NewLine}", "}") .Replace($";{Environment.NewLine}", ";"); var projectId = ProjectId.CreateNewId(); var documentId = DocumentId.CreateNewId(projectId); var solution = new AdhocWorkspace().CurrentSolution .AddProject(projectId, "ProjectName", "AssemblyName", LanguageNames.CSharp) .AddDocument(documentId, "DocumentName", text); var document = solution.GetDocument(documentId); var root = document.GetSyntaxRootAsync(CancellationToken.None).Result.WithAdditionalAnnotations(Formatter.Annotation); solution = solution.WithDocumentSyntaxRoot(documentId, root); _document = solution.GetDocument(documentId); _options = new CSharpSyntaxFormattingOptions( LineFormattingOptions.Default, separateImportDirectiveGroups: CSharpSyntaxFormattingOptions.Default.SeparateImportDirectiveGroups, spacing: CSharpSyntaxFormattingOptions.Default.Spacing, spacingAroundBinaryOperator: CSharpSyntaxFormattingOptions.Default.SpacingAroundBinaryOperator, CSharpSyntaxFormattingOptions.Default.NewLines | NewLinePlacement.BeforeOpenBraceInTypes, labelPositioning: CSharpSyntaxFormattingOptions.Default.LabelPositioning, indentation: CSharpSyntaxFormattingOptions.Default.Indentation, wrappingKeepStatementsOnSingleLine: false, wrappingPreserveSingleLine: false); }
private static Document CreateSolutionDocument(string sourceText) { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var solution = new AdhocWorkspace().CurrentSolution .AddProject(pid, "test", "test", LanguageNames.CSharp) .AddMetadataReference(pid, TestReferences.NetFx.v4_0_30319.mscorlib) .AddDocument(did, "goo.cs", SourceText.From(sourceText)); return(solution.GetDocument(did)); }
public static async Task <(Document, Compilation)> CreateLightGuardClausesDllInMemory(string projectName, string code) { var projectId = ProjectId.CreateNewId(projectName); var codeFileName = $"{projectName}Source.cs"; var codeFileId = DocumentId.CreateNewId(projectId, codeFileName); var project = new AdhocWorkspace().CurrentSolution .AddProject(projectId, projectName, projectName, LanguageNames.CSharp) .AddMetadataReferences(projectId, AllReferences) .AddDocument(codeFileId, codeFileName, SourceText.From(code)) .AddThrowClass(projectId) .GetProject(projectId) .WithCompilationOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary)); var document = project.GetDocument(codeFileId); var compilation = await project.GetCompilationAsync(); return(document, compilation); }
public static Document GetTestDocument(string source, params string[] additionalFiles) { var projectId = ProjectId.CreateNewId(); var documentId = DocumentId.CreateNewId(projectId); var solution = new AdhocWorkspace().CurrentSolution .AddProject(projectId, "MyProject", "MyProject", LanguageNames.CSharp) .AddMetadataReference(projectId, Mscorlib) .AddMetadataReference(projectId, SystemCore) .AddDocument(documentId, "MyFile.cs", source); for (int i = 0; i < additionalFiles.Length; i++) { solution = solution.AddDocument(DocumentId.CreateNewId(projectId), $"{i}.cs", additionalFiles[i]); } return(solution.GetDocument(documentId)); }
private static async Task <SyntaxTreeAnalysisContext> CreateAnalysisContextAsync(string stylecopJSON) { var projectId = ProjectId.CreateNewId(); var documentId = DocumentId.CreateNewId(projectId); var solution = new AdhocWorkspace() .CurrentSolution .AddProject(projectId, TestProjectName, TestProjectName, LanguageNames.CSharp) .AddDocument(documentId, "Test0.cs", SourceText.From(string.Empty)); var document = solution.GetDocument(documentId); var syntaxTree = await document.GetSyntaxTreeAsync().ConfigureAwait(false); var stylecopJSONFile = new AdditionalTextHelper("stylecop.json", stylecopJSON); var additionalFiles = ImmutableArray.Create <AdditionalText>(stylecopJSONFile); var analyzerOptions = new AnalyzerOptions(additionalFiles); return(new SyntaxTreeAnalysisContext(syntaxTree, analyzerOptions, rd => { }, isd => { return true; }, CancellationToken.None)); }
protected async Task PositionAtStarShouldProduceExpectedUsingAdditionalLibraries(string code, ParserOutput expected, bool isCSharp, Profile profileOverload, params string[] additionalLibraryPaths) { this.EnsureOneStar(code); var(pos, actualCode) = this.GetCodeAndCursorPos(code); var projectId = ProjectId.CreateNewId(); var documentId = DocumentId.CreateNewId(projectId); var language = isCSharp ? LanguageNames.CSharp : LanguageNames.VisualBasic; var fileExt = isCSharp ? "cs" : "vb"; var solution = new AdhocWorkspace().CurrentSolution .AddProject(projectId, "MyProject", "MyProject", language) .AddDocument(documentId, $"MyFile.{fileExt}", actualCode); foreach (var libPath in additionalLibraryPaths) { var lib = MetadataReference.CreateFromFile(libPath); solution = solution.AddMetadataReference(projectId, lib); } var document = solution.GetDocument(documentId); var semModel = await document.GetSemanticModelAsync(); var syntaxTree = await document.GetSyntaxTreeAsync(); var indent = new TestVisualStudioAbstraction().XamlIndent; var parser = isCSharp ? new CSharpParser(DefaultTestLogger.Create(), indent, profileOverload) as IDocumentParser : new VisualBasicParser(DefaultTestLogger.Create(), indent, profileOverload); var actual = parser.GetSingleItemOutput(await syntaxTree.GetRootAsync(), semModel, pos); this.AssertOutput(expected, actual); }
public ExpressionResolverGeneralTests() { _documentCSharpCode = @"using System; using System.Collections; using System.Linq; using System.Text; namespace HelloWorld { class Program { static void Main(string[] args) { var case1 = TestMethod(""unittest"", """"); var case2 = TestMethod(""unit""+""test"",""""); var case3 = TestMethod(""unit""+""test"",""""); var case4 = TestMethod(""u""+""n""+""i""+""t""+""t""+""e""+""s""+""t"",""""); var case5 = TestMethod(constString,""""); var case6 = TestMethod(constUnit+constTest,""""); var case7 = TestMethod($""{constUnit}test"",""""); var case8 = TestMethod($""unit{constTest}"",""""); var case9 = TestMethod($""{constUnit}{constTest}"",""""); var case10 = TestMethod($""{""unit""}{""test""}"",""""); var case11 = TestMethod(stringFromInterpolation,""""); var case12 = TestMethod(nameof(unittest),""""); var case13 = TestMethod(constantStringUnitTest,""""); var case14 = TestMethod(constantNameOfResult,""""); var case15 = TestMethod(string.Format(""{0}"", ""unittest""),""""); var case16 = TestMethod(string.Format(""{0}{1}"", ""unit"",""test""),""""); var case17 = TestMethod(string.Format(""{0}{1}"", ""unit"", constTest),""""); var case18 = TestMethod(string.Format(""{0}{1}"", constUnit, constTest),""""); var case19 = TestMethod(typeof(unittest).Name,""""); var case20 = TestMethod(constantTypeOfNameResult,""""); var case21 = TestMethod(PublicFieldStringUnitTest,""""); var case22 = TestMethod(PrivateFieldStringUnitTest,""""); var case23 = TestMethod(PublicFieldStringUnitTestFromLambda,""""); var case24 = TestMethod(PrivateFieldStringUnitTestFromLambda,""""); var case25 = TestMethod(PublicFieldStringUnitTestWithGetter,""""); var case26 = TestMethod(PrivateFieldStringUnitTestWithGetter,""""); var case27 = TestMethod(PublicFieldStringUnitTestWithGetterNonDirectReturn,""""); var case28 = TestMethod(PrivateFieldStringUnitTestWithGetterNonDirectReturn,""""); var case29 = TestMethod(constUnit.Replace(""unit"", ""unittest""),""""); var case30 = TestMethod(constUnit.Replace(constUnit, ""unittest""),""""); var case31 = TestMethod(constUnit.Replace(constUnit, constString),""""); var constString = ""unittest""; var constUnit = ""unit""; var constTest = ""test""; const string constantStringUnitTest = ""unittest""; const string constantNameOfResult = nameof(unittest); var stringFromInterpolation = $""{constUnit}{constTest}""; var stringFromStringFormat = string.Format(""{0}"", ""unittest""); var constantTypeOfNameResult = typeof(unittest).Name; } public static string TestMethod(string one, string two) { return one + two; } public string PublicFieldStringUnitTest = ""unittest""; private string PrivateFieldStringUnitTest = ""unittest""; public string PublicFieldStringUnitTestFromLambda => ""unittest""; private string PrivateFieldStringUnitTestFromLambda => ""unittest""; public string PublicFieldStringUnitTestWithGetter { get { return ""unittest""; } set { } } private string PrivateFieldStringUnitTestWithGetter { get { return ""unittest""; } set { } } public string PublicFieldStringUnitTestWithGetterNonDirectReturn { get { var returnValue =""unittest""; return returnValue; } set { } } private string PrivateFieldStringUnitTestWithGetterNonDirectReturn { get { var returnValue =""unittest""; return returnValue; } set { } } public void unittest(){} } }"; var projectId = ProjectId.CreateNewId(); var documentId = DocumentId.CreateNewId(projectId); var solution = new AdhocWorkspace().CurrentSolution .AddProject(projectId, "MyProject", "MyProject", LanguageNames.CSharp) .AddMetadataReference(projectId, MetadataReference.CreateFromFile(typeof(object).Assembly.Location)) .AddDocument(documentId, "MyFile.cs", _documentCSharpCode); _document = solution.GetDocument(documentId); SyntaxTree tree = CSharpSyntaxTree.ParseText(_documentCSharpCode); var compilation = CSharpCompilation.Create("HelloWorld") .AddReferences( MetadataReference.CreateFromFile( typeof(object).Assembly.Location)) .AddSyntaxTrees(tree); _semanticModel = compilation.GetSemanticModel(tree); _treeRoot = (CompilationUnitSyntax)tree.GetRoot(); _documentNodes = _treeRoot.DescendantNodesAndSelf(); _sourceText = _treeRoot.GetText(); }
public async Task SingleDirectNamespaceAsync() { // var code = @"using System; //using System.Collections.Generic; //using System.Linq; //using System.Text; //using System.Threading.Tasks; //namespace GenericTest //{ // public class GenericTableCalls // { // public void CallGeneric() // { // var genericDA = new GenericDataAccess<SomeTable>(); // var result = genericDA.GetAll(); // } // } //} //"; var code = @"using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GenericTest { public class GenericTableCalls { public void CallGeneric() { var query = ""Query""; var query2 = query + ""2""; } } } "; ProjectId pid = ProjectId.CreateNewId(); DocumentId did = DocumentId.CreateNewId(pid); DocumentId mainId = DocumentId.CreateNewId(pid); var workspace = new AdhocWorkspace() .CurrentSolution .AddProject(pid, "GenericTest", "GenericTest", LanguageNames.CSharp) .AddMetadataReference(pid, MetadataReference.CreateFromFile(typeof(object).Assembly.Location)) .AddDocument(did, "GenericDataAccess.cs", SourceText.From(_fieldNamespaceCtor)) .AddDocument(mainId, "main.cs", SourceText.From(code)); var document = workspace.GetDocument(mainId); var semanticModel = await document.GetSemanticModelAsync(); var syntaxTree = await document.GetSyntaxTreeAsync(); var text = await syntaxTree.GetTextAsync(); var line = text.Lines[8]; var span = line.Span; var nodesAtLine = (await syntaxTree.GetRootAsync()).DescendantNodes(span).OfType <VariableDeclarationSyntax>().FirstOrDefault(); //var test1 = nodesAtLine.Ancestors(); //var test2 = nodesAtLine.ChildNodes(); var initializer = (await syntaxTree.GetRootAsync()).DescendantNodes(text.Lines[13].Span); List <List <ISymbol> > xx = new List <List <ISymbol> >(); List <List <SymbolCallerInfo> > xxx = new List <List <SymbolCallerInfo> >(); Dictionary <SyntaxNode, ControlFlowAnalysis> cfl = new Dictionary <SyntaxNode, ControlFlowAnalysis>(); Dictionary <SyntaxNode, DataFlowAnalysis> dfl = new Dictionary <SyntaxNode, DataFlowAnalysis>(); foreach (var node in initializer) { try { cfl.Add(node, semanticModel.AnalyzeControlFlow(node)); } catch (Exception) { cfl.Add(node, null); } try { dfl.Add(node, semanticModel.AnalyzeDataFlow(node)); } catch (Exception) { dfl.Add(node, null); } //if (node is StatementSyntax) //{ // cfl.Add(node, semanticModel.AnalyzeControlFlow(node)); // dfl.Add(node, semanticModel.AnalyzeDataFlow(node)); //} //if (node is ExpressionSyntax) //{ // dfl.Add(node, semanticModel.AnalyzeDataFlow(node)); //} //var symbol = semanticModel.GetDeclaredSymbol(node); //if (symbol != null) //{ // xx.Add(SymbolFinder.FindImplementationsAsync(symbol, workspace).Result.ToList()); // xxx.Add(SymbolFinder.FindCallersAsync(symbol, workspace).Result.ToList()); // var t = SymbolFinder. //} } }