Created
August 20, 2012 12:47
-
-
Save schani/3403790 to your computer and use it in GitHub Desktop.
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
| using System.Collections.Generic; | |
| using System.Linq; | |
| using ICSharpCode.NRefactory.Semantics; | |
| using ICSharpCode.NRefactory.TypeSystem; | |
| using ICSharpCode.NRefactory.PatternMatching; | |
| namespace ICSharpCode.NRefactory.CSharp.Refactoring | |
| { | |
| [IssueDescription("Any() should be used with predicate and Where() removed", | |
| Description= "Detects redundant Where() with predicate calls followed by Any().", | |
| Category = IssueCategories.CodeQualityIssues, | |
| Severity = Severity.Hint)] | |
| public class RedundantWhereWithPredicateIssue | |
| { | |
| static readonly AstNode pattern = | |
| new InvocationExpression ( | |
| new MemberReferenceExpression ( | |
| new NamedNode ("whereInvoke", | |
| new InvocationExpression ( | |
| new MemberReferenceExpression (new AnyNode (), "Where"), | |
| new Expression[] { new AnyNode () })), | |
| "Any"), | |
| new Expression[] {}); | |
| public IEnumerable<CodeIssue> GetIssues(BaseRefactoringContext context) | |
| { | |
| return new GatherVisitor(context).GetIssues(); | |
| } | |
| class GatherVisitor : GatherVisitorBase | |
| { | |
| public GatherVisitor (BaseRefactoringContext ctx) : base (ctx) | |
| { | |
| } | |
| public override void VisitInvocationExpression (InvocationExpression anyInvoke) | |
| { | |
| var match = pattern.Match (anyInvoke); | |
| if (!match.Success) | |
| return; | |
| var anyResolve = ctx.Resolve (anyInvoke) as InvocationResolveResult; | |
| if (anyResolve.Member.FullName != "System.Linq.Enumerable.Any") | |
| return; | |
| var whereInvoke = match.Get<InvocationExpression> ("whereInvoke").Single (); | |
| var whereResolve = ctx.Resolve (whereInvoke) as InvocationResolveResult; | |
| if (whereResolve.Member.FullName != "System.Linq.Enumerable.Where") | |
| return; | |
| if (whereResolve.Member.Parameters.Count != 2) | |
| return; | |
| var predResolve = whereResolve.Member.Parameters [1]; | |
| if (predResolve.Type.TypeParameterCount != 2) | |
| return; | |
| AddIssue (anyInvoke, "Redundant Where() call with predicate followed by Any()", script => { | |
| var arg = whereInvoke.Arguments.Single ().Clone (); | |
| script.Replace (anyInvoke, new InvocationExpression (whereInvoke.Target.Clone (), | |
| new Expression[] { arg })); | |
| }); | |
| } | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment