Skip to content

Commit

Permalink
Fix S1104 FP: Do not report in Unity serializable classes
Browse files Browse the repository at this point in the history
  • Loading branch information
sebastien-marichal committed Jul 9, 2024
1 parent a94a3ae commit 0825155
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@ public sealed class FieldsShouldBeEncapsulatedInProperties : SonarDiagnosticAnal
SyntaxKind.ConstKeyword
};

private static readonly ImmutableArray<KnownType> IgnoredTypes = ImmutableArray.Create(
KnownType.UnityEngine_MonoBehaviour,
KnownType.UnityEngine_ScriptableObject);

public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } = ImmutableArray.Create(Rule);

protected override void Initialize(SonarAnalysisContext context) =>
Expand All @@ -52,7 +56,9 @@ protected override void Initialize(SonarAnalysisContext context) =>
var firstVariable = fieldDeclaration.Declaration.Variables[0];
var symbol = c.SemanticModel.GetDeclaredSymbol(firstVariable);
var parentSymbol = c.SemanticModel.GetDeclaredSymbol(fieldDeclaration.Parent);
if (parentSymbol.HasAttribute(KnownType.System_Runtime_InteropServices_StructLayoutAttribute) || Serializable(symbol, parentSymbol))
if (symbol.ContainingType.DerivesFromAny(IgnoredTypes)
|| parentSymbol.HasAttribute(KnownType.System_Runtime_InteropServices_StructLayoutAttribute)
|| Serializable(symbol, parentSymbol))
{
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,13 @@ public class FieldsShouldBeEncapsulatedInPropertiesTest
public void FieldsShouldBeEncapsulatedInProperties() =>
builder.AddPaths("FieldsShouldBeEncapsulatedInProperties.cs").Verify();

[TestMethod]
public void FieldsShouldBeEncapsulatedInProperties_Unity3D_Ignored() =>
builder.AddPaths("FieldsShouldBeEncapsulatedInProperties.Unity3D.cs")
// Concurrent analysis puts fake Unity3D class into the Concurrent namespace
.WithConcurrentAnalysis(false)
.VerifyNoIssues();

#if NET

[TestMethod]
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// https://github.com/SonarSource/sonar-dotnet/issues/7522
public class UnityMonoBehaviour : UnityEngine.MonoBehaviour
{
public int Field1; // Compliant
}

public class UnityScriptableObject : UnityEngine.ScriptableObject
{
public int Field1; // Compliant
}

// Unity3D does not seem to be available as a nuget package and we cannot use the original classes
// Cannot run this test case in Concurrent mode because of the Concurrent namespace
namespace UnityEngine
{
public class MonoBehaviour { }
public class ScriptableObject { }
}

0 comments on commit 0825155

Please sign in to comment.