Skip to content

Commit 96517ea

Browse files
authored
Merge pull request #359 from CommunityToolkit/dev/fix-linker-pragma-suppressions
Replace linker suppressions with attributes
2 parents 8528092 + 321fc50 commit 96517ea

File tree

4 files changed

+103
-11
lines changed

4 files changed

+103
-11
lines changed

CommunityToolkit.Mvvm/ComponentModel/ObservableValidator.cs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -545,9 +545,9 @@ IEnumerable<ValidationResult> GetAllErrors()
545545
"Additionally, due to the usage of validation APIs, the type of the current instance cannot be statically discovered.")]
546546
protected void ValidateAllProperties()
547547
{
548-
#pragma warning disable IL2026
549548
// Fast path that tries to create a delegate from a generated type-specific method. This
550549
// is used to make this method more AOT-friendly and faster, as there is no dynamic code.
550+
[RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")]
551551
static Action<object> GetValidationAction(Type type)
552552
{
553553
if (type.Assembly.GetType("CommunityToolkit.Mvvm.ComponentModel.__Internals.__ObservableValidatorExtensions") is Type extensionsType &&
@@ -558,7 +558,6 @@ static Action<object> GetValidationAction(Type type)
558558

559559
return GetValidationActionFallback(type);
560560
}
561-
#pragma warning restore IL2026
562561

563562
// Fallback method to create the delegate with a compiled LINQ expression
564563
static Action<object> GetValidationActionFallback(Type type)
@@ -615,7 +614,9 @@ from property in validatableProperties
615614

616615
// Get or compute the cached list of properties to validate. Here we're using a static lambda to ensure the
617616
// delegate is cached by the C# compiler, see the related issue at https://github.com/dotnet/roslyn/issues/5835.
618-
EntityValidatorMap.GetValue(GetType(), static t => GetValidationAction(t))(this);
617+
EntityValidatorMap.GetValue(
618+
GetType(),
619+
[RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")] static (t) => GetValidationAction(t))(this);
619620
}
620621

621622
/// <summary>

CommunityToolkit.Mvvm/ComponentModel/__Internals/__ObservableValidatorHelper.cs

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
using System;
66
using System.ComponentModel;
7+
using System.Diagnostics.CodeAnalysis;
78

89
namespace CommunityToolkit.Mvvm.ComponentModel.__Internals;
910

@@ -23,10 +24,12 @@ public static class __ObservableValidatorHelper
2324
/// <param name="propertyName">The name of the property to validate.</param>
2425
[EditorBrowsable(EditorBrowsableState.Never)]
2526
[Obsolete("This method is not intended to be called directly by user code")]
27+
[UnconditionalSuppressMessage(
28+
"ReflectionAnalysis",
29+
"IL2026:RequiresUnreferencedCode",
30+
Justification = "This helper is called by generated code from public APIs that have the proper annotations already (and we don't want generated code to produce warnings that developers cannot fix).")]
2631
public static void ValidateProperty(ObservableValidator instance, object? value, string propertyName)
2732
{
28-
#pragma warning disable IL2026
2933
instance.ValidateProperty(value, propertyName);
30-
#pragma warning restore IL2026
3134
}
3235
}

CommunityToolkit.Mvvm/Messaging/IMessengerExtensions.cs

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -95,10 +95,10 @@ public static void RegisterAll(this IMessenger messenger, object recipient)
9595
ArgumentNullException.ThrowIfNull(messenger);
9696
ArgumentNullException.ThrowIfNull(recipient);
9797

98-
#pragma warning disable IL2026
9998
// We use this method as a callback for the conditional weak table, which will handle
10099
// thread-safety for us. This first callback will try to find a generated method for the
101100
// target recipient type, and just invoke it to get the delegate to cache and use later.
101+
[RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")]
102102
static Action<IMessenger, object>? LoadRegistrationMethodsForType(Type recipientType)
103103
{
104104
if (recipientType.Assembly.GetType("CommunityToolkit.Mvvm.Messaging.__Internals.__IMessengerExtensions") is Type extensionsType &&
@@ -109,12 +109,11 @@ public static void RegisterAll(this IMessenger messenger, object recipient)
109109

110110
return null;
111111
}
112-
#pragma warning restore IL2026
113112

114113
// Try to get the cached delegate, if the generator has run correctly
115114
Action<IMessenger, object>? registrationAction = DiscoveredRecipients.RegistrationMethods.GetValue(
116115
recipient.GetType(),
117-
static t => LoadRegistrationMethodsForType(t));
116+
[RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")] static (t) => LoadRegistrationMethodsForType(t));
118117

119118
if (registrationAction is not null)
120119
{
@@ -152,11 +151,11 @@ public static void RegisterAll<TToken>(this IMessenger messenger, object recipie
152151
ArgumentNullException.ThrowIfNull(recipient);
153152
ArgumentNullException.For<TToken>.ThrowIfNull(token);
154153

155-
#pragma warning disable IL2026
156154
// We use this method as a callback for the conditional weak table, which will handle
157155
// thread-safety for us. This first callback will try to find a generated method for the
158156
// target recipient type, and just invoke it to get the delegate to cache and use later.
159157
// In this case we also need to create a generic instantiation of the target method first.
158+
[RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")]
160159
static Action<IMessenger, object, TToken> LoadRegistrationMethodsForType(Type recipientType)
161160
{
162161
if (recipientType.Assembly.GetType("CommunityToolkit.Mvvm.Messaging.__Internals.__IMessengerExtensions") is Type extensionsType &&
@@ -224,7 +223,6 @@ from registrationMethod in registrationMethods
224223

225224
return Expression.Lambda<Action<IMessenger, object, TToken>>(body, arg0, arg1, arg2).Compile();
226225
}
227-
#pragma warning restore IL2026
228226

229227
// Get or compute the registration method for the current recipient type.
230228
// As in CommunityToolkit.Diagnostics.TypeExtensions.ToTypeString, we use a lambda
@@ -233,7 +231,7 @@ from registrationMethod in registrationMethods
233231
// For more info on this, see the related issue at https://github.com/dotnet/roslyn/issues/5835.
234232
Action<IMessenger, object, TToken> registrationAction = DiscoveredRecipients<TToken>.RegistrationMethods.GetValue(
235233
recipient.GetType(),
236-
static t => LoadRegistrationMethodsForType(t));
234+
[RequiresUnreferencedCode("The type of the current instance cannot be statically discovered.")] static (t) => LoadRegistrationMethodsForType(t));
237235

238236
// Invoke the cached delegate to actually execute the message registration
239237
registrationAction(messenger, recipient, token);
Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
// Licensed to the .NET Foundation under one or more agreements.
2+
// The .NET Foundation licenses this file to you under the MIT license.
3+
// See the LICENSE file in the project root for more information.
4+
5+
#if !NET6_0_OR_GREATER
6+
7+
namespace System.Diagnostics.CodeAnalysis;
8+
9+
/// <summary>
10+
/// Suppresses reporting of a specific rule violation, allowing multiple suppressions on a
11+
/// single code artifact.
12+
/// </summary>
13+
/// <remarks>
14+
/// <see cref="UnconditionalSuppressMessageAttribute"/> is different than
15+
/// <see cref="SuppressMessageAttribute"/> in that it doesn't have a
16+
/// <see cref="ConditionalAttribute"/>. So it is always preserved in the compiled assembly.
17+
/// </remarks>
18+
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
19+
[Conditional("DEBUG")]
20+
internal sealed class UnconditionalSuppressMessageAttribute : Attribute
21+
{
22+
/// <summary>
23+
/// Initializes a new instance of the <see cref="UnconditionalSuppressMessageAttribute"/>
24+
/// class, specifying the category of the tool and the identifier for an analysis rule.
25+
/// </summary>
26+
/// <param name="category">The category for the attribute.</param>
27+
/// <param name="checkId">The identifier of the analysis rule the attribute applies to.</param>
28+
public UnconditionalSuppressMessageAttribute(string category, string checkId)
29+
{
30+
Category = category;
31+
CheckId = checkId;
32+
}
33+
34+
/// <summary>
35+
/// Gets the category identifying the classification of the attribute.
36+
/// </summary>
37+
/// <remarks>
38+
/// The <see cref="Category"/> property describes the tool or tool analysis category
39+
/// for which a message suppression attribute applies.
40+
/// </remarks>
41+
public string Category { get; }
42+
43+
/// <summary>
44+
/// Gets the identifier of the analysis tool rule to be suppressed.
45+
/// </summary>
46+
/// <remarks>
47+
/// Concatenated together, the <see cref="Category"/> and <see cref="CheckId"/>
48+
/// properties form a unique check identifier.
49+
/// </remarks>
50+
public string CheckId { get; }
51+
52+
/// <summary>
53+
/// Gets or sets the scope of the code that is relevant for the attribute.
54+
/// </summary>
55+
/// <remarks>
56+
/// The Scope property is an optional argument that specifies the metadata scope for which
57+
/// the attribute is relevant.
58+
/// </remarks>
59+
public string? Scope { get; set; }
60+
61+
/// <summary>
62+
/// Gets or sets a fully qualified path that represents the target of the attribute.
63+
/// </summary>
64+
/// <remarks>
65+
/// The <see cref="Target"/> property is an optional argument identifying the analysis target
66+
/// of the attribute. An example value is "System.IO.Stream.ctor():System.Void".
67+
/// Because it is fully qualified, it can be long, particularly for targets such as parameters.
68+
/// The analysis tool user interface should be capable of automatically formatting the parameter.
69+
/// </remarks>
70+
public string? Target { get; set; }
71+
72+
/// <summary>
73+
/// Gets or sets an optional argument expanding on exclusion criteria.
74+
/// </summary>
75+
/// <remarks>
76+
/// The <see cref="MessageId "/> property is an optional argument that specifies additional
77+
/// exclusion where the literal metadata target is not sufficiently precise. For example,
78+
/// the <see cref="UnconditionalSuppressMessageAttribute"/> cannot be applied within a method,
79+
/// and it may be desirable to suppress a violation against a statement in the method that will
80+
/// give a rule violation, but not against all statements in the method.
81+
/// </remarks>
82+
public string? MessageId { get; set; }
83+
84+
/// <summary>
85+
/// Gets or sets the justification for suppressing the code analysis message.
86+
/// </summary>
87+
public string? Justification { get; set; }
88+
}
89+
90+
#endif

0 commit comments

Comments
 (0)