public static async Task <Solution> RefactorAsync( Document document, FieldDeclarationSyntax fieldDeclaration, VariableDeclaratorSyntax variableDeclarator, CancellationToken cancellationToken) { ExpressionSyntax value = variableDeclarator.Initializer.Value; ParenthesizedExpressionSyntax newValue = value.Parenthesize(); SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); ISymbol symbol = semanticModel.GetDeclaredSymbol(variableDeclarator, cancellationToken); IEnumerable <ReferencedSymbol> referencedSymbols = await SymbolFinder.FindReferencesAsync(symbol, document.Solution(), cancellationToken).ConfigureAwait(false); var newDocuments = new List <KeyValuePair <DocumentId, SyntaxNode> >(); foreach (IGrouping <Document, ReferenceLocation> grouping in referencedSymbols .First() .Locations .Where(f => !f.IsImplicit && !f.IsCandidateLocation) .GroupBy(f => f.Document)) { SyntaxNode root = await grouping.Key.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); SyntaxNode newRoot = root.ReplaceNodes( GetNodesToReplace(grouping.AsEnumerable(), root, fieldDeclaration, variableDeclarator), (f, _) => { if (f.IsKind(SyntaxKind.FieldDeclaration, SyntaxKind.VariableDeclarator)) { return(f.WithAdditionalAnnotations(_removeAnnotation)); } return(newValue.WithTriviaFrom(f)); }); SyntaxNode nodeToRemove = newRoot.GetAnnotatedNodes(_removeAnnotation).FirstOrDefault(); if (nodeToRemove != null) { newRoot = newRoot.RemoveNode(nodeToRemove); } newDocuments.Add(new KeyValuePair <DocumentId, SyntaxNode>(grouping.Key.Id, newRoot)); } Solution newSolution = document.Solution(); foreach (KeyValuePair <DocumentId, SyntaxNode> kvp in newDocuments) { newSolution = newSolution.WithDocumentSyntaxRoot(kvp.Key, kvp.Value); } return(newSolution); }
/// <summary> /// Creates parenthesized expression that is parenthesizing the specified expression. /// </summary> /// <param name="expression"></param> /// <param name="includeElasticTrivia">If true, add elastic trivia.</param> /// <param name="simplifiable">If true, attach <see cref="Simplifier.Annotation"/> to the parenthesized expression.</param> /// <returns></returns> public static ParenthesizedExpressionSyntax Parenthesize( this ExpressionSyntax expression, bool includeElasticTrivia = true, bool simplifiable = true) { ParenthesizedExpressionSyntax parenthesizedExpression = null; if (includeElasticTrivia) { parenthesizedExpression = ParenthesizedExpression(expression.WithoutTrivia()); } else { parenthesizedExpression = ParenthesizedExpression( Token(SyntaxTriviaList.Empty, SyntaxKind.OpenParenToken, SyntaxTriviaList.Empty), expression.WithoutTrivia(), Token(SyntaxTriviaList.Empty, SyntaxKind.CloseParenToken, SyntaxTriviaList.Empty)); } return(parenthesizedExpression .WithTriviaFrom(expression) .WithSimplifierAnnotationIf(simplifiable)); }