Ejemplo n.º 1
0
        private void AnalyzeNode(SyntaxNodeAnalysisContext context)
        {
            var ifStatement = (IfStatementSyntax)context.Node;

            bool?expressionValue = IfResultAnalyzer.GetResult(ifStatement.Condition);

            if (expressionValue.HasValue)
            {
                var diagnostic = Diagnostic.Create(Rule, ifStatement.Condition.GetLocation(), expressionValue.Value);
                context.ReportDiagnostic(diagnostic);
            }
        }
Ejemplo n.º 2
0
        private async Task <Document> FixIfStatement(Document document,
                                                     IfStatementSyntax ifExpr,
                                                     CancellationToken cancellationToken)
        {
            var semanticModel =
                await document.GetSemanticModelAsync(cancellationToken);

            var ifResult = IfResultAnalyzer.GetResult(ifExpr.Condition);

            if (!ifResult.HasValue)
            {
                return(document);
            }

            StatementSyntax ifContent;

            if (ifResult.Value)
            {
                ifContent = ifExpr.Statement;//.RemoveNode();
            }
            else if (ifExpr.Else != null)
            {
                ifContent = ifExpr.Else.Statement;
            }
            else
            {
                ifContent = null;
            }

            var root = await document.GetSyntaxRootAsync();

            SyntaxNode newRoot = null;

            if (ifContent != null)
            {
                List <StatementSyntax> statements;
                var blockStatementSyntax = ifContent as BlockSyntax;
                if (blockStatementSyntax != null)
                {
                    statements = blockStatementSyntax.Statements.Select(stmn => stmn.WithoutLeadingTrivia()).ToList();
                }
                else
                {
                    statements = new List <StatementSyntax> {
                        ifContent.WithoutLeadingTrivia()
                    };
                }

                var list = SyntaxFactory.List(statements);

                newRoot = root.ReplaceNode(ifExpr, list);
            }
            else
            {
                newRoot = root.RemoveNode(ifExpr, SyntaxRemoveOptions.KeepEndOfLine);
            }

            var newDocument = document.WithSyntaxRoot(newRoot);

            return(newDocument);
        }