private static Solution UpdateMainDocument(Document document, SyntaxNode root, MethodDeclarationSyntax method, IEnumerable<IGrouping<Document, ReferenceLocation>> documentGroups)
 {
     var mainDocGroup = documentGroups.FirstOrDefault(dg => dg.Key.Equals(document));
     SyntaxNode newRoot;
     if (mainDocGroup == null)
     {
         newRoot = root.ReplaceNode(method, method.AddModifiers(staticToken));
     }
     else
     {
         var diagnosticNodes = mainDocGroup.Select(referenceLocation => root.FindNode(referenceLocation.Location.SourceSpan)).ToList();
         newRoot = root.TrackNodes(diagnosticNodes.Union(new[] { method }));
         newRoot = newRoot.ReplaceNode(newRoot.GetCurrentNode(method), method.AddModifiers(staticToken));
         foreach (var diagnosticNode in diagnosticNodes)
         {
             var token = newRoot.FindToken(diagnosticNode.GetLocation().SourceSpan.Start);
             var tokenParent = token.Parent;
             if (token.Parent.IsKind(SyntaxKind.IdentifierName)) continue;
             var invocationExpression = newRoot.GetCurrentNode(diagnosticNode).FirstAncestorOrSelfOfType<InvocationExpressionSyntax>()?.Expression;
             if (invocationExpression == null || invocationExpression.IsKind(SyntaxKind.IdentifierName)) continue;
             var memberAccess = invocationExpression as MemberAccessExpressionSyntax;
             if (memberAccess == null) continue;
             var newMemberAccessParent = memberAccess.Parent.ReplaceNode(memberAccess, memberAccess.Name)
                 .WithAdditionalAnnotations(Formatter.Annotation);
             newRoot = newRoot.ReplaceNode(memberAccess.Parent, newMemberAccessParent);
         }
     }
     var newSolution = document.Project.Solution.WithDocumentSyntaxRoot(document.Id, newRoot);
     return newSolution;
 }
 private static SyntaxNode CreateNewLiteral(LiteralExpressionSyntax literal, SyntaxNode root)
 {
     SyntaxNode newRoot;
     if (literal.Token.ValueText != literal.Token.Text)
     {
         var newTokenText = literal.Token.ValueText;
         var newLiteral = literal.WithToken(SyntaxFactory.ParseToken(newTokenText));
         newRoot = root.ReplaceNode(literal, newLiteral);
     }
     else
     {
         var value = (dynamic)literal.Token.Value;
         if (literal.Parent != null && literal.Parent.IsKind(SyntaxKind.UnaryMinusExpression))
         {
             var newTokenText = (string)("0x" + (value * -1).ToString("X"));
             var newLiteral = literal.WithToken(SyntaxFactory.ParseToken(newTokenText))
                 .WithLeadingTrivia(literal.Parent.GetLeadingTrivia())
                 .WithTrailingTrivia(literal.Parent.GetTrailingTrivia());
             newRoot = root.ReplaceNode(literal.Parent, newLiteral);
         }
         else
         {
             var newTokenText = (string)("0x" + value.ToString("X"));
             var newLiteral = literal.WithToken(SyntaxFactory.ParseToken(newTokenText));
             newRoot = root.ReplaceNode(literal, newLiteral);
         }
     }
     return newRoot;
 }
        private Task<Solution> UseExpressionBodiedMemberAsync(Document document, SyntaxNode root, SyntaxNode statement)
        {
            var returnStatement = (ReturnStatementSyntax) statement;
            var expression = returnStatement.Expression;
            var arrowClause = SyntaxFactory.ArrowExpressionClause(expression);

            var property = statement.AncestorsAndSelf().OfType<PropertyDeclarationSyntax>().FirstOrDefault();
            if (property != null)
            {
                var newProperty = property.RemoveNode(property.AccessorList, SyntaxRemoveOptions.KeepNoTrivia)
                                          .WithExpressionBody(arrowClause)
                                          .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken));


                root = root.ReplaceNode(property, newProperty);
            }

            var method = statement.AncestorsAndSelf().OfType<MethodDeclarationSyntax>().FirstOrDefault();
            if (method != null)
            {
                root = root.ReplaceNode(method, method.RemoveNode(method.Body, SyntaxRemoveOptions.KeepNoTrivia)
                                                      .WithExpressionBody(arrowClause)
                                                      .WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)));
            }

            return Task.FromResult(document.WithSyntaxRoot(root).Project.Solution);
        }
        private static SyntaxNode CalculateNewRoot(SyntaxNode root, IfStatementSyntax ifStatement)
        {
            SyntaxNode newRoot;
            var isTrue = ifStatement.Condition.IsKind(SyntaxKind.TrueLiteralExpression);

            if (isTrue)
            {
                var block = ifStatement.Statement as BlockSyntax;
                newRoot = block == null
                    ? root.ReplaceNode(ifStatement, ifStatement.Statement)
                    : root.ReplaceNode(ifStatement, block.Statements);
            }
            else
            {
                if (ifStatement.Else == null)
                {
                    newRoot = root.RemoveNode(ifStatement, SyntaxRemoveOptions.KeepNoTrivia);
                }
                else
                {
                    var block = ifStatement.Else.Statement as BlockSyntax;
                    newRoot = block == null
                        ? root.ReplaceNode(ifStatement, ifStatement.Else.Statement)
                        : root.ReplaceNode(ifStatement, block.Statements);
                }
            }

            return newRoot.WithAdditionalAnnotations(Formatter.Annotation);
        }
 private static SyntaxNode ReplaceInvocation(InvocationExpressionSyntax invocation, ExpressionSyntax newInvocation, SyntaxNode root)
 {
     if (invocation.Parent.IsKind(SyntaxKind.LogicalNotExpression))
         return root.ReplaceNode(invocation.Parent, newInvocation);
     var negatedInvocation = SyntaxFactory.PrefixUnaryExpression(SyntaxKind.LogicalNotExpression, newInvocation);
     var newRoot = root.ReplaceNode(invocation, negatedInvocation);
     return newRoot;
 }
 private static SyntaxNode ReplaceInvocation(InvocationExpressionSyntax invocation, ExpressionSyntax newInvocation, SyntaxNode root)
 {
     ExpressionSyntax lastExpression = invocation;
     while (lastExpression.Parent is ExpressionSyntax)
         lastExpression = (ExpressionSyntax)lastExpression.Parent;
     var lastExpressionWithNewInvocation = lastExpression.ReplaceNode(invocation, newInvocation);
     if (lastExpression.IsKind(SyntaxKind.LogicalNotExpression))
         return root.ReplaceNode(lastExpression, ((PrefixUnaryExpressionSyntax)lastExpressionWithNewInvocation).Operand);
     var negatedLastExpression = SyntaxFactory.PrefixUnaryExpression(SyntaxKind.LogicalNotExpression, lastExpressionWithNewInvocation);
     var newRoot = root.ReplaceNode(lastExpression, negatedLastExpression);
     return newRoot;
 }
        private Task<Document> ConvertToInterpolatedString(Document document, SyntaxNode root, InvocationExpressionSyntax invocation, CancellationToken cancellationToken)
        {
            string previousString = null;
            var parts = new List<InterpolatedStringContentSyntax>(invocation.ArgumentList.Arguments.Count);
            for (int i = 0; i < invocation.ArgumentList.Arguments.Count; i++)
            {
                ArgumentSyntax argument = invocation.ArgumentList.Arguments[i];
                var literal = argument.Expression as LiteralExpressionSyntax;

                if (literal?.IsKind(SyntaxKind.StringLiteralExpression) ?? false)
                {
                    //strings needs to be collapsed, otherwise VS will insert additional whitespaces
                    previousString += literal.Token.Text.Substring(1, literal.Token.Text.Length - 2);
                }
                else
                {
                    if (previousString != null)
                    {
                        parts.Add(InterpolatedStringGenerator.TextPart(previousString));
                        previousString = null;
                    }
                    parts.Add(InterpolatedStringGenerator.ExpressionPart(argument.Expression.WithoutLeadingTrivia().WithoutTrailingTrivia()));
                }
            }
            if (previousString != null)
            {
                parts.Add(InterpolatedStringGenerator.TextPart(previousString));
            }

            SyntaxNode interpolated = InterpolatedStringGenerator.InterpolatedString(parts);

            root = root.ReplaceNode(invocation, interpolated);

            return Task.FromResult(document.WithSyntaxRoot(root));
        }
        protected sealed override async Task RegisterCodeFixesAsync(SyntaxNode root, CodeFixContext context)
        {
            var diagnostic = context.Diagnostics.First();
            var diagnosticSpan = diagnostic.Location.SourceSpan;
            var attribute = root.FindNode(diagnosticSpan, getInnermostNodeForTie: true) as AttributeSyntax;
            var attributeList = attribute?.Parent as AttributeListSyntax;
            if (attribute == null ||
                attributeList == null)
            {
                return;
            }

            var semanticModel = await context.Document.GetSemanticModelAsync().ConfigureAwait(false);
            var optionalAttribute = semanticModel?.Compilation?.GetTypeByMetadataName(
                KnownType.System_Runtime_InteropServices_OptionalAttribute.TypeName);
            if (optionalAttribute == null)
            {
                return;
            }

            context.RegisterCodeFix(
                CodeAction.Create(
                    Title,
                    c =>
                    {
                        var newRoot = root.ReplaceNode(
                            attributeList,
                            GetNewAttributeList(attributeList, optionalAttribute, semanticModel));
                        return Task.FromResult(context.Document.WithSyntaxRoot(newRoot));
                    }),
                context.Diagnostics);
        }
 private Task<Solution> MakePublicAsync(Document document, SyntaxNode root, MethodDeclarationSyntax method)
 {
     var generator = SyntaxGenerator.GetGenerator(document);
     var newMethod = generator.WithAccessibility(method, Accessibility.Public);
     var newRoot = root.ReplaceNode(method, newMethod);
     return Task.FromResult(document.WithSyntaxRoot(newRoot).Project.Solution);
 }
 private Task<Solution> RemoveRethrowAsync(Document document, SyntaxNode root, ThrowStatementSyntax throwStatement)
 {
     var newStatement = SyntaxFactory.ThrowStatement();
     var newRoot = root.ReplaceNode(throwStatement, newStatement);
     var newDocument = document.WithSyntaxRoot(newRoot);
     return Task.FromResult(newDocument.Project.Solution);
 }
        internal override Task<Document> GetUpdatedDocumentAsync(Document document, SemanticModel model, SyntaxNode root, SyntaxNode nodeToFix, string diagnosticId, CancellationToken cancellationToken)
        {
            //// We are going to implement IDisposable interface:
            ////
            ////        public void Dispose()
            ////        {
            ////            throw new NotImplementedException();
            ////        }

            var syntaxNode = nodeToFix as ClassDeclarationSyntax;
            if (syntaxNode == null)
            {
                return Task.FromResult(document);
            }

            var statement = CreateThrowNotImplementedStatement(model);
            if (statement == null)
            {
                return Task.FromResult(document);
            }

            var member = CreateSimpleMethodDeclaration(CA1001DiagnosticAnalyzer.Dispose, statement);
            var newNode =
                syntaxNode.BaseList != null ?
                    syntaxNode.AddBaseListTypes(SyntaxFactory.ParseTypeName(CA1001DiagnosticAnalyzer.IDisposable)).AddMembers(new[] { member }) :
                    syntaxNode.AddBaseListTypes(SyntaxFactory.ParseTypeName(CA1001DiagnosticAnalyzer.IDisposable)).AddMembers(new[] { member }).WithIdentifier(syntaxNode.Identifier.WithTrailingTrivia(SyntaxFactory.Space));
            newNode = newNode.WithAdditionalAnnotations(Formatter.Annotation, Simplifier.Annotation);
            return Task.FromResult(document.WithSyntaxRoot(root.ReplaceNode(nodeToFix, newNode)));
        }
        protected sealed override async Task RegisterCodeFixesAsync(SyntaxNode root, CodeFixContext context)
        {
            var diagnostic = context.Diagnostics.First();
            var diagnosticSpan = diagnostic.Location.SourceSpan;
            var prefix = root.FindNode(diagnosticSpan, getInnermostNodeForTie: true) as PrefixUnaryExpressionSyntax;

            if (prefix == null)
            {
                return;
            }

            context.RegisterCodeFix(
                CodeAction.Create(
                    Title,
                    c =>
                    {
                        ExpressionSyntax expression;
                        uint count;
                        GetExpression(prefix, out expression, out count);

                        if (count%2 == 1)
                        {
                            expression = SyntaxFactory.PrefixUnaryExpression(
                                prefix.Kind(),
                                expression);
                        }

                        var newRoot = root.ReplaceNode(prefix, expression
                            .WithAdditionalAnnotations(Formatter.Annotation));
                        return Task.FromResult(context.Document.WithSyntaxRoot(newRoot));
                    }),
                context.Diagnostics);
        }
        static Document PerformAction(Document document, SyntaxNode root, InvocationExpressionSyntax invocationNode)
        {
            var arg = invocationNode.ArgumentList.Arguments.Select(a => a.Expression).First();
            if (!arg.DescendantNodesAndSelf().OfType<BinaryExpressionSyntax>().All(bop => bop.IsKind(SyntaxKind.BitwiseOrExpression)))
                return document;

            arg = ConvertBitwiseFlagComparisonToHasFlagsCodeRefactoringProvider.MakeFlatExpression(arg, SyntaxKind.BitwiseAndExpression);
            if (arg is BinaryExpressionSyntax)
                arg = SyntaxFactory.ParenthesizedExpression(arg);

            SyntaxNode nodeToReplace = invocationNode;
            while (nodeToReplace.Parent is ParenthesizedExpressionSyntax)
                nodeToReplace = nodeToReplace.Parent;

            bool negateHasFlags = nodeToReplace.Parent != null && nodeToReplace.Parent.IsKind(SyntaxKind.LogicalNotExpression);
            if (negateHasFlags)
                nodeToReplace = nodeToReplace.Parent;

            var expr = SyntaxFactory.BinaryExpression(
                negateHasFlags ? SyntaxKind.EqualsExpression : SyntaxKind.NotEqualsExpression,
                SyntaxFactory.ParenthesizedExpression(SyntaxFactory.BinaryExpression(SyntaxKind.BitwiseAndExpression, ((MemberAccessExpressionSyntax)invocationNode.Expression).Expression, arg))
                .WithAdditionalAnnotations(Formatter.Annotation),
                SyntaxFactory.ParseExpression("0")
            );

            var newRoot = root.ReplaceNode((SyntaxNode)
                nodeToReplace,
                expr.WithAdditionalAnnotations(Formatter.Annotation)
            );
            return document.WithSyntaxRoot(newRoot);
        }
        protected sealed override async Task RegisterCodeFixesAsync(SyntaxNode root, CodeFixContext context)
        {
            var diagnostic = context.Diagnostics.First();
            var diagnosticSpan = diagnostic.Location.SourceSpan;
            var literal = root.FindNode(diagnosticSpan, getInnermostNodeForTie: true) as LiteralExpressionSyntax;
            if (literal == null)
            {
                return;
            }

            var newLiteral = SyntaxFactory.Literal(
                literal.Token.Text.ToUpperInvariant(),
                (long)literal.Token.Value);

            if (!newLiteral.IsKind(SyntaxKind.None))
            {
                context.RegisterCodeFix(
                    CodeAction.Create(
                        Title,
                        c =>
                        {
                            var newRoot = root.ReplaceNode(literal,
                                literal.WithToken(newLiteral).WithTriviaFrom(literal));
                            return Task.FromResult(context.Document.WithSyntaxRoot(newRoot));
                        }),
                    context.Diagnostics);
            }
        }
        protected sealed override async Task RegisterCodeFixesAsync(SyntaxNode root, CodeFixContext context)
        {
            var diagnostic = context.Diagnostics.First();
            var diagnosticSpan = diagnostic.Location.SourceSpan;
            var syntaxNode = root.FindNode(diagnosticSpan, getInnermostNodeForTie: true) as PrefixUnaryExpressionSyntax;

            if (syntaxNode == null)
            {
                return;
            }

            context.RegisterCodeFix(
                CodeAction.Create(
                    Title,
                    c =>
                    {
                        var expression = syntaxNode.Operand.RemoveParentheses();
                        var newBinary = ChangeOperator((BinaryExpressionSyntax)expression);

                        if (syntaxNode.Parent is ExpressionSyntax &&
                            !ExpressionTypesWithNoParens.Any(type => type.IsInstanceOfType(syntaxNode.Parent)))
                        {
                            newBinary = SyntaxFactory.ParenthesizedExpression(newBinary);
                        }

                        var newRoot = root.ReplaceNode(
                            syntaxNode,
                            newBinary.WithAdditionalAnnotations(Formatter.Annotation));

                        return Task.FromResult(context.Document.WithSyntaxRoot(newRoot));
                    }),
                context.Diagnostics);
        }
        private static async Task<Document> RemoveEmptyStatementAsync(Document document, SyntaxNode root, EmptyStatementSyntax node, CancellationToken cancellationToken)
        {
            SyntaxNode newRoot;

            switch (node.Parent.Kind())
            {
            case SyntaxKind.Block:
            case SyntaxKind.SwitchSection:
                // empty statements in a block or switch section can be removed
                return await RemoveSemicolonTextAsync(document, node.SemicolonToken, cancellationToken).ConfigureAwait(false);

            case SyntaxKind.IfStatement:
            case SyntaxKind.ElseClause:
            case SyntaxKind.ForStatement:
            case SyntaxKind.WhileStatement:
            case SyntaxKind.DoStatement:
                // these cases are always replaced with an empty block
                newRoot = root.ReplaceNode(node, SyntaxFactory.Block().WithTriviaFrom(node));
                return document.WithSyntaxRoot(newRoot);

            case SyntaxKind.LabeledStatement:
                // handle this case as a text manipulation for simplicity
                return await RemoveSemicolonTextAsync(document, node.SemicolonToken, cancellationToken).ConfigureAwait(false);

            default:
                return document;
            }
        }
        protected IEnumerable<CodeAction> GetActions(Document document, SemanticModel semanticModel, SyntaxNode root, TextSpan span, ParameterSyntax node)
        {
            if (!node.Identifier.Span.Contains(span))
                yield break;

            var parameter = node;
            var bodyStatement = parameter.Parent.Parent.ChildNodes().OfType<BlockSyntax>().FirstOrDefault();
            if (bodyStatement == null)
                yield break;

            var parameterSymbol = semanticModel.GetDeclaredSymbol(node);
            var type = parameterSymbol.Type;
            if (type == null || type.IsValueType || HasNotNullContract(semanticModel, parameterSymbol, bodyStatement))
                yield break;

            yield return CreateAction(
                node.Identifier.Span
                , t2 => {
                    var newBody = bodyStatement.WithStatements(SyntaxFactory.List<StatementSyntax>(new[] { CreateContractRequiresCall(node.Identifier.ToString()) }.Concat(bodyStatement.Statements)));

                    var newRoot = (CompilationUnitSyntax)root.ReplaceNode((SyntaxNode)bodyStatement, newBody);

                    if (UsingStatementNotPresent(newRoot)) newRoot = AddUsingStatement(node, newRoot);

                    return Task.FromResult(document.WithSyntaxRoot(newRoot));
                }
                , "Add contract requiring parameter must not be null"
            );
        }
        public static SyntaxNode IntroduceFieldFromConstructor(SyntaxNode root, ConstructorDeclarationSyntax constructorStatement, ParameterSyntax parameter)
        {
            var oldClass = constructorStatement.FirstAncestorOrSelf<ClassDeclarationSyntax>();
            var newClass = oldClass;
            var fieldName = parameter.Identifier.ValueText;
            var fieldType = parameter.Type;
            var members = ExtractMembersFromClass(oldClass.Members);

            var addMember = false;
            if (!members.Any(p => p.Key == fieldName && p.Value == fieldType.ToString()))
            {
                var identifierPostFix = 0;
                while (members.Any(p => p.Key == fieldName))
                    fieldName = parameter.Identifier.ValueText + ++identifierPostFix;

                addMember = true;
            }

            var assignmentField = SyntaxFactory.ExpressionStatement(SyntaxFactory.AssignmentExpression(SyntaxKind.SimpleAssignmentExpression,
                                               SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.ThisExpression(),
                                               SyntaxFactory.IdentifierName(fieldName)), SyntaxFactory.IdentifierName(parameter.Identifier.ValueText)));
            var newConstructor = constructorStatement.WithBody(constructorStatement.Body.AddStatements(assignmentField));
            newClass = newClass.ReplaceNode(constructorStatement, newConstructor);

            if (addMember)
            {
                var newField = SyntaxFactory.FieldDeclaration(SyntaxFactory.VariableDeclaration(parameter.Type)
                                    .WithVariables(SyntaxFactory.SingletonSeparatedList(SyntaxFactory.VariableDeclarator(SyntaxFactory.Identifier(fieldName)))))
                                    .WithModifiers(SyntaxFactory.TokenList(new[] { SyntaxFactory.Token(SyntaxKind.PrivateKeyword), SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword) }))
                                    .WithAdditionalAnnotations(Formatter.Annotation);
                newClass = newClass.WithMembers(newClass.Members.Insert(0, newField)).WithoutAnnotations(Formatter.Annotation);
            }
            var newRoot = root.ReplaceNode(oldClass, newClass);
            return newRoot;
        }
        protected sealed override async Task RegisterCodeFixesAsync(SyntaxNode root, CodeFixContext context)
        {
            var diagnostic = context.Diagnostics.First();
            var diagnosticSpan = diagnostic.Location.SourceSpan;
            var syntaxNode = root.FindNode(diagnosticSpan);

            var variableDeclarator = syntaxNode.FirstAncestorOrSelf<VariableDeclaratorSyntax>();
            var variableDeclaration = variableDeclarator?.Parent as VariableDeclarationSyntax;
            if (variableDeclaration == null)
            {
                return;
            }

            if (variableDeclaration.Variables.Count == 1)
            {
                var fieldDeclaration = variableDeclaration.Parent as FieldDeclarationSyntax;
                if (fieldDeclaration == null)
                {
                    return;
                }

                context.RegisterCodeFix(
                    CodeAction.Create(
                        Title,
                        c =>
                        {
                            var newFieldDeclaration = fieldDeclaration.AddModifiers(
                                SyntaxFactory.Token(SyntaxKind.ReadOnlyKeyword));
                            var newRoot = root.ReplaceNode(fieldDeclaration, newFieldDeclaration);
                            return Task.FromResult(context.Document.WithSyntaxRoot(newRoot));
                        }),
                    context.Diagnostics);
            }
        }
        protected sealed override async Task RegisterCodeFixesAsync(SyntaxNode root, CodeFixContext context)
        {
            var diagnostic = context.Diagnostics.First();
            var diagnosticSpan = diagnostic.Location.SourceSpan;
            var paramsToken = root.FindToken(diagnosticSpan.Start);

            if (!paramsToken.IsKind(SyntaxKind.ParamsKeyword))
            {
                return;
            }

            context.RegisterCodeFix(
                CodeAction.Create(
                    Title,
                    c =>
                    {
                        var node = paramsToken.Parent;
                        var newNode = node.ReplaceToken(
                            paramsToken,
                            SyntaxFactory.Token(SyntaxKind.None));

                        newNode = newNode.WithTriviaFrom(node);

                        var newRoot = root.ReplaceNode(node, newNode);
                        return Task.FromResult(context.Document.WithSyntaxRoot(newRoot));
                    }),
                context.Diagnostics);
        }
 public async static Task<Solution> MakeAutoPropertyAsync(Document document, SyntaxNode root, PropertyDeclarationSyntax property, CancellationToken cancellationToken)
 {
     var semanticModel = await document.GetSemanticModelAsync(cancellationToken);
     var getterReturn = (ReturnStatementSyntax)property.AccessorList.Accessors.First(a => a.Keyword.ValueText == "get").Body.Statements.First();
     var returnIdentifier = (IdentifierNameSyntax)(getterReturn.Expression is MemberAccessExpressionSyntax ? ((MemberAccessExpressionSyntax)getterReturn.Expression).Name : getterReturn.Expression);
     var returnIdentifierSymbol = semanticModel.GetSymbolInfo(returnIdentifier).Symbol;
     var variableDeclarator = (VariableDeclaratorSyntax)returnIdentifierSymbol.DeclaringSyntaxReferences.First().GetSyntax();
     var fieldDeclaration = variableDeclarator.FirstAncestorOfType<FieldDeclarationSyntax>();
     root = root.TrackNodes(returnIdentifier, fieldDeclaration, property);
     document = document.WithSyntaxRoot(root);
     root = await document.GetSyntaxRootAsync(cancellationToken);
     semanticModel = await document.GetSemanticModelAsync(cancellationToken);
     returnIdentifier = root.GetCurrentNode(returnIdentifier);
     returnIdentifierSymbol = semanticModel.GetSymbolInfo(returnIdentifier).Symbol;
     var newProperty = GetSimpleProperty(property, variableDeclarator)
         .WithTriviaFrom(property)
         .WithAdditionalAnnotations(Formatter.Annotation);
     var newSolution = await Renamer.RenameSymbolAsync(document.Project.Solution, returnIdentifierSymbol, property.Identifier.ValueText, document.Project.Solution.Workspace.Options, cancellationToken);
     document = newSolution.GetDocument(document.Id);
     root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
     root = root.InsertNodesAfter(root.GetCurrentNode(property), new[] { newProperty });
     var multipleVariableDeclaration = fieldDeclaration.Declaration.Variables.Count > 1;
     if (multipleVariableDeclaration)
     {
         var newfieldDeclaration = fieldDeclaration.WithDeclaration(fieldDeclaration.Declaration.RemoveNode(variableDeclarator, SyntaxRemoveOptions.KeepNoTrivia));
         root = root.RemoveNode(root.GetCurrentNode<SyntaxNode>(property), SyntaxRemoveOptions.KeepNoTrivia);
         root = root.ReplaceNode(root.GetCurrentNode(fieldDeclaration), newfieldDeclaration);
     }
     else
     {
         root = root.RemoveNodes(root.GetCurrentNodes<SyntaxNode>(new SyntaxNode[] { fieldDeclaration, property }), SyntaxRemoveOptions.KeepNoTrivia);
     }
     document = document.WithSyntaxRoot(root);
     return document.Project.Solution;
 }
    private static void AddCodeFixWithNewPublicConstructor(CodeFixContext context, SyntaxNode root,
      Diagnostic diagnostic, ClassDeclarationSyntax classNode)
    {
      // Generated from http://roslynquoter.azurewebsites.net/
      var constructor = SyntaxFactory.ConstructorDeclaration(classNode.Identifier)
        .WithModifiers(
          SyntaxFactory.TokenList(
            SyntaxFactory.Token(SyntaxKind.PublicKeyword)))
        .WithParameterList(SyntaxFactory.ParameterList()
          .WithOpenParenToken(
            SyntaxFactory.Token(SyntaxKind.OpenParenToken))
          .WithCloseParenToken(
            SyntaxFactory.Token(
              SyntaxKind.CloseParenToken)))
        .WithBody(SyntaxFactory.Block()
          .WithOpenBraceToken(
            SyntaxFactory.Token(
              SyntaxKind.OpenBraceToken))
          .WithCloseBraceToken(
            SyntaxFactory.Token(
              SyntaxKind.CloseBraceToken))).NormalizeWhitespace().WithAdditionalAnnotations(Formatter.Annotation);
      var newClassNode = classNode.AddMembers(constructor);
      var newRoot = root.ReplaceNode(classNode, newClassNode);

      context.RegisterCodeFix(
        CodeAction.Create(
          CheckConstructorsAnalyzerPublicConstructorCodeFixConstants.AddPublicConstructorDescription,
          _ => Task.FromResult(context.Document.WithSyntaxRoot(newRoot)),
          CheckConstructorsAnalyzerPublicConstructorCodeFixConstants.AddPublicConstructorDescription), diagnostic);
    }
        protected sealed override async Task RegisterCodeFixesAsync(SyntaxNode root, CodeFixContext context)
        {
            var diagnostic = context.Diagnostics.First();
            var diagnosticSpan = diagnostic.Location.SourceSpan;
            var nameEquals = root.FindNode(diagnosticSpan) as NameEqualsSyntax;
            var anonymousObjectCreation = nameEquals?.Parent?.Parent as AnonymousObjectCreationExpressionSyntax;
            if (anonymousObjectCreation == null)
            {
                return;
            }

            context.RegisterCodeFix(
                CodeAction.Create(
                    Title,
                    c =>
                    {
                        var newInitializersWithSeparators = anonymousObjectCreation.Initializers.GetWithSeparators()
                            .Select(item => GetNewSyntaxListItem(item));
                        var newAnonymousObjectCreation = anonymousObjectCreation
                            .WithInitializers(SyntaxFactory.SeparatedList<AnonymousObjectMemberDeclaratorSyntax>(newInitializersWithSeparators))
                            .WithTriviaFrom(anonymousObjectCreation);

                        var newRoot = root.ReplaceNode(
                            anonymousObjectCreation,
                            newAnonymousObjectCreation);
                        return Task.FromResult(context.Document.WithSyntaxRoot(newRoot));
                    }),
                context.Diagnostics);
        }
        private Task<Solution> SimplifyExpressionAsync(Document document, SyntaxNode root, SyntaxNode statement)
        {
            var trueLiteralExpression = (LiteralExpressionSyntax) statement;
            var binaryExpression = (BinaryExpressionSyntax) trueLiteralExpression.Parent;
            SyntaxNode newRoot;
            if (binaryExpression.Left == trueLiteralExpression)
            {
                newRoot = root.ReplaceNode(binaryExpression, binaryExpression.Right).WithAdditionalAnnotations(Formatter.Annotation);
            }
            else
            {
                newRoot = root.ReplaceNode(binaryExpression, binaryExpression.Left).WithAdditionalAnnotations(Formatter.Annotation);
            }

            var newDocument = document.WithSyntaxRoot(newRoot);
            return Task.FromResult(newDocument.Project.Solution);
        }
 private static SyntaxNode AddAttribute(SyntaxNode root, ClassDeclarationSyntax classNode,
   string name)
 {
   var attribute = SyntaxFactory.Attribute(SyntaxFactory.ParseName(name));
   var attributeList = SyntaxFactory.AttributeList(SyntaxFactory.SeparatedList<AttributeSyntax>().Add(attribute));
   var newClassNode = classNode.AddAttributeLists(attributeList);
   return root.ReplaceNode(classNode, newClassNode);
 }
        private Task<Solution> RemoveConditionalAsync(Document document, SyntaxNode root, SyntaxNode statement)
        {
            var conditionalExpression = (ConditionalExpressionSyntax) statement;

            var newRoot = root.ReplaceNode(conditionalExpression, conditionalExpression.Condition).WithAdditionalAnnotations(Formatter.Annotation);
            var newDocument = document.WithSyntaxRoot(newRoot);
            return Task.FromResult(newDocument.Project.Solution);
        }
        private static Task<Document> AddJustificationToAttributeAsync(Document document, SyntaxNode syntaxRoot, AttributeSyntax attribute)
        {
            var attributeName = SyntaxFactory.IdentifierName(nameof(SuppressMessageAttribute.Justification));
            var newArgument = SyntaxFactory.AttributeArgument(SyntaxFactory.NameEquals(attributeName), null, GetNewAttributeValue());

            var newArgumentList = attribute.ArgumentList.AddArguments(newArgument);
            return Task.FromResult(document.WithSyntaxRoot(syntaxRoot.ReplaceNode(attribute.ArgumentList, newArgumentList)));
        }
 internal static SyntaxNode ComputeExpression(SyntaxNode nodeToReplace, BinaryExpressionSyntax expression, SyntaxNode root, SemanticModel semanticModel)
 {
     var result = semanticModel.GetConstantValue(expression);
     if (!result.HasValue) return null;
     var newExpression = SyntaxFactory.ParseExpression(System.Convert.ToString(result.Value, System.Globalization.CultureInfo.InvariantCulture));
     var newRoot = root.ReplaceNode(nodeToReplace, newExpression);
     return newRoot;
 }
 protected override async Task<Document> FixEquals(Document document, SyntaxGenerator generator, SyntaxNode root, SyntaxNode node, CancellationToken cancellationToken)
 {
     SemanticModel model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
     var binaryExpression = (BinaryExpressionSyntax)node;
     SyntaxNode invocation = CreateEqualsExpression(generator, model, binaryExpression.Left, binaryExpression.Right, node.Kind() == SyntaxKind.EqualsExpression).WithAdditionalAnnotations(Formatter.Annotation);
     SyntaxNode newRoot = root.ReplaceNode(node, invocation);
     return document.WithSyntaxRoot(newRoot);
 }
        static Document PerformAction(Document document, SyntaxNode root, BinaryExpressionSyntax bop)
        {
            var nodeToReplace = bop.IsParentKind(SyntaxKind.ParenthesizedExpression) ? bop.Parent : bop;
            var castExpr = (ExpressionSyntax)SyntaxFactory.CastExpression(bop.Right as TypeSyntax, CSharpUtil.AddParensIfRequired(bop.Left.WithoutLeadingTrivia().WithoutTrailingTrivia())).WithLeadingTrivia(bop.GetLeadingTrivia()).WithTrailingTrivia(bop.GetTrailingTrivia());

            var newRoot = root.ReplaceNode((SyntaxNode)nodeToReplace, castExpr);
            return document.WithSyntaxRoot(newRoot);
        }