static void Main(string[] args) { //Code to create a node to add in the tree NameSyntax name = IdentifierName("System"); Console.WriteLine($"\tCreated the identifier {name.ToString()}"); name = QualifiedName(name, IdentifierName("Collections")); Console.WriteLine(name.ToString()); name = QualifiedName(name, IdentifierName("Generic")); Console.WriteLine(name.ToString()); //Creation of the tree SyntaxTree tree = CSharpSyntaxTree.ParseText(sampleCode); CompilationUnitSyntax root = tree.GetCompilationUnitRoot(); //Since the syntax tree is immutable, the new node has not been added yet. var oldUsing = root.Usings[1]; var newUsing = oldUsing.WithName(name); Console.WriteLine(root.ToString()); //The below code replaces the old node(oldUsing) with the new node(newUsing) root = root.ReplaceNode(oldUsing, newUsing); Console.WriteLine(root.ToString()); }
private static void Main() { NameSyntax name = SyntaxFactory.IdentifierName("System"); Console.WriteLine(name.ToString()); name = SyntaxFactory.QualifiedName(name, SyntaxFactory.IdentifierName("Collections")); Console.WriteLine(name.ToString()); name = SyntaxFactory.QualifiedName(name, SyntaxFactory.IdentifierName("Generic")); Console.WriteLine(name.ToString()); Console.WriteLine(); Console.WriteLine(); // System.Collections.Generic SyntaxTree tree = CSharpSyntaxTree.ParseText(sampleCode); var root = (CompilationUnitSyntax)tree.GetRoot(); // Second using = System.Collections var oldUsing = root.Usings[1]; // Create a new node with new name var newUsing = oldUsing.WithName(name); // Root is still the same (immutable) Console.WriteLine(root.ToString()); Console.WriteLine(); Console.WriteLine(); // Replace old node with new node root = root.ReplaceNode(oldUsing, newUsing); Console.WriteLine(root.ToString()); }
static async Task Main(string[] args) { // Create a syntax node from scratch NameSyntax name = IdentifierName("System"); WriteLine(name.ToString()); ReadKey(); name = QualifiedName(name, IdentifierName("Collections")); WriteLine(name.ToString()); ReadKey(); name = QualifiedName(name, IdentifierName("Generic")); WriteLine(name.ToString()); ReadKey(); // Make a syntax tree to put our new node inside of SyntaxTree tree = CSharpSyntaxTree.ParseText(sampleCode); var root = (CompilationUnitSyntax)tree.GetRoot(); WriteLine(root.ToString()); ReadKey(); WriteLine(); // Make a new using node var oldUsing = root.Usings[1]; var newUsing = oldUsing.WithName(name); // Make a new tree root = root.ReplaceNode(oldUsing, newUsing); WriteLine(root.ToString()); ReadKey(); }
public static string GetLocalName(this NameSyntax name) { if (name is QualifiedNameSyntax qualifiedName) { return(GetLocalName(qualifiedName.Right)); } return(name.ToString()); }
internal QualifiedNameExpression(AstNode parent, NameSyntax csNode) : base(parent) { Qualifiers.AddRange( csNode .ToString() .Split('.') ); }
private SyntaxNode MaybeReplaceName(NameSyntax node) { var existingName = node.ToString(); return(existingName == _oldTypeName ? SyntaxFactory.ParseName(_newTypeName).WithTriviaFrom(node) : node); }
static void Main(string[] args) { //Using syntax factory to create syntax tree. NameSyntax name = SyntaxFactory.IdentifierName("System"); Console.WriteLine(name.ToString()); name = SyntaxFactory.QualifiedName(name, SyntaxFactory.IdentifierName("Collections")); Console.WriteLine(name.ToString()); name = SyntaxFactory.QualifiedName(name, SyntaxFactory.IdentifierName("Generic")); Console.WriteLine(name.ToString()); SyntaxTree tree = CSharpSyntaxTree.ParseText( @" using System; using System.Collections; using System.Linq; using System.Text; namespace HelloWorld { class Program { static void Main(string[] args) { Console.WriteLine(""Hello, World!""); } } }"); //Get the first using `System.Collections` from the code and replace it with System.Collection.Generic var root = (CompilationUnitSyntax)tree.GetRoot(); var oldUsing = root.Usings[1]; var newUsing = oldUsing.WithName(name); Console.WriteLine(newUsing.ToString()); var modifiedRoot = root.ReplaceNode(oldUsing, newUsing); Console.WriteLine("Old code"); Console.WriteLine(root.ToString().Normalize()); Console.WriteLine("Modified code"); Console.WriteLine(modifiedRoot.ToString().Normalize()); }
static void Main(string[] args) { NameSyntax name = IdentifierName("System"); WriteLine($"\tCreated the identifier {name.ToString()}"); name = QualifiedName(name, IdentifierName("Collections")); WriteLine(name.ToString()); name = QualifiedName(name, IdentifierName("Generic")); WriteLine(name.ToString()); var tree = CSharpSyntaxTree.ParseText(sampleCode); var root = (CompilationUnitSyntax)tree.GetRoot(); var oldUsing = root.Usings[1]; var newUsing = oldUsing.WithName(name); WriteLine(root.ToString()); root = root.ReplaceNode(oldUsing, newUsing); WriteLine(root.ToString()); }
/// <summary> /// Gets the name contained in the <see cref="NameSyntax"/>, without an alias prefix. /// </summary> /// <param name="nameSyntax">The <see cref="NameSyntax"/> from which the name will be extracted.</param> /// <returns>The name contained in the <see cref="NameSyntax"/>, with its alias removed (if any).</returns> internal static string ToUnaliasedString(this NameSyntax nameSyntax) { var name = nameSyntax.ToString(); var aliasSepatorIndex = name.IndexOf(AliasSeparator); if (aliasSepatorIndex != -1) { name = name.Substring(aliasSepatorIndex + AliasSeparator.Length); } return(name); }
// </SnippetDeclareSampleCode> static void Main(string[] args) { var workspace = MSBuildWorkspace.Create(); // <SnippetCreateIdentifierName> NameSyntax name = IdentifierName("System"); WriteLine($"\tCreated the identifier {name.ToString()}"); // </SnippetCreateIdentifierName> // <SnippetCreateQualifiedIdentifierName> name = QualifiedName(name, IdentifierName("Collections")); WriteLine(name.ToString()); // </SnippetCreateQualifiedIdentifierName> // <SnippetCreateFullNamespace> name = QualifiedName(name, IdentifierName("Generic")); WriteLine(name.ToString()); // </SnippetCreateFullNamespace> // <SnippetCreateParseTree> SyntaxTree tree = CSharpSyntaxTree.ParseText(sampleCode); var root = (CompilationUnitSyntax)tree.GetRoot(); // </SnippetCreateParseTree> // <SnippetBuildNewUsing> var oldUsing = root.Usings[1]; var newUsing = oldUsing.WithName(name); WriteLine(root.ToString()); // </SnippetBuildNewUsing> Console.WriteLine(); Console.WriteLine(); // <SnippetTransformTree> root = root.ReplaceNode(oldUsing, newUsing); WriteLine(root.ToString()); // </SnippetTransformTree> }
static void Main(string[] args) { NameSyntax name = SyntaxFactory.IdentifierName("System"); Console.WriteLine(name.ToString()); name = SyntaxFactory.QualifiedName(name, SyntaxFactory.IdentifierName("Collections")); Console.WriteLine(name.ToString()); name = SyntaxFactory.QualifiedName(name, SyntaxFactory.IdentifierName("Generic")); Console.WriteLine(name.ToString()); SyntaxTree tree = CSharpSyntaxTree.ParseText( @"using System; using System.Collections; using System.Linq; using System.Text; namespace HelloWorld { class Program { static void Main(string[] args) { Console.WriteLine(""Hello, World!""); } } }"); var root = (CompilationUnitSyntax)tree.GetRoot(); var oldUsing = root.Usings[1]; var newUsing = oldUsing.WithName(name); root = root.ReplaceNode(oldUsing, newUsing); Console.WriteLine(root.ToString()); Console.ReadLine(); }
protected static SyntaxList <UsingDirectiveSyntax> AddUsingDirectiveIfMissing(SyntaxList <UsingDirectiveSyntax> usings, NameSyntax namespaceName) { string namespaceToImport = namespaceName.ToString(); int? insertionIndex = null; // If the `using` directive is missing, then when we add it, we'll // attempt to keep the existing statements in alphabetical order. for (int i = 0; i < usings.Count; i++) { // Type aliases are usually put last, so if we haven't found an // insertion index yet, then we can insert it before this statement. if (usings[i].Alias is not null) { if (!insertionIndex.HasValue) { insertionIndex = i; } } else { string name = usings[i].Name.ToString(); // If the namespace is already imported, then we can return // the original list of `using` directives without modifying them. if (string.Equals(name, namespaceToImport, System.StringComparison.Ordinal)) { return(usings); } // If we don't have an insertion index, and this `using` directive is // greater than the one we want to insert, then this is the first // directive that should appear after the one we insert. if (!insertionIndex.HasValue && string.Compare(name, namespaceToImport) > 0) { insertionIndex = i; } } } UsingDirectiveSyntax directive = SyntaxFactory.UsingDirective(namespaceName); // If we found where to insert the new directive, then insert // it at that index; otherwise, it must be greater than all // existing directives, so add it to the end of the list. if (insertionIndex.HasValue) { return(usings.Insert(insertionIndex.Value, directive)); } else { return(usings.Add(directive)); } }
public static string GetIdentifierName(this NameSyntax name) { if (name is SimpleNameSyntax simpleName) { return(simpleName.Identifier.Text); } else if (name is QualifiedNameSyntax qualified) { return(qualified.Right.Identifier.Text); } return(name.ToString()); }
static void ConstructionCS() { NameSyntax name = IdentifierName("System"); WriteLine($"Created the identifier {name.ToString()}"); name = QualifiedName(name, IdentifierName("Collections")); WriteLine(name.ToString()); name = QualifiedName(name, IdentifierName("Generic")); WriteLine(name.ToString()); WriteLine("\n"); SyntaxTree tree = CSharpSyntaxTree.ParseText(programText); var root = (CompilationUnitSyntax)tree.GetRoot(); var oldUsing = root.Usings[1]; var newUsing = oldUsing.WithName(name); var newUsing2 = oldUsing.WithName(IdentifierName("System")); root = root.ReplaceNode(oldUsing, newUsing); WriteLine(root.ToString()); WriteLine("\n"); root.Usings.Replace(newUsing, newUsing2); WriteLine(root.ToString()); }
/// <summary> /// Return the child namespace (e.g. "Shapes", "Transforms", etc. or null if there is no child /// and classes should be at the root. /// </summary> /// <param name="sourceNamespace">source namespace</param> /// <returns>child namespace</returns> public static string?GetChildNamespace(NameSyntax sourceNamespace) { string sourceNamespaceString = sourceNamespace.ToString(); if (!sourceNamespaceString.StartsWith(RootNamespace)) { throw new InvalidOperationException($"Source namespace {sourceNamespace} doesn't start with '{RootNamespace}' as expected"); } if (!sourceNamespaceString.StartsWith(RootNamespace + ".")) { return(null); } return(sourceNamespaceString.Substring(sourceNamespaceString.LastIndexOf('.') + 1)); }
private ITransformation[] CreateParametersForName(NameSyntax name) { var rawParameters = name.ToString().Split('.'); var parameters = new List <ITransformation>(); var startIndex = 0; foreach (var rawParameter in rawParameters) { parameters.Add(new StringTransformation(rawParameter, new Range(startIndex, rawParameter.Length))); startIndex += rawParameter.Length + 1; } parameters.Add(new StringTransformation(this.FileName, Range.AfterNode(name))); return(parameters.ToArray()); }
public static string GetTypeName(this NameSyntax nameSyntax) { switch (nameSyntax) { case SimpleNameSyntax simple: return(simple.Identifier.ValueText); case QualifiedNameSyntax qualified: return(qualified.Right.Identifier.ValueText); case AliasQualifiedNameSyntax alias: return(alias.Alias.Identifier.ValueText); default: return(nameSyntax.ToString()); } }
public static string GetName(this NameSyntax name) { if (name == null) { return(null); } switch (name.Kind()) { case SyntaxKind.IdentifierName: case SyntaxKind.GenericName: return(((SimpleNameSyntax)name).Identifier.Text); case SyntaxKind.QualifiedName: return(((QualifiedNameSyntax)name).Right.Identifier.Text); case SyntaxKind.AliasQualifiedName: return(((AliasQualifiedNameSyntax)name).Name.Identifier.Text); } return(name.ToString()); }
private static int CompareNames(NameSyntax name1, NameSyntax name2) { var nameText1 = name1.ToString(); var nameText2 = name2.ToString(); var systemNameText1 = nameText1.StartsWith("System"); var systemNameText2 = nameText2.StartsWith("System"); if (systemNameText1 && !systemNameText2) { return(-1); } else if (systemNameText2 && !systemNameText1) { return(1); } return(StringComparer.CurrentCulture.Compare(nameText1, nameText2)); }
/// <summary> /// Adds a using statement to the compilation if necessary. /// </summary> /// <param name="compilation">The compilation unit to add the using to.</param> /// <param name="name">The name of the using to add.</param> /// <returns>The updated compilation unit with the new using.</returns> public static CompilationUnitSyntax AddUsingIfMissing(CompilationUnitSyntax compilation, NameSyntax name) { // TODO improve string comparison (replace) var stringName = name.ToString(); if (compilation.DescendantNodes().OfType <UsingDirectiveSyntax>().Any(u => Equals(u.Name.ToString(), stringName))) { return(compilation); } // TODO ensure order? if (!compilation.ContainsDirectives || compilation.Usings.Count > 0) { return(compilation.AddUsings(SyntaxFactory.UsingDirective(name))); } // Roslyn bug: AddUsings adds the using before preprocessor settings (aka #define), which is incorrect (compiler error). return(compilation.WithoutLeadingTrivia().AddUsings(SyntaxFactory.UsingDirective(name).WithLeadingTrivia(compilation.GetLeadingTrivia()))); }
public static string ToModuleNamespace(this NameSyntax fixtureNamespace) { return(fixtureNamespace.ToString().Replace(".Test", "")); }
// Determine if the changes made required the addition of a new Using Directive private static SyntaxNode WriteUsings(CompilationUnitSyntax root) => !root.Usings.Select(d => d.Name.ToString()).Any(u => u == qualifiedName.ToString()) ? root?.AddUsings(usingDirective).NormalizeWhitespace() : root;
public override int GetHashCode() { return(name.ToString().GetHashCode()); }
public static T MapBase <T>(SyntaxNode source, NameSyntax name, CodeViewUserControl control, SemanticModel semanticModel) where T : CodeItem { return(MapBase <T>(source, name.ToString(), new SyntaxTokenList(), control, semanticModel)); }
public override string ToString() { return(Name.ToString().ToLower()); }
private void SynchronizeNamespaces(List <Microsoft.CodeAnalysis.Document> documents, Microsoft.CodeAnalysis.Solution solution) { var solutionProjects = solution.Projects.Where(p => p.SupportsCompilation); var usingDirectiveChangelogs = new Dictionary <string, Dictionary <string, string> >(); var projectReferences = new Dictionary <string, List <string> >(); // 修复文件的命名空间 for (var documentIndex = 0; documentIndex < documents.Count; documentIndex++) { var document = documents[documentIndex]; var project = document.Project; var projectNamespace = string.IsNullOrEmpty(project.DefaultNamespace) ? project.Name : project.DefaultNamespace; var projectDir = Path.GetDirectoryName(project.FilePath); if (document.TryGetSyntaxRoot(out var syntaxRoot) && syntaxRoot is CompilationUnitSyntax compilationUnitSyntax) { var memberDeclarationSyntaxNodes = compilationUnitSyntax.Members.ToArray(); var documentFixed = false; var documentDir = Path.GetDirectoryName(document.FilePath); for (var i = 0; i < memberDeclarationSyntaxNodes.Length; i++) { if (!(memberDeclarationSyntaxNodes[i] is NamespaceDeclarationSyntax namespaceDeclarationSyntaxNode)) { continue; } var nameSpace = namespaceDeclarationSyntaxNode.Name.ToString(); var fixedNameSpace = projectNamespace; if (documentDir.StartsWith(projectDir) && documentDir.Length > projectDir.Length) { var relativePath = documentDir.Substring(projectDir.Length); fixedNameSpace = projectNamespace + relativePath.Replace(Path.DirectorySeparatorChar, '.').Replace(Path.AltDirectorySeparatorChar, '.'); } if (nameSpace.Equals(fixedNameSpace)) { continue; } var identifierNameSyntaxNodes = fixedNameSpace.Split('.').Where(n => !string.IsNullOrEmpty(n)) .Select(n => SyntaxFactory.IdentifierName(n)).ToArray(); if (identifierNameSyntaxNodes.Length <= 0) { continue; } NameSyntax nameSyntaxNode = identifierNameSyntaxNodes[0]; for (var ii = 1; ii < identifierNameSyntaxNodes.Length; ii++) { nameSyntaxNode = SyntaxFactory.QualifiedName(nameSyntaxNode, identifierNameSyntaxNodes[ii]); } if (!projectReferences.TryGetValue(project.FilePath, out var affectedProjects)) { affectedProjects = solutionProjects.Where(p => p.AllProjectReferences.Any(r => r.ProjectId.Equals(project.Id))).Select(p => p.FilePath).ToList(); affectedProjects.Add(project.FilePath); projectReferences.Add(project.FilePath, affectedProjects); } foreach (var affectedProject in affectedProjects) { if (!usingDirectiveChangelogs.TryGetValue(affectedProject, out var transformedNamespaces)) { transformedNamespaces = new Dictionary <string, string>(); usingDirectiveChangelogs.Add(affectedProject, transformedNamespaces); } transformedNamespaces[nameSpace] = nameSyntaxNode.ToString(); } nameSyntaxNode = nameSyntaxNode.WithTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed); memberDeclarationSyntaxNodes[i] = namespaceDeclarationSyntaxNode.WithName(nameSyntaxNode); documentFixed = true; } if (documentFixed) { documents[documentIndex] = document .WithSyntaxRoot( compilationUnitSyntax.WithMembers( new SyntaxList <MemberDeclarationSyntax>(memberDeclarationSyntaxNodes))); } } } var solutionDocuments = solutionProjects.Select(project => project.Documents.ToList()).DimensionReduction().ToList(); // 修复解决方案中文件的命名空间引用 for (var documentIndex = 0; documentIndex < solutionDocuments.Count; documentIndex++) { var document = solutionDocuments[documentIndex]; if (!usingDirectiveChangelogs.TryGetValue(document.Project.FilePath, out var transformedNamespaces)) { continue; } if (document.TryGetSyntaxRoot(out var syntaxRoot) && syntaxRoot is CompilationUnitSyntax compilationUnitSyntax) { var usingDirectiveSyntaxNodes = compilationUnitSyntax.Usings.ToArray(); var documentFixed = false; var documentDir = Path.GetDirectoryName(document.FilePath); for (var i = 0; i < usingDirectiveSyntaxNodes.Length; i++) { var usingDirectiveSyntaxNode = usingDirectiveSyntaxNodes[i]; var key = usingDirectiveSyntaxNode.Name.ToString(); if (transformedNamespaces.ContainsKey(key)) { usingDirectiveSyntaxNodes[i] = usingDirectiveSyntaxNode.WithName(SyntaxFactory.IdentifierName(transformedNamespaces[key])); documentFixed = true; } } if (documentFixed) { solutionDocuments[documentIndex] = document .WithSyntaxRoot( compilationUnitSyntax.WithUsings( new SyntaxList <UsingDirectiveSyntax>(usingDirectiveSyntaxNodes))); } } } }
public static T MapBase <T>(SyntaxNode source, NameSyntax name) where T : CodeItem { return(MapBase <T>(source, name.ToString(), new SyntaxTokenList())); }