-
Notifications
You must be signed in to change notification settings - Fork 26
Add null-ckeck analyzer and code fix #43
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
s-arash
wants to merge
3
commits into
DustinCampbell:master
Choose a base branch
from
s-arash:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 2 commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
54 changes: 54 additions & 0 deletions
54
...arpEssentials.Tests/NullCheckToNullConditional/NullCheckToNullConditionalAnalyzerTests.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
using RoslynNUnitLight; | ||
using System; | ||
using System.Collections.Generic; | ||
using System.Linq; | ||
using System.Text; | ||
using System.Threading.Tasks; | ||
using Microsoft.CodeAnalysis.Diagnostics; | ||
using Microsoft.CodeAnalysis; | ||
using CSharpEssentials.NullCheckToNullConditional; | ||
using NUnit.Framework; | ||
|
||
namespace CSharpEssentials.Tests.NullCheckToNullConditional | ||
{ | ||
class NullCheckToNullConditionalAnalyzerTests : AnalyzerTestFixture | ||
{ | ||
protected override string LanguageName => LanguageNames.CSharp; | ||
|
||
protected override DiagnosticAnalyzer CreateAnalyzer() => new NullCheckToNullConditionalAnalyzer(); | ||
|
||
[Test] | ||
public void TestNoFixOnComipleError() | ||
{ | ||
const string markup = @" | ||
class C | ||
{ | ||
void M(object o) | ||
{ | ||
if(o.GetType != null){ | ||
o.GetType.ToString() | ||
} | ||
} | ||
} | ||
"; | ||
NoDiagnostic(markup, DiagnosticIds.UseNullConditional); | ||
} | ||
|
||
[Test] | ||
public void TestNoFixOnNoneInvocationBody() | ||
{ | ||
const string markup = @" | ||
class C | ||
{ | ||
object M(object o) | ||
{ | ||
if(o != null){ | ||
return o; | ||
} | ||
} | ||
} | ||
"; | ||
NoDiagnostic(markup, DiagnosticIds.UseNullConditional); | ||
} | ||
} | ||
} |
105 changes: 105 additions & 0 deletions
105
...harpEssentials.Tests/NullCheckToNullConditional/NullCheckToNullConditionalCodeFixTests.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,105 @@ | ||
using RoslynNUnitLight; | ||
using System; | ||
using System.Collections.Generic; | ||
using System.Linq; | ||
using System.Text; | ||
using System.Threading.Tasks; | ||
using Microsoft.CodeAnalysis.CodeRefactorings; | ||
using Microsoft.CodeAnalysis; | ||
using CSharpEssentials.NullCheckToNullConditional; | ||
using NUnit.Framework; | ||
using Microsoft.CodeAnalysis.CodeFixes; | ||
using Microsoft.CodeAnalysis.Text; | ||
using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
|
||
namespace CSharpEssentials.Tests.NullCheckToNullConditional | ||
{ | ||
class NullCheckToNullConditionalCodeFixTests : CodeFixTestFixture | ||
{ | ||
protected override string LanguageName => LanguageNames.CSharp; | ||
protected override CodeFixProvider CreateProvider() => new NullCheckToNullConditionalCodeFix(); | ||
|
||
const string codeBase = @" | ||
class SuperAwesomeCode | ||
{ | ||
interface A { B b(); } | ||
interface B { C c { get; } } | ||
interface C { DHolder this[int i] { get; } } | ||
interface DHolder { D d { get; } } | ||
interface D { void m(object o1, object o2); MyStruct? myStruct{ get; } } | ||
struct MyStruct { int this[int i] => i; } | ||
void M(A a, B b, C c, DHolder dHolder, D d, object blah, dynamic dyn) | ||
{ | ||
<<<<<code>>>>> | ||
} | ||
} | ||
"; | ||
string InsertCode(string s) => codeBase.Replace("<<<<<code>>>>>", s); | ||
|
||
[Test] | ||
public void SimpleTest() | ||
{ | ||
var markupCode = InsertCode("[|if (null != d ) d.m(blah, blah);|]"); | ||
var expected = InsertCode("d?.m(blah, blah);"); | ||
TestCodeFix(markupCode, expected, DiagnosticDescriptors.UseNullConditionalMemberAccess); | ||
} | ||
|
||
[Test] | ||
public void TestPropertyAccessor() | ||
{ | ||
var markupCode = InsertCode("[|if (b != null) b.c.ToString();|]"); | ||
var expected = InsertCode("b?.c.ToString();"); | ||
TestCodeFix(markupCode, expected, DiagnosticDescriptors.UseNullConditionalMemberAccess); | ||
} | ||
|
||
[Test] | ||
public void TestIndexer() | ||
{ | ||
var markupCode = InsertCode("[|if (b.c != null) b.c[0].ToString();|]"); | ||
var expected = InsertCode("b.c?[0].ToString();"); | ||
TestCodeFix(markupCode, expected, DiagnosticDescriptors.UseNullConditionalMemberAccess); | ||
} | ||
|
||
[Test] | ||
public void TestNullableValueType() | ||
{ | ||
var markupCode = InsertCode("[|if (d.myStruct != null) d.myStruct.Value[0].CompareTo(42).ToString();|]"); | ||
var expected = InsertCode("d.myStruct?[0].CompareTo(42).ToString();"); | ||
TestCodeFix(markupCode, expected, DiagnosticDescriptors.UseNullConditionalMemberAccess); | ||
} | ||
|
||
[Test] | ||
public void TestDynamicExpression() | ||
{ | ||
var markupCode = InsertCode("[|if (dyn.x.y.z != null) dyn.x.y.z.m();|]"); | ||
var expected = InsertCode("dyn.x.y.z?.m();"); | ||
TestCodeFix(markupCode, expected, DiagnosticDescriptors.UseNullConditionalMemberAccess); | ||
} | ||
|
||
[Test] | ||
public void TestBlockStatement() | ||
{ | ||
var markupCode = InsertCode("[|if (a.b() != null) { a.b().c[0].ToString(); }|]"); | ||
var expected = InsertCode("a.b()?.c[0].ToString();"); | ||
TestCodeFix(markupCode, expected, DiagnosticDescriptors.UseNullConditionalMemberAccess); | ||
} | ||
|
||
[Test] | ||
public void TestInvocationStartsWith() | ||
{ | ||
var code = InsertCode("[|if (a != null) a.b().c[1].d.m(blah, blah);|]"); | ||
var expeced = InsertCode("a?.b().c[1].d.m(blah, blah);"); | ||
|
||
Document doc; | ||
TextSpan span; | ||
TestHelpers.TryGetDocumentAndSpanFromMarkup(code, LanguageNames.CSharp, out doc, out span); | ||
var root = doc.GetSyntaxRootAsync().Result; | ||
var ifStatement = root.FindNode(span) as IfStatementSyntax; | ||
var exp = (ifStatement.Condition as BinaryExpressionSyntax).Left; | ||
var chain = (ifStatement.Statement as ExpressionStatementSyntax).Expression; | ||
ExpressionSyntax _; | ||
Assert.True(NullCheckToNullConditionalCodeFix.MemberAccessChainExpressionStartsWith(chain, exp, out _)); | ||
|
||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
59 changes: 59 additions & 0 deletions
59
Source/CSharpEssentials/NullCheckToNullConditional/NullCheckToNullConditionalAnalyzer.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,59 @@ | ||
using System; | ||
using System.Threading; | ||
using System.Threading.Tasks; | ||
using Microsoft.CodeAnalysis; | ||
using Microsoft.CodeAnalysis.CodeActions; | ||
using Microsoft.CodeAnalysis.CodeRefactorings; | ||
using Microsoft.CodeAnalysis.CSharp; | ||
using Microsoft.CodeAnalysis.CSharp.Syntax; | ||
using Microsoft.CodeAnalysis.Formatting; | ||
using System.Collections.Immutable; | ||
using Microsoft.CodeAnalysis.Simplification; | ||
using Microsoft.CodeAnalysis.Diagnostics; | ||
using Microsoft.CodeAnalysis.Text; | ||
|
||
namespace CSharpEssentials.NullCheckToNullConditional | ||
{ | ||
[DiagnosticAnalyzer(LanguageNames.CSharp)] | ||
public class NullCheckToNullConditionalAnalyzer : DiagnosticAnalyzer | ||
{ | ||
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics => ImmutableArray.Create(DiagnosticDescriptors.UseNullConditionalMemberAccessFadedToken, DiagnosticDescriptors.UseNullConditionalMemberAccess); | ||
|
||
private static async void AnalyzeThat(SyntaxNodeAnalysisContext context) | ||
{ | ||
var ifStatement = context.Node.FindNode(context.Node.Span, getInnermostNodeForTie: true)?.FirstAncestorOrSelf<IfStatementSyntax>(); | ||
try | ||
{ | ||
if (await NullCheckToNullConditionalCodeFix.GetCodeFixAsync(() => Task.FromResult(context.SemanticModel), ifStatement) != null) | ||
{ | ||
if (ifStatement.SyntaxTree.IsGeneratedCode(context.CancellationToken)) | ||
return; | ||
var fadeoutLocations = ImmutableArray.CreateBuilder<Location>(); | ||
fadeoutLocations.Add(Location.Create(context.Node.SyntaxTree, TextSpan.FromBounds(ifStatement.IfKeyword.SpanStart, ifStatement.Statement.SpanStart))); | ||
|
||
var statementBlock = ifStatement.Statement as BlockSyntax; | ||
if (statementBlock != null) | ||
{ | ||
fadeoutLocations.Add(Location.Create(context.Node.SyntaxTree, (statementBlock.OpenBraceToken.Span))); | ||
fadeoutLocations.Add(Location.Create(context.Node.SyntaxTree, (statementBlock.CloseBraceToken.Span))); | ||
} | ||
foreach (var location in fadeoutLocations) | ||
{ | ||
context.ReportDiagnostic(Diagnostic.Create(DiagnosticDescriptors.UseNullConditionalMemberAccessFadedToken, location)); | ||
} | ||
context.ReportDiagnostic(Diagnostic.Create(DiagnosticDescriptors.UseNullConditionalMemberAccess, | ||
Location.Create(context.Node.SyntaxTree, ifStatement.Span))); | ||
} | ||
} | ||
catch (OperationCanceledException ex) when (ex.CancellationToken == context.CancellationToken) | ||
{ | ||
// we should ignore cancellation exceptions, instead of blowing up the universe! | ||
} | ||
} | ||
|
||
public override void Initialize(AnalysisContext context) | ||
{ | ||
context.RegisterSyntaxNodeAction(AnalyzeThat, ImmutableArray.Create(SyntaxKind.IfStatement)); | ||
} | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why is this needed?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
My bad. Fixed it.