public static (SyntaxTree Tree, string[] ClassNames, string formatter, IEnumerable <Diagnostic> errors) GetTreeInfo(string content) { SyntaxTree tree = CSharpSyntaxTree.ParseText(content, new CSharpParseOptions(LanguageVersion.Latest)); CompilationUnitSyntax root = tree.GetCompilationUnitRoot(); root = (CompilationUnitSyntax)Formatter.Format(root, _workSpace); var errors = root.GetDiagnostics(); var formatter = root.ToString(); var result = new List <string>(from typeNodes in root.DescendantNodes().OfType <ClassDeclarationSyntax>() select typeNodes.Identifier.Text); result.AddRange(from typeNodes in root.DescendantNodes().OfType <StructDeclarationSyntax>() select typeNodes.Identifier.Text); result.AddRange(from typeNodes in root.DescendantNodes().OfType <InterfaceDeclarationSyntax>() select typeNodes.Identifier.Text); result.AddRange(from typeNodes in root.DescendantNodes().OfType <EnumDeclarationSyntax>() select typeNodes.Identifier.Text); return(root.SyntaxTree, result.ToArray(), formatter, errors); }
private static void GetPreviousBlock() { BlockSyntax block = root.DescendantNodes().OfType <BlockSyntax>().Where(n => n.HasAnnotation(currentBlock)).Single(); block = block.Parent as BlockSyntax; currentBlock = block.GetAnnotations("Block").Single(); }
public void TestUsing() { var expected = "Microsoft.VisualStudio.TestTools.UnitTesting"; var actual = compilationUnit.DescendantNodes().OfType <UsingDirectiveSyntax>().First().Name.ToFullString(); Assert.AreEqual(expected, actual); }
public void NamespaceDeclarationsTest() { IEnumerable <NamespaceDeclarationSyntax> namespaces = _root.DescendantNodes().OfType <NamespaceDeclarationSyntax>(); Assert.AreEqual(1, namespaces.Count()); Assert.AreEqual("TestsGenerator.Tests", namespaces.ElementAt <NamespaceDeclarationSyntax>(0).Name.ToString()); }
private string Modify(string phrase) { string tempVar = $"tmp_qrwer"; string res = @"namespace Namespace1 { class Program { static int Main(string[] args) { int " + tempVar + "= 0;" + phrase + @" return " + tempVar + @"; } } }"; SyntaxTree tree = CSharpSyntaxTree.ParseText(res); CompilationUnitSyntax root = tree.GetCompilationUnitRoot(); dynamic cycle; if (IsDoWhile) { cycle = (from methodDeclaration in root.DescendantNodes() .OfType <DoStatementSyntax>() select methodDeclaration).First(); res = res.Insert(cycle.Statement.FullSpan.Start + 1, $"{tempVar}++;"); } else { cycle = (from methodDeclaration in root.DescendantNodes() .OfType <WhileStatementSyntax>() select methodDeclaration).First(); res = res.Insert(cycle.Statement.FullSpan.Start + 1, $"{tempVar}++;"); } return(res); }
private EntityInfo EntityParse(string entityFilePath, ProjectInfo projectInfo) { string sourceText = File.ReadAllText(entityFilePath); SyntaxTree tree = CSharpSyntaxTree.ParseText(sourceText); CompilationUnitSyntax root = tree.GetCompilationUnitRoot(); string @namespace = root.DescendantNodes().OfType <NamespaceDeclarationSyntax>().Single().Name.ToString();//不满足项目命名空间 ClassDeclarationSyntax classDeclarationSyntax = root.DescendantNodes().OfType <ClassDeclarationSyntax>().Single(); string className = classDeclarationSyntax.Identifier.ToString(); BaseListSyntax baseList = classDeclarationSyntax.BaseList; GenericNameSyntax genericNameSyntax = baseList.DescendantNodes().OfType <SimpleBaseTypeSyntax>() .First(node => !node.ToFullString().StartsWith("I")) // Not interface .DescendantNodes().OfType <GenericNameSyntax>() .FirstOrDefault(); string baseType; string primaryKey; if (genericNameSyntax == null) { // No generic parameter -> Entity with Composite Keys baseType = baseList.DescendantNodes().OfType <SimpleBaseTypeSyntax>().Single().Type.ToString(); primaryKey = "long"; } else { // Normal entity baseType = genericNameSyntax.Identifier.ToString(); primaryKey = genericNameSyntax.DescendantNodes().OfType <TypeArgumentListSyntax>().Single().Arguments[0].ToString(); } List <PropertyInfo> properties = root.DescendantNodes().OfType <PropertyDeclarationSyntax>() .Select(prop => new PropertyInfo(prop.Type.ToString(), prop.Identifier.Value.ToString()) ) .ToList(); string xmlPath = _settingOptions.BaseDirectory + projectInfo.FullName + ".Core.xml"; string entityRemark = Util.GetEntityRemarkBySummary(xmlPath, properties, @namespace + "." + className); if (_settingOptions.Areas != null) { @namespace = projectInfo.FullName + "." + _settingOptions.Areas + "." + className.Pluralize(); } else { @namespace = projectInfo.FullName + "." + className.Pluralize(); } string relativeDirectory = @namespace.RemovePreFix(projectInfo.FullName + ".").Replace('.', '/'); EntityInfo entityInfo = new EntityInfo(@namespace, className, baseType, primaryKey, relativeDirectory); entityInfo.Properties.AddRange(properties); entityInfo.EntityRemark = entityRemark; return(entityInfo); }
public void MsTestUsing() { var str = "Microsoft.VisualStudio.TestTools.UnitTesting"; var actual = _compilationUnit.DescendantNodes().OfType <UsingDirectiveSyntax>() .Count(x => x.Name.ToString() == str); Assert.AreNotEqual(0, actual); }
public void UnitUsingDirectiveTest() { IEnumerable <UsingDirectiveSyntax> NUnitUsingDirective = from usingDirective in _compilationUnitSyntax.DescendantNodes().OfType <UsingDirectiveSyntax>() where usingDirective.Name.ToString() == "Microsoft.VisualStudio.TestTools.UnitTesting" select usingDirective; Assert.IsNotNull(NUnitUsingDirective.FirstOrDefault()); }
public void ClassTest() { IEnumerable <ClassDeclarationSyntax> classes = root.DescendantNodes().OfType <ClassDeclarationSyntax>(); Assert.AreEqual(1, classes.Count()); Assert.AreEqual("MyClassTests", classes.ElementAt <ClassDeclarationSyntax>(0).Identifier.ToString()); Assert.AreEqual(1, classes.ElementAt <ClassDeclarationSyntax>(0).AttributeLists.Count); Assert.AreEqual("TestClass", classes.ElementAt <ClassDeclarationSyntax>(0).AttributeLists[0].Attributes[0].Name.ToString()); }
public FileInformation(string path) { var programText = File.ReadAllText(path); SyntaxTree tree = CSharpSyntaxTree.ParseText(programText); root = tree.GetCompilationUnitRoot(); UsedNamespaces = root.Usings.Select(x => x.Name.ToString()); //Console.WriteLine($"The tree is a {root.Kind()} node."); //Console.WriteLine($"The tree has {root.Members.Count} elements in it."); //Console.WriteLine($"The tree has {root.Usings.Count} using statements. They are:"); //foreach (UsingDirectiveSyntax element in root.Usings) // Console.WriteLine($"\t{element.Name}"); foreach (var item in root.DescendantTokens().Where(m => m.Kind() == SyntaxKind.IdentifierToken)) { SyntaxKind type = item.Parent.Kind(); if (type == SyntaxKind.IdentifierName) { type = item.Parent.Parent.Kind(); } HashSet <string> list; if (!pairs.TryGetValue(type, out list)) { list = new HashSet <string>(); pairs.Add(type, list); } list.Add(item.Text); } List <Type> types = root.DescendantNodes().Where(m => m.Kind() == SyntaxKind.IdentifierName).Select(x => x.Parent.GetType()).ToList(); UsedMembers = pairs.Select(x => x.Value).SelectMany(x => x); UsedAttributes = Consume(SyntaxKind.Attribute); DefinedClasses = Consume(SyntaxKind.ClassDeclaration); DefinedFunctions = Consume(SyntaxKind.MethodDeclaration, SyntaxKind.ConstructorDeclaration); DefinedVariables = Consume(SyntaxKind.VariableDeclarator, SyntaxKind.Parameter, SyntaxKind.PropertyDeclaration, SyntaxKind.ForEachStatement, SyntaxKind.Argument, SyntaxKind.SimpleAssignmentExpression); var nodes = root.DescendantNodes().Where(m => m.Kind() == SyntaxKind.Parameter); var available = nodes.SelectMany(x => { var children = x.ChildNodes(); if (children == null || children.FirstOrDefault() == null) { return(new List <SyntaxNode>()); } return(new List <SyntaxNode> { children.First() }); }); UsedTypes = available.Select(x => x.ToString().RemoveSpecialCharacters()); UsedTypes = UsedTypes.Concat(Consume(SyntaxKind.ObjectCreationExpression, SyntaxKind.VariableDeclaration, SyntaxKind.SimpleBaseType, SyntaxKind.ClassDeclaration)); UsedFunctions = Consume(SyntaxKind.MethodDeclaration, SyntaxKind.ConstructorDeclaration, SyntaxKind.InvocationExpression, SyntaxKind.Parameter, SyntaxKind.PropertyDeclaration, SyntaxKind.ForEachStatement); UsedGenerics = Consume(SyntaxKind.GenericName); }
public void NamespacesTest() { IEnumerable <NamespaceDeclarationSyntax> namespaces; namespaces = compilationUnit1.DescendantNodes().OfType <NamespaceDeclarationSyntax>(); Assert.AreEqual(1, namespaces.Count()); Assert.AreEqual("FakerLib.Test", namespaces.First().Name.ToString()); namespaces = compilationUnit2.DescendantNodes().OfType <NamespaceDeclarationSyntax>(); Assert.AreEqual(1, namespaces.Count()); Assert.AreEqual("FakerLib.Test", namespaces.First().Name.ToString()); }
public void ProcessMethod() { string method = GetMethodText(vsCMPart.vsCMPartWhole); SyntaxTree syntaxTree = this.SyntaxTree = CSharpSyntaxTree.ParseText(method); CompilationUnitSyntax root = (CompilationUnitSyntax)syntaxTree.GetRoot(); variableDeclarations = root.DescendantNodes().OfType <VariableDeclarationSyntax>().ToArray(); variableAssignments = root.DescendantNodes().OfType <AssignmentExpressionSyntax>().ToArray(); }
public void scan() { StreamReader sr = new StreamReader(fs); SyntaxTree tree = CSharpSyntaxTree.ParseText(sr.ReadToEnd()); PrintBefore(tree.ToString()); var compilation = CSharpCompilation.Create("TestTree") .AddReferences( MetadataReference.CreateFromFile( typeof(object).Assembly.Location)) .AddSyntaxTrees(tree); Logger.Info("Compilation language: " + compilation.Language + " " + compilation.LanguageVersion); Logger.Info("--------------------------"); var root = (CompilationUnitSyntax)tree.GetRoot(); root = TranslateUsingDirective(root); var methods = root.DescendantNodes().OfType <MethodDeclarationSyntax>().ToList(); CompilationUnitSyntax translatedRoot = root; ClassDeclarationSyntax classDeclarationSyntax; for (int i = 0; i < translatedRoot.DescendantNodes().OfType <ClassDeclarationSyntax>().ToList().Count; i++) { classDeclarationSyntax = translatedRoot.DescendantNodes().OfType <ClassDeclarationSyntax>().ToList()[i]; if (IsTranslatable(classDeclarationSyntax)) { ClassDeclarationSyntax translated = TranslateClass(classDeclarationSyntax); translatedRoot = translatedRoot.ReplaceNode(classDeclarationSyntax, translated); Logger.Info("Root after translation: \n" + translatedRoot); } else { // var node = classDeclarationSyntax.WithTrailingTrivia(SyntaxFactory.ParseTrailingTrivia("*/" + classDeclarationSyntax.GetTrailingTrivia())); // node = node.WithLeadingTrivia(SyntaxFactory.ParseLeadingTrivia(node.GetLeadingTrivia() + "/*")); // translatedRoot = translatedRoot.ReplaceNode(classDeclarationSyntax, node); //translatedRoot = translatedRoot.InsertTriviaAfter(classDeclarationSyntax.GetTrailingTrivia()[classDeclarationSyntax.GetTrailingTrivia().Count - 1], SyntaxFactory.ParseTrailingTrivia("*/")); var commented = Comment(classDeclarationSyntax); translatedRoot = translatedRoot.ReplaceNode(translatedRoot.DescendantNodes().OfType <ClassDeclarationSyntax>().ToList()[i], commented); translatedRoot = translatedRoot.RemoveNode(translatedRoot.DescendantNodes().OfType <ClassDeclarationSyntax>().ToList()[i], SyntaxRemoveOptions.KeepLeadingTrivia); i--; } } Print(translatedRoot.ToFullString()); }
IEnumerable <MethodDeclarationSyntax> GetMethods(CompilationUnitSyntax root, string code) { var methods = root.DescendantNodes().OfType <MethodDeclarationSyntax>(); if (methods.Count() == 0) { code = CreateMethod(code); root = GetRoot(code); methods = root.DescendantNodes().OfType <MethodDeclarationSyntax>(); } return(methods); }
public void TestUsings() { string expectedUsing = "Microsoft.VisualStudio.TestTools.UnitTesting"; Assert.IsTrue(generatedUnit.DescendantNodes().OfType <UsingDirectiveSyntax>().Any(x => x.Name.ToString() == expectedUsing), " no such using : " + expectedUsing); }
private List <string> GetVBPropertiesForComparison(CompilationUnitSyntax vbRoot) { List <SyntaxNode> syntaxNodes = vbRoot.DescendantNodes().OfType <PropertyStatementSyntax>().Select(p => p as SyntaxNode).ToList(); syntaxNodes.AddRange(vbRoot.DescendantNodes().OfType <PropertyBlockSyntax>().ToList()); var result = new List <string>(syntaxNodes.Count); foreach (var syntaxNode in syntaxNodes) { var identifier = syntaxNode.ChildTokens().FirstOrDefault(t => t.RawKind == (int)SyntaxKind.IdentifierToken).ValueText; if (identifier == null && syntaxNode is PropertyBlockSyntax) { identifier = (syntaxNode as PropertyBlockSyntax).PropertyStatement.Identifier.ValueText; } var descendentNodes = syntaxNode.DescendantNodes().ToList(); string propertyType; if (descendentNodes.Any(n => n is SimpleAsClauseSyntax)) { propertyType = descendentNodes.OfType <SimpleAsClauseSyntax>().FirstOrDefault()?.Type.ToString(); } else if (descendentNodes.Any(n => n is GenericNameSyntax)) { propertyType = descendentNodes.OfType <GenericNameSyntax>().FirstOrDefault()?.ToString(); } else if (descendentNodes.Any(n => n is PredefinedTypeSyntax)) { propertyType = descendentNodes.OfType <PredefinedTypeSyntax>().FirstOrDefault()?.Keyword.ValueText; } else if (descendentNodes.Any(n => n is ObjectCreationExpressionSyntax)) { propertyType = descendentNodes.OfType <ObjectCreationExpressionSyntax>().FirstOrDefault()?.Type.ToString(); } else { throw new ArgumentException($"Unknown type for property {identifier}"); } var csEquivType = GetCSharpEquivalentProperty(propertyType); result.Add($"{identifier}-{csEquivType}"); } return(result.Distinct().ToList()); }
private static IList <string> ExtractUsings(CompilationUnitSyntax root) { return(root.DescendantNodes() .OfType <UsingDirectiveSyntax>() .Select(GetDirectiveName) .Where(IsNotDefaultUsing) .ToList());
private async Task <List <GeneratedClass> > GenerateTestFileAsync(string readedCode) { CompilationUnitSyntax compilationUnitSyntax = ParseCompilationUnit(readedCode); var classes = compilationUnitSyntax.DescendantNodes().OfType <ClassDeclarationSyntax>(); List <UsingDirectiveSyntax> usings = new List <UsingDirectiveSyntax> { UsingDirective(QualifiedName(IdentifierName("Microsoft.VisualStudio"), IdentifierName("TestTools.UnitTesting"))) }; List <GeneratedClass> generatedTestNsClassesList = new List <GeneratedClass>(); foreach (var cl in classes) { var methods = cl.DescendantNodes().OfType <MethodDeclarationSyntax>() .Where(x => x.Modifiers.Any(t => t.ValueText == "public")); string ns = (cl.Parent as NamespaceDeclarationSyntax)?.Name.ToString(); if (ns == null) { ns = "Global"; } var methodsDeclarationList = TransformMethodsList(methods); var classDeclaration = PrepareClassDeclaration(cl.Identifier.ValueText + "Test", methodsDeclarationList, ns); generatedTestNsClassesList.Add( new GeneratedClass( cl.Identifier.ValueText + "Test", PrepareResultDeclaration(ns, classDeclaration, usings).NormalizeWhitespace().ToFullString() )); } return(generatedTestNsClassesList); }
public void DeterminesTypeByMethodCall() { string code = @" using System; public class TestClass { public void TestMethod() { this.GetInt(); } private int GetInt() { return 1; } } "; CompilationUnitSyntax root = CSharpSyntaxTree.ParseText(code).GetCompilationUnitRoot(); InvocationExpressionSyntax node = root.DescendantNodes() .OfType <InvocationExpressionSyntax>() .First(); Type result = TypeResolver.GetNodeDataType(node); Assert.Equal(typeof(int), result); }
private async Task <List <TestClass> > TestsFiles(string code) { CompilationUnitSyntax unitSyntax = ParseCompilationUnit(code); var classes = unitSyntax.DescendantNodes().OfType <ClassDeclarationSyntax>(); List <TestClass> testClasses = new List <TestClass>(); List <UsingDirectiveSyntax> usings = new List <UsingDirectiveSyntax> { UsingDirective(QualifiedName(IdentifierName("Microsoft.VisualStudio"), IdentifierName("TestTools.UnitTesting"))) }; foreach (var clas in classes) { var methods = clas.DescendantNodes().OfType <MethodDeclarationSyntax>().Where(x => x.Modifiers.Any(y => y.ValueText == "public")); string nameSpace = (clas.Parent as NamespaceDeclarationSyntax)?.Name.ToString(); var methodsList = MethodsList(methods); var classdeclar = ClassDeclar(clas.Identifier.ValueText + "Test", methodsList); if (nameSpace == null) { testClasses.Add(new TestClass(clas.Identifier.ValueText + "Test", ResultDeclar(usings, classdeclar, "Global").NormalizeWhitespace().ToFullString())); } else { testClasses.Add(new TestClass(clas.Identifier.ValueText + "Test", ResultDeclar(usings, classdeclar, nameSpace).NormalizeWhitespace().ToFullString())); } } return(testClasses); }
private CompilationUnitSyntax ImportNeededNamespace(CompilationUnitSyntax root, SemanticModel semanticModel, MemberAccessExpressionSyntax callerMethod) { var symbolInfo = semanticModel.GetSymbolInfo(callerMethod.Name); var methodSymbol = symbolInfo.Symbol as IMethodSymbol; if (methodSymbol == null) { return(root); } var namespaceDisplayString = methodSymbol.ContainingNamespace.ToDisplayString(); var hasNamespaceImported = root .DescendantNodes() .OfType <UsingDirectiveSyntax>() .Select(s => s.DescendantNodes().OfType <IdentifierNameSyntax>()) .Select(s => TransformIdentifierNameSyntaxIntoNamespace(s)) .Any(p => p == namespaceDisplayString); if (!hasNamespaceImported) { var namespaceQualifiedName = GenerateNamespaceQualifiedName(namespaceDisplayString.Split('.')); root = root.AddUsings(SyntaxFactory.UsingDirective(namespaceQualifiedName)); } return(root); }
private static bool ShouldAddExternAlias(ImmutableArray <string> aliases, CompilationUnitSyntax root) { var identifiers = root.DescendantNodes().OfType <ExternAliasDirectiveSyntax>().Select(e => e.Identifier.ToString()); var externAliases = aliases.Where(a => identifiers.Contains(a)); return(!externAliases.Any()); }
public AnalysisResult Analyze(string classAsAString) { SyntaxTree tree = CSharpSyntaxTree.ParseText(classAsAString); CompilationUnitSyntax root = tree.GetCompilationUnitRoot(); var classDeclarationSyntax = root.DescendantNodes().OfType <ClassDeclarationSyntax>().FirstOrDefault(); if (classDeclarationSyntax == null) { throw new Exception("No class definition"); } var className = classDeclarationSyntax.Identifier.ValueText; var propertyDeclarationSyntaxArray = classDeclarationSyntax.DescendantNodes() .OfType <PropertyDeclarationSyntax>() .ToArray(); var properties = new List <ClassMember>(propertyDeclarationSyntaxArray.Length); foreach (var propertyDeclarationSyntax in propertyDeclarationSyntaxArray) { var type = propertyDeclarationSyntax.Type.ToString(); var name = propertyDeclarationSyntax.Identifier.ValueText; var property = new ClassMember(type, name); properties.Add(property); } return(new AnalysisResult(className, properties)); }
/// <summary> /// Generator for different Linqexpressions /// </summary> /// <param name="expression"></param> /// <returns></returns> private IEnumerable <IdentifierNameSyntax> GenerateExpressions(LinqExpression expression) { SyntaxTree tree = CSharpSyntaxTree.ParseText( $@"using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace TestApplication {{ class Program {{ static void Main(string[] args) {{ IEnumerable<string> Test = new[] {{""1"", ""2"", ""3"", ""4"", ""5""}}; Console.WriteLine(Test.{expression.ToString()}()); }} }} }}"); CompilationUnitSyntax root = (CompilationUnitSyntax)tree.GetRoot(); IEnumerable <IdentifierNameSyntax> expressions = root.DescendantNodes() .Where(d => d.Kind().Equals(SyntaxKind.IdentifierName) && ((IdentifierNameSyntax)d).Identifier.ValueText.Equals( expression.ToString())) .Cast <IdentifierNameSyntax>(); return(expressions); }
public List <SyntaxNode> GenerateCompilationUnitFromSourceCode(string sourceCode) { try { CompilationUnitSyntax sourceRoot = CSharpSyntaxTree.ParseText(sourceCode).GetCompilationUnitRoot(); if (sourceRoot.Members.Count == 0) { return(null); } List <ClassDeclarationSyntax> classDeclarations = sourceRoot.DescendantNodes().OfType <ClassDeclarationSyntax>().ToList(); List <SyntaxNode> Syntaxnodes = new List <SyntaxNode>(); foreach (var classDeclaration in classDeclarations) { SyntaxNode result = GenerateCompilationUnit(classDeclaration); result = GenerateClassNode(result, classDeclaration); result = GenerateTestMethods(result, classDeclaration.DescendantNodes().OfType <MethodDeclarationSyntax>().Where(method => method.Modifiers.Any(modifier => modifier.ToString() == "public"))); Syntaxnodes.Add(result.NormalizeWhitespace()); } return(Syntaxnodes); } catch (Exception e) { return(null); } }
/// <summary> /// 根据命名空间和类的位置获取类型 /// </summary> /// <param name="content">脚本内容</param> /// <param name="classIndex">命名空间里的第index个类</param> /// <param name="namespaceIndex">第namespaceIndex个命名空间</param> /// <returns></returns> public static (SyntaxTree Tree, string ClassName) GetTreeAndClassName(string content, int classIndex = 1, int namespaceIndex = 1) { classIndex -= 1; namespaceIndex -= 1; SyntaxTree tree = CSharpSyntaxTree.ParseText(content); CompilationUnitSyntax root = tree.GetCompilationUnitRoot(); var firstMember = root.Members[namespaceIndex]; IEnumerable <SyntaxNode> result = from namespaceNodes in root.DescendantNodes().OfType <NamespaceDeclarationSyntax>() select namespaceNodes; SyntaxNode node = null; if (result.Count() != 0) { node = result.ToArray()[namespaceIndex]; } else { node = root; } var classResult = from classNodes in node.DescendantNodes().OfType <ClassDeclarationSyntax>() select classNodes; return(tree, classResult.ToArray()[classIndex].Identifier.Text); }
private static string ExtractNamespace(CompilationUnitSyntax root) { var namespaceDeclaration = root.DescendantNodes() .OfType <NamespaceDeclarationSyntax>(); return(namespaceDeclaration.Single().Name.ToString()); }
private void ChangeTestMethodAttributesToFact(CompilationUnitSyntax root, SemanticModel semanticModel, TransformationTracker transformationTracker) { List <AttributeSyntax> nodesToReplace = new List <AttributeSyntax>(); foreach (var attributeSyntax in root.DescendantNodes().OfType <AttributeSyntax>()) { var typeInfo = semanticModel.GetTypeInfo(attributeSyntax); if (typeInfo.Type != null) { string attributeTypeDocID = typeInfo.Type.GetDocumentationCommentId(); if (IsTestNamespaceType(attributeTypeDocID, "TestMethodAttribute")) { nodesToReplace.Add(attributeSyntax); } } } transformationTracker.AddTransformation(nodesToReplace, (transformationRoot, rewrittenNodes, originalNodeMap) => { return(transformationRoot.ReplaceNodes(rewrittenNodes, (originalNode, rewrittenNode) => { return ((AttributeSyntax)rewrittenNode).WithName(SyntaxFactory.ParseName("Fact")).NormalizeWhitespace(); })); }); }
public static CompilationUnitSyntax AddUsing(this CompilationUnitSyntax root, string @namespace, string targetNamespace) { var usings = root.DescendantNodes(n => true).OfType <UsingDirectiveSyntax>(); var lastUsing = usings.LastOrDefault(); var namespaceDecl = !string.IsNullOrWhiteSpace(targetNamespace) ? root.GetNamespaceDeclaration(targetNamespace) : null; if (namespaceDecl == null || lastUsing == null || !lastUsing.Ancestors().OfType <NamespaceDeclarationSyntax>().Any()) { root = root.AddUsings(CreateUsing(@namespace)); return(root); } var nsTTokens = targetNamespace.Split('.'); var nsTokens = @namespace.Split('.'); var i = 0; while (i < nsTokens.Length && i < nsTTokens.Length && nsTTokens[i] == nsTokens[i]) { i++; } nsTokens = nsTokens.Skip(i).ToArray(); if (nsTokens.Length == 0) { return(root); } @namespace = nsTokens.Join("."); var newNamespaceDecl = namespaceDecl.AddUsings(CreateUsing(@namespace)); root = root.ReplaceNode(namespaceDecl, newNamespaceDecl); return(root); }
private void ChangeTestInitializeAttributesToCtor(CompilationUnitSyntax root, SemanticModel semanticModel, TransformationTracker transformationTracker) { List <AttributeSyntax> nodesToReplace = new List <AttributeSyntax>(); foreach (var attributeSyntax in root.DescendantNodes().OfType <AttributeSyntax>()) { var typeInfo = semanticModel.GetTypeInfo(attributeSyntax); if (typeInfo.Type != null) { string attributeTypeDocID = typeInfo.Type.GetDocumentationCommentId(); if (IsTestNamespaceType(attributeTypeDocID, "TestInitializeAttribute")) { nodesToReplace.Add(attributeSyntax); } } } transformationTracker.AddTransformation(nodesToReplace, (transformationRoot, rewrittenNodes, originalNodeMap) => { foreach (AttributeSyntax rewrittenNode in rewrittenNodes) { var attributeListSyntax = (AttributeListSyntax)rewrittenNode.Parent; var methodDeclarationSyntax = (MethodDeclarationSyntax)attributeListSyntax.Parent; var className = transformationRoot.DescendantNodes().OfType <ClassDeclarationSyntax>().Last().Identifier; ConstructorDeclarationSyntax ctorSyntax = ConstructorDeclaration(new SyntaxList <AttributeListSyntax>(), methodDeclarationSyntax.Modifiers, className.NormalizeWhitespace(), methodDeclarationSyntax.ParameterList, null, methodDeclarationSyntax.Body); transformationRoot = transformationRoot.ReplaceNode(methodDeclarationSyntax, ctorSyntax); } return(transformationRoot); }); }