From 1c65b805a990ecdc7b6be9250e07f3cc5b751568 Mon Sep 17 00:00:00 2001 From: Sebastien Lebreton Date: Mon, 30 Nov 2026 16:50:26 +0100 Subject: [PATCH] Fix UNT0042 false positives for setters and per-iteration meshes Mesh array property setters do not allocate (the array is passed as a Span to native code), so only getters are reported now. The code fix no longer rewrites setters to the cached local. Accesses on a mesh that changes with each iteration (foreach variable, locals declared or assigned in the loop, meshes[i]) are no longer reported, as they cannot be cached before the loop. Occurrences also require equivalent receivers, so meshes[0].vertices and meshes[i].vertices are no longer treated as the same access. Fixes #520 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Copilot-Session: b3f0f070-0d78-4e38-9909-19a4d7af65a0 --- doc/UNT0042.md | 2 + .../MeshArrayPropertyInLoopTests.cs | 273 ++++++++++++++++++ .../MeshArrayPropertyInLoop.cs | 79 +++-- 3 files changed, 336 insertions(+), 18 deletions(-) diff --git a/doc/UNT0042.md b/doc/UNT0042.md index b572531a..2996270b 100644 --- a/doc/UNT0042.md +++ b/doc/UNT0042.md @@ -2,6 +2,8 @@ Accessing array properties like `vertices`, `normals`, `tangents`, `uv`, `colors`, etc. on `Mesh` inside a loop causes a new array allocation on each access. This can significantly impact performance, especially in frequently called methods like `Update()`. +Only reading these properties allocates. Assigning them (for example `mesh.vertices = vertices;`) does not allocate and is not reported. Accesses on a mesh that changes with each iteration (for example a `foreach` variable) are not reported either, as they cannot be cached before the loop. + ## Examples of patterns that are flagged by this analyzer ```csharp diff --git a/src/Microsoft.Unity.Analyzers.Tests/MeshArrayPropertyInLoopTests.cs b/src/Microsoft.Unity.Analyzers.Tests/MeshArrayPropertyInLoopTests.cs index 1c13505d..6a5fc6ab 100644 --- a/src/Microsoft.Unity.Analyzers.Tests/MeshArrayPropertyInLoopTests.cs +++ b/src/Microsoft.Unity.Analyzers.Tests/MeshArrayPropertyInLoopTests.cs @@ -676,6 +676,279 @@ void Update() // loop end } } +"; + + await VerifyCSharpFixAsync(test, fixedTest); + } + + [Fact] + public async Task SetterInLoop() + { + const string test = @" +using UnityEngine; + +class Camera : MonoBehaviour +{ + void Update() + { + Mesh mesh = GetComponent().mesh; + Vector3[] vertices = new Vector3[0]; + Color32[] colors = new Color32[0]; + for (int i = 0; i < 10; i++) + { + mesh.vertices = vertices; + (mesh.colors32) = colors; + } + } +} +"; + + // Setters are not allocating + await VerifyCSharpDiagnosticAsync(test); + } + + [Fact] + public async Task SetterWithDeconstructionInLoop() + { + const string test = @" +using UnityEngine; + +class Camera : MonoBehaviour +{ + void Update() + { + Mesh mesh = GetComponent().mesh; + Vector3[] vertices = new Vector3[0]; + Vector3[] normals = new Vector3[0]; + for (int i = 0; i < 10; i++) + { + (mesh.vertices, mesh.normals) = (vertices, normals); + } + } +} +"; + + await VerifyCSharpDiagnosticAsync(test); + } + + [Fact] + public async Task SetterBeforeGetterInLoop() + { + const string test = @" +using UnityEngine; + +class Camera : MonoBehaviour +{ + void Update() + { + Mesh mesh = GetComponent().mesh; + Vector3[] vertices = new Vector3[0]; + for (int i = 0; i < 10; i++) + { + mesh.vertices = vertices; + var v = mesh.vertices[i]; + } + } +} +"; + + var diagnostic = ExpectDiagnostic() + .WithLocation(13, 21) + .WithArguments("vertices"); + + await VerifyCSharpDiagnosticAsync(test, diagnostic); + } + + [Fact] + public async Task GetterAndSetterInLoop() + { + const string test = @" +using UnityEngine; + +class Camera : MonoBehaviour +{ + void Update() + { + Mesh mesh = GetComponent().mesh; + for (int i = 0; i < mesh.vertexCount; i++) + { + var vertices = mesh.vertices; + vertices[i] += Vector3.up; + mesh.vertices = vertices; + } + } +} +"; + + var diagnostic = ExpectDiagnostic() + .WithLocation(11, 28) + .WithArguments("vertices"); + + await VerifyCSharpDiagnosticAsync(test, diagnostic); + + const string fixedTest = @" +using UnityEngine; + +class Camera : MonoBehaviour +{ + void Update() + { + Mesh mesh = GetComponent().mesh; + Vector3[] meshVertices = mesh.vertices; + for (int i = 0; i < mesh.vertexCount; i++) + { + var vertices = meshVertices; + vertices[i] += Vector3.up; + mesh.vertices = vertices; + } + } +} +"; + + await VerifyCSharpFixAsync(test, fixedTest); + } + + [Fact] + public async Task ReceiverDeclaredInLoop() + { + const string test = @" +using UnityEngine; + +class Camera : MonoBehaviour +{ + void Update() + { + foreach (var filter in GetComponentsInChildren()) + { + var normals = filter.mesh.normals; + Mesh mesh = filter.mesh; + var vertices = mesh.vertices; + } + } +} +"; + + // A different mesh is used on each iteration, so it cannot be cached before the loop + await VerifyCSharpDiagnosticAsync(test); + } + + [Fact] + public async Task ReceiverAssignedInLoop() + { + const string test = @" +using UnityEngine; + +class Camera : MonoBehaviour +{ + void Update() + { + Mesh[] meshes = new Mesh[0]; + Mesh mesh = null; + for (int i = 0; i < meshes.Length; i++) + { + mesh = meshes[i]; + var vertices = mesh.vertices; + } + } +} +"; + + await VerifyCSharpDiagnosticAsync(test); + } + + [Fact] + public async Task ReceiverDeclaredInOuterLoop() + { + const string test = @" +using UnityEngine; + +class Camera : MonoBehaviour +{ + void Update() + { + foreach (var filter in GetComponentsInChildren()) + { + Mesh mesh = filter.mesh; + for (int i = 0; i < mesh.vertices.Length; i++) + { + // some work + } + } + } +} +"; + + var diagnostic = ExpectDiagnostic() + .WithLocation(11, 33) + .WithArguments("vertices"); + + await VerifyCSharpDiagnosticAsync(test, diagnostic); + + const string fixedTest = @" +using UnityEngine; + +class Camera : MonoBehaviour +{ + void Update() + { + foreach (var filter in GetComponentsInChildren()) + { + Mesh mesh = filter.mesh; + Vector3[] meshVertices = mesh.vertices; + for (int i = 0; i < meshVertices.Length; i++) + { + // some work + } + } + } +} +"; + + await VerifyCSharpFixAsync(test, fixedTest); + } + + [Fact] + public async Task ReceiverUsingLoopVariable() + { + const string test = @" +using UnityEngine; + +class Camera : MonoBehaviour +{ + void Update() + { + Mesh[] meshes = new Mesh[0]; + for (int i = 0; i < meshes.Length; i++) + { + var current = meshes[i].vertices; + var first = meshes[0].vertices; + } + } +} +"; + + var diagnostic = ExpectDiagnostic() + .WithLocation(12, 25) + .WithArguments("vertices"); + + await VerifyCSharpDiagnosticAsync(test, diagnostic); + + const string fixedTest = @" +using UnityEngine; + +class Camera : MonoBehaviour +{ + void Update() + { + Mesh[] meshes = new Mesh[0]; + Vector3[] meshVertices = meshes[0].vertices; + for (int i = 0; i < meshes.Length; i++) + { + var current = meshes[i].vertices; + var first = meshVertices; + } + } +} "; await VerifyCSharpFixAsync(test, fixedTest); diff --git a/src/Microsoft.Unity.Analyzers/MeshArrayPropertyInLoop.cs b/src/Microsoft.Unity.Analyzers/MeshArrayPropertyInLoop.cs index 720fecf0..e7aa48d9 100644 --- a/src/Microsoft.Unity.Analyzers/MeshArrayPropertyInLoop.cs +++ b/src/Microsoft.Unity.Analyzers/MeshArrayPropertyInLoop.cs @@ -58,6 +58,10 @@ private static void AnalyzeMemberAccess(SyntaxNodeAnalysisContext context) if (loop == null) return; + // Assigning the property only invokes its setter, which does not allocate + if (IsSetterOnlyAccess(memberAccess)) + return; + if (!IsAllocatingMeshProperty(context, memberAccess, out var propertyName)) return; @@ -66,13 +70,17 @@ private static void AnalyzeMemberAccess(SyntaxNodeAnalysisContext context) if (!IsFirstOccurrenceInLoop(context.SemanticModel, memberAccess, loop)) return; + // The mesh must be the same on each iteration to be cached before the loop + if (!IsLoopInvariant(context.SemanticModel, memberAccess.Expression, loop)) + return; + context.ReportDiagnostic(Diagnostic.Create( Rule, memberAccess.GetLocation(), propertyName)); } - internal static SyntaxNode? FindContainingLoop(SyntaxNode node) + internal static StatementSyntax? FindContainingLoop(SyntaxNode node) { var current = node.Parent; while (current != null) @@ -83,7 +91,7 @@ private static void AnalyzeMemberAccess(SyntaxNodeAnalysisContext context) case ForEachStatementSyntax: case WhileStatementSyntax: case DoStatementSyntax: - return current; + return (StatementSyntax)current; // Stop looking if we hit a method/lambda/function boundary case MethodDeclarationSyntax: @@ -100,17 +108,60 @@ private static void AnalyzeMemberAccess(SyntaxNodeAnalysisContext context) private static bool IsFirstOccurrenceInLoop(SemanticModel model, MemberAccessExpressionSyntax memberAccess, SyntaxNode loop) { - var allOccurrences = loop.DescendantNodes() + return FindOccurrencesInLoop(model, memberAccess, loop).FirstOrDefault() == memberAccess; + } + + internal static IEnumerable FindOccurrencesInLoop(SemanticModel model, MemberAccessExpressionSyntax memberAccess, SyntaxNode loop) + { + return loop.DescendantNodes() .OfType() - .Where(m => IsInLoopConditionOrBody(m, loop) && IsSameMeshPropertyAccess(model, m, memberAccess)) - .OrderBy(m => m.SpanStart) - .ToList(); + .Where(m => IsInLoopConditionOrBody(m, loop) && !IsSetterOnlyAccess(m) && IsSameMeshPropertyAccess(model, m, memberAccess)); + } + + private static bool IsSetterOnlyAccess(ExpressionSyntax expression) + { + SyntaxNode current = expression; + while (true) + { + switch (current.Parent) + { + case ParenthesizedExpressionSyntax parentheses: + current = parentheses; + continue; + // Deconstruction, like (mesh.vertices, mesh.normals) = (vertices, normals) + case ArgumentSyntax { Parent: TupleExpressionSyntax tuple }: + current = tuple; + continue; + } - return allOccurrences.Count > 0 && allOccurrences[0] == memberAccess; + break; + } + + // Compound assignments, like ??=, are invoking the getter as well + return current.Parent is AssignmentExpressionSyntax assignment + && assignment.IsKind(SyntaxKind.SimpleAssignmentExpression) + && assignment.Left == current; + } + + private static bool IsLoopInvariant(SemanticModel model, ExpressionSyntax expression, StatementSyntax loop) + { + var loopFlow = model.AnalyzeDataFlow(loop); + var expressionFlow = model.AnalyzeDataFlow(expression); + if (loopFlow is not { Succeeded: true } || expressionFlow is not { Succeeded: true }) + return false; + + // Variables declared or written inside the loop can change on each iteration + return !expressionFlow.ReadInside.Any(symbol => + loopFlow.VariablesDeclared.Contains(symbol, SymbolEqualityComparer.Default) + || loopFlow.WrittenInside.Contains(symbol, SymbolEqualityComparer.Default)); } - internal static bool IsSameMeshPropertyAccess(SemanticModel model, MemberAccessExpressionSyntax candidate, MemberAccessExpressionSyntax reference) + private static bool IsSameMeshPropertyAccess(SemanticModel model, MemberAccessExpressionSyntax candidate, MemberAccessExpressionSyntax reference) { + // Different receivers can share the same symbol, like meshes[0] and meshes[i] + if (!SyntaxFactory.AreEquivalent(candidate.Expression, reference.Expression)) + return false; + var candidateSymbol = model.GetSymbolInfo(candidate).Symbol; var referenceSymbol = model.GetSymbolInfo(reference).Symbol; @@ -126,7 +177,7 @@ internal static bool IsSameMeshPropertyAccess(SemanticModel model, MemberAccessE return SymbolEqualityComparer.Default.Equals(candidateExprSymbol, referenceExprSymbol); } - internal static bool IsInLoopConditionOrBody(SyntaxNode node, SyntaxNode loop) + private static bool IsInLoopConditionOrBody(SyntaxNode node, SyntaxNode loop) { if (!loop.Contains(node)) return false; @@ -237,7 +288,6 @@ private static async Task CacheMeshPropertyAsync(Document document, Me if (loop == null) return document; - var allOccurrences = FindAllPropertyAccesses(semanticModel, memberAccess, loop); var variableName = GenerateVariableName(semanticModel, memberAccess, propertySymbol, loop); var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); var typeName = propertySymbol.Type.ToMinimalDisplayString(semanticModel, memberAccess.SpanStart); @@ -261,19 +311,12 @@ private static async Task CacheMeshPropertyAsync(Document document, Me editor.InsertBefore(loop, variableDeclaration); - foreach (var occurrence in allOccurrences) + foreach (var occurrence in MeshArrayPropertyInLoopAnalyzer.FindOccurrencesInLoop(semanticModel, memberAccess, loop)) editor.ReplaceNode(occurrence, SyntaxFactory.IdentifierName(variableName).WithTriviaFrom(occurrence)); return editor.GetChangedDocument(); } - private static List FindAllPropertyAccesses(SemanticModel model, MemberAccessExpressionSyntax memberAccess, SyntaxNode loop) - { - return [.. loop.DescendantNodes() - .OfType() - .Where(m => MeshArrayPropertyInLoopAnalyzer.IsSameMeshPropertyAccess(model, m, memberAccess) && MeshArrayPropertyInLoopAnalyzer.IsInLoopConditionOrBody(m, loop))]; - } - private static string GenerateVariableName(SemanticModel semanticModel, MemberAccessExpressionSyntax memberAccess, IPropertySymbol propertySymbol, SyntaxNode loop) { var prefix = memberAccess.Expression switch