Skip to content

Commit

Permalink
Ignore member order on ReadonlyFieldAnalyzer
Browse files Browse the repository at this point in the history
Fix code-cracker#812
Add constructor to the top of the list so we add fields with
constructors initializers first
  • Loading branch information
giggio committed Aug 19, 2016
1 parent 01ee962 commit b40843e
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
14 changes: 14 additions & 0 deletions src/CSharp/CodeCracker/Usage/ReadonlyFieldAnalyzer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,19 @@ private static void AnalyzeCompilation(CompilationStartAnalysisContext compilati
compilationStartAnalysisContext.RegisterSyntaxTreeAction(context => AnalyzeTree(context, compilation));
}

private struct MethodKindComparer : IComparer<MethodKind>
{
public int Compare(MethodKind x, MethodKind y) =>
x - y == 0
? 0
: (x == MethodKind.Constructor
? 1
: (y == MethodKind.Constructor
? -1
: x - y));
}
private static readonly MethodKindComparer methodKindComparer = new MethodKindComparer();

private static void AnalyzeTree(SyntaxTreeAnalysisContext context, Compilation compilation)
{
if (context.IsGenerated()) return;
Expand All @@ -51,6 +64,7 @@ private static void AnalyzeTree(SyntaxTreeAnalysisContext context, Compilation c
var typeSymbol = semanticModel.GetDeclaredSymbol(type);
if (typeSymbol == null) continue;
var methods = typeSymbol.GetAllMethodsIncludingFromInnerTypes();
methods = methods.OrderByDescending(m => m.MethodKind, methodKindComparer).ToList();
foreach (var method in methods)
{
foreach (var syntaxReference in method.DeclaringSyntaxReferences)
Expand Down
24 changes: 24 additions & 0 deletions test/CSharp/CodeCracker.Test/Usage/ReadonlyFieldTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -967,5 +967,29 @@ public Person(string name)
};
await VerifyCSharpDiagnosticAsync(source, expected);
}

[Fact]
public async Task IgnoreWhenConstructorIsTheLastMember()
{
const string source = @"
class Test
{
private int value;
public int Value
{
get { return value; }
set { this.value = value; }
}
public void Foo()
{
value = 1;
}
public Test()
{
value = 8;
}
}";
await VerifyCSharpHasNoDiagnosticsAsync(source);
}
}
}

0 comments on commit b40843e

Please sign in to comment.