public async override Task RegisterCodeFixesAsync(CodeFixContext context) { var document = context.Document; var cancellationToken = context.CancellationToken; var span = context.Span; var diagnostics = context.Diagnostics; var model = await document.GetSemanticModelAsync(cancellationToken); var root = await document.GetSyntaxRootAsync(cancellationToken); var diagnostic = diagnostics.First(); var node = root.FindNode(context.Span) as IfStatementSyntax; if (node == null) { return; } int foundCasts; foreach (var fix in UseAsAndNullCheckCodeRefactoringProvider.ScanIfElse(model, document, root, node, node.Condition.SkipParens() as BinaryExpressionSyntax, out foundCasts)) { context.RegisterCodeFix(fix, diagnostic); } }
internal static bool CheckIfElse(SemanticModel ctx, SyntaxNode root, IfStatementSyntax ifElseStatement, out BinaryExpressionSyntax isExpression) { isExpression = null; var embeddedStatment = ifElseStatement.Statement; TypeInfo rr; ExpressionSyntax castToType; List <SyntaxNode> foundCasts; var innerCondition = ifElseStatement.Condition.SkipParens(); if (innerCondition != null && innerCondition.IsKind(SyntaxKind.LogicalNotExpression)) { var c2 = ((PrefixUnaryExpressionSyntax)innerCondition).Operand.SkipParens(); if (c2.IsKind(SyntaxKind.IsExpression)) { isExpression = c2 as BinaryExpressionSyntax; castToType = isExpression.Right; rr = ctx.GetTypeInfo(castToType); if (rr.Type == null || !rr.Type.IsReferenceType) { return(false); } SyntaxNode searchStmt = embeddedStatment; if (UseAsAndNullCheckCodeRefactoringProvider.IsControlFlowChangingStatement(searchStmt)) { searchStmt = ifElseStatement.Parent; foundCasts = searchStmt.DescendantNodesAndSelf(n => !UseAsAndNullCheckCodeRefactoringProvider.IsCast(ctx, n, rr.Type)).Where(arg => arg.SpanStart >= ifElseStatement.SpanStart && UseAsAndNullCheckCodeRefactoringProvider.IsCast(ctx, arg, rr.Type)).ToList(); foundCasts.AddRange(ifElseStatement.Condition.DescendantNodesAndSelf(n => !UseAsAndNullCheckCodeRefactoringProvider.IsCast(ctx, n, rr.Type)).Where(arg => arg.SpanStart > c2.Span.End && UseAsAndNullCheckCodeRefactoringProvider.IsCast(ctx, arg, rr.Type))); } else { foundCasts = new List <SyntaxNode>(); } return(foundCasts.Count > 0); } return(false); } isExpression = innerCondition as BinaryExpressionSyntax; if (isExpression == null) { return(false); } castToType = isExpression.Right; rr = ctx.GetTypeInfo(castToType); if (rr.Type == null || !rr.Type.IsReferenceType) { return(false); } foundCasts = embeddedStatment.DescendantNodesAndSelf(n => !UseAsAndNullCheckCodeRefactoringProvider.IsCast(ctx, n, rr.Type)).Where(arg => UseAsAndNullCheckCodeRefactoringProvider.IsCast(ctx, arg, rr.Type)).ToList(); foundCasts.AddRange(ifElseStatement.Condition.DescendantNodesAndSelf(n => !UseAsAndNullCheckCodeRefactoringProvider.IsCast(ctx, n, rr.Type)).Where(arg => arg.SpanStart > innerCondition.Span.End && UseAsAndNullCheckCodeRefactoringProvider.IsCast(ctx, arg, rr.Type))); return(foundCasts.Count > 0); }