Skip to content

Commit f30a633

Browse files
authored
Suppress warning in instance fields if the instance constructors are annotated with Requires (dotnet/linker#2973)
Commit migrated from dotnet/linker@6b5bc03
1 parent 07c9ace commit f30a633

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

src/tools/illink/src/ILLink.RoslynAnalyzer/RequiresISymbolExtensions.cs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,15 @@ private static bool IsInRequiresScope (this ISymbol member, string requiresAttri
7272
if (checkAssociatedSymbol && member is IMethodSymbol { AssociatedSymbol: { } associated } && associated.HasAttribute (requiresAttribute))
7373
return true;
7474

75+
// When using instance fields suppress the warning if the constructor has already the Requires annotation
76+
if (member is IFieldSymbol field && !field.IsStatic) {
77+
foreach (var constructor in field.ContainingType.InstanceConstructors) {
78+
if (!constructor.HasAttribute (requiresAttribute))
79+
return false;
80+
}
81+
return true;
82+
}
83+
7584
return false;
7685
}
7786
}

src/tools/illink/test/Mono.Linker.Tests.Cases/RequiresCapability/RequiresOnClass.cs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ public static void Main ()
2525
TestRequiresOnBaseButNotOnDerived ();
2626
TestRequiresOnDerivedButNotOnBase ();
2727
TestRequiresOnBaseAndDerived ();
28+
TestInstanceFieldSuppression ();
2829
TestSuppressionsOnClass ();
2930
TestStaticMethodOnRequiresTypeSuppressedByRequiresOnMethod ();
3031
TestStaticConstructorCalls ();
@@ -246,6 +247,22 @@ static void TestInstanceFieldCallDontWarn ()
246247
var _ = instance.field;
247248
}
248249

250+
public class ClassWithInstanceFieldWhichInitsDangerousClass
251+
{
252+
private ClassWithRequires _instanceField = new ClassWithRequires ();
253+
254+
[RequiresUnreferencedCode ("Calling the constructor is dangerous")]
255+
[RequiresDynamicCode ("Calling the constructor is dangerous")]
256+
public ClassWithInstanceFieldWhichInitsDangerousClass () { }
257+
}
258+
259+
[ExpectedWarning ("IL2026", "Calling the constructor is dangerous")]
260+
[ExpectedWarning ("IL3050", "Calling the constructor is dangerous", ProducedBy = ProducedBy.Analyzer)]
261+
static void TestInstanceFieldSuppression ()
262+
{
263+
_ = new ClassWithInstanceFieldWhichInitsDangerousClass ();
264+
}
265+
249266
[RequiresUnreferencedCode ("Message for --StaticCtorTriggeredByMethodCall2--")]
250267
[RequiresDynamicCode ("Message for --StaticCtorTriggeredByMethodCall2--")]
251268
class StaticCtorTriggeredByMethodCall2

0 commit comments

Comments
 (0)