Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix S109 FP: named arguments, constructor calls, single-value attributes #5247

Merged
merged 12 commits into from
Jan 12, 2022
Prev Previous commit
Next Next commit
Ignore attributes when single or named argument
  • Loading branch information
andrei-epure-sonarsource committed Jan 7, 2022
commit 04eaed993797a0f18889660efc4cc53c710d19a2
Original file line number Diff line number Diff line change
Expand Up @@ -70,12 +70,20 @@ private static bool IsExceptionToTheRule(LiteralExpressionSyntax literalExpressi
|| literalExpression.FirstAncestorOrSelf<PragmaWarningDirectiveTriviaSyntax>() != null
// It's ok to use magic numbers in property declaration
|| IsInsideProperty(literalExpression)
|| IsNamedArgument(literalExpression);
|| IsNamedArgument(literalExpression)
|| IsInAllowedAttribute(literalExpression);

private static bool IsNamedArgument(LiteralExpressionSyntax literalExpression) =>
literalExpression.Parent is ArgumentSyntax arg
&& arg.NameColon is not null;

// Either it is the only argument of the attribute, or it is a named argument.
private static bool IsInAllowedAttribute(LiteralExpressionSyntax literalExpression) =>
literalExpression.Parent is AttributeArgumentSyntax arg
&& (arg.NameColon is not null
|| arg.NameEquals is not null
|| (arg.Parent is AttributeArgumentListSyntax argList && argList.Arguments.Count == 1));

// Inside property we consider magic numbers as exceptions in the following cases:
// - A {get; set;} = MAGIC_NUMBER
// - A { get { return MAGIC_NUMBER; } }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,14 +65,13 @@ public override int GetHashCode()
return MY_VALUE * 397;
}

[Foo(Bar: 42, Baz = 43)] // Noncompliant FP - Compliant, explicit attribute argument names
// Noncompliant @-1
[Foo(Bar: 42, Baz = 43)] // Compliant, explicit attribute argument names
public void Foo(int value = 42)
{
var x = -1 < 1;
}

[Foo(42)] // Noncompliant FP -Compliant, attribute with only one argument
[Foo(42)] // Compliant, attribute with only one argument
public static int Bar(int value) => 0;
}

Expand Down