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
9 changes: 9 additions & 0 deletions src/ILLink.RoslynAnalyzer/RequiresISymbolExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,15 @@ private static bool IsInRequiresScope (this ISymbol member, string requiresAttri
if (checkAssociatedSymbol && member is IMethodSymbol { AssociatedSymbol: { } associated } && associated.HasAttribute (requiresAttribute))
return true;

// When using instance fields suppress the warning if the constructor has already the Requires annotation
if (member is IFieldSymbol field && !field.IsStatic) {
foreach (var constructor in field.ContainingType.InstanceConstructors) {
if (!constructor.HasAttribute (requiresAttribute))
return false;
}
return true;
}

return false;
}
}
Expand Down
17 changes: 17 additions & 0 deletions test/Mono.Linker.Tests.Cases/RequiresCapability/RequiresOnClass.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ public static void Main ()
TestRequiresOnBaseButNotOnDerived ();
TestRequiresOnDerivedButNotOnBase ();
TestRequiresOnBaseAndDerived ();
TestInstanceFieldSuppression ();
TestSuppressionsOnClass ();
TestStaticMethodOnRequiresTypeSuppressedByRequiresOnMethod ();
TestStaticConstructorCalls ();
Expand Down Expand Up @@ -246,6 +247,22 @@ static void TestInstanceFieldCallDontWarn ()
var _ = instance.field;
}

public class ClassWithInstanceFieldWhichInitsDangerousClass
{
private ClassWithRequires _instanceField = new ClassWithRequires ();

[RequiresUnreferencedCode ("Calling the constructor is dangerous")]
[RequiresDynamicCode ("Calling the constructor is dangerous")]
public ClassWithInstanceFieldWhichInitsDangerousClass () { }
}

[ExpectedWarning ("IL2026", "Calling the constructor is dangerous")]
[ExpectedWarning ("IL3050", "Calling the constructor is dangerous", ProducedBy = ProducedBy.Analyzer)]
static void TestInstanceFieldSuppression ()
{
_ = new ClassWithInstanceFieldWhichInitsDangerousClass ();
}

[RequiresUnreferencedCode ("Message for --StaticCtorTriggeredByMethodCall2--")]
[RequiresDynamicCode ("Message for --StaticCtorTriggeredByMethodCall2--")]
class StaticCtorTriggeredByMethodCall2
Expand Down