private static LambdaExpressionSyntax GetNewNode( LambdaExpressionSyntax lambda, ExpressionSyntax expression, ISymbol symbol) { BlockSyntax block = Block(GetStatement(expression, symbol)); block = block .WithCloseBraceToken( block.CloseBraceToken .WithLeadingTrivia(TriviaList(CSharpFactory.NewLineTrivia()))); switch (lambda.Kind()) { case SyntaxKind.SimpleLambdaExpression: { return(((SimpleLambdaExpressionSyntax)lambda) .WithBody(block)); } case SyntaxKind.ParenthesizedLambdaExpression: { return(((ParenthesizedLambdaExpressionSyntax)lambda) .WithBody(block)); } } return(lambda); }
private static bool AreEquivalent(StatementSyntax statement1, StatementSyntax statement2) { if (statement1 == null) { return(false); } if (statement2 == null) { return(false); } if (!(statement1 is BlockSyntax block1)) { return(CSharpFactory.AreEquivalent(statement1, statement2.SingleNonBlockStatementOrDefault())); } SyntaxList <StatementSyntax> statements1 = block1.Statements; if (!(statement2 is BlockSyntax block2)) { return(CSharpFactory.AreEquivalent(statement2, statement1.SingleNonBlockStatementOrDefault())); } SyntaxList <StatementSyntax> statements2 = block2.Statements; return(SyntaxFactory.AreEquivalent(statements1, statements2, topLevel: false)); }
public static async Task <Document> RefactorAsync( Document document, StatementSyntax statement, CancellationToken cancellationToken) { StatementSyntax newStatement = statement .WithLeadingTrivia(statement.GetLeadingTrivia().Insert(0, CSharpFactory.NewLineTrivia())) .WithFormatterAnnotation(); if (statement.IsParentKind(SyntaxKind.Block)) { var block = (BlockSyntax)statement.Parent; if (block.IsSingleLine(includeExteriorTrivia: false)) { SyntaxTriviaList triviaList = block.CloseBraceToken.LeadingTrivia .Add(CSharpFactory.NewLineTrivia()); BlockSyntax newBlock = block .WithCloseBraceToken(block.CloseBraceToken.WithLeadingTrivia(triviaList)) .WithStatements(block.Statements.Replace(statement, newStatement)) .WithFormatterAnnotation(); return(await document.ReplaceNodeAsync(block, newBlock, cancellationToken).ConfigureAwait(false)); } else { return(await document.ReplaceNodeAsync(statement, newStatement, cancellationToken).ConfigureAwait(false)); } } else { return(await document.ReplaceNodeAsync(statement, newStatement, cancellationToken).ConfigureAwait(false)); } }
public static Task <Document> RefactorAsync( Document document, BlockSyntax block, CancellationToken cancellationToken) { SyntaxList <StatementSyntax> statements = block.Statements; var ifStatement = (IfStatementSyntax)statements[0]; var returnStatement = (ReturnStatementSyntax)statements[1]; var expressionStatement = (ExpressionStatementSyntax)ifStatement.GetSingleStatementOrDefault(); var assignment = (AssignmentExpressionSyntax)expressionStatement.Expression; ExpressionSyntax expression = returnStatement.Expression.WithoutTrivia(); BinaryExpressionSyntax coalesceExpression = CSharpFactory.CoalesceExpression( expression, CSharpFactory.SimpleAssignmentExpression(expression, assignment.Right.WithoutTrivia()).Parenthesize()); ReturnStatementSyntax newReturnStatement = returnStatement .WithExpression(coalesceExpression) .WithLeadingTrivia(ifStatement.GetLeadingTrivia()); SyntaxList <StatementSyntax> newStatements = statements .Replace(returnStatement, newReturnStatement) .RemoveAt(0); BlockSyntax newBlock = block.WithStatements(newStatements); return(document.ReplaceNodeAsync(block, newBlock, cancellationToken)); }
private static bool CanUseCoalesceExpression(StatementSyntax statement, ExpressionSyntax expression) { SyntaxKind kind = statement.Kind(); if (kind == SyntaxKind.LocalDeclarationStatement) { var localDeclarationStatement = (LocalDeclarationStatementSyntax)statement; VariableDeclaratorSyntax declarator = localDeclarationStatement.Declaration? .Variables .SingleOrDefault(shouldThrow: false); ExpressionSyntax value = declarator?.Initializer?.Value; return(value != null && expression.IsKind(SyntaxKind.IdentifierName) && string.Equals(declarator.Identifier.ValueText, ((IdentifierNameSyntax)expression).Identifier.ValueText, StringComparison.Ordinal) && !value.GetTrailingTrivia().Any(f => f.IsDirective) && !localDeclarationStatement.SemicolonToken.ContainsDirectives); } else if (kind == SyntaxKind.ExpressionStatement) { var expressionStatement = (ExpressionStatementSyntax)statement; SimpleAssignmentStatementInfo assignmentInfo = SyntaxInfo.SimpleAssignmentStatementInfo(expressionStatement); return(assignmentInfo.Success && CSharpFactory.AreEquivalent(expression, assignmentInfo.Left) && !assignmentInfo.Right.GetTrailingTrivia().Any(f => f.IsDirective) && !expressionStatement.SemicolonToken.ContainsDirectives); } return(false); }
internal static ExpressionSyntax FindExpressionThatCanBeConditionallyAccessed(ExpressionSyntax expressionToFind, ExpressionSyntax expression) { if (expression.IsKind(SyntaxKind.LogicalNotExpression)) { expression = ((PrefixUnaryExpressionSyntax)expression).Operand; } SyntaxKind kind = expressionToFind.Kind(); SyntaxToken firstToken = expression.GetFirstToken(); int start = firstToken.SpanStart; SyntaxNode node = firstToken.Parent; while (node?.SpanStart == start) { if (kind == node.Kind() && node.IsParentKind(SyntaxKind.SimpleMemberAccessExpression, SyntaxKind.ElementAccessExpression) && CSharpFactory.AreEquivalent(expressionToFind, node)) { return((ExpressionSyntax)node); } node = node.Parent; } return(null); }
public static async Task ComputeRefactoringsAsync(RefactoringContext context, CastExpressionSyntax castExpression) { if (context.IsRefactoringEnabled(RefactoringIdentifiers.ReplaceCastWithAs) && context.Span.IsEmptyAndContainedInSpanOrBetweenSpans(castExpression)) { SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(castExpression.Type, context.CancellationToken); if (typeSymbol?.IsErrorType() == false && typeSymbol.IsReferenceTypeOrNullableType()) { Document document = context.Document; context.RegisterRefactoring( "Replace cast with 'as'", cancellationToken => { BinaryExpressionSyntax newNode = CSharpFactory.AsExpression(castExpression.Expression.WithTriviaFrom(castExpression.Type), castExpression.Type.WithTriviaFrom(castExpression.Expression)) .WithTriviaFrom(castExpression) .WithFormatterAnnotation(); return(document.ReplaceNodeAsync(castExpression, newNode, cancellationToken)); }, RefactoringIdentifiers.ReplaceCastWithAs); } } }
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) { SyntaxNode root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); ImplicitArrayCreationExpressionSyntax expression = root .FindNode(context.Span, getInnermostNodeForTie: true)? .FirstAncestorOrSelf <ImplicitArrayCreationExpressionSyntax>(); if (expression != null && context.Document.SupportsSemanticModel) { SemanticModel semanticModel = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false); var typeSymbol = semanticModel .GetTypeInfo(expression, context.CancellationToken) .Type as IArrayTypeSymbol; if (typeSymbol?.ElementType?.IsErrorType() == false) { var arrayType = CSharpFactory.Type(typeSymbol) as ArrayTypeSyntax; if (arrayType != null) { CodeAction codeAction = CodeAction.Create( $"Declare explicit type '{typeSymbol.ToMinimalDisplayString(semanticModel, expression.Span.Start, SyntaxUtility.DefaultSymbolDisplayFormat)}'", cancellationToken => RefactorAsync(context.Document, expression, arrayType, cancellationToken), DiagnosticIdentifiers.AvoidImplicitlyTypedArray + EquivalenceKeySuffix); context.RegisterCodeFix(codeAction, context.Diagnostics); } } } }
private static bool NullCheckExists(ExpressionSyntax expression, StatementSyntax statement) { StatementListInfo statementsInfo = SyntaxInfo.StatementListInfo(statement); if (!statementsInfo.Success) { return(false); } SyntaxList <StatementSyntax> statements = statementsInfo.Statements; int index = statements.IndexOf(statement); if (index >= statements.Count - 1) { return(false); } StatementSyntax nextStatement = statements[index + 1]; if (!(nextStatement is IfStatementSyntax ifStatement)) { return(false); } NullCheckExpressionInfo nullCheck = SyntaxInfo.NullCheckExpressionInfo(ifStatement.Condition, NullCheckStyles.NotEqualsToNull); if (!nullCheck.Success) { return(false); } return(CSharpFactory.AreEquivalent(expression, nullCheck.Expression)); }
public static async Task ComputeRefactoringAsync(RefactoringContext context, MethodDeclarationSyntax methodDeclaration) { if (context.IsRefactoringEnabled(RefactoringIdentifiers.ChangeMethodReturnTypeToVoid) && methodDeclaration.ReturnType?.IsVoid() == false && methodDeclaration.Body?.Statements.Count > 0 && !methodDeclaration.IsIterator() && context.SupportsSemanticModel) { SemanticModel semanticModel = await context.GetSemanticModelAsync().ConfigureAwait(false); if (!IsAsyncMethodThatReturnsTask(methodDeclaration, semanticModel, context.CancellationToken)) { ControlFlowAnalysis analysis = semanticModel.AnalyzeControlFlow(methodDeclaration.Body); if (analysis.Succeeded && analysis.ReturnStatements.All(node => IsReturnStatementWithoutExpression(node))) { context.RegisterRefactoring( "Change return type to 'void'", cancellationToken => { return(ChangeTypeRefactoring.ChangeTypeAsync( context.Document, methodDeclaration.ReturnType, CSharpFactory.VoidType(), cancellationToken)); }); } } } }
private static Task <Document> ConvertWhileStatementToForStatementAsync( Document document, WhileStatementSyntax whileStatement, CancellationToken cancellationToken) { StatementListInfo statementsInfo = SyntaxInfo.StatementListInfo(whileStatement); SyntaxList <StatementSyntax> statements = statementsInfo.Statements; int index = statements.IndexOf(whileStatement); SingleLocalDeclarationStatementInfo localInfo = SyntaxInfo.SingleLocalDeclarationStatementInfo((LocalDeclarationStatementSyntax)statements[index - 1]); var block = (BlockSyntax)whileStatement.Statement; var expressionStatement = (ExpressionStatementSyntax)block.Statements.Last(); var postIncrementExpression = (PostfixUnaryExpressionSyntax)expressionStatement.Expression; BlockSyntax newBlock = block.WithStatements(block.Statements.Remove(expressionStatement)); ForStatementSyntax forStatement = CSharpFactory.ForStatement( declaration: localInfo.Declaration.TrimTrivia(), condition: whileStatement.Condition, incrementor: postIncrementExpression.TrimTrivia(), statement: newBlock); forStatement = forStatement .WithLeadingTrivia(localInfo.Statement.GetLeadingTrivia().AddRange(whileStatement.GetLeadingTrivia().EmptyIfWhitespace())) .WithFormatterAnnotation(); SyntaxList <StatementSyntax> newStatements = statements.ReplaceRange(index - 1, 2, new StatementSyntax[] { forStatement }); return(document.ReplaceStatementsAsync(statementsInfo, newStatements, cancellationToken)); }
public static void ComputeRefactorings(RefactoringContext context, StatementListSelection selectedStatements) { if (selectedStatements.Count != 2) { return; } SimpleAssignmentStatementInfo simpleAssignment = SyntaxInfo.SimpleAssignmentStatementInfo(selectedStatements.First()); if (!simpleAssignment.Success) { return; } if (selectedStatements.Last() is not ReturnStatementSyntax returnStatement) { return; } if (returnStatement.Expression == null) { return; } if (!CSharpFactory.AreEquivalent(simpleAssignment.Left, returnStatement.Expression)) { return; } context.RegisterRefactoring( "Remove unnecessary assignment", ct => RefactorAsync(context.Document, simpleAssignment.Statement, returnStatement, ct), RefactoringDescriptors.RemoveUnnecessaryAssignment); }
private static Task <Document> RefactorAsync( Document document, EnumDeclarationSyntax enumDeclaration, INamedTypeSymbol enumSymbol, ulong?value, CancellationToken cancellationToken) { EqualsValueClauseSyntax equalsValue = null; if (value != null) { equalsValue = EqualsValueClause(CSharpFactory.NumericLiteralExpression(value.Value, enumSymbol.EnumUnderlyingType.SpecialType)); } string name = NameGenerator.Default.EnsureUniqueMemberName(DefaultNames.EnumMember, enumSymbol); SyntaxToken identifier = Identifier(name).WithRenameAnnotation(); EnumMemberDeclarationSyntax newEnumMember = EnumMemberDeclaration( default(SyntaxList <AttributeListSyntax>), identifier, equalsValue); EnumDeclarationSyntax newNode = enumDeclaration.AddMembers(newEnumMember); return(document.ReplaceNodeAsync(enumDeclaration, newNode, cancellationToken)); }
private static bool CanUseCoalesceExpression(StatementSyntax statement, ExpressionSyntax expression) { SyntaxKind kind = statement.Kind(); if (kind == SyntaxKind.LocalDeclarationStatement) { SingleLocalDeclarationStatementInfo localInfo = SyntaxInfo.SingleLocalDeclarationStatementInfo((LocalDeclarationStatementSyntax)statement); return(localInfo.Success && !localInfo.Type.IsKind(SyntaxKind.RefType) && expression.IsKind(SyntaxKind.IdentifierName) && string.Equals(localInfo.IdentifierText, ((IdentifierNameSyntax)expression).Identifier.ValueText, StringComparison.Ordinal) && !localInfo.Value.GetTrailingTrivia().Any(f => f.IsDirective) && !localInfo.SemicolonToken.ContainsDirectives); } else if (kind == SyntaxKind.ExpressionStatement) { var expressionStatement = (ExpressionStatementSyntax)statement; SimpleAssignmentStatementInfo assignmentInfo = SyntaxInfo.SimpleAssignmentStatementInfo(expressionStatement); return(assignmentInfo.Success && CSharpFactory.AreEquivalent(expression, assignmentInfo.Left) && !assignmentInfo.Right.GetTrailingTrivia().Any(f => f.IsDirective) && !expressionStatement.SemicolonToken.ContainsDirectives); } return(false); }
private static async Task <Document> ChangeTypeAndAddAwaitAsync( Document document, VariableDeclarationSyntax variableDeclaration, ITypeSymbol typeSymbol, CancellationToken cancellationToken = default(CancellationToken)) { SyntaxNode oldRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); ExpressionSyntax initializerValue = variableDeclaration.Variables[0].Initializer.Value; AwaitExpressionSyntax newInitializerValue = SyntaxFactory.AwaitExpression(initializerValue) .WithTriviaFrom(initializerValue); VariableDeclarationSyntax newNode = variableDeclaration.ReplaceNode(initializerValue, newInitializerValue); newNode = newNode .WithType( CSharpFactory.Type(typeSymbol) .WithTriviaFrom(variableDeclaration.Type) .WithSimplifierAnnotation()); SyntaxNode newRoot = oldRoot.ReplaceNode(variableDeclaration, newNode); return(document.WithSyntaxRoot(newRoot)); }
private static bool IsFixable( ExpressionStatementSyntax expressionStatement, IfStatementSyntax ifStatement, ExpressionSyntax expression, SyntaxNode parent) { ExpressionSyntax expression2 = expressionStatement.Expression; if (expression2?.Kind() == SyntaxKind.SimpleAssignmentExpression) { var assignment = (AssignmentExpressionSyntax)expression2; ExpressionSyntax left = assignment.Left; if (left?.IsMissing == false) { ExpressionSyntax right = assignment.Right; return(right?.IsMissing == false && CSharpFactory.AreEquivalent(expression, left) && !parent.ContainsDirectives(TextSpan.FromBounds(right.Span.End, ifStatement.SpanStart))); } } return(false); }
private static SyntaxToken CreateTokenWithTrailingNewLine(SyntaxKind kind) { return(Token( TriviaList(), kind, TriviaList(CSharpFactory.NewLineTrivia()))); }
public static ConstructorDeclarationSyntax AddStaticModifier(ConstructorDeclarationSyntax constructorDeclaration) { SyntaxTokenList modifiers = constructorDeclaration.Modifiers; if (!modifiers.Contains(SyntaxKind.StaticKeyword)) { SyntaxTokenList newModifiers = modifiers; if (modifiers.ContainsAccessModifier()) { newModifiers = modifiers.RemoveAccessModifiers(); if (newModifiers.Any()) { newModifiers = newModifiers.ReplaceAt(0, newModifiers[0].WithLeadingTrivia(modifiers[0].LeadingTrivia)); newModifiers = Inserter.InsertModifier(newModifiers, SyntaxKind.StaticKeyword); } else { newModifiers = Inserter.InsertModifier(newModifiers, CSharpFactory.StaticKeyword().WithLeadingTrivia(modifiers[0].LeadingTrivia)); } } else { newModifiers = Inserter.InsertModifier(newModifiers, SyntaxKind.StaticKeyword); } return(constructorDeclaration.WithModifiers(newModifiers)); } else { return(constructorDeclaration); } }
private static ConditionalExpressionSyntax CreateMultilineConditionalExpression(ConditionalExpressionSyntax conditionalExpression) { SyntaxTriviaList triviaList = SyntaxUtility.GetIndentTrivia(conditionalExpression.Parent).Add(CSharpFactory.IndentTrivia()); triviaList = triviaList.Insert(0, CSharpFactory.NewLineTrivia()); ParenthesizedExpressionSyntax condition = null; if (conditionalExpression.Condition.IsKind(SyntaxKind.ParenthesizedExpression)) { condition = (ParenthesizedExpressionSyntax)conditionalExpression.Condition; } else { condition = ParenthesizedExpression(conditionalExpression.Condition.WithoutTrailingTrivia()) .WithCloseParenToken(CreateTokenWithTrailingNewLine(SyntaxKind.CloseParenToken)); } return(ConditionalExpression( condition.WithoutTrailingTrivia(), conditionalExpression.WhenTrue.WithoutTrailingTrivia(), conditionalExpression.WhenFalse.WithoutTrailingTrivia()) .WithQuestionToken(CreateToken(SyntaxKind.QuestionToken, triviaList)) .WithColonToken(CreateToken(SyntaxKind.ColonToken, triviaList))); }
public static void ComputeRefactorings(RefactoringContext context, StatementListSelection selectedStatements) { if (selectedStatements.Count != 2) { return; } SimpleAssignmentStatementInfo simpleAssignment = SyntaxInfo.SimpleAssignmentStatementInfo(selectedStatements.First()); if (!simpleAssignment.Success) { return; } if (!(selectedStatements.Last() is ReturnStatementSyntax returnStatement)) { return; } if (returnStatement.Expression == null) { return; } if (!CSharpFactory.AreEquivalent(simpleAssignment.Left, returnStatement.Expression)) { return; } context.RegisterRefactoring( "Merge statements", ct => RefactorAsync(context.Document, simpleAssignment.Statement, returnStatement, ct), RefactoringIdentifiers.MergeAssignmentExpressionWithReturnStatement); }
private static bool AreEquivalent(StatementSyntax statement1, StatementSyntax statement2) { return(statement1.Kind() == statement2.Kind() && CSharpFactory.AreEquivalent(statement1, statement2) && statement1.DescendantTrivia().All(f => f.IsWhitespaceOrEndOfLineTrivia()) && statement2.DescendantTrivia().All(f => f.IsWhitespaceOrEndOfLineTrivia())); }
private static Task <Document> DuplicateStatementAsync( Document document, StatementSyntax statement, CancellationToken cancellationToken = default(CancellationToken)) { StatementContainer container; if (StatementContainer.TryCreate(statement, out container)) { int index = container.Statements.IndexOf(statement); if (index == 0 && container.IsBlock && container.Block.OpenBraceToken.GetFullSpanEndLine() == statement.GetFullSpanStartLine()) { statement = statement.PrependToLeadingTrivia(CSharpFactory.NewLine()); } SyntaxList <StatementSyntax> newStatements = container.Statements.Insert(index + 1, statement); SyntaxNode newNode = container.NodeWithStatements(newStatements); return(document.ReplaceNodeAsync(container.Node, newNode, cancellationToken)); } else { SyntaxList <StatementSyntax> statements = SyntaxFactory.List(new StatementSyntax[] { statement, statement }); BlockSyntax block = SyntaxFactory.Block(statements); return(document.ReplaceNodeAsync(statement, block, cancellationToken)); } }
public static bool IsFixable(AssignmentExpressionSyntax assignmentExpression) { SimpleAssignmentExpressionInfo assignmentInfo = SyntaxInfo.SimpleAssignmentExpressionInfo(assignmentExpression); if (!assignmentInfo.Success) { return(false); } if (assignmentExpression.IsParentKind(SyntaxKind.ObjectInitializerExpression)) { return(false); } if (!IsFixableBinaryExpression(assignmentInfo.Right.Kind())) { return(false); } BinaryExpressionInfo binaryInfo = SyntaxInfo.BinaryExpressionInfo((BinaryExpressionSyntax)assignmentInfo.Right); if (!binaryInfo.Success) { return(false); } if (!CSharpFactory.AreEquivalent(assignmentInfo.Left, binaryInfo.Left)) { return(false); } return(true); }
private static Task <Document> DuplicateStatementAsync( Document document, StatementSyntax statement, CancellationToken cancellationToken = default(CancellationToken)) { StatementsInfo statementsInfo = SyntaxInfo.StatementsInfo(statement); if (statementsInfo.Success) { int index = statementsInfo.Statements.IndexOf(statement); if (index == 0 && statementsInfo.IsInBlock && statementsInfo.Block.OpenBraceToken.GetFullSpanEndLine() == statement.GetFullSpanStartLine()) { statement = statement.PrependToLeadingTrivia(CSharpFactory.NewLine()); } SyntaxList <StatementSyntax> newStatements = statementsInfo.Statements.Insert(index + 1, statement.WithNavigationAnnotation()); StatementsInfo newInfo = statementsInfo.WithStatements(newStatements); return(document.ReplaceNodeAsync(statementsInfo.Node, newInfo.Node, cancellationToken)); } else { SyntaxList <StatementSyntax> statements = SyntaxFactory.List(new StatementSyntax[] { statement, statement.WithNavigationAnnotation() }); BlockSyntax block = SyntaxFactory.Block(statements); return(document.ReplaceNodeAsync(statement, block, cancellationToken)); } }
private static InitializerExpressionSyntax GetMultilineInitializer(InitializerExpressionSyntax initializer) { SyntaxNode parent = initializer.Parent; if (parent.IsKind(SyntaxKind.ObjectCreationExpression) && !initializer.IsKind(SyntaxKind.CollectionInitializerExpression)) { return(initializer .WithExpressions( SeparatedList( initializer.Expressions.Select(expression => expression.WithLeadingTrivia(CSharpFactory.NewLineTrivia())))) .WithFormatterAnnotation()); } SyntaxTriviaList indent = SyntaxUtility.GetIndentTrivia(initializer); SyntaxTriviaList indent2 = indent.Add(CSharpFactory.IndentTrivia()); indent = indent.Insert(0, CSharpFactory.NewLineTrivia()); indent2 = indent2.Insert(0, CSharpFactory.NewLineTrivia()); return(initializer .WithExpressions( SeparatedList( initializer.Expressions.Select(expression => expression.WithLeadingTrivia(indent2)))) .WithOpenBraceToken(initializer.OpenBraceToken.WithLeadingTrivia(indent)) .WithCloseBraceToken(initializer.CloseBraceToken.WithLeadingTrivia(indent)) .WithFormatterAnnotation()); }
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)); }
private static Task <Document> SimplifyDefaultExpressionAsync( Document document, DefaultExpressionSyntax defaultExpression, CancellationToken cancellationToken) { LiteralExpressionSyntax defaultLiteral = CSharpFactory.DefaultLiteralExpression().WithTrailingTrivia(defaultExpression.GetTrailingTrivia()); return(document.ReplaceNodeAsync(defaultExpression, defaultLiteral, cancellationToken)); }
private static Task <Document> RefactorAsync( Document document, SyntaxToken token, CancellationToken cancellationToken) { SyntaxToken newToken = token.AppendToTrailingTrivia(CSharpFactory.NewLineTrivia()); return(document.ReplaceTokenAsync(token, newToken, cancellationToken)); }
private static Task <Document> UseEmptyStringLiteralInsteadOfStringEmptyAsync( Document document, MemberAccessExpressionSyntax memberAccessExpression, CancellationToken cancellationToken = default) { LiteralExpressionSyntax newNode = CSharpFactory.StringLiteralExpression("").WithTriviaFrom(memberAccessExpression); return(document.ReplaceNodeAsync(memberAccessExpression, newNode, cancellationToken)); }
public static Task <Document> RefactorAsync( Document document, MemberAccessExpressionSyntax node, CancellationToken cancellationToken = default) { LiteralExpressionSyntax newNode = CSharpFactory.StringLiteralExpression("").WithTriviaFrom(node); return(document.ReplaceNodeAsync(node, newNode, cancellationToken)); }