Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort and remove (unused) using statements Roslyn script/code?

Sort and remove (unused) using statements Roslyn script/code? I'm looking for some .NET/Roslyn (compiler as service) code that can run through a project and sort and remove unused using statements. I believe this is possible with Roslyn? Can anyone point me to code that could do this rewrite?

like image 917
lucidquiet Avatar asked Mar 28 '12 19:03

lucidquiet


4 Answers

Roslyn CTP September 2012 provides a GetUnusedImportDirectives() method, which is of great use here.

By modifying the OrganizeSolution sample project Matt referenced you can achieve both sorting and removing of (unused) using directives. An (outdated) version of this project can be found here: http://go.microsoft.com/fwlink/?LinkId=263977. It is outdated because document.GetUpdatedDocument() does not exist anymore,

var document = newSolution.GetDocument(documentId);
var transformation = document.OrganizeImports();
var newDocument = transformation.GetUpdatedDocument();

can be simplified to

var document = newSolution.GetDocument(documentId);
var newDocument = document.OrganizeImports();

Adding newDocument = RemoveUnusedImportDirectives(newDocument); and providing the following method will do the trick.

private static IDocument RemoveUnusedImportDirectives(IDocument document)
{
    var root = document.GetSyntaxRoot();
    var semanticModel = document.GetSemanticModel();

    // An IDocument can refer to both a CSharp as well as a VisualBasic source file.
    // Therefore we need to distinguish those cases and provide appropriate casts.  
    // Since the question was tagged c# only the CSharp way is provided.
    switch (document.LanguageServices.Language)
    {
        case LanguageNames.CSharp:
            var oldUsings = ((CompilationUnitSyntax)root).Usings;
            var unusedUsings = ((SemanticModel)semanticModel).GetUnusedImportDirectives();
            var newUsings = Syntax.List(oldUsings.Where(item => !unusedUsings.Contains(item)));
            root = ((CompilationUnitSyntax)root).WithUsings(newUsings);
            document = document.UpdateSyntaxRoot(root);
            break;

        case LanguageNames.VisualBasic:
            // TODO
            break;
    }
    return document;
}
like image 155
jdoerrie Avatar answered Nov 16 '22 07:11

jdoerrie


This is a feature in Visual Studio, but academically I think you would collect using statements from your SyntaxTree like this:

var usings = syntaxTree.Root.DescendentNodes().Where(node is UsingDirectiveSyntax);

...and compare that to the namespaces resolved by the symbol table like this:

private static IEnumerable<INamespaceSymbol> GetNamespaceSymbol(ISymbol symbol)
{
    if (symbol != null && symbol.ContainingNamespace != null)
        yield return symbol.ContainingNamespace;
}

var ns = semanticModel.SyntaxTree.Root.DescendentNodes().SelectMany(node =>
    GetNamespaceSymbol(semanticModel.GetSemanticInfo(node).Symbol)).Distinct();
like image 21
Jeff Griffin Avatar answered Nov 16 '22 06:11

Jeff Griffin


Check out the OrganizeSolution sample project that came with Roslyn. It does something similar to what you want. It does the sorting part. You'll have to also use the SemanticModel like Jeff shows to determine if there are no references to a particular namespace in the source.

like image 1
Matt Warren Avatar answered Nov 16 '22 08:11

Matt Warren


I use this the following extension method to sort usings

internal static SyntaxList<UsingDirectiveSyntax> Sort(this SyntaxList<UsingDirectiveSyntax> usingDirectives, bool placeSystemNamespaceFirst = false) =>
    SyntaxFactory.List(
        usingDirectives
        .OrderBy(x => x.StaticKeyword.IsKind(SyntaxKind.StaticKeyword) ? 1 : x.Alias == null ? 0 : 2)
        .ThenBy(x => x.Alias?.ToString())
        .ThenByDescending(x => placeSystemNamespaceFirst && x.Name.ToString().StartsWith(nameof(System) + "."))
        .ThenBy(x => x.Name.ToString()));

and

compilationUnit = compilationUnit.WithUsings(SortUsings(compilationUnit.Usings))
like image 2
Leroy K Avatar answered Nov 16 '22 07:11

Leroy K