Alex Rivera | Logout

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

Asked 2012-03-28T19:00:54.680
12

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?

Edit
Report

2 Answers

4

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:
            /
answered 2013-07-16T12:52:46.160
1

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.

answered 2012-04-03T22:46:05.757

Your Answer