Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,8 @@ public sealed override void Initialize(AnalysisContext context)
// foreach loops are special, in that as with other loops we don't want stackallocs
// in the body of the loop, but in the expression of a foreach is ok.
case SyntaxKind.ForEachStatement:
ForEachStatementSyntax foreachStatement = (ForEachStatementSyntax)node;
case SyntaxKind.ForEachVariableStatement:
var foreachStatement = (CommonForEachStatementSyntax)node;
Comment on lines +41 to +42
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is the main fix.

if (foreachStatement.Expression.Contains(ctx.Node))
{
continue;
Expand Down Expand Up @@ -71,7 +72,7 @@ static bool ShouldWarn(IOperation? op, SyntaxNode node)
foreach (IOperation child in block.Operations)
{
if (child.Syntax.SpanStart > node.SpanStart &&
(child is IReturnOperation || (child is IBranchOperation branch && branch.BranchKind == BranchKind.Break)))
(child is IReturnOperation or IBranchOperation { BranchKind: BranchKind.Break }))
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No behavior change here. only a minor stylish change.

{
// Err on the side of false negatives / caution and say this stackalloc is ok.
// Note, too, it's possible we're breaking out of a nested loop, and the outer loop
Expand All @@ -88,7 +89,7 @@ static bool ShouldWarn(IOperation? op, SyntaxNode node)
}

// Warn as needed.
if (ShouldWarn(ctx.SemanticModel.GetOperationWalkingUpParentChain(ctx.Node, default), ctx.Node))
if (ShouldWarn(ctx.SemanticModel.GetOperationWalkingUpParentChain(ctx.Node, ctx.CancellationToken), ctx.Node))
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is an unrelated improvement.

{
ctx.ReportDiagnostic(ctx.Node.CreateDiagnostic(Rule));
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -285,5 +285,26 @@ private static void SourceOfForeachLoopInAnotherLoop() {
}"
}.RunAsync();
}

[Fact]
public async Task Diagnostics_StackallocAsSourceOfForeachVariableLoop()
{
await new VerifyCS.Test
{
LanguageVersion = LanguageVersion.CSharp8,
TestCode = @"
using System;
public class C
{
public static void Foo()
{
foreach (var (x, y) in stackalloc (double, double)[] { (0, 0) })
{
Span<byte> span = {|CA2014:stackalloc byte[1024]|};
}
}
}"
}.RunAsync();
}
}
}