Exemple #1
0
        private static IEnumerable <LocalDeclarationStatementSyntax> SplitLocalDeclaration(LocalDeclarationStatementSyntax statement)
        {
            SeparatedSyntaxList <VariableDeclaratorSyntax> variables = statement.Declaration.Variables;

            LocalDeclarationStatementSyntax statement2 = statement.WithoutTrivia();

            for (int i = 0; i < variables.Count; i++)
            {
                LocalDeclarationStatementSyntax newStatement = LocalDeclarationStatement(
                    statement2.Modifiers,
                    VariableDeclaration(
                        statement2.Declaration.Type,
                        SingletonSeparatedList(variables[i])));

                if (i == 0)
                {
                    newStatement = newStatement.WithLeadingTrivia(statement.GetLeadingTrivia());
                }

                if (i == variables.Count - 1)
                {
                    newStatement = newStatement.WithTrailingTrivia(statement.GetTrailingTrivia());
                }

                yield return(newStatement.WithFormatterAnnotation());
            }
        }
Exemple #2
0
        private static async Task <Document> ApplyAddUsingFixAsync(CodeFixContext context, LocalDeclarationStatementSyntax statement, ITypeSymbol type, CancellationToken cancellationToken)
        {
            var editor = await DocumentEditor.CreateAsync(context.Document, cancellationToken).ConfigureAwait(false);

            var containingType      = statement.FirstAncestor <TypeDeclarationSyntax>();
            var usesUnderscoreNames = containingType.UsesUnderscoreNames(editor.SemanticModel, cancellationToken);
            var variableDeclarator  = statement.Declaration.Variables[0];
            var identifier          = variableDeclarator.Identifier;
            var field = editor.AddField(
                containingType,
                usesUnderscoreNames
                    ? "_" + identifier.ValueText
                    : identifier.ValueText,
                Accessibility.Private,
                DeclarationModifiers.ReadOnly,
                type,
                CancellationToken.None);

            var fieldAccess = usesUnderscoreNames
                ? SyntaxFactory.IdentifierName(field.Name())
                : SyntaxFactory.ParseExpression($"this.{field.Name()}");

            editor.ReplaceNode(
                statement,
                SyntaxFactory.ExpressionStatement(
                    (ExpressionSyntax)editor.Generator.AssignmentStatement(
                        fieldAccess,
                        variableDeclarator.Initializer.Value))
                .WithLeadingTrivia(statement.GetLeadingTrivia())
                .WithTrailingTrivia(statement.GetTrailingTrivia()));

            return(editor.GetChangedDocument());
        }
        private static async Task <Document> RefactorAsync(
            Document document,
            ConditionalExpressionSyntax conditionalExpression,
            LocalDeclarationStatementSyntax localDeclaration,
            CancellationToken cancellationToken)
        {
            SyntaxNode oldRoot = await document.GetSyntaxRootAsync(cancellationToken);

            SemanticModel semanticModel = await document.GetSemanticModelAsync();

            var block = (BlockSyntax)localDeclaration.Parent;

            LocalDeclarationStatementSyntax newLocalDeclaration = GetNewLocalDeclaration(conditionalExpression, localDeclaration, semanticModel)
                                                                  .WithLeadingTrivia(localDeclaration.GetLeadingTrivia())
                                                                  .WithAdditionalAnnotations(Formatter.Annotation);

            var variableDeclarator = (VariableDeclaratorSyntax)conditionalExpression.Parent.Parent;

            IfStatementSyntax ifStatement = ConvertToIfElseWithAssignment(conditionalExpression, IdentifierName(variableDeclarator.Identifier.ToString()))
                                            .WithTrailingTrivia(localDeclaration.GetTrailingTrivia())
                                            .WithAdditionalAnnotations(Formatter.Annotation);

            SyntaxList <StatementSyntax> statements = block.Statements
                                                      .Replace(localDeclaration, newLocalDeclaration)
                                                      .Insert(block.Statements.IndexOf(localDeclaration) + 1, ifStatement);

            SyntaxNode newRoot = oldRoot.ReplaceNode(block, block.WithStatements(statements));

            return(document.WithSyntaxRoot(newRoot));
        }
Exemple #4
0
        private static async Task <Document> RefactorAsync(
            Document document,
            LocalDeclarationStatementSyntax localDeclaration,
            ConditionalExpressionSyntax conditionalExpression,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            SemanticModel semanticModel = await document.GetSemanticModelAsync().ConfigureAwait(false);

            TypeSyntax type = localDeclaration.Declaration.Type;

            LocalDeclarationStatementSyntax newLocalDeclaration = localDeclaration.RemoveNode(conditionalExpression.Parent, SyntaxRemoveOptions.KeepExteriorTrivia);

            if (type.IsVar)
            {
                ITypeSymbol typeSymbol = semanticModel.GetTypeSymbol(conditionalExpression);

                if (typeSymbol?.IsErrorType() == false)
                {
                    newLocalDeclaration = newLocalDeclaration.ReplaceNode(
                        newLocalDeclaration.Declaration.Type,
                        typeSymbol.ToMinimalTypeSyntax(semanticModel, type.SpanStart).WithSimplifierAnnotation());
                }
            }

            newLocalDeclaration = newLocalDeclaration
                                  .WithLeadingTrivia(localDeclaration.GetLeadingTrivia())
                                  .WithFormatterAnnotation();

            IfStatementSyntax ifStatement = CreateIfStatement(conditionalExpression)
                                            .WithTrailingTrivia(localDeclaration.GetTrailingTrivia())
                                            .WithFormatterAnnotation();

            SyntaxNode parent = localDeclaration.Parent;

            if (parent.IsKind(SyntaxKind.SwitchSection))
            {
                var section = (SwitchSectionSyntax)parent;

                SyntaxList <StatementSyntax> statements = section.Statements;

                statements = statements
                             .Replace(localDeclaration, newLocalDeclaration)
                             .Insert(statements.IndexOf(localDeclaration) + 1, ifStatement);

                return(await document.ReplaceNodeAsync(section, section.WithStatements(statements), cancellationToken).ConfigureAwait(false));
            }
            else
            {
                var block = (BlockSyntax)parent;

                SyntaxList <StatementSyntax> statements = block.Statements;

                statements = statements
                             .Replace(localDeclaration, newLocalDeclaration)
                             .Insert(statements.IndexOf(localDeclaration) + 1, ifStatement);

                return(await document.ReplaceNodeAsync(block, block.WithStatements(statements), cancellationToken).ConfigureAwait(false));
            }
        }
        private static async Task <Document> ApplyAddUsingFixAsync(CodeFixContext context, LocalDeclarationStatementSyntax statement, ITypeSymbol type)
        {
            var editor = await DocumentEditor.CreateAsync(context.Document).ConfigureAwait(false);

            var usesUnderscoreNames = editor.SemanticModel.SyntaxTree.GetRoot().UsesUnderscoreNames(editor.SemanticModel, CancellationToken.None);
            var identifier          = statement.Declaration.Variables[0].Identifier;
            var name = usesUnderscoreNames
                ? "_" + identifier.ValueText
                : identifier.ValueText;
            var containingType = statement.FirstAncestor <TypeDeclarationSyntax>();
            var declaredSymbol = editor.SemanticModel.GetDeclaredSymbol(containingType);

            while (declaredSymbol.MemberNames.Contains(name))
            {
                name += "_";
            }

            var newField = (FieldDeclarationSyntax)editor.Generator.FieldDeclaration(
                name,
                accessibility: Accessibility.Private,
                modifiers: DeclarationModifiers.ReadOnly,
                type: SyntaxFactory.ParseTypeName(type.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)));
            var members = containingType.Members;

            if (members.TryGetFirst(x => x is FieldDeclarationSyntax, out MemberDeclarationSyntax field))
            {
                editor.InsertBefore(field, new[] { newField });
            }
            else if (members.TryGetFirst(out field))
            {
                editor.InsertBefore(field, new[] { newField });
            }
            else
            {
                editor.AddMember(containingType, newField);
            }

            var fieldAccess = usesUnderscoreNames
                ? SyntaxFactory.IdentifierName(name)
                : SyntaxFactory.ParseExpression($"this.{name}");

            editor.ReplaceNode(
                statement,
                SyntaxFactory.ExpressionStatement(
                    (ExpressionSyntax)editor.Generator.AssignmentStatement(
                        fieldAccess,
                        statement.Declaration.Variables[0].Initializer.Value))
                .WithLeadingTrivia(statement.GetLeadingTrivia())
                .WithTrailingTrivia(statement.GetTrailingTrivia()));
            return(editor.GetChangedDocument());
        }
Exemple #6
0
        private static async Task <Document> RefactorAsync(
            Document document,
            ConditionalExpressionSyntax conditionalExpression,
            LocalDeclarationStatementSyntax localDeclaration,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);

            SemanticModel semanticModel = await document.GetSemanticModelAsync().ConfigureAwait(false);

            LocalDeclarationStatementSyntax newLocalDeclaration = GetNewLocalDeclaration(conditionalExpression, localDeclaration, semanticModel)
                                                                  .WithLeadingTrivia(localDeclaration.GetLeadingTrivia())
                                                                  .WithFormatterAnnotation();

            var variableDeclarator = (VariableDeclaratorSyntax)conditionalExpression.Parent.Parent;

            IfStatementSyntax ifStatement = ReplaceWithIfElseWithAssignment(conditionalExpression, IdentifierName(variableDeclarator.Identifier.ValueText))
                                            .WithTrailingTrivia(localDeclaration.GetTrailingTrivia())
                                            .WithFormatterAnnotation();

            SyntaxNode parent = localDeclaration.Parent;

            if (parent.IsKind(SyntaxKind.SwitchSection))
            {
                var section = (SwitchSectionSyntax)parent;

                SyntaxList <StatementSyntax> statements = section.Statements;

                statements = statements
                             .Replace(localDeclaration, newLocalDeclaration)
                             .Insert(statements.IndexOf(localDeclaration) + 1, ifStatement);

                root = root.ReplaceNode(section, section.WithStatements(statements));
            }
            else
            {
                var block = (BlockSyntax)parent;

                SyntaxList <StatementSyntax> statements = block.Statements;

                statements = statements
                             .Replace(localDeclaration, newLocalDeclaration)
                             .Insert(statements.IndexOf(localDeclaration) + 1, ifStatement);

                root = root.ReplaceNode(block, block.WithStatements(statements));
            }

            return(document.WithSyntaxRoot(root));
        }
Exemple #7
0
        private static BlockSyntax CreateBlock(ImmutableArray <StatementSyntax> statements, LocalDeclarationStatementSyntax localDeclaration)
        {
            if (statements.Length > 1)
            {
                var nodes = new List <StatementSyntax>(statements.Skip(1));

                nodes[0] = nodes[0].WithLeadingTrivia(
                    localDeclaration
                    .GetTrailingTrivia()
                    .AddRange(nodes[0].GetLeadingTrivia()));

                nodes[nodes.Count - 1] = nodes[nodes.Count - 1].WithTrailingTrivia();

                return(Block(nodes));
            }

            return(Block());
        }
        private async Task <Document> MakeConstantAsync(Document document, LocalDeclarationStatementSyntax localDeclaration, CancellationToken cancellationToken)
        {
            var declaration = localDeclaration.Declaration;
            var typeName    = declaration.Type;

            if (typeName.IsVar)
            {
                var semanticModel = await document.GetSemanticModelAsync(cancellationToken);

                var aliasInfo = semanticModel.GetAliasInfo(typeName);
                if (aliasInfo == null)
                {
                    var type = semanticModel.GetTypeInfo(typeName).ConvertedType;
                    if (type.Name != "var")
                    {
                        var newtypeName = SyntaxFactory.ParseTypeName(type.ToDisplayString());
                        declaration = declaration.WithType(newtypeName);
                    }
                }
            }

            var @const = SyntaxFactory.Token(SyntaxKind.ConstKeyword)
                         .WithLeadingTrivia(localDeclaration.GetLeadingTrivia());

            var modifiers = localDeclaration.Modifiers.Insert(0, @const);

            var newLocalDeclaration = localDeclaration
                                      .WithModifiers(modifiers)
                                      .WithDeclaration(declaration.WithoutLeadingTrivia())
                                      .WithTrailingTrivia(localDeclaration.GetTrailingTrivia())
                                      .WithAdditionalAnnotations(Formatter.Annotation);

            var root = await document.GetSyntaxRootAsync(cancellationToken);

            var newRoot = root.ReplaceNode(localDeclaration, newLocalDeclaration);

            return(document.WithSyntaxRoot(newRoot));
        }
        private static Task <Document> RefactorAsync(
            Document document,
            SingleLocalDeclarationStatementInfo localInfo,
            TypeSyntax type,
            CancellationToken cancellationToken)
        {
            LocalDeclarationStatementSyntax localStatement = localInfo.Statement;

            StatementsInfo statementsInfo = SyntaxInfo.StatementsInfo(localStatement);

            int index = statementsInfo.IndexOf(localStatement);

            VariableDeclaratorSyntax declarator = localInfo.Declarator;

            VariableDeclaratorSyntax newDeclarator = declarator.WithInitializer(null);

            VariableDeclarationSyntax newDeclaration = localInfo.Declaration.ReplaceNode(declarator, newDeclarator);

            if (type != null)
            {
                newDeclaration = newDeclaration.WithType(type.WithTriviaFrom(newDeclaration.Type));
            }

            LocalDeclarationStatementSyntax newLocalStatement = localStatement
                                                                .WithDeclaration(newDeclaration)
                                                                .WithTrailingTrivia(NewLine())
                                                                .WithFormatterAnnotation();

            ExpressionStatementSyntax assignmentStatement = SimpleAssignmentStatement(IdentifierName(localInfo.Identifier), localInfo.Initializer.Value)
                                                            .WithTrailingTrivia(localStatement.GetTrailingTrivia())
                                                            .WithFormatterAnnotation();

            StatementsInfo newStatementsInfo = statementsInfo
                                               .Insert(index + 1, assignmentStatement)
                                               .ReplaceAt(index, newLocalStatement);

            return(document.ReplaceStatementsAsync(statementsInfo, newStatementsInfo, cancellationToken));
        }