Skip to content

Commit 41c4b5a

Browse files
authored
AK2001 - Add as cast expression detection (#114)
1 parent 9838782 commit 41c4b5a

File tree

2 files changed

+59
-1
lines changed

2 files changed

+59
-1
lines changed

src/Akka.Analyzers.Tests/Analyzers/AK2000/MustNotHandleAutomaticallyHandledMessagesInMessageExtractorAnalyzerSpecs.cs

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -333,7 +333,47 @@ IMessageExtractor Create(){
333333
""", new[]
334334
{
335335
(10, 26, 10, 48)
336-
})
336+
}),
337+
338+
(
339+
// Simple message extractor edge case - using expression body instead of block
340+
"""
341+
// 01
342+
using Akka.Cluster.Sharding;
343+
public sealed class ShardMessageExtractor : HashCodeMessageExtractor
344+
{
345+
/// <summary>
346+
/// We only ever run with a maximum of two nodes, so ~10 shards per node
347+
/// </summary>
348+
public ShardMessageExtractor(int shardCount = 20) : base(shardCount)
349+
{
350+
}
351+
352+
public override string EntityId(object message)
353+
=> (message as ShardingEnvelope)?.EntityId ?? null;
354+
}
355+
""", new[]{(13, 13, 13, 40)}),
356+
357+
(
358+
// Simple message extractor edge case - using `as`
359+
"""
360+
// 02
361+
using Akka.Cluster.Sharding;
362+
public sealed class ShardMessageExtractor : HashCodeMessageExtractor
363+
{
364+
/// <summary>
365+
/// We only ever run with a maximum of two nodes, so ~10 shards per node
366+
/// </summary>
367+
public ShardMessageExtractor(int shardCount = 20) : base(shardCount)
368+
{
369+
}
370+
371+
public override string EntityId(object message)
372+
{
373+
return (message as ShardingEnvelope)?.EntityId ?? null;
374+
}
375+
}
376+
""", new[]{(14, 17, 14, 44)}),
337377
};
338378

339379
[Theory]

src/Akka.Analyzers/AK2000/MustNotUseAutomaticallyHandledMessagesInsideMessageExtractorAnalyzer.cs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,24 @@ private static void AnalyzeDeclaredVariableNodes(SyntaxNodeAnalysisContext ctx,
159159

160160
break;
161161
}
162+
163+
case BinaryExpressionSyntax binaryExpressionSyntax when binaryExpressionSyntax.IsKind(SyntaxKind.AsExpression) && binaryExpressionSyntax.Right is TypeSyntax typeSyntax:
164+
var typeSymbol = semanticModel.GetTypeInfo(typeSyntax).Type;
165+
if (forbiddenTypes.Any(t => SymbolEqualityComparer.Default.Equals(t, typeSymbol)))
166+
{
167+
var location = binaryExpressionSyntax.GetLocation();
168+
169+
// duplicate
170+
if (reportedLocations.Contains(location))
171+
break;
172+
var diagnostic = Diagnostic.Create(
173+
RuleDescriptors
174+
.Ak2001DoNotUseAutomaticallyHandledMessagesInShardMessageExtractor,
175+
location);
176+
ctx.ReportDiagnostic(diagnostic);
177+
reportedLocations.Add(location);
178+
}
179+
break;
162180
}
163181
}
164182
}

0 commit comments

Comments
 (0)