private static async Task <Document> RefactorAsync( Document document, ForEachStatementSyntax forEachStatement, IEnumerable <ISymbol> deconstructSymbols, ISymbol identifierSymbol, SemanticModel semanticModel, CancellationToken cancellationToken) { int position = forEachStatement.SpanStart; ITypeSymbol elementType = semanticModel.GetForEachStatementInfo(forEachStatement).ElementType; SyntaxNode enclosingSymbolSyntax = semanticModel.GetEnclosingSymbolSyntax(position, cancellationToken); ImmutableArray <ISymbol> declaredSymbols = semanticModel.GetDeclaredSymbols(enclosingSymbolSyntax, excludeAnonymousTypeProperty: true, cancellationToken); ImmutableArray <ISymbol> symbols = declaredSymbols .Concat(semanticModel.LookupSymbols(position)) .Distinct() .Except(deconstructSymbols) .ToImmutableArray(); Dictionary <string, string> newNames = deconstructSymbols .Select(parameter => { string name = StringUtility.FirstCharToLower(parameter.Name); string newName = NameGenerator.Default.EnsureUniqueName(name, symbols); return(name: parameter.Name, newName); }) .ToDictionary(f => f.name, f => f.newName); var rewriter = new DeconstructForeachVariableRewriter(identifierSymbol, newNames, semanticModel, cancellationToken); var newStatement = (StatementSyntax)rewriter.Visit(forEachStatement.Statement); DeclarationExpressionSyntax variableExpression = DeclarationExpression( CSharpFactory.VarType().WithTriviaFrom(forEachStatement.Type), ParenthesizedVariableDesignation( deconstructSymbols.Select(parameter => { return(SingleVariableDesignation( Identifier(SyntaxTriviaList.Empty, newNames[parameter.Name], SyntaxTriviaList.Empty))); }) .ToSeparatedSyntaxList <VariableDesignationSyntax>()) .WithTriviaFrom(forEachStatement.Identifier)) .WithFormatterAnnotation(); ForEachVariableStatementSyntax forEachVariableStatement = ForEachVariableStatement( forEachStatement.AttributeLists, forEachStatement.AwaitKeyword, forEachStatement.ForEachKeyword, forEachStatement.OpenParenToken, variableExpression, forEachStatement.InKeyword, forEachStatement.Expression, forEachStatement.CloseParenToken, newStatement); return(await document.ReplaceNodeAsync(forEachStatement, forEachVariableStatement, cancellationToken).ConfigureAwait(false)); }
public static void ChangeTypeToVar( CodeFixContext context, Diagnostic diagnostic, TypeSyntax type, string additionalKey = null) { Document document = context.Document; CodeAction codeAction = CodeAction.Create( "Change type to 'var'", cancellationToken => { TypeSyntax newType = CSharpFactory.VarType().WithTriviaFrom(type); return(document.ReplaceNodeAsync(type, newType, cancellationToken)); }, EquivalenceKeyProvider.GetEquivalenceKey(diagnostic, additionalKey)); context.RegisterCodeFix(codeAction, diagnostic); }