diff --git a/Src/Newtonsoft.Json/Converters/BinaryConverter.cs b/Src/Newtonsoft.Json/Converters/BinaryConverter.cs index 47833a2a..57bcdee1 100644 --- a/Src/Newtonsoft.Json/Converters/BinaryConverter.cs +++ b/Src/Newtonsoft.Json/Converters/BinaryConverter.cs @@ -29,6 +29,7 @@ using System.Globalization; using Newtonsoft.Json.Utilities; using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; #if HAVE_ADO_NET using System.Data.SqlTypes; #endif @@ -38,6 +39,8 @@ namespace Newtonsoft.Json.Converters /// /// Converts a binary value to and from a base 64 string value. /// + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public class BinaryConverter : JsonConverter { #if HAVE_LINQ diff --git a/Src/Newtonsoft.Json/Converters/CustomCreationConverter.cs b/Src/Newtonsoft.Json/Converters/CustomCreationConverter.cs index f693ce57..ae3b2a5e 100644 --- a/Src/Newtonsoft.Json/Converters/CustomCreationConverter.cs +++ b/Src/Newtonsoft.Json/Converters/CustomCreationConverter.cs @@ -24,6 +24,7 @@ #endregion using System; +using System.Diagnostics.CodeAnalysis; using System.Reflection; using Newtonsoft.Json.Utilities; @@ -33,6 +34,8 @@ namespace Newtonsoft.Json.Converters /// Creates a custom object. /// /// The object type to convert. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public abstract class CustomCreationConverter : JsonConverter { /// diff --git a/Src/Newtonsoft.Json/Converters/DataSetConverter.cs b/Src/Newtonsoft.Json/Converters/DataSetConverter.cs index 214728e6..3b31915a 100644 --- a/Src/Newtonsoft.Json/Converters/DataSetConverter.cs +++ b/Src/Newtonsoft.Json/Converters/DataSetConverter.cs @@ -26,13 +26,17 @@ #if HAVE_ADO_NET using System; using System.Data; +using System.Diagnostics.CodeAnalysis; using Newtonsoft.Json.Serialization; +using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Converters { /// /// Converts a to and from JSON. /// + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public class DataSetConverter : JsonConverter { /// diff --git a/Src/Newtonsoft.Json/Converters/DataTableConverter.cs b/Src/Newtonsoft.Json/Converters/DataTableConverter.cs index 1a32e512..a5c50878 100644 --- a/Src/Newtonsoft.Json/Converters/DataTableConverter.cs +++ b/Src/Newtonsoft.Json/Converters/DataTableConverter.cs @@ -26,6 +26,7 @@ #if HAVE_ADO_NET using System.Collections; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using Newtonsoft.Json.Utilities; using System; @@ -37,6 +38,8 @@ namespace Newtonsoft.Json.Converters /// /// Converts a to and from JSON. /// + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public class DataTableConverter : JsonConverter { /// diff --git a/Src/Newtonsoft.Json/Converters/DiscriminatedUnionConverter.cs b/Src/Newtonsoft.Json/Converters/DiscriminatedUnionConverter.cs index c4c5d08a..93bc559e 100644 --- a/Src/Newtonsoft.Json/Converters/DiscriminatedUnionConverter.cs +++ b/Src/Newtonsoft.Json/Converters/DiscriminatedUnionConverter.cs @@ -28,6 +28,7 @@ using Newtonsoft.Json.Linq; using System; using System.Collections; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; #if !HAVE_LINQ using Newtonsoft.Json.Utilities.LinqBridge; #else @@ -43,6 +44,8 @@ namespace Newtonsoft.Json.Converters /// /// Converts a F# discriminated union type to and from JSON. /// + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public class DiscriminatedUnionConverter : JsonConverter { #region UnionDefinition diff --git a/Src/Newtonsoft.Json/Converters/EntityKeyMemberConverter.cs b/Src/Newtonsoft.Json/Converters/EntityKeyMemberConverter.cs index 757c8fac..947aeba9 100644 --- a/Src/Newtonsoft.Json/Converters/EntityKeyMemberConverter.cs +++ b/Src/Newtonsoft.Json/Converters/EntityKeyMemberConverter.cs @@ -26,6 +26,7 @@ #if HAVE_ENTITY_FRAMEWORK using System; using Newtonsoft.Json.Serialization; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using Newtonsoft.Json.Utilities; using System.Diagnostics; @@ -35,6 +36,8 @@ namespace Newtonsoft.Json.Converters /// /// Converts an Entity Framework to and from JSON. /// + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public class EntityKeyMemberConverter : JsonConverter { private const string EntityKeyMemberFullTypeName = "System.Data.EntityKeyMember"; @@ -157,7 +160,7 @@ namespace Newtonsoft.Json.Converters /// public override bool CanConvert(Type objectType) { - return objectType.AssignableToTypeName(EntityKeyMemberFullTypeName, false); + return objectType.AssignableToTypeName(EntityKeyMemberFullTypeName); } } } diff --git a/Src/Newtonsoft.Json/Converters/KeyValuePairConverter.cs b/Src/Newtonsoft.Json/Converters/KeyValuePairConverter.cs index 0221e933..14bc9544 100644 --- a/Src/Newtonsoft.Json/Converters/KeyValuePairConverter.cs +++ b/Src/Newtonsoft.Json/Converters/KeyValuePairConverter.cs @@ -25,6 +25,7 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Utilities; using System.Reflection; @@ -34,6 +35,8 @@ namespace Newtonsoft.Json.Converters /// /// Converts a to and from JSON. /// + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public class KeyValuePairConverter : JsonConverter { private const string KeyName = "Key"; diff --git a/Src/Newtonsoft.Json/Converters/RegexConverter.cs b/Src/Newtonsoft.Json/Converters/RegexConverter.cs index 13db1bb5..5868fc9b 100644 --- a/Src/Newtonsoft.Json/Converters/RegexConverter.cs +++ b/Src/Newtonsoft.Json/Converters/RegexConverter.cs @@ -24,6 +24,7 @@ #endregion using System; +using System.Diagnostics.CodeAnalysis; using System.Text.RegularExpressions; using Newtonsoft.Json.Bson; using System.Globalization; @@ -36,6 +37,8 @@ namespace Newtonsoft.Json.Converters /// /// Converts a to and from JSON and BSON. /// + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public class RegexConverter : JsonConverter { private const string PatternName = "Pattern"; diff --git a/Src/Newtonsoft.Json/Converters/StringEnumConverter.cs b/Src/Newtonsoft.Json/Converters/StringEnumConverter.cs index a9840080..5abb555b 100644 --- a/Src/Newtonsoft.Json/Converters/StringEnumConverter.cs +++ b/Src/Newtonsoft.Json/Converters/StringEnumConverter.cs @@ -27,6 +27,7 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; @@ -44,6 +45,8 @@ namespace Newtonsoft.Json.Converters /// /// Converts an to and from its name string value. /// + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public class StringEnumConverter : JsonConverter { /// diff --git a/Src/Newtonsoft.Json/Converters/XmlNodeConverter.cs b/Src/Newtonsoft.Json/Converters/XmlNodeConverter.cs index 12bde515..f4c0c193 100644 --- a/Src/Newtonsoft.Json/Converters/XmlNodeConverter.cs +++ b/Src/Newtonsoft.Json/Converters/XmlNodeConverter.cs @@ -2198,13 +2198,13 @@ namespace Newtonsoft.Json.Converters public override bool CanConvert(Type valueType) { #if HAVE_XLINQ - if (valueType.AssignableToTypeName("System.Xml.Linq.XObject", false)) + if (valueType.AssignableToTypeName("System.Xml.Linq.XObject")) { return IsXObject(valueType); } #endif #if HAVE_XML_DOCUMENT - if (valueType.AssignableToTypeName("System.Xml.XmlNode", false)) + if (valueType.AssignableToTypeName("System.Xml.XmlNode")) { return IsXmlNode(valueType); } diff --git a/Src/Newtonsoft.Json/JsonConvert.cs b/Src/Newtonsoft.Json/JsonConvert.cs index 1fa3f219..b507d43e 100644 --- a/Src/Newtonsoft.Json/JsonConvert.cs +++ b/Src/Newtonsoft.Json/JsonConvert.cs @@ -525,6 +525,8 @@ namespace Newtonsoft.Json /// The object to serialize. /// A JSON string representation of the object. [DebuggerStepThrough] + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static string SerializeObject(object? value) { return SerializeObject(value, null, (JsonSerializerSettings?)null); @@ -539,6 +541,8 @@ namespace Newtonsoft.Json /// A JSON string representation of the object. /// [DebuggerStepThrough] + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static string SerializeObject(object? value, Formatting formatting) { return SerializeObject(value, formatting, (JsonSerializerSettings?)null); @@ -551,6 +555,8 @@ namespace Newtonsoft.Json /// A collection of converters used while serializing. /// A JSON string representation of the object. [DebuggerStepThrough] + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static string SerializeObject(object? value, params JsonConverter[] converters) { JsonSerializerSettings? settings = (converters != null && converters.Length > 0) @@ -568,6 +574,8 @@ namespace Newtonsoft.Json /// A collection of converters used while serializing. /// A JSON string representation of the object. [DebuggerStepThrough] + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static string SerializeObject(object? value, Formatting formatting, params JsonConverter[] converters) { JsonSerializerSettings? settings = (converters != null && converters.Length > 0) @@ -587,6 +595,8 @@ namespace Newtonsoft.Json /// A JSON string representation of the object. /// [DebuggerStepThrough] + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static string SerializeObject(object? value, JsonSerializerSettings? settings) { return SerializeObject(value, null, settings); @@ -607,6 +617,8 @@ namespace Newtonsoft.Json /// A JSON string representation of the object. /// [DebuggerStepThrough] + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static string SerializeObject(object? value, Type? type, JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); @@ -625,6 +637,8 @@ namespace Newtonsoft.Json /// A JSON string representation of the object. /// [DebuggerStepThrough] + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static string SerializeObject(object? value, Formatting formatting, JsonSerializerSettings? settings) { return SerializeObject(value, null, formatting, settings); @@ -646,6 +660,8 @@ namespace Newtonsoft.Json /// A JSON string representation of the object. /// [DebuggerStepThrough] + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static string SerializeObject(object? value, Type? type, Formatting formatting, JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); @@ -654,6 +670,8 @@ namespace Newtonsoft.Json return SerializeObjectInternal(value, type, jsonSerializer); } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private static string SerializeObjectInternal(object? value, Type? type, JsonSerializer jsonSerializer) { StringBuilder sb = new StringBuilder(256); @@ -676,6 +694,8 @@ namespace Newtonsoft.Json /// The JSON to deserialize. /// The deserialized object from the JSON string. [DebuggerStepThrough] + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static object? DeserializeObject(string value) { return DeserializeObject(value, null, (JsonSerializerSettings?)null); @@ -691,6 +711,8 @@ namespace Newtonsoft.Json /// /// The deserialized object from the JSON string. [DebuggerStepThrough] + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static object? DeserializeObject(string value, JsonSerializerSettings settings) { return DeserializeObject(value, null, settings); @@ -703,6 +725,8 @@ namespace Newtonsoft.Json /// The of object being deserialized. /// The deserialized object from the JSON string. [DebuggerStepThrough] + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static object? DeserializeObject(string value, Type type) { return DeserializeObject(value, type, (JsonSerializerSettings?)null); @@ -715,6 +739,8 @@ namespace Newtonsoft.Json /// The JSON to deserialize. /// The deserialized object from the JSON string. [DebuggerStepThrough] + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static T? DeserializeObject(string value) { return DeserializeObject(value, (JsonSerializerSettings?)null); @@ -732,6 +758,8 @@ namespace Newtonsoft.Json /// The anonymous type object. /// The deserialized anonymous type from the JSON string. [DebuggerStepThrough] + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static T? DeserializeAnonymousType(string value, T anonymousTypeObject) { return DeserializeObject(value); @@ -753,6 +781,8 @@ namespace Newtonsoft.Json /// /// The deserialized anonymous type from the JSON string. [DebuggerStepThrough] + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static T? DeserializeAnonymousType(string value, T anonymousTypeObject, JsonSerializerSettings settings) { return DeserializeObject(value, settings); @@ -766,6 +796,8 @@ namespace Newtonsoft.Json /// Converters to use while deserializing. /// The deserialized object from the JSON string. [DebuggerStepThrough] + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static T? DeserializeObject(string value, params JsonConverter[] converters) { return (T?)DeserializeObject(value, typeof(T), converters); @@ -782,6 +814,8 @@ namespace Newtonsoft.Json /// /// The deserialized object from the JSON string. [DebuggerStepThrough] + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static T? DeserializeObject(string value, JsonSerializerSettings? settings) { return (T?)DeserializeObject(value, typeof(T), settings); @@ -795,6 +829,8 @@ namespace Newtonsoft.Json /// Converters to use while deserializing. /// The deserialized object from the JSON string. [DebuggerStepThrough] + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static object? DeserializeObject(string value, Type type, params JsonConverter[] converters) { JsonSerializerSettings? settings = (converters != null && converters.Length > 0) @@ -814,6 +850,8 @@ namespace Newtonsoft.Json /// If this is null, default serialization settings will be used. /// /// The deserialized object from the JSON string. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static object? DeserializeObject(string value, Type? type, JsonSerializerSettings? settings) { ValidationUtils.ArgumentNotNull(value, nameof(value)); @@ -840,6 +878,8 @@ namespace Newtonsoft.Json /// The JSON to populate values from. /// The target object to populate values onto. [DebuggerStepThrough] + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static void PopulateObject(string value, object target) { PopulateObject(value, target, null); @@ -854,6 +894,8 @@ namespace Newtonsoft.Json /// The used to deserialize the object. /// If this is null, default serialization settings will be used. /// + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static void PopulateObject(string value, object target, JsonSerializerSettings? settings) { JsonSerializer jsonSerializer = JsonSerializer.CreateDefault(settings); @@ -883,6 +925,8 @@ namespace Newtonsoft.Json /// /// The node to serialize. /// A JSON string of the . + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static string SerializeXmlNode(XmlNode? node) { return SerializeXmlNode(node, Formatting.None); @@ -894,6 +938,8 @@ namespace Newtonsoft.Json /// The node to serialize. /// Indicates how the output should be formatted. /// A JSON string of the . + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static string SerializeXmlNode(XmlNode? node, Formatting formatting) { XmlNodeConverter converter = new XmlNodeConverter(); @@ -908,6 +954,8 @@ namespace Newtonsoft.Json /// Indicates how the output should be formatted. /// Omits writing the root object. /// A JSON string of the . + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static string SerializeXmlNode(XmlNode? node, Formatting formatting, bool omitRootObject) { XmlNodeConverter converter = new XmlNodeConverter { OmitRootObject = omitRootObject }; @@ -920,6 +968,8 @@ namespace Newtonsoft.Json /// /// The JSON string. /// The deserialized . + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static XmlDocument? DeserializeXmlNode(string value) { return DeserializeXmlNode(value, null); @@ -931,6 +981,8 @@ namespace Newtonsoft.Json /// The JSON string. /// The name of the root element to append when deserializing. /// The deserialized . + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName) { return DeserializeXmlNode(value, deserializeRootElementName, false); @@ -947,6 +999,8 @@ namespace Newtonsoft.Json /// This attribute helps preserve arrays when converting the written XML back to JSON. /// /// The deserialized . + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute) { return DeserializeXmlNode(value, deserializeRootElementName, writeArrayAttribute, false); @@ -969,6 +1023,8 @@ namespace Newtonsoft.Json /// as part of the XML element name. /// /// The deserialized . + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static XmlDocument? DeserializeXmlNode(string value, string? deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters) { XmlNodeConverter converter = new XmlNodeConverter(); @@ -986,6 +1042,8 @@ namespace Newtonsoft.Json /// /// The node to convert to JSON. /// A JSON string of the . + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static string SerializeXNode(XObject? node) { return SerializeXNode(node, Formatting.None); @@ -997,6 +1055,8 @@ namespace Newtonsoft.Json /// The node to convert to JSON. /// Indicates how the output should be formatted. /// A JSON string of the . + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static string SerializeXNode(XObject? node, Formatting formatting) { return SerializeXNode(node, formatting, false); @@ -1009,6 +1069,8 @@ namespace Newtonsoft.Json /// Indicates how the output should be formatted. /// Omits writing the root object. /// A JSON string of the . + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static string SerializeXNode(XObject? node, Formatting formatting, bool omitRootObject) { XmlNodeConverter converter = new XmlNodeConverter { OmitRootObject = omitRootObject }; @@ -1021,6 +1083,8 @@ namespace Newtonsoft.Json /// /// The JSON string. /// The deserialized . + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static XDocument? DeserializeXNode(string value) { return DeserializeXNode(value, null); @@ -1032,6 +1096,8 @@ namespace Newtonsoft.Json /// The JSON string. /// The name of the root element to append when deserializing. /// The deserialized . + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName) { return DeserializeXNode(value, deserializeRootElementName, false); @@ -1048,6 +1114,8 @@ namespace Newtonsoft.Json /// This attribute helps preserve arrays when converting the written XML back to JSON. /// /// The deserialized . + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute) { return DeserializeXNode(value, deserializeRootElementName, writeArrayAttribute, false); @@ -1070,6 +1138,8 @@ namespace Newtonsoft.Json /// as part of the XML element name. /// /// The deserialized . + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static XDocument? DeserializeXNode(string value, string? deserializeRootElementName, bool writeArrayAttribute, bool encodeSpecialCharacters) { XmlNodeConverter converter = new XmlNodeConverter(); diff --git a/Src/Newtonsoft.Json/JsonSerializer.cs b/Src/Newtonsoft.Json/JsonSerializer.cs index 13e3a9c6..b72625df 100644 --- a/Src/Newtonsoft.Json/JsonSerializer.cs +++ b/Src/Newtonsoft.Json/JsonSerializer.cs @@ -44,6 +44,8 @@ namespace Newtonsoft.Json /// Serializes and deserializes objects into and from the JSON format. /// The enables you to control how objects are encoded into JSON. /// + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public class JsonSerializer { internal TypeNameHandling _typeNameHandling; diff --git a/Src/Newtonsoft.Json/Linq/JArray.Async.cs b/Src/Newtonsoft.Json/Linq/JArray.Async.cs index 25ffe4ef..f80556a3 100644 --- a/Src/Newtonsoft.Json/Linq/JArray.Async.cs +++ b/Src/Newtonsoft.Json/Linq/JArray.Async.cs @@ -25,6 +25,7 @@ #if HAVE_ASYNC +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Threading; using System.Threading.Tasks; @@ -41,6 +42,8 @@ namespace Newtonsoft.Json.Linq /// The token to monitor for cancellation requests. /// A collection of which will be used when writing the token. /// A that represents the asynchronous write operation. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public override async Task WriteToAsync(JsonWriter writer, CancellationToken cancellationToken, params JsonConverter[] converters) { await writer.WriteStartArrayAsync(cancellationToken).ConfigureAwait(false); diff --git a/Src/Newtonsoft.Json/Linq/JArray.cs b/Src/Newtonsoft.Json/Linq/JArray.cs index c589e211..2abe6d1a 100644 --- a/Src/Newtonsoft.Json/Linq/JArray.cs +++ b/Src/Newtonsoft.Json/Linq/JArray.cs @@ -26,6 +26,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using Newtonsoft.Json.Utilities; using System.IO; using System.Globalization; @@ -188,6 +189,8 @@ namespace Newtonsoft.Json.Linq /// /// The object that will be used to create . /// A with the values of the specified object. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public new static JArray FromObject(object o) { return FromObject(o, JsonSerializer.CreateDefault()); @@ -199,6 +202,8 @@ namespace Newtonsoft.Json.Linq /// The object that will be used to create . /// The that will be used to read the object. /// A with the values of the specified object. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public new static JArray FromObject(object o, JsonSerializer jsonSerializer) { JToken token = FromObjectInternal(o, jsonSerializer); @@ -216,6 +221,8 @@ namespace Newtonsoft.Json.Linq /// /// A into which this method will write. /// A collection of which will be used when writing the token. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public override void WriteTo(JsonWriter writer, params JsonConverter[] converters) { writer.WriteStartArray(); diff --git a/Src/Newtonsoft.Json/Linq/JConstructor.Async.cs b/Src/Newtonsoft.Json/Linq/JConstructor.Async.cs index bdbeff69..5b69dfc7 100644 --- a/Src/Newtonsoft.Json/Linq/JConstructor.Async.cs +++ b/Src/Newtonsoft.Json/Linq/JConstructor.Async.cs @@ -25,6 +25,7 @@ #if HAVE_ASYNC +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Threading; using System.Threading.Tasks; @@ -41,6 +42,8 @@ namespace Newtonsoft.Json.Linq /// The token to monitor for cancellation requests. /// A collection of which will be used when writing the token. /// A that represents the asynchronous write operation. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public override async Task WriteToAsync(JsonWriter writer, CancellationToken cancellationToken, params JsonConverter[] converters) { await writer.WriteStartConstructorAsync(_name ?? string.Empty, cancellationToken).ConfigureAwait(false); diff --git a/Src/Newtonsoft.Json/Linq/JConstructor.cs b/Src/Newtonsoft.Json/Linq/JConstructor.cs index 703dbbc1..d29c2b89 100644 --- a/Src/Newtonsoft.Json/Linq/JConstructor.cs +++ b/Src/Newtonsoft.Json/Linq/JConstructor.cs @@ -26,6 +26,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using Newtonsoft.Json.Utilities; using System.Globalization; @@ -163,6 +164,8 @@ namespace Newtonsoft.Json.Linq /// /// A into which this method will write. /// A collection of which will be used when writing the token. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public override void WriteTo(JsonWriter writer, params JsonConverter[] converters) { writer.WriteStartConstructor(_name!); diff --git a/Src/Newtonsoft.Json/Linq/JContainer.cs b/Src/Newtonsoft.Json/Linq/JContainer.cs index e19be361..dd9ef762 100644 --- a/Src/Newtonsoft.Json/Linq/JContainer.cs +++ b/Src/Newtonsoft.Json/Linq/JContainer.cs @@ -959,9 +959,17 @@ namespace Newtonsoft.Json.Linq PropertyDescriptorCollection ITypedList.GetItemProperties(PropertyDescriptor[] listAccessors) { +#if HAVE_APPCONTEXT + if (!ComponentModelIsSupported) + { + throw new NotSupportedException(ComponentModelNotSupportedMessage); + } +#endif ICustomTypeDescriptor? d = First as ICustomTypeDescriptor; +#pragma warning disable IL2026 return d?.GetProperties() ?? new PropertyDescriptorCollection(CollectionUtils.ArrayEmpty()); +#pragma warning restore IL2026 } #endif diff --git a/Src/Newtonsoft.Json/Linq/JObject.Async.cs b/Src/Newtonsoft.Json/Linq/JObject.Async.cs index 67f01fe5..c317b31e 100644 --- a/Src/Newtonsoft.Json/Linq/JObject.Async.cs +++ b/Src/Newtonsoft.Json/Linq/JObject.Async.cs @@ -26,6 +26,7 @@ #if HAVE_ASYNC using System; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Threading; using System.Threading.Tasks; @@ -42,6 +43,8 @@ namespace Newtonsoft.Json.Linq /// The token to monitor for cancellation requests. /// A collection of which will be used when writing the token. /// A that represents the asynchronous write operation. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public override Task WriteToAsync(JsonWriter writer, CancellationToken cancellationToken, params JsonConverter[] converters) { Task t = writer.WriteStartObjectAsync(cancellationToken); @@ -62,6 +65,7 @@ namespace Newtonsoft.Json.Linq return writer.WriteEndObjectAsync(cancellationToken); // Local functions, params renamed (capitalized) so as not to capture and allocate when calling async + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] async Task AwaitProperties(Task task, int i, JsonWriter Writer, CancellationToken CancellationToken, JsonConverter[] Converters) { await task.ConfigureAwait(false); diff --git a/Src/Newtonsoft.Json/Linq/JObject.cs b/Src/Newtonsoft.Json/Linq/JObject.cs index fab460da..41d64347 100644 --- a/Src/Newtonsoft.Json/Linq/JObject.cs +++ b/Src/Newtonsoft.Json/Linq/JObject.cs @@ -485,6 +485,8 @@ namespace Newtonsoft.Json.Linq /// /// The object that will be used to create . /// A with the values of the specified object. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public new static JObject FromObject(object o) { return FromObject(o, JsonSerializer.CreateDefault()); @@ -496,6 +498,8 @@ namespace Newtonsoft.Json.Linq /// The object that will be used to create . /// The that will be used to read the object. /// A with the values of the specified object. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public new static JObject FromObject(object o, JsonSerializer jsonSerializer) { JToken token = FromObjectInternal(o, jsonSerializer); @@ -513,6 +517,8 @@ namespace Newtonsoft.Json.Linq /// /// A into which this method will write. /// A collection of which will be used when writing the token. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public override void WriteTo(JsonWriter writer, params JsonConverter[] converters) { writer.WriteStartObject(); @@ -742,11 +748,13 @@ namespace Newtonsoft.Json.Linq // include custom type descriptor on JObject rather than use a provider because the properties are specific to a type #region ICustomTypeDescriptor + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties() { return ((ICustomTypeDescriptor)this).GetProperties(null); } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] PropertyDescriptorCollection ICustomTypeDescriptor.GetProperties(Attribute[]? attributes) { PropertyDescriptor[] propertiesArray = new PropertyDescriptor[Count]; @@ -775,26 +783,31 @@ namespace Newtonsoft.Json.Linq return null; } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] TypeConverter ICustomTypeDescriptor.GetConverter() { return new TypeConverter(); } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] EventDescriptor? ICustomTypeDescriptor.GetDefaultEvent() { return null; } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] PropertyDescriptor? ICustomTypeDescriptor.GetDefaultProperty() { return null; } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] object? ICustomTypeDescriptor.GetEditor(Type editorBaseType) { return null; } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] EventDescriptorCollection ICustomTypeDescriptor.GetEvents(Attribute[]? attributes) { return EventDescriptorCollection.Empty; @@ -828,7 +841,15 @@ namespace Newtonsoft.Json.Linq /// protected override DynamicMetaObject GetMetaObject(Expression parameter) { +#if HAVE_APPCONTEXT + if (!DynamicIsSupported) + { + throw new NotSupportedException(DynamicNotSupportedMessage); + } +#endif +#pragma warning disable IL2026, IL3050 return new DynamicProxyMetaObject(parameter, this, new JObjectDynamicProxy()); +#pragma warning restore IL2026, IL3050 } private class JObjectDynamicProxy : DynamicProxy diff --git a/Src/Newtonsoft.Json/Linq/JProperty.Async.cs b/Src/Newtonsoft.Json/Linq/JProperty.Async.cs index d1e845dc..d632f51b 100644 --- a/Src/Newtonsoft.Json/Linq/JProperty.Async.cs +++ b/Src/Newtonsoft.Json/Linq/JProperty.Async.cs @@ -25,6 +25,7 @@ #if HAVE_ASYNC +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Threading; using System.Threading.Tasks; @@ -41,6 +42,8 @@ namespace Newtonsoft.Json.Linq /// The token to monitor for cancellation requests. /// A collection of which will be used when writing the token. /// A that represents the asynchronous write operation. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public override Task WriteToAsync(JsonWriter writer, CancellationToken cancellationToken, params JsonConverter[] converters) { Task task = writer.WritePropertyNameAsync(_name, cancellationToken); @@ -52,6 +55,8 @@ namespace Newtonsoft.Json.Linq return WriteToAsync(task, writer, cancellationToken, converters); } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private async Task WriteToAsync(Task task, JsonWriter writer, CancellationToken cancellationToken, params JsonConverter[] converters) { await task.ConfigureAwait(false); @@ -59,6 +64,8 @@ namespace Newtonsoft.Json.Linq await WriteValueAsync(writer, cancellationToken, converters).ConfigureAwait(false); } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private Task WriteValueAsync(JsonWriter writer, CancellationToken cancellationToken, JsonConverter[] converters) { JToken value = Value; diff --git a/Src/Newtonsoft.Json/Linq/JProperty.cs b/Src/Newtonsoft.Json/Linq/JProperty.cs index b8c7ace6..5645d239 100644 --- a/Src/Newtonsoft.Json/Linq/JProperty.cs +++ b/Src/Newtonsoft.Json/Linq/JProperty.cs @@ -26,6 +26,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using Newtonsoft.Json.Utilities; using System.Diagnostics; using System.Globalization; @@ -342,6 +343,8 @@ namespace Newtonsoft.Json.Linq /// /// A into which this method will write. /// A collection of which will be used when writing the token. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public override void WriteTo(JsonWriter writer, params JsonConverter[] converters) { writer.WritePropertyName(_name); diff --git a/Src/Newtonsoft.Json/Linq/JToken.Async.cs b/Src/Newtonsoft.Json/Linq/JToken.Async.cs index 4d147c2d..9ace19ac 100644 --- a/Src/Newtonsoft.Json/Linq/JToken.Async.cs +++ b/Src/Newtonsoft.Json/Linq/JToken.Async.cs @@ -26,6 +26,7 @@ #if HAVE_ASYNC using System; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Threading; using System.Threading.Tasks; @@ -42,6 +43,8 @@ namespace Newtonsoft.Json.Linq /// The token to monitor for cancellation requests. /// A collection of which will be used when writing the token. /// A that represents the asynchronous write operation. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public virtual Task WriteToAsync(JsonWriter writer, CancellationToken cancellationToken, params JsonConverter[] converters) { throw new NotImplementedException(); @@ -53,11 +56,38 @@ namespace Newtonsoft.Json.Linq /// A into which this method will write. /// A collection of which will be used when writing the token. /// A that represents the asynchronous write operation. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public Task WriteToAsync(JsonWriter writer, params JsonConverter[] converters) { return WriteToAsync(writer, default, converters); } + /// + /// Writes this token to a asynchronously. + /// + /// A into which this method will write. + /// The token to monitor for cancellation requests. + /// A that represents the asynchronous write operation. + [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "WriteToAsync without converters is safe.")] + [UnconditionalSuppressMessage("AOT", "IL3050", Justification = "WriteToAsync without converters is safe.")] + public Task WriteToAsync(JsonWriter writer, CancellationToken cancellationToken) + { + return WriteToAsync(writer, default, CollectionUtils.ArrayEmpty()); + } + + /// + /// Writes this token to a asynchronously. + /// + /// A into which this method will write. + /// A that represents the asynchronous write operation. + [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "WriteToAsync without converters is safe.")] + [UnconditionalSuppressMessage("AOT", "IL3050", Justification = "WriteToAsync without converters is safe.")] + public Task WriteToAsync(JsonWriter writer) + { + return WriteToAsync(writer, default, CollectionUtils.ArrayEmpty()); + } + /// /// Asynchronously creates a from a . /// diff --git a/Src/Newtonsoft.Json/Linq/JToken.cs b/Src/Newtonsoft.Json/Linq/JToken.cs index 27f84d8b..c01e51e4 100644 --- a/Src/Newtonsoft.Json/Linq/JToken.cs +++ b/Src/Newtonsoft.Json/Linq/JToken.cs @@ -80,6 +80,33 @@ namespace Newtonsoft.Json.Linq private static readonly JTokenType[] DateTimeTypes = new[] { JTokenType.Date, JTokenType.String, JTokenType.Comment, JTokenType.Raw }; private static readonly JTokenType[] BytesTypes = new[] { JTokenType.Bytes, JTokenType.String, JTokenType.Comment, JTokenType.Raw, JTokenType.Integer }; +#if HAVE_APPCONTEXT + [FeatureSwitchDefinition("Newtonsoft.Json.Linq.JToken.SerializationIsSupported")] + [FeatureGuard(typeof(RequiresUnreferencedCodeAttribute))] + [FeatureGuard(typeof(RequiresDynamicCodeAttribute))] + internal static bool SerializationIsSupported => AppContext.TryGetSwitch("Newtonsoft.Json.Linq.JToken.SerializationIsSupported", out bool isSupported) ? isSupported : true; + + internal const string SerializationNotSupportedMessage = "Newtonsoft.Json serialization is not compatible with trimming and has been disabled. Newtonsoft.Json.Linq.JToken.SerializationIsSupported is set to false."; + +#if HAVE_COMPONENT_MODEL + [FeatureSwitchDefinition("Newtonsoft.Json.Linq.JToken.ComponentModelIsSupported")] + [FeatureGuard(typeof(RequiresUnreferencedCodeAttribute))] + internal static bool ComponentModelIsSupported => AppContext.TryGetSwitch("Newtonsoft.Json.Linq.JToken.ComponentModelIsSupported", out bool isSupported) ? isSupported : true; + + internal const string ComponentModelNotSupportedMessage = "Newtonsoft.Json support for System.ComponentModel is not compatible with trimming and has been disabled. Newtonsoft.Json.Linq.JToken.ComponentModelIsSupported is set to false."; +#endif // HAVE_COMPONENT_MODEL + +#if HAVE_DYNAMIC + [FeatureSwitchDefinition("Newtonsoft.Json.Linq.JToken.DynamicIsSupported")] + [FeatureGuard(typeof(RequiresUnreferencedCodeAttribute))] + [FeatureGuard(typeof(RequiresDynamicCodeAttribute))] + internal static bool DynamicIsSupported => AppContext.TryGetSwitch("Newtonsoft.Json.Linq.JToken.DynamicIsSupported", out bool isSupported) ? isSupported : true; + + internal const string DynamicNotSupportedMessage = "Newtonsoft.Json support for dynamic is not compatible with trimming and has been disabled. Newtonsoft.Json.Linq.JToken.DynamicIsSupported is set to false."; +#endif // HAVE_DYNAMIC + +#endif // HAVE_APPCONTEXT + /// /// Gets a comparer that can compare two tokens for value equality. /// @@ -411,11 +438,24 @@ namespace Newtonsoft.Json.Linq _parent.ReplaceItem(this, value); } + /// + /// Writes this token to a . + /// + /// A into which this method will write. + [UnconditionalSuppressMessage("Trimming", "IL2026", Justification = "WriteTo without converters is safe.")] + [UnconditionalSuppressMessage("AOT", "IL3050", Justification = "WriteTo without converters is safe.")] + public void WriteTo(JsonWriter writer) + { + WriteTo(writer, CollectionUtils.ArrayEmpty()); + } + /// /// Writes this token to a . /// /// A into which this method will write. /// A collection of which will be used when writing the token. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public abstract void WriteTo(JsonWriter writer, params JsonConverter[] converters); /// @@ -433,12 +473,32 @@ namespace Newtonsoft.Json.Linq return ToString(Formatting.Indented); } + /// + /// Returns the JSON for this token using the given formatting and converters. + /// + /// Indicates how the output should be formatted. + /// The JSON for this token using the given formatting and converters. + public string ToString(Formatting formatting) + { + using (StringWriter sw = new StringWriter(CultureInfo.InvariantCulture)) + { + JsonTextWriter jw = new JsonTextWriter(sw); + jw.Formatting = formatting; + + WriteTo(jw); + + return sw.ToString(); + } + } + /// /// Returns the JSON for this token using the given formatting and converters. /// /// Indicates how the output should be formatted. /// A collection of s which will be used when writing the token. /// The JSON for this token using the given formatting and converters. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public string ToString(Formatting formatting, params JsonConverter[] converters) { using (StringWriter sw = new StringWriter(CultureInfo.InvariantCulture)) @@ -1889,6 +1949,8 @@ namespace Newtonsoft.Json.Linq return new JTokenReader(this); } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] internal static JToken FromObjectInternal(object o, JsonSerializer jsonSerializer) { ValidationUtils.ArgumentNotNull(o, nameof(o)); @@ -1909,6 +1971,8 @@ namespace Newtonsoft.Json.Linq /// /// The object that will be used to create . /// A with the value of the specified object. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static JToken FromObject(object o) { return FromObjectInternal(o, JsonSerializer.CreateDefault()); @@ -1920,6 +1984,8 @@ namespace Newtonsoft.Json.Linq /// The object that will be used to create . /// The that will be used when reading the object. /// A with the value of the specified object. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static JToken FromObject(object o, JsonSerializer jsonSerializer) { return FromObjectInternal(o, jsonSerializer); @@ -1930,6 +1996,8 @@ namespace Newtonsoft.Json.Linq /// /// The object type that the token will be deserialized to. /// The new object created from the JSON value. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public T? ToObject() { return (T?)ToObject(typeof(T)); @@ -1940,6 +2008,8 @@ namespace Newtonsoft.Json.Linq /// /// The object type that the token will be deserialized to. /// The new object created from the JSON value. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public object? ToObject(Type objectType) { if (JsonConvert.DefaultSettings == null) @@ -2063,6 +2133,8 @@ namespace Newtonsoft.Json.Linq /// The object type that the token will be deserialized to. /// The that will be used when creating the object. /// The new object created from the JSON value. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public T? ToObject(JsonSerializer jsonSerializer) { return (T?)ToObject(typeof(T), jsonSerializer); @@ -2074,6 +2146,8 @@ namespace Newtonsoft.Json.Linq /// The object type that the token will be deserialized to. /// The that will be used when creating the object. /// The new object created from the JSON value. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public object? ToObject(Type? objectType, JsonSerializer jsonSerializer) { ValidationUtils.ArgumentNotNull(jsonSerializer, nameof(jsonSerializer)); @@ -2414,7 +2488,15 @@ namespace Newtonsoft.Json.Linq /// protected virtual DynamicMetaObject GetMetaObject(Expression parameter) { +#if HAVE_APPCONTEXT + if (!DynamicIsSupported) + { + throw new NotSupportedException(DynamicNotSupportedMessage); + } +#endif +#pragma warning disable IL2026, IL3050 return new DynamicProxyMetaObject(parameter, this, new DynamicProxy()); +#pragma warning restore IL2026, IL3050 } /// diff --git a/Src/Newtonsoft.Json/Linq/JValue.Async.cs b/Src/Newtonsoft.Json/Linq/JValue.Async.cs index e80b880a..e8808a4a 100644 --- a/Src/Newtonsoft.Json/Linq/JValue.Async.cs +++ b/Src/Newtonsoft.Json/Linq/JValue.Async.cs @@ -26,6 +26,7 @@ #if HAVE_ASYNC using System; +using System.Diagnostics.CodeAnalysis; using System.Globalization; #if HAVE_BIG_INTEGER using System.Numerics; @@ -45,6 +46,8 @@ namespace Newtonsoft.Json.Linq /// The token to monitor for cancellation requests. /// A collection of which will be used when writing the token. /// A that represents the asynchronous write operation. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public override Task WriteToAsync(JsonWriter writer, CancellationToken cancellationToken, params JsonConverter[] converters) { if (converters != null && converters.Length > 0 && _value != null) diff --git a/Src/Newtonsoft.Json/Linq/JValue.cs b/Src/Newtonsoft.Json/Linq/JValue.cs index c2f03991..7568960d 100644 --- a/Src/Newtonsoft.Json/Linq/JValue.cs +++ b/Src/Newtonsoft.Json/Linq/JValue.cs @@ -727,6 +727,8 @@ namespace Newtonsoft.Json.Linq /// /// A into which this method will write. /// A collection of s which will be used when writing the token. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public override void WriteTo(JsonWriter writer, params JsonConverter[] converters) { if (converters != null && converters.Length > 0 && _value != null) @@ -972,9 +974,19 @@ namespace Newtonsoft.Json.Linq /// protected override DynamicMetaObject GetMetaObject(Expression parameter) { +#if HAVE_APPCONTEXT + if (!DynamicIsSupported) + { + throw new NotSupportedException(DynamicNotSupportedMessage); + } +#endif +#pragma warning disable IL2026, IL3050 return new DynamicProxyMetaObject(parameter, this, new JValueDynamicProxy()); +#pragma warning restore IL2026, IL3050 } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private class JValueDynamicProxy : DynamicProxy { public override bool TryConvert(JValue instance, ConvertBinder binder, [NotNullWhen(true)]out object? result) @@ -1188,7 +1200,15 @@ namespace Newtonsoft.Json.Linq object IConvertible.ToType(Type conversionType, IFormatProvider? provider) { +#if HAVE_APPCONTEXT + if (!SerializationIsSupported) + { + throw new NotSupportedException(SerializationNotSupportedMessage); + } +#endif +#pragma warning disable IL2026, IL3050 return ToObject(conversionType)!; +#pragma warning restore IL2026, IL3050 } #endif } diff --git a/Src/Newtonsoft.Json/Newtonsoft.Json.csproj b/Src/Newtonsoft.Json/Newtonsoft.Json.csproj index 47c63018..fe606797 100644 --- a/Src/Newtonsoft.Json/Newtonsoft.Json.csproj +++ b/Src/Newtonsoft.Json/Newtonsoft.Json.csproj @@ -1,6 +1,6 @@  - net6.0;net45;net40;net35;net20;netstandard1.0;netstandard1.3;netstandard2.0 + net8.0;net6.0;net45;net40;net35;net20;netstandard1.0;netstandard1.3;netstandard2.0 $(LibraryFrameworks) 9.0 @@ -40,6 +40,12 @@ Disable that warning since local builds do not strong-name sign the assembly, causing a mistmatch when comparing the previously shipped assemblies and current.--> $(NoWarn);CP0003 + + + true + true + true @@ -51,9 +57,13 @@ + + Json.NET .NET 8.0 + HAVE_APPCONTEXT;HAVE_ADO_NET;HAVE_APP_DOMAIN;HAVE_ASYNC;HAVE_ASYNC_DISPOSABLE;HAVE_BIG_INTEGER;HAVE_BINARY_FORMATTER;HAVE_BINARY_SERIALIZATION;HAVE_BINARY_EXCEPTION_SERIALIZATION;HAVE_CHAR_TO_LOWER_WITH_CULTURE;HAVE_CHAR_TO_STRING_WITH_CULTURE;HAVE_COM_ATTRIBUTES;HAVE_COMPONENT_MODEL;HAVE_CONCURRENT_COLLECTIONS;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DB_NULL_TYPE_CODE;HAVE_DYNAMIC;HAVE_EMPTY_TYPES;HAVE_ENTITY_FRAMEWORK;HAVE_EXPRESSIONS;HAVE_FAST_REVERSE;HAVE_FSHARP_TYPES;HAVE_FULL_REFLECTION;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_ICLONEABLE;HAVE_ICONVERTIBLE;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_INOTIFY_PROPERTY_CHANGING;HAVE_ISET;HAVE_LINQ;HAVE_MEMORY_BARRIER;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_REFLECTION_EMIT;HAVE_REGEX_TIMEOUTS;HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STREAM_READER_WRITER_CLOSE;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TRACE_WRITER;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_XML_DOCUMENT;HAVE_XML_DOCUMENT_TYPE;HAVE_CONCURRENT_DICTIONARY;HAVE_INDEXOF_STRING_COMPARISON;HAVE_REPLACE_STRING_COMPARISON;HAVE_REPLACE_STRING_COMPARISON;HAVE_GETHASHCODE_STRING_COMPARISON;HAVE_NULLABLE_ATTRIBUTES;HAVE_DYNAMIC_CODE_COMPILED;HAS_ARRAY_EMPTY;HAVE_DATE_ONLY;$(AdditionalConstants) + Json.NET .NET 6.0 - HAVE_ADO_NET;HAVE_APP_DOMAIN;HAVE_ASYNC;HAVE_ASYNC_DISPOSABLE;HAVE_BIG_INTEGER;HAVE_BINARY_FORMATTER;HAVE_BINARY_SERIALIZATION;HAVE_BINARY_EXCEPTION_SERIALIZATION;HAVE_CHAR_TO_LOWER_WITH_CULTURE;HAVE_CHAR_TO_STRING_WITH_CULTURE;HAVE_COM_ATTRIBUTES;HAVE_COMPONENT_MODEL;HAVE_CONCURRENT_COLLECTIONS;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DB_NULL_TYPE_CODE;HAVE_DYNAMIC;HAVE_EMPTY_TYPES;HAVE_ENTITY_FRAMEWORK;HAVE_EXPRESSIONS;HAVE_FAST_REVERSE;HAVE_FSHARP_TYPES;HAVE_FULL_REFLECTION;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_ICLONEABLE;HAVE_ICONVERTIBLE;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_INOTIFY_PROPERTY_CHANGING;HAVE_ISET;HAVE_LINQ;HAVE_MEMORY_BARRIER;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_REFLECTION_EMIT;HAVE_REGEX_TIMEOUTS;HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STREAM_READER_WRITER_CLOSE;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TRACE_WRITER;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_XML_DOCUMENT;HAVE_XML_DOCUMENT_TYPE;HAVE_CONCURRENT_DICTIONARY;HAVE_INDEXOF_STRING_COMPARISON;HAVE_REPLACE_STRING_COMPARISON;HAVE_REPLACE_STRING_COMPARISON;HAVE_GETHASHCODE_STRING_COMPARISON;HAVE_NULLABLE_ATTRIBUTES;HAVE_DYNAMIC_CODE_COMPILED;HAS_ARRAY_EMPTY;HAVE_DATE_ONLY;$(AdditionalConstants) + HAVE_APPCONTEXT;HAVE_ADO_NET;HAVE_APP_DOMAIN;HAVE_ASYNC;HAVE_ASYNC_DISPOSABLE;HAVE_BIG_INTEGER;HAVE_BINARY_FORMATTER;HAVE_BINARY_SERIALIZATION;HAVE_BINARY_EXCEPTION_SERIALIZATION;HAVE_CHAR_TO_LOWER_WITH_CULTURE;HAVE_CHAR_TO_STRING_WITH_CULTURE;HAVE_COM_ATTRIBUTES;HAVE_COMPONENT_MODEL;HAVE_CONCURRENT_COLLECTIONS;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DB_NULL_TYPE_CODE;HAVE_DYNAMIC;HAVE_EMPTY_TYPES;HAVE_ENTITY_FRAMEWORK;HAVE_EXPRESSIONS;HAVE_FAST_REVERSE;HAVE_FSHARP_TYPES;HAVE_FULL_REFLECTION;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_ICLONEABLE;HAVE_ICONVERTIBLE;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_INOTIFY_PROPERTY_CHANGING;HAVE_ISET;HAVE_LINQ;HAVE_MEMORY_BARRIER;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_REFLECTION_EMIT;HAVE_REGEX_TIMEOUTS;HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STREAM_READER_WRITER_CLOSE;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TRACE_WRITER;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_XML_DOCUMENT;HAVE_XML_DOCUMENT_TYPE;HAVE_CONCURRENT_DICTIONARY;HAVE_INDEXOF_STRING_COMPARISON;HAVE_REPLACE_STRING_COMPARISON;HAVE_REPLACE_STRING_COMPARISON;HAVE_GETHASHCODE_STRING_COMPARISON;HAVE_NULLABLE_ATTRIBUTES;HAVE_DYNAMIC_CODE_COMPILED;HAS_ARRAY_EMPTY;HAVE_DATE_ONLY;$(AdditionalConstants) Json.NET .NET 4.5 @@ -86,10 +96,10 @@ Json.NET .NET Standard 1.3 - NETSTANDARD1_3;PORTABLE;HAVE_ASYNC;HAVE_BIG_INTEGER;HAVE_BINARY_SERIALIZATION;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DYNAMIC;HAVE_EXPRESSIONS;HAVE_FSHARP_TYPES;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_INOTIFY_PROPERTY_CHANGING;HAVE_ISET;HAVE_LINQ;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_REFLECTION_BINDER;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_OBSOLETE_FORMATTER_ASSEMBLY_STYLE;HAVE_XML_DOCUMENT;HAVE_CONCURRENT_DICTIONARY;HAVE_ICONVERTIBLE;HAVE_REGEX_TIMEOUTS;HAVE_REGEX_TIMEOUTS;$(AdditionalConstants) + HAVE_APPCONTEXT;NETSTANDARD1_3;PORTABLE;HAVE_ASYNC;HAVE_BIG_INTEGER;HAVE_BINARY_SERIALIZATION;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DYNAMIC;HAVE_EXPRESSIONS;HAVE_FSHARP_TYPES;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_INOTIFY_PROPERTY_CHANGING;HAVE_ISET;HAVE_LINQ;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_REFLECTION_BINDER;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_OBSOLETE_FORMATTER_ASSEMBLY_STYLE;HAVE_XML_DOCUMENT;HAVE_CONCURRENT_DICTIONARY;HAVE_ICONVERTIBLE;HAVE_REGEX_TIMEOUTS;HAVE_REGEX_TIMEOUTS;$(AdditionalConstants) Json.NET .NET Standard 2.0 - NETSTANDARD2_0;HAVE_ADO_NET;HAVE_APP_DOMAIN;HAVE_ASYNC;HAVE_BIG_INTEGER;HAVE_BINARY_FORMATTER;HAVE_BINARY_SERIALIZATION;HAVE_BINARY_EXCEPTION_SERIALIZATION;HAVE_CHAR_TO_LOWER_WITH_CULTURE;HAVE_CHAR_TO_STRING_WITH_CULTURE;HAVE_COM_ATTRIBUTES;HAVE_COMPONENT_MODEL;HAVE_CONCURRENT_COLLECTIONS;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DB_NULL_TYPE_CODE;HAVE_DYNAMIC;HAVE_EMPTY_TYPES;HAVE_ENTITY_FRAMEWORK;HAVE_EXPRESSIONS;HAVE_FAST_REVERSE;HAVE_FSHARP_TYPES;HAVE_FULL_REFLECTION;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_ICLONEABLE;HAVE_ICONVERTIBLE;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_INOTIFY_PROPERTY_CHANGING;HAVE_ISET;HAVE_LINQ;HAVE_MEMORY_BARRIER;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STREAM_READER_WRITER_CLOSE;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TRACE_WRITER;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_XML_DOCUMENT;HAVE_XML_DOCUMENT_TYPE;HAVE_CONCURRENT_DICTIONARY;HAVE_REGEX_TIMEOUTS;$(AdditionalConstants) + HAVE_APPCONTEXT;NETSTANDARD2_0;HAVE_ADO_NET;HAVE_APP_DOMAIN;HAVE_ASYNC;HAVE_BIG_INTEGER;HAVE_BINARY_FORMATTER;HAVE_BINARY_SERIALIZATION;HAVE_BINARY_EXCEPTION_SERIALIZATION;HAVE_CHAR_TO_LOWER_WITH_CULTURE;HAVE_CHAR_TO_STRING_WITH_CULTURE;HAVE_COM_ATTRIBUTES;HAVE_COMPONENT_MODEL;HAVE_CONCURRENT_COLLECTIONS;HAVE_COVARIANT_GENERICS;HAVE_DATA_CONTRACTS;HAVE_DATE_TIME_OFFSET;HAVE_DB_NULL_TYPE_CODE;HAVE_DYNAMIC;HAVE_EMPTY_TYPES;HAVE_ENTITY_FRAMEWORK;HAVE_EXPRESSIONS;HAVE_FAST_REVERSE;HAVE_FSHARP_TYPES;HAVE_FULL_REFLECTION;HAVE_GUID_TRY_PARSE;HAVE_HASH_SET;HAVE_ICLONEABLE;HAVE_ICONVERTIBLE;HAVE_IGNORE_DATA_MEMBER_ATTRIBUTE;HAVE_INOTIFY_COLLECTION_CHANGED;HAVE_INOTIFY_PROPERTY_CHANGING;HAVE_ISET;HAVE_LINQ;HAVE_MEMORY_BARRIER;HAVE_METHOD_IMPL_ATTRIBUTE;HAVE_NON_SERIALIZED_ATTRIBUTE;HAVE_READ_ONLY_COLLECTIONS;HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE;HAVE_SERIALIZATION_BINDER_BIND_TO_NAME;HAVE_STREAM_READER_WRITER_CLOSE;HAVE_STRING_JOIN_WITH_ENUMERABLE;HAVE_TIME_SPAN_PARSE_WITH_CULTURE;HAVE_TIME_SPAN_TO_STRING_WITH_CULTURE;HAVE_TIME_ZONE_INFO;HAVE_TRACE_WRITER;HAVE_TYPE_DESCRIPTOR;HAVE_UNICODE_SURROGATE_DETECTION;HAVE_VARIANT_TYPE_PARAMETERS;HAVE_VERSION_TRY_PARSE;HAVE_XLINQ;HAVE_XML_DOCUMENT;HAVE_XML_DOCUMENT_TYPE;HAVE_CONCURRENT_DICTIONARY;HAVE_REGEX_TIMEOUTS;$(AdditionalConstants) \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Schema/Extensions.cs b/Src/Newtonsoft.Json/Schema/Extensions.cs index df8ffbaa..4e1e58ea 100644 --- a/Src/Newtonsoft.Json/Schema/Extensions.cs +++ b/Src/Newtonsoft.Json/Schema/Extensions.cs @@ -25,6 +25,7 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Utilities; @@ -57,6 +58,8 @@ namespace Newtonsoft.Json.Schema /// true if the specified is valid; otherwise, false. /// [Obsolete("JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschema for more details.")] + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static bool IsValid(this JToken source, JsonSchema schema) { bool valid = true; @@ -79,6 +82,8 @@ namespace Newtonsoft.Json.Schema /// true if the specified is valid; otherwise, false. /// [Obsolete("JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschema for more details.")] + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static bool IsValid(this JToken source, JsonSchema schema, out IList errorMessages) { IList errors = new List(); @@ -100,6 +105,8 @@ namespace Newtonsoft.Json.Schema /// The source to test. /// The schema to test with. [Obsolete("JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschema for more details.")] + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static void Validate(this JToken source, JsonSchema schema) { source.Validate(schema, null); @@ -117,6 +124,8 @@ namespace Newtonsoft.Json.Schema /// The schema to test with. /// The validation event handler. [Obsolete("JSON Schema validation has been moved to its own package. See https://www.newtonsoft.com/jsonschema for more details.")] + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static void Validate(this JToken source, JsonSchema schema, ValidationEventHandler validationEventHandler) { ValidationUtils.ArgumentNotNull(source, nameof(source)); diff --git a/Src/Newtonsoft.Json/Schema/JsonSchema.cs b/Src/Newtonsoft.Json/Schema/JsonSchema.cs index 034bd063..7da54650 100644 --- a/Src/Newtonsoft.Json/Schema/JsonSchema.cs +++ b/Src/Newtonsoft.Json/Schema/JsonSchema.cs @@ -25,6 +25,7 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.IO; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Utilities; @@ -318,6 +319,8 @@ namespace Newtonsoft.Json.Schema /// Writes this schema to a . /// /// A into which this method will write. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public void WriteTo(JsonWriter writer) { WriteTo(writer, new JsonSchemaResolver()); @@ -328,6 +331,8 @@ namespace Newtonsoft.Json.Schema /// /// A into which this method will write. /// The resolver used. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public void WriteTo(JsonWriter writer, JsonSchemaResolver resolver) { ValidationUtils.ArgumentNotNull(writer, nameof(writer)); @@ -345,11 +350,19 @@ namespace Newtonsoft.Json.Schema /// public override string ToString() { +#if HAVE_APPCONTEXT + if (!JToken.SerializationIsSupported) + { + throw new NotSupportedException(JToken.SerializationNotSupportedMessage); + } +#endif StringWriter writer = new StringWriter(CultureInfo.InvariantCulture); JsonTextWriter jsonWriter = new JsonTextWriter(writer); jsonWriter.Formatting = Formatting.Indented; +#pragma warning disable IL2026, IL3050 WriteTo(jsonWriter); +#pragma warning restore IL2026, IL3050 return writer.ToString(); } diff --git a/Src/Newtonsoft.Json/Schema/JsonSchemaGenerator.cs b/Src/Newtonsoft.Json/Schema/JsonSchemaGenerator.cs index 7cdab611..8e604163 100644 --- a/Src/Newtonsoft.Json/Schema/JsonSchemaGenerator.cs +++ b/Src/Newtonsoft.Json/Schema/JsonSchemaGenerator.cs @@ -30,6 +30,8 @@ using System.Collections.Generic; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Utilities; using Newtonsoft.Json.Serialization; +using System.Diagnostics.CodeAnalysis; + #if !HAVE_LINQ using Newtonsoft.Json.Utilities.LinqBridge; #else @@ -65,6 +67,8 @@ namespace Newtonsoft.Json.Schema /// The contract resolver. public IContractResolver ContractResolver { + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] get { if (_contractResolver == null) @@ -127,6 +131,8 @@ namespace Newtonsoft.Json.Schema /// /// The type to generate a from. /// A generated from the specified type. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public JsonSchema Generate(Type type) { return Generate(type, new JsonSchemaResolver(), false); @@ -138,6 +144,8 @@ namespace Newtonsoft.Json.Schema /// The type to generate a from. /// The used to resolve schema references. /// A generated from the specified type. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public JsonSchema Generate(Type type, JsonSchemaResolver resolver) { return Generate(type, resolver, false); @@ -149,6 +157,8 @@ namespace Newtonsoft.Json.Schema /// The type to generate a from. /// Specify whether the generated root will be nullable. /// A generated from the specified type. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public JsonSchema Generate(Type type, bool rootSchemaNullable) { return Generate(type, new JsonSchemaResolver(), rootSchemaNullable); @@ -161,6 +171,8 @@ namespace Newtonsoft.Json.Schema /// The used to resolve schema references. /// Specify whether the generated root will be nullable. /// A generated from the specified type. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public JsonSchema Generate(Type type, JsonSchemaResolver resolver, bool rootSchemaNullable) { ValidationUtils.ArgumentNotNull(type, nameof(type)); @@ -171,6 +183,8 @@ namespace Newtonsoft.Json.Schema return GenerateInternal(type, (!rootSchemaNullable) ? Required.Always : Required.Default, false); } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private string GetTitle(Type type) { JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute(type); @@ -183,6 +197,8 @@ namespace Newtonsoft.Json.Schema return null; } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private string GetDescription(Type type) { JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute(type); @@ -200,6 +216,8 @@ namespace Newtonsoft.Json.Schema #endif } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private string GetTypeId(Type type, bool explicitOnly) { JsonContainerAttribute containerAttribute = JsonTypeReflector.GetCachedAttribute(type); @@ -225,7 +243,13 @@ namespace Newtonsoft.Json.Schema } } - private JsonSchema GenerateInternal(Type type, Required valueRequired, bool required) + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] + private JsonSchema GenerateInternal( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] + Type type, + Required valueRequired, + bool required) { ValidationUtils.ArgumentNotNull(type, nameof(type)); @@ -382,6 +406,8 @@ namespace Newtonsoft.Json.Schema return ((value & flag) == flag); } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private void GenerateObjectSchema(Type type, JsonObjectContract contract) { CurrentSchema.Properties = new Dictionary(); diff --git a/Src/Newtonsoft.Json/Schema/JsonSchemaWriter.cs b/Src/Newtonsoft.Json/Schema/JsonSchemaWriter.cs index c5843bed..c15e87e1 100644 --- a/Src/Newtonsoft.Json/Schema/JsonSchemaWriter.cs +++ b/Src/Newtonsoft.Json/Schema/JsonSchemaWriter.cs @@ -25,6 +25,7 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Utilities; @@ -52,6 +53,8 @@ namespace Newtonsoft.Json.Schema _resolver = resolver; } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private void ReferenceOrWriteSchema(JsonSchema schema) { if (schema.Id != null && _resolver.GetSchema(schema.Id) != null) @@ -67,6 +70,8 @@ namespace Newtonsoft.Json.Schema } } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public void WriteSchema(JsonSchema schema) { ValidationUtils.ArgumentNotNull(schema, nameof(schema)); @@ -167,6 +172,8 @@ namespace Newtonsoft.Json.Schema _writer.WriteEndObject(); } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private void WriteSchemaDictionaryIfNotNull(JsonWriter writer, string propertyName, IDictionary properties) { if (properties != null) @@ -182,6 +189,8 @@ namespace Newtonsoft.Json.Schema } } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private void WriteItems(JsonSchema schema) { if (schema.Items == null && !schema.PositionalItemsValidation) diff --git a/Src/Newtonsoft.Json/Serialization/CachedAttributeGetter.cs b/Src/Newtonsoft.Json/Serialization/CachedAttributeGetter.cs index 40697594..4d68a73f 100644 --- a/Src/Newtonsoft.Json/Serialization/CachedAttributeGetter.cs +++ b/Src/Newtonsoft.Json/Serialization/CachedAttributeGetter.cs @@ -24,11 +24,14 @@ #endregion using System; +using System.Diagnostics.CodeAnalysis; using System.Reflection; using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Serialization { + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] internal static class CachedAttributeGetter where T : Attribute { private static readonly ThreadSafeStore TypeAttributeCache = new ThreadSafeStore(JsonTypeReflector.GetAttribute); diff --git a/Src/Newtonsoft.Json/Serialization/CamelCasePropertyNamesContractResolver.cs b/Src/Newtonsoft.Json/Serialization/CamelCasePropertyNamesContractResolver.cs index 554e89a5..ba336e00 100644 --- a/Src/Newtonsoft.Json/Serialization/CamelCasePropertyNamesContractResolver.cs +++ b/Src/Newtonsoft.Json/Serialization/CamelCasePropertyNamesContractResolver.cs @@ -25,6 +25,7 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using Newtonsoft.Json.Utilities; @@ -33,6 +34,8 @@ namespace Newtonsoft.Json.Serialization /// /// Resolves member mappings for a type, camel casing property names. /// + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public class CamelCasePropertyNamesContractResolver : DefaultContractResolver { private static readonly object TypeContractCacheLock = new object(); diff --git a/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs b/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs index 3ff2208c..f59e8aee 100644 --- a/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs +++ b/Src/Newtonsoft.Json/Serialization/DefaultContractResolver.cs @@ -31,6 +31,7 @@ using System.Collections.Concurrent; using Newtonsoft.Json.Schema; using System.Collections.Generic; using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; #if HAVE_DYNAMIC using System.Dynamic; #endif @@ -58,6 +59,8 @@ namespace Newtonsoft.Json.Serialization /// /// Used by to resolve a for a given . /// + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public class DefaultContractResolver : IContractResolver { private static readonly IContractResolver _instance = new DefaultContractResolver(); @@ -290,7 +293,7 @@ namespace Newtonsoft.Json.Serialization #if HAVE_DATA_CONTRACTS // don't include EntityKey on entities objects... this is a bit hacky - if (objectType.AssignableToTypeName("System.Data.Objects.DataClasses.EntityObject", false, out _)) + if (objectType.AssignableToTypeName("System.Data.Objects.DataClasses.EntityObject", out _)) { serializableMembers = serializableMembers.Where(ShouldSerializeEntityMember).ToList(); } diff --git a/Src/Newtonsoft.Json/Serialization/DefaultSerializationBinder.cs b/Src/Newtonsoft.Json/Serialization/DefaultSerializationBinder.cs index 37d25cf2..35bf05d7 100644 --- a/Src/Newtonsoft.Json/Serialization/DefaultSerializationBinder.cs +++ b/Src/Newtonsoft.Json/Serialization/DefaultSerializationBinder.cs @@ -24,6 +24,7 @@ #endregion using System; +using System.Diagnostics.CodeAnalysis; using System.Runtime.Serialization; using System.Reflection; using System.Globalization; @@ -35,6 +36,8 @@ namespace Newtonsoft.Json.Serialization /// /// The default serialization binder used when resolving and loading classes from type names. /// + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public class DefaultSerializationBinder : #pragma warning disable 618 SerializationBinder, diff --git a/Src/Newtonsoft.Json/Serialization/DynamicValueProvider.cs b/Src/Newtonsoft.Json/Serialization/DynamicValueProvider.cs index cb19a61e..ba3b9470 100644 --- a/Src/Newtonsoft.Json/Serialization/DynamicValueProvider.cs +++ b/Src/Newtonsoft.Json/Serialization/DynamicValueProvider.cs @@ -33,12 +33,14 @@ using System.Text; using System.Reflection; using Newtonsoft.Json.Utilities; using System.Globalization; +using System.Diagnostics.CodeAnalysis; namespace Newtonsoft.Json.Serialization { /// /// Get and set values for a using dynamic methods. /// + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public class DynamicValueProvider : IValueProvider { private readonly MemberInfo _memberInfo; diff --git a/Src/Newtonsoft.Json/Serialization/ExpressionValueProvider.cs b/Src/Newtonsoft.Json/Serialization/ExpressionValueProvider.cs index 99da718d..5def6e84 100644 --- a/Src/Newtonsoft.Json/Serialization/ExpressionValueProvider.cs +++ b/Src/Newtonsoft.Json/Serialization/ExpressionValueProvider.cs @@ -34,12 +34,14 @@ using System.Text; using System.Reflection; using Newtonsoft.Json.Utilities; using System.Globalization; +using System.Diagnostics.CodeAnalysis; namespace Newtonsoft.Json.Serialization { /// /// Get and set values for a using dynamic methods. /// + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public class ExpressionValueProvider : IValueProvider { private readonly MemberInfo _memberInfo; diff --git a/Src/Newtonsoft.Json/Serialization/JsonArrayContract.cs b/Src/Newtonsoft.Json/Serialization/JsonArrayContract.cs index 87c409e6..4a68bfe9 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonArrayContract.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonArrayContract.cs @@ -32,6 +32,8 @@ using System.Reflection; using Newtonsoft.Json.Utilities; using System.Collections; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; + #if !HAVE_LINQ using Newtonsoft.Json.Utilities.LinqBridge; #else @@ -60,6 +62,7 @@ namespace Newtonsoft.Json.Serialization private readonly Type? _genericCollectionDefinitionType; + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] private Type? _genericWrapperType; private ObjectConstructor? _genericWrapperCreator; private Func? _genericTemporaryCollectionCreator; @@ -75,6 +78,7 @@ namespace Newtonsoft.Json.Serialization internal ObjectConstructor? ParameterizedCreator { + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] get { if (_parameterizedCreator == null && _parameterizedConstructor != null) @@ -113,6 +117,8 @@ namespace Newtonsoft.Json.Serialization /// Initializes a new instance of the class. /// /// The underlying type for the contract. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public JsonArrayContract(Type underlyingType) : base(underlyingType) { @@ -269,6 +275,7 @@ namespace Newtonsoft.Json.Serialization } } + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] internal IWrappedCollection CreateWrapper(object list) { if (_genericWrapperCreator == null) @@ -297,6 +304,7 @@ namespace Newtonsoft.Json.Serialization return (IWrappedCollection)_genericWrapperCreator(list); } + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] internal IList CreateTemporaryCollection() { if (_genericTemporaryCollectionCreator == null) @@ -314,6 +322,8 @@ namespace Newtonsoft.Json.Serialization } #if HAVE_FSHARP_TYPES + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private void StoreFSharpListCreatorIfNecessary(Type underlyingType) { if (!HasParameterizedCreatorInternal && underlyingType.Name == FSharpUtils.FSharpListTypeName) diff --git a/Src/Newtonsoft.Json/Serialization/JsonContainerContract.cs b/Src/Newtonsoft.Json/Serialization/JsonContainerContract.cs index 9956ed31..e60d80ea 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonContainerContract.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonContainerContract.cs @@ -25,6 +25,7 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Reflection; using Newtonsoft.Json.Utilities; using System.Collections; @@ -94,6 +95,8 @@ namespace Newtonsoft.Json.Serialization /// Initializes a new instance of the class. /// /// The underlying type for the contract. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] internal JsonContainerContract(Type underlyingType) : base(underlyingType) { diff --git a/Src/Newtonsoft.Json/Serialization/JsonContract.cs b/Src/Newtonsoft.Json/Serialization/JsonContract.cs index d4f802cb..7524d275 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonContract.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonContract.cs @@ -26,6 +26,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Runtime.Serialization; using Newtonsoft.Json.Linq; @@ -83,6 +84,8 @@ namespace Newtonsoft.Json.Serialization internal bool IsNullable; internal bool IsConvertable; internal bool IsEnum; + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] internal Type NonNullableUnderlyingType; internal ReadType InternalReadType; internal JsonContractType ContractType; @@ -95,6 +98,8 @@ namespace Newtonsoft.Json.Serialization private List? _onSerializedCallbacks; private List? _onSerializingCallbacks; private List? _onErrorCallbacks; + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] private Type _createdType; /// @@ -107,6 +112,7 @@ namespace Newtonsoft.Json.Serialization /// Gets or sets the type created during deserialization. /// /// The type created during deserialization. + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] public Type CreatedType { get => _createdType; @@ -236,7 +242,10 @@ namespace Newtonsoft.Json.Serialization /// true if the default object creator is non-public; otherwise, false. public bool DefaultCreatorNonPublic { get; set; } - internal JsonContract(Type underlyingType) + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + internal JsonContract( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] + Type underlyingType) { ValidationUtils.ArgumentNotNull(underlyingType, nameof(underlyingType)); diff --git a/Src/Newtonsoft.Json/Serialization/JsonDictionaryContract.cs b/Src/Newtonsoft.Json/Serialization/JsonDictionaryContract.cs index 25828d13..8c4fcf99 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonDictionaryContract.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonDictionaryContract.cs @@ -29,6 +29,7 @@ using System.Collections.ObjectModel; using System.Reflection; using Newtonsoft.Json.Utilities; using System.Collections; +using System.Diagnostics.CodeAnalysis; #if !HAVE_LINQ using Newtonsoft.Json.Utilities.LinqBridge; @@ -63,6 +64,7 @@ namespace Newtonsoft.Json.Serialization private readonly Type? _genericCollectionDefinitionType; + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] private Type? _genericWrapperType; private ObjectConstructor? _genericWrapperCreator; @@ -77,6 +79,7 @@ namespace Newtonsoft.Json.Serialization internal ObjectConstructor? ParameterizedCreator { + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] get { if (_parameterizedCreator == null && _parameterizedConstructor != null) @@ -110,6 +113,8 @@ namespace Newtonsoft.Json.Serialization /// Initializes a new instance of the class. /// /// The underlying type for the contract. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public JsonDictionaryContract(Type underlyingType) : base(underlyingType) { @@ -219,6 +224,7 @@ namespace Newtonsoft.Json.Serialization } } + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] internal IWrappedDictionary CreateWrapper(object dictionary) { if (_genericWrapperCreator == null) @@ -232,6 +238,7 @@ namespace Newtonsoft.Json.Serialization return (IWrappedDictionary)_genericWrapperCreator(dictionary); } + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] internal IDictionary CreateTemporaryDictionary() { if (_genericTemporaryDictionaryCreator == null) diff --git a/Src/Newtonsoft.Json/Serialization/JsonDynamicContract.cs b/Src/Newtonsoft.Json/Serialization/JsonDynamicContract.cs index 5908890b..558b5f7d 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonDynamicContract.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonDynamicContract.cs @@ -25,6 +25,7 @@ #if HAVE_DYNAMIC using System; +using System.Diagnostics.CodeAnalysis; using System.Dynamic; using System.Runtime.CompilerServices; using Newtonsoft.Json.Utilities; @@ -54,6 +55,8 @@ namespace Newtonsoft.Json.Serialization private readonly ThreadSafeStore>> _callSiteSetters = new ThreadSafeStore>>(CreateCallSiteSetter); + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private static CallSite> CreateCallSiteGetter(string name) { GetMemberBinder getMemberBinder = (GetMemberBinder)DynamicUtils.BinderWrapper.GetMember(name, typeof(DynamicUtils)); @@ -61,6 +64,8 @@ namespace Newtonsoft.Json.Serialization return CallSite>.Create(new NoThrowGetBinderMember(getMemberBinder)); } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private static CallSite> CreateCallSiteSetter(string name) { SetMemberBinder binder = (SetMemberBinder)DynamicUtils.BinderWrapper.SetMember(name, typeof(DynamicUtils)); @@ -72,6 +77,8 @@ namespace Newtonsoft.Json.Serialization /// Initializes a new instance of the class. /// /// The underlying type for the contract. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public JsonDynamicContract(Type underlyingType) : base(underlyingType) { diff --git a/Src/Newtonsoft.Json/Serialization/JsonFormatterConverter.cs b/Src/Newtonsoft.Json/Serialization/JsonFormatterConverter.cs index 408a0297..177fe381 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonFormatterConverter.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonFormatterConverter.cs @@ -25,6 +25,7 @@ #if HAVE_BINARY_SERIALIZATION using System; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.Serialization; using Newtonsoft.Json.Utilities; @@ -32,6 +33,8 @@ using Newtonsoft.Json.Linq; namespace Newtonsoft.Json.Serialization { + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] internal class JsonFormatterConverter : IFormatterConverter { private readonly JsonSerializerInternalReader _reader; diff --git a/Src/Newtonsoft.Json/Serialization/JsonISerializableContract.cs b/Src/Newtonsoft.Json/Serialization/JsonISerializableContract.cs index 55ea9e3a..9e79e819 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonISerializableContract.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonISerializableContract.cs @@ -26,6 +26,8 @@ #if HAVE_BINARY_SERIALIZATION using System; using System.Runtime.Serialization; +using System.Diagnostics.CodeAnalysis; +using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Serialization { @@ -44,6 +46,8 @@ namespace Newtonsoft.Json.Serialization /// Initializes a new instance of the class. /// /// The underlying type for the contract. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public JsonISerializableContract(Type underlyingType) : base(underlyingType) { diff --git a/Src/Newtonsoft.Json/Serialization/JsonLinqContract.cs b/Src/Newtonsoft.Json/Serialization/JsonLinqContract.cs index c91b3f00..1b81eef2 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonLinqContract.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonLinqContract.cs @@ -24,6 +24,8 @@ #endregion using System; +using System.Diagnostics.CodeAnalysis; +using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Serialization { @@ -36,6 +38,7 @@ namespace Newtonsoft.Json.Serialization /// Initializes a new instance of the class. /// /// The underlying type for the contract. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] public JsonLinqContract(Type underlyingType) : base(underlyingType) { diff --git a/Src/Newtonsoft.Json/Serialization/JsonObjectContract.cs b/Src/Newtonsoft.Json/Serialization/JsonObjectContract.cs index 221843db..82a1f46c 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonObjectContract.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonObjectContract.cs @@ -24,6 +24,7 @@ #endregion using System; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Reflection; using System.Runtime.Serialization; @@ -172,6 +173,8 @@ namespace Newtonsoft.Json.Serialization /// Initializes a new instance of the class. /// /// The underlying type for the contract. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public JsonObjectContract(Type underlyingType) : base(underlyingType) { diff --git a/Src/Newtonsoft.Json/Serialization/JsonPrimitiveContract.cs b/Src/Newtonsoft.Json/Serialization/JsonPrimitiveContract.cs index 6d662de5..adce77ef 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonPrimitiveContract.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonPrimitiveContract.cs @@ -25,6 +25,7 @@ using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Serialization @@ -40,6 +41,7 @@ namespace Newtonsoft.Json.Serialization /// Initializes a new instance of the class. /// /// The underlying type for the contract. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] public JsonPrimitiveContract(Type underlyingType) : base(underlyingType) { diff --git a/Src/Newtonsoft.Json/Serialization/JsonProperty.cs b/Src/Newtonsoft.Json/Serialization/JsonProperty.cs index 183a5a72..1c7ffb35 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonProperty.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonProperty.cs @@ -25,6 +25,7 @@ using System; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Reflection; using Newtonsoft.Json.Utilities; @@ -46,6 +47,8 @@ namespace Newtonsoft.Json.Serialization private bool _hasGeneratedDefaultValue; private string? _propertyName; internal bool _skipPropertyNameEscape; + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] private Type? _propertyType; // use to cache contract during deserialization @@ -99,6 +102,7 @@ namespace Newtonsoft.Json.Serialization /// Gets or sets the type of the property. /// /// The type of the property. + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] public Type? PropertyType { get => _propertyType; diff --git a/Src/Newtonsoft.Json/Serialization/JsonPropertyCollection.cs b/Src/Newtonsoft.Json/Serialization/JsonPropertyCollection.cs index 684be0d3..ee6f7c8f 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonPropertyCollection.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonPropertyCollection.cs @@ -71,6 +71,7 @@ namespace Newtonsoft.Json.Serialization /// Adds a object. /// /// The property to add to the collection. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] public void AddProperty(JsonProperty property) { MiscellaneousUtils.Assert(property.PropertyName != null); diff --git a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs index 72bc0cca..9fa36466 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalReader.cs @@ -64,6 +64,8 @@ namespace Newtonsoft.Json.Serialization { } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public void Populate(JsonReader reader, object target) { ValidationUtils.ArgumentNotNull(target, nameof(target)); @@ -139,6 +141,8 @@ namespace Newtonsoft.Json.Serialization return Serializer._contractResolver.ResolveContract(type); } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public object? Deserialize(JsonReader reader, Type? objectType, bool checkAdditionalContent) { if (reader == null) @@ -204,6 +208,8 @@ namespace Newtonsoft.Json.Serialization } } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private JsonSerializerProxy GetInternalSerializer() { if (InternalSerializer == null) @@ -292,6 +298,8 @@ namespace Newtonsoft.Json.Serialization } } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private object? CreateValueInternal(JsonReader reader, Type? objectType, JsonContract? contract, JsonProperty? member, JsonContainerContract? containerContract, JsonProperty? containerMember, object? existingValue) { if (contract != null && contract.ContractType == JsonContractType.Linq) @@ -424,6 +432,8 @@ namespace Newtonsoft.Json.Serialization return converter; } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private object? CreateObject(JsonReader reader, Type? objectType, JsonContract? contract, JsonProperty? member, JsonContainerContract? containerContract, JsonProperty? containerMember, object? existingValue) { string? id; @@ -598,6 +608,8 @@ namespace Newtonsoft.Json.Serialization throw JsonSerializationException.Create(reader, message); } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private bool ReadMetadataPropertiesToken(JTokenReader reader, ref Type? objectType, ref JsonContract? contract, JsonProperty? member, JsonContainerContract? containerContract, JsonProperty? containerMember, object? existingValue, out object? newValue, out string? id) { id = null; @@ -685,6 +697,8 @@ namespace Newtonsoft.Json.Serialization return false; } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private bool ReadMetadataProperties(JsonReader reader, ref Type? objectType, ref JsonContract? contract, JsonProperty? member, JsonContainerContract? containerContract, JsonProperty? containerMember, object? existingValue, out object? newValue, out string? id) { id = null; @@ -840,6 +854,8 @@ namespace Newtonsoft.Json.Serialization return arrayContract; } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private object? CreateList(JsonReader reader, Type? objectType, JsonContract? contract, JsonProperty? member, object? existingValue, string? id) { object? value; @@ -938,6 +954,8 @@ namespace Newtonsoft.Json.Serialization ); } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private object? EnsureType(JsonReader reader, object? value, CultureInfo culture, JsonContract? contract, Type? targetType) { if (targetType == null) @@ -1009,6 +1027,8 @@ namespace Newtonsoft.Json.Serialization return value; } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private bool SetPropertyValue(JsonProperty property, JsonConverter? propertyConverter, JsonContainerContract? containerContract, JsonProperty? containerProperty, JsonReader reader, object target) { bool skipSettingProperty = CalculatePropertyDetails( @@ -1215,6 +1235,7 @@ namespace Newtonsoft.Json.Serialization return true; } + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private IList CreateNewList(JsonReader reader, JsonArrayContract contract, out bool createdFromNonDefaultCreator) { // some types like non-generic IEnumerable can be serialized but not deserialized @@ -1283,6 +1304,7 @@ namespace Newtonsoft.Json.Serialization } } + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private IDictionary CreateNewDictionary(JsonReader reader, JsonDictionaryContract contract, out bool createdFromNonDefaultCreator) { if (contract.OverrideCreator != null) @@ -1351,6 +1373,8 @@ namespace Newtonsoft.Json.Serialization contract.InvokeOnDeserialized(value, Serializer._context); } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private object PopulateDictionary(IDictionary dictionary, JsonReader reader, JsonDictionaryContract contract, JsonProperty? containerProperty, string? id) { object underlyingDictionary = dictionary is IWrappedDictionary wrappedDictionary ? wrappedDictionary.UnderlyingDictionary : dictionary; @@ -1474,6 +1498,8 @@ namespace Newtonsoft.Json.Serialization return underlyingDictionary; } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private object PopulateMultidimensionalArray(IList list, JsonReader reader, JsonArrayContract contract, JsonProperty? containerProperty, string? id) { int rank = contract.UnderlyingType.GetArrayRank(); @@ -1624,6 +1650,8 @@ namespace Newtonsoft.Json.Serialization } } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private object PopulateList(IList list, JsonReader reader, JsonArrayContract contract, JsonProperty? containerProperty, string? id) { #pragma warning disable CS8600, CS8602, CS8603, CS8604 @@ -1726,6 +1754,8 @@ namespace Newtonsoft.Json.Serialization } #if HAVE_BINARY_SERIALIZATION + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private object CreateISerializable(JsonReader reader, JsonISerializableContract contract, JsonProperty? member, string? id) { Type objectType = contract.UnderlyingType; @@ -1798,6 +1828,8 @@ namespace Newtonsoft.Json.Serialization return createdObject; } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] internal object? CreateISerializableItem(JToken token, Type type, JsonISerializableContract contract, JsonProperty? member) { JsonContract? itemContract = GetContractSafe(type); @@ -1822,6 +1854,8 @@ namespace Newtonsoft.Json.Serialization #endif #if HAVE_DYNAMIC + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private object CreateDynamic(JsonReader reader, JsonDynamicContract contract, JsonProperty? member, string? id) { IDynamicMetaObjectProvider newObject; @@ -1948,6 +1982,8 @@ namespace Newtonsoft.Json.Serialization } } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private object CreateObjectUsingCreatorWithParameters(JsonReader reader, JsonObjectContract contract, JsonProperty? containerProperty, ObjectConstructor creator, string? id) { ValidationUtils.ArgumentNotNull(creator, nameof(creator)); @@ -2182,6 +2218,8 @@ namespace Newtonsoft.Json.Serialization return createdObject; } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private object? DeserializeConvertable(JsonConverter converter, JsonReader reader, Type objectType, object? existingValue) { if (TraceWriter != null && TraceWriter.LevelFilter >= TraceLevel.Info) @@ -2199,6 +2237,8 @@ namespace Newtonsoft.Json.Serialization return value; } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private List ResolvePropertyAndCreatorValues(JsonObjectContract contract, JsonProperty? containerProperty, JsonReader reader, Type objectType) { List propertyValues = new List(); @@ -2298,6 +2338,8 @@ namespace Newtonsoft.Json.Serialization return propertyValues; } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public object CreateNewObject(JsonReader reader, JsonObjectContract objectContract, JsonProperty? containerMember, JsonProperty? containerProperty, string? id, out bool createdFromNonDefaultCreator) { object? newObject = null; @@ -2341,6 +2383,8 @@ namespace Newtonsoft.Json.Serialization return newObject; } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private object PopulateObject(object newObject, JsonReader reader, JsonObjectContract contract, JsonProperty? member, string? id) { OnDeserializing(reader, contract, newObject); @@ -2509,6 +2553,8 @@ namespace Newtonsoft.Json.Serialization return false; } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private void SetExtensionData(JsonObjectContract contract, JsonProperty? member, JsonReader reader, string memberName, object o) { if (contract.ExtensionDataSetter != null) @@ -2530,6 +2576,8 @@ namespace Newtonsoft.Json.Serialization } } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private object? ReadExtensionDataValue(JsonObjectContract contract, JsonProperty? member, JsonReader reader) { object? value; @@ -2544,6 +2592,8 @@ namespace Newtonsoft.Json.Serialization return value; } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private void EndProcessProperty(object newObject, JsonReader reader, JsonObjectContract contract, int initialDepth, JsonProperty property, PropertyPresence presence, bool setDefaultValue) { if (presence == PropertyPresence.None || presence == PropertyPresence.Null) diff --git a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs index 7feb6ad3..fbf53838 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs @@ -58,6 +58,8 @@ namespace Newtonsoft.Json.Serialization { } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public void Serialize(JsonWriter jsonWriter, object? value, Type? objectType) { if (jsonWriter == null) @@ -104,6 +106,8 @@ namespace Newtonsoft.Json.Serialization } } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private JsonSerializerProxy GetInternalSerializer() { if (InternalSerializer == null) @@ -151,6 +155,8 @@ namespace Newtonsoft.Json.Serialization JsonWriter.WriteValue(writer, contract.TypeCode, value); } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private void SerializeValue(JsonWriter writer, object? value, JsonContract? valueContract, JsonProperty? member, JsonContainerContract? containerContract, JsonProperty? containerProperty) { if (value == null) @@ -394,6 +400,7 @@ namespace Newtonsoft.Json.Serialization } } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] internal static bool TryConvertToString(object value, Type type, [NotNullWhen(true)]out string? s) { #if HAVE_DATE_ONLY @@ -435,6 +442,7 @@ namespace Newtonsoft.Json.Serialization return false; } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] private void SerializeString(JsonWriter writer, object value, JsonStringContract contract) { OnSerializing(writer, contract, value); @@ -465,6 +473,8 @@ namespace Newtonsoft.Json.Serialization contract.InvokeOnSerialized(value, Serializer._context); } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private void SerializeObject(JsonWriter writer, object value, JsonObjectContract contract, JsonProperty? member, JsonContainerContract? collectionContract, JsonProperty? containerProperty) { OnSerializing(writer, contract, value); @@ -659,6 +669,8 @@ namespace Newtonsoft.Json.Serialization return ((value & flag) == flag); } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private void SerializeConvertable(JsonWriter writer, JsonConverter converter, object value, JsonContract contract, JsonContainerContract? collectionContract, JsonProperty? containerProperty) { if (ShouldWriteReference(value, null, contract, collectionContract, containerProperty)) @@ -690,6 +702,8 @@ namespace Newtonsoft.Json.Serialization } } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private void SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty? member, JsonContainerContract? collectionContract, JsonProperty? containerProperty) { object underlyingList = values is IWrappedCollection wrappedCollection ? wrappedCollection.UnderlyingCollection : values; @@ -753,6 +767,8 @@ namespace Newtonsoft.Json.Serialization OnSerialized(writer, contract, underlyingList); } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty? member, JsonContainerContract? collectionContract, JsonProperty? containerProperty) { OnSerializing(writer, contract, values); @@ -773,6 +789,8 @@ namespace Newtonsoft.Json.Serialization OnSerialized(writer, contract, values); } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private void SerializeMultidimensionalArray(JsonWriter writer, Array values, JsonArrayContract contract, JsonProperty? member, int initialDepth, int[] indices) { int dimension = indices.Length; @@ -866,6 +884,8 @@ namespace Newtonsoft.Json.Serialization #if HAVE_SECURITY_SAFE_CRITICAL_ATTRIBUTE [SecuritySafeCritical] #endif + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private void SerializeISerializable(JsonWriter writer, ISerializable value, JsonISerializableContract contract, JsonProperty? member, JsonContainerContract? collectionContract, JsonProperty? containerProperty) { if (!JsonTypeReflector.FullyTrusted) @@ -909,6 +929,8 @@ namespace Newtonsoft.Json.Serialization #endif #if HAVE_DYNAMIC + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private void SerializeDynamic(JsonWriter writer, IDynamicMetaObjectProvider value, JsonDynamicContract contract, JsonProperty? member, JsonContainerContract? collectionContract, JsonProperty? containerProperty) { OnSerializing(writer, contract, value); @@ -993,6 +1015,7 @@ namespace Newtonsoft.Json.Serialization } #endif + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] private bool ShouldWriteDynamicProperty(object? memberValue) { if (Serializer._nullValueHandling == NullValueHandling.Ignore && memberValue == null) @@ -1053,6 +1076,8 @@ namespace Newtonsoft.Json.Serialization return false; } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private void SerializeDictionary(JsonWriter writer, IDictionary values, JsonDictionaryContract contract, JsonProperty? member, JsonContainerContract? collectionContract, JsonProperty? containerProperty) { #pragma warning disable CS8600, CS8602, CS8604 @@ -1137,6 +1162,7 @@ namespace Newtonsoft.Json.Serialization #pragma warning restore CS8600, CS8602, CS8604 } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] private string GetPropertyName(JsonWriter writer, object name, JsonContract contract, out bool escape) { if (contract.ContractType == JsonContractType.Primitive) diff --git a/Src/Newtonsoft.Json/Serialization/JsonSerializerProxy.cs b/Src/Newtonsoft.Json/Serialization/JsonSerializerProxy.cs index a122fe00..fa18d84a 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonSerializerProxy.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonSerializerProxy.cs @@ -25,6 +25,7 @@ using System; using System.Collections; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Runtime.Serialization.Formatters; using Newtonsoft.Json.Utilities; @@ -32,6 +33,8 @@ using System.Runtime.Serialization; namespace Newtonsoft.Json.Serialization { + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] internal class JsonSerializerProxy : JsonSerializer { private readonly JsonSerializerInternalReader? _serializerReader; diff --git a/Src/Newtonsoft.Json/Serialization/JsonStringContract.cs b/Src/Newtonsoft.Json/Serialization/JsonStringContract.cs index be096bc5..1eb207b1 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonStringContract.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonStringContract.cs @@ -24,6 +24,8 @@ #endregion using System; +using System.Diagnostics.CodeAnalysis; +using Newtonsoft.Json.Utilities; namespace Newtonsoft.Json.Serialization { @@ -36,6 +38,7 @@ namespace Newtonsoft.Json.Serialization /// Initializes a new instance of the class. /// /// The underlying type for the contract. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] public JsonStringContract(Type underlyingType) : base(underlyingType) { diff --git a/Src/Newtonsoft.Json/Serialization/JsonTypeReflector.cs b/Src/Newtonsoft.Json/Serialization/JsonTypeReflector.cs index da843007..c90458c1 100644 --- a/Src/Newtonsoft.Json/Serialization/JsonTypeReflector.cs +++ b/Src/Newtonsoft.Json/Serialization/JsonTypeReflector.cs @@ -34,6 +34,8 @@ using System.Security.Permissions; #endif using Newtonsoft.Json.Utilities; using System.Runtime.CompilerServices; +using System.Diagnostics.CodeAnalysis; + #if !HAVE_LINQ using Newtonsoft.Json.Utilities.LinqBridge; #else @@ -59,20 +61,34 @@ namespace Newtonsoft.Json.Serialization public const string ConcurrentDictionaryTypeName = "System.Collections.Concurrent.ConcurrentDictionary`2"; - private static readonly ThreadSafeStore> CreatorCache = - new ThreadSafeStore>(GetCreator); + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] + private static class CreatorCache + { + internal static readonly ThreadSafeStore> Instance = + new ThreadSafeStore>(GetCreator); + } #if !(NET20 || DOTNET) - private static readonly ThreadSafeStore AssociatedMetadataTypesCache = new ThreadSafeStore(GetAssociateMetadataTypeFromAttribute); + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] + private static class AssociatedMetadataTypesCache + { + internal static readonly ThreadSafeStore Instance = new ThreadSafeStore(GetAssociateMetadataTypeFromAttribute); + } + private static ReflectionObject? _metadataTypeAttributeReflectionObject; #endif + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static T? GetCachedAttribute(object attributeProvider) where T : Attribute { return CachedAttributeGetter.GetAttribute(attributeProvider); } #if HAVE_TYPE_DESCRIPTOR + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] public static bool CanTypeDescriptorConvertString(Type type, out TypeConverter typeConverter) { typeConverter = TypeDescriptor.GetConverter(type); @@ -85,7 +101,7 @@ namespace Newtonsoft.Json.Serialization if (!string.Equals(converterType.FullName, "System.ComponentModel.ComponentConverter", StringComparison.Ordinal) && !string.Equals(converterType.FullName, "System.ComponentModel.ReferenceConverter", StringComparison.Ordinal) && !string.Equals(converterType.FullName, "System.Windows.Forms.Design.DataSourceConverter", StringComparison.Ordinal) - && converterType != typeof(TypeConverter)) + && converterType != typeof(TypeConverter)) { return typeConverter.CanConvertTo(typeof(string)); } @@ -97,6 +113,8 @@ namespace Newtonsoft.Json.Serialization #endif #if HAVE_DATA_CONTRACTS + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static DataContractAttribute? GetDataContractAttribute(Type type) { // DataContractAttribute does not have inheritance @@ -116,6 +134,8 @@ namespace Newtonsoft.Json.Serialization return null; } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static DataMemberAttribute? GetDataMemberAttribute(MemberInfo memberInfo) { // DataMemberAttribute does not have inheritance @@ -152,6 +172,8 @@ namespace Newtonsoft.Json.Serialization } #endif + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static MemberSerialization GetObjectMemberSerialization(Type objectType, bool ignoreSerializableAttribute) { JsonObjectAttribute? objectAttribute = GetCachedAttribute(objectType); @@ -179,13 +201,15 @@ namespace Newtonsoft.Json.Serialization return MemberSerialization.OptOut; } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static JsonConverter? GetJsonConverter(object attributeProvider) { JsonConverterAttribute? converterAttribute = GetCachedAttribute(attributeProvider); if (converterAttribute != null) { - Func creator = CreatorCache.Get(converterAttribute.ConverterType); + Func creator = CreatorCache.Instance.Get(converterAttribute.ConverterType); if (creator != null) { return (JsonConverter)creator(converterAttribute.ConverterParameters); @@ -201,18 +225,24 @@ namespace Newtonsoft.Json.Serialization /// The type to create. /// Optional arguments to pass to an initializing constructor of the JsonConverter. /// If null, the default constructor is used. + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static JsonConverter CreateJsonConverterInstance(Type converterType, object[]? args) { - Func converterCreator = CreatorCache.Get(converterType); + Func converterCreator = CreatorCache.Instance.Get(converterType); return (JsonConverter)converterCreator(args); } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static NamingStrategy CreateNamingStrategyInstance(Type namingStrategyType, object[]? args) { - Func converterCreator = CreatorCache.Get(namingStrategyType); + Func converterCreator = CreatorCache.Instance.Get(namingStrategyType); return (NamingStrategy)converterCreator(args); } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static NamingStrategy? GetContainerNamingStrategy(JsonContainerAttribute containerAttribute) { if (containerAttribute.NamingStrategyInstance == null) @@ -228,7 +258,10 @@ namespace Newtonsoft.Json.Serialization return containerAttribute.NamingStrategyInstance; } - private static Func GetCreator(Type type) + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] + private static Func GetCreator( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] + Type type) { Func? defaultConstructor = (ReflectionUtils.HasDefaultConstructor(type, false)) ? ReflectionDelegateFactory.CreateDefaultConstructor(type) @@ -277,11 +310,15 @@ namespace Newtonsoft.Json.Serialization } #if !(NET20 || DOTNET) + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private static Type? GetAssociatedMetadataType(Type type) { - return AssociatedMetadataTypesCache.Get(type); + return AssociatedMetadataTypesCache.Instance.Get(type); } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private static Type? GetAssociateMetadataTypeFromAttribute(Type type) { Attribute[] customAttributes = ReflectionUtils.GetAttributes(type, null, true); @@ -309,7 +346,9 @@ namespace Newtonsoft.Json.Serialization } #endif - private static T? GetAttribute(Type type) where T : Attribute + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] + private static T? GetAttribute([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] Type type) where T : Attribute { T? attribute; @@ -343,6 +382,8 @@ namespace Newtonsoft.Json.Serialization return null; } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private static T? GetAttribute(MemberInfo memberInfo) where T : Attribute { T? attribute; @@ -424,6 +465,8 @@ namespace Newtonsoft.Json.Serialization } #endif + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static T? GetAttribute(object provider) where T : Attribute { if (provider is Type type) diff --git a/Src/Newtonsoft.Json/Utilities/CollectionUtils.cs b/Src/Newtonsoft.Json/Utilities/CollectionUtils.cs index 8b0a0125..be6fda06 100644 --- a/Src/Newtonsoft.Json/Utilities/CollectionUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/CollectionUtils.cs @@ -26,6 +26,7 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Text; using System.Collections; @@ -94,6 +95,7 @@ namespace Newtonsoft.Json.Utilities } #endif + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] public static bool IsDictionaryType(Type type) { ValidationUtils.ArgumentNotNull(type, nameof(type)); @@ -116,14 +118,23 @@ namespace Newtonsoft.Json.Utilities return false; } - public static ConstructorInfo? ResolveEnumerableCollectionConstructor(Type collectionType, Type collectionItemType) + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] + public static ConstructorInfo? ResolveEnumerableCollectionConstructor( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] + Type collectionType, + Type collectionItemType) { Type genericConstructorArgument = typeof(IList<>).MakeGenericType(collectionItemType); return ResolveEnumerableCollectionConstructor(collectionType, collectionItemType, genericConstructorArgument); } - public static ConstructorInfo? ResolveEnumerableCollectionConstructor(Type collectionType, Type collectionItemType, Type constructorArgumentType) + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] + public static ConstructorInfo? ResolveEnumerableCollectionConstructor( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] + Type collectionType, + Type collectionItemType, + Type constructorArgumentType) { Type genericEnumerable = typeof(IEnumerable<>).MakeGenericType(collectionItemType); ConstructorInfo? match = null; @@ -351,6 +362,7 @@ namespace Newtonsoft.Json.Utilities return currentList; } + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static Array ToMultidimensionalArray(IList values, Type type, int rank) { IList dimensions = GetDimensions(values, rank); diff --git a/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs b/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs index b6837eca..4c1b2360 100644 --- a/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/ConvertUtils.cs @@ -198,6 +198,7 @@ namespace Newtonsoft.Json.Utilities return GetTypeCode(t, out _); } + [UnconditionalSuppressMessage("AotAnalysis", "IL3050", Justification = "Nullable instantiated over primitive types are kept by TypeCodeMap")] public static PrimitiveTypeCode GetTypeCode(Type t, out bool isEnum) { if (TypeCodeMap.TryGetValue(t, out PrimitiveTypeCode typeCode)) @@ -256,9 +257,16 @@ namespace Newtonsoft.Json.Utilities #endif } - private static readonly ThreadSafeStore, Func?> CastConverters = - new ThreadSafeStore, Func?>(CreateCastConverter); + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] + static class CastConverters + { + public static readonly ThreadSafeStore, Func?> Instance = + new ThreadSafeStore, Func?>(CreateCastConverter); + } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private static Func? CreateCastConverter(StructMultiKey t) { Type initialType = t.Value1; @@ -369,6 +377,8 @@ namespace Newtonsoft.Json.Utilities NoValidConversion = 3 } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static object Convert(object initialValue, CultureInfo culture, Type targetType) { switch (TryConvertInternal(initialValue, culture, targetType, out object? value)) @@ -386,6 +396,8 @@ namespace Newtonsoft.Json.Utilities } } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private static bool TryConvert(object? initialValue, CultureInfo culture, Type targetType, out object? value) { try @@ -405,6 +417,8 @@ namespace Newtonsoft.Json.Utilities } } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private static ConvertResult TryConvertInternal(object? initialValue, CultureInfo culture, Type targetType, out object? value) { if (initialValue == null) @@ -587,6 +601,8 @@ namespace Newtonsoft.Json.Utilities /// The converted type. If conversion was unsuccessful, the initial value /// is returned if assignable to the target type. /// + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static object? ConvertOrCast(object? initialValue, CultureInfo culture, Type targetType) { if (targetType == typeof(object)) @@ -607,6 +623,8 @@ namespace Newtonsoft.Json.Utilities return EnsureTypeAssignable(initialValue, ReflectionUtils.GetObjectType(initialValue)!, targetType); } #endregion + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private static object? EnsureTypeAssignable(object? value, Type initialType, Type targetType) { @@ -619,7 +637,7 @@ namespace Newtonsoft.Json.Utilities return value; } - Func? castConverter = CastConverters.Get(new StructMultiKey(valueType, targetType)); + Func? castConverter = CastConverters.Instance.Get(new StructMultiKey(valueType, targetType)); if (castConverter != null) { return castConverter(value); diff --git a/Src/Newtonsoft.Json/Utilities/DynamicProxy.cs b/Src/Newtonsoft.Json/Utilities/DynamicProxy.cs index 76734ca3..77f35c3b 100644 --- a/Src/Newtonsoft.Json/Utilities/DynamicProxy.cs +++ b/Src/Newtonsoft.Json/Utilities/DynamicProxy.cs @@ -25,6 +25,7 @@ #if HAVE_DYNAMIC using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Dynamic; namespace Newtonsoft.Json.Utilities @@ -42,6 +43,7 @@ namespace Newtonsoft.Json.Utilities return false; } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] public virtual bool TryConvert(T instance, ConvertBinder binder, out object? result) { result = null; diff --git a/Src/Newtonsoft.Json/Utilities/DynamicProxyMetaObject.cs b/Src/Newtonsoft.Json/Utilities/DynamicProxyMetaObject.cs index a00cc2ce..c2ab0de4 100644 --- a/Src/Newtonsoft.Json/Utilities/DynamicProxyMetaObject.cs +++ b/Src/Newtonsoft.Json/Utilities/DynamicProxyMetaObject.cs @@ -1,4 +1,4 @@ -#region License +#region License // Copyright (c) 2007 James Newton-King // // Permission is hereby granted, free of charge, to any person @@ -26,12 +26,15 @@ #if HAVE_DYNAMIC using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Dynamic; using System.Linq; using System.Linq.Expressions; namespace Newtonsoft.Json.Utilities { + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] internal sealed class DynamicProxyMetaObject : DynamicMetaObject { private readonly DynamicProxy _proxy; @@ -373,6 +376,7 @@ namespace Newtonsoft.Json.Utilities // is only used by DynamicObject.GetMember--it is not expected to // (and cannot) implement binding semantics. It is just so the DO // can use the Name and IgnoreCase properties. + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private sealed class GetBinderAdapter : GetMemberBinder { internal GetBinderAdapter(InvokeMemberBinder binder) : diff --git a/Src/Newtonsoft.Json/Utilities/DynamicReflectionDelegateFactory.cs b/Src/Newtonsoft.Json/Utilities/DynamicReflectionDelegateFactory.cs index 10b4acb3..beb7002f 100644 --- a/Src/Newtonsoft.Json/Utilities/DynamicReflectionDelegateFactory.cs +++ b/Src/Newtonsoft.Json/Utilities/DynamicReflectionDelegateFactory.cs @@ -26,6 +26,7 @@ #if HAVE_REFLECTION_EMIT using System; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; #if !HAVE_LINQ using Newtonsoft.Json.Utilities.LinqBridge; #endif @@ -40,6 +41,7 @@ namespace Newtonsoft.Json.Utilities { internal static DynamicReflectionDelegateFactory Instance { get; } = new DynamicReflectionDelegateFactory(); + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private static DynamicMethod CreateDynamicMethod(string name, Type? returnType, Type[] parameterTypes, Type owner) { DynamicMethod dynamicMethod = !owner.IsInterface() @@ -49,6 +51,7 @@ namespace Newtonsoft.Json.Utilities return dynamicMethod; } + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public override ObjectConstructor CreateParameterizedConstructor(MethodBase method) { DynamicMethod dynamicMethod = CreateDynamicMethod(method.ToString()!, typeof(object), new[] { typeof(object[]) }, method.DeclaringType!); @@ -59,6 +62,7 @@ namespace Newtonsoft.Json.Utilities return (ObjectConstructor)dynamicMethod.CreateDelegate(typeof(ObjectConstructor)); } + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public override MethodCall CreateMethodCall(MethodBase method) { DynamicMethod dynamicMethod = CreateDynamicMethod(method.ToString()!, typeof(object), new[] { typeof(object), typeof(object[]) }, method.DeclaringType!); @@ -242,7 +246,10 @@ namespace Newtonsoft.Json.Utilities generator.Return(); } - public override Func CreateDefaultConstructor(Type type) + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] + public override Func CreateDefaultConstructor( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] + Type type) { DynamicMethod dynamicMethod = CreateDynamicMethod("Create" + type.FullName, typeof(T), ReflectionUtils.EmptyTypes, type); dynamicMethod.InitLocals = true; @@ -253,7 +260,11 @@ namespace Newtonsoft.Json.Utilities return (Func)dynamicMethod.CreateDelegate(typeof(Func)); } - private void GenerateCreateDefaultConstructorIL(Type type, ILGenerator generator, Type delegateType) + private void GenerateCreateDefaultConstructorIL( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] + Type type, + ILGenerator generator, + Type delegateType) { if (type.IsValueType()) { @@ -282,6 +293,7 @@ namespace Newtonsoft.Json.Utilities generator.Return(); } + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public override Func CreateGet(PropertyInfo propertyInfo) { DynamicMethod dynamicMethod = CreateDynamicMethod("Get" + propertyInfo.Name, typeof(object), new[] { typeof(T) }, propertyInfo.DeclaringType!); @@ -310,6 +322,7 @@ namespace Newtonsoft.Json.Utilities generator.Return(); } + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public override Func CreateGet(FieldInfo fieldInfo) { if (fieldInfo.IsLiteral) @@ -343,6 +356,7 @@ namespace Newtonsoft.Json.Utilities generator.Return(); } + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public override Action CreateSet(FieldInfo fieldInfo) { DynamicMethod dynamicMethod = CreateDynamicMethod("Set" + fieldInfo.Name, null, new[] { typeof(T), typeof(object) }, fieldInfo.DeclaringType!); @@ -375,6 +389,7 @@ namespace Newtonsoft.Json.Utilities generator.Return(); } + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public override Action CreateSet(PropertyInfo propertyInfo) { DynamicMethod dynamicMethod = CreateDynamicMethod("Set" + propertyInfo.Name, null, new[] { typeof(T), typeof(object) }, propertyInfo.DeclaringType!); diff --git a/Src/Newtonsoft.Json/Utilities/DynamicUtils.cs b/Src/Newtonsoft.Json/Utilities/DynamicUtils.cs index 51aa7413..5eac5440 100644 --- a/Src/Newtonsoft.Json/Utilities/DynamicUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/DynamicUtils.cs @@ -39,6 +39,7 @@ using System.Text; using System.Globalization; using Newtonsoft.Json.Serialization; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; namespace Newtonsoft.Json.Utilities { @@ -60,6 +61,8 @@ namespace Newtonsoft.Json.Utilities private static MethodCall? _setMemberCall; private static bool _init; + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private static void Init() { if (!_init) @@ -80,6 +83,7 @@ namespace Newtonsoft.Json.Utilities } } + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private static object CreateSharpArgumentInfoArray(params int[] values) { Type csharpArgumentInfoType = Type.GetType(CSharpArgumentInfoTypeName, true)!; @@ -97,6 +101,8 @@ namespace Newtonsoft.Json.Utilities return a; } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private static void CreateMemberCalls() { Type csharpArgumentInfoType = Type.GetType(CSharpArgumentInfoTypeName, true)!; @@ -113,6 +119,8 @@ namespace Newtonsoft.Json.Utilities } #endif + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static CallSiteBinder GetMember(string name, Type context) { #if !HAVE_REFLECTION_BINDER @@ -126,6 +134,8 @@ namespace Newtonsoft.Json.Utilities #endif } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static CallSiteBinder SetMember(string name, Type context) { #if !HAVE_REFLECTION_BINDER @@ -151,6 +161,7 @@ namespace Newtonsoft.Json.Utilities } } + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] internal class NoThrowGetBinderMember : GetMemberBinder { private readonly GetMemberBinder _innerBinder; @@ -173,6 +184,7 @@ namespace Newtonsoft.Json.Utilities } } + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] internal class NoThrowSetBinderMember : SetMemberBinder { private readonly SetMemberBinder _innerBinder; diff --git a/Src/Newtonsoft.Json/Utilities/DynamicallyAccessedMemberTypes.cs b/Src/Newtonsoft.Json/Utilities/DynamicallyAccessedMemberTypes.cs new file mode 100644 index 00000000..1c62d6ca --- /dev/null +++ b/Src/Newtonsoft.Json/Utilities/DynamicallyAccessedMemberTypes.cs @@ -0,0 +1,99 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +#if !NET5_0_OR_GREATER + +namespace System.Diagnostics.CodeAnalysis +{ + /// + /// Specifies the types of members that are dynamically accessed. + /// + /// This enumeration has a attribute that allows a + /// bitwise combination of its member values. + /// + [Flags] + internal enum DynamicallyAccessedMemberTypes + { + /// + /// Specifies no members. + /// + None = 0, + + /// + /// Specifies the default, parameterless public constructor. + /// + PublicParameterlessConstructor = 0x0001, + + /// + /// Specifies all public constructors. + /// + PublicConstructors = 0x0002 | PublicParameterlessConstructor, + + /// + /// Specifies all non-public constructors. + /// + NonPublicConstructors = 0x0004, + + /// + /// Specifies all public methods. + /// + PublicMethods = 0x0008, + + /// + /// Specifies all non-public methods. + /// + NonPublicMethods = 0x0010, + + /// + /// Specifies all public fields. + /// + PublicFields = 0x0020, + + /// + /// Specifies all non-public fields. + /// + NonPublicFields = 0x0040, + + /// + /// Specifies all public nested types. + /// + PublicNestedTypes = 0x0080, + + /// + /// Specifies all non-public nested types. + /// + NonPublicNestedTypes = 0x0100, + + /// + /// Specifies all public properties. + /// + PublicProperties = 0x0200, + + /// + /// Specifies all non-public properties. + /// + NonPublicProperties = 0x0400, + + /// + /// Specifies all public events. + /// + PublicEvents = 0x0800, + + /// + /// Specifies all non-public events. + /// + NonPublicEvents = 0x1000, + + /// + /// Specifies all interfaces implemented by the type. + /// + Interfaces = 0x2000, + + /// + /// Specifies all members. + /// + All = ~None + } +} + +#endif // !NET5_0_OR_GREATER diff --git a/Src/Newtonsoft.Json/Utilities/DynamicallyAccessedMembersAttribute.cs b/Src/Newtonsoft.Json/Utilities/DynamicallyAccessedMembersAttribute.cs new file mode 100644 index 00000000..61b27a40 --- /dev/null +++ b/Src/Newtonsoft.Json/Utilities/DynamicallyAccessedMembersAttribute.cs @@ -0,0 +1,55 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +#if !NET5_0_OR_GREATER + +namespace System.Diagnostics.CodeAnalysis +{ + /// + /// Indicates that certain members on a specified are accessed dynamically, + /// for example through . + /// + /// + /// This allows tools to understand which members are being accessed during the execution + /// of a program. + /// + /// This attribute is valid on members whose type is or . + /// + /// When this attribute is applied to a location of type , the assumption is + /// that the string represents a fully qualified type name. + /// + /// When this attribute is applied to a class, interface, or struct, the members specified + /// can be accessed dynamically on instances returned from calling + /// on instances of that class, interface, or struct. + /// + /// If the attribute is applied to a method it's treated as a special case and it implies + /// the attribute should be applied to the "this" parameter of the method. As such the attribute + /// should only be used on instance methods of types assignable to System.Type (or string, but no methods + /// will use it there). + /// + [AttributeUsage( + AttributeTargets.Field | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter | + AttributeTargets.Parameter | AttributeTargets.Property | AttributeTargets.Method | + AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct, + Inherited = false)] + internal sealed class DynamicallyAccessedMembersAttribute : Attribute + { + /// + /// Initializes a new instance of the class + /// with the specified member types. + /// + /// The types of members dynamically accessed. + public DynamicallyAccessedMembersAttribute(DynamicallyAccessedMemberTypes memberTypes) + { + MemberTypes = memberTypes; + } + + /// + /// Gets the which specifies the type + /// of members dynamically accessed. + /// + public DynamicallyAccessedMemberTypes MemberTypes { get; } + } +} + +#endif // !NET5_0_OR_GREATER diff --git a/Src/Newtonsoft.Json/Utilities/EnumUtils.cs b/Src/Newtonsoft.Json/Utilities/EnumUtils.cs index a1b3bae9..8376dcfb 100644 --- a/Src/Newtonsoft.Json/Utilities/EnumUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/EnumUtils.cs @@ -48,6 +48,7 @@ namespace Newtonsoft.Json.Utilities private static readonly ThreadSafeStore, EnumInfo> ValuesAndNamesPerEnum = new ThreadSafeStore, EnumInfo>(InitializeValuesAndNames); + [UnconditionalSuppressMessage("TrimAnalysis", "IL2080", Justification = "Enum fields are not trimmed")] private static EnumInfo InitializeValuesAndNames(StructMultiKey key) { Type enumType = key.Value1; diff --git a/Src/Newtonsoft.Json/Utilities/ExpressionReflectionDelegateFactory.cs b/Src/Newtonsoft.Json/Utilities/ExpressionReflectionDelegateFactory.cs index 36acc7c0..ad29a4e6 100644 --- a/Src/Newtonsoft.Json/Utilities/ExpressionReflectionDelegateFactory.cs +++ b/Src/Newtonsoft.Json/Utilities/ExpressionReflectionDelegateFactory.cs @@ -26,6 +26,7 @@ #if !(NET20 || NET35) using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Text; using System; @@ -41,6 +42,7 @@ namespace Newtonsoft.Json.Utilities internal static ReflectionDelegateFactory Instance => _instance; + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public override ObjectConstructor CreateParameterizedConstructor(MethodBase method) { ValidationUtils.ArgumentNotNull(method, nameof(method)); @@ -57,6 +59,7 @@ namespace Newtonsoft.Json.Utilities return compiled; } + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public override MethodCall CreateMethodCall(MethodBase method) { ValidationUtils.ArgumentNotNull(method, nameof(method)); @@ -187,7 +190,10 @@ namespace Newtonsoft.Json.Utilities return callExpression; } - public override Func CreateDefaultConstructor(Type type) + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] + public override Func CreateDefaultConstructor( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] + Type type) { ValidationUtils.ArgumentNotNull(type, "type"); @@ -218,6 +224,7 @@ namespace Newtonsoft.Json.Utilities } } + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public override Func CreateGet(PropertyInfo propertyInfo) { ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo)); @@ -253,6 +260,7 @@ namespace Newtonsoft.Json.Utilities return compiled; } + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public override Func CreateGet(FieldInfo fieldInfo) { ValidationUtils.ArgumentNotNull(fieldInfo, nameof(fieldInfo)); @@ -277,6 +285,7 @@ namespace Newtonsoft.Json.Utilities return compiled; } + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public override Action CreateSet(FieldInfo fieldInfo) { ValidationUtils.ArgumentNotNull(fieldInfo, nameof(fieldInfo)); @@ -313,6 +322,7 @@ namespace Newtonsoft.Json.Utilities return compiled; } + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public override Action CreateSet(PropertyInfo propertyInfo) { ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo)); diff --git a/Src/Newtonsoft.Json/Utilities/FSharpUtils.cs b/Src/Newtonsoft.Json/Utilities/FSharpUtils.cs index 925219ff..63ae3c34 100644 --- a/Src/Newtonsoft.Json/Utilities/FSharpUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/FSharpUtils.cs @@ -32,6 +32,7 @@ using System.Reflection; using System.Text; using Newtonsoft.Json.Serialization; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; namespace Newtonsoft.Json.Utilities { @@ -56,6 +57,8 @@ namespace Newtonsoft.Json.Utilities internal class FSharpUtils { + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private FSharpUtils(Assembly fsharpCoreAssembly) { FSharpCoreAssembly = fsharpCoreAssembly; @@ -100,6 +103,8 @@ namespace Newtonsoft.Json.Utilities } private MethodInfo _ofSeq; + + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] private Type _mapType; public Assembly FSharpCoreAssembly { get; private set; } @@ -117,6 +122,8 @@ namespace Newtonsoft.Json.Utilities public const string FSharpListTypeName = "FSharpList`1"; public const string FSharpMapTypeName = "FSharpMap`2"; + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public static void EnsureInitialized(Assembly fsharpCoreAssembly) { if (_instance == null) @@ -131,7 +138,11 @@ namespace Newtonsoft.Json.Utilities } } - private static MethodInfo GetMethodWithNonPublicFallback(Type type, string methodName, BindingFlags bindingFlags) + private static MethodInfo GetMethodWithNonPublicFallback( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] + Type type, + string methodName, + BindingFlags bindingFlags) { MethodInfo methodInfo = type.GetMethod(methodName, bindingFlags)!; @@ -147,6 +158,8 @@ namespace Newtonsoft.Json.Utilities return methodInfo!; } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] private static MethodCall CreateFSharpFuncCall(Type type, string methodName) { MethodInfo innerMethodInfo = GetMethodWithNonPublicFallback(type, methodName, BindingFlags.Public | BindingFlags.Static); @@ -166,6 +179,8 @@ namespace Newtonsoft.Json.Utilities return createFunction; } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public ObjectConstructor CreateSeq(Type t) { MethodInfo seqType = _ofSeq.MakeGenericMethod(t); @@ -173,6 +188,8 @@ namespace Newtonsoft.Json.Utilities return JsonTypeReflector.ReflectionDelegateFactory.CreateParameterizedConstructor(seqType); } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public ObjectConstructor CreateMap(Type keyType, Type valueType) { MethodInfo creatorDefinition = typeof(FSharpUtils).GetMethod("BuildMapCreator")!; @@ -182,6 +199,8 @@ namespace Newtonsoft.Json.Utilities return (ObjectConstructor)creatorGeneric.Invoke(this, null)!; } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public ObjectConstructor BuildMapCreator() { Type genericMapType = _mapType.MakeGenericType(typeof(TKey), typeof(TValue)); diff --git a/Src/Newtonsoft.Json/Utilities/FeatureGuardAttribute.cs b/Src/Newtonsoft.Json/Utilities/FeatureGuardAttribute.cs new file mode 100644 index 00000000..222f6d9b --- /dev/null +++ b/Src/Newtonsoft.Json/Utilities/FeatureGuardAttribute.cs @@ -0,0 +1,39 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +#if !NET9_0_OR_GREATER + +namespace System.Diagnostics.CodeAnalysis +{ + /// + /// Indicates that the specified public static boolean get-only property + /// guards access to the specified feature. + /// + /// + /// Analyzers can use this to prevent warnings on calls to code that is + /// annotated as requiring that feature, when the callsite is guarded by a + /// call to the property. + /// + [AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = true)] + internal sealed class FeatureGuardAttribute : Attribute + { + /// + /// Initializes a new instance of the class + /// with the specified feature type. + /// + /// + /// The type that represents the feature guarded by the property. + /// + public FeatureGuardAttribute(Type featureType) + { + FeatureType = featureType; + } + + /// + /// The type that represents the feature guarded by the property. + /// + public Type FeatureType { get; } + } +} + +#endif // !NET9_0_OR_GREATER diff --git a/Src/Newtonsoft.Json/Utilities/FeatureSwitchDefinitionAttribute.cs b/Src/Newtonsoft.Json/Utilities/FeatureSwitchDefinitionAttribute.cs new file mode 100644 index 00000000..99a9b88b --- /dev/null +++ b/Src/Newtonsoft.Json/Utilities/FeatureSwitchDefinitionAttribute.cs @@ -0,0 +1,38 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +#if !NET9_0_OR_GREATER + +namespace System.Diagnostics.CodeAnalysis +{ + /// + /// Indicates that the specified public static boolean get-only property + /// corresponds to the feature switch specified by name. + /// + /// + /// IL rewriters and compilers can use this to substitute the return value + /// of the specified property with the value of the feature switch. + /// + [AttributeUsage(AttributeTargets.Property, Inherited = false)] + internal sealed class FeatureSwitchDefinitionAttribute : Attribute + { + /// + /// Initializes a new instance of the class + /// with the specified feature switch name. + /// + /// + /// The name of the feature switch that provides the value for the specified property. + /// + public FeatureSwitchDefinitionAttribute(string switchName) + { + SwitchName = switchName; + } + + /// + /// The name of the feature switch that provides the value for the specified property. + /// + public string SwitchName { get; } + } +} + +#endif // !NET9_0_OR_GREATER diff --git a/Src/Newtonsoft.Json/Utilities/ImmutableCollectionsUtils.cs b/Src/Newtonsoft.Json/Utilities/ImmutableCollectionsUtils.cs index 8d7ba74d..fd2b931a 100644 --- a/Src/Newtonsoft.Json/Utilities/ImmutableCollectionsUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/ImmutableCollectionsUtils.cs @@ -111,6 +111,8 @@ namespace Newtonsoft.Json.Utilities new ImmutableCollectionTypeInfo(ImmutableDictionaryGenericTypeName, ImmutableDictionaryGenericTypeName, ImmutableDictionaryTypeName) }; + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] internal static bool TryBuildImmutableForArrayContract(Type underlyingType, Type collectionItemType, [NotNullWhen(true)]out Type? createdType, [NotNullWhen(true)]out ObjectConstructor? parameterizedCreator) { if (underlyingType.IsGenericType()) @@ -143,6 +145,8 @@ namespace Newtonsoft.Json.Utilities return false; } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] internal static bool TryBuildImmutableForDictionaryContract(Type underlyingType, Type keyItemType, Type valueItemType, [NotNullWhen(true)]out Type? createdType, [NotNullWhen(true)]out ObjectConstructor? parameterizedCreator) { if (underlyingType.IsGenericType()) diff --git a/Src/Newtonsoft.Json/Utilities/LateBoundReflectionDelegateFactory.cs b/Src/Newtonsoft.Json/Utilities/LateBoundReflectionDelegateFactory.cs index 67526268..5f46acf2 100644 --- a/Src/Newtonsoft.Json/Utilities/LateBoundReflectionDelegateFactory.cs +++ b/Src/Newtonsoft.Json/Utilities/LateBoundReflectionDelegateFactory.cs @@ -26,6 +26,7 @@ using System; using Newtonsoft.Json.Serialization; using System.Reflection; +using System.Diagnostics.CodeAnalysis; #if !HAVE_LINQ using Newtonsoft.Json.Utilities.LinqBridge; @@ -39,6 +40,7 @@ namespace Newtonsoft.Json.Utilities internal static ReflectionDelegateFactory Instance => _instance; + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public override ObjectConstructor CreateParameterizedConstructor(MethodBase method) { ValidationUtils.ArgumentNotNull(method, nameof(method)); @@ -53,6 +55,7 @@ namespace Newtonsoft.Json.Utilities return a => method.Invoke(null, a)!; } + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public override MethodCall CreateMethodCall(MethodBase method) { ValidationUtils.ArgumentNotNull(method, nameof(method)); @@ -65,7 +68,10 @@ namespace Newtonsoft.Json.Utilities return (o, a) => method.Invoke(o, a); } - public override Func CreateDefaultConstructor(Type type) + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] + public override Func CreateDefaultConstructor( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] + Type type) { ValidationUtils.ArgumentNotNull(type, nameof(type)); @@ -83,6 +89,7 @@ namespace Newtonsoft.Json.Utilities return () => (T)constructorInfo.Invoke(null); } + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public override Func CreateGet(PropertyInfo propertyInfo) { ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo)); @@ -90,6 +97,7 @@ namespace Newtonsoft.Json.Utilities return o => propertyInfo.GetValue(o, null); } + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public override Func CreateGet(FieldInfo fieldInfo) { ValidationUtils.ArgumentNotNull(fieldInfo, nameof(fieldInfo)); @@ -97,6 +105,7 @@ namespace Newtonsoft.Json.Utilities return o => fieldInfo.GetValue(o); } + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public override Action CreateSet(FieldInfo fieldInfo) { ValidationUtils.ArgumentNotNull(fieldInfo, nameof(fieldInfo)); @@ -104,6 +113,7 @@ namespace Newtonsoft.Json.Utilities return (o, v) => fieldInfo.SetValue(o, v); } + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public override Action CreateSet(PropertyInfo propertyInfo) { ValidationUtils.ArgumentNotNull(propertyInfo, nameof(propertyInfo)); diff --git a/Src/Newtonsoft.Json/Utilities/MiscellaneousUtils.cs b/Src/Newtonsoft.Json/Utilities/MiscellaneousUtils.cs index c469ce64..87b0fcaf 100644 --- a/Src/Newtonsoft.Json/Utilities/MiscellaneousUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/MiscellaneousUtils.cs @@ -40,6 +40,10 @@ namespace Newtonsoft.Json.Utilities internal static class MiscellaneousUtils { + internal const string TrimWarning = "Newtonsoft.Json relies on reflection over types that may be removed when trimming."; + + internal const string AotWarning = "Newtonsoft.Json relies on dynamically creating types that may not be available with Ahead of Time compilation."; + [Conditional("DEBUG")] public static void Assert([DoesNotReturnIf(false)] bool condition, string? message = null) { diff --git a/Src/Newtonsoft.Json/Utilities/ReflectionDelegateFactory.cs b/Src/Newtonsoft.Json/Utilities/ReflectionDelegateFactory.cs index 6b2d4ee2..a87346f7 100644 --- a/Src/Newtonsoft.Json/Utilities/ReflectionDelegateFactory.cs +++ b/Src/Newtonsoft.Json/Utilities/ReflectionDelegateFactory.cs @@ -24,6 +24,7 @@ #endregion using System; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Reflection; using Newtonsoft.Json.Serialization; @@ -36,6 +37,7 @@ namespace Newtonsoft.Json.Utilities { internal abstract class ReflectionDelegateFactory { + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public Func CreateGet(MemberInfo memberInfo) { if (memberInfo is PropertyInfo propertyInfo) @@ -57,6 +59,7 @@ namespace Newtonsoft.Json.Utilities throw new Exception("Could not create getter for {0}.".FormatWith(CultureInfo.InvariantCulture, memberInfo)); } + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public Action CreateSet(MemberInfo memberInfo) { if (memberInfo is PropertyInfo propertyInfo) @@ -72,12 +75,21 @@ namespace Newtonsoft.Json.Utilities throw new Exception("Could not create setter for {0}.".FormatWith(CultureInfo.InvariantCulture, memberInfo)); } + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public abstract MethodCall CreateMethodCall(MethodBase method); + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public abstract ObjectConstructor CreateParameterizedConstructor(MethodBase method); - public abstract Func CreateDefaultConstructor(Type type); + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] + public abstract Func CreateDefaultConstructor( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] + Type type); + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public abstract Func CreateGet(PropertyInfo propertyInfo); + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public abstract Func CreateGet(FieldInfo fieldInfo); + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public abstract Action CreateSet(FieldInfo fieldInfo); + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] public abstract Action CreateSet(PropertyInfo propertyInfo); } } \ No newline at end of file diff --git a/Src/Newtonsoft.Json/Utilities/ReflectionObject.cs b/Src/Newtonsoft.Json/Utilities/ReflectionObject.cs index 1463416d..90809521 100644 --- a/Src/Newtonsoft.Json/Utilities/ReflectionObject.cs +++ b/Src/Newtonsoft.Json/Utilities/ReflectionObject.cs @@ -28,6 +28,8 @@ using System; using System.Collections.Generic; using System.Reflection; using System.Globalization; +using System.Diagnostics.CodeAnalysis; + #if !HAVE_LINQ using Newtonsoft.Json.Utilities.LinqBridge; #else @@ -72,12 +74,35 @@ namespace Newtonsoft.Json.Utilities return Members[member].MemberType!; } - public static ReflectionObject Create(Type t, params string[] memberNames) + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] + public static ReflectionObject Create( + [DynamicallyAccessedMembers( + DynamicallyAccessedMemberTypes.NonPublicConstructors | + DynamicallyAccessedMemberTypes.PublicConstructors | + DynamicallyAccessedMemberTypes.PublicEvents | + DynamicallyAccessedMemberTypes.PublicFields | + DynamicallyAccessedMemberTypes.PublicMethods | + DynamicallyAccessedMemberTypes.PublicNestedTypes | + DynamicallyAccessedMemberTypes.PublicProperties)] + Type t, + params string[] memberNames) { return Create(t, null, memberNames); } - public static ReflectionObject Create(Type t, MethodBase? creator, params string[] memberNames) + [RequiresDynamicCode(MiscellaneousUtils.AotWarning)] + public static ReflectionObject Create( + [DynamicallyAccessedMembers( + DynamicallyAccessedMemberTypes.NonPublicConstructors | + DynamicallyAccessedMemberTypes.PublicConstructors | + DynamicallyAccessedMemberTypes.PublicEvents | + DynamicallyAccessedMemberTypes.PublicFields | + DynamicallyAccessedMemberTypes.PublicMethods | + DynamicallyAccessedMemberTypes.PublicNestedTypes | + DynamicallyAccessedMemberTypes.PublicProperties)] + Type t, + MethodBase? creator, + params string[] memberNames) { ReflectionDelegateFactory delegateFactory = JsonTypeReflector.ReflectionDelegateFactory; diff --git a/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs b/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs index f3d59424..bfa91771 100644 --- a/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs +++ b/Src/Newtonsoft.Json/Utilities/ReflectionUtils.cs @@ -233,7 +233,9 @@ namespace Newtonsoft.Json.Utilities return builder.ToString(); } - public static bool HasDefaultConstructor(Type t, bool nonPublic) + public static bool HasDefaultConstructor( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] Type t, + bool nonPublic) { ValidationUtils.ArgumentNotNull(t, nameof(t)); @@ -245,12 +247,15 @@ namespace Newtonsoft.Json.Utilities return (GetDefaultConstructor(t, nonPublic) != null); } - public static ConstructorInfo? GetDefaultConstructor(Type t) + public static ConstructorInfo? GetDefaultConstructor( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] Type t) { return GetDefaultConstructor(t, false); } - public static ConstructorInfo? GetDefaultConstructor(Type t, bool nonPublic) + public static ConstructorInfo? GetDefaultConstructor( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.NonPublicConstructors)] Type t, + bool nonPublic) { BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public; if (nonPublic) @@ -305,12 +310,18 @@ namespace Newtonsoft.Json.Utilities return (t == genericInterfaceDefinition); } - public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition) + public static bool ImplementsGenericDefinition( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] + Type type, + Type genericInterfaceDefinition) { return ImplementsGenericDefinition(type, genericInterfaceDefinition, out _); } - public static bool ImplementsGenericDefinition(Type type, Type genericInterfaceDefinition, [NotNullWhen(true)]out Type? implementingType) + public static bool ImplementsGenericDefinition( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] Type type, + Type genericInterfaceDefinition, + [NotNullWhen(true)]out Type? implementingType) { ValidationUtils.ArgumentNotNull(type, nameof(type)); ValidationUtils.ArgumentNotNull(genericInterfaceDefinition, nameof(genericInterfaceDefinition)); @@ -394,7 +405,9 @@ namespace Newtonsoft.Json.Utilities /// /// The type. /// The type of the typed collection's items. - public static Type? GetCollectionItemType(Type type) + public static Type? GetCollectionItemType( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] + Type type) { ValidationUtils.ArgumentNotNull(type, nameof(type)); @@ -419,7 +432,11 @@ namespace Newtonsoft.Json.Utilities throw new Exception("Type {0} is not a collection.".FormatWith(CultureInfo.InvariantCulture, type)); } - public static void GetDictionaryKeyValueTypes(Type dictionaryType, out Type? keyType, out Type? valueType) + public static void GetDictionaryKeyValueTypes( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] + Type dictionaryType, + out Type? keyType, + out Type? valueType) { ValidationUtils.ArgumentNotNull(dictionaryType, nameof(dictionaryType)); @@ -648,6 +665,7 @@ namespace Newtonsoft.Json.Utilities } } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] public static List GetFieldsAndProperties(Type type, BindingFlags bindingAttr) { List targetMembers = new List(); @@ -701,6 +719,7 @@ namespace Newtonsoft.Json.Utilities return distinctMembers; } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] private static bool IsOverridenGenericMember(MemberInfo memberInfo, BindingFlags bindingAttr) { if (memberInfo.MemberType() != MemberTypes.Property) @@ -885,7 +904,22 @@ namespace Newtonsoft.Json.Utilities return null; } - public static MemberInfo? GetMemberInfoFromType(Type targetType, MemberInfo memberInfo) + public static MemberInfo? GetMemberInfoFromType( + [DynamicallyAccessedMembers( + DynamicallyAccessedMemberTypes.NonPublicConstructors | + DynamicallyAccessedMemberTypes.NonPublicEvents | + DynamicallyAccessedMemberTypes.NonPublicFields | + DynamicallyAccessedMemberTypes.NonPublicMethods | + DynamicallyAccessedMemberTypes.NonPublicNestedTypes | + DynamicallyAccessedMemberTypes.NonPublicProperties | + DynamicallyAccessedMemberTypes.PublicConstructors | + DynamicallyAccessedMemberTypes.PublicEvents | + DynamicallyAccessedMemberTypes.PublicFields | + DynamicallyAccessedMemberTypes.PublicMethods | + DynamicallyAccessedMemberTypes.PublicNestedTypes | + DynamicallyAccessedMemberTypes.PublicProperties)] + Type targetType, + MemberInfo memberInfo) { const BindingFlags bindingAttr = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; @@ -902,7 +936,11 @@ namespace Newtonsoft.Json.Utilities } } - public static IEnumerable GetFields(Type targetType, BindingFlags bindingAttr) + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] + public static IEnumerable GetFields( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicFields | DynamicallyAccessedMemberTypes.NonPublicFields)] + Type targetType, + BindingFlags bindingAttr) { ValidationUtils.ArgumentNotNull(targetType, nameof(targetType)); @@ -917,6 +955,7 @@ namespace Newtonsoft.Json.Utilities } #if !PORTABLE + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] private static void GetChildPrivateFields(IList initialFields, Type type, BindingFlags bindingAttr) { Type? targetType = type; @@ -940,6 +979,7 @@ namespace Newtonsoft.Json.Utilities } #endif + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] public static IEnumerable GetProperties(Type targetType, BindingFlags bindingAttr) { ValidationUtils.ArgumentNotNull(targetType, nameof(targetType)); @@ -978,6 +1018,7 @@ namespace Newtonsoft.Json.Utilities : bindingAttr; } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] private static void GetChildPrivateProperties(IList initialProperties, Type type, BindingFlags bindingAttr) { // fix weirdness with private PropertyInfos only being returned for the current Type @@ -1045,7 +1086,11 @@ namespace Newtonsoft.Json.Utilities } } - public static bool IsMethodOverridden(Type currentType, Type methodDeclaringType, string method) + public static bool IsMethodOverridden( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods)] + Type currentType, + Type methodDeclaringType, + string method) { bool isMethodOverriden = currentType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance) .Any(info => @@ -1058,7 +1103,9 @@ namespace Newtonsoft.Json.Utilities return isMethodOverriden; } - public static object? GetDefaultValue(Type type) + public static object? GetDefaultValue( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)] + Type type) { if (!type.IsValueType()) { diff --git a/Src/Newtonsoft.Json/Utilities/RequiresDynamicCodeAttribute.cs b/Src/Newtonsoft.Json/Utilities/RequiresDynamicCodeAttribute.cs new file mode 100644 index 00000000..645c4a5b --- /dev/null +++ b/Src/Newtonsoft.Json/Utilities/RequiresDynamicCodeAttribute.cs @@ -0,0 +1,43 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +#if !NET7_0_OR_GREATER + +namespace System.Diagnostics.CodeAnalysis +{ + /// + /// Indicates that the specified method requires the ability to generate new code at runtime, + /// for example through . + /// + /// + /// This allows tools to understand which methods are unsafe to call when compiling ahead of time. + /// + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class, Inherited = false)] + internal sealed class RequiresDynamicCodeAttribute : Attribute + { + /// + /// Initializes a new instance of the class + /// with the specified message. + /// + /// + /// A message that contains information about the usage of dynamic code. + /// + public RequiresDynamicCodeAttribute(string message) + { + Message = message; + } + + /// + /// Gets a message that contains information about the usage of dynamic code. + /// + public string Message { get; } + + /// + /// Gets or sets an optional URL that contains more information about the method, + /// why it requires dynamic code, and what options a consumer has to deal with it. + /// + public string? Url { get; set; } + } +} + +#endif // !NET7_0_OR_GREATER diff --git a/Src/Newtonsoft.Json/Utilities/RequiresUnreferencedCodeAttribute.cs b/Src/Newtonsoft.Json/Utilities/RequiresUnreferencedCodeAttribute.cs new file mode 100644 index 00000000..5359917e --- /dev/null +++ b/Src/Newtonsoft.Json/Utilities/RequiresUnreferencedCodeAttribute.cs @@ -0,0 +1,44 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +#if !NET5_0_OR_GREATER + +namespace System.Diagnostics.CodeAnalysis +{ + /// + /// Indicates that the specified method requires dynamic access to code that is not referenced + /// statically, for example through . + /// + /// + /// This allows tools to understand which methods are unsafe to call when removing unreferenced + /// code from an application. + /// + [AttributeUsage(AttributeTargets.Method | AttributeTargets.Constructor | AttributeTargets.Class, Inherited = false)] + internal sealed class RequiresUnreferencedCodeAttribute : Attribute + { + /// + /// Initializes a new instance of the class + /// with the specified message. + /// + /// + /// A message that contains information about the usage of unreferenced code. + /// + public RequiresUnreferencedCodeAttribute(string message) + { + Message = message; + } + + /// + /// Gets a message that contains information about the usage of unreferenced code. + /// + public string Message { get; } + + /// + /// Gets or sets an optional URL that contains more information about the method, + /// why it requires unreferenced code, and what options a consumer has to deal with it. + /// + public string? Url { get; set; } + } +} + +#endif // !NET5_0_OR_GREATER diff --git a/Src/Newtonsoft.Json/Utilities/TypeExtensions.cs b/Src/Newtonsoft.Json/Utilities/TypeExtensions.cs index 934302d6..1299d801 100644 --- a/Src/Newtonsoft.Json/Utilities/TypeExtensions.cs +++ b/Src/Newtonsoft.Json/Utilities/TypeExtensions.cs @@ -578,7 +578,31 @@ namespace Newtonsoft.Json.Utilities #endif } - public static bool AssignableToTypeName(this Type type, string fullTypeName, bool searchInterfaces, [NotNullWhen(true)]out Type? match) + public static bool AssignableToTypeNameIncludingInterfaces( + [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)] + this Type type, + string fullTypeName, + [NotNullWhen(true)]out Type? match) + { + if (AssignableToTypeName(type, fullTypeName, out match)) + { + return true; + } + + foreach (Type i in type.GetInterfaces()) + { + if (string.Equals(i.Name, fullTypeName, StringComparison.Ordinal)) + { + match = type; + return true; + } + } + + match = null; + return false; + } + + public static bool AssignableToTypeName(this Type type, string fullTypeName, [NotNullWhen(true)]out Type? match) { Type? current = type; @@ -593,27 +617,16 @@ namespace Newtonsoft.Json.Utilities current = current.BaseType(); } - if (searchInterfaces) - { - foreach (Type i in type.GetInterfaces()) - { - if (string.Equals(i.Name, fullTypeName, StringComparison.Ordinal)) - { - match = type; - return true; - } - } - } - match = null; return false; } - public static bool AssignableToTypeName(this Type type, string fullTypeName, bool searchInterfaces) + public static bool AssignableToTypeName(this Type type, string fullTypeName) { - return type.AssignableToTypeName(fullTypeName, searchInterfaces, out _); + return AssignableToTypeName(type, fullTypeName, out _); } + [RequiresUnreferencedCode(MiscellaneousUtils.TrimWarning)] public static bool ImplementInterface(this Type type, Type interfaceType) { for (Type? currentType = type; currentType != null; currentType = currentType.BaseType()) diff --git a/Src/Newtonsoft.Json/Utilities/UnconditionalSuppressMessageAttribute.cs b/Src/Newtonsoft.Json/Utilities/UnconditionalSuppressMessageAttribute.cs new file mode 100644 index 00000000..4478b7a7 --- /dev/null +++ b/Src/Newtonsoft.Json/Utilities/UnconditionalSuppressMessageAttribute.cs @@ -0,0 +1,89 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +#if !NET5_0_OR_GREATER + +namespace System.Diagnostics.CodeAnalysis +{ + /// + /// Suppresses reporting of a specific rule violation, allowing multiple suppressions on a + /// single code artifact. + /// + /// + /// is different than + /// in that it doesn't have a + /// . So it is always preserved in the compiled assembly. + /// + [AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)] + internal sealed class UnconditionalSuppressMessageAttribute : Attribute + { + /// + /// Initializes a new instance of the + /// class, specifying the category of the tool and the identifier for an analysis rule. + /// + /// The category for the attribute. + /// The identifier of the analysis rule the attribute applies to. + public UnconditionalSuppressMessageAttribute(string category, string checkId) + { + Category = category; + CheckId = checkId; + } + + /// + /// Gets the category identifying the classification of the attribute. + /// + /// + /// The property describes the tool or tool analysis category + /// for which a message suppression attribute applies. + /// + public string Category { get; } + + /// + /// Gets the identifier of the analysis tool rule to be suppressed. + /// + /// + /// Concatenated together, the and + /// properties form a unique check identifier. + /// + public string CheckId { get; } + + /// + /// Gets or sets the scope of the code that is relevant for the attribute. + /// + /// + /// The Scope property is an optional argument that specifies the metadata scope for which + /// the attribute is relevant. + /// + public string? Scope { get; set; } + + /// + /// Gets or sets a fully qualified path that represents the target of the attribute. + /// + /// + /// The property is an optional argument identifying the analysis target + /// of the attribute. An example value is "System.IO.Stream.ctor():System.Void". + /// Because it is fully qualified, it can be long, particularly for targets such as parameters. + /// The analysis tool user interface should be capable of automatically formatting the parameter. + /// + public string? Target { get; set; } + + /// + /// Gets or sets an optional argument expanding on exclusion criteria. + /// + /// + /// The property is an optional argument that specifies additional + /// exclusion where the literal metadata target is not sufficiently precise. For example, + /// the cannot be applied within a method, + /// and it may be desirable to suppress a violation against a statement in the method that will + /// give a rule violation, but not against all statements in the method. + /// + public string? MessageId { get; set; } + + /// + /// Gets or sets the justification for suppressing the code analysis message. + /// + public string? Justification { get; set; } + } +} + +#endif // !NET5_0_OR_GREATER