public static string Simplify(SyntaxNode node) { var source = node.ToString(); var projectId = ProjectId.CreateNewId(); var documentId = DocumentId.CreateNewId(projectId); var solution = new CustomWorkspace().CurrentSolution .AddProject(projectId, "MyProject", "MyProject", LanguageNames.CSharp) .AddMetadataReference(projectId, RoslynRDomUtilities.Mscorlib) .AddMetadataReference(projectId, AppDomain.CurrentDomain.GetAssemblies() .Where(a => string.Compare(a.GetName().Name, "System", StringComparison.OrdinalIgnoreCase) == 0) .Select(a => new MetadataFileReference(a.Location)).Single()) .AddDocument(documentId, "MyFile.cs", source); var document = solution.GetDocument(documentId); // Format the document. document = Formatter.FormatAsync(document).Result; // Simplify names used in the document i.e. remove unnecessary namespace qualifiers. var newRoot = (SyntaxNode)document.GetSyntaxRootAsync().Result; newRoot = new SimplifyNamesAnnotionRewriter().Visit(newRoot); document = document.WithSyntaxRoot(newRoot); document = Simplifier.ReduceAsync(document).Result; var ret = document.GetSyntaxRootAsync().Result.ToString(); return ret; }
private Document CreateSolutionDocument(string sourceText) { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var solution = new CustomWorkspace().CurrentSolution .AddProject(pid, "test", "test", LanguageNames.CSharp) .AddMetadataReference(pid, mscorlib) .AddDocument(did, "foo.cs", SourceText.From(sourceText)); return solution.GetDocument(did); }
public void TestTrackNodesWithDocument() { var pid = ProjectId.CreateNewId(); var did = DocumentId.CreateNewId(pid); var sourceText = @"public class C { void M() { } }"; var sol = new CustomWorkspace().CurrentSolution .AddProject(pid, "proj", "proj", LanguageNames.CSharp) .AddDocument(did, "doc", sourceText); var doc = sol.GetDocument(did); // find initial nodes of interest var root = doc.GetSyntaxRootAsync().Result; 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 = doc.Project.GetCompilationAsync().Result; var cgenField = CodeGenerationSymbolFactory.CreateFieldSymbol( attributes: null, accessibility: Accessibility.Private, modifiers: new SymbolModifiers(), type: comp.GetSpecialType(SpecialType.System_Int32), name: "X"); var currentClassDecl = trackedRoot.GetCurrentNodes(classDecl).First(); var classDeclWithField = Formatter.Format( CodeGenerator.AddFieldDeclaration(currentClassDecl, cgenField, sol.Workspace), sol.Workspace); // 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 = doc.GetSyntaxRootAsync().Result; 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 { private System.Int32 X; void M() { } }", finalClassDecl.ToString()); // and other tracked nodes too var finalMethodDecl = root2.GetCurrentNodes(methodDecl).First(); Assert.NotNull(finalMethodDecl); Assert.NotEqual(finalMethodDecl, methodDecl); }
public void TestWorkspaceDiagnosticHasDebuggerText() { var solution = new CustomWorkspace().CurrentSolution; WorkspaceDiagnostic diagnostic = null; solution.Workspace.WorkspaceFailed += (sender, args) => { diagnostic = args.Diagnostic; }; ProjectId pid = ProjectId.CreateNewId(); DocumentId did = DocumentId.CreateNewId(pid); solution = solution.AddProject(pid, "foo", "foo", LanguageNames.CSharp) .AddDocument(did, "x", new FileTextLoader("doesnotexist.cs")); var doc = solution.GetDocument(did); var text = doc.GetTextAsync().Result; WaitFor(() => diagnostic != null, TimeSpan.FromSeconds(5)); Assert.NotNull(diagnostic); var dd = diagnostic as DocumentDiagnostic; Assert.NotNull(dd); Assert.Equal(dd.GetDebuggerDisplay(), string.Format("[{0}] {1}", dd.Kind.ToString(), dd.Message)); }
public void TestDocumentFileAccessFailureMissingFile() { var solution = new CustomWorkspace().CurrentSolution; WorkspaceDiagnostic diagnostic = null; solution.Workspace.WorkspaceFailed += (sender, args) => { diagnostic = args.Diagnostic; }; ProjectId pid = ProjectId.CreateNewId(); DocumentId did = DocumentId.CreateNewId(pid); solution = solution.AddProject(pid, "foo", "foo", LanguageNames.CSharp) .AddDocument(did, "x", new FileTextLoader("doesnotexist.cs")); var doc = solution.GetDocument(did); var text = doc.GetTextAsync().Result; WaitFor(() => diagnostic != null, TimeSpan.FromSeconds(5)); Assert.NotNull(diagnostic); var dd = diagnostic as DocumentDiagnostic; Assert.NotNull(dd); Assert.Equal(did, dd.DocumentId); Assert.Equal(WorkspaceDiagnosticKind.FileAccessFailure, dd.Kind); }
public void UseServices() { var source = @"using System.Diagnostics; using System; using System.IO; namespace NS { public class C { } } class Program { public static void Main() { System.Int32 i = 0; System.Console.WriteLine(i.ToString()); Process p = Process.GetCurrentProcess(); Console.WriteLine(p.Id); } }"; var projectId = ProjectId.CreateNewId(); var documentId = DocumentId.CreateNewId(projectId); var solution = new CustomWorkspace().CurrentSolution .AddProject(projectId, "MyProject", "MyProject", LanguageNames.CSharp) .AddMetadataReference(projectId, Mscorlib) .AddMetadataReference(projectId, AppDomain.CurrentDomain.GetAssemblies() .Where(a => string.Compare(a.GetName().Name, "System", StringComparison.OrdinalIgnoreCase) == 0) .Select(a => new MetadataFileReference(a.Location)).Single()) .AddDocument(documentId, "MyFile.cs", source); var document = solution.GetDocument(documentId); // Format the document. document = Formatter.FormatAsync(document).Result; Assert.AreEqual(@"using System.Diagnostics; using System; using System.IO; namespace NS { public class C { } } class Program { public static void Main() { System.Int32 i = 0; System.Console.WriteLine(i.ToString()); Process p = Process.GetCurrentProcess(); Console.WriteLine(p.Id); } }", document.GetSyntaxRootAsync().Result.ToString()); // Simplify names used in the document i.e. remove unnecessary namespace qualifiers. var newRoot = (SyntaxNode)document.GetSyntaxRootAsync().Result; newRoot = new SimplifyNamesAnnotionRewriter().Visit(newRoot); document = document.WithSyntaxRoot(newRoot); document = Simplifier.ReduceAsync(document).Result; Assert.AreEqual(@"using System.Diagnostics; using System; using System.IO; namespace NS { public class C { } } class Program { public static void Main() { int i = 0; Console.WriteLine(i.ToString()); Process p = Process.GetCurrentProcess(); Console.WriteLine(p.Id); } }", document.GetSyntaxRootAsync().Result.ToString()); }
public void GetTypeForExpressions() { var source = @" using System; class Program { public void M(short[] s) { var d = 1.0; Console.WriteLine(s[0] + d); } public static void Main() { } }"; ProjectId projectId = ProjectId.CreateNewId(); DocumentId documentId = DocumentId.CreateNewId(projectId); var solution = new CustomWorkspace().CurrentSolution .AddProject(projectId, "MyProject", "MyProject", LanguageNames.CSharp) .AddMetadataReference(projectId, Mscorlib) .AddDocument(documentId, "MyFile.cs", source); var document = solution.GetDocument(documentId); var model = (SemanticModel)document.GetSemanticModelAsync().Result; // Get BinaryExpressionSyntax corresponding to the expression 's[0] + d' above. BinaryExpressionSyntax addExpression = document.GetSyntaxRootAsync().Result .DescendantNodes().OfType<BinaryExpressionSyntax>().Single(); // Get TypeSymbol corresponding to expression 's[0] + d' above. TypeInfo expressionTypeInfo = model.GetTypeInfo(addExpression); var expressionType = expressionTypeInfo.Type; Assert.AreEqual(SpecialType.System_Double, expressionType.SpecialType); Assert.AreEqual("double", expressionType.ToDisplayString()); Assert.AreEqual(SpecialType.System_Double, expressionTypeInfo.ConvertedType.SpecialType); var conversion = model.GetConversion(addExpression); Assert.IsTrue(conversion.IsIdentity); // Get IdentifierNameSyntax corresponding to the variable 'd' in expression 's[0] + d' above. var identifier = (IdentifierNameSyntax)addExpression.Right; // Use GetTypeInfo() to get TypeSymbol corresponding to variable 'd' above. TypeInfo variableTypeInfo = model.GetTypeInfo(identifier); var variableType = variableTypeInfo.Type; Assert.AreEqual(SpecialType.System_Double, variableType.SpecialType); Assert.AreEqual("double", variableType.ToDisplayString()); Assert.AreEqual(SpecialType.System_Double, variableTypeInfo.ConvertedType.SpecialType); conversion = model.GetConversion(identifier); Assert.IsTrue(conversion.IsIdentity); // Alternately, use GetSymbolInfo() to get TypeSymbol corresponding to variable 'd' above. variableType = ((ILocalSymbol)model.GetSymbolInfo(identifier).Symbol).Type; Assert.AreEqual(SpecialType.System_Double, variableType.SpecialType); Assert.AreEqual("double", variableType.ToDisplayString()); // Get ElementAccessExpressionSyntax corresponding to 's[0]' in expression 's[0] + d' above. var elementAccess = (ElementAccessExpressionSyntax)addExpression.Left; // Use GetTypeInfo() to get TypeSymbol corresponding to 's[0]' above. expressionTypeInfo = model.GetTypeInfo(elementAccess); expressionType = expressionTypeInfo.Type; Assert.AreEqual(SpecialType.System_Int16, expressionType.SpecialType); Assert.AreEqual("short", expressionType.ToDisplayString()); Assert.AreEqual(SpecialType.System_Double, expressionTypeInfo.ConvertedType.SpecialType); conversion = model.GetConversion(elementAccess); Assert.IsTrue(conversion.IsImplicit && conversion.IsNumeric); // Get IdentifierNameSyntax corresponding to the parameter 's' in expression 's[0] + d' above. identifier = (IdentifierNameSyntax)elementAccess.Expression; // Use GetTypeInfo() to get TypeSymbol corresponding to parameter 's' above. variableTypeInfo = model.GetTypeInfo(identifier); variableType = variableTypeInfo.Type; Assert.AreEqual("short[]", variableType.ToDisplayString()); Assert.AreEqual("short[]", variableTypeInfo.ConvertedType.ToDisplayString()); conversion = model.GetConversion(identifier); Assert.IsTrue(conversion.IsIdentity); // Alternately, use GetSymbolInfo() to get TypeSymbol corresponding to parameter 's' above. variableType = ((IParameterSymbol)model.GetSymbolInfo(identifier).Symbol).Type; Assert.AreEqual("short[]", variableType.ToDisplayString()); Assert.AreEqual(SpecialType.System_Int16, ((IArrayTypeSymbol)variableType).ElementType.SpecialType); }
public void GetFullyQualifiedName() { var source = @" using System; using Alias=NS.C<int>; namespace NS { public class C<T> { public struct S<U> { } } } class Program { public static void Main() { Alias.S<long> s = new Alias.S<long>(); Console.WriteLine(s.ToString()); } }"; var projectId = ProjectId.CreateNewId(); var documentId = DocumentId.CreateNewId(projectId); var solution = new CustomWorkspace().CurrentSolution .AddProject(projectId, "MyProject", "MyProject", LanguageNames.CSharp) .AddMetadataReference(projectId, Mscorlib) .AddDocument(documentId, "MyFile.cs", source); var document = solution.GetDocument(documentId); var root = document.GetSyntaxRootAsync().Result; var model = (SemanticModel)document.GetSemanticModelAsync().Result; // Get StructDeclarationSyntax corresponding to 'struct S' above. StructDeclarationSyntax structDeclaration = root.DescendantNodes() .OfType<StructDeclarationSyntax>().Single(); // Get TypeSymbol corresponding to 'struct S' above. var structType = model.GetDeclaredSymbol(structDeclaration); // Use ToDisplayString() to get fully qualified name. Assert.AreEqual("NS.C<T>.S<U>", structType.ToDisplayString()); Assert.AreEqual("global::NS.C<T>.S<U>", structType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)); // Get VariableDeclaratorSyntax corresponding to 'Alias.S<long> s = ...' above. VariableDeclaratorSyntax variableDeclarator = root.DescendantNodes() .OfType<VariableDeclaratorSyntax>().Single(); // Get TypeSymbol corresponding to above VariableDeclaratorSyntax. var variableType = ((ILocalSymbol)model.GetDeclaredSymbol(variableDeclarator)).Type; Assert.IsFalse(variableType.Equals(structType)); // Type of variable is a closed generic type while that of the struct is an open generic type. Assert.IsTrue(variableType.OriginalDefinition.Equals(structType)); // OriginalDefinition for a closed generic type points to corresponding open generic type. Assert.AreEqual("NS.C<int>.S<long>", variableType.ToDisplayString()); Assert.AreEqual("global::NS.C<int>.S<long>", variableType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat)); }