Custom Code Refactoring with VB 2015 and the .NET Compiler Platform
In Part 1 of this series, you started working with the new code-focused experience in Visual Basic 2015. You saw how Visual Basic 2015 introduces integrated code refactoring tools for the first time, learning which and how many refactorings are already available for you to use. The very good news is that you can also create and share custom code refactorings that integrate into Visual Studio's code editor. This is possible because of the .NET Compiler Platform APIs, which empower the code editor and allow for creating custom refactorings other than code analyzers.
In Part 2 (which you should read before going further with this article), you started using the .NET Compiler Platform APIs, creating an analyzer that provides live code analysis as you type.
This article wraps up the series by showing you how to build a custom code refactoring that extends the Visual Basic toolbox in a domain-specific scenario.
Developing a Code Refactoring
Visual Basic 2015 ships with a number of built-in code refactorings, which provide a better way of reorganizing portions of code. However, in some situations you might need customized refactoring techniques. For instance, imagine you want to build a class library that perfectly adheres to the .NET Framework naming conventions. Among the many naming rules, one states that names for public fields must be in Pascal-case when the identifier is composed of multiple words (such as ProductQuantity). For the sake of simplicity, this article provides an example that capitalizes the first letter for the names of public fields, disregarding whether they are made of multiple words.
Creating a refactoring involves many techniques that you learned in the previous articles. The Syntax Visualizer tool helps you to understand where you need to introduce a refactoring and which syntax nodes and objects to use. To understand what you need to accomplish, we'll work with the following proposed example.
In a Console project, write the following field definition at the Module level:
Public oneString As String, oneInt As Integer, twoInt As Integer
Open the Syntax Visualizer. As Figure 1 shows, a field is represented by the FieldDeclaration syntax node and mapped by a FieldDeclarationSyntax object.
Figure 1 Field definitions in the .NET Compiler Platform.
Every FieldDeclaration has one VariableDeclarator element per identifier/type pair. The VariableDeclarator element is mapped by a VariableDeclaratorSyntax object. Every VariableDeclarator element has a ModifiedIdentifier element that represents the variable identifier, mapped by a ModifiedIdentifierSyntax object. Additional elements include SimpleAsClause, which represents the As keyword, PredefinedType, which represents a built-in type in the .NET Framework, and so on. Your goal is checking the first letter for each variable identifier, so you don't need a lot of syntax nodes; you simply need to find FieldDeclaration elements, their VariableDeclarator nodes, and the ModifiedIdentifier nodes. Let's get started.
Create a new project based on the Code Refactoring template and name it PublicFieldCodeRefactoring (see Figure 2).
Figure 2 Creating a new code refactoring project.
When the project is ready, it includes just one code file, called CodeRefactoringProvider.vb. The auto-generated class inherits from Microsoft.CodeAnalysis.CodeRefactorings.CodeRefactoringProvider, which offers the proper infrastructure to build a code refactoring via the ComputeRefactoringAsync method. This is where you write your refactoring logic. But first, add the following simple method, which returns a new string in which the first letter is uppercase:
Private Function ConvertName(oldName As String) As String Return Char.ToLowerInvariant(oldName(0)) + oldName.Substring(1) End Function
Now move inside the ComputeRefactoringAsync method and delete all of its auto-generated content. The first thing to add is checking whether the current syntax node is of type FieldDeclarationSyntax and its modifier is Public; in fact, you need to avoid refactoring a Private, Protected, or Protected Friend field, because these fields allow their first letter to be lowercase. Add the following code:
Public NotOverridable Overrides Async Function _ ComputeRefactoringsAsync(context As CodeRefactoringContext) As Task Dim root = Await context.Document. GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(False) ' Find the node at the selection. Dim node = root.FindNode(context.Span) Dim fieldDecl = TryCast(node, FieldDeclarationSyntax) If fieldDecl Is Nothing Or fieldDecl.Modifiers. ToFullString.Contains("Private") = False Then Return End If
Notice how the FieldDeclarationSyntax object exposes a property called Modifiers, of type SyntaxTokenList, which represents a collection of SyntaxToken objects and can be used to detect the visibility of the current field. Next, you can check whether at least one identifier in the field declaration should be refactored. Take a look at this code:
Dim mustRegisterAction As Boolean For Each declarator In fieldDecl.Declarators 'If at least one starting character is uppercase, must register an action If declarator.Names.Any(Function(d) _ Char.IsUpper(d.Identifier.Value.ToString(0))) Then mustRegisterAction = True Else mustRegisterAction = False End If Next
FieldDeclarationSyntax exposes a property called Declarators, of type SeparatedSyntaxList(Of VariableDeclaratorSyntax), which contains the list of VariableDeclarator elements in the field. Each exposes the Names property, of type SeparatedSyntaxList(Of ModifiedIdentifierSyntax), which contains the list of identifiers in the VariableDeclarator. The code iterates each VariableDeclarator: if at least one variable name starts with an uppercase letter, it sets with True a Boolean variable that determines whether an action must be registered for refactoring the current field. The ModifiedIdentifierSyntax type exposes the Identifier property, which represents the actual variable identifier. You'll work with it later; for now, its Value property is used to detect the form of the first letter in its string representation. If at least one identifier matches the condition, you register an action for the current syntax node as follows:
If mustRegisterAction = False Then Return Else Dim action = CodeAction.Create("Make first char uppercase", Function(c) RenameFieldAsync(context. Document, fieldDecl, c)) ' Register this code action. context.RegisterRefactoring(action) End If
You create an action by invoking the Create method from the Microsoft.CodeAnalysis.CodeActions.CodeAction class; arguments are the text shown in the Light Bulb and a delegate that performs the refactoring. The latter, as for analyzers, receives the current document instance, the current syntax node, and a cancellation token as its arguments. The RenameFieldAsync method begins by getting an instance of the semantic model and the syntax root for the current document, which is something you already saw with analyzers:
Private Async Function RenameFieldAsync(document As Document, fieldDeclaration As FieldDeclarationSyntax, cancellationToken As CancellationToken) _ As Task(Of Document) Dim semanticModel = Await document. GetSemanticModelAsync(cancellationToken). ConfigureAwait(False) Dim root = Await document.GetSyntaxRootAsync
The logic of your action requires iterating variable declarators in the current field; for each declarator, you will need to generate new identifiers for variables whose name starts with a lowercase letter. Finally, you have to generate new declarators and a new document based on the supplied changes. Start by storing the collection of existing variable declarators and declaring two collections of ModifiedIdentifierSyntax and VariableDeclaratorSyntax objects, as follows:
Dim oldDeclarators = fieldDeclaration.Declarators Dim listOfNewModifiedIdentifiers As _ New SeparatedSyntaxList(Of ModifiedIdentifierSyntax) Dim listOfNewModifiedDeclarators As _ New SeparatedSyntaxList(Of VariableDeclaratorSyntax)
The next step is iterating the collection of variable declarators and their names in order to generate new ModifiedIdentifierSyntax objects with new names. The following code demonstrates this process (read inline comments for better understanding):
'Iterate the declarators collection For Each declarator In oldDeclarators 'For each variable name in the declarator... For Each modifiedIdentifier In declarator.Names 'Get a new proper name Dim tempString = ConvertName(modifiedIdentifier.ToFullString) 'Generate a new ModifiedIdentifierSyntax based on 'the previous one's properties but with a new Identifier Dim newModifiedIdentifier As ModifiedIdentifierSyntax = modifiedIdentifier. WithIdentifier(SyntaxFactory.ParseToken(tempString)). WithTrailingTrivia(modifiedIdentifier.GetTrailingTrivia) 'Add the new element to the collection listOfNewModifiedIdentifiers = listOfNewModifiedIdentifiers.Add(newModifiedIdentifier) Next 'Store a new variable declarator with new variable names listOfNewModifiedDeclarators = listOfNewModifiedDeclarators.Add(declarator. WithNames(listOfNewModifiedIdentifiers)) 'Clear the list before next iteration listOfNewModifiedIdentifiers = Nothing listOfNewModifiedIdentifiers = New _ SeparatedSyntaxList(Of ModifiedIdentifierSyntax) Next
Once you have a list of new VariableDeclaratorSyntax objects, you can generate a new FieldDeclarationSyntax like this:
Dim newField = fieldDeclaration. WithDeclarators(listOfNewModifiedDeclarators)
The FieldDeclarationSyntax.WithDeclarators method allows you to specify the variable declarators for the field instance. As you did with analyzers, you finally generate a new syntax node, replacing the old FieldDeclarationSyntax node with the newly created one:
Dim newRoot As SyntaxNode = root.ReplaceNode(fieldDeclaration, newField) Dim newDocument = document.WithSyntaxRoot(newRoot) Return newDocument End Function
You can now press F5 to start the experimental instance and test your code refactoring. If you right-click the field declaration and select Quick Actions, you can see a preview of how the code will be refactored, as demonstrated in Figure 3.
Figure 3 The new code refactoring suggests edits in the Light Bulb.
As well as for analyzers, custom refactorings offer additional domain-specific possibilities and can help developers to write better code. Your effort is pretty easy; you write the analysis logic, and the compiler's APIs do the rest, including the integration with Visual Studio and the Light Bulb. Now that we've reached the end of this article series, it should be much clearer how the .NET Compiler Platform offers new and amazing scenarios, especially for developers whose business is building and selling libraries and/or user controls, because they can now include live code analysis with their APIs.