From c131a1aebaf275746b0771ebc9f83604bd0be5ee Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20Cant=C3=BA?= Date: Thu, 20 Aug 2020 01:56:14 -0700 Subject: [PATCH 01/14] Add nullability annotations to System.Private.Xml.Linq project (#40744) * Add nullability annotations to Xml.Linq project * Fix misplaced assertion * Address feedback * Add missing NotNullIfNotNull attributes to operators --- .../src/System.Private.Xml.Linq.csproj | 1 + .../src/System/Xml/Linq/Extensions.cs | 102 ++++---- .../src/System/Xml/Linq/XAttribute.cs | 51 ++-- .../src/System/Xml/Linq/XComment.cs | 2 +- .../src/System/Xml/Linq/XContainer.cs | 185 +++++++------- .../src/System/Xml/Linq/XDeclaration.cs | 14 +- .../src/System/Xml/Linq/XDocument.cs | 32 +-- .../src/System/Xml/Linq/XDocumentType.cs | 16 +- .../src/System/Xml/Linq/XElement.cs | 146 ++++++----- .../src/System/Xml/Linq/XHashtable.cs | 13 +- .../src/System/Xml/Linq/XHelper.cs | 2 +- .../src/System/Xml/Linq/XLinq.cs | 120 ++++----- .../src/System/Xml/Linq/XName.cs | 18 +- .../src/System/Xml/Linq/XNamespace.cs | 42 ++-- .../src/System/Xml/Linq/XNode.cs | 84 +++---- .../src/System/Xml/Linq/XNodeBuilder.cs | 46 ++-- .../Xml/Linq/XNodeDocumentOrderComparer.cs | 8 +- .../System/Xml/Linq/XNodeEqualityComparer.cs | 12 +- .../src/System/Xml/Linq/XNodeReader.cs | 231 +++++++++--------- .../src/System/Xml/Linq/XObject.cs | 85 +++---- .../Xml/Linq/XObjectChangeAnnotation.cs | 4 +- .../System/Xml/Linq/XProcessingInstruction.cs | 2 +- .../src/System/Xml/Linq/XStreamingElement.cs | 6 +- .../src/System/Xml/Schema/XNodeValidator.cs | 161 ++++++------ .../src/System/Xml/XPath/XNodeNavigator.cs | 156 ++++++------ .../src/System/Xml/XPath/XObjectExtensions.cs | 4 +- .../src/System/Xml/XPath/XPathNavigator.cs | 4 +- 27 files changed, 809 insertions(+), 738 deletions(-) diff --git a/src/libraries/System.Private.Xml.Linq/src/System.Private.Xml.Linq.csproj b/src/libraries/System.Private.Xml.Linq/src/System.Private.Xml.Linq.csproj index 4db38b8700d29d..a174b927459d72 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System.Private.Xml.Linq.csproj +++ b/src/libraries/System.Private.Xml.Linq/src/System.Private.Xml.Linq.csproj @@ -2,6 +2,7 @@ System.Xml $(NetCoreAppCurrent) + enable in the target /// of . /// - public static IEnumerable Attributes(this IEnumerable source) + public static IEnumerable Attributes(this IEnumerable source) { if (source == null) throw new ArgumentNullException(nameof(source)); return GetAttributes(source, null); @@ -37,7 +37,7 @@ public static IEnumerable Attributes(this IEnumerable sour /// Attributes with a matching for every in /// the target of . /// - public static IEnumerable Attributes(this IEnumerable source, XName name) + public static IEnumerable Attributes(this IEnumerable source, XName? name) { if (source == null) throw new ArgumentNullException(nameof(source)); return name != null ? GetAttributes(source, name) : XAttribute.EmptySequence; @@ -53,7 +53,7 @@ public static IEnumerable Attributes(this IEnumerable sour /// and it's parent up to the root) of each of the s in this /// of . /// - public static IEnumerable Ancestors(this IEnumerable source) where T : XNode + public static IEnumerable Ancestors(this IEnumerable source) where T : XNode { if (source == null) throw new ArgumentNullException(nameof(source)); return GetAncestors(source, null, false); @@ -69,7 +69,7 @@ public static IEnumerable Ancestors(this IEnumerable source) whe /// and it's parent up to the root) that have a matching . This is done for each /// in this of . /// - public static IEnumerable Ancestors(this IEnumerable source, XName name) where T : XNode + public static IEnumerable Ancestors(this IEnumerable source, XName? name) where T : XNode { if (source == null) throw new ArgumentNullException(nameof(source)); return name != null ? GetAncestors(source, name, false) : XElement.EmptySequence; @@ -87,7 +87,7 @@ public static IEnumerable Ancestors(this IEnumerable source, XNa /// This is done for each in this of /// . /// - public static IEnumerable AncestorsAndSelf(this IEnumerable source) + public static IEnumerable AncestorsAndSelf(this IEnumerable source) { if (source == null) throw new ArgumentNullException(nameof(source)); return GetAncestors(source, null, true); @@ -105,7 +105,7 @@ public static IEnumerable AncestorsAndSelf(this IEnumerable /// that match the passed in . This is done for each /// in this of . /// - public static IEnumerable AncestorsAndSelf(this IEnumerable source, XName name) + public static IEnumerable AncestorsAndSelf(this IEnumerable source, XName? name) { if (source == null) throw new ArgumentNullException(nameof(source)); return name != null ? GetAncestors(source, name, true) : XElement.EmptySequence; @@ -114,24 +114,24 @@ public static IEnumerable AncestorsAndSelf(this IEnumerable /// /// Returns an of over the content of a set of nodes /// - public static IEnumerable Nodes(this IEnumerable source) where T : XContainer + public static IEnumerable Nodes(this IEnumerable source) where T : XContainer { if (source == null) throw new ArgumentNullException(nameof(source)); return NodesIterator(source); } - private static IEnumerable NodesIterator(IEnumerable source) where T : XContainer + private static IEnumerable NodesIterator(IEnumerable source) where T : XContainer { - foreach (XContainer root in source) + foreach (XContainer? root in source) { if (root != null) { - XNode n = root.LastNode; + XNode? n = root.LastNode; if (n != null) { do { - n = n.next; + n = n.next!; yield return n; } while (n.parent == root && n != root.content); } @@ -142,7 +142,7 @@ private static IEnumerable NodesIterator(IEnumerable source) where /// /// Returns an of over the descendants of a set of nodes /// - public static IEnumerable DescendantNodes(this IEnumerable source) where T : XContainer + public static IEnumerable DescendantNodes(this IEnumerable source) where T : XContainer { if (source == null) throw new ArgumentNullException(nameof(source)); return GetDescendantNodes(source, false); @@ -158,7 +158,7 @@ public static IEnumerable DescendantNodes(this IEnumerable source) /// and their children down to the leaf level). This is done for each in /// this of . /// - public static IEnumerable Descendants(this IEnumerable source) where T : XContainer + public static IEnumerable Descendants(this IEnumerable source) where T : XContainer { if (source == null) throw new ArgumentNullException(nameof(source)); return GetDescendants(source, null, false); @@ -174,7 +174,7 @@ public static IEnumerable Descendants(this IEnumerable source) w /// and their children down to the leaf level) that have a matching . This is done /// for each in this of . /// - public static IEnumerable Descendants(this IEnumerable source, XName name) where T : XContainer + public static IEnumerable Descendants(this IEnumerable source, XName? name) where T : XContainer { if (source == null) throw new ArgumentNullException(nameof(source)); return name != null ? GetDescendants(source, name, false) : XElement.EmptySequence; @@ -192,7 +192,7 @@ public static IEnumerable Descendants(this IEnumerable source, X /// This is done for each /// in this of . /// - public static IEnumerable DescendantNodesAndSelf(this IEnumerable source) + public static IEnumerable DescendantNodesAndSelf(this IEnumerable source) { if (source == null) throw new ArgumentNullException(nameof(source)); return GetDescendantNodes(source, true); @@ -210,7 +210,7 @@ public static IEnumerable DescendantNodesAndSelf(this IEnumerable in this /// of . /// - public static IEnumerable DescendantsAndSelf(this IEnumerable source) + public static IEnumerable DescendantsAndSelf(this IEnumerable source) { if (source == null) throw new ArgumentNullException(nameof(source)); return GetDescendants(source, null, true); @@ -228,7 +228,7 @@ public static IEnumerable DescendantsAndSelf(this IEnumerable. This is done for /// each in this of . /// - public static IEnumerable DescendantsAndSelf(this IEnumerable source, XName name) + public static IEnumerable DescendantsAndSelf(this IEnumerable source, XName? name) { if (source == null) throw new ArgumentNullException(nameof(source)); return name != null ? GetDescendants(source, name, true) : XElement.EmptySequence; @@ -242,7 +242,7 @@ public static IEnumerable DescendantsAndSelf(this IEnumerable of containing the child elements /// for each in this of . /// - public static IEnumerable Elements(this IEnumerable source) where T : XContainer + public static IEnumerable Elements(this IEnumerable source) where T : XContainer { if (source == null) throw new ArgumentNullException(nameof(source)); return GetElements(source, null); @@ -256,7 +256,7 @@ public static IEnumerable Elements(this IEnumerable source) wher /// An of containing the child elements /// for each in this of . /// - public static IEnumerable Elements(this IEnumerable source, XName name) where T : XContainer + public static IEnumerable Elements(this IEnumerable source, XName? name) where T : XContainer { if (source == null) throw new ArgumentNullException(nameof(source)); return name != null ? GetElements(source, name) : XElement.EmptySequence; @@ -277,6 +277,8 @@ public static IEnumerable InDocumentOrder(this IEnumerable source) wher return DocumentOrderIterator(source); } + // TODO-NULLABLE: Consider changing to T? instead. + // If we do it, we will also need to change XNodeDocumentOrderComparer to implement IComparer instead. private static IEnumerable DocumentOrderIterator(IEnumerable source) where T : XNode { int count; @@ -293,15 +295,15 @@ private static IEnumerable DocumentOrderIterator(IEnumerable source) wh /// . Note that this method uses snapshot semantics (copies the /// attributes to an array before deleting each). /// - public static void Remove(this IEnumerable source) + public static void Remove(this IEnumerable source) { if (source == null) throw new ArgumentNullException(nameof(source)); int count; - XAttribute[] attributes = EnumerableHelpers.ToArray(source, out count); + XAttribute?[] attributes = EnumerableHelpers.ToArray(source, out count); for (int i = 0; i < count; i++) { - XAttribute a = attributes[i]; + XAttribute? a = attributes[i]; if (a != null) a.Remove(); } } @@ -311,31 +313,31 @@ public static void Remove(this IEnumerable source) /// T which must be a derived from . Note that this method uses snapshot semantics /// (copies the s to an array before deleting each). /// - public static void Remove(this IEnumerable source) where T : XNode + public static void Remove(this IEnumerable source) where T : XNode { if (source == null) throw new ArgumentNullException(nameof(source)); int count; - T[] nodes = EnumerableHelpers.ToArray(source, out count); + T?[] nodes = EnumerableHelpers.ToArray(source, out count); for (int i = 0; i < count; i++) { - T node = nodes[i]; + T? node = nodes[i]; if (node != null) node.Remove(); } } - private static IEnumerable GetAttributes(IEnumerable source, XName name) + private static IEnumerable GetAttributes(IEnumerable source, XName? name) { - foreach (XElement e in source) + foreach (XElement? e in source) { if (e != null) { - XAttribute a = e.lastAttr; + XAttribute? a = e.lastAttr; if (a != null) { do { - a = a.next; + a = a.next!; if (name == null || a.name == name) yield return a; } while (a.parent == e && a != e.lastAttr); } @@ -343,13 +345,13 @@ private static IEnumerable GetAttributes(IEnumerable sourc } } - private static IEnumerable GetAncestors(IEnumerable source, XName name, bool self) where T : XNode + private static IEnumerable GetAncestors(IEnumerable source, XName? name, bool self) where T : XNode { - foreach (XNode node in source) + foreach (XNode? node in source) { if (node != null) { - XElement e = (self ? node : node.parent) as XElement; + XElement? e = (self ? node : node.parent) as XElement; while (e != null) { if (name == null || e.name == name) yield return e; @@ -359,27 +361,27 @@ private static IEnumerable GetAncestors(IEnumerable source, XNam } } - private static IEnumerable GetDescendantNodes(IEnumerable source, bool self) where T : XContainer + private static IEnumerable GetDescendantNodes(IEnumerable source, bool self) where T : XContainer { - foreach (XContainer root in source) + foreach (XContainer? root in source) { if (root != null) { if (self) yield return root; - XNode n = root; + XNode? n = root; while (true) { - XContainer c = n as XContainer; - XNode first; + XContainer? c = n as XContainer; + XNode? first; if (c != null && (first = c.FirstNode) != null) { n = first; } else { - while (n != null && n != root && n == n.parent.content) n = n.parent; + while (n != null && n != root && n == n.parent!.content) n = n.parent; if (n == null || n == root) break; - n = n.next; + n = n.next!; } yield return n; } @@ -387,9 +389,9 @@ private static IEnumerable GetDescendantNodes(IEnumerable source, b } } - private static IEnumerable GetDescendants(IEnumerable source, XName name, bool self) where T : XContainer + private static IEnumerable GetDescendants(IEnumerable source, XName? name, bool self) where T : XContainer { - foreach (XContainer root in source) + foreach (XContainer? root in source) { if (root != null) { @@ -398,8 +400,8 @@ private static IEnumerable GetDescendants(IEnumerable source, XN XElement e = (XElement)root; if (name == null || e.name == name) yield return e; } - XNode n = root; - XContainer c = root; + XNode? n = root; + XContainer? c = root; while (true) { if (c != null && c.content is XNode) @@ -408,11 +410,11 @@ private static IEnumerable GetDescendants(IEnumerable source, XN } else { - while (n != null && n != root && n == n.parent.content) n = n.parent; + while (n != null && n != root && n == n.parent!.content) n = n.parent; if (n == null || n == root) break; n = n.next; } - XElement e = n as XElement; + XElement? e = n as XElement; if (e != null && (name == null || e.name == name)) yield return e; c = e; } @@ -420,19 +422,19 @@ private static IEnumerable GetDescendants(IEnumerable source, XN } } - private static IEnumerable GetElements(IEnumerable source, XName name) where T : XContainer + private static IEnumerable GetElements(IEnumerable source, XName? name) where T : XContainer { - foreach (XContainer root in source) + foreach (XContainer? root in source) { if (root != null) { - XNode n = root.content as XNode; + XNode? n = root.content as XNode; if (n != null) { do { - n = n.next; - XElement e = n as XElement; + n = n.next!; + XElement? e = n as XElement; if (e != null && (name == null || e.name == name)) yield return e; } while (n.parent == root && n != root.content); } diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XAttribute.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XAttribute.cs index 0fde359789c234..deb5138f07d7fc 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XAttribute.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XAttribute.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.IO; using CultureInfo = System.Globalization.CultureInfo; @@ -29,7 +31,7 @@ public static IEnumerable EmptySequence } } - internal XAttribute next; + internal XAttribute? next; internal XName name; internal string value; @@ -105,7 +107,7 @@ public XName Name /// If this attribute does not have a parent, or if there is no next attribute, /// then this property returns null. /// - public XAttribute NextAttribute + public XAttribute? NextAttribute { get { return parent != null && ((XElement)parent).lastAttr != this ? next : null; } } @@ -131,15 +133,15 @@ public override XmlNodeType NodeType /// If this attribute does not have a parent, or if there is no previous attribute, /// then this property returns null. /// - public XAttribute PreviousAttribute + public XAttribute? PreviousAttribute { get { if (parent == null) return null; - XAttribute a = ((XElement)parent).lastAttr; + XAttribute a = ((XElement)parent).lastAttr!; while (a.next != this) { - a = a.next; + a = a.next!; } return a != ((XElement)parent).lastAttr ? a : null; } @@ -226,7 +228,8 @@ public override string ToString() /// The content of this as a . /// [CLSCompliant(false)] - public static explicit operator string(XAttribute attribute) + [return: NotNullIfNotNull("attribute")] + public static explicit operator string?(XAttribute? attribute) { if (attribute == null) return null; return attribute.value; @@ -261,7 +264,8 @@ public static explicit operator bool(XAttribute attribute) /// The content of this as a ?. /// [CLSCompliant(false)] - public static explicit operator bool?(XAttribute attribute) + [return: NotNullIfNotNull("attribute")] + public static explicit operator bool?(XAttribute? attribute) { if (attribute == null) return null; return XmlConvert.ToBoolean(attribute.value.ToLowerInvariant()); @@ -296,6 +300,7 @@ public static explicit operator int(XAttribute attribute) /// The content of this as an ?. /// [CLSCompliant(false)] + [return: NotNullIfNotNull("attribute")] public static explicit operator int?(XAttribute attribute) { if (attribute == null) return null; @@ -331,7 +336,8 @@ public static explicit operator uint(XAttribute attribute) /// The content of this as an ?. /// [CLSCompliant(false)] - public static explicit operator uint?(XAttribute attribute) + [return: NotNullIfNotNull("attribute")] + public static explicit operator uint?(XAttribute? attribute) { if (attribute == null) return null; return XmlConvert.ToUInt32(attribute.value); @@ -366,7 +372,8 @@ public static explicit operator long(XAttribute attribute) /// The content of this as a ?. /// [CLSCompliant(false)] - public static explicit operator long?(XAttribute attribute) + [return: NotNullIfNotNull("attribute")] + public static explicit operator long?(XAttribute? attribute) { if (attribute == null) return null; return XmlConvert.ToInt64(attribute.value); @@ -401,7 +408,8 @@ public static explicit operator ulong(XAttribute attribute) /// The content of this as an ?. /// [CLSCompliant(false)] - public static explicit operator ulong?(XAttribute attribute) + [return: NotNullIfNotNull("attribute")] + public static explicit operator ulong?(XAttribute? attribute) { if (attribute == null) return null; return XmlConvert.ToUInt64(attribute.value); @@ -436,7 +444,8 @@ public static explicit operator float(XAttribute attribute) /// The content of this as a ?. /// [CLSCompliant(false)] - public static explicit operator float?(XAttribute attribute) + [return: NotNullIfNotNull("attribute")] + public static explicit operator float?(XAttribute? attribute) { if (attribute == null) return null; return XmlConvert.ToSingle(attribute.value); @@ -471,7 +480,8 @@ public static explicit operator double(XAttribute attribute) /// The content of this as a ?. /// [CLSCompliant(false)] - public static explicit operator double?(XAttribute attribute) + [return: NotNullIfNotNull("attribute")] + public static explicit operator double?(XAttribute? attribute) { if (attribute == null) return null; return XmlConvert.ToDouble(attribute.value); @@ -506,7 +516,8 @@ public static explicit operator decimal(XAttribute attribute) /// The content of this as a ?. /// [CLSCompliant(false)] - public static explicit operator decimal?(XAttribute attribute) + [return: NotNullIfNotNull("attribute")] + public static explicit operator decimal?(XAttribute? attribute) { if (attribute == null) return null; return XmlConvert.ToDecimal(attribute.value); @@ -541,7 +552,8 @@ public static explicit operator DateTime(XAttribute attribute) /// The content of this as a ?. /// [CLSCompliant(false)] - public static explicit operator DateTime?(XAttribute attribute) + [return: NotNullIfNotNull("attribute")] + public static explicit operator DateTime?(XAttribute? attribute) { if (attribute == null) return null; return DateTime.Parse(attribute.value, CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.RoundtripKind); @@ -576,7 +588,8 @@ public static explicit operator DateTimeOffset(XAttribute attribute) /// The content of this as a ?. /// [CLSCompliant(false)] - public static explicit operator DateTimeOffset?(XAttribute attribute) + [return: NotNullIfNotNull("attribute")] + public static explicit operator DateTimeOffset?(XAttribute? attribute) { if (attribute == null) return null; return XmlConvert.ToDateTimeOffset(attribute.value); @@ -611,7 +624,8 @@ public static explicit operator TimeSpan(XAttribute attribute) /// The content of this as a ?. /// [CLSCompliant(false)] - public static explicit operator TimeSpan?(XAttribute attribute) + [return: NotNullIfNotNull("attribute")] + public static explicit operator TimeSpan?(XAttribute? attribute) { if (attribute == null) return null; return XmlConvert.ToTimeSpan(attribute.value); @@ -646,7 +660,8 @@ public static explicit operator Guid(XAttribute attribute) /// The content of this as a ?. /// [CLSCompliant(false)] - public static explicit operator Guid?(XAttribute attribute) + [return: NotNullIfNotNull("attribute")] + public static explicit operator Guid?(XAttribute? attribute) { if (attribute == null) return null; return XmlConvert.ToGuid(attribute.value); @@ -657,7 +672,7 @@ internal int GetDeepHashCode() return name.GetHashCode() ^ value.GetHashCode(); } - internal string GetPrefixOfNamespace(XNamespace ns) + internal string? GetPrefixOfNamespace(XNamespace ns) { string namespaceName = ns.NamespaceName; if (namespaceName.Length == 0) return string.Empty; diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XComment.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XComment.cs index 9f566c756b603d..dbb8ba0f9108a1 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XComment.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XComment.cs @@ -118,7 +118,7 @@ internal override XNode CloneNode() internal override bool DeepEquals(XNode node) { - XComment other = node as XComment; + XComment? other = node as XComment; return other != null && value == other.value; } diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XContainer.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XContainer.cs index d1fed61e1e1640..325c00d90cfc91 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XContainer.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XContainer.cs @@ -9,6 +9,7 @@ using IEnumerable = System.Collections.IEnumerable; using StringBuilder = System.Text.StringBuilder; using Interlocked = System.Threading.Interlocked; +using System.Diagnostics.CodeAnalysis; namespace System.Xml.Linq { @@ -21,7 +22,7 @@ namespace System.Xml.Linq /// public abstract class XContainer : XNode { - internal object content; + internal object? content; internal XContainer() { } @@ -34,12 +35,12 @@ internal XContainer(XContainer other) } else { - XNode n = (XNode)other.content; + XNode? n = (XNode?)other.content; if (n != null) { do { - n = n.next; + n = n.next!; AppendNodeSkipNotify(n.CloneNode()); } while (n != other.content); } @@ -49,11 +50,11 @@ internal XContainer(XContainer other) /// /// Get the first child node of this node. /// - public XNode FirstNode + public XNode? FirstNode { get { - XNode last = LastNode; + XNode? last = LastNode; return last != null ? last.next : null; } } @@ -61,14 +62,14 @@ public XNode FirstNode /// /// Get the last child node of this node. /// - public XNode LastNode + public XNode? LastNode { get { if (content == null) return null; - XNode n = content as XNode; + XNode? n = content as XNode; if (n != null) return n; - string s = content as string; + string? s = content as string; if (s != null) { if (s.Length == 0) return null; @@ -132,7 +133,7 @@ public XNode LastNode /// An added attribute must have a unique name within the element to /// which it is being added. /// - public void Add(object content) + public void Add(object? content) { if (SkipNotify()) { @@ -140,37 +141,37 @@ public void Add(object content) return; } if (content == null) return; - XNode n = content as XNode; + XNode? n = content as XNode; if (n != null) { AddNode(n); return; } - string s = content as string; + string? s = content as string; if (s != null) { AddString(s); return; } - XAttribute a = content as XAttribute; + XAttribute? a = content as XAttribute; if (a != null) { AddAttribute(a); return; } - XStreamingElement x = content as XStreamingElement; + XStreamingElement? x = content as XStreamingElement; if (x != null) { AddNode(new XElement(x)); return; } - object[] o = content as object[]; + object[]? o = content as object[]; if (o != null) { foreach (object obj in o) Add(obj); return; } - IEnumerable e = content as IEnumerable; + IEnumerable? e = content as IEnumerable; if (e != null) { foreach (object obj in e) Add(obj); @@ -210,7 +211,7 @@ public void Add(params object[] content) /// See for details about the content that can be added /// using this method. /// - public void AddFirst(object content) + public void AddFirst(object? content) { new Inserter(this, null).Add(content); } @@ -275,7 +276,7 @@ public IEnumerable Descendants() /// /// The to match against descendant s. /// An of - public IEnumerable Descendants(XName name) + public IEnumerable Descendants(XName? name) { return name != null ? GetDescendants(name, false) : XElement.EmptySequence; } @@ -291,15 +292,15 @@ public IEnumerable Descendants(XName name) /// /// An child that matches the passed in, or null. /// - public XElement Element(XName name) + public XElement? Element(XName name) { - XNode n = content as XNode; + XNode? n = content as XNode; if (n != null) { do { - n = n.next; - XElement e = n as XElement; + n = n.next!; + XElement? e = n as XElement; if (e != null && e.name == name) return e; } while (n != content); } @@ -330,7 +331,7 @@ public IEnumerable Elements() /// An of children of this that have /// a matching . /// - public IEnumerable Elements(XName name) + public IEnumerable Elements(XName? name) { return name != null ? GetElements(name) : XElement.EmptySequence; } @@ -348,12 +349,12 @@ public IEnumerable Elements(XName name) /// The contents of this public IEnumerable Nodes() { - XNode n = LastNode; + XNode? n = LastNode; if (n != null) { do { - n = n.next; + n = n.next!; yield return n; } while (n.parent == this && n != content); } @@ -373,7 +374,7 @@ public void RemoveNodes() } while (content != null) { - string s = content as string; + string? s = content as string; if (s != null) { if (s.Length > 0) @@ -397,10 +398,10 @@ public void RemoveNodes() } } } - XNode last = content as XNode; + XNode? last = content as XNode; if (last != null) { - XNode n = last.next; + XNode n = last.next!; NotifyChanging(n, XObjectChangeEventArgs.Remove); if (last != content || n != last.next) throw new InvalidOperationException(SR.InvalidOperation_ExternalCode); if (n != last) @@ -434,7 +435,7 @@ public void RemoveNodes() /// See XContainer.Add(object content) for details about the content that can be added /// using this method. /// - public void ReplaceNodes(object content) + public void ReplaceNodes(object? content) { content = GetContentSnapshot(content); RemoveNodes(); @@ -464,40 +465,40 @@ internal virtual void AddAttributeSkipNotify(XAttribute a) { } - internal void AddContentSkipNotify(object content) + internal void AddContentSkipNotify(object? content) { if (content == null) return; - XNode n = content as XNode; + XNode? n = content as XNode; if (n != null) { AddNodeSkipNotify(n); return; } - string s = content as string; + string? s = content as string; if (s != null) { AddStringSkipNotify(s); return; } - XAttribute a = content as XAttribute; + XAttribute? a = content as XAttribute; if (a != null) { AddAttributeSkipNotify(a); return; } - XStreamingElement x = content as XStreamingElement; + XStreamingElement? x = content as XStreamingElement; if (x != null) { AddNodeSkipNotify(new XElement(x)); return; } - object[] o = content as object[]; + object[]? o = content as object[]; if (o != null) { foreach (object obj in o) AddContentSkipNotify(obj); return; } - IEnumerable e = content as IEnumerable; + IEnumerable? e = content as IEnumerable; if (e != null) { foreach (object obj in e) AddContentSkipNotify(obj); @@ -569,7 +570,7 @@ internal void AddString(string s) else if (s.Length > 0) { ConvertTextToNode(); - XText tn = content as XText; + XText? tn = content as XText; if (tn != null && !(tn is XCData)) { tn.Value += s; @@ -590,14 +591,14 @@ internal void AddStringSkipNotify(string s) } else if (s.Length > 0) { - string stringContent = content as string; + string? stringContent = content as string; if (stringContent != null) { content = stringContent + s; } else { - XText tn = content as XText; + XText? tn = content as XText; if (tn != null && !(tn is XCData)) { tn.text += s; @@ -636,35 +637,35 @@ internal void AppendNodeSkipNotify(XNode n) internal override void AppendText(StringBuilder sb) { - string s = content as string; + string? s = content as string; if (s != null) { sb.Append(s); } else { - XNode n = (XNode)content; + XNode? n = (XNode?)content; if (n != null) { do { - n = n.next; + n = n.next!; n.AppendText(sb); } while (n != content); } } } - private string GetTextOnly() + private string? GetTextOnly() { if (content == null) return null; - string s = content as string; + string? s = content as string; if (s == null) { XNode n = (XNode)content; do { - n = n.next; + n = n.next!; if (n.NodeType != XmlNodeType.Text) return null; s += ((XText)n).Value; } while (n != content); @@ -672,7 +673,7 @@ private string GetTextOnly() return s; } - private string CollectText(ref XNode n) + private string CollectText(ref XNode? n) { string s = ""; while (n != null && n.NodeType == XmlNodeType.Text) @@ -686,10 +687,10 @@ private string CollectText(ref XNode n) internal bool ContentsEqual(XContainer e) { if (content == e.content) return true; - string s = GetTextOnly(); + string? s = GetTextOnly(); if (s != null) return s == e.GetTextOnly(); - XNode n1 = content as XNode; - XNode n2 = e.content as XNode; + XNode? n1 = content as XNode; + XNode? n2 = e.content as XNode; if (n1 != null && n2 != null) { n1 = n1.next; @@ -708,10 +709,10 @@ internal bool ContentsEqual(XContainer e) internal int ContentsHashCode() { - string s = GetTextOnly(); + string? s = GetTextOnly(); if (s != null) return s.GetHashCode(); int h = 0; - XNode n = content as XNode; + XNode? n = content as XNode; if (n != null) { do @@ -731,7 +732,7 @@ internal int ContentsHashCode() internal void ConvertTextToNode() { - string s = content as string; + string? s = content as string; if (!string.IsNullOrEmpty(s)) { XText t = new XText(s); @@ -747,23 +748,23 @@ internal IEnumerable GetDescendantNodes(bool self) XNode n = this; while (true) { - XContainer c = n as XContainer; - XNode first; + XContainer? c = n as XContainer; + XNode? first; if (c != null && (first = c.FirstNode) != null) { n = first; } else { - while (n != null && n != this && n == n.parent.content) n = n.parent; + while (n != null && n != this && n == n.parent!.content) n = n.parent; if (n == null || n == this) break; - n = n.next; + n = n.next!; } yield return n; } } - internal IEnumerable GetDescendants(XName name, bool self) + internal IEnumerable GetDescendants(XName? name, bool self) { if (self) { @@ -771,34 +772,34 @@ internal IEnumerable GetDescendants(XName name, bool self) if (name == null || e.name == name) yield return e; } XNode n = this; - XContainer c = this; + XContainer? c = this; while (true) { if (c != null && c.content is XNode) { - n = ((XNode)c.content).next; + n = ((XNode)c.content).next!; } else { - while (n != this && n == n.parent.content) n = n.parent; + while (n != this && n == n.parent!.content) n = n.parent; if (n == this) break; - n = n.next; + n = n.next!; } - XElement e = n as XElement; + XElement? e = n as XElement; if (e != null && (name == null || e.name == name)) yield return e; c = e; } } - private IEnumerable GetElements(XName name) + private IEnumerable GetElements(XName? name) { - XNode n = content as XNode; + XNode? n = content as XNode; if (n != null) { do { - n = n.next; - XElement e = n as XElement; + n = n.next!; + XElement? e = n as XElement; if (e != null && (name == null || e.name == name)) yield return e; } while (n.parent == this && n != content); } @@ -806,7 +807,7 @@ private IEnumerable GetElements(XName name) internal static string GetStringValue(object value) { - string s = value as string; + string? s = value as string; if (s != null) { return s; @@ -905,9 +906,9 @@ private sealed class ContentReader { private readonly NamespaceCache _eCache; private readonly NamespaceCache _aCache; - private readonly IXmlLineInfo _lineInfo; + private readonly IXmlLineInfo? _lineInfo; private XContainer _currentContainer; - private string _baseUri; + private string? _baseUri; public ContentReader(XContainer rootContainer) { @@ -947,7 +948,7 @@ public bool ReadContentFrom(XContainer rootContainer, XmlReader r) _currentContainer.content = string.Empty; } if (_currentContainer == rootContainer) return false; - _currentContainer = _currentContainer.parent; + _currentContainer = _currentContainer.parent!; break; case XmlNodeType.Text: case XmlNodeType.SignificantWhitespace: @@ -1006,7 +1007,7 @@ public async ValueTask ReadContentFromAsync(XContainer rootContainer, XmlR _currentContainer.content = string.Empty; } if (_currentContainer == rootContainer) return false; - _currentContainer = _currentContainer.parent; + _currentContainer = _currentContainer.parent!; break; case XmlNodeType.Text: case XmlNodeType.SignificantWhitespace: @@ -1039,8 +1040,9 @@ public async ValueTask ReadContentFromAsync(XContainer rootContainer, XmlR public bool ReadContentFrom(XContainer rootContainer, XmlReader r, LoadOptions o) { - XNode newNode = null; - string baseUri = r.BaseURI; + XNode? newNode = null; + // TODO-NULLABLE: Consider changing XmlReader.BaseURI to non-nullable. + string baseUri = r.BaseURI!; switch (r.NodeType) { @@ -1087,7 +1089,7 @@ public bool ReadContentFrom(XContainer rootContainer, XmlReader r, LoadOptions o } // Store the line info of the end element tag. // Note that since we've got EndElement the current container must be an XElement - XElement e = _currentContainer as XElement; + XElement? e = _currentContainer as XElement; Debug.Assert(e != null, "EndElement received but the current container is not an element."); if (e != null && _lineInfo != null && _lineInfo.HasLineInfo()) { @@ -1096,9 +1098,9 @@ public bool ReadContentFrom(XContainer rootContainer, XmlReader r, LoadOptions o if (_currentContainer == rootContainer) return false; if (_baseUri != null && _currentContainer.HasBaseUri) { - _baseUri = _currentContainer.parent.BaseUri; + _baseUri = _currentContainer.parent!.BaseUri; } - _currentContainer = _currentContainer.parent; + _currentContainer = _currentContainer.parent!; break; } case XmlNodeType.Text: @@ -1157,8 +1159,8 @@ public bool ReadContentFrom(XContainer rootContainer, XmlReader r, LoadOptions o public async ValueTask ReadContentFromAsync(XContainer rootContainer, XmlReader r, LoadOptions o) { - XNode newNode = null; - string baseUri = r.BaseURI; + XNode? newNode = null; + string baseUri = r.BaseURI!; switch (r.NodeType) { @@ -1207,7 +1209,7 @@ public async ValueTask ReadContentFromAsync(XContainer rootContainer, XmlR } // Store the line info of the end element tag. // Note that since we've got EndElement the current container must be an XElement - XElement e = _currentContainer as XElement; + XElement? e = _currentContainer as XElement; Debug.Assert(e != null, "EndElement received but the current container is not an element."); if (e != null && _lineInfo != null && _lineInfo.HasLineInfo()) { @@ -1216,9 +1218,9 @@ public async ValueTask ReadContentFromAsync(XContainer rootContainer, XmlR if (_currentContainer == rootContainer) return false; if (_baseUri != null && _currentContainer.HasBaseUri) { - _baseUri = _currentContainer.parent.BaseUri; + _baseUri = _currentContainer.parent!.BaseUri; } - _currentContainer = _currentContainer.parent; + _currentContainer = _currentContainer.parent!; break; } case XmlNodeType.Text: @@ -1280,8 +1282,10 @@ internal void RemoveNode(XNode n) { bool notify = NotifyChanging(n, XObjectChangeEventArgs.Remove); if (n.parent != this) throw new InvalidOperationException(SR.InvalidOperation_ExternalCode); + + Debug.Assert(content != null); XNode p = (XNode)content; - while (p.next != n) p = p.next; + while (p.next != n) p = p.next!; if (p == n) { content = null; @@ -1298,12 +1302,12 @@ internal void RemoveNode(XNode n) private void RemoveNodesSkipNotify() { - XNode n = content as XNode; + XNode? n = content as XNode; if (n != null) { do { - XNode next = n.next; + XNode next = n.next!; n.parent = null; n.next = null; n = next; @@ -1314,7 +1318,7 @@ private void RemoveNodesSkipNotify() // Validate insertion of the given node. previous is the node after which insertion // will occur. previous == null means at beginning, previous == this means at end. - internal virtual void ValidateNode(XNode node, XNode previous) + internal virtual void ValidateNode(XNode node, XNode? previous) { } @@ -1326,7 +1330,7 @@ internal void WriteContentTo(XmlWriter writer) { if (content != null) { - string stringContent = content as string; + string? stringContent = content as string; if (stringContent != null) { if (this is XDocument) @@ -1343,7 +1347,7 @@ internal void WriteContentTo(XmlWriter writer) XNode n = (XNode)content; do { - n = n.next; + n = n.next!; n.WriteTo(writer); } while (n != content); } @@ -1354,7 +1358,7 @@ internal async Task WriteContentToAsync(XmlWriter writer, CancellationToken canc { if (content != null) { - string stringContent = content as string; + string? stringContent = content as string; if (stringContent != null) { @@ -1378,7 +1382,7 @@ internal async Task WriteContentToAsync(XmlWriter writer, CancellationToken canc XNode n = (XNode)content; do { - n = n.next; + n = n.next!; await n.WriteToAsync(writer, cancellationToken).ConfigureAwait(false); } while (n != content); } @@ -1387,7 +1391,7 @@ internal async Task WriteContentToAsync(XmlWriter writer, CancellationToken canc private static void AddContentToList(List list, object content) { - IEnumerable e = content is string ? null : content as IEnumerable; + IEnumerable? e = content is string ? null : content as IEnumerable; if (e == null) { list.Add(content); @@ -1401,7 +1405,8 @@ private static void AddContentToList(List list, object content) } } - internal static object GetContentSnapshot(object content) + [return: NotNullIfNotNull("content")] + internal static object? GetContentSnapshot(object? content) { if (content is string || !(content is IEnumerable)) return content; List list = new List(); diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XDeclaration.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XDeclaration.cs index 10b1139d0c5aae..8407f48b9ed198 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XDeclaration.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XDeclaration.cs @@ -16,9 +16,9 @@ namespace System.Xml.Linq /// public class XDeclaration { - private string _version; - private string _encoding; - private string _standalone; + private string? _version; + private string? _encoding; + private string? _standalone; /// /// Initializes a new instance of the class from the @@ -34,7 +34,7 @@ public class XDeclaration /// Specifies whether the XML is standalone or requires external entities /// to be resolved. /// - public XDeclaration(string version, string encoding, string standalone) + public XDeclaration(string? version, string? encoding, string? standalone) { _version = version; _encoding = encoding; @@ -67,7 +67,7 @@ internal XDeclaration(XmlReader r) /// /// Gets or sets the encoding for this document. /// - public string Encoding + public string? Encoding { get { return _encoding; } set { _encoding = value; } @@ -79,7 +79,7 @@ public string Encoding /// /// The valid values for standalone are "yes" or "no". /// - public string Standalone + public string? Standalone { get { return _standalone; } set { _standalone = value; } @@ -91,7 +91,7 @@ public string Standalone /// /// The value is usually "1.0". /// - public string Version + public string? Version { get { return _version; } set { _version = value; } diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XDocument.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XDocument.cs index 537cbc31088760..5ee37a8fe6ddc1 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XDocument.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XDocument.cs @@ -26,7 +26,7 @@ namespace System.Xml.Linq /// public class XDocument : XContainer { - private XDeclaration _declaration; + private XDeclaration? _declaration; /// /// Initializes a new instance of the class. @@ -87,7 +87,7 @@ public XDocument(params object[] content) /// See for details about the content that can be added /// using this method. /// - public XDocument(XDeclaration declaration, params object[] content) + public XDocument(XDeclaration? declaration, params object[] content) : this(content) { _declaration = declaration; @@ -112,7 +112,7 @@ public XDocument(XDocument other) /// /// Gets the XML declaration for this document. /// - public XDeclaration Declaration + public XDeclaration? Declaration { get { return _declaration; } set { _declaration = value; } @@ -121,7 +121,7 @@ public XDeclaration Declaration /// /// Gets the Document Type Definition (DTD) for this document. /// - public XDocumentType DocumentType + public XDocumentType? DocumentType { get { @@ -146,7 +146,7 @@ public override XmlNodeType NodeType /// /// Gets the root element of the XML Tree for this document. /// - public XElement Root + public XElement? Root { get { @@ -481,7 +481,7 @@ private static XDocument InitLoad(XmlReader reader, LoadOptions options) XDocument d = new XDocument(); if ((options & LoadOptions.SetBaseUri) != 0) { - string baseUri = reader.BaseURI; + string? baseUri = reader.BaseURI; if (!string.IsNullOrEmpty(baseUri)) { d.SetBaseUri(baseUri); @@ -489,7 +489,7 @@ private static XDocument InitLoad(XmlReader reader, LoadOptions options) } if ((options & LoadOptions.SetLineInfo) != 0) { - IXmlLineInfo li = reader as IXmlLineInfo; + IXmlLineInfo? li = reader as IXmlLineInfo; if (li != null && li.HasLineInfo()) { d.SetLineInfo(li.LineNumber, li.LinePosition); @@ -867,7 +867,7 @@ internal override XNode CloneNode() internal override bool DeepEquals(XNode node) { - XDocument other = node as XDocument; + XDocument? other = node as XDocument; return other != null && ContentsEqual(other); } @@ -876,15 +876,15 @@ internal override int GetDeepHashCode() return ContentsHashCode(); } - private T GetFirstNode() where T : XNode + private T? GetFirstNode() where T : XNode { - XNode n = content as XNode; + XNode? n = content as XNode; if (n != null) { do { - n = n.next; - T e = n as T; + n = n.next!; + T? e = n as T; if (e != null) return e; } while (n != content); } @@ -900,7 +900,7 @@ internal static bool IsWhitespace(string s) return true; } - internal override void ValidateNode(XNode node, XNode previous) + internal override void ValidateNode(XNode node, XNode? previous) { switch (node.NodeType) { @@ -920,15 +920,15 @@ internal override void ValidateNode(XNode node, XNode previous) } } - private void ValidateDocument(XNode previous, XmlNodeType allowBefore, XmlNodeType allowAfter) + private void ValidateDocument(XNode? previous, XmlNodeType allowBefore, XmlNodeType allowAfter) { - XNode n = content as XNode; + XNode? n = content as XNode; if (n != null) { if (previous == null) allowBefore = allowAfter; do { - n = n.next; + n = n.next!; XmlNodeType nt = n.NodeType; if (nt == XmlNodeType.Element || nt == XmlNodeType.DocumentType) { diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XDocumentType.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XDocumentType.cs index f31c09681c6e94..7ba36d110aa0dd 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XDocumentType.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XDocumentType.cs @@ -12,14 +12,14 @@ namespace System.Xml.Linq public class XDocumentType : XNode { private string _name; - private string _publicId; - private string _systemId; + private string? _publicId; + private string? _systemId; private string _internalSubset; /// /// Initializes an empty instance of the class. /// - public XDocumentType(string name, string publicId, string systemId, string internalSubset) + public XDocumentType(string name, string? publicId, string? systemId, string internalSubset) { _name = XmlConvert.VerifyName(name); _publicId = publicId; @@ -57,6 +57,10 @@ public string InternalSubset { get { + // TODO-NULLABLE: As per documentation, this should return string.Empty. + // Should we check for null here? + // This is also referenced by XNodeReader.Value which overrides XmlReader.Value, which is non-nullable. + // There is one case that passes a nullable parameter (XNodeBuilder.WriteDocType), currently we are just asserting that the nullable parameter does not receive null. return _internalSubset; } set @@ -102,7 +106,7 @@ public override XmlNodeType NodeType /// /// Gets or sets the public identifier for this Document Type Definition (DTD). /// - public string PublicId + public string? PublicId { get { @@ -119,7 +123,7 @@ public string PublicId /// /// Gets or sets the system identifier for this Document Type Definition (DTD). /// - public string SystemId + public string? SystemId { get { @@ -170,7 +174,7 @@ internal override XNode CloneNode() internal override bool DeepEquals(XNode node) { - XDocumentType other = node as XDocumentType; + XDocumentType? other = node as XDocumentType; return other != null && _name == other._name && _publicId == other._publicId && _systemId == other.SystemId && _internalSubset == other._internalSubset; } diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XElement.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XElement.cs index 5a019ea4edfbf9..8b595a34e5f967 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XElement.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XElement.cs @@ -13,6 +13,8 @@ using IEnumerable = System.Collections.IEnumerable; using SuppressMessageAttribute = System.Diagnostics.CodeAnalysis.SuppressMessageAttribute; using StringBuilder = System.Text.StringBuilder; +using System.Diagnostics.CodeAnalysis; +using System.Diagnostics; namespace System.Xml.Linq { @@ -45,8 +47,8 @@ public static IEnumerable EmptySequence } } - internal XName name; - internal XAttribute lastAttr; + internal XName name = null!; + internal XAttribute? lastAttr; /// /// Initializes a new instance of the XElement class with the specified name. @@ -71,7 +73,7 @@ public XElement(XName name) /// See XContainer.Add(object content) for details about the content that can be added /// using this method. /// - public XElement(XName name, object content) + public XElement(XName name, object? content) : this(name) { AddContentSkipNotify(content); @@ -105,12 +107,12 @@ public XElement(XElement other) : base(other) { this.name = other.name; - XAttribute a = other.lastAttr; + XAttribute? a = other.lastAttr; if (a != null) { do { - a = a.next; + a = a.next!; AppendAttributeSkipNotify(new XAttribute(a)); } while (a != other.lastAttr); } @@ -131,7 +133,7 @@ public XElement(XStreamingElement other) } internal XElement() - : this("default") + : this("default"!) { } @@ -209,7 +211,7 @@ public void Save(string fileName, SaveOptions options) /// /// Gets the first attribute of an element. /// - public XAttribute FirstAttribute + public XAttribute? FirstAttribute { get { return lastAttr != null ? lastAttr.next : null; } } @@ -229,13 +231,13 @@ public bool HasElements { get { - XNode n = content as XNode; + XNode? n = content as XNode; if (n != null) { do { if (n is XElement) return true; - n = n.next; + n = n.next!; } while (n != content); } return false; @@ -253,7 +255,7 @@ public bool IsEmpty /// /// Gets the last attribute of an element. /// - public XAttribute LastAttribute + public XAttribute? LastAttribute { get { return lastAttr; } } @@ -302,7 +304,7 @@ public string Value get { if (content == null) return string.Empty; - string s = content as string; + string? s = content as string; if (s != null) return s; StringBuilder sb = StringBuilderCache.Acquire(); AppendText(sb); @@ -351,7 +353,7 @@ public IEnumerable AncestorsAndSelf() /// An of containing the /// ancestors of this with a matching . /// - public IEnumerable AncestorsAndSelf(XName name) + public IEnumerable AncestorsAndSelf(XName? name) { return name != null ? GetAncestors(name, true) : XElement.EmptySequence; } @@ -367,14 +369,14 @@ public IEnumerable AncestorsAndSelf(XName name) /// The with the passed in. If there is no /// with this then null is returned. /// - public XAttribute Attribute(XName name) + public XAttribute? Attribute(XName name) { - XAttribute a = lastAttr; + XAttribute? a = lastAttr; if (a != null) { do { - a = a.next; + a = a.next!; if (a.name == name) return a; } while (a != lastAttr); } @@ -409,7 +411,7 @@ public IEnumerable Attributes() /// /// The (s) with the matching /// - public IEnumerable Attributes(XName name) + public IEnumerable Attributes(XName? name) { return name != null ? GetAttributes(name) : XAttribute.EmptySequence; } @@ -454,7 +456,7 @@ public IEnumerable DescendantsAndSelf() /// An of containing all of the descendant /// s that have this . /// - public IEnumerable DescendantsAndSelf(XName name) + public IEnumerable DescendantsAndSelf(XName? name) { return name != null ? GetDescendants(name, true) : XElement.EmptySequence; } @@ -464,7 +466,7 @@ public IEnumerable DescendantsAndSelf(XName name) /// public XNamespace GetDefaultNamespace() { - string namespaceName = GetNamespaceOfPrefixInScope("xmlns", null); + string? namespaceName = GetNamespaceOfPrefixInScope("xmlns", null); return namespaceName != null ? XNamespace.Get(namespaceName) : XNamespace.None; } @@ -474,12 +476,12 @@ public XNamespace GetDefaultNamespace() /// /// The namespace prefix to look up /// An for the namespace bound to the prefix - public XNamespace GetNamespaceOfPrefix(string prefix) + public XNamespace? GetNamespaceOfPrefix(string prefix) { if (prefix == null) throw new ArgumentNullException(nameof(prefix)); if (prefix.Length == 0) throw new ArgumentException(SR.Format(SR.Argument_InvalidPrefix, prefix)); if (prefix == "xmlns") return XNamespace.Xmlns; - string namespaceName = GetNamespaceOfPrefixInScope(prefix, null); + string? namespaceName = GetNamespaceOfPrefixInScope(prefix, null); if (namespaceName != null) return XNamespace.Get(namespaceName); if (prefix == "xml") return XNamespace.Xml; return null; @@ -490,21 +492,21 @@ public XNamespace GetNamespaceOfPrefix(string prefix) /// /// The for which to get a prefix /// The namespace prefix string - public string GetPrefixOfNamespace(XNamespace ns) + public string? GetPrefixOfNamespace(XNamespace ns) { if (ns == null) throw new ArgumentNullException(nameof(ns)); string namespaceName = ns.NamespaceName; bool hasInScopeNamespace = false; - XElement e = this; + XElement? e = this; do { - XAttribute a = e.lastAttr; + XAttribute? a = e.lastAttr; if (a != null) { bool hasLocalNamespace = false; do { - a = a.next; + a = a.next!; if (a.IsNamespaceDeclaration) { if (a.Value == namespaceName) @@ -932,7 +934,7 @@ public void RemoveAttributes() } while (lastAttr != null) { - XAttribute a = lastAttr.next; + XAttribute a = lastAttr.next!; NotifyChanging(a, XObjectChangeEventArgs.Remove); if (lastAttr == null || a != lastAttr.next) throw new InvalidOperationException(SR.InvalidOperation_ExternalCode); if (a != lastAttr) @@ -964,7 +966,7 @@ public void RemoveAttributes() /// See XContainer.Add(object content) for details about the content that can be added /// using this method. /// - public void ReplaceAll(object content) + public void ReplaceAll(object? content) { content = GetContentSnapshot(content); RemoveAll(); @@ -1001,7 +1003,7 @@ public void ReplaceAll(params object[] content) /// See XContainer.Add(object content) for details about the content that can be added /// using this method. /// - public void ReplaceAttributes(object content) + public void ReplaceAttributes(object? content) { content = GetContentSnapshot(content); RemoveAttributes(); @@ -1207,9 +1209,9 @@ private async Task SaveAsyncInternal(XmlWriter writer, CancellationToken cancell /// /// Thrown if the value is an instance of . /// - public void SetAttributeValue(XName name, object value) + public void SetAttributeValue(XName name, object? value) { - XAttribute a = Attribute(name); + XAttribute? a = Attribute(name); if (value == null) { if (a != null) RemoveAttribute(a); @@ -1247,9 +1249,9 @@ public void SetAttributeValue(XName name, object value) /// /// Thrown if the value is an instance of . /// - public void SetElementValue(XName name, object value) + public void SetElementValue(XName name, object? value) { - XElement e = Element(name); + XElement? e = Element(name); if (value == null) { if (e != null) RemoveNode(e); @@ -1330,7 +1332,8 @@ public override Task WriteToAsync(XmlWriter writer, CancellationToken cancellati /// The content of this as a . /// [CLSCompliant(false)] - public static explicit operator string(XElement element) + [return: NotNullIfNotNull("element")] + public static explicit operator string?(XElement? element) { if (element == null) return null; return element.Value; @@ -1371,7 +1374,8 @@ public static explicit operator bool(XElement element) /// Thrown if the element does not contain a valid boolean value. /// [CLSCompliant(false)] - public static explicit operator bool?(XElement element) + [return: NotNullIfNotNull("element")] + public static explicit operator bool?(XElement? element) { if (element == null) return null; return XmlConvert.ToBoolean(element.Value.ToLowerInvariant()); @@ -1412,7 +1416,8 @@ public static explicit operator int(XElement element) /// Thrown if the specified element does not contain a valid integer value. /// [CLSCompliant(false)] - public static explicit operator int?(XElement element) + [return: NotNullIfNotNull("element")] + public static explicit operator int?(XElement? element) { if (element == null) return null; return XmlConvert.ToInt32(element.Value); @@ -1453,7 +1458,8 @@ public static explicit operator uint(XElement element) /// Thrown if the specified element does not contain a valid unsigned integer value. /// [CLSCompliant(false)] - public static explicit operator uint?(XElement element) + [return: NotNullIfNotNull("element")] + public static explicit operator uint?(XElement? element) { if (element == null) return null; return XmlConvert.ToUInt32(element.Value); @@ -1494,7 +1500,8 @@ public static explicit operator long(XElement element) /// Thrown if the specified element does not contain a valid long integer value. /// [CLSCompliant(false)] - public static explicit operator long?(XElement element) + [return: NotNullIfNotNull("element")] + public static explicit operator long?(XElement? element) { if (element == null) return null; return XmlConvert.ToInt64(element.Value); @@ -1535,7 +1542,8 @@ public static explicit operator ulong(XElement element) /// Thrown if the specified element does not contain a valid unsigned long integer value. /// [CLSCompliant(false)] - public static explicit operator ulong?(XElement element) + [return: NotNullIfNotNull("element")] + public static explicit operator ulong?(XElement? element) { if (element == null) return null; return XmlConvert.ToUInt64(element.Value); @@ -1576,7 +1584,8 @@ public static explicit operator float(XElement element) /// Thrown if the specified element does not contain a valid float value. /// [CLSCompliant(false)] - public static explicit operator float?(XElement element) + [return: NotNullIfNotNull("element")] + public static explicit operator float?(XElement? element) { if (element == null) return null; return XmlConvert.ToSingle(element.Value); @@ -1617,7 +1626,8 @@ public static explicit operator double(XElement element) /// Thrown if the specified element does not contain a valid double value. /// [CLSCompliant(false)] - public static explicit operator double?(XElement element) + [return: NotNullIfNotNull("element")] + public static explicit operator double?(XElement? element) { if (element == null) return null; return XmlConvert.ToDouble(element.Value); @@ -1658,7 +1668,8 @@ public static explicit operator decimal(XElement element) /// Thrown if the specified element does not contain a valid decimal value. /// [CLSCompliant(false)] - public static explicit operator decimal?(XElement element) + [return: NotNullIfNotNull("element")] + public static explicit operator decimal?(XElement? element) { if (element == null) return null; return XmlConvert.ToDecimal(element.Value); @@ -1699,7 +1710,8 @@ public static explicit operator DateTime(XElement element) /// Thrown if the specified element does not contain a valid value. /// [CLSCompliant(false)] - public static explicit operator DateTime?(XElement element) + [return: NotNullIfNotNull("element")] + public static explicit operator DateTime?(XElement? element) { if (element == null) return null; return DateTime.Parse(element.Value, CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.RoundtripKind); @@ -1740,7 +1752,8 @@ public static explicit operator DateTimeOffset(XElement element) /// Thrown if the specified element does not contain a valid value. /// [CLSCompliant(false)] - public static explicit operator DateTimeOffset?(XElement element) + [return: NotNullIfNotNull("element")] + public static explicit operator DateTimeOffset?(XElement? element) { if (element == null) return null; return XmlConvert.ToDateTimeOffset(element.Value); @@ -1781,7 +1794,8 @@ public static explicit operator TimeSpan(XElement element) /// Thrown if the specified element does not contain a valid value. /// [CLSCompliant(false)] - public static explicit operator TimeSpan?(XElement element) + [return: NotNullIfNotNull("element")] + public static explicit operator TimeSpan?(XElement? element) { if (element == null) return null; return XmlConvert.ToTimeSpan(element.Value); @@ -1822,7 +1836,8 @@ public static explicit operator Guid(XElement element) /// Thrown if the specified element does not contain a valid guid. /// [CLSCompliant(false)] - public static explicit operator Guid?(XElement element) + [return: NotNullIfNotNull("element")] + public static explicit operator Guid?(XElement? element) { if (element == null) return null; return XmlConvert.ToGuid(element.Value); @@ -1831,7 +1846,7 @@ public static explicit operator Guid(XElement element) /// /// This method is obsolete for the IXmlSerializable contract. /// - XmlSchema IXmlSerializable.GetSchema() + XmlSchema? IXmlSerializable.GetSchema() { return null; } @@ -1902,14 +1917,14 @@ internal void AppendAttributeSkipNotify(XAttribute a) private bool AttributesEqual(XElement e) { - XAttribute a1 = lastAttr; - XAttribute a2 = e.lastAttr; + XAttribute? a1 = lastAttr; + XAttribute? a2 = e.lastAttr; if (a1 != null && a2 != null) { do { - a1 = a1.next; - a2 = a2.next; + a1 = a1.next!; + a2 = a2.next!; if (a1.name != a2.name || a1.value != a2.value) return false; } while (a1 != lastAttr); return a2 == e.lastAttr; @@ -1924,34 +1939,35 @@ internal override XNode CloneNode() internal override bool DeepEquals(XNode node) { - XElement e = node as XElement; + XElement? e = node as XElement; return e != null && name == e.name && ContentsEqual(e) && AttributesEqual(e); } - private IEnumerable GetAttributes(XName name) + private IEnumerable GetAttributes(XName? name) { - XAttribute a = lastAttr; + XAttribute? a = lastAttr; if (a != null) { do { - a = a.next; + a = a.next!; if (name == null || a.name == name) yield return a; } while (a.parent == this && a != lastAttr); } } - private string GetNamespaceOfPrefixInScope(string prefix, XElement outOfScope) + private string? GetNamespaceOfPrefixInScope(string prefix, XElement? outOfScope) { - XElement e = this; + XElement? e = this; while (e != outOfScope) { - XAttribute a = e.lastAttr; + Debug.Assert(e != null); + XAttribute? a = e.lastAttr; if (a != null) { do { - a = a.next; + a = a.next!; if (a.IsNamespaceDeclaration && a.Name.LocalName == prefix) return a.Value; } while (a != e.lastAttr); @@ -1965,12 +1981,12 @@ internal override int GetDeepHashCode() { int h = name.GetHashCode(); h ^= ContentsHashCode(); - XAttribute a = lastAttr; + XAttribute? a = lastAttr; if (a != null) { do { - a = a.next; + a = a.next!; h ^= a.GetDeepHashCode(); } while (a != lastAttr); } @@ -2015,13 +2031,13 @@ private void ReadElementFromImpl(XmlReader r, LoadOptions o) name = XNamespace.Get(r.NamespaceURI).GetName(r.LocalName); if ((o & LoadOptions.SetBaseUri) != 0) { - string baseUri = r.BaseURI; + string? baseUri = r.BaseURI; if (!string.IsNullOrEmpty(baseUri)) { SetBaseUri(baseUri); } } - IXmlLineInfo li = null; + IXmlLineInfo? li = null; if ((o & LoadOptions.SetLineInfo) != 0) { li = r as IXmlLineInfo; @@ -2049,8 +2065,8 @@ internal void RemoveAttribute(XAttribute a) { bool notify = NotifyChanging(a, XObjectChangeEventArgs.Remove); if (a.parent != this) throw new InvalidOperationException(SR.InvalidOperation_ExternalCode); - XAttribute p = lastAttr, n; - while ((n = p.next) != a) p = n; + XAttribute? p = lastAttr!, n; + while ((n = p.next!) != a) p = n; if (p == a) { lastAttr = null; @@ -2072,7 +2088,7 @@ private void RemoveAttributesSkipNotify() XAttribute a = lastAttr; do { - XAttribute next = a.next; + XAttribute next = a.next!; a.parent = null; a.next = null; a = next; @@ -2086,7 +2102,7 @@ internal void SetEndElementLineInfo(int lineNumber, int linePosition) AddAnnotation(new LineInfoEndElementAnnotation(lineNumber, linePosition)); } - internal override void ValidateNode(XNode node, XNode previous) + internal override void ValidateNode(XNode node, XNode? previous) { if (node is XDocument) throw new ArgumentException(SR.Format(SR.Argument_AddNode, XmlNodeType.Document)); if (node is XDocumentType) throw new ArgumentException(SR.Format(SR.Argument_AddNode, XmlNodeType.DocumentType)); diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XHashtable.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XHashtable.cs index 24ea8411a64517..58c536966a3593 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XHashtable.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XHashtable.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Diagnostics.CodeAnalysis; using System.Threading; using Debug = System.Diagnostics.Debug; using Interlocked = System.Threading.Interlocked; @@ -66,7 +67,7 @@ internal sealed class XHashtable /// Prototype of function which is called to extract a string key value from a hashed value. /// Returns null if the hashed value is invalid (e.g. value has been released due to a WeakReference TValue being cleaned up). /// - public delegate string ExtractKeyDelegate(TValue value); + public delegate string? ExtractKeyDelegate(TValue value); /// /// Construct a new XHashtable with the specified starting capacity. @@ -79,7 +80,7 @@ public XHashtable(ExtractKeyDelegate extractKey, int capacity) /// /// Get an existing value from the hash table. Return false if no such value exists. /// - public bool TryGetValue(string key, int index, int count, out TValue value) + public bool TryGetValue(string key, int index, int count, [MaybeNullWhen(false)] out TValue value) { return _state.TryGetValue(key, index, count, out value); } @@ -238,7 +239,7 @@ public XHashtableState Resize() /// Attempt to find "key" in the table. If the key exists, return the associated value in "value" and /// return true. Otherwise return false. /// - public bool TryGetValue(string key, int index, int count, out TValue value) + public bool TryGetValue(string key, int index, int count, [MaybeNullWhen(false)] out TValue value) { int hashCode = ComputeHashCode(key, index, count); int entryIndex = 0; @@ -264,7 +265,7 @@ public bool TryGetValue(string key, int index, int count, out TValue value) public bool TryAdd(TValue value, out TValue newValue) { int newEntry, entryIndex; - string key; + string? key; int hashCode; // Assume "value" will be added and returned as "newValue" @@ -345,7 +346,7 @@ private bool FindEntry(int hashCode, string key, int index, int count, ref int e // Check for matching hash code, then matching key if (_entries[currentIndex].HashCode == hashCode) { - string keyCompare = _extractKey(_entries[currentIndex].Value); + string? keyCompare = _extractKey(_entries[currentIndex].Value); // If the key is invalid, then attempt to remove the current entry from the linked list. // This is thread-safe in the case where the Next field points to another entry, since once a Next field points @@ -356,7 +357,7 @@ private bool FindEntry(int hashCode, string key, int index, int count, ref int e { // PUBLISH (buckets slot or entries slot) // Entry is invalid, so modify previous entry to point to its next entry - _entries[currentIndex].Value = default(TValue); + _entries[currentIndex].Value = default(TValue)!; currentIndex = _entries[currentIndex].Next; if (previousIndex == 0) diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XHelper.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XHelper.cs index 9249cce442fe90..f127fe02fa4cb3 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XHelper.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XHelper.cs @@ -9,7 +9,7 @@ namespace System.Xml.Linq { internal static class XHelper { - internal static bool IsInstanceOfType(object o, Type type) + internal static bool IsInstanceOfType(object? o, Type type) { Debug.Assert(type != null); diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XLinq.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XLinq.cs index 85e563ca1ed56a..0d47b5596cdc4a 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XLinq.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XLinq.cs @@ -13,17 +13,17 @@ namespace System.Xml.Linq internal struct Inserter { private readonly XContainer _parent; - private XNode _previous; - private string _text; + private XNode? _previous; + private string? _text; - public Inserter(XContainer parent, XNode anchor) + public Inserter(XContainer parent, XNode? anchor) { _parent = parent; _previous = anchor; _text = null; } - public void Add(object content) + public void Add(object? content) { AddContent(content); if (_text != null) @@ -60,7 +60,7 @@ public void Add(object content) } else if (_text.Length > 0) { - XText prevXText = _previous as XText; + XText? prevXText = _previous as XText; if (prevXText != null && !(_previous is XCData)) { prevXText.Value += _text; @@ -74,34 +74,34 @@ public void Add(object content) } } - private void AddContent(object content) + private void AddContent(object? content) { if (content == null) return; - XNode n = content as XNode; + XNode? n = content as XNode; if (n != null) { AddNode(n); return; } - string s = content as string; + string? s = content as string; if (s != null) { AddString(s); return; } - XStreamingElement x = content as XStreamingElement; + XStreamingElement? x = content as XStreamingElement; if (x != null) { AddNode(new XElement(x)); return; } - object[] o = content as object[]; + object[]? o = content as object[]; if (o != null) { foreach (object obj in o) AddContent(obj); return; } - IEnumerable e = content as IEnumerable; + IEnumerable? e = content as IEnumerable; if (e != null) { foreach (object obj in e) AddContent(obj); @@ -129,7 +129,7 @@ private void AddNode(XNode n) { if (_text.Length > 0) { - XText prevXText = _previous as XText; + XText? prevXText = _previous as XText; if (prevXText != null && !(_previous is XCData)) { prevXText.Value += _text; @@ -210,17 +210,17 @@ public void WriteElement(XElement e) XNode n = e; while (true) { - e = n as XElement; - if (e != null) + XElement? current = n as XElement; + if (current != null) { - WriteStartElement(e); - if (e.content == null) + WriteStartElement(current); + if (current.content == null) { WriteEndElement(); } else { - string s = e.content as string; + string? s = current.content as string; if (s != null) { _writer.WriteString(s); @@ -228,7 +228,7 @@ public void WriteElement(XElement e) } else { - n = ((XNode)e.content).next; + n = ((XNode)current.content).next!; continue; } } @@ -237,13 +237,13 @@ public void WriteElement(XElement e) { n.WriteTo(_writer); } - while (n != root && n == n.parent.content) + while (n != root && n == n.parent!.content) { n = n.parent; WriteFullEndElement(); } if (n == root) break; - n = n.next; + n = n.next!; } } @@ -254,17 +254,17 @@ public async Task WriteElementAsync(XElement e, CancellationToken cancellationTo XNode n = e; while (true) { - e = n as XElement; - if (e != null) + XElement? current = n as XElement; + if (current != null) { - await WriteStartElementAsync(e, cancellationToken).ConfigureAwait(false); - if (e.content == null) + await WriteStartElementAsync(current, cancellationToken).ConfigureAwait(false); + if (current.content == null) { await WriteEndElementAsync(cancellationToken).ConfigureAwait(false); } else { - string s = e.content as string; + string? s = current.content as string; if (s != null) { cancellationToken.ThrowIfCancellationRequested(); @@ -273,7 +273,7 @@ public async Task WriteElementAsync(XElement e, CancellationToken cancellationTo } else { - n = ((XNode)e.content).next; + n = ((XNode)current.content).next!; continue; } } @@ -282,39 +282,39 @@ public async Task WriteElementAsync(XElement e, CancellationToken cancellationTo { await n.WriteToAsync(_writer, cancellationToken).ConfigureAwait(false); } - while (n != root && n == n.parent.content) + while (n != root && n == n.parent!.content) { n = n.parent; await WriteFullEndElementAsync(cancellationToken).ConfigureAwait(false); } if (n == root) break; - n = n.next; + n = n.next!; } } - private string GetPrefixOfNamespace(XNamespace ns, bool allowDefaultNamespace) + private string? GetPrefixOfNamespace(XNamespace ns, bool allowDefaultNamespace) { string namespaceName = ns.NamespaceName; if (namespaceName.Length == 0) return string.Empty; - string prefix = _resolver.GetPrefixOfNamespace(ns, allowDefaultNamespace); + string? prefix = _resolver.GetPrefixOfNamespace(ns, allowDefaultNamespace); if (prefix != null) return prefix; if ((object)namespaceName == (object)XNamespace.xmlPrefixNamespace) return "xml"; if ((object)namespaceName == (object)XNamespace.xmlnsPrefixNamespace) return "xmlns"; return null; } - private void PushAncestors(XElement e) + private void PushAncestors(XElement? e) { while (true) { - e = e.parent as XElement; + e = e!.parent as XElement; if (e == null) break; - XAttribute a = e.lastAttr; + XAttribute? a = e.lastAttr; if (a != null) { do { - a = a.next; + a = a.next!; if (a.IsNamespaceDeclaration) { _resolver.AddFirst(a.Name.NamespaceName.Length == 0 ? string.Empty : a.Name.LocalName, XNamespace.Get(a.Value)); @@ -327,12 +327,12 @@ private void PushAncestors(XElement e) private void PushElement(XElement e) { _resolver.PushScope(); - XAttribute a = e.lastAttr; + XAttribute? a = e.lastAttr; if (a != null) { do { - a = a.next; + a = a.next!; if (a.IsNamespaceDeclaration) { _resolver.Add(a.Name.NamespaceName.Length == 0 ? string.Empty : a.Name.LocalName, XNamespace.Get(a.Value)); @@ -372,12 +372,12 @@ private void WriteStartElement(XElement e) PushElement(e); XNamespace ns = e.Name.Namespace; _writer.WriteStartElement(GetPrefixOfNamespace(ns, true), e.Name.LocalName, ns.NamespaceName); - XAttribute a = e.lastAttr; + XAttribute? a = e.lastAttr; if (a != null) { do { - a = a.next; + a = a.next!; ns = a.Name.Namespace; string localName = a.Name.LocalName; string namespaceName = ns.NamespaceName; @@ -391,12 +391,12 @@ private async Task WriteStartElementAsync(XElement e, CancellationToken cancella PushElement(e); XNamespace ns = e.Name.Namespace; await _writer.WriteStartElementAsync(GetPrefixOfNamespace(ns, true), e.Name.LocalName, ns.NamespaceName).ConfigureAwait(false); - XAttribute a = e.lastAttr; + XAttribute? a = e.lastAttr; if (a != null) { do { - a = a.next; + a = a.next!; ns = a.Name.Namespace; string localName = a.Name.LocalName; string namespaceName = ns.NamespaceName; @@ -410,15 +410,15 @@ internal struct NamespaceResolver { private class NamespaceDeclaration { - public string prefix; - public XNamespace ns; + public string prefix = null!; + public XNamespace ns = null!; public int scope; - public NamespaceDeclaration prev; + public NamespaceDeclaration prev = null!; } private int _scope; - private NamespaceDeclaration _declaration; - private NamespaceDeclaration _rover; + private NamespaceDeclaration? _declaration; + private NamespaceDeclaration? _rover; public void PushScope() { @@ -427,7 +427,7 @@ public void PushScope() public void PopScope() { - NamespaceDeclaration d = _declaration; + NamespaceDeclaration? d = _declaration; if (d != null) { do @@ -440,7 +440,7 @@ public void PopScope() } else { - _declaration.prev = d.prev; + _declaration!.prev = d.prev; } _rover = null; } while (d != _declaration && _declaration != null); @@ -487,10 +487,10 @@ public void AddFirst(string prefix, XNamespace ns) // Only elements allow default namespace declarations. The rover // caches the last namespace declaration used by an element. - public string GetPrefixOfNamespace(XNamespace ns, bool allowDefaultNamespace) + public string? GetPrefixOfNamespace(XNamespace ns, bool allowDefaultNamespace) { if (_rover != null && _rover.ns == ns && (allowDefaultNamespace || _rover.prefix.Length > 0)) return _rover.prefix; - NamespaceDeclaration d = _declaration; + NamespaceDeclaration? d = _declaration; if (d != null) { do @@ -498,7 +498,7 @@ public string GetPrefixOfNamespace(XNamespace ns, bool allowDefaultNamespace) d = d.prev; if (d.ns == ns) { - NamespaceDeclaration x = _declaration.prev; + NamespaceDeclaration x = _declaration!.prev; while (x != d && x.prefix != d.prefix) { x = x.prev; @@ -525,7 +525,7 @@ public string GetPrefixOfNamespace(XNamespace ns, bool allowDefaultNamespace) internal struct StreamingElementWriter { private readonly XmlWriter _writer; - private XStreamingElement _element; + private XStreamingElement? _element; private readonly List _attributes; private NamespaceResolver _resolver; @@ -556,11 +556,11 @@ private void FlushElement() } } - private string GetPrefixOfNamespace(XNamespace ns, bool allowDefaultNamespace) + private string? GetPrefixOfNamespace(XNamespace ns, bool allowDefaultNamespace) { string namespaceName = ns.NamespaceName; if (namespaceName.Length == 0) return string.Empty; - string prefix = _resolver.GetPrefixOfNamespace(ns, allowDefaultNamespace); + string? prefix = _resolver.GetPrefixOfNamespace(ns, allowDefaultNamespace); if (prefix != null) return prefix; if ((object)namespaceName == (object)XNamespace.xmlPrefixNamespace) return "xml"; if ((object)namespaceName == (object)XNamespace.xmlnsPrefixNamespace) return "xmlns"; @@ -579,40 +579,40 @@ private void PushElement() } } - private void Write(object content) + private void Write(object? content) { if (content == null) return; - XNode n = content as XNode; + XNode? n = content as XNode; if (n != null) { WriteNode(n); return; } - string s = content as string; + string? s = content as string; if (s != null) { WriteString(s); return; } - XAttribute a = content as XAttribute; + XAttribute? a = content as XAttribute; if (a != null) { WriteAttribute(a); return; } - XStreamingElement x = content as XStreamingElement; + XStreamingElement? x = content as XStreamingElement; if (x != null) { WriteStreamingElement(x); return; } - object[] o = content as object[]; + object[]? o = content as object[]; if (o != null) { foreach (object obj in o) Write(obj); return; } - IEnumerable e = content as IEnumerable; + IEnumerable? e = content as IEnumerable; if (e != null) { foreach (object obj in e) Write(obj); diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XName.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XName.cs index 1b6c7fa99a1f55..66ab4828ffa09d 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XName.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XName.cs @@ -3,6 +3,7 @@ using SuppressMessageAttribute = System.Diagnostics.CodeAnalysis.SuppressMessageAttribute; using System.Runtime.Serialization; +using System.Diagnostics.CodeAnalysis; namespace System.Xml.Linq { @@ -101,7 +102,8 @@ public static XName Get(string localName, string namespaceName) /// A string containing an expanded XML name in the format: {namespace}localname. /// An XName object constructed from the expanded name. [CLSCompliant(false)] - public static implicit operator XName(string expandedName) + [return: NotNullIfNotNull("expandedName")] + public static implicit operator XName?(string? expandedName) { return expandedName != null ? Get(expandedName) : null; } @@ -116,7 +118,7 @@ public static implicit operator XName(string expandedName) /// /// For two objects to be equal, they must have the same expanded name. /// - public override bool Equals(object obj) + public override bool Equals(object? obj) { return (object)this == obj; } @@ -146,9 +148,9 @@ public override int GetHashCode() /// This overload is included to enable the comparison between /// an instance of XName and string. /// - public static bool operator ==(XName left, XName right) + public static bool operator ==(XName? left, XName? right) { - return (object)left == (object)right; + return (object?)left == (object?)right; } /// @@ -161,9 +163,9 @@ public override int GetHashCode() /// This overload is included to enable the comparison between /// an instance of XName and string. /// - public static bool operator !=(XName left, XName right) + public static bool operator !=(XName? left, XName? right) { - return (object)left != (object)right; + return (object?)left != (object?)right; } /// @@ -176,9 +178,9 @@ public override int GetHashCode() /// Returns true if the current is equal to /// the specified . Returns false otherwise. /// - bool IEquatable.Equals(XName other) + bool IEquatable.Equals(XName? other) { - return (object)this == (object)other; + return (object)this == (object?)other; } /// diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNamespace.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNamespace.cs index 8b673a644fde9b..c3fa5a3d85ac13 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNamespace.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNamespace.cs @@ -4,6 +4,7 @@ using Debug = System.Diagnostics.Debug; using SuppressMessageAttribute = System.Diagnostics.CodeAnalysis.SuppressMessageAttribute; using Interlocked = System.Threading.Interlocked; +using System.Diagnostics.CodeAnalysis; namespace System.Xml.Linq { @@ -15,10 +16,10 @@ public sealed class XNamespace internal const string xmlPrefixNamespace = "http://www.w3.org/XML/1998/namespace"; internal const string xmlnsPrefixNamespace = "http://www.w3.org/2000/xmlns/"; - private static XHashtable s_namespaces; - private static WeakReference s_refNone; - private static WeakReference s_refXml; - private static WeakReference s_refXmlns; + private static XHashtable? s_namespaces; + private static WeakReference? s_refNone; + private static WeakReference? s_refXml; + private static WeakReference? s_refXmlns; private readonly string _namespaceName; private readonly int _hashCode; @@ -123,7 +124,8 @@ public static XNamespace Get(string namespaceName) /// A string containing the namespace name. /// An constructed from the namespace name string. [CLSCompliant(false)] - public static implicit operator XNamespace(string namespaceName) + [return: NotNullIfNotNull("namespaceName")] + public static implicit operator XNamespace?(string? namespaceName) { return namespaceName != null ? Get(namespaceName) : null; } @@ -151,7 +153,7 @@ public static implicit operator XNamespace(string namespaceName) /// For two objects to be equal they must have the same /// namespace name. /// - public override bool Equals(object obj) + public override bool Equals(object? obj) { return (object)this == obj; } @@ -182,9 +184,9 @@ public override int GetHashCode() /// This overload is included to enable the comparison between /// an instance of and string. /// - public static bool operator ==(XNamespace left, XNamespace right) + public static bool operator ==(XNamespace? left, XNamespace? right) { - return (object)left == (object)right; + return (object?)left == (object?)right; } /// @@ -197,9 +199,9 @@ public override int GetHashCode() /// This overload is included to enable the comparison between /// an instance of and string. /// - public static bool operator !=(XNamespace left, XNamespace right) + public static bool operator !=(XNamespace? left, XNamespace? right) { - return (object)left != (object)right; + return (object?)left != (object?)right; } /// @@ -213,7 +215,7 @@ internal XName GetName(string localName, int index, int count) Debug.Assert(count >= 0 && index + count <= localName.Length, "Caller should have checked that count was in bounds"); // Attempt to get the local name from the hash table - XName name; + XName? name; if (_names.TryGetValue(localName, index, count, out name)) return name; @@ -236,8 +238,8 @@ internal static XNamespace Get(string namespaceName, int index, int count) if (s_namespaces == null) Interlocked.CompareExchange(ref s_namespaces, new XHashtable(ExtractNamespace, NamespacesCapacity), null); - WeakReference refNamespace; - XNamespace ns; + WeakReference? refNamespace; + XNamespace? ns; // Keep looping until a non-null namespace has been retrieved do @@ -253,7 +255,7 @@ internal static XNamespace Get(string namespaceName, int index, int count) refNamespace = s_namespaces.Add(new WeakReference(new XNamespace(namespaceName.Substring(index, count)))); } - ns = (refNamespace != null) ? (XNamespace)refNamespace.Target : null; + ns = (refNamespace != null) ? (XNamespace?)refNamespace.Target : null; } while (ns == null); @@ -274,11 +276,11 @@ private static string ExtractLocalName(XName n) /// This function is used by the to extract the XNamespace that the WeakReference is /// referencing. In cases where the XNamespace has been cleaned up, this function returns null. /// - private static string ExtractNamespace(WeakReference r) + private static string? ExtractNamespace(WeakReference? r) { - XNamespace ns; + XNamespace? ns; - if (r == null || (ns = (XNamespace)r.Target) == null) + if (r == null || (ns = (XNamespace?)r.Target) == null) return null; return ns.NamespaceName; @@ -290,9 +292,9 @@ private static string ExtractNamespace(WeakReference r) /// since other threads can be concurrently calling this method, and the target of a WeakReference can be cleaned up /// at any time by the GC. /// - private static XNamespace EnsureNamespace(ref WeakReference refNmsp, string namespaceName) + private static XNamespace EnsureNamespace(ref WeakReference? refNmsp, string namespaceName) { - WeakReference refOld; + WeakReference? refOld; // Keep looping until a non-null namespace has been retrieved while (true) @@ -303,7 +305,7 @@ private static XNamespace EnsureNamespace(ref WeakReference refNmsp, string name if (refOld != null) { // If the target of the WeakReference is non-null, then we're done--just return the value - XNamespace ns = (XNamespace)refOld.Target; + XNamespace? ns = (XNamespace?)refOld.Target; if (ns != null) return ns; } diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNode.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNode.cs index d8645161a48f45..aa34604d8a05bd 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNode.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNode.cs @@ -9,6 +9,7 @@ using CultureInfo = System.Globalization.CultureInfo; using SuppressMessageAttribute = System.Diagnostics.CodeAnalysis.SuppressMessageAttribute; using StringBuilder = System.Text.StringBuilder; +using System.Diagnostics; namespace System.Xml.Linq { @@ -28,10 +29,10 @@ namespace System.Xml.Linq /// public abstract class XNode : XObject { - private static XNodeDocumentOrderComparer s_documentOrderComparer; - private static XNodeEqualityComparer s_equalityComparer; + private static XNodeDocumentOrderComparer? s_documentOrderComparer; + private static XNodeEqualityComparer? s_equalityComparer; - internal XNode next; + internal XNode? next; internal XNode() { } @@ -42,7 +43,7 @@ internal XNode() { } /// If this property does not have a parent, or if there is no next node, /// then this property returns null. /// - public XNode NextNode + public XNode? NextNode { get { @@ -57,17 +58,18 @@ public XNode NextNode /// If this property does not have a parent, or if there is no previous node, /// then this property returns null. /// - public XNode PreviousNode + public XNode? PreviousNode { get { if (parent == null) return null; - XNode n = ((XNode)parent.content).next; - XNode p = null; + Debug.Assert(parent.content != null); + XNode n = ((XNode)parent.content!).next!; + XNode? p = null; while (n != this) { p = n; - n = n.next; + n = n.next!; } return p; } @@ -117,7 +119,7 @@ public static XNodeEqualityComparer EqualityComparer /// See XContainer.Add(object content) for details about the content that can be added /// using this method. /// - public void AddAfterSelf(object content) + public void AddAfterSelf(object? content) { if (parent == null) throw new InvalidOperationException(SR.InvalidOperation_MissingParent); new Inserter(parent, this).Add(content); @@ -161,11 +163,11 @@ public void AddAfterSelf(params object[] content) /// See XContainer.Add(object content) for details about the content that can be added /// using this method. /// - public void AddBeforeSelf(object content) + public void AddBeforeSelf(object? content) { if (parent == null) throw new InvalidOperationException(SR.InvalidOperation_MissingParent); - XNode p = (XNode)parent.content; - while (p.next != this) p = p.next; + XNode? p = (XNode)parent.content!; + while (p.next != this) p = p.next!; if (p == parent.content) p = null; new Inserter(parent, p).Add(content); } @@ -218,7 +220,7 @@ public IEnumerable Ancestors() /// /// This method will not return itself in the results. /// - public IEnumerable Ancestors(XName name) + public IEnumerable Ancestors(XName? name) { return name != null ? GetAncestors(name, false) : XElement.EmptySequence; } @@ -234,7 +236,7 @@ public IEnumerable Ancestors(XName name) /// /// Thrown if the two nodes do not share a common ancestor. /// - public static int CompareDocumentOrder(XNode n1, XNode n2) + public static int CompareDocumentOrder(XNode? n1, XNode? n2) { if (n1 == n2) return 0; if (n1 == null) return -1; @@ -259,7 +261,7 @@ public static int CompareDocumentOrder(XNode n1, XNode n2) { do { - n2 = n2.parent; + n2 = n2.parent!; height++; } while (height != 0); if (n1 == n2) return -1; @@ -268,25 +270,25 @@ public static int CompareDocumentOrder(XNode n1, XNode n2) { do { - n1 = n1.parent; + n1 = n1.parent!; height--; } while (height != 0); if (n1 == n2) return 1; } while (n1.parent != n2.parent) { - n1 = n1.parent; - n2 = n2.parent; + n1 = n1.parent!; + n2 = n2.parent!; } } else if (n1.parent == null) { throw new InvalidOperationException(SR.InvalidOperation_MissingAncestor); } - XNode n = (XNode)n1.parent.content; + XNode n = (XNode)n1.parent!.content!; while (true) { - n = n.next; + n = n.next!; if (n == n1) return -1; if (n == n2) return 1; } @@ -325,7 +327,7 @@ public IEnumerable NodesAfterSelf() XNode n = this; while (n.parent != null && n != n.parent.content) { - n = n.next; + n = n.next!; yield return n; } } @@ -341,10 +343,10 @@ public IEnumerable NodesBeforeSelf() { if (parent != null) { - XNode n = (XNode)parent.content; + XNode n = (XNode)parent.content!; do { - n = n.next; + n = n.next!; if (n == this) break; yield return n; } while (parent != null && parent == n.parent); @@ -372,7 +374,7 @@ public IEnumerable ElementsAfterSelf() /// /// The element nodes after this node with the specified name. /// The name of elements to enumerate. - public IEnumerable ElementsAfterSelf(XName name) + public IEnumerable ElementsAfterSelf(XName? name) { return name != null ? GetElementsAfterSelf(name) : XElement.EmptySequence; } @@ -398,7 +400,7 @@ public IEnumerable ElementsBeforeSelf() /// /// The element nodes before this node with the specified name. /// The name of elements to enumerate. - public IEnumerable ElementsBeforeSelf(XName name) + public IEnumerable ElementsBeforeSelf(XName? name) { return name != null ? GetElementsBeforeSelf(name) : XElement.EmptySequence; } @@ -409,7 +411,7 @@ public IEnumerable ElementsBeforeSelf(XName name) /// /// The node to compare for document order. /// True if this node appears after the specified node; false if not. - public bool IsAfter(XNode node) + public bool IsAfter(XNode? node) { return CompareDocumentOrder(this, node) > 0; } @@ -420,7 +422,7 @@ public bool IsAfter(XNode node) /// /// The node to compare for document order. /// True if this node appears before the specified node; false if not. - public bool IsBefore(XNode node) + public bool IsBefore(XNode? node) { return CompareDocumentOrder(this, node) < 0; } @@ -549,12 +551,12 @@ public void Remove() /// Replaces the content of this . /// /// Content that replaces this node. - public void ReplaceWith(object content) + public void ReplaceWith(object? content) { if (parent == null) throw new InvalidOperationException(SR.InvalidOperation_MissingParent); XContainer c = parent; - XNode p = (XNode)parent.content; - while (p.next != this) p = p.next; + XNode? p = (XNode)parent.content!; + while (p.next != this) p = p.next!; if (p == parent.content) p = null; parent.RemoveNode(this); if (p != null && p.parent != c) throw new InvalidOperationException(SR.InvalidOperation_ExternalCode); @@ -611,7 +613,7 @@ public string ToString(SaveOptions options) /// Two nodes are equal if they have the same /// target and data. Two nodes are equal if the have the /// same name, public id, system id, and internal subset. - public static bool DeepEquals(XNode n1, XNode n2) + public static bool DeepEquals(XNode? n1, XNode? n2) { if (n1 == n2) return true; if (n1 == null || n2 == null) return false; @@ -639,9 +641,9 @@ internal virtual void AppendText(StringBuilder sb) internal abstract bool DeepEquals(XNode node); - internal IEnumerable GetAncestors(XName name, bool self) + internal IEnumerable GetAncestors(XName? name, bool self) { - XElement e = (self ? this : parent) as XElement; + XElement? e = (self ? this : parent) as XElement; while (e != null) { if (name == null || e.name == name) yield return e; @@ -649,27 +651,27 @@ internal IEnumerable GetAncestors(XName name, bool self) } } - private IEnumerable GetElementsAfterSelf(XName name) + private IEnumerable GetElementsAfterSelf(XName? name) { XNode n = this; while (n.parent != null && n != n.parent.content) { - n = n.next; - XElement e = n as XElement; + n = n.next!; + XElement? e = n as XElement; if (e != null && (name == null || e.name == name)) yield return e; } } - private IEnumerable GetElementsBeforeSelf(XName name) + private IEnumerable GetElementsBeforeSelf(XName? name) { if (parent != null) { - XNode n = (XNode)parent.content; + XNode n = (XNode)parent.content!; do { - n = n.next; + n = n.next!; if (n == this) break; - XElement e = n as XElement; + XElement? e = n as XElement; if (e != null && (name == null || e.name == name)) yield return e; } while (parent != null && parent == n.parent); } @@ -712,7 +714,7 @@ private string GetXmlString(SaveOptions o) if (this is XText) ws.ConformanceLevel = ConformanceLevel.Fragment; using (XmlWriter w = XmlWriter.Create(sw, ws)) { - XDocument n = this as XDocument; + XDocument? n = this as XDocument; if (n != null) { n.WriteContentTo(w); diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNodeBuilder.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNodeBuilder.cs index 0c6f99cf18c299..5269b2fc077a3c 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNodeBuilder.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNodeBuilder.cs @@ -2,15 +2,16 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; +using System.Diagnostics; namespace System.Xml.Linq { internal class XNodeBuilder : XmlWriter { - private List _content; - private XContainer _parent; - private XName _attrName; - private string _attrValue; + private List? _content; + private XContainer? _parent; + private XName? _attrName; + private string? _attrValue; private readonly XContainer _root; public XNodeBuilder(XContainer container) @@ -60,9 +61,9 @@ public override void WriteBase64(byte[] buffer, int index, int count) throw new NotSupportedException(SR.NotSupported_WriteBase64); } - public override void WriteCData(string text) + public override void WriteCData(string? text) { - AddNode(new XCData(text)); + AddNode(new XCData(text!)); } public override void WriteCharEntity(char ch) @@ -75,19 +76,20 @@ public override void WriteChars(char[] buffer, int index, int count) AddString(new string(buffer, index, count)); } - public override void WriteComment(string text) + public override void WriteComment(string? text) { - AddNode(new XComment(text)); + AddNode(new XComment(text!)); } - public override void WriteDocType(string name, string pubid, string sysid, string subset) + public override void WriteDocType(string name, string? pubid, string? sysid, string? subset) { + Debug.Assert(subset != null); AddNode(new XDocumentType(name, pubid, sysid, subset)); } public override void WriteEndAttribute() { - XAttribute a = new XAttribute(_attrName, _attrValue); + XAttribute a = new XAttribute(_attrName!, _attrValue!); _attrName = null; _attrValue = null; if (_parent != null) @@ -106,7 +108,7 @@ public override void WriteEndDocument() public override void WriteEndElement() { - _parent = ((XElement)_parent).parent; + _parent = ((XElement)_parent!).parent; } public override void WriteEntityRef(string name) @@ -135,7 +137,7 @@ public override void WriteEntityRef(string name) public override void WriteFullEndElement() { - XElement e = (XElement)_parent; + XElement e = (XElement)_parent!; if (e.IsEmpty) { e.Add(string.Empty); @@ -143,13 +145,13 @@ public override void WriteFullEndElement() _parent = e.parent; } - public override void WriteProcessingInstruction(string name, string text) + public override void WriteProcessingInstruction(string name, string? text) { if (name == "xml") { return; } - AddNode(new XProcessingInstruction(name, text)); + AddNode(new XProcessingInstruction(name, text!)); } public override void WriteRaw(char[] buffer, int index, int count) @@ -162,10 +164,10 @@ public override void WriteRaw(string data) AddString(data); } - public override void WriteStartAttribute(string prefix, string localName, string namespaceName) + public override void WriteStartAttribute(string? prefix, string localName, string? namespaceName) { if (prefix == null) throw new ArgumentNullException(nameof(prefix)); - _attrName = XNamespace.Get(prefix.Length == 0 ? string.Empty : namespaceName).GetName(localName); + _attrName = XNamespace.Get(prefix.Length == 0 ? string.Empty : namespaceName!).GetName(localName); _attrValue = string.Empty; } @@ -177,12 +179,12 @@ public override void WriteStartDocument(bool standalone) { } - public override void WriteStartElement(string prefix, string localName, string namespaceName) + public override void WriteStartElement(string? prefix, string localName, string? namespaceName) { - AddNode(new XElement(XNamespace.Get(namespaceName).GetName(localName))); + AddNode(new XElement(XNamespace.Get(namespaceName!).GetName(localName))); } - public override void WriteString(string text) + public override void WriteString(string? text) { AddString(text); } @@ -200,7 +202,7 @@ public override void WriteValue(DateTimeOffset value) WriteString(XmlConvert.ToString(value)); } - public override void WriteWhitespace(string ws) + public override void WriteWhitespace(string? ws) { AddString(ws); } @@ -224,14 +226,14 @@ private void AddNode(XNode n) { Add(n); } - XContainer c = n as XContainer; + XContainer? c = n as XContainer; if (c != null) { _parent = c; } } - private void AddString(string s) + private void AddString(string? s) { if (s == null) { diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNodeDocumentOrderComparer.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNodeDocumentOrderComparer.cs index c80448c404de71..6abc99f4dc025e 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNodeDocumentOrderComparer.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNodeDocumentOrderComparer.cs @@ -28,7 +28,7 @@ public sealed class XNodeDocumentOrderComparer : /// /// Thrown if the two nodes do not share a common ancestor. /// - public int Compare(XNode x, XNode y) + public int Compare(XNode? x, XNode? y) { return XNode.CompareDocumentOrder(x, y); } @@ -49,11 +49,11 @@ public int Compare(XNode x, XNode y) /// /// Thrown if either of the two nodes are not derived from XNode. /// - int IComparer.Compare(object x, object y) + int IComparer.Compare(object? x, object? y) { - XNode n1 = x as XNode; + XNode? n1 = x as XNode; if (n1 == null && x != null) throw new ArgumentException(SR.Format(SR.Argument_MustBeDerivedFrom, typeof(XNode)), nameof(x)); - XNode n2 = y as XNode; + XNode? n2 = y as XNode; if (n2 == null && y != null) throw new ArgumentException(SR.Format(SR.Argument_MustBeDerivedFrom, typeof(XNode)), nameof(y)); return Compare(n1, n2); } diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNodeEqualityComparer.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNodeEqualityComparer.cs index 93b40b1fd11ca0..0b3b2dd94ac18c 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNodeEqualityComparer.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNodeEqualityComparer.cs @@ -34,7 +34,7 @@ public sealed class XNodeEqualityComparer : /// target and data. Two nodes are equal if the have the /// same name, public id, system id, and internal subset. /// - public bool Equals(XNode x, XNode y) + public bool Equals(XNode? x, XNode? y) { return XNode.DeepEquals(x, y); } @@ -73,11 +73,11 @@ public int GetHashCode(XNode obj) /// target and data. Two nodes are equal if the have the /// same name, public id, system id, and internal subset. /// - bool IEqualityComparer.Equals(object x, object y) + bool IEqualityComparer.Equals(object? x, object? y) { - XNode n1 = x as XNode; + XNode? n1 = x as XNode; if (n1 == null && x != null) throw new ArgumentException(SR.Format(SR.Argument_MustBeDerivedFrom, typeof(XNode)), nameof(x)); - XNode n2 = y as XNode; + XNode? n2 = y as XNode; if (n2 == null && y != null) throw new ArgumentException(SR.Format(SR.Argument_MustBeDerivedFrom, typeof(XNode)), nameof(y)); return Equals(n1, n2); } @@ -94,9 +94,9 @@ bool IEqualityComparer.Equals(object x, object y) /// int IEqualityComparer.GetHashCode(object obj) { - XNode n = obj as XNode; + XNode? n = obj as XNode; if (n == null && obj != null) throw new ArgumentException(SR.Format(SR.Argument_MustBeDerivedFrom, typeof(XNode)), nameof(obj)); - return GetHashCode(n); + return GetHashCode(n!); } } } diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNodeReader.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNodeReader.cs index daa1a2e1022f21..96b9d9f5d68073 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNodeReader.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XNodeReader.cs @@ -14,13 +14,13 @@ internal class XNodeReader : XmlReader, IXmlLineInfo // uses (instance, parent attribute). End element uses (instance, // instance). Common XObject uses (instance, null). private object _source; - private object _parent; + private object? _parent; private ReadState _state; private XNode _root; private readonly XmlNameTable _nameTable; private readonly bool _omitDuplicateNamespaces; - internal XNodeReader(XNode node, XmlNameTable nameTable, ReaderOptions options) + internal XNodeReader(XNode node, XmlNameTable? nameTable, ReaderOptions options) { _source = node; _root = node; @@ -28,7 +28,7 @@ internal XNodeReader(XNode node, XmlNameTable nameTable, ReaderOptions options) _omitDuplicateNamespaces = (options & ReaderOptions.OmitDuplicateNamespaces) != 0 ? true : false; } - internal XNodeReader(XNode node, XmlNameTable nameTable) + internal XNodeReader(XNode node, XmlNameTable? nameTable) : this(node, nameTable, (node.GetSaveOptionsFromAnnotations() & SaveOptions.OmitDuplicateNamespaces) != 0 ? ReaderOptions.OmitDuplicateNamespaces : ReaderOptions.None) @@ -44,15 +44,15 @@ public override int AttributeCount return 0; } int count = 0; - XElement e = GetElementInAttributeScope(); + XElement? e = GetElementInAttributeScope(); if (e != null) { - XAttribute a = e.lastAttr; + XAttribute? a = e.lastAttr; if (a != null) { do { - a = a.next; + a = a.next!; if (!_omitDuplicateNamespaces || !IsDuplicateNamespaceAttribute(a)) { count++; @@ -68,7 +68,7 @@ public override string BaseURI { get { - XObject o = _source as XObject; + XObject? o = _source as XObject; if (o != null) { return o.BaseUri; @@ -90,7 +90,7 @@ public override int Depth { return 0; } - XObject o = _source as XObject; + XObject? o = _source as XObject; if (o != null) { return GetDepth(o); @@ -132,12 +132,12 @@ public override bool HasAttributes { return false; } - XElement e = GetElementInAttributeScope(); + XElement? e = GetElementInAttributeScope(); if (e != null && e.lastAttr != null) { if (_omitDuplicateNamespaces) { - return GetFirstNonDuplicateNamespaceAttribute(e.lastAttr.next) != null; + return GetFirstNonDuplicateNamespaceAttribute(e.lastAttr.next!) != null; } else { @@ -159,7 +159,7 @@ public override bool HasValue { return false; } - XObject o = _source as XObject; + XObject? o = _source as XObject; if (o != null) { switch (o.NodeType) @@ -187,7 +187,7 @@ public override bool IsEmptyElement { return false; } - XElement e = _source as XElement; + XElement? e = _source as XElement; return e != null && e.IsEmpty; } } @@ -203,22 +203,22 @@ private string GetLocalName() { return string.Empty; } - XElement e = _source as XElement; + XElement? e = _source as XElement; if (e != null) { return e.Name.LocalName; } - XAttribute a = _source as XAttribute; + XAttribute? a = _source as XAttribute; if (a != null) { return a.Name.LocalName; } - XProcessingInstruction p = _source as XProcessingInstruction; + XProcessingInstruction? p = _source as XProcessingInstruction; if (p != null) { return p.Target; } - XDocumentType n = _source as XDocumentType; + XDocumentType? n = _source as XDocumentType; if (n != null) { return n.Name; @@ -250,12 +250,12 @@ private string GetNamespaceURI() { return string.Empty; } - XElement e = _source as XElement; + XElement? e = _source as XElement; if (e != null) { return e.Name.NamespaceName; } - XAttribute a = _source as XAttribute; + XAttribute? a = _source as XAttribute; if (a != null) { string namespaceName = a.Name.NamespaceName; @@ -281,7 +281,7 @@ public override XmlNodeType NodeType { return XmlNodeType.None; } - XObject o = _source as XObject; + XObject? o = _source as XObject; if (o != null) { if (IsEndElement) @@ -318,20 +318,20 @@ private string GetPrefix() { return string.Empty; } - XElement e = _source as XElement; + XElement? e = _source as XElement; if (e != null) { - string prefix = e.GetPrefixOfNamespace(e.Name.Namespace); + string? prefix = e.GetPrefixOfNamespace(e.Name.Namespace); if (prefix != null) { return prefix; } return string.Empty; } - XAttribute a = _source as XAttribute; + XAttribute? a = _source as XAttribute; if (a != null) { - string prefix = a.GetPrefixOfNamespace(a.Name.Namespace); + string? prefix = a.GetPrefixOfNamespace(a.Name.Namespace); if (prefix != null) { return prefix; @@ -363,7 +363,7 @@ public override string Value { return string.Empty; } - XObject o = _source as XObject; + XObject? o = _source as XObject; if (o != null) { switch (o.NodeType) @@ -395,13 +395,13 @@ public override string XmlLang { return string.Empty; } - XElement e = GetElementInScope(); + XElement? e = GetElementInScope(); if (e != null) { XName name = XNamespace.Xml.GetName("lang"); do { - XAttribute a = e.Attribute(name); + XAttribute? a = e.Attribute(name); if (a != null) { return a.Value; @@ -421,13 +421,13 @@ public override XmlSpace XmlSpace { return XmlSpace.None; } - XElement e = GetElementInScope(); + XElement? e = GetElementInScope(); if (e != null) { XName name = XNamespace.Xml.GetName("space"); do { - XAttribute a = e.Attribute(name); + XAttribute? a = e.Attribute(name); if (a != null) { switch (a.Value.Trim(s_WhitespaceChars)) @@ -457,29 +457,29 @@ protected override void Dispose(bool disposing) public override void Close() { - _source = null; + _source = null!; _parent = null; - _root = null; + _root = null!; _state = ReadState.Closed; } - public override string GetAttribute(string name) + public override string? GetAttribute(string name) { if (!IsInteractive) { return null; } - XElement e = GetElementInAttributeScope(); + XElement? e = GetElementInAttributeScope(); if (e != null) { - string localName, namespaceName; + string? localName, namespaceName; GetNameInAttributeScope(name, e, out localName, out namespaceName); - XAttribute a = e.lastAttr; + XAttribute? a = e.lastAttr; if (a != null) { do { - a = a.next; + a = a.next!; if (a.Name.LocalName == localName && a.Name.NamespaceName == namespaceName) { if (_omitDuplicateNamespaces && IsDuplicateNamespaceAttribute(a)) @@ -495,7 +495,7 @@ public override string GetAttribute(string name) } return null; } - XDocumentType n = _source as XDocumentType; + XDocumentType? n = _source as XDocumentType; if (n != null) { switch (name) @@ -509,13 +509,13 @@ public override string GetAttribute(string name) return null; } - public override string GetAttribute(string localName, string namespaceName) + public override string? GetAttribute(string localName, string? namespaceName) { if (!IsInteractive) { return null; } - XElement e = GetElementInAttributeScope(); + XElement? e = GetElementInAttributeScope(); if (e != null) { if (localName == "xmlns") @@ -529,12 +529,12 @@ public override string GetAttribute(string localName, string namespaceName) namespaceName = string.Empty; } } - XAttribute a = e.lastAttr; + XAttribute? a = e.lastAttr; if (a != null) { do { - a = a.next; + a = a.next!; if (a.Name.LocalName == localName && a.Name.NamespaceName == namespaceName) { if (_omitDuplicateNamespaces && IsDuplicateNamespaceAttribute(a)) @@ -552,25 +552,26 @@ public override string GetAttribute(string localName, string namespaceName) return null; } + // TODO-NULLABLE: decide if base signature should be switched to return string? public override string GetAttribute(int index) { if (!IsInteractive) { - return null; + return null!; } if (index < 0) { - return null; + return null!; } - XElement e = GetElementInAttributeScope(); + XElement? e = GetElementInAttributeScope(); if (e != null) { - XAttribute a = e.lastAttr; + XAttribute? a = e.lastAttr; if (a != null) { do { - a = a.next; + a = a.next!; if (!_omitDuplicateNamespaces || !IsDuplicateNamespaceAttribute(a)) { if (index-- == 0) @@ -581,10 +582,10 @@ public override string GetAttribute(int index) } while (a != e.lastAttr); } } - return null; + return null!; } - public override string LookupNamespace(string prefix) + public override string? LookupNamespace(string prefix) { if (!IsInteractive) { @@ -594,10 +595,10 @@ public override string LookupNamespace(string prefix) { return null; } - XElement e = GetElementInScope(); + XElement? e = GetElementInScope(); if (e != null) { - XNamespace ns = prefix.Length == 0 ? e.GetDefaultNamespace() : e.GetNamespaceOfPrefix(prefix); + XNamespace? ns = prefix.Length == 0 ? e.GetDefaultNamespace() : e.GetNamespaceOfPrefix(prefix); if (ns != null) { return _nameTable.Add(ns.NamespaceName); @@ -612,17 +613,17 @@ public override bool MoveToAttribute(string name) { return false; } - XElement e = GetElementInAttributeScope(); + XElement? e = GetElementInAttributeScope(); if (e != null) { - string localName, namespaceName; + string? localName, namespaceName; GetNameInAttributeScope(name, e, out localName, out namespaceName); - XAttribute a = e.lastAttr; + XAttribute? a = e.lastAttr; if (a != null) { do { - a = a.next; + a = a.next!; if (a.Name.LocalName == localName && a.Name.NamespaceName == namespaceName) { @@ -644,13 +645,13 @@ public override bool MoveToAttribute(string name) return false; } - public override bool MoveToAttribute(string localName, string namespaceName) + public override bool MoveToAttribute(string localName, string? namespaceName) { if (!IsInteractive) { return false; } - XElement e = GetElementInAttributeScope(); + XElement? e = GetElementInAttributeScope(); if (e != null) { if (localName == "xmlns") @@ -664,12 +665,12 @@ public override bool MoveToAttribute(string localName, string namespaceName) namespaceName = string.Empty; } } - XAttribute a = e.lastAttr; + XAttribute? a = e.lastAttr; if (a != null) { do { - a = a.next; + a = a.next!; if (a.Name.LocalName == localName && a.Name.NamespaceName == namespaceName) { @@ -698,15 +699,15 @@ public override void MoveToAttribute(int index) return; } if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); - XElement e = GetElementInAttributeScope(); + XElement? e = GetElementInAttributeScope(); if (e != null) { - XAttribute a = e.lastAttr; + XAttribute? a = e.lastAttr; if (a != null) { do { - a = a.next; + a = a.next!; if (!_omitDuplicateNamespaces || !IsDuplicateNamespaceAttribute(a)) { // Only count those which are non-duplicates if we're asked to @@ -729,7 +730,7 @@ public override bool MoveToElement() { return false; } - XAttribute a = _source as XAttribute; + XAttribute? a = _source as XAttribute; if (a == null) { a = _parent as XAttribute; @@ -752,14 +753,14 @@ public override bool MoveToFirstAttribute() { return false; } - XElement e = GetElementInAttributeScope(); + XElement? e = GetElementInAttributeScope(); if (e != null) { if (e.lastAttr != null) { if (_omitDuplicateNamespaces) { - object na = GetFirstNonDuplicateNamespaceAttribute(e.lastAttr.next); + object? na = GetFirstNonDuplicateNamespaceAttribute(e.lastAttr.next!); if (na == null) { return false; @@ -768,7 +769,7 @@ public override bool MoveToFirstAttribute() } else { - _source = e.lastAttr.next; + _source = e.lastAttr.next!; } return true; } @@ -782,7 +783,7 @@ public override bool MoveToNextAttribute() { return false; } - XElement e = _source as XElement; + XElement? e = _source as XElement; if (e != null) { if (IsEndElement) @@ -796,7 +797,7 @@ public override bool MoveToNextAttribute() // Skip duplicate namespace attributes // We must NOT modify the this.source until we find the one we're looking for // because if we don't find anything, we need to stay positioned where we're now - object na = GetFirstNonDuplicateNamespaceAttribute(e.lastAttr.next); + object? na = GetFirstNonDuplicateNamespaceAttribute(e.lastAttr.next!); if (na == null) { return false; @@ -805,13 +806,13 @@ public override bool MoveToNextAttribute() } else { - _source = e.lastAttr.next; + _source = e.lastAttr.next!; } return true; } return false; } - XAttribute a = _source as XAttribute; + XAttribute? a = _source as XAttribute; if (a == null) { a = _parent as XAttribute; @@ -825,7 +826,7 @@ public override bool MoveToNextAttribute() // Skip duplicate namespace attributes // We must NOT modify the this.source until we find the one we're looking for // because if we don't find anything, we need to stay positioned where we're now - object na = GetFirstNonDuplicateNamespaceAttribute(a.next); + object? na = GetFirstNonDuplicateNamespaceAttribute(a.next!); if (na == null) { return false; @@ -834,7 +835,7 @@ public override bool MoveToNextAttribute() } else { - _source = a.next; + _source = a.next!; } _parent = null; return true; @@ -849,7 +850,7 @@ public override bool Read() { case ReadState.Initial: _state = ReadState.Interactive; - XDocument d = _source as XDocument; + XDocument? d = _source as XDocument; if (d != null) { return ReadIntoDocument(d); @@ -868,7 +869,7 @@ public override bool ReadAttributeValue() { return false; } - XAttribute a = _source as XAttribute; + XAttribute? a = _source as XAttribute; if (a != null) { return ReadIntoAttribute(a); @@ -883,7 +884,7 @@ public override bool ReadToDescendant(string localName, string namespaceName) return false; } MoveToElement(); - XElement c = _source as XElement; + XElement? c = _source as XElement; if (c != null && !c.IsEmpty) { if (IsEndElement) @@ -908,7 +909,7 @@ public override bool ReadToFollowing(string localName, string namespaceName) { while (Read()) { - XElement e = _source as XElement; + XElement? e = _source as XElement; if (e != null) { if (IsEndElement) continue; @@ -930,7 +931,7 @@ public override bool ReadToNextSibling(string localName, string namespaceName) MoveToElement(); if (_source != _root) { - XNode n = _source as XNode; + XNode? n = _source as XNode; if (n != null) { foreach (XElement e in n.ElementsAfterSelf()) @@ -983,7 +984,7 @@ bool IXmlLineInfo.HasLineInfo() { // Special case for EndElement - we store the line info differently in this case // we also know that the current node (source) is XElement - XElement e = _source as XElement; + XElement? e = _source as XElement; if (e != null) { return e.Annotation() != null; @@ -991,7 +992,7 @@ bool IXmlLineInfo.HasLineInfo() } else { - IXmlLineInfo li = _source as IXmlLineInfo; + IXmlLineInfo? li = _source as IXmlLineInfo; if (li != null) { return li.HasLineInfo(); @@ -1008,10 +1009,10 @@ int IXmlLineInfo.LineNumber { // Special case for EndElement - we store the line info differently in this case // we also know that the current node (source) is XElement - XElement e = _source as XElement; + XElement? e = _source as XElement; if (e != null) { - LineInfoEndElementAnnotation a = e.Annotation(); + LineInfoEndElementAnnotation? a = e.Annotation(); if (a != null) { return a.lineNumber; @@ -1020,7 +1021,7 @@ int IXmlLineInfo.LineNumber } else { - IXmlLineInfo li = _source as IXmlLineInfo; + IXmlLineInfo? li = _source as IXmlLineInfo; if (li != null) { return li.LineNumber; @@ -1038,10 +1039,10 @@ int IXmlLineInfo.LinePosition { // Special case for EndElement - we store the line info differently in this case // we also know that the current node (source) is XElement - XElement e = _source as XElement; + XElement? e = _source as XElement; if (e != null) { - LineInfoEndElementAnnotation a = e.Annotation(); + LineInfoEndElementAnnotation? a = e.Annotation(); if (a != null) { return a.linePosition; @@ -1050,7 +1051,7 @@ int IXmlLineInfo.LinePosition } else { - IXmlLineInfo li = _source as IXmlLineInfo; + IXmlLineInfo? li = _source as IXmlLineInfo; if (li != null) { return li.LinePosition; @@ -1080,9 +1081,9 @@ private static XmlNameTable CreateNameTable() return nameTable; } - private XElement GetElementInAttributeScope() + private XElement? GetElementInAttributeScope() { - XElement e = _source as XElement; + XElement? e = _source as XElement; if (e != null) { if (IsEndElement) @@ -1091,35 +1092,35 @@ private XElement GetElementInAttributeScope() } return e; } - XAttribute a = _source as XAttribute; + XAttribute? a = _source as XAttribute; if (a != null) { - return (XElement)a.parent; + return (XElement?)a.parent; } a = _parent as XAttribute; if (a != null) { - return (XElement)a.parent; + return (XElement?)a.parent; } return null; } - private XElement GetElementInScope() + private XElement? GetElementInScope() { - XElement e = _source as XElement; + XElement? e = _source as XElement; if (e != null) { return e; } - XNode n = _source as XNode; + XNode? n = _source as XNode; if (n != null) { return n.parent as XElement; } - XAttribute a = _source as XAttribute; + XAttribute? a = _source as XAttribute; if (a != null) { - return (XElement)a.parent; + return (XElement?)a.parent; } e = _parent as XElement; if (e != null) @@ -1129,12 +1130,12 @@ private XElement GetElementInScope() a = _parent as XAttribute; if (a != null) { - return (XElement)a.parent; + return (XElement?)a.parent; } return null; } - private static void GetNameInAttributeScope(string qualifiedName, XElement e, out string localName, out string namespaceName) + private static void GetNameInAttributeScope(string? qualifiedName, XElement e, out string? localName, out string? namespaceName) { if (!string.IsNullOrEmpty(qualifiedName)) { @@ -1147,7 +1148,7 @@ private static void GetNameInAttributeScope(string qualifiedName, XElement e, ou namespaceName = string.Empty; return; } - XNamespace ns = e.GetNamespaceOfPrefix(qualifiedName.Substring(0, i)); + XNamespace? ns = e.GetNamespaceOfPrefix(qualifiedName.Substring(0, i)); if (ns != null) { localName = qualifiedName.Substring(i + 1, qualifiedName.Length - i - 1); @@ -1162,7 +1163,7 @@ private static void GetNameInAttributeScope(string qualifiedName, XElement e, ou private bool Read(bool skipContent) { - XElement e = _source as XElement; + XElement? e = _source as XElement; if (e != null) { if (e.IsEmpty || IsEndElement || skipContent) @@ -1171,12 +1172,12 @@ private bool Read(bool skipContent) } return ReadIntoElement(e); } - XNode n = _source as XNode; + XNode? n = _source as XNode; if (n != null) { return ReadOverNode(n); } - XAttribute a = _source as XAttribute; + XAttribute? a = _source as XAttribute; if (a != null) { return ReadOverAttribute(a, skipContent); @@ -1186,13 +1187,13 @@ private bool Read(bool skipContent) private bool ReadIntoDocument(XDocument d) { - XNode n = d.content as XNode; + XNode? n = d.content as XNode; if (n != null) { - _source = n.next; + _source = n.next!; return true; } - string s = d.content as string; + string? s = d.content as string; if (s != null) { if (s.Length > 0) @@ -1207,13 +1208,13 @@ private bool ReadIntoDocument(XDocument d) private bool ReadIntoElement(XElement e) { - XNode n = e.content as XNode; + XNode? n = e.content as XNode; if (n != null) { - _source = n.next; + _source = n.next!; return true; } - string s = e.content as string; + string? s = e.content as string; if (s != null) { if (s.Length > 0) @@ -1240,7 +1241,7 @@ private bool ReadIntoAttribute(XAttribute a) private bool ReadOverAttribute(XAttribute a, bool skipContent) { - XElement e = (XElement)a.parent; + XElement? e = (XElement?)a.parent; if (e != null) { if (e.IsEmpty || skipContent) @@ -1258,8 +1259,8 @@ private bool ReadOverNode(XNode n) { return ReadToEnd(); } - XNode next = n.next; - if (null == next || next == n || n == n.parent.content) + XNode? next = n.next; + if (null == next || next == n || n == n.parent!.content) { if (n.parent == null || (n.parent.parent == null && n.parent is XDocument)) { @@ -1286,7 +1287,7 @@ private bool ReadOverText(bool skipContent) return true; } - XAttribute parent = _parent as XAttribute; + XAttribute? parent = _parent as XAttribute; if (parent != null) { _parent = null; @@ -1333,7 +1334,7 @@ private bool IsDuplicateNamespaceAttributeInner(XAttribute candidateAttribute) // and find the closest namespace declaration attribute which declares the same prefix // If it declares that prefix to the exact same URI as ours does then ours is a duplicate // Note that if we find a namespace declaration for the same prefix but with a different URI, then we don't have a dupe! - XElement element = candidateAttribute.parent as XElement; + XElement? element = candidateAttribute.parent as XElement; if (element == _root || element == null) { // If there's only the parent element of our attribute, there can be no duplicates @@ -1347,7 +1348,7 @@ private bool IsDuplicateNamespaceAttributeInner(XAttribute candidateAttribute) // (The default ns decl is represented by an XName "xmlns{}", even if you try to create // an attribute with XName "xmlns{http://www.w3.org/2000/xmlns/}" it will fail, // because it's treated as a declaration of prefix "xmlns" which is invalid) - XAttribute a = element.lastAttr; + XAttribute? a = element.lastAttr; if (a != null) { do @@ -1367,7 +1368,7 @@ private bool IsDuplicateNamespaceAttributeInner(XAttribute candidateAttribute) return false; } } - a = a.next; + a = a.next!; } while (a != element.lastAttr); } if (element == _root) @@ -1384,7 +1385,7 @@ private bool IsDuplicateNamespaceAttributeInner(XAttribute candidateAttribute) /// /// The attribute to start with /// The first attribute which is not a namespace attribute or null if the end of attributes has bean reached - private XAttribute GetFirstNonDuplicateNamespaceAttribute(XAttribute candidate) + private XAttribute? GetFirstNonDuplicateNamespaceAttribute(XAttribute candidate) { Debug.Assert(_omitDuplicateNamespaces, "This method should only be called if we're omitting duplicate namespace attribute." + "For perf reason it's better to test this flag in the caller method."); @@ -1393,12 +1394,12 @@ private XAttribute GetFirstNonDuplicateNamespaceAttribute(XAttribute candidate) return candidate; } - XElement e = candidate.parent as XElement; + XElement? e = candidate.parent as XElement; if (e != null && candidate != e.lastAttr) { do { - candidate = candidate.next; + candidate = candidate.next!; if (!IsDuplicateNamespaceAttribute(candidate)) { return candidate; diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XObject.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XObject.cs index 26af0ce9100dd0..1855419be7db42 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XObject.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XObject.cs @@ -13,8 +13,8 @@ namespace System.Xml.Linq /// public abstract class XObject : IXmlLineInfo { - internal XContainer parent; - internal object annotations; + internal XContainer? parent; + internal object? annotations; internal XObject() { } @@ -25,7 +25,7 @@ public string BaseUri { get { - XObject o = this; + XObject? o = this; while (true) { while (o != null && o.annotations == null) @@ -33,7 +33,7 @@ public string BaseUri o = o.parent; } if (o == null) break; - BaseUriAnnotation a = o.Annotation(); + BaseUriAnnotation? a = o.Annotation(); if (a != null) return a.baseUri; o = o.parent; } @@ -44,13 +44,16 @@ public string BaseUri /// /// Gets the XDocument object for this . /// - public XDocument Document + public XDocument? Document { get { XObject n = this; while (n.parent != null) n = n.parent; - return n as XDocument; + + XDocument? doc = n as XDocument; + + return doc; } } @@ -65,7 +68,7 @@ public XDocument Document /// /// If this has no parent , this property returns null. /// - public XElement Parent + public XElement? Parent { get { return parent as XElement; } } @@ -83,7 +86,7 @@ public void AddAnnotation(object annotation) } else { - object[] a = annotations as object[]; + object?[]? a = annotations as object[]; if (a == null) { annotations = new object[] { annotations, annotation }; @@ -111,12 +114,12 @@ public void AddAnnotation(object annotation) /// The first matching annotation object, or null /// if no annotation is the specified type. /// - public object Annotation(Type type) + public object? Annotation(Type type) { if (type == null) throw new ArgumentNullException(nameof(type)); if (annotations != null) { - object[] a = annotations as object[]; + object?[]? a = annotations as object[]; if (a == null) { if (XHelper.IsInstanceOfType(annotations, type)) return annotations; @@ -125,7 +128,7 @@ public object Annotation(Type type) { for (int i = 0; i < a.Length; i++) { - object obj = a[i]; + object? obj = a[i]; if (obj == null) break; if (XHelper.IsInstanceOfType(obj, type)) return obj; } @@ -134,13 +137,13 @@ public object Annotation(Type type) return null; } - private object AnnotationForSealedType(Type type) + private object? AnnotationForSealedType(Type type) { Debug.Assert(type != null); if (annotations != null) { - object[] a = annotations as object[]; + object?[]? a = annotations as object[]; if (a == null) { if (annotations.GetType() == type) return annotations; @@ -149,7 +152,7 @@ private object AnnotationForSealedType(Type type) { for (int i = 0; i < a.Length; i++) { - object obj = a[i]; + object? obj = a[i]; if (obj == null) break; if (obj.GetType() == type) return obj; } @@ -167,17 +170,17 @@ private object AnnotationForSealedType(Type type) /// The first matching annotation object, or null if no annotation /// is the specified type. /// - public T Annotation() where T : class + public T? Annotation() where T : class { if (annotations != null) { - object[] a = annotations as object[]; + object?[]? a = annotations as object[]; if (a == null) return annotations as T; for (int i = 0; i < a.Length; i++) { - object obj = a[i]; + object? obj = a[i]; if (obj == null) break; - T result = obj as T; + T? result = obj as T; if (result != null) return result; } } @@ -200,7 +203,7 @@ private IEnumerable AnnotationsIterator(Type type) { if (annotations != null) { - object[] a = annotations as object[]; + object?[]? a = annotations as object[]; if (a == null) { if (XHelper.IsInstanceOfType(annotations, type)) yield return annotations; @@ -209,7 +212,7 @@ private IEnumerable AnnotationsIterator(Type type) { for (int i = 0; i < a.Length; i++) { - object obj = a[i]; + object? obj = a[i]; if (obj == null) break; if (XHelper.IsInstanceOfType(obj, type)) yield return obj; } @@ -227,19 +230,19 @@ public IEnumerable Annotations() where T : class { if (annotations != null) { - object[] a = annotations as object[]; + object?[]? a = annotations as object[]; if (a == null) { - T result = annotations as T; + T? result = annotations as T; if (result != null) yield return result; } else { for (int i = 0; i < a.Length; i++) { - object obj = a[i]; + object? obj = a[i]; if (obj == null) break; - T result = obj as T; + T? result = obj as T; if (result != null) yield return result; } } @@ -255,7 +258,7 @@ public void RemoveAnnotations(Type type) if (type == null) throw new ArgumentNullException(nameof(type)); if (annotations != null) { - object[] a = annotations as object[]; + object?[]? a = annotations as object[]; if (a == null) { if (XHelper.IsInstanceOfType(annotations, type)) annotations = null; @@ -265,7 +268,7 @@ public void RemoveAnnotations(Type type) int i = 0, j = 0; while (i < a.Length) { - object obj = a[i]; + object? obj = a[i]; if (obj == null) break; if (!XHelper.IsInstanceOfType(obj, type)) a[j++] = obj; i++; @@ -290,7 +293,7 @@ public void RemoveAnnotations() where T : class { if (annotations != null) { - object[] a = annotations as object[]; + object?[]? a = annotations as object[]; if (a == null) { if (annotations is T) annotations = null; @@ -300,7 +303,7 @@ public void RemoveAnnotations() where T : class int i = 0, j = 0; while (i < a.Length) { - object obj = a[i]; + object? obj = a[i]; if (obj == null) break; if (!(obj is T)) a[j++] = obj; i++; @@ -325,7 +328,7 @@ public event EventHandler Changed add { if (value == null) return; - XObjectChangeAnnotation a = Annotation(); + XObjectChangeAnnotation? a = Annotation(); if (a == null) { a = new XObjectChangeAnnotation(); @@ -336,7 +339,7 @@ public event EventHandler Changed remove { if (value == null) return; - XObjectChangeAnnotation a = Annotation(); + XObjectChangeAnnotation? a = Annotation(); if (a == null) return; a.changed -= value; if (a.changing == null && a.changed == null) @@ -354,7 +357,7 @@ public event EventHandler Changing add { if (value == null) return; - XObjectChangeAnnotation a = Annotation(); + XObjectChangeAnnotation? a = Annotation(); if (a == null) { a = new XObjectChangeAnnotation(); @@ -365,7 +368,7 @@ public event EventHandler Changing remove { if (value == null) return; - XObjectChangeAnnotation a = Annotation(); + XObjectChangeAnnotation? a = Annotation(); if (a == null) return; a.changing -= value; if (a.changing == null && a.changed == null) @@ -384,7 +387,7 @@ int IXmlLineInfo.LineNumber { get { - LineInfoAnnotation a = Annotation(); + LineInfoAnnotation? a = Annotation(); if (a != null) return a.lineNumber; return 0; } @@ -394,7 +397,7 @@ int IXmlLineInfo.LinePosition { get { - LineInfoAnnotation a = Annotation(); + LineInfoAnnotation? a = Annotation(); if (a != null) return a.linePosition; return 0; } @@ -411,7 +414,7 @@ internal bool HasBaseUri internal bool NotifyChanged(object sender, XObjectChangeEventArgs e) { bool notify = false; - XObject o = this; + XObject? o = this; while (true) { while (o != null && o.annotations == null) @@ -419,7 +422,7 @@ internal bool NotifyChanged(object sender, XObjectChangeEventArgs e) o = o.parent; } if (o == null) break; - XObjectChangeAnnotation a = o.Annotation(); + XObjectChangeAnnotation? a = o.Annotation(); if (a != null) { notify = true; @@ -436,7 +439,7 @@ internal bool NotifyChanged(object sender, XObjectChangeEventArgs e) internal bool NotifyChanging(object sender, XObjectChangeEventArgs e) { bool notify = false; - XObject o = this; + XObject? o = this; while (true) { while (o != null && o.annotations == null) @@ -444,7 +447,7 @@ internal bool NotifyChanging(object sender, XObjectChangeEventArgs e) o = o.parent; } if (o == null) break; - XObjectChangeAnnotation a = o.Annotation(); + XObjectChangeAnnotation? a = o.Annotation(); if (a != null) { notify = true; @@ -470,7 +473,7 @@ internal void SetLineInfo(int lineNumber, int linePosition) internal bool SkipNotify() { - XObject o = this; + XObject? o = this; while (true) { while (o != null && o.annotations == null) @@ -490,7 +493,7 @@ internal bool SkipNotify() /// The effective for this internal SaveOptions GetSaveOptionsFromAnnotations() { - XObject o = this; + XObject? o = this; while (true) { while (o != null && o.annotations == null) @@ -501,7 +504,7 @@ internal SaveOptions GetSaveOptionsFromAnnotations() { return SaveOptions.None; } - object saveOptions = o.AnnotationForSealedType(typeof(SaveOptions)); + object? saveOptions = o.AnnotationForSealedType(typeof(SaveOptions)); if (saveOptions != null) { return (SaveOptions)saveOptions; diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XObjectChangeAnnotation.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XObjectChangeAnnotation.cs index 2b1d74da4b1c4f..54409b0e11a8a5 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XObjectChangeAnnotation.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XObjectChangeAnnotation.cs @@ -5,7 +5,7 @@ namespace System.Xml.Linq { internal class XObjectChangeAnnotation { - internal EventHandler changing; - internal EventHandler changed; + internal EventHandler? changing; + internal EventHandler? changed; } } diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XProcessingInstruction.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XProcessingInstruction.cs index 9cd39d6ac8a5f7..4218332977c11d 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XProcessingInstruction.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XProcessingInstruction.cs @@ -144,7 +144,7 @@ internal override XNode CloneNode() internal override bool DeepEquals(XNode node) { - XProcessingInstruction other = node as XProcessingInstruction; + XProcessingInstruction? other = node as XProcessingInstruction; return other != null && target == other.target && data == other.data; } diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XStreamingElement.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XStreamingElement.cs index eae330e4feffd8..d8a71a9c203f7f 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XStreamingElement.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Linq/XStreamingElement.cs @@ -15,7 +15,7 @@ namespace System.Xml.Linq public class XStreamingElement { internal XName name; - internal object content; + internal object? content; /// /// Creates a node with a given name @@ -69,11 +69,11 @@ public XName Name /// Add content to an /// /// Object containing content to add - public void Add(object content) + public void Add(object? content) { if (content != null) { - List list = this.content as List; + List? list = this.content as List; if (list == null) { list = new List(); diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Schema/XNodeValidator.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Schema/XNodeValidator.cs index 96cbfc6ad2f5a4..5d1f1208f4138b 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/Schema/XNodeValidator.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/Schema/XNodeValidator.cs @@ -8,25 +8,26 @@ using System.Xml; using System.Xml.Linq; using System.Runtime.Versioning; +using System.Diagnostics; namespace System.Xml.Schema { internal class XNodeValidator { private readonly XmlSchemaSet schemas; - private readonly ValidationEventHandler validationEventHandler; + private readonly ValidationEventHandler? validationEventHandler; - private XObject source; + private XObject? source; private bool addSchemaInfo; - private XmlNamespaceManager namespaceManager; - private XmlSchemaValidator validator; + private XmlNamespaceManager? namespaceManager; + private XmlSchemaValidator? validator; - private Dictionary schemaInfos; - private ArrayList defaultAttributes; + private Dictionary? schemaInfos; + private ArrayList? defaultAttributes; private readonly XName xsiTypeName; private readonly XName xsiNilName; - public XNodeValidator(XmlSchemaSet schemas, ValidationEventHandler validationEventHandler) + public XNodeValidator(XmlSchemaSet schemas, ValidationEventHandler? validationEventHandler) { this.schemas = schemas; this.validationEventHandler = validationEventHandler; @@ -36,7 +37,7 @@ public XNodeValidator(XmlSchemaSet schemas, ValidationEventHandler validationEve xsiNilName = xsi.GetName("nil"); } - public void Validate(XObject source, XmlSchemaObject partialValidationType, bool addSchemaInfo) + public void Validate(XObject source, XmlSchemaObject? partialValidationType, bool addSchemaInfo) { this.source = source; this.addSchemaInfo = addSchemaInfo; @@ -45,7 +46,7 @@ public void Validate(XObject source, XmlSchemaObject partialValidationType, bool switch (nt) { case XmlNodeType.Document: - source = ((XDocument)source).Root; + source = ((XDocument)source).Root!; if (source == null) throw new InvalidOperationException(SR.InvalidOperation_MissingRoot); validationFlags |= XmlSchemaValidationFlags.ProcessIdentityConstraints; break; @@ -91,16 +92,21 @@ private XmlSchemaInfo GetDefaultAttributeSchemaInfo(XmlSchemaAttribute sa) si.IsDefault = true; si.IsNil = false; si.SchemaAttribute = sa; + Debug.Assert(sa.AttributeSchemaType != null); XmlSchemaSimpleType st = sa.AttributeSchemaType; si.SchemaType = st; + Debug.Assert(st.Datatype != null); if (st.Datatype.Variety == XmlSchemaDatatypeVariety.Union) { - string value = GetDefaultValue(sa); - foreach (XmlSchemaSimpleType mt in ((XmlSchemaSimpleTypeUnion)st.Content).BaseMemberTypes) + string? value = GetDefaultValue(sa); + Debug.Assert(st.Content != null); + foreach (XmlSchemaSimpleType mt in ((XmlSchemaSimpleTypeUnion)st.Content).BaseMemberTypes!) { - object typedValue = null; + object? typedValue = null; try { + Debug.Assert(mt.Datatype != null); + Debug.Assert(value != null); typedValue = mt.Datatype.ParseValue(value, schemas.NameTable, namespaceManager); } catch (XmlSchemaException) @@ -117,30 +123,32 @@ private XmlSchemaInfo GetDefaultAttributeSchemaInfo(XmlSchemaAttribute sa) return si; } - private string GetDefaultValue(XmlSchemaAttribute sa) + private string? GetDefaultValue(XmlSchemaAttribute sa) { - XmlQualifiedName name = sa.RefName; + XmlSchemaAttribute? saCopy = sa; + XmlQualifiedName name = saCopy.RefName; if (!name.IsEmpty) { - sa = schemas.GlobalAttributes[name] as XmlSchemaAttribute; - if (sa == null) return null; + saCopy = schemas.GlobalAttributes[name] as XmlSchemaAttribute; + if (saCopy == null) return null; } - string s = sa.FixedValue; + string? s = saCopy.FixedValue; if (s != null) return s; - return sa.DefaultValue; + return saCopy.DefaultValue; } - private string GetDefaultValue(XmlSchemaElement se) + private string? GetDefaultValue(XmlSchemaElement se) { - XmlQualifiedName name = se.RefName; + XmlSchemaElement? seCopy = se; + XmlQualifiedName name = seCopy.RefName; if (!name.IsEmpty) { - se = schemas.GlobalElements[name] as XmlSchemaElement; - if (se == null) return null; + seCopy = schemas.GlobalElements[name] as XmlSchemaElement; + if (seCopy == null) return null; } - string s = se.FixedValue; + string? s = seCopy.FixedValue; if (s != null) return s; - return se.DefaultValue; + return seCopy.DefaultValue; } private void ReplaceSchemaInfo(XObject o, XmlSchemaInfo schemaInfo) @@ -149,7 +157,7 @@ private void ReplaceSchemaInfo(XObject o, XmlSchemaInfo schemaInfo) { schemaInfos = new Dictionary(new XmlSchemaInfoEqualityComparer()); } - XmlSchemaInfo si = o.Annotation(); + XmlSchemaInfo? si = o.Annotation(); if (si != null) { if (!schemaInfos.ContainsKey(si)) @@ -166,16 +174,16 @@ private void ReplaceSchemaInfo(XObject o, XmlSchemaInfo schemaInfo) o.AddAnnotation(si); } - private void PushAncestorsAndSelf(XElement e) + private void PushAncestorsAndSelf(XElement? e) { while (e != null) { - XAttribute a = e.lastAttr; + XAttribute? a = e.lastAttr; if (a != null) { do { - a = a.next; + a = a.next!; if (a.IsNamespaceDeclaration) { string localName = a.Name.LocalName; @@ -183,7 +191,7 @@ private void PushAncestorsAndSelf(XElement e) { localName = string.Empty; } - if (!namespaceManager.HasNamespace(localName)) + if (!namespaceManager!.HasNamespace(localName)) { namespaceManager.AddNamespace(localName, a.Value); } @@ -194,15 +202,15 @@ private void PushAncestorsAndSelf(XElement e) } } - private void PushElement(XElement e, ref string xsiType, ref string xsiNil) + private void PushElement(XElement e, ref string? xsiType, ref string? xsiNil) { - namespaceManager.PushScope(); - XAttribute a = e.lastAttr; + namespaceManager!.PushScope(); + XAttribute? a = e.lastAttr; if (a != null) { do { - a = a.next; + a = a.next!; if (a.IsNamespaceDeclaration) { string localName = a.Name.LocalName; @@ -228,41 +236,41 @@ private void PushElement(XElement e, ref string xsiType, ref string xsiNil) } } - private IXmlLineInfo SaveLineInfo(XObject source) + private IXmlLineInfo SaveLineInfo(XObject? source) { - IXmlLineInfo previousLineInfo = validator.LineInfoProvider; + IXmlLineInfo previousLineInfo = validator!.LineInfoProvider; validator.LineInfoProvider = source as IXmlLineInfo; return previousLineInfo; } private void RestoreLineInfo(IXmlLineInfo originalLineInfo) { - validator.LineInfoProvider = originalLineInfo; + validator!.LineInfoProvider = originalLineInfo; } private void ValidateAttribute(XAttribute a) { IXmlLineInfo original = SaveLineInfo(a); - XmlSchemaInfo si = addSchemaInfo ? new XmlSchemaInfo() : null; + XmlSchemaInfo? si = addSchemaInfo ? new XmlSchemaInfo() : null; source = a; - validator.ValidateAttribute(a.Name.LocalName, a.Name.NamespaceName, a.Value, si); + validator!.ValidateAttribute(a.Name.LocalName, a.Name.NamespaceName, a.Value, si); if (addSchemaInfo) { - ReplaceSchemaInfo(a, si); + ReplaceSchemaInfo(a, si!); } RestoreLineInfo(original); } private void ValidateAttributes(XElement e) { - XAttribute a = e.lastAttr; + XAttribute? a = e.lastAttr; IXmlLineInfo orginal = SaveLineInfo(a); if (a != null) { do { - a = a.next; + a = a.next!; if (!a.IsNamespaceDeclaration) { ValidateAttribute(a); @@ -280,10 +288,10 @@ private void ValidateAttributes(XElement e) { defaultAttributes.Clear(); } - validator.GetUnspecifiedDefaultAttributes(defaultAttributes); + validator!.GetUnspecifiedDefaultAttributes(defaultAttributes); foreach (XmlSchemaAttribute sa in defaultAttributes) { - a = new XAttribute(XNamespace.Get(sa.QualifiedName.Namespace).GetName(sa.QualifiedName.Name), GetDefaultValue(sa)); + a = new XAttribute(XNamespace.Get(sa.QualifiedName.Namespace).GetName(sa.QualifiedName.Name), GetDefaultValue(sa)!); ReplaceSchemaInfo(a, GetDefaultAttributeSchemaInfo(sa)); e.Add(a); } @@ -293,52 +301,53 @@ private void ValidateAttributes(XElement e) private void ValidateElement(XElement e) { - XmlSchemaInfo si = addSchemaInfo ? new XmlSchemaInfo() : null; - string xsiType = null; - string xsiNil = null; + XmlSchemaInfo? si = addSchemaInfo ? new XmlSchemaInfo() : null; + string? xsiType = null; + string? xsiNil = null; PushElement(e, ref xsiType, ref xsiNil); IXmlLineInfo original = SaveLineInfo(e); source = e; - validator.ValidateElement(e.Name.LocalName, e.Name.NamespaceName, si, xsiType, xsiNil, null, null); + validator!.ValidateElement(e.Name.LocalName, e.Name.NamespaceName, si, xsiType, xsiNil, null, null); ValidateAttributes(e); validator.ValidateEndOfAttributes(si); ValidateNodes(e); validator.ValidateEndElement(si); if (addSchemaInfo) { - if (si.Validity == XmlSchemaValidity.Valid && si.IsDefault) + if (si!.Validity == XmlSchemaValidity.Valid && si.IsDefault) { - e.Value = GetDefaultValue(si.SchemaElement); + Debug.Assert(si.SchemaElement != null); + e.Value = GetDefaultValue(si.SchemaElement)!; } ReplaceSchemaInfo(e, si); } RestoreLineInfo(original); - namespaceManager.PopScope(); + namespaceManager!.PopScope(); } private void ValidateNodes(XElement e) { - XNode n = e.content as XNode; + XNode? n = e.content as XNode; IXmlLineInfo orginal = SaveLineInfo(n); if (n != null) { do { - n = n.next; - XElement c = n as XElement; + n = n.next!; + XElement? c = n as XElement; if (c != null) { ValidateElement(c); } else { - XText t = n as XText; + XText? t = n as XText; if (t != null) { string s = t.Value; if (s.Length > 0) { - validator.LineInfoProvider = t as IXmlLineInfo; + validator!.LineInfoProvider = t as IXmlLineInfo; validator.ValidateText(s); } } @@ -348,16 +357,16 @@ private void ValidateNodes(XElement e) } else { - string s = e.content as string; + string? s = e.content as string; if (s != null && s.Length > 0) { - validator.ValidateText(s); + validator!.ValidateText(s); } } RestoreLineInfo(orginal); } - private void ValidationCallback(object sender, ValidationEventArgs e) + private void ValidationCallback(object? sender, ValidationEventArgs e) { if (validationEventHandler != null) { @@ -372,21 +381,21 @@ private void ValidationCallback(object sender, ValidationEventArgs e) internal class XmlSchemaInfoEqualityComparer : IEqualityComparer { - public bool Equals(XmlSchemaInfo si1, XmlSchemaInfo si2) + public bool Equals(XmlSchemaInfo? si1, XmlSchemaInfo? si2) { if (si1 == si2) return true; if (si1 == null || si2 == null) return false; return si1.ContentType == si2.ContentType && si1.IsDefault == si2.IsDefault && si1.IsNil == si2.IsNil && - (object)si1.MemberType == (object)si2.MemberType && - (object)si1.SchemaAttribute == (object)si2.SchemaAttribute && - (object)si1.SchemaElement == (object)si2.SchemaElement && - (object)si1.SchemaType == (object)si2.SchemaType && + (object?)si1.MemberType == (object?)si2.MemberType && + (object?)si1.SchemaAttribute == (object?)si2.SchemaAttribute && + (object?)si1.SchemaElement == (object?)si2.SchemaElement && + (object?)si1.SchemaType == (object?)si2.SchemaType && si1.Validity == si2.Validity; } - public int GetHashCode(XmlSchemaInfo si) + public int GetHashCode(XmlSchemaInfo? si) { if (si == null) return 0; int h = (int)si.ContentType; @@ -398,22 +407,22 @@ public int GetHashCode(XmlSchemaInfo si) { h ^= 1; } - XmlSchemaSimpleType memberType = si.MemberType; + XmlSchemaSimpleType? memberType = si.MemberType; if (memberType != null) { h ^= memberType.GetHashCode(); } - XmlSchemaAttribute schemaAttribute = si.SchemaAttribute; + XmlSchemaAttribute? schemaAttribute = si.SchemaAttribute; if (schemaAttribute != null) { h ^= schemaAttribute.GetHashCode(); } - XmlSchemaElement schemaElement = si.SchemaElement; + XmlSchemaElement? schemaElement = si.SchemaElement; if (schemaElement != null) { h ^= schemaElement.GetHashCode(); } - XmlSchemaType schemaType = si.SchemaType; + XmlSchemaType? schemaType = si.SchemaType; if (schemaType != null) { h ^= schemaType.GetHashCode(); @@ -432,7 +441,7 @@ public static class Extensions /// Gets the schema information that has been assigned to the as a result of schema validation. /// /// Extension point - public static IXmlSchemaInfo GetSchemaInfo(this XElement source) + public static IXmlSchemaInfo? GetSchemaInfo(this XElement source) { if (source == null) throw new ArgumentNullException(nameof(source)); return source.Annotation(); @@ -442,7 +451,7 @@ public static IXmlSchemaInfo GetSchemaInfo(this XElement source) /// Gets the schema information that has been assigned to the as a result of schema validation. /// /// Extension point - public static IXmlSchemaInfo GetSchemaInfo(this XAttribute source) + public static IXmlSchemaInfo? GetSchemaInfo(this XAttribute source) { if (source == null) throw new ArgumentNullException(nameof(source)); return source.Annotation(); @@ -456,7 +465,7 @@ public static IXmlSchemaInfo GetSchemaInfo(this XAttribute source) /// The /// that receives schema validation warnings and errors encountered during schema /// validation - public static void Validate(this XDocument source, XmlSchemaSet schemas, ValidationEventHandler validationEventHandler) + public static void Validate(this XDocument source, XmlSchemaSet schemas, ValidationEventHandler? validationEventHandler) { source.Validate(schemas, validationEventHandler, false); } @@ -472,7 +481,7 @@ public static void Validate(this XDocument source, XmlSchemaSet schemas, Validat /// If enabled the and the corresponding /// subtree is augmented with PSVI in the form of annotations, /// default attributes and default element values - public static void Validate(this XDocument source, XmlSchemaSet schemas, ValidationEventHandler validationEventHandler, bool addSchemaInfo) + public static void Validate(this XDocument source, XmlSchemaSet schemas, ValidationEventHandler? validationEventHandler, bool addSchemaInfo) { if (source == null) throw new ArgumentNullException(nameof(source)); if (schemas == null) throw new ArgumentNullException(nameof(schemas)); @@ -490,7 +499,7 @@ public static void Validate(this XDocument source, XmlSchemaSet schemas, Validat /// The that /// receives schema validation warnings and errors encountered during schema /// validation - public static void Validate(this XElement source, XmlSchemaObject partialValidationType, XmlSchemaSet schemas, ValidationEventHandler validationEventHandler) + public static void Validate(this XElement source, XmlSchemaObject partialValidationType, XmlSchemaSet schemas, ValidationEventHandler? validationEventHandler) { source.Validate(partialValidationType, schemas, validationEventHandler, false); } @@ -509,7 +518,7 @@ public static void Validate(this XElement source, XmlSchemaObject partialValidat /// If enabled the and the corresponding /// subtree is augmented with PSVI in the form of annotations, /// default attributes and default element values - public static void Validate(this XElement source, XmlSchemaObject partialValidationType, XmlSchemaSet schemas, ValidationEventHandler validationEventHandler, bool addSchemaInfo) + public static void Validate(this XElement source, XmlSchemaObject partialValidationType, XmlSchemaSet schemas, ValidationEventHandler? validationEventHandler, bool addSchemaInfo) { if (source == null) throw new ArgumentNullException(nameof(source)); if (partialValidationType == null) throw new ArgumentNullException(nameof(partialValidationType)); @@ -528,7 +537,7 @@ public static void Validate(this XElement source, XmlSchemaObject partialValidat /// The that /// receives schema validation warnings and errors encountered during schema /// validation - public static void Validate(this XAttribute source, XmlSchemaObject partialValidationType, XmlSchemaSet schemas, ValidationEventHandler validationEventHandler) + public static void Validate(this XAttribute source, XmlSchemaObject partialValidationType, XmlSchemaSet schemas, ValidationEventHandler? validationEventHandler) { source.Validate(partialValidationType, schemas, validationEventHandler, false); } @@ -547,7 +556,7 @@ public static void Validate(this XAttribute source, XmlSchemaObject partialValid /// If enabled the is augmented with PSVI /// in the form of annotations, default attributes and /// default element values - public static void Validate(this XAttribute source, XmlSchemaObject partialValidationType, XmlSchemaSet schemas, ValidationEventHandler validationEventHandler, bool addSchemaInfo) + public static void Validate(this XAttribute source, XmlSchemaObject partialValidationType, XmlSchemaSet schemas, ValidationEventHandler? validationEventHandler, bool addSchemaInfo) { if (source == null) throw new ArgumentNullException(nameof(source)); if (partialValidationType == null) throw new ArgumentNullException(nameof(partialValidationType)); diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/XPath/XNodeNavigator.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/XPath/XNodeNavigator.cs index 614769bb567122..c301348cda7cb7 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/XPath/XNodeNavigator.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/XPath/XNodeNavigator.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Collections.Generic; +using System.Diagnostics; using System.Linq; using System.Xml.Linq; @@ -36,17 +37,17 @@ internal class XNodeNavigator : XPathNavigator, IXmlLineInfo (1 << (int)XmlNodeType.CDATA) | (1 << (int)XmlNodeType.Text); - private static XAttribute s_XmlNamespaceDeclaration; + private static XAttribute? s_XmlNamespaceDeclaration; // The navigator position is encoded by the tuple (source, parent). // Namespace declaration uses (instance, parent element). // Common XObjects uses (instance, null). private XObject _source; - private XElement _parent; + private XElement? _parent; private readonly XmlNameTable _nameTable; - public XNodeNavigator(XNode node, XmlNameTable nameTable) + public XNodeNavigator(XNode node, XmlNameTable? nameTable) { _source = node; _nameTable = nameTable != null ? nameTable : CreateNameTable(); @@ -79,7 +80,7 @@ public override bool HasAttributes { get { - XElement element = _source as XElement; + XElement? element = _source as XElement; if (element != null) { foreach (XAttribute attribute in element.Attributes()) @@ -98,7 +99,7 @@ public override bool HasChildren { get { - XContainer container = _source as XContainer; + XContainer? container = _source as XContainer; if (container != null) { foreach (XNode node in container.Nodes()) @@ -117,7 +118,7 @@ public override bool IsEmptyElement { get { - XElement e = _source as XElement; + XElement? e = _source as XElement; return e != null && e.IsEmpty; } } @@ -129,12 +130,12 @@ public override string LocalName private string GetLocalName() { - XElement e = _source as XElement; + XElement? e = _source as XElement; if (e != null) { return e.Name.LocalName; } - XAttribute a = _source as XAttribute; + XAttribute? a = _source as XAttribute; if (a != null) { if (_parent != null && a.Name.NamespaceName.Length == 0) @@ -143,7 +144,7 @@ private string GetLocalName() } return a.Name.LocalName; } - XProcessingInstruction p = _source as XProcessingInstruction; + XProcessingInstruction? p = _source as XProcessingInstruction; if (p != null) { return p.Target; @@ -171,12 +172,12 @@ public override string NamespaceURI private string GetNamespaceURI() { - XElement e = _source as XElement; + XElement? e = _source as XElement; if (e != null) { return e.Name.NamespaceName; } - XAttribute a = _source as XAttribute; + XAttribute? a = _source as XAttribute; if (a != null) { if (_parent != null) @@ -227,24 +228,24 @@ public override string Prefix private string GetPrefix() { - XElement e = _source as XElement; + XElement? e = _source as XElement; if (e != null) { - string prefix = e.GetPrefixOfNamespace(e.Name.Namespace); + string? prefix = e.GetPrefixOfNamespace(e.Name.Namespace); if (prefix != null) { return prefix; } return string.Empty; } - XAttribute a = _source as XAttribute; + XAttribute? a = _source as XAttribute; if (a != null) { if (_parent != null) { return string.Empty; // backcompat } - string prefix = a.GetPrefixOfNamespace(a.Name.Namespace); + string? prefix = a.GetPrefixOfNamespace(a.Name.Namespace); if (prefix != null) { return prefix; @@ -274,7 +275,7 @@ public override string Value case XmlNodeType.Attribute: return ((XAttribute)_source).Value; case XmlNodeType.Document: - XElement root = ((XDocument)_source).Root; + XElement? root = ((XDocument)_source).Root; return root != null ? root.Value : string.Empty; case XmlNodeType.Text: case XmlNodeType.CDATA: @@ -298,7 +299,7 @@ public override XPathNavigator Clone() public override bool IsSamePosition(XPathNavigator navigator) { - XNodeNavigator other = navigator as XNodeNavigator; + XNodeNavigator? other = navigator as XNodeNavigator; if (other == null) { return false; @@ -308,7 +309,7 @@ public override bool IsSamePosition(XPathNavigator navigator) public override bool MoveTo(XPathNavigator navigator) { - XNodeNavigator other = navigator as XNodeNavigator; + XNodeNavigator? other = navigator as XNodeNavigator; if (other != null) { _source = other._source; @@ -320,7 +321,7 @@ public override bool MoveTo(XPathNavigator navigator) public override bool MoveToAttribute(string localName, string namespaceName) { - XElement e = _source as XElement; + XElement? e = _source as XElement; if (e != null) { foreach (XAttribute attribute in e.Attributes()) @@ -339,7 +340,7 @@ public override bool MoveToAttribute(string localName, string namespaceName) public override bool MoveToChild(string localName, string namespaceName) { - XContainer c = _source as XContainer; + XContainer? c = _source as XContainer; if (c != null) { foreach (XElement element in c.Elements()) @@ -357,7 +358,7 @@ public override bool MoveToChild(string localName, string namespaceName) public override bool MoveToChild(XPathNodeType type) { - XContainer c = _source as XContainer; + XContainer? c = _source as XContainer; if (c != null) { int mask = GetElementContentMask(type); @@ -379,7 +380,7 @@ public override bool MoveToChild(XPathNodeType type) public override bool MoveToFirstAttribute() { - XElement e = _source as XElement; + XElement? e = _source as XElement; if (e != null) { foreach (XAttribute attribute in e.Attributes()) @@ -396,7 +397,7 @@ public override bool MoveToFirstAttribute() public override bool MoveToFirstChild() { - XContainer container = _source as XContainer; + XContainer? container = _source as XContainer; if (container != null) { foreach (XNode node in container.Nodes()) @@ -413,10 +414,10 @@ public override bool MoveToFirstChild() public override bool MoveToFirstNamespace(XPathNamespaceScope scope) { - XElement e = _source as XElement; + XElement? e = _source as XElement; if (e != null) { - XAttribute a = null; + XAttribute? a = null; switch (scope) { case XPathNamespaceScope.Local: @@ -454,18 +455,19 @@ public override bool MoveToId(string id) public override bool MoveToNamespace(string localName) { - XElement e = _source as XElement; + XElement? e = _source as XElement; if (e != null) { if (localName == "xmlns") { return false; // backcompat } + // TODO-NULLABLE: Unnecessary null check? if (localName != null && localName.Length == 0) { localName = "xmlns"; // backcompat } - XAttribute a = GetFirstNamespaceDeclarationGlobal(e); + XAttribute? a = GetFirstNamespaceDeclarationGlobal(e); while (a != null) { if (a.Name.LocalName == localName) @@ -488,13 +490,13 @@ public override bool MoveToNamespace(string localName) public override bool MoveToNext() { - XNode currentNode = _source as XNode; + XNode? currentNode = _source as XNode; if (currentNode != null) { - XContainer container = currentNode.GetParent(); + XContainer? container = currentNode.GetParent(); if (container != null) { - XNode next = null; + XNode? next = null; for (XNode node = currentNode; node != null; node = next) { next = node.NextNode; @@ -515,7 +517,7 @@ public override bool MoveToNext() public override bool MoveToNext(string localName, string namespaceName) { - XNode currentNode = _source as XNode; + XNode? currentNode = _source as XNode; if (currentNode != null) { foreach (XElement element in currentNode.ElementsAfterSelf()) @@ -533,10 +535,10 @@ public override bool MoveToNext(string localName, string namespaceName) public override bool MoveToNext(XPathNodeType type) { - XNode currentNode = _source as XNode; + XNode? currentNode = _source as XNode; if (currentNode != null) { - XContainer container = currentNode.GetParent(); + XContainer? container = currentNode.GetParent(); if (container != null) { int mask = GetElementContentMask(type); @@ -544,7 +546,7 @@ public override bool MoveToNext(XPathNodeType type) { mask &= ~TextMask; } - XNode next = null; + XNode? next = null; for (XNode node = currentNode; ; node = next) { next = node.NextNode; @@ -565,13 +567,13 @@ public override bool MoveToNext(XPathNodeType type) public override bool MoveToNextAttribute() { - XAttribute currentAttribute = _source as XAttribute; + XAttribute? currentAttribute = _source as XAttribute; if (currentAttribute != null && _parent == null) { - XElement e = (XElement)currentAttribute.GetParent(); + XElement? e = (XElement?)currentAttribute.GetParent(); if (e != null) { - for (XAttribute attribute = currentAttribute.NextAttribute; attribute != null; attribute = attribute.NextAttribute) + for (XAttribute? attribute = currentAttribute.NextAttribute; attribute != null; attribute = attribute.NextAttribute) { if (!attribute.IsNamespaceDeclaration) { @@ -586,7 +588,7 @@ public override bool MoveToNextAttribute() public override bool MoveToNextNamespace(XPathNamespaceScope scope) { - XAttribute a = _source as XAttribute; + XAttribute? a = _source as XAttribute; if (a != null && _parent != null && !IsXmlNamespaceDeclaration(a)) { switch (scope) @@ -636,7 +638,7 @@ public override bool MoveToParent() _parent = null; return true; } - XNode parentNode = _source.GetParent(); + XNode? parentNode = _source.GetParent(); if (parentNode != null) { _source = parentNode; @@ -647,13 +649,13 @@ public override bool MoveToParent() public override bool MoveToPrevious() { - XNode currentNode = _source as XNode; + XNode? currentNode = _source as XNode; if (currentNode != null) { - XContainer container = currentNode.GetParent(); + XContainer? container = currentNode.GetParent(); if (container != null) { - XNode previous = null; + XNode? previous = null; foreach (XNode node in container.Nodes()) { if (node == currentNode) @@ -678,7 +680,7 @@ public override bool MoveToPrevious() public override XmlReader ReadSubtree() { - XContainer c = _source as XContainer; + XContainer? c = _source as XContainer; if (c == null) throw new InvalidOperationException(SR.Format(SR.InvalidOperation_BadNodeType, NodeType)); return c.CreateReader(); } @@ -726,7 +728,7 @@ private static string CollectText(XText n) { foreach (XNode node in n.NodesAfterSelf()) { - XText t = node as XText; + XText? t = node as XText; if (t == null) break; s += t.Value; } @@ -767,21 +769,22 @@ private static int GetElementContentMask(XPathNodeType type) return s_ElementContentMasks[(int)type]; } - private static XAttribute GetFirstNamespaceDeclarationGlobal(XElement e) + private static XAttribute? GetFirstNamespaceDeclarationGlobal(XElement e) { + XElement? ce = e; do { - XAttribute a = GetFirstNamespaceDeclarationLocal(e); + XAttribute? a = GetFirstNamespaceDeclarationLocal(ce); if (a != null) { return a; } - e = e.Parent; - } while (e != null); + ce = ce.Parent; + } while (ce != null); return null; } - private static XAttribute GetFirstNamespaceDeclarationLocal(XElement e) + private static XAttribute? GetFirstNamespaceDeclarationLocal(XElement e) { foreach (XAttribute attribute in e.Attributes()) { @@ -793,14 +796,14 @@ private static XAttribute GetFirstNamespaceDeclarationLocal(XElement e) return null; } - private static XAttribute GetNextNamespaceDeclarationGlobal(XAttribute a) + private static XAttribute? GetNextNamespaceDeclarationGlobal(XAttribute a) { - XElement e = (XElement)a.GetParent(); + XElement? e = (XElement?)a.GetParent(); if (e == null) { return null; } - XAttribute next = GetNextNamespaceDeclarationLocal(a); + XAttribute? next = GetNextNamespaceDeclarationLocal(a); if (next != null) { return next; @@ -813,21 +816,22 @@ private static XAttribute GetNextNamespaceDeclarationGlobal(XAttribute a) return GetFirstNamespaceDeclarationGlobal(e); } - private static XAttribute GetNextNamespaceDeclarationLocal(XAttribute a) + private static XAttribute? GetNextNamespaceDeclarationLocal(XAttribute a) { - XElement e = a.Parent; + XElement? e = a.Parent; if (e == null) { return null; } - a = a.NextAttribute; - while (a != null) + XAttribute? ca = a; + ca = ca.NextAttribute; + while (ca != null) { - if (a.IsNamespaceDeclaration) + if (ca.IsNamespaceDeclaration) { - return a; + return ca; } - a = a.NextAttribute; + ca = ca.NextAttribute; } return null; } @@ -844,13 +848,14 @@ private static XAttribute GetXmlNamespaceDeclaration() private static bool HasNamespaceDeclarationInScope(XAttribute a, XElement e) { XName name = a.Name; - while (e != null && e != a.GetParent()) + XElement? ce = e; + while (ce != null && ce != a.GetParent()) { - if (e.Attribute(name) != null) + if (ce.Attribute(name) != null) { return true; } - e = e.Parent; + ce = ce.Parent; } return false; } @@ -858,11 +863,11 @@ private static bool HasNamespaceDeclarationInScope(XAttribute a, XElement e) internal readonly struct XPathEvaluator { - public object Evaluate(XNode node, string expression, IXmlNamespaceResolver resolver) where T : class + public object Evaluate(XNode node, string expression, IXmlNamespaceResolver? resolver) where T : class { XPathNavigator navigator = node.CreateNavigator(); object result = navigator.Evaluate(expression, resolver); - XPathNodeIterator iterator = result as XPathNodeIterator; + XPathNodeIterator? iterator = result as XPathNodeIterator; if (iterator != null) { return EvaluateIterator(iterator); @@ -875,10 +880,11 @@ private IEnumerable EvaluateIterator(XPathNodeIterator result) { foreach (XPathNavigator navigator in result) { + Debug.Assert(navigator.UnderlyingObject != null); object r = navigator.UnderlyingObject; if (!(r is T)) throw new InvalidOperationException(SR.Format(SR.InvalidOperation_UnexpectedEvaluation, r.GetType())); yield return (T)r; - XText t = r as XText; + XText? t = r as XText; if (t != null && t.GetParent() != null) { do @@ -886,7 +892,7 @@ private IEnumerable EvaluateIterator(XPathNodeIterator result) t = t.NextNode as XText; if (t == null) break; yield return (T)(object)t; - } while (t != t.GetParent().LastNode); + } while (t != t.GetParent()!.LastNode); } } } @@ -914,11 +920,11 @@ public static XPathNavigator CreateNavigator(this XNode node) /// The to be used by /// the /// An - public static XPathNavigator CreateNavigator(this XNode node, XmlNameTable nameTable) + public static XPathNavigator CreateNavigator(this XNode node, XmlNameTable? nameTable) { if (node == null) throw new ArgumentNullException(nameof(node)); if (node is XDocumentType) throw new ArgumentException(SR.Format(SR.Argument_CreateNavigator, XmlNodeType.DocumentType)); - XText text = node as XText; + XText? text = node as XText; if (text != null) { if (text.GetParent() is XDocument) throw new ArgumentException(SR.Format(SR.Argument_CreateNavigator, XmlNodeType.Whitespace)); @@ -948,7 +954,7 @@ public static object XPathEvaluate(this XNode node, string expression) /// prefixes used in the XPath expression /// The result of evaluating the expression which can be typed as bool, double, string or /// IEnumerable - public static object XPathEvaluate(this XNode node, string expression, IXmlNamespaceResolver resolver) + public static object XPathEvaluate(this XNode node, string expression, IXmlNamespaceResolver? resolver) { if (node == null) throw new ArgumentNullException(nameof(node)); return default(XPathEvaluator).Evaluate(node, expression, resolver); @@ -960,7 +966,7 @@ public static object XPathEvaluate(this XNode node, string expression, IXmlNames /// Extension point /// The XPath expression /// An or null - public static XElement XPathSelectElement(this XNode node, string expression) + public static XElement? XPathSelectElement(this XNode node, string expression) { return node.XPathSelectElement(expression, null); } @@ -973,7 +979,7 @@ public static XElement XPathSelectElement(this XNode node, string expression) /// A for the namespace /// prefixes used in the XPath expression /// An or null - public static XElement XPathSelectElement(this XNode node, string expression, IXmlNamespaceResolver resolver) + public static XElement? XPathSelectElement(this XNode node, string expression, IXmlNamespaceResolver? resolver) { return node.XPathSelectElements(expression, resolver).FirstOrDefault(); } @@ -997,7 +1003,7 @@ public static IEnumerable XPathSelectElements(this XNode node, string /// A for the namespace /// prefixes used in the XPath expression /// An corresponding to the resulting set of elements - public static IEnumerable XPathSelectElements(this XNode node, string expression, IXmlNamespaceResolver resolver) + public static IEnumerable XPathSelectElements(this XNode node, string expression, IXmlNamespaceResolver? resolver) { if (node == null) throw new ArgumentNullException(nameof(node)); return (IEnumerable)default(XPathEvaluator).Evaluate(node, expression, resolver); @@ -1005,18 +1011,18 @@ public static IEnumerable XPathSelectElements(this XNode node, string private static XText CalibrateText(XText n) { - XContainer parentNode = n.GetParent(); + XContainer? parentNode = n.GetParent(); if (parentNode == null) { return n; } foreach (XNode node in parentNode.Nodes()) { - XText t = node as XText; + XText? t = node as XText; bool isTextNode = t != null; if (isTextNode && node == n) { - return t; + return t!; } } diff --git a/src/libraries/System.Private.Xml.Linq/src/System/Xml/XPath/XObjectExtensions.cs b/src/libraries/System.Private.Xml.Linq/src/System/Xml/XPath/XObjectExtensions.cs index d32860ffd11943..829b2e34af5990 100644 --- a/src/libraries/System.Private.Xml.Linq/src/System/Xml/XPath/XObjectExtensions.cs +++ b/src/libraries/System.Private.Xml.Linq/src/System/Xml/XPath/XObjectExtensions.cs @@ -7,9 +7,9 @@ namespace System.Xml.XPath { internal static class XObjectExtensions { - public static XContainer GetParent(this XObject obj) + public static XContainer? GetParent(this XObject obj) { - XContainer ret = obj.Parent; + XContainer? ret = obj.Parent; if (ret == null) { ret = obj.Document; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigator.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigator.cs index 02baf072f2a2c0..288f8d5212386b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigator.cs @@ -1186,7 +1186,7 @@ public virtual XPathNodeIterator Select(string xpath) return this.Select(XPathExpression.Compile(xpath)); } - public virtual XPathNodeIterator Select(string xpath, IXmlNamespaceResolver resolver) + public virtual XPathNodeIterator Select(string xpath, IXmlNamespaceResolver? resolver) { return this.Select(XPathExpression.Compile(xpath, resolver)); } @@ -1206,7 +1206,7 @@ public virtual object Evaluate(string xpath) return Evaluate(XPathExpression.Compile(xpath), null); } - public virtual object Evaluate(string xpath, IXmlNamespaceResolver resolver) + public virtual object Evaluate(string xpath, IXmlNamespaceResolver? resolver) { return this.Evaluate(XPathExpression.Compile(xpath, resolver)); } From 44390bcfa3f9d1df94ef9bdbb36dc3aa91439c7e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20Cant=C3=BA?= Date: Wed, 19 Aug 2020 22:41:41 -0700 Subject: [PATCH 02/14] Enable nullability on System.Xml.XPath (#41060) * Enable nullability on System.Xml.XPath * Switch XPathException ctor's message parameter to string? --- .../src/System/Xml/XPath/XPathException.cs | 12 ++++++------ .../System.Xml.XPath/ref/System.Xml.XPath.cs | 4 ++-- .../System.Xml.XPath/ref/System.Xml.XPath.csproj | 1 + .../System.Xml.XPath/src/System.Xml.XPath.csproj | 1 + 4 files changed, 10 insertions(+), 8 deletions(-) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathException.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathException.cs index 017f4044d61351..af0c9d0bf35e42 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathException.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathException.cs @@ -17,7 +17,7 @@ public class XPathException : SystemException { // we need to keep this members for V1 serialization compatibility private readonly string _res; - private readonly string[]? _args; + private readonly string?[]? _args; // message != null for V1 & V2 exceptions deserialized in Whidbey // message == null for created V2 exceptions; the exception message is stored in Exception._message @@ -60,10 +60,10 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont public XPathException() : this(string.Empty, (Exception?)null) { } - public XPathException(string message) : this(message, (Exception?)null) { } + public XPathException(string? message) : this(message, (Exception?)null) { } - public XPathException(string message, Exception? innerException) : - this(SR.Xml_UserException, new string[] { message }, innerException) + public XPathException(string? message, Exception? innerException) : + this(SR.Xml_UserException, new string?[] { message }, innerException) { } @@ -92,7 +92,7 @@ private XPathException(string res, string[]? args) : { } - private XPathException(string res, string[]? args, Exception? inner) : + private XPathException(string res, string?[]? args, Exception? inner) : base(CreateMessage(res, args), inner) { HResult = HResults.XmlXPath; @@ -100,7 +100,7 @@ private XPathException(string res, string[]? args, Exception? inner) : _args = args; } - private static string CreateMessage(string res, string[]? args) + private static string CreateMessage(string res, string?[]? args) { try { diff --git a/src/libraries/System.Xml.XPath/ref/System.Xml.XPath.cs b/src/libraries/System.Xml.XPath/ref/System.Xml.XPath.cs index a13b69f5630990..05b896d6f87d54 100644 --- a/src/libraries/System.Xml.XPath/ref/System.Xml.XPath.cs +++ b/src/libraries/System.Xml.XPath/ref/System.Xml.XPath.cs @@ -20,8 +20,8 @@ public partial class XPathException : System.SystemException { public XPathException() { } protected XPathException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } - public XPathException(string message) { } - public XPathException(string message, System.Exception innerException) { } + public XPathException(string? message) { } + public XPathException(string? message, System.Exception? innerException) { } public override string Message { get { throw null; } } public override void GetObjectData(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { } } diff --git a/src/libraries/System.Xml.XPath/ref/System.Xml.XPath.csproj b/src/libraries/System.Xml.XPath/ref/System.Xml.XPath.csproj index 6dbe6ca18418af..6cbf41c40f82ba 100644 --- a/src/libraries/System.Xml.XPath/ref/System.Xml.XPath.csproj +++ b/src/libraries/System.Xml.XPath/ref/System.Xml.XPath.csproj @@ -1,6 +1,7 @@ $(NetCoreAppCurrent) + enable diff --git a/src/libraries/System.Xml.XPath/src/System.Xml.XPath.csproj b/src/libraries/System.Xml.XPath/src/System.Xml.XPath.csproj index 8159a0e77d94bd..a2a87b23e74cf8 100644 --- a/src/libraries/System.Xml.XPath/src/System.Xml.XPath.csproj +++ b/src/libraries/System.Xml.XPath/src/System.Xml.XPath.csproj @@ -2,6 +2,7 @@ true $(NetCoreAppCurrent) + enable From 1e723cef589b675b08a1dc2a17ada27984b35186 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?David=20Cant=C3=BA?= Date: Thu, 20 Aug 2020 02:56:50 -0700 Subject: [PATCH 03/14] Change nullability of public IXmlNamespaceResolver parameters where appropriate (#41079) --- .../src/System/Xml/BinaryXml/XmlBinaryReader.cs | 4 ++-- .../src/System/Xml/Core/XmlAsyncCheckReader.cs | 4 ++-- .../System.Private.Xml/src/System/Xml/Core/XmlReader.cs | 2 +- .../System.Private.Xml/src/System/Xml/Core/XmlReaderAsync.cs | 2 +- .../src/System/Xml/Core/XmlSubtreeReader.cs | 2 +- .../src/System/Xml/Core/XmlSubtreeReaderAsync.cs | 2 +- .../src/System/Xml/Core/XsdValidatingReader.cs | 2 +- .../src/System/Xml/Core/XsdValidatingReaderAsync.cs | 2 +- .../System.Private.Xml/src/System/Xml/XPath/XPathExpr.cs | 2 +- 9 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/BinaryXml/XmlBinaryReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/BinaryXml/XmlBinaryReader.cs index c7d02fafc8397c..aed2a195af520a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/BinaryXml/XmlBinaryReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/BinaryXml/XmlBinaryReader.cs @@ -1784,7 +1784,7 @@ public override object ReadContentAsObject() return base.ReadContentAsObject(); } - public override object ReadContentAs(Type returnType, IXmlNamespaceResolver namespaceResolver) + public override object ReadContentAs(Type returnType, IXmlNamespaceResolver? namespaceResolver) { int origPos = _pos; try @@ -4229,7 +4229,7 @@ private XmlValueConverter GetValueConverter(XmlTypeCode typeCode) return xsst.ValueConverter; } - private object ValueAs(BinXmlToken token, Type returnType, IXmlNamespaceResolver namespaceResolver) + private object ValueAs(BinXmlToken token, Type returnType, IXmlNamespaceResolver? namespaceResolver) { object value; CheckValueTokenBounds(); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlAsyncCheckReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlAsyncCheckReader.cs index 752e156d1a2303..97909cf5d95f83 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlAsyncCheckReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlAsyncCheckReader.cs @@ -278,7 +278,7 @@ public override string ReadContentAsString() return _coreReader.ReadContentAsString(); } - public override object ReadContentAs(Type returnType, IXmlNamespaceResolver namespaceResolver) + public override object ReadContentAs(Type returnType, IXmlNamespaceResolver? namespaceResolver) { CheckAsync(); return _coreReader.ReadContentAs(returnType, namespaceResolver); @@ -801,7 +801,7 @@ public override Task ReadContentAsStringAsync() return task; } - public override Task ReadContentAsAsync(Type returnType, IXmlNamespaceResolver namespaceResolver) + public override Task ReadContentAsAsync(Type returnType, IXmlNamespaceResolver? namespaceResolver) { CheckAsync(); var task = _coreReader.ReadContentAsAsync(returnType, namespaceResolver); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlReader.cs index 36abf85f126cf5..8c8e8a039bb5fe 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlReader.cs @@ -378,7 +378,7 @@ public virtual string ReadContentAsString() // Concatenates values of textual nodes of the current content, ignoring comments and PIs, expanding entity references, // and converts the content to the requested type. Stops at start tags and end tags. - public virtual object ReadContentAs(Type returnType, IXmlNamespaceResolver namespaceResolver) + public virtual object ReadContentAs(Type returnType, IXmlNamespaceResolver? namespaceResolver) { if (!CanReadContentAs()) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlReaderAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlReaderAsync.cs index af94b024cc21f7..e1f7f65b33ab08 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlReaderAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlReaderAsync.cs @@ -48,7 +48,7 @@ public virtual Task ReadContentAsStringAsync() // Concatenates values of textual nodes of the current content, ignoring comments and PIs, expanding entity references, // and converts the content to the requested type. Stops at start tags and end tags. - public virtual async Task ReadContentAsAsync(Type returnType, IXmlNamespaceResolver namespaceResolver) + public virtual async Task ReadContentAsAsync(Type returnType, IXmlNamespaceResolver? namespaceResolver) { if (!CanReadContentAs()) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlSubtreeReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlSubtreeReader.cs index d00bc27d68c69b..97b9bbb69efd27 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlSubtreeReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlSubtreeReader.cs @@ -799,7 +799,7 @@ public override string ReadContentAsString() } } - public override object ReadContentAs(Type returnType, IXmlNamespaceResolver namespaceResolver) + public override object ReadContentAs(Type returnType, IXmlNamespaceResolver? namespaceResolver) { try { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlSubtreeReaderAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlSubtreeReaderAsync.cs index b0d74bd4ed9fd5..b79b54ef68096e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlSubtreeReaderAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlSubtreeReaderAsync.cs @@ -214,7 +214,7 @@ public override async Task ReadContentAsStringAsync() } } - public override async Task ReadContentAsAsync(Type returnType, IXmlNamespaceResolver namespaceResolver) + public override async Task ReadContentAsAsync(Type returnType, IXmlNamespaceResolver? namespaceResolver) { try { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdValidatingReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdValidatingReader.cs index cc0b4053e85d9d..09f0615fdfadcf 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdValidatingReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdValidatingReader.cs @@ -728,7 +728,7 @@ public override string ReadContentAsString() } } - public override object ReadContentAs(Type returnType, IXmlNamespaceResolver namespaceResolver) + public override object ReadContentAs(Type returnType, IXmlNamespaceResolver? namespaceResolver) { if (!CanReadContentAs(this.NodeType)) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdValidatingReaderAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdValidatingReaderAsync.cs index cd6ccdb20bb8f2..652fdf73cbceb1 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdValidatingReaderAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdValidatingReaderAsync.cs @@ -74,7 +74,7 @@ public override async Task ReadContentAsStringAsync() } } - public override async Task ReadContentAsAsync(Type returnType, IXmlNamespaceResolver namespaceResolver) + public override async Task ReadContentAsAsync(Type returnType, IXmlNamespaceResolver? namespaceResolver) { if (!CanReadContentAs(this.NodeType)) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathExpr.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathExpr.cs index af967030af5997..f9b5e4c644914b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathExpr.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathExpr.cs @@ -51,7 +51,7 @@ internal XPathExpression() { } public abstract void SetContext(XmlNamespaceManager nsManager); - public abstract void SetContext(IXmlNamespaceResolver nsResolver); + public abstract void SetContext(IXmlNamespaceResolver? nsResolver); public abstract XPathResultType ReturnType { get; } From 631231f5d7f096ab6d9ace8723571235d6045435 Mon Sep 17 00:00:00 2001 From: Shay Rojansky Date: Fri, 21 Aug 2020 12:38:54 +0300 Subject: [PATCH 04/14] Annotate DbDataReader.GetSchemaTable as nullable (#41082) Reverts decision made in #509 --- .../System/Data/ProviderBase/DbMetaDataFactory.cs | 2 +- .../System.Data.Common/ref/System.Data.Common.cs | 10 +++++----- .../src/System/Data/Common/DBCommandBuilder.cs | 2 +- .../src/System/Data/Common/DbDataReader.cs | 13 +++++++------ .../System/Data/Common/DbDataReaderExtensions.cs | 13 ++++++++----- .../src/System/Data/IDataReader.cs | 2 +- .../System/Data/ProviderBase/DataReaderContainer.cs | 2 +- .../tests/System/Data/Common/DbDataReaderTest.cs | 2 +- .../System.Data.Odbc/ref/System.Data.Odbc.cs | 2 +- .../src/System/Data/Odbc/OdbcDataReader.cs | 10 ++-------- .../src/System/Data/Odbc/OdbcMetaDataFactory.cs | 2 +- .../System.Data.OleDb/ref/System.Data.OleDb.cs | 2 +- .../System.Data.OleDb/src/OleDbDataReader.cs | 5 +---- 13 files changed, 31 insertions(+), 36 deletions(-) diff --git a/src/libraries/Common/src/System/Data/ProviderBase/DbMetaDataFactory.cs b/src/libraries/Common/src/System/Data/ProviderBase/DbMetaDataFactory.cs index 3a12fa546dfa5c..e2727c92b6bdfa 100644 --- a/src/libraries/Common/src/System/Data/ProviderBase/DbMetaDataFactory.cs +++ b/src/libraries/Common/src/System/Data/ProviderBase/DbMetaDataFactory.cs @@ -168,7 +168,7 @@ private DataTable ExecuteCommand(DataRow requestedCollectionRow, string?[]? rest Locale = CultureInfo.InvariantCulture }; - schemaTable = reader.GetSchemaTable(); + schemaTable = reader.GetSchemaTable()!; foreach (DataRow row in schemaTable.Rows) { resultTable.Columns.Add(row["ColumnName"] as string, (Type)row["DataType"]); diff --git a/src/libraries/System.Data.Common/ref/System.Data.Common.cs b/src/libraries/System.Data.Common/ref/System.Data.Common.cs index 763f079568b2a2..d567c0290eac0f 100644 --- a/src/libraries/System.Data.Common/ref/System.Data.Common.cs +++ b/src/libraries/System.Data.Common/ref/System.Data.Common.cs @@ -863,7 +863,7 @@ public override void Close() { } public override System.Type GetProviderSpecificFieldType(int ordinal) { throw null; } public override object GetProviderSpecificValue(int ordinal) { throw null; } public override int GetProviderSpecificValues(object[] values) { throw null; } - public override System.Data.DataTable GetSchemaTable() { throw null; } + public override System.Data.DataTable? GetSchemaTable() { throw null; } public override string GetString(int ordinal) { throw null; } public override object GetValue(int ordinal) { throw null; } public override int GetValues(object[] values) { throw null; } @@ -1247,7 +1247,7 @@ public partial interface IDataReader : System.Data.IDataRecord, System.IDisposab bool IsClosed { get; } int RecordsAffected { get; } void Close(); - System.Data.DataTable GetSchemaTable(); + System.Data.DataTable? GetSchemaTable(); bool NextResult(); bool Read(); } @@ -1948,7 +1948,7 @@ protected override void Dispose(bool disposing) { } protected abstract string GetParameterName(int parameterOrdinal); protected abstract string GetParameterName(string parameterName); protected abstract string GetParameterPlaceholder(int parameterOrdinal); - protected virtual System.Data.DataTable GetSchemaTable(System.Data.Common.DbCommand sourceCommand) { throw null; } + protected virtual System.Data.DataTable? GetSchemaTable(System.Data.Common.DbCommand sourceCommand) { throw null; } public System.Data.Common.DbCommand GetUpdateCommand() { throw null; } public System.Data.Common.DbCommand GetUpdateCommand(bool useColumnsForParameterNames) { throw null; } protected virtual System.Data.Common.DbCommand InitializeCommand(System.Data.Common.DbCommand? command) { throw null; } @@ -2169,8 +2169,8 @@ protected virtual void Dispose(bool disposing) { } public virtual object GetProviderSpecificValue(int ordinal) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public virtual int GetProviderSpecificValues(object[] values) { throw null; } - public virtual System.Data.DataTable GetSchemaTable() { throw null; } - public virtual System.Threading.Tasks.Task GetSchemaTableAsync(System.Threading.CancellationToken cancellationToken = default) { throw null; } + public virtual System.Data.DataTable? GetSchemaTable() { throw null; } + public virtual System.Threading.Tasks.Task GetSchemaTableAsync(System.Threading.CancellationToken cancellationToken = default) { throw null; } public virtual System.Threading.Tasks.Task> GetColumnSchemaAsync(System.Threading.CancellationToken cancellationToken = default) { throw null; } public virtual System.IO.Stream GetStream(int ordinal) { throw null; } public abstract string GetString(int ordinal); diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DBCommandBuilder.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DBCommandBuilder.cs index 3fe1c1af3b6abd..dfc46cfcb2185b 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DBCommandBuilder.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DBCommandBuilder.cs @@ -646,7 +646,7 @@ private void BuildCache(bool closeConnection, DataRow? dataRow, bool useColumnsF ADP.BuildSchemaTableInfoTableNames(srcColumnNames); } - protected virtual DataTable GetSchemaTable(DbCommand sourceCommand) + protected virtual DataTable? GetSchemaTable(DbCommand sourceCommand) { using (IDataReader dataReader = sourceCommand.ExecuteReader(CommandBehavior.SchemaOnly | CommandBehavior.KeyInfo)) { diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DbDataReader.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DbDataReader.cs index 6e405dca65b8c0..1770e10355ab0d 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DbDataReader.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DbDataReader.cs @@ -75,12 +75,13 @@ public virtual ValueTask DisposeAsync() /// /// Returns a that describes the column metadata of the >. + /// + /// Returns if the executed command returned no resultset, or after + /// returns . /// /// A that describes the column metadata. /// The is closed. - /// The column index is out of range. - /// .NET Core only: This member is not supported. - public virtual DataTable GetSchemaTable() + public virtual DataTable? GetSchemaTable() { throw new NotSupportedException(); } @@ -97,11 +98,11 @@ public virtual DataTable GetSchemaTable() /// /// The cancellation instruction. /// A task representing the asynchronous operation. - public virtual Task GetSchemaTableAsync(CancellationToken cancellationToken = default) + public virtual Task GetSchemaTableAsync(CancellationToken cancellationToken = default) { if (cancellationToken.IsCancellationRequested) { - return Task.FromCanceled(cancellationToken); + return Task.FromCanceled(cancellationToken); } try @@ -110,7 +111,7 @@ public virtual Task GetSchemaTableAsync(CancellationToken cancellatio } catch (Exception e) { - return Task.FromException(e); + return Task.FromException(e); } } diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/DbDataReaderExtensions.cs b/src/libraries/System.Data.Common/src/System/Data/Common/DbDataReaderExtensions.cs index 8b851446d44d45..2140301f49ca86 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/DbDataReaderExtensions.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/DbDataReaderExtensions.cs @@ -73,12 +73,15 @@ public static bool CanGetColumnSchema(this DbDataReader reader) private static ReadOnlyCollection GetColumnSchemaCompatibility(DbDataReader reader) { var columnSchema = new List(); - DataTable schemaTable = reader.GetSchemaTable(); - DataColumnCollection schemaTableColumns = schemaTable.Columns; - foreach (DataRow row in schemaTable.Rows) + DataTable? schemaTable = reader.GetSchemaTable(); + if (schemaTable != null) { - Debug.Assert(row != null); - columnSchema.Add(new DataRowDbColumn(row, schemaTableColumns)); + DataColumnCollection schemaTableColumns = schemaTable.Columns; + foreach (DataRow row in schemaTable.Rows) + { + Debug.Assert(row != null); + columnSchema.Add(new DataRowDbColumn(row, schemaTableColumns)); + } } return new ReadOnlyCollection(columnSchema); } diff --git a/src/libraries/System.Data.Common/src/System/Data/IDataReader.cs b/src/libraries/System.Data.Common/src/System/Data/IDataReader.cs index 86ffd483541ad7..f1858180f19c05 100644 --- a/src/libraries/System.Data.Common/src/System/Data/IDataReader.cs +++ b/src/libraries/System.Data.Common/src/System/Data/IDataReader.cs @@ -9,7 +9,7 @@ public interface IDataReader : IDisposable, IDataRecord bool IsClosed { get; } int RecordsAffected { get; } void Close(); - DataTable GetSchemaTable(); + DataTable? GetSchemaTable(); bool NextResult(); bool Read(); } diff --git a/src/libraries/System.Data.Common/src/System/Data/ProviderBase/DataReaderContainer.cs b/src/libraries/System.Data.Common/src/System/Data/ProviderBase/DataReaderContainer.cs index cb010fc3932c46..830983f36f1f24 100644 --- a/src/libraries/System.Data.Common/src/System/Data/ProviderBase/DataReaderContainer.cs +++ b/src/libraries/System.Data.Common/src/System/Data/ProviderBase/DataReaderContainer.cs @@ -51,7 +51,7 @@ internal string GetName(int ordinal) Debug.Assert(null != fieldName, "null GetName"); return ((null != fieldName) ? fieldName : ""); } - internal DataTable GetSchemaTable() + internal DataTable? GetSchemaTable() { return _dataReader.GetSchemaTable(); } diff --git a/src/libraries/System.Data.Common/tests/System/Data/Common/DbDataReaderTest.cs b/src/libraries/System.Data.Common/tests/System/Data/Common/DbDataReaderTest.cs index 05e0d6a19b1b70..0ce087dba1d744 100644 --- a/src/libraries/System.Data.Common/tests/System/Data/Common/DbDataReaderTest.cs +++ b/src/libraries/System.Data.Common/tests/System/Data/Common/DbDataReaderTest.cs @@ -516,7 +516,7 @@ public async Task GetSchemaTableAsync_calls_GetSchemaTable() var readerTable = new DataTable(); readerTable.Columns.Add("text_col", typeof(string)); - var table = await new SchemaDbDataReaderMock(readerTable).GetSchemaTableAsync(); + var table = (await new SchemaDbDataReaderMock(readerTable).GetSchemaTableAsync())!; DataRow textColRow = table.Rows.Cast().Single()!; Assert.Equal("text_col", textColRow["ColumnName"]); diff --git a/src/libraries/System.Data.Odbc/ref/System.Data.Odbc.cs b/src/libraries/System.Data.Odbc/ref/System.Data.Odbc.cs index 65430bf1bd8a78..5a2a8319a5777f 100644 --- a/src/libraries/System.Data.Odbc/ref/System.Data.Odbc.cs +++ b/src/libraries/System.Data.Odbc/ref/System.Data.Odbc.cs @@ -187,7 +187,7 @@ protected override void Dispose(bool disposing) { } public override long GetInt64(int i) { throw null; } public override string GetName(int i) { throw null; } public override int GetOrdinal(string value) { throw null; } - public override System.Data.DataTable GetSchemaTable() { throw null; } + public override System.Data.DataTable? GetSchemaTable() { throw null; } public override string GetString(int i) { throw null; } public System.TimeSpan GetTime(int i) { throw null; } public override object GetValue(int i) { throw null; } diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcDataReader.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcDataReader.cs index 87c0e9238ab25b..496e1543d92ee4 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcDataReader.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcDataReader.cs @@ -405,12 +405,9 @@ public override string GetDataTypeName(int i) DbSchemaInfo info = _dataCache.GetSchema(i); if (info._typename == null) { - info._typename = GetColAttributeStr(i, ODBC32.SQL_DESC.TYPE_NAME, ODBC32.SQL_COLUMN.TYPE_NAME, ODBC32.HANDLER.THROW); + info._typename = GetColAttributeStr(i, ODBC32.SQL_DESC.TYPE_NAME, ODBC32.SQL_COLUMN.TYPE_NAME, ODBC32.HANDLER.THROW)!; } -// TODO-NULLABLE: Behavior change probably needed here - when there's no data type, we mostly probably need to throw instead of returning null. -#nullable disable return info._typename; -#nullable enable } throw ADP.DataReaderNoData(); } @@ -2245,7 +2242,7 @@ private DataTable NewSchemaTable() // The default values are already defined in DbSchemaRows (see DbSchemaRows.cs) so there is no need to set any default value // - public override DataTable GetSchemaTable() + public override DataTable? GetSchemaTable() { if (IsClosed) { // MDAC 68331 @@ -2253,10 +2250,7 @@ public override DataTable GetSchemaTable() } if (_noMoreResults) { -// TODO-NULLABLE: Behavior change (https://github.com/dotnet/runtime/issues/509) -#nullable disable return null; // no more results -#nullable enable } if (null != _schemaTable) { diff --git a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcMetaDataFactory.cs b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcMetaDataFactory.cs index f8eefe7edb6687..33ce321e304862 100644 --- a/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcMetaDataFactory.cs +++ b/src/libraries/System.Data.Odbc/src/System/Data/Odbc/OdbcMetaDataFactory.cs @@ -1101,7 +1101,7 @@ private DataTable NewDataTableFromReader(IDataReader reader, out object[] values { DataTable resultTable = new DataTable(tableName); resultTable.Locale = System.Globalization.CultureInfo.InvariantCulture; - DataTable schemaTable = reader.GetSchemaTable(); + DataTable schemaTable = reader.GetSchemaTable()!; foreach (DataRow row in schemaTable.Rows) { resultTable.Columns.Add(row["ColumnName"] as string, (Type)row["DataType"]); diff --git a/src/libraries/System.Data.OleDb/ref/System.Data.OleDb.cs b/src/libraries/System.Data.OleDb/ref/System.Data.OleDb.cs index fc819919b613f3..8b53b0fe651f53 100644 --- a/src/libraries/System.Data.OleDb/ref/System.Data.OleDb.cs +++ b/src/libraries/System.Data.OleDb/ref/System.Data.OleDb.cs @@ -212,7 +212,7 @@ public override void Close() { } public override long GetInt64(int ordinal) { throw null; } public override string GetName(int index) { throw null; } public override int GetOrdinal(string name) { throw null; } - public override System.Data.DataTable GetSchemaTable() { throw null; } + public override System.Data.DataTable? GetSchemaTable() { throw null; } public override string GetString(int ordinal) { throw null; } public System.TimeSpan GetTimeSpan(int ordinal) { throw null; } public override object GetValue(int ordinal) { throw null; } diff --git a/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs b/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs index cf0a8ef67023b8..98846eab53ae15 100644 --- a/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs +++ b/src/libraries/System.Data.OleDb/src/OleDbDataReader.cs @@ -252,7 +252,7 @@ private UnsafeNativeMethods.IRow IRow() return irow; } - public override DataTable GetSchemaTable() + public override DataTable? GetSchemaTable() { DataTable? schemaTable = _dbSchemaTable; if (null == schemaTable) @@ -273,10 +273,7 @@ public override DataTable GetSchemaTable() //GetSchemaTable() is defined to return null after NextResult returns false //throw ADP.DataReaderNoData(); } -// TODO-NULLABLE: Behavior change (https://github.com/dotnet/runtime/issues/509) -#nullable disable return schemaTable; -#nullable enable } internal void BuildMetaInfo() From b9f3fcc3ab7509c664a0ee82dcc5131d7f3d37ef Mon Sep 17 00:00:00 2001 From: Prashanth Govindarajan Date: Wed, 26 Aug 2020 10:29:19 -0700 Subject: [PATCH 05/14] Nullability annotations for HttpListener (#41189) * src files annotated * ref file * Address feedback --- .../Windows/HttpApi/Interop.HttpApi.cs | 38 ++--- .../ref/System.Net.HttpListener.cs | 35 ++--- .../ref/System.Net.HttpListener.csproj | 1 + .../src/System.Net.HttpListener.csproj | 4 +- .../src/System/Net/HttpListener.cs | 22 +-- .../src/System/Net/HttpListenerContext.cs | 8 +- .../src/System/Net/HttpListenerRequest.cs | 76 +++++----- .../Net/HttpListenerRequestUriBuilder.cs | 29 ++-- .../src/System/Net/HttpListenerResponse.cs | 24 ++-- .../src/System/Net/HttpRequestStream.cs | 6 +- .../src/System/Net/HttpResponseStream.cs | 4 +- .../src/System/Net/Managed/ChunkStream.cs | 2 +- .../System/Net/Managed/ChunkedInputStream.cs | 10 +- .../src/System/Net/Managed/HttpConnection.cs | 73 +++++----- .../Net/Managed/HttpEndPointListener.cs | 40 +++--- .../System/Net/Managed/HttpEndPointManager.cs | 14 +- .../Net/Managed/HttpListener.Certificates.cs | 2 +- .../Net/Managed/HttpListener.Managed.cs | 12 +- .../Managed/HttpListenerContext.Managed.cs | 11 +- .../Managed/HttpListenerRequest.Managed.cs | 36 ++--- .../Managed/HttpListenerResponse.Managed.cs | 16 +-- .../Net/Managed/HttpRequestStream.Managed.cs | 2 +- .../Net/Managed/HttpResponseStream.Managed.cs | 18 +-- .../Net/Managed/HttpStreamAsyncResult.cs | 12 +- .../Managed/ListenerAsyncResult.Managed.cs | 34 ++--- .../src/System/Net/Managed/ListenerPrefix.cs | 18 +-- .../WebSockets/HttpWebSocket.Managed.cs | 22 +-- .../src/System/Net/ServiceNameStore.cs | 24 ++-- .../HttpListenerWebSocketContext.cs | 4 +- .../System/Net/WebSockets/HttpWebSocket.cs | 10 +- .../System/Net/Windows/AsyncRequestContext.cs | 8 +- .../System/Net/Windows/CookieExtensions.cs | 16 +-- .../Net/Windows/HttpListener.Windows.cs | 131 +++++++++--------- .../Windows/HttpListenerContext.Windows.cs | 18 +-- .../Windows/HttpListenerRequest.Windows.cs | 56 ++++---- .../Net/Windows/HttpListenerRequestContext.cs | 2 +- .../Windows/HttpListenerResponse.Windows.cs | 39 +++--- .../Windows/HttpListenerSession.Windows.cs | 4 +- .../Net/Windows/HttpRequestStream.Windows.cs | 26 ++-- .../Net/Windows/HttpResponseStream.Windows.cs | 20 +-- .../Windows/HttpResponseStreamAsyncResult.cs | 20 +-- .../Windows/ListenerAsyncResult.Windows.cs | 21 +-- .../ListenerClientCertAsyncResult.Windows.cs | 18 +-- .../WebSockets/HttpWebSocket.Windows.cs | 20 +-- .../Net/Windows/WebSockets/WebSocketBase.cs | 118 ++++++++-------- .../Net/Windows/WebSockets/WebSocketBuffer.cs | 34 ++--- .../WebSocketHttpListenerDuplexStream.cs | 92 ++++++------ .../WebSockets/WebSocketProtocolComponent.cs | 30 ++-- 48 files changed, 650 insertions(+), 630 deletions(-) diff --git a/src/libraries/Common/src/Interop/Windows/HttpApi/Interop.HttpApi.cs b/src/libraries/Common/src/Interop/Windows/HttpApi/Interop.HttpApi.cs index ed6e282d0e6caf..25b03f5ddebf8a 100644 --- a/src/libraries/Common/src/Interop/Windows/HttpApi/Interop.HttpApi.cs +++ b/src/libraries/Common/src/Interop/Windows/HttpApi/Interop.HttpApi.cs @@ -536,7 +536,7 @@ protected override bool ReleaseHandle() [DllImport(Libraries.HttpApi, SetLastError = true)] internal static extern unsafe uint HttpReceiveClientCertificate(SafeHandle requestQueueHandle, ulong connectionId, uint flags, byte* pSslClientCertInfo, uint sslClientCertInfoSize, uint* pBytesReceived, NativeOverlapped* pOverlapped); - internal static readonly string[] HttpVerbs = new string[] + internal static readonly string?[] HttpVerbs = new string?[] { null, "Unknown", @@ -661,9 +661,9 @@ internal static int IndexOfKnownHeader(string headerName) } } - private static unsafe string GetKnownHeader(HTTP_REQUEST* request, long fixup, int headerIndex) + private static unsafe string? GetKnownHeader(HTTP_REQUEST* request, long fixup, int headerIndex) { - string header = null; + string? header = null; HTTP_KNOWN_HEADER* pKnownHeader = (&request->Headers.KnownHeaders) + headerIndex; @@ -683,14 +683,14 @@ private static unsafe string GetKnownHeader(HTTP_REQUEST* request, long fixup, i return header; } - internal static unsafe string GetKnownHeader(HTTP_REQUEST* request, int headerIndex) + internal static unsafe string? GetKnownHeader(HTTP_REQUEST* request, int headerIndex) { return GetKnownHeader(request, 0, headerIndex); } - private static unsafe string GetVerb(HTTP_REQUEST* request, long fixup) + private static unsafe string? GetVerb(HTTP_REQUEST* request, long fixup) { - string verb = null; + string? verb = null; if ((int)request->Verb > (int)HTTP_VERB.HttpVerbUnknown && (int)request->Verb < (int)HTTP_VERB.HttpVerbMaximum) { @@ -704,12 +704,12 @@ private static unsafe string GetVerb(HTTP_REQUEST* request, long fixup) return verb; } - internal static unsafe string GetVerb(HTTP_REQUEST* request) + internal static unsafe string? GetVerb(HTTP_REQUEST* request) { return GetVerb(request, 0); } - internal static unsafe string GetVerb(IntPtr memoryBlob, IntPtr originalAddress) + internal static unsafe string? GetVerb(IntPtr memoryBlob, IntPtr originalAddress) { return GetVerb((HTTP_REQUEST*)memoryBlob.ToPointer(), (byte*)memoryBlob - (byte*)originalAddress); } @@ -834,17 +834,17 @@ internal static unsafe HTTP_VERB GetKnownVerb(IntPtr memoryBlob, IntPtr original return verb; } - internal static unsafe IPEndPoint GetRemoteEndPoint(IntPtr memoryBlob, IntPtr originalAddress) + internal static unsafe IPEndPoint? GetRemoteEndPoint(IntPtr memoryBlob, IntPtr originalAddress) { - SocketAddress v4address = new SocketAddress(AddressFamily.InterNetwork, IPv4AddressSize); - SocketAddress v6address = new SocketAddress(AddressFamily.InterNetworkV6, IPv6AddressSize); + SocketAddress? v4address = new SocketAddress(AddressFamily.InterNetwork, IPv4AddressSize); + SocketAddress? v6address = new SocketAddress(AddressFamily.InterNetworkV6, IPv6AddressSize); byte* pMemoryBlob = (byte*)memoryBlob; HTTP_REQUEST* request = (HTTP_REQUEST*)pMemoryBlob; IntPtr address = request->Address.pRemoteAddress != null ? (IntPtr)(pMemoryBlob - (byte*)originalAddress + (byte*)request->Address.pRemoteAddress) : IntPtr.Zero; CopyOutAddress(address, ref v4address, ref v6address); - IPEndPoint endpoint = null; + IPEndPoint? endpoint = null; if (v4address != null) { endpoint = new IPEndPoint(IPAddress.Any, IPEndPoint.MinPort).Create(v4address) as IPEndPoint; @@ -857,17 +857,17 @@ internal static unsafe IPEndPoint GetRemoteEndPoint(IntPtr memoryBlob, IntPtr or return endpoint; } - internal static unsafe IPEndPoint GetLocalEndPoint(IntPtr memoryBlob, IntPtr originalAddress) + internal static unsafe IPEndPoint? GetLocalEndPoint(IntPtr memoryBlob, IntPtr originalAddress) { - SocketAddress v4address = new SocketAddress(AddressFamily.InterNetwork, IPv4AddressSize); - SocketAddress v6address = new SocketAddress(AddressFamily.InterNetworkV6, IPv6AddressSize); + SocketAddress? v4address = new SocketAddress(AddressFamily.InterNetwork, IPv4AddressSize); + SocketAddress? v6address = new SocketAddress(AddressFamily.InterNetworkV6, IPv6AddressSize); byte* pMemoryBlob = (byte*)memoryBlob; HTTP_REQUEST* request = (HTTP_REQUEST*)pMemoryBlob; IntPtr address = request->Address.pLocalAddress != null ? (IntPtr)(pMemoryBlob - (byte*)originalAddress + (byte*)request->Address.pLocalAddress) : IntPtr.Zero; CopyOutAddress(address, ref v4address, ref v6address); - IPEndPoint endpoint = null; + IPEndPoint? endpoint = null; if (v4address != null) { endpoint = s_any.Create(v4address) as IPEndPoint; @@ -880,7 +880,7 @@ internal static unsafe IPEndPoint GetLocalEndPoint(IntPtr memoryBlob, IntPtr ori return endpoint; } - private static unsafe void CopyOutAddress(IntPtr address, ref SocketAddress v4address, ref SocketAddress v6address) + private static unsafe void CopyOutAddress(IntPtr address, ref SocketAddress? v4address, ref SocketAddress? v6address) { if (address != IntPtr.Zero) { @@ -890,7 +890,7 @@ private static unsafe void CopyOutAddress(IntPtr address, ref SocketAddress v4ad v6address = null; for (int index = 2; index < IPv4AddressSize; index++) { - v4address[index] = ((byte*)address)[index]; + v4address![index] = ((byte*)address)[index]; } return; } @@ -899,7 +899,7 @@ private static unsafe void CopyOutAddress(IntPtr address, ref SocketAddress v4ad v4address = null; for (int index = 2; index < IPv6AddressSize; index++) { - v6address[index] = ((byte*)address)[index]; + v6address![index] = ((byte*)address)[index]; } return; } diff --git a/src/libraries/System.Net.HttpListener/ref/System.Net.HttpListener.cs b/src/libraries/System.Net.HttpListener/ref/System.Net.HttpListener.cs index 27f33aac7a2aa2..10e2e36f3cce09 100644 --- a/src/libraries/System.Net.HttpListener/ref/System.Net.HttpListener.cs +++ b/src/libraries/System.Net.HttpListener/ref/System.Net.HttpListener.cs @@ -11,15 +11,16 @@ public sealed partial class HttpListener : System.IDisposable { public HttpListener() { } public System.Net.AuthenticationSchemes AuthenticationSchemes { get { throw null; } set { } } - public System.Net.AuthenticationSchemeSelector AuthenticationSchemeSelectorDelegate { get { throw null; } set { } } + public System.Net.AuthenticationSchemeSelector? AuthenticationSchemeSelectorDelegate { get { throw null; } set { } } public System.Security.Authentication.ExtendedProtection.ServiceNameCollection DefaultServiceNames { get { throw null; } } public System.Security.Authentication.ExtendedProtection.ExtendedProtectionPolicy ExtendedProtectionPolicy { get { throw null; } set { } } - public System.Net.HttpListener.ExtendedProtectionSelector ExtendedProtectionSelectorDelegate { get { throw null; } set { } } + [System.Diagnostics.CodeAnalysis.DisallowNullAttribute] + public System.Net.HttpListener.ExtendedProtectionSelector? ExtendedProtectionSelectorDelegate { get { throw null; } set { } } public bool IgnoreWriteExceptions { get { throw null; } set { } } public bool IsListening { get { throw null; } } public static bool IsSupported { get { throw null; } } public System.Net.HttpListenerPrefixCollection Prefixes { get { throw null; } } - public string Realm { get { throw null; } set { } } + public string? Realm { get { throw null; } set { } } public System.Net.HttpListenerTimeoutManager TimeoutManager { get { throw null; } } public bool UnsafeConnectionNtlmAuthentication { get { throw null; } set { } } public void Abort() { } @@ -43,7 +44,7 @@ public sealed partial class HttpListenerContext internal HttpListenerContext() { } public System.Net.HttpListenerRequest Request { get { throw null; } } public System.Net.HttpListenerResponse Response { get { throw null; } } - public System.Security.Principal.IPrincipal User { get { throw null; } } + public System.Security.Principal.IPrincipal? User { get { throw null; } } public System.Threading.Tasks.Task AcceptWebSocketAsync(string subProtocol) { throw null; } public System.Threading.Tasks.Task AcceptWebSocketAsync(string subProtocol, int receiveBufferSize, System.TimeSpan keepAliveInterval) { throw null; } public System.Threading.Tasks.Task AcceptWebSocketAsync(string subProtocol, int receiveBufferSize, System.TimeSpan keepAliveInterval, System.ArraySegment internalBuffer) { throw null; } @@ -75,11 +76,11 @@ public void CopyTo(string[] array, int offset) { } public sealed partial class HttpListenerRequest { internal HttpListenerRequest() { } - public string[] AcceptTypes { get { throw null; } } + public string[]? AcceptTypes { get { throw null; } } public int ClientCertificateError { get { throw null; } } public System.Text.Encoding ContentEncoding { get { throw null; } } public long ContentLength64 { get { throw null; } } - public string ContentType { get { throw null; } } + public string? ContentType { get { throw null; } } public System.Net.CookieCollection Cookies { get { throw null; } } public bool HasEntityBody { get { throw null; } } public System.Collections.Specialized.NameValueCollection Headers { get { throw null; } } @@ -93,34 +94,34 @@ internal HttpListenerRequest() { } public System.Net.IPEndPoint LocalEndPoint { get { throw null; } } public System.Version ProtocolVersion { get { throw null; } } public System.Collections.Specialized.NameValueCollection QueryString { get { throw null; } } - public string RawUrl { get { throw null; } } + public string? RawUrl { get { throw null; } } public System.Net.IPEndPoint RemoteEndPoint { get { throw null; } } public System.Guid RequestTraceIdentifier { get { throw null; } } - public string ServiceName { get { throw null; } } + public string? ServiceName { get { throw null; } } public System.Net.TransportContext TransportContext { get { throw null; } } - public System.Uri Url { get { throw null; } } - public System.Uri UrlReferrer { get { throw null; } } + public System.Uri? Url { get { throw null; } } + public System.Uri? UrlReferrer { get { throw null; } } public string UserAgent { get { throw null; } } public string UserHostAddress { get { throw null; } } public string UserHostName { get { throw null; } } - public string[] UserLanguages { get { throw null; } } + public string[]? UserLanguages { get { throw null; } } public System.IAsyncResult BeginGetClientCertificate(System.AsyncCallback requestCallback, object state) { throw null; } - public System.Security.Cryptography.X509Certificates.X509Certificate2 EndGetClientCertificate(System.IAsyncResult asyncResult) { throw null; } - public System.Security.Cryptography.X509Certificates.X509Certificate2 GetClientCertificate() { throw null; } - public System.Threading.Tasks.Task GetClientCertificateAsync() { throw null; } + public System.Security.Cryptography.X509Certificates.X509Certificate2? EndGetClientCertificate(System.IAsyncResult asyncResult) { throw null; } + public System.Security.Cryptography.X509Certificates.X509Certificate2? GetClientCertificate() { throw null; } + public System.Threading.Tasks.Task GetClientCertificateAsync() { throw null; } } public sealed partial class HttpListenerResponse : System.IDisposable { internal HttpListenerResponse() { } - public System.Text.Encoding ContentEncoding { get { throw null; } set { } } + public System.Text.Encoding? ContentEncoding { get { throw null; } set { } } public long ContentLength64 { get { throw null; } set { } } - public string ContentType { get { throw null; } set { } } + public string? ContentType { get { throw null; } set { } } public System.Net.CookieCollection Cookies { get { throw null; } set { } } public System.Net.WebHeaderCollection Headers { get { throw null; } set { } } public bool KeepAlive { get { throw null; } set { } } public System.IO.Stream OutputStream { get { throw null; } } public System.Version ProtocolVersion { get { throw null; } set { } } - public string RedirectLocation { get { throw null; } set { } } + public string? RedirectLocation { get { throw null; } set { } } public bool SendChunked { get { throw null; } set { } } public int StatusCode { get { throw null; } set { } } public string StatusDescription { get { throw null; } set { } } diff --git a/src/libraries/System.Net.HttpListener/ref/System.Net.HttpListener.csproj b/src/libraries/System.Net.HttpListener/ref/System.Net.HttpListener.csproj index 35b678e353a56c..00bc53369a021a 100644 --- a/src/libraries/System.Net.HttpListener/ref/System.Net.HttpListener.csproj +++ b/src/libraries/System.Net.HttpListener/ref/System.Net.HttpListener.csproj @@ -1,6 +1,7 @@ $(NetCoreAppCurrent) + enable diff --git a/src/libraries/System.Net.HttpListener/src/System.Net.HttpListener.csproj b/src/libraries/System.Net.HttpListener/src/System.Net.HttpListener.csproj index 6948d70ef10db6..476f5987eb069a 100644 --- a/src/libraries/System.Net.HttpListener/src/System.Net.HttpListener.csproj +++ b/src/libraries/System.Net.HttpListener/src/System.Net.HttpListener.csproj @@ -1,9 +1,9 @@ - + true false $(NetCoreAppCurrent)-Windows_NT;$(NetCoreAppCurrent)-Unix;$(NetCoreAppCurrent)-Browser - annotations + enable diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListener.cs b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListener.cs index bde2c4e22ed911..b391474791591f 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListener.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListener.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; +using System.Diagnostics.CodeAnalysis; using System.Security.Authentication.ExtendedProtection; using System.Text; using System.Threading.Tasks; @@ -20,10 +21,10 @@ public sealed unsafe partial class HttpListener : IDisposable private readonly ServiceNameStore _defaultServiceNames; private readonly HttpListenerTimeoutManager _timeoutManager; private ExtendedProtectionPolicy _extendedProtectionPolicy; - private AuthenticationSchemeSelector _authenticationDelegate; + private AuthenticationSchemeSelector? _authenticationDelegate; private AuthenticationSchemes _authenticationScheme = AuthenticationSchemes.Anonymous; - private ExtendedProtectionSelector _extendedProtectionSelectorDelegate; - private string _realm; + private ExtendedProtectionSelector? _extendedProtectionSelectorDelegate; + private string? _realm; internal ICollection PrefixCollection => _uriPrefixes.Keys; @@ -41,7 +42,7 @@ public HttpListener() _extendedProtectionPolicy = new ExtendedProtectionPolicy(PolicyEnforcement.Never); } - public AuthenticationSchemeSelector AuthenticationSchemeSelectorDelegate + public AuthenticationSchemeSelector? AuthenticationSchemeSelectorDelegate { get => _authenticationDelegate; set @@ -51,7 +52,8 @@ public AuthenticationSchemeSelector AuthenticationSchemeSelectorDelegate } } - public ExtendedProtectionSelector ExtendedProtectionSelectorDelegate + [DisallowNull] + public ExtendedProtectionSelector? ExtendedProtectionSelectorDelegate { get => _extendedProtectionSelectorDelegate; set @@ -108,7 +110,7 @@ public HttpListenerPrefixCollection Prefixes internal void AddPrefix(string uriPrefix) { - string registeredPrefix = null; + string? registeredPrefix = null; try { if (uriPrefix == null) @@ -207,7 +209,7 @@ internal bool RemovePrefix(string uriPrefix) if (_state == State.Started) { - RemovePrefixCore((string)_uriPrefixes[uriPrefix]); + RemovePrefixCore((string)_uriPrefixes[uriPrefix]!); } _uriPrefixes.Remove(uriPrefix); @@ -243,7 +245,7 @@ internal void RemoveAll(bool clear) } } - public string Realm + public string? Realm { get => _realm; set @@ -268,8 +270,8 @@ public bool IgnoreWriteExceptions public Task GetContextAsync() { return Task.Factory.FromAsync( - (callback, state) => ((HttpListener)state).BeginGetContext(callback, state), - iar => ((HttpListener)iar.AsyncState).EndGetContext(iar), + (callback, state) => ((HttpListener)state!).BeginGetContext(callback, state), + iar => ((HttpListener)iar!.AsyncState!).EndGetContext(iar), this); } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerContext.cs b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerContext.cs index 3297590d6643af..fe1a1c42f8de78 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerContext.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerContext.cs @@ -9,13 +9,13 @@ namespace System.Net { public sealed unsafe partial class HttpListenerContext { - internal HttpListener _listener; - private HttpListenerResponse _response; - private IPrincipal _user; + internal HttpListener? _listener; + private HttpListenerResponse? _response; + private IPrincipal? _user; public HttpListenerRequest Request { get; } - public IPrincipal User => _user; + public IPrincipal? User => _user; // This can be used to cache the results of HttpListener.AuthenticationSchemeSelectorDelegate. internal AuthenticationSchemes AuthenticationSchemes { get; set; } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequest.cs b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequest.cs index 22f1a1548994b4..2cd1587bd8adb5 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequest.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequest.cs @@ -15,24 +15,24 @@ namespace System.Net { public sealed unsafe partial class HttpListenerRequest { - private CookieCollection _cookies; + private CookieCollection? _cookies; private bool? _keepAlive; - private string _rawUrl; - private Uri _requestUri; + private string? _rawUrl; + private Uri? _requestUri; private Version _version; - public string[] AcceptTypes => Helpers.ParseMultivalueHeader(Headers[HttpKnownHeaderNames.Accept]); + public string[]? AcceptTypes => Helpers.ParseMultivalueHeader(Headers[HttpKnownHeaderNames.Accept]!); - public string[] UserLanguages => Helpers.ParseMultivalueHeader(Headers[HttpKnownHeaderNames.AcceptLanguage]); + public string[]? UserLanguages => Helpers.ParseMultivalueHeader(Headers[HttpKnownHeaderNames.AcceptLanguage]!); - private CookieCollection ParseCookies(Uri uri, string setCookieHeader) + private CookieCollection ParseCookies(Uri? uri, string setCookieHeader) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "uri:" + uri + " setCookieHeader:" + setCookieHeader); CookieCollection cookies = new CookieCollection(); CookieParser parser = new CookieParser(setCookieHeader); while (true) { - Cookie cookie = parser.GetServer(); + Cookie? cookie = parser.GetServer(); if (cookie == null) { // EOF, done. @@ -55,7 +55,7 @@ public CookieCollection Cookies { if (_cookies == null) { - string cookieString = Headers[HttpKnownHeaderNames.Cookie]; + string? cookieString = Headers[HttpKnownHeaderNames.Cookie]; if (!string.IsNullOrEmpty(cookieString)) { _cookies = ParseCookies(RequestUri, cookieString); @@ -75,7 +75,7 @@ public Encoding ContentEncoding { if (UserAgent != null && CultureInfo.InvariantCulture.CompareInfo.IsPrefix(UserAgent, "UP")) { - string postDataCharset = Headers["x-up-devcap-post-charset"]; + string? postDataCharset = Headers["x-up-devcap-post-charset"]; if (postDataCharset != null && postDataCharset.Length > 0) { try @@ -91,7 +91,7 @@ public Encoding ContentEncoding { if (ContentType != null) { - string charSet = Helpers.GetCharSetValueFromHeader(ContentType); + string? charSet = Helpers.GetCharSetValueFromHeader(ContentType); if (charSet != null) { try @@ -108,9 +108,9 @@ public Encoding ContentEncoding } } - public string ContentType => Headers[HttpKnownHeaderNames.ContentType]; + public string? ContentType => Headers[HttpKnownHeaderNames.ContentType]; - public bool IsLocal => LocalEndPoint.Address.Equals(RemoteEndPoint.Address); + public bool IsLocal => LocalEndPoint!.Address.Equals(RemoteEndPoint!.Address); public bool IsWebSocketRequest { @@ -127,7 +127,7 @@ public bool IsWebSocketRequest return false; } - foreach (string connection in Headers.GetValues(HttpKnownHeaderNames.Connection)) + foreach (string connection in Headers.GetValues(HttpKnownHeaderNames.Connection)!) { if (string.Equals(connection, HttpKnownHeaderNames.Upgrade, StringComparison.OrdinalIgnoreCase)) { @@ -141,7 +141,7 @@ public bool IsWebSocketRequest return false; } - foreach (string upgrade in Headers.GetValues(HttpKnownHeaderNames.Upgrade)) + foreach (string upgrade in Headers.GetValues(HttpKnownHeaderNames.Upgrade)!) { if (string.Equals(upgrade, HttpWebSocket.WebSocketUpgradeToken, StringComparison.OrdinalIgnoreCase)) { @@ -159,7 +159,7 @@ public bool KeepAlive { if (!_keepAlive.HasValue) { - string header = Headers[HttpKnownHeaderNames.ProxyConnection]; + string? header = Headers[HttpKnownHeaderNames.ProxyConnection]; if (string.IsNullOrEmpty(header)) { header = Headers[HttpKnownHeaderNames.Connection]; @@ -195,41 +195,41 @@ public NameValueCollection QueryString get { NameValueCollection queryString = new NameValueCollection(); - Helpers.FillFromString(queryString, Url.Query, true, ContentEncoding); + Helpers.FillFromString(queryString, Url!.Query, true, ContentEncoding); return queryString; } } - public string RawUrl => _rawUrl; + public string? RawUrl => _rawUrl; private string RequestScheme => IsSecureConnection ? UriScheme.Https : UriScheme.Http; - public string UserAgent => Headers[HttpKnownHeaderNames.UserAgent]; + public string UserAgent => Headers[HttpKnownHeaderNames.UserAgent]!; - public string UserHostAddress => LocalEndPoint.ToString(); + public string UserHostAddress => LocalEndPoint!.ToString(); - public string UserHostName => Headers[HttpKnownHeaderNames.Host]; + public string UserHostName => Headers[HttpKnownHeaderNames.Host]!; - public Uri UrlReferrer + public Uri? UrlReferrer { get { - string referrer = Headers[HttpKnownHeaderNames.Referer]; + string? referrer = Headers[HttpKnownHeaderNames.Referer]; if (referrer == null) { return null; } - bool success = Uri.TryCreate(referrer, UriKind.RelativeOrAbsolute, out Uri urlReferrer); + bool success = Uri.TryCreate(referrer, UriKind.RelativeOrAbsolute, out Uri? urlReferrer); return success ? urlReferrer : null; } } - public Uri Url => RequestUri; + public Uri? Url => RequestUri; public Version ProtocolVersion => _version; - public X509Certificate2 GetClientCertificate() + public X509Certificate2? GetClientCertificate() { if (ClientCertState == ListenerClientCertState.InProgress) throw new InvalidOperationException(SR.Format(SR.net_listener_callinprogress, $"{nameof(GetClientCertificate)}()/{nameof(BeginGetClientCertificate)}()")); @@ -253,16 +253,16 @@ public IAsyncResult BeginGetClientCertificate(AsyncCallback requestCallback, obj return BeginGetClientCertificateCore(requestCallback, state); } - public Task GetClientCertificateAsync() + public Task GetClientCertificateAsync() { return Task.Factory.FromAsync( - (callback, state) => ((HttpListenerRequest)state).BeginGetClientCertificate(callback, state), - iar => ((HttpListenerRequest)iar.AsyncState).EndGetClientCertificate(iar), + (callback, state) => ((HttpListenerRequest)state!).BeginGetClientCertificate(callback, state), + iar => ((HttpListenerRequest)iar.AsyncState!).EndGetClientCertificate(iar), this); } internal ListenerClientCertState ClientCertState { get; set; } = ListenerClientCertState.NotInitialized; - internal X509Certificate2 ClientCertificate { get; set; } + internal X509Certificate2? ClientCertificate { get; set; } public int ClientCertificateError { @@ -282,7 +282,7 @@ private static class Helpers // // Get attribute off header value // - internal static string GetCharSetValueFromHeader(string headerValue) + internal static string? GetCharSetValueFromHeader(string headerValue) { const string AttrName = "charset"; @@ -327,7 +327,7 @@ internal static string GetCharSetValueFromHeader(string headerValue) return null; // parse the value - string attrValue = null; + string? attrValue = null; int j; @@ -358,7 +358,7 @@ internal static string GetCharSetValueFromHeader(string headerValue) return attrValue; } - internal static string[] ParseMultivalueHeader(string s) + internal static string[]? ParseMultivalueHeader(string s) { if (s == null) return null; @@ -481,7 +481,7 @@ private class UrlDecoder // Accumulate bytes for decoding into characters in a special array private int _numBytes; - private byte[] _byteBuffer; + private byte[]? _byteBuffer; // Encoding to convert chars to bytes private readonly Encoding _encoding; @@ -490,7 +490,7 @@ private void FlushBytes() { if (_numBytes > 0) { - _numChars += _encoding.GetChars(_byteBuffer, 0, _numBytes, _charBuffer, _numChars); + _numChars += _encoding.GetChars(_byteBuffer!, 0, _numBytes, _charBuffer, _numChars); _numBytes = 0; } } @@ -537,8 +537,8 @@ internal string GetString() internal static void FillFromString(NameValueCollection nvc, string s, bool urlencoded, Encoding encoding) { - int l = (s != null) ? s.Length : 0; - int i = (s.Length > 0 && s[0] == '?') ? 1 : 0; + int l = s.Length; + int i = (l > 0 && s[0] == '?') ? 1 : 0; while (i < l) { @@ -566,8 +566,8 @@ internal static void FillFromString(NameValueCollection nvc, string s, bool urle // extract the name / value pair - string name = null; - string value = null; + string? name = null; + string? value = null; if (ti >= 0) { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequestUriBuilder.cs b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequestUriBuilder.cs index 45d2b85015aa9c..18c6106b27cde5 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequestUriBuilder.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerRequestUriBuilder.cs @@ -25,7 +25,7 @@ internal sealed class HttpListenerRequestUriBuilder private readonly string _cookedUriQuery; // This field is used to build the final request Uri string from the Uri parts passed to the ctor. - private StringBuilder _requestUriString; + private StringBuilder? _requestUriString; // The raw path is parsed by looping through all characters from left to right. 'rawOctets' // is used to store consecutive percent encoded octets as actual byte values: e.g. for path /pa%C3%84th%2F/ @@ -37,11 +37,11 @@ internal sealed class HttpListenerRequestUriBuilder // we reach 't', the content of rawOctets { 0xC4 } will be fed into the ANSI encoding. The resulting // string '\u00C4' will be percent encoded into UTF-8 octets and appended to requestUriString. The final // path will be '/pa%C3%84th/', where '%C3%84' is the UTF-8 percent encoded character. - private List _rawOctets; - private string _rawPath; + private List? _rawOctets; + private string? _rawPath; // Holds the final request Uri. - private Uri _requestUri; + private Uri? _requestUri; private HttpListenerRequestUriBuilder(string rawUri, string cookedUriScheme, string cookedUriHost, string cookedUriPath, string cookedUriQuery) @@ -76,7 +76,7 @@ private Uri Build() BuildRequestUriUsingCookedPath(); } - return _requestUri; + return _requestUri!; } private void BuildRequestUriUsingCookedPath() @@ -174,6 +174,7 @@ private ParsingResult ParseRawPath(Encoding encoding) int index = 0; char current = '\0'; + Debug.Assert(_rawPath != null); while (index < _rawPath.Length) { current = _rawPath[index]; @@ -220,7 +221,8 @@ private ParsingResult ParseRawPath(Encoding encoding) return ParsingResult.EncodingError; } // Append the current character to the result. - _requestUriString.Append(current); + Debug.Assert(_requestUriString != null); + _requestUriString!.Append(current); index++; } } @@ -247,11 +249,11 @@ private bool AppendUnicodeCodePointValuePercentEncoded(string codePoint) return false; } - string unicodeString = null; + string? unicodeString = null; try { unicodeString = char.ConvertFromUtf32(codePointValue); - AppendOctetsPercentEncoded(_requestUriString, s_utf8Encoding.GetBytes(unicodeString)); + AppendOctetsPercentEncoded(_requestUriString!, s_utf8Encoding.GetBytes(unicodeString)); return true; } @@ -278,19 +280,20 @@ private bool AddPercentEncodedOctetToRawOctetsList(Encoding encoding, string esc return false; } - _rawOctets.Add(encodedValue); + Debug.Assert(_rawOctets != null); + _rawOctets!.Add(encodedValue); return true; } private bool EmptyDecodeAndAppendRawOctetsList(Encoding encoding) { - if (_rawOctets.Count == 0) + if (_rawOctets!.Count == 0) { return true; } - string decodedString = null; + string? decodedString = null; try { // If the encoding can get a string out of the byte array, this is a valid string in the @@ -299,11 +302,11 @@ private bool EmptyDecodeAndAppendRawOctetsList(Encoding encoding) if (encoding == s_utf8Encoding) { - AppendOctetsPercentEncoded(_requestUriString, _rawOctets.ToArray()); + AppendOctetsPercentEncoded(_requestUriString!, _rawOctets.ToArray()); } else { - AppendOctetsPercentEncoded(_requestUriString, s_utf8Encoding.GetBytes(decodedString)); + AppendOctetsPercentEncoded(_requestUriString!, s_utf8Encoding.GetBytes(decodedString)); } _rawOctets.Clear(); diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerResponse.cs b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerResponse.cs index da852b17453311..6b7ddc839b3030 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerResponse.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpListenerResponse.cs @@ -10,11 +10,11 @@ namespace System.Net public sealed unsafe partial class HttpListenerResponse : IDisposable { private BoundaryType _boundaryType = BoundaryType.None; - private CookieCollection _cookies; - private readonly HttpListenerContext _httpContext; + private CookieCollection? _cookies; + private readonly HttpListenerContext? _httpContext; private bool _keepAlive = true; - private HttpResponseStream _responseStream; - private string _statusDescription; + private HttpResponseStream? _responseStream; + private string? _statusDescription; private WebHeaderCollection _webHeaders = new WebHeaderCollection(); public WebHeaderCollection Headers @@ -30,9 +30,9 @@ public WebHeaderCollection Headers } } - public Encoding ContentEncoding { get; set; } + public Encoding? ContentEncoding { get; set; } - public string ContentType + public string? ContentType { get => Headers[HttpKnownHeaderNames.ContentType]; set @@ -49,9 +49,9 @@ public string ContentType } } - private HttpListenerContext HttpListenerContext => _httpContext; + private HttpListenerContext HttpListenerContext => _httpContext!; - private HttpListenerRequest HttpListenerRequest => HttpListenerContext.Request; + private HttpListenerRequest HttpListenerRequest => HttpListenerContext!.Request; internal EntitySendFormat EntitySendFormat { @@ -134,11 +134,11 @@ public Stream OutputStream { CheckDisposed(); EnsureResponseStream(); - return _responseStream; + return _responseStream!; } } - public string RedirectLocation + public string? RedirectLocation { get => Headers[HttpResponseHeader.Location]; set @@ -224,7 +224,7 @@ private void ComputeCookies() if (_cookies != null) { // now go through the collection, and concatenate all the cookies in per-variant strings - string setCookie2 = null, setCookie = null; + string? setCookie2 = null, setCookie = null; for (int index = 0; index < _cookies.Count; index++) { Cookie cookie = _cookies[index]; @@ -271,7 +271,7 @@ public void Redirect(string url) if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"url={url}"); Headers[HttpResponseHeader.Location] = url; StatusCode = (int)HttpStatusCode.Redirect; - StatusDescription = HttpStatusDescription.Get(StatusCode); + StatusDescription = HttpStatusDescription.Get(StatusCode)!; } public void SetCookie(Cookie cookie) diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/HttpRequestStream.cs b/src/libraries/System.Net.HttpListener/src/System/Net/HttpRequestStream.cs index c05875af66320b..f8890573c0f2c7 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpRequestStream.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpRequestStream.cs @@ -37,7 +37,7 @@ public override int Read(byte[] buffer, int offset, int size) return ReadCore(buffer, offset, size); } - public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, object state) + public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback? callback, object? state) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "buffer.Length:" + buffer?.Length + " size:" + size + " offset:" + offset); @@ -54,7 +54,7 @@ public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, Asyn throw new ArgumentOutOfRangeException(nameof(size)); } - return BeginReadCore(buffer, offset, size, callback, state); + return BeginReadCore(buffer, offset, size, callback, state)!; } public override void Flush() { } @@ -74,7 +74,7 @@ public override long Position public override void Write(byte[] buffer, int offset, int size) => throw new InvalidOperationException(SR.net_readonlystream); - public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, object state) + public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback? callback, object? state) { throw new InvalidOperationException(SR.net_readonlystream); } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/HttpResponseStream.cs b/src/libraries/System.Net.HttpListener/src/System/Net/HttpResponseStream.cs index fea4e192bbf2c8..e51f8027e603d5 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/HttpResponseStream.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/HttpResponseStream.cs @@ -33,7 +33,7 @@ public override long Position public override int Read(byte[] buffer, int offset, int size) => throw new InvalidOperationException(SR.net_writeonlystream); - public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, object state) + public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback? callback, object? state) { throw new InvalidOperationException(SR.net_writeonlystream); } @@ -64,7 +64,7 @@ public override void Write(byte[] buffer, int offset, int size) WriteCore(buffer, offset, size); } - public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, object state) + public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback? callback, object? state) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "buffer.Length:" + buffer?.Length + " size:" + size + " offset:" + offset); if (buffer == null) diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ChunkStream.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ChunkStream.cs index 09794af735b30e..b5402428c359ab 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ChunkStream.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ChunkStream.cs @@ -381,7 +381,7 @@ private State ReadTrailer(byte[] buffer, ref int offset, int size) } StringReader reader = new StringReader(_saved.ToString()); - string line; + string? line; while ((line = reader.ReadLine()) != null && line != "") _headers.Add(line); diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ChunkedInputStream.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ChunkedInputStream.cs index a21b1018db3799..6eb6f5d7b883d9 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ChunkedInputStream.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ChunkedInputStream.cs @@ -75,7 +75,7 @@ protected override int ReadCore(byte[] buffer, int offset, int count) return EndRead(ares); } - protected override IAsyncResult BeginReadCore(byte[] buffer, int offset, int size, AsyncCallback cback, object state) + protected override IAsyncResult BeginReadCore(byte[] buffer, int offset, int size, AsyncCallback? cback, object? state) { HttpStreamAsyncResult ares = new HttpStreamAsyncResult(this); ares._callback = cback; @@ -113,7 +113,7 @@ protected override IAsyncResult BeginReadCore(byte[] buffer, int offset, int siz private void OnRead(IAsyncResult base_ares) { - ReadBufferState rb = (ReadBufferState)base_ares.AsyncState; + ReadBufferState rb = (ReadBufferState)base_ares.AsyncState!; HttpStreamAsyncResult ares = rb.Ares; try { @@ -126,7 +126,7 @@ private void OnRead(IAsyncResult base_ares) return; } - _decoder.Write(ares._buffer, ares._offset, nread); + _decoder.Write(ares._buffer!, ares._offset, nread); nread = _decoder.Read(rb.Buffer, rb.Offset, rb.Count); rb.Offset += nread; rb.Count -= nread; @@ -139,7 +139,7 @@ private void OnRead(IAsyncResult base_ares) } ares._offset = 0; ares._count = Math.Min(8192, _decoder.ChunkLeft + 6); - base.BeginReadCore(ares._buffer, ares._offset, ares._count, OnRead, rb); + base.BeginReadCore(ares._buffer!, ares._offset, ares._count, OnRead, rb); } catch (Exception e) { @@ -153,7 +153,7 @@ public override int EndRead(IAsyncResult asyncResult) if (asyncResult == null) throw new ArgumentNullException(nameof(asyncResult)); - HttpStreamAsyncResult ares = asyncResult as HttpStreamAsyncResult; + HttpStreamAsyncResult? ares = asyncResult as HttpStreamAsyncResult; if (ares == null || !ReferenceEquals(this, ares._parent)) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpConnection.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpConnection.cs index 5de16059ceae46..2e7e7aef28c607 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpConnection.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpConnection.cs @@ -29,6 +29,7 @@ // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Net.Security; using System.Net.Sockets; @@ -43,16 +44,16 @@ internal sealed class HttpConnection { private static AsyncCallback s_onreadCallback = new AsyncCallback(OnRead); private const int BufferSize = 8192; - private Socket _socket; + private Socket? _socket; private Stream _stream; private HttpEndPointListener _epl; - private MemoryStream _memoryStream; - private byte[] _buffer; + private MemoryStream? _memoryStream; + private byte[]? _buffer; private HttpListenerContext _context; - private StringBuilder _currentLine; - private ListenerPrefix _prefix; - private HttpRequestStream _requestStream; - private HttpResponseStream _responseStream; + private StringBuilder? _currentLine; + private ListenerPrefix? _prefix; + private HttpRequestStream? _requestStream; + private HttpResponseStream? _responseStream; private bool _chunked; private int _reuses; private bool _contextBound; @@ -60,11 +61,11 @@ internal sealed class HttpConnection private X509Certificate _cert; private int _timeout = 90000; // 90k ms for first request, 15k ms from then on private Timer _timer; - private IPEndPoint _localEndPoint; - private HttpListener _lastListener; - private int[] _clientCertErrors; - private X509Certificate2 _clientCert; - private SslStream _sslStream; + private IPEndPoint? _localEndPoint; + private HttpListener? _lastListener; + private int[]? _clientCertErrors; + private X509Certificate2? _clientCert; + private SslStream? _sslStream; private InputState _inputState = InputState.RequestLine; private LineState _lineState = LineState.None; private int _position; @@ -111,21 +112,23 @@ public HttpConnection(Socket sock, HttpEndPointListener epl, bool secure, X509Ce Init(); } - internal int[] ClientCertificateErrors + internal int[]? ClientCertificateErrors { get { return _clientCertErrors; } } - internal X509Certificate2 ClientCertificate + internal X509Certificate2? ClientCertificate { get { return _clientCert; } } - internal SslStream SslStream + internal SslStream? SslStream { get { return _sslStream; } } + [MemberNotNull(nameof(_memoryStream))] + [MemberNotNull(nameof(_context))] private void Init() { _contextBound = false; @@ -152,21 +155,21 @@ public int Reuses get { return _reuses; } } - public IPEndPoint LocalEndPoint + public IPEndPoint? LocalEndPoint { get { if (_localEndPoint != null) return _localEndPoint; - _localEndPoint = (IPEndPoint)_socket.LocalEndPoint; + _localEndPoint = (IPEndPoint?)_socket!.LocalEndPoint; return _localEndPoint; } } - public IPEndPoint RemoteEndPoint + public IPEndPoint? RemoteEndPoint { - get { return (IPEndPoint)_socket.RemoteEndPoint; } + get { return (IPEndPoint?)_socket!.RemoteEndPoint; } } public bool IsSecure @@ -174,13 +177,13 @@ public bool IsSecure get { return _secure; } } - public ListenerPrefix Prefix + public ListenerPrefix? Prefix { get { return _prefix; } set { _prefix = value; } } - private void OnTimeout(object unused) + private void OnTimeout(object? unused) { CloseSocket(); Unbind(); @@ -209,8 +212,8 @@ public HttpRequestStream GetRequestStream(bool chunked, long contentlength) { if (_requestStream == null) { - byte[] buffer = _memoryStream.GetBuffer(); - int length = (int)_memoryStream.Length; + byte[] buffer = _memoryStream!.GetBuffer(); + int length = (int)_memoryStream!.Length; _memoryStream = null; if (chunked) { @@ -230,7 +233,7 @@ public HttpResponseStream GetResponseStream() { if (_responseStream == null) { - HttpListener listener = _context._listener; + HttpListener? listener = _context._listener; if (listener == null) return new HttpResponseStream(_stream, _context.Response, true); @@ -242,7 +245,7 @@ public HttpResponseStream GetResponseStream() private static void OnRead(IAsyncResult ares) { - HttpConnection cnc = (HttpConnection)ares.AsyncState; + HttpConnection cnc = (HttpConnection)ares.AsyncState!; cnc.OnReadInternal(ares); } @@ -253,7 +256,7 @@ private void OnReadInternal(IAsyncResult ares) try { nread = _stream.EndRead(ares); - _memoryStream.Write(_buffer, 0, nread); + _memoryStream!.Write(_buffer!, 0, nread); if (_memoryStream.Length > 32768) { SendError(HttpStatusDescription.Get(400), 400); @@ -299,7 +302,7 @@ private void OnReadInternal(IAsyncResult ares) Close(true); return; } - HttpListener listener = _context._listener; + HttpListener listener = _context._listener!; if (_lastListener != listener) { RemoveConnection(); @@ -311,7 +314,7 @@ private void OnReadInternal(IAsyncResult ares) listener.RegisterContext(_context); return; } - _stream.BeginRead(_buffer, 0, BufferSize, s_onreadCallback, this); + _stream.BeginRead(_buffer!, 0, BufferSize, s_onreadCallback, this); } private void RemoveConnection() @@ -342,7 +345,7 @@ private bool ProcessInput(MemoryStream ms) byte[] buffer = ms.GetBuffer(); int len = (int)ms.Length; int used = 0; - string line; + string? line; while (true) { @@ -359,7 +362,7 @@ private bool ProcessInput(MemoryStream ms) } catch { - _context.ErrorMessage = HttpStatusDescription.Get(400); + _context.ErrorMessage = HttpStatusDescription.Get(400)!; _context.ErrorStatus = 400; return true; } @@ -372,7 +375,7 @@ private bool ProcessInput(MemoryStream ms) if (_inputState == InputState.RequestLine) continue; _currentLine = null; - ms = null; + ms = null!; return true; } @@ -404,7 +407,7 @@ private bool ProcessInput(MemoryStream ms) return false; } - private string ReadLine(byte[] buffer, int offset, int len, ref int used) + private string? ReadLine(byte[] buffer, int offset, int len, ref int used) { if (_currentLine == null) _currentLine = new StringBuilder(128); @@ -428,7 +431,7 @@ private string ReadLine(byte[] buffer, int offset, int len, ref int used) } } - string result = null; + string? result = null; if (_lineState == LineState.LF) { _lineState = LineState.None; @@ -439,14 +442,14 @@ private string ReadLine(byte[] buffer, int offset, int len, ref int used) return result; } - public void SendError(string msg, int status) + public void SendError(string? msg, int status) { try { HttpListenerResponse response = _context.Response; response.StatusCode = status; response.ContentType = "text/html"; - string description = HttpStatusDescription.Get(status); + string? description = HttpStatusDescription.Get(status); string str; if (msg != null) str = string.Format("

{0} ({1})

", description, msg); diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpEndPointListener.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpEndPointListener.cs index 7fc69e7f646a50..d7804240fbd26d 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpEndPointListener.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpEndPointListener.cs @@ -43,9 +43,9 @@ internal sealed class HttpEndPointListener private readonly Socket _socket; private readonly Dictionary _unregisteredConnections; private Dictionary _prefixes; - private List _unhandledPrefixes; // host = '*' - private List _allPrefixes; // host = '+' - private X509Certificate _cert; + private List? _unhandledPrefixes; // host = '*' + private List? _allPrefixes; // host = '+' + private X509Certificate? _cert; private bool _secure; public HttpEndPointListener(HttpListener listener, IPAddress addr, int port, bool secure) @@ -102,9 +102,9 @@ private void Accept(SocketAsyncEventArgs e) private static void ProcessAccept(SocketAsyncEventArgs args) { - HttpEndPointListener epl = (HttpEndPointListener)args.UserToken; + HttpEndPointListener epl = (HttpEndPointListener)args.UserToken!; - Socket accepted = args.SocketError == SocketError.Success ? args.AcceptSocket : null; + Socket? accepted = args.SocketError == SocketError.Success ? args.AcceptSocket : null; epl.Accept(args); if (accepted == null) @@ -119,7 +119,7 @@ private static void ProcessAccept(SocketAsyncEventArgs args) HttpConnection conn; try { - conn = new HttpConnection(accepted, epl, epl._secure, epl._cert); + conn = new HttpConnection(accepted, epl, epl._secure, epl._cert!); } catch { @@ -134,7 +134,7 @@ private static void ProcessAccept(SocketAsyncEventArgs args) conn.BeginReadRequest(); } - private static void OnAccept(object sender, SocketAsyncEventArgs e) + private static void OnAccept(object? sender, SocketAsyncEventArgs e) { ProcessAccept(e); } @@ -150,8 +150,8 @@ internal void RemoveConnection(HttpConnection conn) public bool BindContext(HttpListenerContext context) { HttpListenerRequest req = context.Request; - ListenerPrefix prefix; - HttpListener listener = SearchListener(req.Url, out prefix); + ListenerPrefix? prefix; + HttpListener? listener = SearchListener(req.Url, out prefix); if (listener == null) return false; @@ -165,10 +165,10 @@ public void UnbindContext(HttpListenerContext context) if (context == null || context.Request == null) return; - context._listener.UnregisterContext(context); + context._listener!.UnregisterContext(context); } - private HttpListener SearchListener(Uri uri, out ListenerPrefix prefix) + private HttpListener? SearchListener(Uri? uri, out ListenerPrefix? prefix) { prefix = null; if (uri == null) @@ -179,7 +179,7 @@ private HttpListener SearchListener(Uri uri, out ListenerPrefix prefix) string path = WebUtility.UrlDecode(uri.AbsolutePath); string pathSlash = path[path.Length - 1] == '/' ? path : path + "/"; - HttpListener bestMatch = null; + HttpListener? bestMatch = null; int bestLength = -1; if (host != null && host != "") @@ -187,7 +187,7 @@ private HttpListener SearchListener(Uri uri, out ListenerPrefix prefix) Dictionary localPrefixes = _prefixes; foreach (ListenerPrefix p in localPrefixes.Keys) { - string ppath = p.Path; + string ppath = p.Path!; if (ppath.Length < bestLength) continue; @@ -205,7 +205,7 @@ private HttpListener SearchListener(Uri uri, out ListenerPrefix prefix) return bestMatch; } - List list = _unhandledPrefixes; + List? list = _unhandledPrefixes; bestMatch = MatchFromList(host, path, list, out prefix); if (path != pathSlash && bestMatch == null) @@ -226,18 +226,18 @@ private HttpListener SearchListener(Uri uri, out ListenerPrefix prefix) return null; } - private HttpListener MatchFromList(string host, string path, List list, out ListenerPrefix prefix) + private HttpListener? MatchFromList(string? host, string path, List? list, out ListenerPrefix? prefix) { prefix = null; if (list == null) return null; - HttpListener bestMatch = null; + HttpListener? bestMatch = null; int bestLength = -1; foreach (ListenerPrefix p in list) { - string ppath = p.Path; + string ppath = p.Path!; if (ppath.Length < bestLength) continue; @@ -288,7 +288,7 @@ private void CheckIfRemove() if (_prefixes.Count > 0) return; - List list = _unhandledPrefixes; + List? list = _unhandledPrefixes; if (list != null && list.Count > 0) return; @@ -315,7 +315,7 @@ public void Close() public void AddPrefix(ListenerPrefix prefix, HttpListener listener) { - List current; + List? current; List future; if (prefix.Host == "*") { @@ -356,7 +356,7 @@ public void AddPrefix(ListenerPrefix prefix, HttpListener listener) public void RemovePrefix(ListenerPrefix prefix, HttpListener listener) { - List current; + List? current; List future; if (prefix.Host == "*") { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpEndPointManager.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpEndPointManager.cs index c14013ac73bc98..cf3dd38ae5c769 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpEndPointManager.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpEndPointManager.cs @@ -95,14 +95,14 @@ private static void AddPrefixInternal(string p, HttpListener listener) if (lp.Host != "*" && lp.Host != "+" && Uri.CheckHostName(lp.Host) == UriHostNameType.Unknown) throw new HttpListenerException((int)HttpStatusCode.BadRequest, SR.net_listener_host); - if (lp.Path.Contains('%')) + if (lp.Path!.Contains('%')) throw new HttpListenerException((int)HttpStatusCode.BadRequest, SR.net_invalid_path); if (lp.Path.IndexOf("//", StringComparison.Ordinal) != -1) throw new HttpListenerException((int)HttpStatusCode.BadRequest, SR.net_invalid_path); // listens on all the interfaces if host name cannot be parsed by IPAddress. - HttpEndPointListener epl = GetEPListener(lp.Host, lp.Port, listener, lp.Secure); + HttpEndPointListener epl = GetEPListener(lp.Host!, lp.Port, listener, lp.Secure); epl.AddPrefix(lp, listener); } @@ -133,7 +133,7 @@ private static HttpEndPointListener GetEPListener(string host, int port, HttpLis } } - Dictionary p = null; + Dictionary? p = null; if (s_ipEndPoints.ContainsKey(addr)) { p = s_ipEndPoints[addr]; @@ -144,7 +144,7 @@ private static HttpEndPointListener GetEPListener(string host, int port, HttpLis s_ipEndPoints[addr] = p; } - HttpEndPointListener epl = null; + HttpEndPointListener? epl = null; if (p.ContainsKey(port)) { epl = p[port]; @@ -169,7 +169,7 @@ public static void RemoveEndPoint(HttpEndPointListener epl, IPEndPoint ep) { lock ((s_ipEndPoints as ICollection).SyncRoot) { - Dictionary p = null; + Dictionary? p = null; p = s_ipEndPoints[ep.Address]; p.Remove(ep.Port); if (p.Count == 0) @@ -202,13 +202,13 @@ public static void RemovePrefix(string prefix, HttpListener listener) private static void RemovePrefixInternal(string prefix, HttpListener listener) { ListenerPrefix lp = new ListenerPrefix(prefix); - if (lp.Path.Contains('%')) + if (lp.Path!.Contains('%')) return; if (lp.Path.IndexOf("//", StringComparison.Ordinal) != -1) return; - HttpEndPointListener epl = GetEPListener(lp.Host, lp.Port, listener, lp.Secure); + HttpEndPointListener epl = GetEPListener(lp.Host!, lp.Port, listener, lp.Secure); epl.RemovePrefix(lp, listener); } } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListener.Certificates.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListener.Certificates.cs index d595af0f7be62e..48f0f551a8947b 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListener.Certificates.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListener.Certificates.cs @@ -16,7 +16,7 @@ internal SslStream CreateSslStream(Stream innerStream, bool ownsStream, RemoteCe return new SslStream(innerStream, ownsStream, callback); } - internal X509Certificate LoadCertificateAndKey(IPAddress addr, int port) + internal X509Certificate? LoadCertificateAndKey(IPAddress addr, int port) { // TODO https://github.com/dotnet/runtime/issues/19752: Implement functionality to read SSL certificate. return null; diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListener.Managed.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListener.Managed.cs index 02a747eefdc332..3839b27cff25b4 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListener.Managed.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListener.Managed.cs @@ -192,7 +192,7 @@ internal void RegisterContext(HttpListenerContext context) _listenerContexts[context] = context; } - ListenerAsyncResult ares = null; + ListenerAsyncResult? ares = null; lock ((_asyncWaitQueue as ICollection).SyncRoot) { if (_asyncWaitQueue.Count == 0) @@ -257,7 +257,7 @@ private void Cleanup(bool close_existing) } } - private HttpListenerContext GetContextFromQueue() + private HttpListenerContext? GetContextFromQueue() { lock ((_contextQueue as ICollection).SyncRoot) { @@ -273,7 +273,7 @@ private HttpListenerContext GetContextFromQueue() } } - public IAsyncResult BeginGetContext(AsyncCallback callback, object state) + public IAsyncResult BeginGetContext(AsyncCallback? callback, object? state) { CheckDisposed(); if (_state != State.Started) @@ -288,7 +288,7 @@ public IAsyncResult BeginGetContext(AsyncCallback callback, object state) { lock ((_contextQueue as ICollection).SyncRoot) { - HttpListenerContext ctx = GetContextFromQueue(); + HttpListenerContext? ctx = GetContextFromQueue(); if (ctx != null) { ares.Complete(ctx, true); @@ -310,7 +310,7 @@ public HttpListenerContext EndGetContext(IAsyncResult asyncResult) throw new ArgumentNullException(nameof(asyncResult)); } - ListenerAsyncResult ares = asyncResult as ListenerAsyncResult; + ListenerAsyncResult? ares = asyncResult as ListenerAsyncResult; if (ares == null || !ReferenceEquals(this, ares._parent)) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); @@ -332,7 +332,7 @@ public HttpListenerContext EndGetContext(IAsyncResult asyncResult) _asyncWaitQueue.RemoveAt(idx); } - HttpListenerContext context = ares.GetContext(); + HttpListenerContext context = ares.GetContext()!; context.ParseAuthentication(context.AuthenticationSchemes); return context; } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerContext.Managed.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerContext.Managed.cs index b771a2490acba5..8abb640e5c79f4 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerContext.Managed.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerContext.Managed.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.ComponentModel; +using System.Diagnostics.CodeAnalysis; using System.Net.WebSockets; using System.Security.Principal; using System.Text; @@ -23,7 +24,7 @@ internal HttpListenerContext(HttpConnection connection) internal int ErrorStatus { get; set; } - internal string ErrorMessage { get; set; } + internal string? ErrorMessage { get; set; } internal bool HaveError => ErrorMessage != null; @@ -34,7 +35,7 @@ internal void ParseAuthentication(AuthenticationSchemes expectedSchemes) if (expectedSchemes == AuthenticationSchemes.Anonymous) return; - string header = Request.Headers[HttpKnownHeaderNames.Authorization]; + string? header = Request.Headers[HttpKnownHeaderNames.Authorization]; if (string.IsNullOrEmpty(header)) return; @@ -44,8 +45,8 @@ internal void ParseAuthentication(AuthenticationSchemes expectedSchemes) } } - internal IPrincipal ParseBasicAuthentication(string authData) => - TryParseBasicAuth(authData, out HttpStatusCode errorCode, out string username, out string password) ? + internal IPrincipal? ParseBasicAuthentication(string authData) => + TryParseBasicAuth(authData, out HttpStatusCode errorCode, out string? username, out string? password) ? new GenericPrincipal(new HttpListenerBasicIdentity(username, password), Array.Empty()) : null; @@ -54,7 +55,7 @@ internal static bool IsBasicHeader(string header) => header[5] == ' ' && string.Compare(header, 0, AuthenticationTypes.Basic, 0, 5, StringComparison.OrdinalIgnoreCase) == 0; - internal static bool TryParseBasicAuth(string headerValue, out HttpStatusCode errorCode, out string username, out string password) + internal static bool TryParseBasicAuth(string headerValue, out HttpStatusCode errorCode, [NotNullWhen(true)] out string? username, [NotNullWhen(true)] out string? password) { errorCode = HttpStatusCode.OK; username = password = null; diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerRequest.Managed.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerRequest.Managed.cs index b1ca677bbe9770..d18b621d0f505e 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerRequest.Managed.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerRequest.Managed.cs @@ -31,6 +31,7 @@ // using System.Collections.Specialized; +using System.Diagnostics; using System.Globalization; using System.IO; using System.Security.Authentication.ExtendedProtection; @@ -43,7 +44,7 @@ public sealed partial class HttpListenerRequest { private class Context : TransportContext { - public override ChannelBinding GetChannelBinding(ChannelBindingKind kind) + public override ChannelBinding? GetChannelBinding(ChannelBindingKind kind) { if (kind != ChannelBindingKind.Endpoint) { @@ -57,8 +58,8 @@ public override ChannelBinding GetChannelBinding(ChannelBindingKind kind) private long _contentLength; private bool _clSet; private WebHeaderCollection _headers; - private string _method; - private Stream _inputStream; + private string? _method; + private Stream? _inputStream; private HttpListenerContext _context; private bool _isChunked; @@ -176,8 +177,9 @@ internal void FinishInitialization() } string path; - Uri raw_uri = null; - if (MaybeUri(_rawUrl.ToLowerInvariant()) && Uri.TryCreate(_rawUrl, UriKind.Absolute, out raw_uri)) + Uri? raw_uri = null; + Debug.Assert(_rawUrl != null); + if (MaybeUri(_rawUrl!.ToLowerInvariant()) && Uri.TryCreate(_rawUrl, UriKind.Absolute, out raw_uri)) path = raw_uri.PathAndQuery; else path = _rawUrl; @@ -192,7 +194,7 @@ internal void FinishInitialization() if (colon >= 0) host = host.Substring(0, colon); - string base_uri = string.Format("{0}://{1}:{2}", RequestScheme, host, LocalEndPoint.Port); + string base_uri = string.Format("{0}://{1}:{2}", RequestScheme, host, LocalEndPoint!.Port); if (!Uri.TryCreate(base_uri + path, UriKind.Absolute, out _requestUri)) { @@ -205,7 +207,7 @@ internal void FinishInitialization() if (_version >= HttpVersion.Version11) { - string t_encoding = Headers[HttpKnownHeaderNames.TransferEncoding]; + string? t_encoding = Headers[HttpKnownHeaderNames.TransferEncoding]; _isChunked = (t_encoding != null && string.Equals(t_encoding, "chunked", StringComparison.OrdinalIgnoreCase)); // 'identity' is not valid! if (t_encoding != null && !_isChunked) @@ -321,14 +323,14 @@ internal bool FlushInput() } } - private X509Certificate2 GetClientCertificateCore() => ClientCertificate = _context.Connection.ClientCertificate; + private X509Certificate2? GetClientCertificateCore() => ClientCertificate = _context.Connection.ClientCertificate; private int GetClientCertificateErrorCore() { HttpConnection cnc = _context.Connection; if (cnc.ClientCertificate == null) return 0; - int[] errors = cnc.ClientCertificateErrors; + int[]? errors = cnc.ClientCertificateErrors; if (errors != null && errors.Length > 0) return errors[0]; return 0; @@ -349,7 +351,7 @@ public long ContentLength64 public NameValueCollection Headers => _headers; - public string HttpMethod => _method; + public string? HttpMethod => _method; public Stream InputStream { @@ -371,9 +373,9 @@ public Stream InputStream public bool IsSecureConnection => _context.Connection.IsSecure; - public IPEndPoint LocalEndPoint => _context.Connection.LocalEndPoint; + public IPEndPoint? LocalEndPoint => _context.Connection.LocalEndPoint; - public IPEndPoint RemoteEndPoint => _context.Connection.RemoteEndPoint; + public IPEndPoint? RemoteEndPoint => _context.Connection.RemoteEndPoint; public Guid RequestTraceIdentifier { get; } = Guid.NewGuid(); @@ -389,12 +391,12 @@ private IAsyncResult BeginGetClientCertificateCore(AsyncCallback requestCallback return asyncResult; } - public X509Certificate2 EndGetClientCertificate(IAsyncResult asyncResult) + public X509Certificate2? EndGetClientCertificate(IAsyncResult asyncResult) { if (asyncResult == null) throw new ArgumentNullException(nameof(asyncResult)); - GetClientCertificateAsyncResult clientCertAsyncResult = asyncResult as GetClientCertificateAsyncResult; + GetClientCertificateAsyncResult? clientCertAsyncResult = asyncResult as GetClientCertificateAsyncResult; if (clientCertAsyncResult == null || clientCertAsyncResult.AsyncObject != this) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); @@ -405,14 +407,14 @@ public X509Certificate2 EndGetClientCertificate(IAsyncResult asyncResult) } clientCertAsyncResult.EndCalled = true; - return (X509Certificate2)clientCertAsyncResult.Result; + return (X509Certificate2?)clientCertAsyncResult.Result; } - public string ServiceName => null; + public string? ServiceName => null; public TransportContext TransportContext => new Context(); - private Uri RequestUri => _requestUri; + private Uri? RequestUri => _requestUri; private bool SupportsWebSockets => true; private class GetClientCertificateAsyncResult : LazyAsyncResult diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerResponse.Managed.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerResponse.Managed.cs index ff7a1954db05de..504c2ca9c9b7e2 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerResponse.Managed.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpListenerResponse.Managed.cs @@ -53,7 +53,7 @@ private void EnsureResponseStream() { if (_responseStream == null) { - _responseStream = _httpContext.Connection.GetResponseStream(); + _responseStream = _httpContext!.Connection.GetResponseStream(); } } @@ -111,7 +111,7 @@ public void Abort() private void Close(bool force) { Disposed = true; - _httpContext.Connection.Close(force); + _httpContext!.Connection.Close(force); } public void Close(byte[] responseEntity, bool willBlock) @@ -143,7 +143,7 @@ public void Close(byte[] responseEntity, bool willBlock) { OutputStream.BeginWrite(responseEntity, 0, responseEntity.Length, iar => { - var thisRef = (HttpListenerResponse)iar.AsyncState; + var thisRef = (HttpListenerResponse)iar.AsyncState!; try { thisRef.OutputStream.EndWrite(iar); @@ -192,7 +192,7 @@ internal void SendHeaders(bool closing, MemoryStream ms, bool isWebSocketHandsha _boundaryType = BoundaryType.Chunked; } - if (CanSendResponseBody(_httpContext.Response.StatusCode)) + if (CanSendResponseBody(_httpContext!.Response.StatusCode)) { _contentLength = -1; } @@ -207,7 +207,7 @@ internal void SendHeaders(bool closing, MemoryStream ms, bool isWebSocketHandsha { if (_boundaryType != BoundaryType.ContentLength && closing) { - _contentLength = CanSendResponseBody(_httpContext.Response.StatusCode) ? -1 : 0; + _contentLength = CanSendResponseBody(_httpContext!.Response.StatusCode) ? -1 : 0; } if (_boundaryType == BoundaryType.ContentLength) @@ -232,7 +232,7 @@ internal void SendHeaders(bool closing, MemoryStream ms, bool isWebSocketHandsha if (!conn_close) { - conn_close = !_httpContext.Request.KeepAlive; + conn_close = !_httpContext!.Request.KeepAlive; } // They sent both KeepAlive: true and Connection: close @@ -247,7 +247,7 @@ internal void SendHeaders(bool closing, MemoryStream ms, bool isWebSocketHandsha _webHeaders.Set(HttpKnownHeaderNames.TransferEncoding, HttpHeaderStrings.Chunked); } - int reuses = _httpContext.Connection.Reuses; + int reuses = _httpContext!.Connection.Reuses; if (reuses >= 100) { _forceCloseChunked = true; @@ -302,7 +302,7 @@ private static string FormatHeaders(WebHeaderCollection headers) for (int i = 0; i < headers.Count; i++) { string key = headers.GetKey(i); - string[] values = headers.GetValues(i); + string[] values = headers.GetValues(i)!; int startingLength = sb.Length; diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpRequestStream.Managed.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpRequestStream.Managed.cs index 72a27490152653..8a9acf3e196de5 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpRequestStream.Managed.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpRequestStream.Managed.cs @@ -125,7 +125,7 @@ protected virtual int ReadCore(byte[] buffer, int offset, int size) return nread; } - protected virtual IAsyncResult BeginReadCore(byte[] buffer, int offset, int size, AsyncCallback cback, object state) + protected virtual IAsyncResult BeginReadCore(byte[] buffer, int offset, int size, AsyncCallback? cback, object? state) { if (size == 0 || _closed) { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpResponseStream.Managed.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpResponseStream.Managed.cs index 269f83ca5aba02..769a51f8e3f2a9 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpResponseStream.Managed.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpResponseStream.Managed.cs @@ -54,8 +54,8 @@ internal HttpResponseStream(Stream stream, HttpListenerResponse response, bool i private void DisposeCore() { - byte[] bytes = null; - MemoryStream ms = GetHeaders(true); + byte[]? bytes = null; + MemoryStream? ms = GetHeaders(true); bool chunked = _response.SendChunked; if (_stream.CanWrite) { @@ -95,7 +95,7 @@ internal async Task WriteWebSocketHandshakeHeadersAsync() if (_stream.CanWrite) { - MemoryStream ms = GetHeaders(closing: false, isWebSocketHandshake: true); + MemoryStream ms = GetHeaders(closing: false, isWebSocketHandshake: true)!; bool chunked = _response.SendChunked; long start = ms.Position; @@ -111,7 +111,7 @@ internal async Task WriteWebSocketHandshakeHeadersAsync() } } - private MemoryStream GetHeaders(bool closing, bool isWebSocketHandshake = false) + private MemoryStream? GetHeaders(bool closing, bool isWebSocketHandshake = false) { // SendHeaders works on shared headers lock (_response._headersLock) @@ -171,8 +171,8 @@ private void WriteCore(byte[] buffer, int offset, int size) if (size == 0) return; - byte[] bytes = null; - MemoryStream ms = GetHeaders(false); + byte[]? bytes = null; + MemoryStream? ms = GetHeaders(false); bool chunked = _response.SendChunked; if (ms != null) { @@ -204,7 +204,7 @@ private void WriteCore(byte[] buffer, int offset, int size) InternalWrite(s_crlf, 0, 2); } - private IAsyncResult BeginWriteCore(byte[] buffer, int offset, int size, AsyncCallback cback, object state) + private IAsyncResult BeginWriteCore(byte[] buffer, int offset, int size, AsyncCallback? cback, object? state) { if (_closed) { @@ -215,8 +215,8 @@ private IAsyncResult BeginWriteCore(byte[] buffer, int offset, int size, AsyncCa return ares; } - byte[] bytes = null; - MemoryStream ms = GetHeaders(false); + byte[]? bytes = null; + MemoryStream? ms = GetHeaders(false); bool chunked = _response.SendChunked; if (ms != null) { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpStreamAsyncResult.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpStreamAsyncResult.cs index eea8e6b983454b..a92059b5373940 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpStreamAsyncResult.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/HttpStreamAsyncResult.cs @@ -36,17 +36,17 @@ namespace System.Net internal class HttpStreamAsyncResult : IAsyncResult { private object _locker = new object(); - private ManualResetEvent _handle; + private ManualResetEvent? _handle; private bool _completed; internal readonly object _parent; - internal byte[] _buffer; + internal byte[]? _buffer; internal int _offset; internal int _count; - internal AsyncCallback _callback; - internal object _state; + internal AsyncCallback? _callback; + internal object? _state; internal int _synchRead; - internal Exception _error; + internal Exception? _error; internal bool _endCalled; internal HttpStreamAsyncResult(object parent) @@ -76,7 +76,7 @@ public void Complete() } } - public object AsyncState + public object? AsyncState { get { return _state; } } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ListenerAsyncResult.Managed.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ListenerAsyncResult.Managed.cs index 2cc49a1a97e47c..605a26fce8af98 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ListenerAsyncResult.Managed.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ListenerAsyncResult.Managed.cs @@ -37,20 +37,20 @@ namespace System.Net { internal class ListenerAsyncResult : IAsyncResult { - private ManualResetEvent _handle; + private ManualResetEvent? _handle; private bool _synch; private bool _completed; - private AsyncCallback _cb; - private object _state; - private Exception _exception; - private HttpListenerContext _context; + private AsyncCallback? _cb; + private object? _state; + private Exception? _exception; + private HttpListenerContext? _context; private object _locker = new object(); - private ListenerAsyncResult _forward; + private ListenerAsyncResult? _forward; internal readonly HttpListener _parent; internal bool _endCalled; internal bool _inGet; - public ListenerAsyncResult(HttpListener parent, AsyncCallback cb, object state) + public ListenerAsyncResult(HttpListener parent, AsyncCallback? cb, object? state) { _parent = parent; _cb = cb; @@ -78,10 +78,10 @@ internal void Complete(Exception exc) } } - private static WaitCallback s_invokeCB = new WaitCallback(InvokeCallback); + private static WaitCallback s_invokeCB = new WaitCallback(InvokeCallback!); private static void InvokeCallback(object o) { - ListenerAsyncResult ares = (ListenerAsyncResult)o; + ListenerAsyncResult ares = (ListenerAsyncResult)o!; if (ares._forward != null) { InvokeCallback(ares._forward); @@ -89,7 +89,7 @@ private static void InvokeCallback(object o) } try { - ares._cb(ares); + ares._cb!(ares); } catch { @@ -115,7 +115,7 @@ internal void Complete(HttpListenerContext context, bool synch) bool authFailure = false; try { - context.AuthenticationSchemes = context._listener.SelectAuthenticationScheme(context); + context.AuthenticationSchemes = context._listener!.SelectAuthenticationScheme(context); } catch (OutOfMemoryException oom) { @@ -138,17 +138,17 @@ internal void Complete(HttpListenerContext context, bool synch) else if (context.AuthenticationSchemes == AuthenticationSchemes.Basic) { HttpStatusCode errorCode = HttpStatusCode.Unauthorized; - string authHeader = context.Request.Headers["Authorization"]; + string? authHeader = context.Request.Headers["Authorization"]; if (authHeader == null || !HttpListenerContext.IsBasicHeader(authHeader) || authHeader.Length < AuthenticationTypes.Basic.Length + 2 || - !HttpListenerContext.TryParseBasicAuth(authHeader.Substring(AuthenticationTypes.Basic.Length + 1), out errorCode, out string _, out string __)) + !HttpListenerContext.TryParseBasicAuth(authHeader.Substring(AuthenticationTypes.Basic.Length + 1), out errorCode, out _, out _)) { authFailure = true; context.Response.StatusCode = (int)errorCode; if (errorCode == HttpStatusCode.Unauthorized) { - context.Response.Headers["WWW-Authenticate"] = context.AuthenticationSchemes + " realm=\"" + context._listener.Realm + "\""; + context.Response.Headers["WWW-Authenticate"] = context.AuthenticationSchemes + " realm=\"" + context._listener!.Realm + "\""; } } } @@ -156,7 +156,7 @@ internal void Complete(HttpListenerContext context, bool synch) if (authFailure) { context.Response.OutputStream.Close(); - IAsyncResult ares = context._listener.BeginGetContext(_cb, _state); + IAsyncResult ares = context._listener!.BeginGetContext(_cb, _state); _forward = (ListenerAsyncResult)ares; lock (_forward._locker) { @@ -185,7 +185,7 @@ internal void Complete(HttpListenerContext context, bool synch) } } - internal HttpListenerContext GetContext() + internal HttpListenerContext? GetContext() { if (_forward != null) { @@ -200,7 +200,7 @@ internal HttpListenerContext GetContext() return _context; } - public object AsyncState + public object? AsyncState { get { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ListenerPrefix.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ListenerPrefix.cs index a0b19d6802e8fb..576e345047b538 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ListenerPrefix.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/ListenerPrefix.cs @@ -34,12 +34,12 @@ namespace System.Net internal sealed class ListenerPrefix { private string _original; - private string _host; + private string? _host; private ushort _port; - private string _path; + private string? _path; private bool _secure; - private IPAddress[] _addresses; - internal HttpListener _listener; + private IPAddress[]? _addresses; + internal HttpListener? _listener; public ListenerPrefix(string prefix) { @@ -52,7 +52,7 @@ public override string ToString() return _original; } - public IPAddress[] Addresses + public IPAddress[]? Addresses { get { return _addresses; } set { _addresses = value; } @@ -62,7 +62,7 @@ public bool Secure get { return _secure; } } - public string Host + public string? Host { get { return _host; } } @@ -72,15 +72,15 @@ public int Port get { return _port; } } - public string Path + public string? Path { get { return _path; } } // Equals and GetHashCode are required to detect duplicates in HttpListenerPrefixCollection. - public override bool Equals(object o) + public override bool Equals(object? o) { - ListenerPrefix other = o as ListenerPrefix; + ListenerPrefix? other = o as ListenerPrefix; if (other == null) return false; diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/WebSockets/HttpWebSocket.Managed.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/WebSockets/HttpWebSocket.Managed.cs index 2f7d076bbc881d..bd3e39231cda68 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Managed/WebSockets/HttpWebSocket.Managed.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Managed/WebSockets/HttpWebSocket.Managed.cs @@ -22,12 +22,12 @@ internal static async Task AcceptWebSocketAsyncCor HttpListenerRequest request = context.Request; ValidateWebSocketHeaders(context); - string secWebSocketVersion = request.Headers[HttpKnownHeaderNames.SecWebSocketVersion]; + string? secWebSocketVersion = request.Headers[HttpKnownHeaderNames.SecWebSocketVersion]; // Optional for non-browser client - string origin = request.Headers[HttpKnownHeaderNames.Origin]; + string? origin = request.Headers[HttpKnownHeaderNames.Origin]; - string[] secWebSocketProtocols = null; + string[]? secWebSocketProtocols = null; string outgoingSecWebSocketProtocolString; bool shouldSendSecWebSocketProtocolHeader = ProcessWebSocketProtocolHeader( @@ -42,7 +42,7 @@ internal static async Task AcceptWebSocketAsyncCor } // negotiate the websocket key return value - string secWebSocketKey = request.Headers[HttpKnownHeaderNames.SecWebSocketKey]; + string? secWebSocketKey = request.Headers[HttpKnownHeaderNames.SecWebSocketKey]; string secWebSocketAccept = HttpWebSocket.GetSecWebSocketAcceptString(secWebSocketKey); response.Headers.Add(HttpKnownHeaderNames.Connection, HttpKnownHeaderNames.Upgrade); @@ -50,9 +50,9 @@ internal static async Task AcceptWebSocketAsyncCor response.Headers.Add(HttpKnownHeaderNames.SecWebSocketAccept, secWebSocketAccept); response.StatusCode = (int)HttpStatusCode.SwitchingProtocols; // HTTP 101 - response.StatusDescription = HttpStatusDescription.Get(HttpStatusCode.SwitchingProtocols); + response.StatusDescription = HttpStatusDescription.Get(HttpStatusCode.SwitchingProtocols)!; - HttpResponseStream responseStream = response.OutputStream as HttpResponseStream; + HttpResponseStream responseStream = (response.OutputStream as HttpResponseStream)!; // Send websocket handshake headers await responseStream.WriteWebSocketHandshakeHeadersAsync().ConfigureAwait(false); @@ -60,17 +60,17 @@ internal static async Task AcceptWebSocketAsyncCor WebSocket webSocket = WebSocket.CreateFromStream(context.Connection.ConnectedStream, isServer:true, subProtocol, keepAliveInterval); HttpListenerWebSocketContext webSocketContext = new HttpListenerWebSocketContext( - request.Url, + request.Url!, request.Headers, request.Cookies, - context.User, + context.User!, request.IsAuthenticated, request.IsLocal, request.IsSecureConnection, - origin, + origin!, secWebSocketProtocols != null ? secWebSocketProtocols : Array.Empty(), - secWebSocketVersion, - secWebSocketKey, + secWebSocketVersion!, + secWebSocketKey!, webSocket); return webSocketContext; diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/ServiceNameStore.cs b/src/libraries/System.Net.HttpListener/src/System/Net/ServiceNameStore.cs index 15cd3dbb5d7667..9c92cf20bb5a5c 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/ServiceNameStore.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/ServiceNameStore.cs @@ -12,7 +12,7 @@ namespace System.Net internal class ServiceNameStore { private readonly List _serviceNames; - private ServiceNameCollection _serviceNameCollection; + private ServiceNameCollection? _serviceNameCollection; public ServiceNameCollection ServiceNames { @@ -32,7 +32,7 @@ public ServiceNameStore() _serviceNameCollection = null; // set only when needed (due to expensive item-by-item copy) } - private static string NormalizeServiceName(string inputServiceName) + private static string? NormalizeServiceName(string? inputServiceName) { if (string.IsNullOrWhiteSpace(inputServiceName)) { @@ -108,7 +108,7 @@ private static string NormalizeServiceName(string inputServiceName) // Now we have a valid DNS host, normalize it. - Uri constructedUri; + Uri? constructedUri; // This shouldn't fail, but we need to avoid any unexpected exceptions on this code path. if (!Uri.TryCreate(Uri.UriSchemeHttp + Uri.SchemeDelimiter + host, UriKind.Absolute, out constructedUri)) { @@ -132,7 +132,7 @@ private static string NormalizeServiceName(string inputServiceName) private bool AddSingleServiceName(string spn) { - spn = NormalizeServiceName(spn); + spn = NormalizeServiceName(spn)!; if (Contains(spn)) { return false; @@ -177,13 +177,13 @@ public bool Remove(string uriPrefix) { Debug.Assert(!string.IsNullOrEmpty(uriPrefix)); - string newServiceName = BuildSimpleServiceName(uriPrefix); + string? newServiceName = BuildSimpleServiceName(uriPrefix); newServiceName = NormalizeServiceName(newServiceName); bool needToRemove = Contains(newServiceName); if (needToRemove) { - _serviceNames.Remove(newServiceName); + _serviceNames.Remove(newServiceName!); _serviceNameCollection = null; //invalidate (readonly) ServiceNameCollection } @@ -203,7 +203,7 @@ public bool Remove(string uriPrefix) } // Assumes already normalized - private bool Contains(string newServiceName) + private bool Contains(string? newServiceName) { if (newServiceName == null) { @@ -227,7 +227,7 @@ public void Clear() _serviceNameCollection = null; //invalidate (readonly) ServiceNameCollection } - private string ExtractHostname(string uriPrefix, bool allowInvalidUriStrings) + private string? ExtractHostname(string uriPrefix, bool allowInvalidUriStrings) { if (Uri.IsWellFormedUriString(uriPrefix, UriKind.Absolute)) { @@ -264,9 +264,9 @@ private string ExtractHostname(string uriPrefix, bool allowInvalidUriStrings) return null; } - public string BuildSimpleServiceName(string uriPrefix) + public string? BuildSimpleServiceName(string uriPrefix) { - string hostname = ExtractHostname(uriPrefix, false); + string? hostname = ExtractHostname(uriPrefix, false); if (hostname != null) { @@ -280,9 +280,9 @@ public string BuildSimpleServiceName(string uriPrefix) public string[] BuildServiceNames(string uriPrefix) { - string hostname = ExtractHostname(uriPrefix, true); + string hostname = ExtractHostname(uriPrefix, true)!; - IPAddress ipAddress = null; + IPAddress? ipAddress = null; if (string.Equals(hostname, "*", StringComparison.OrdinalIgnoreCase) || string.Equals(hostname, "+", StringComparison.OrdinalIgnoreCase) || IPAddress.TryParse(hostname, out ipAddress)) diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/WebSockets/HttpListenerWebSocketContext.cs b/src/libraries/System.Net.HttpListener/src/System/Net/WebSockets/HttpListenerWebSocketContext.cs index 7f6ea23f352e26..31134051bf0e6c 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/WebSockets/HttpListenerWebSocketContext.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/WebSockets/HttpListenerWebSocketContext.cs @@ -49,7 +49,7 @@ internal HttpListenerWebSocketContext( _cookieCollection.Add(cookieCollection); _headers = new NameValueCollection(headers); - _user = CopyPrincipal(user); + _user = CopyPrincipal(user)!; _requestUri = requestUri; _isAuthenticated = isAuthenticated; @@ -86,7 +86,7 @@ internal HttpListenerWebSocketContext( public override WebSocket WebSocket => _webSocket; - private static IPrincipal CopyPrincipal(IPrincipal user) + private static IPrincipal? CopyPrincipal(IPrincipal user) { if (user != null) { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/WebSockets/HttpWebSocket.cs b/src/libraries/System.Net.HttpListener/src/System/Net/WebSockets/HttpWebSocket.cs index f89b58f38148b0..56a11e43b1afe1 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/WebSockets/HttpWebSocket.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/WebSockets/HttpWebSocket.cs @@ -16,7 +16,7 @@ internal static partial class HttpWebSocket internal const int DefaultClientSendBufferSize = 16 * 1024; [SuppressMessage("Microsoft.Security", "CA5350", Justification = "SHA1 used only for hashing purposes, not for crypto.")] - internal static string GetSecWebSocketAcceptString(string secWebSocketKey) + internal static string GetSecWebSocketAcceptString(string? secWebSocketKey) { string acceptString = string.Concat(secWebSocketKey, HttpWebSocket.SecWebSocketKeyGuid); byte[] toHash = Encoding.UTF8.GetBytes(acceptString); @@ -27,7 +27,7 @@ internal static string GetSecWebSocketAcceptString(string secWebSocketKey) } // return value here signifies if a Sec-WebSocket-Protocol header should be returned by the server. - internal static bool ProcessWebSocketProtocolHeader(string clientSecWebSocketProtocol, + internal static bool ProcessWebSocketProtocolHeader(string? clientSecWebSocketProtocol, string subProtocol, out string acceptProtocol) { @@ -142,7 +142,7 @@ private static void ValidateWebSocketHeaders(HttpListenerContext context) context.Request.Headers[HttpKnownHeaderNames.Upgrade])); } - string secWebSocketVersion = context.Request.Headers[HttpKnownHeaderNames.SecWebSocketVersion]; + string? secWebSocketVersion = context.Request.Headers[HttpKnownHeaderNames.SecWebSocketVersion]; if (string.IsNullOrEmpty(secWebSocketVersion)) { throw new WebSocketException(WebSocketError.HeaderError, @@ -160,14 +160,14 @@ private static void ValidateWebSocketHeaders(HttpListenerContext context) SupportedVersion)); } - string secWebSocketKey = context.Request.Headers[HttpKnownHeaderNames.SecWebSocketKey]; + string? secWebSocketKey = context.Request.Headers[HttpKnownHeaderNames.SecWebSocketKey]; bool isSecWebSocketKeyInvalid = string.IsNullOrWhiteSpace(secWebSocketKey); if (!isSecWebSocketKeyInvalid) { try { // key must be 16 bytes then base64-encoded - isSecWebSocketKeyInvalid = Convert.FromBase64String(secWebSocketKey).Length != 16; + isSecWebSocketKeyInvalid = Convert.FromBase64String(secWebSocketKey!).Length != 16; } catch { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/AsyncRequestContext.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/AsyncRequestContext.cs index 6ebe7a36d744ab..8af3aa485366f7 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/AsyncRequestContext.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/AsyncRequestContext.cs @@ -10,7 +10,7 @@ namespace System.Net internal sealed unsafe class AsyncRequestContext : RequestContextBase { private NativeOverlapped* _nativeOverlapped; - private ThreadPoolBoundHandle _boundHandle; + private ThreadPoolBoundHandle? _boundHandle; private readonly ListenerAsyncResult _result; #if DEBUG @@ -46,7 +46,7 @@ internal AsyncRequestContext(ThreadPoolBoundHandle boundHandle, ListenerAsyncRes NativeOverlapped* nativeOverlapped = _nativeOverlapped; _nativeOverlapped = null; - _boundHandle.FreeNativeOverlapped(nativeOverlapped); + _boundHandle!.FreeNativeOverlapped(nativeOverlapped); } #if DEBUG @@ -75,7 +75,7 @@ protected override void OnReleasePins() NativeOverlapped* nativeOverlapped = _nativeOverlapped; _nativeOverlapped = null; - _boundHandle.FreeNativeOverlapped(nativeOverlapped); + _boundHandle!.FreeNativeOverlapped(nativeOverlapped); } } @@ -89,7 +89,7 @@ protected override void Dispose(bool disposing) #if DEBUG DebugRefCountReleaseNativeOverlapped(); #endif - _boundHandle.FreeNativeOverlapped(_nativeOverlapped); + _boundHandle!.FreeNativeOverlapped(_nativeOverlapped); } } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/CookieExtensions.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/CookieExtensions.cs index 30df21acf5161b..20e1fad79890ff 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/CookieExtensions.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/CookieExtensions.cs @@ -10,20 +10,20 @@ namespace System.Net // TODO https://github.com/dotnet/runtime/issues/19348 internal static class CookieExtensions { - private static Func s_toServerStringFunc; + private static Func? s_toServerStringFunc; public static string ToServerString(this Cookie cookie) { - s_toServerStringFunc ??= (Func)typeof(Cookie).GetMethod("ToServerString", BindingFlags.Instance | BindingFlags.NonPublic).CreateDelegate(typeof(Func)); + s_toServerStringFunc ??= (Func)typeof(Cookie).GetMethod("ToServerString", BindingFlags.Instance | BindingFlags.NonPublic)!.CreateDelegate(typeof(Func)); Debug.Assert(s_toServerStringFunc != null, "Reflection failed for Cookie.ToServerString()."); return s_toServerStringFunc(cookie); } - private static Func s_cloneFunc; + private static Func? s_cloneFunc; public static Cookie Clone(this Cookie cookie) { - s_cloneFunc ??= (Func)typeof(Cookie).GetMethod("Clone", BindingFlags.Instance | BindingFlags.NonPublic).CreateDelegate(typeof(Func)); + s_cloneFunc ??= (Func)typeof(Cookie).GetMethod("Clone", BindingFlags.Instance | BindingFlags.NonPublic)!.CreateDelegate(typeof(Func)); Debug.Assert(s_cloneFunc != null, "Reflection failed for Cookie.Clone()."); return s_cloneFunc(cookie); } @@ -37,11 +37,11 @@ private enum CookieVariant Default = Rfc2109 } - private static Func s_getVariantFunc; + private static Func? s_getVariantFunc; public static bool IsRfc2965Variant(this Cookie cookie) { - s_getVariantFunc ??= (Func)typeof(Cookie).GetProperty("Variant", BindingFlags.Instance | BindingFlags.NonPublic).GetGetMethod(true).CreateDelegate(typeof(Func)); + s_getVariantFunc ??= (Func)typeof(Cookie).GetProperty("Variant", BindingFlags.Instance | BindingFlags.NonPublic)!.GetGetMethod(true)!.CreateDelegate(typeof(Func)); Debug.Assert(s_getVariantFunc != null, "Reflection failed for Cookie.Variant."); return s_getVariantFunc(cookie) == CookieVariant.Rfc2965; } @@ -49,11 +49,11 @@ public static bool IsRfc2965Variant(this Cookie cookie) internal static class CookieCollectionExtensions { - private static Func s_internalAddFunc; + private static Func? s_internalAddFunc; public static int InternalAdd(this CookieCollection cookieCollection, Cookie cookie, bool isStrict) { - s_internalAddFunc ??= (Func)typeof(CookieCollection).GetMethod("InternalAdd", BindingFlags.Instance | BindingFlags.NonPublic).CreateDelegate(typeof(Func)); + s_internalAddFunc ??= (Func)typeof(CookieCollection).GetMethod("InternalAdd", BindingFlags.Instance | BindingFlags.NonPublic)!.CreateDelegate(typeof(Func)); Debug.Assert(s_internalAddFunc != null, "Reflection failed for CookieCollection.InternalAdd()."); return s_internalAddFunc(cookieCollection, cookie, isStrict); } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListener.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListener.Windows.cs index 75be134af2abe0..febae88fa32cb7 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListener.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListener.Windows.cs @@ -41,15 +41,15 @@ public sealed unsafe partial class HttpListener (byte) 'e', (byte) 'n', (byte) 't', (byte) 'i', (byte) 'c', (byte) 'a', (byte) 't', (byte) 'e' }; - private HttpListenerSession _currentSession; + private HttpListenerSession? _currentSession; private bool _unsafeConnectionNtlmAuthentication; - private HttpServerSessionHandle _serverSessionHandle; + private HttpServerSessionHandle? _serverSessionHandle; private ulong _urlGroupId; private bool _V2Initialized; - private Dictionary _disconnectResults; + private Dictionary? _disconnectResults; private void ValidateV2Property() { @@ -312,7 +312,7 @@ private void AttachRequestQueueToUrlGroup() // get delivered to this request queue. Interop.HttpApi.HTTP_BINDING_INFO info = default; info.Flags = Interop.HttpApi.HTTP_FLAGS.HTTP_PROPERTY_FLAG_PRESENT; - info.RequestQueueHandle = _currentSession.RequestQueueHandle.DangerousGetHandle(); + info.RequestQueueHandle = _currentSession!.RequestQueueHandle.DangerousGetHandle(); IntPtr infoptr = new IntPtr(&info); @@ -489,8 +489,8 @@ private void AddPrefixCore(string registeredPrefix) public HttpListenerContext GetContext() { - SyncRequestContext memoryBlob = null; - HttpListenerContext httpContext = null; + SyncRequestContext? memoryBlob = null; + HttpListenerContext? httpContext = null; bool stoleBlob = false; try @@ -508,7 +508,7 @@ public HttpListenerContext GetContext() uint size = 4096; ulong requestId = 0; memoryBlob = new SyncRequestContext((int)size); - HttpListenerSession session = _currentSession; + HttpListenerSession session = _currentSession!; while (true) { @@ -609,7 +609,7 @@ internal static unsafe bool ValidateRequest(HttpListenerSession session, Request public IAsyncResult BeginGetContext(AsyncCallback callback, object state) { - ListenerAsyncResult asyncResult = null; + ListenerAsyncResult? asyncResult = null; try { CheckDisposed(); @@ -620,7 +620,7 @@ public IAsyncResult BeginGetContext(AsyncCallback callback, object state) // prepare the ListenerAsyncResult object (this will have it's own // event that the user can wait on for IO completion - which means we // need to signal it when IO completes) - asyncResult = new ListenerAsyncResult(_currentSession, state, callback); + asyncResult = new ListenerAsyncResult(_currentSession!, state, callback); uint statusCode = asyncResult.QueueBeginGetContext(); if (statusCode != Interop.HttpApi.ERROR_SUCCESS && statusCode != Interop.HttpApi.ERROR_IO_PENDING) @@ -641,7 +641,7 @@ public IAsyncResult BeginGetContext(AsyncCallback callback, object state) public HttpListenerContext EndGetContext(IAsyncResult asyncResult) { - HttpListenerContext httpContext = null; + HttpListenerContext? httpContext = null; try { CheckDisposed(); @@ -663,7 +663,7 @@ public HttpListenerContext EndGetContext(IAsyncResult asyncResult) if (httpContext == null) { Debug.Assert(castedAsyncResult.Result is Exception, "EndGetContext|The result is neither a HttpListenerContext nor an Exception."); - ExceptionDispatchInfo.Throw(castedAsyncResult.Result as Exception); + ExceptionDispatchInfo.Throw((castedAsyncResult.Result as Exception)!); } } catch (Exception exception) @@ -674,15 +674,15 @@ public HttpListenerContext EndGetContext(IAsyncResult asyncResult) return httpContext; } - internal HttpListenerContext HandleAuthentication(HttpListenerSession session, RequestContextBase memoryBlob, out bool stoleBlob) + internal HttpListenerContext? HandleAuthentication(HttpListenerSession session, RequestContextBase memoryBlob, out bool stoleBlob) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "HandleAuthentication() memoryBlob:0x" + ((IntPtr)memoryBlob.RequestBlob).ToString("x")); - string challenge = null; + string? challenge = null; stoleBlob = false; // Some things we need right away. Lift them out now while it's convenient. - string authorizationHeader = Interop.HttpApi.GetKnownHeader(memoryBlob.RequestBlob, (int)HttpRequestHeader.Authorization); + string? authorizationHeader = Interop.HttpApi.GetKnownHeader(memoryBlob.RequestBlob, (int)HttpRequestHeader.Authorization); ulong connectionId = memoryBlob.RequestBlob->ConnectionId; ulong requestId = memoryBlob.RequestBlob->RequestId; bool isSecureConnection = memoryBlob.RequestBlob->pSslInfo != null; @@ -694,13 +694,13 @@ internal HttpListenerContext HandleAuthentication(HttpListenerSession session, R // previously authenticated. // assurance that we do this only for NTLM/Negotiate is not here, but in the // code that caches WindowsIdentity instances in the Dictionary. - DisconnectAsyncResult disconnectResult; + DisconnectAsyncResult? disconnectResult; DisconnectResults.TryGetValue(connectionId, out disconnectResult); if (UnsafeConnectionNtlmAuthentication) { if (authorizationHeader == null) { - WindowsPrincipal principal = disconnectResult?.AuthenticatedConnection; + WindowsPrincipal? principal = disconnectResult?.AuthenticatedConnection; if (principal != null) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Principal: {principal} principal.Identity.Name: {principal.Identity.Name} creating request"); @@ -724,10 +724,10 @@ internal HttpListenerContext HandleAuthentication(HttpListenerSession session, R // Figure out what schemes we're allowing, what context we have. stoleBlob = true; - HttpListenerContext httpContext = null; - NTAuthentication oldContext = null; - NTAuthentication newContext = null; - NTAuthentication context = null; + HttpListenerContext? httpContext = null; + NTAuthentication? oldContext = null; + NTAuthentication? newContext = null; + NTAuthentication? context = null; AuthenticationSchemes headerScheme = AuthenticationSchemes.None; AuthenticationSchemes authenticationScheme = AuthenticationSchemes; ExtendedProtectionPolicy extendedProtectionPolicy = _extendedProtectionPolicy; @@ -748,7 +748,7 @@ internal HttpListenerContext HandleAuthentication(HttpListenerSession session, R httpContext = new HttpListenerContext(session, memoryBlob); - AuthenticationSchemeSelector authenticationSelector = _authenticationDelegate; + AuthenticationSchemeSelector? authenticationSelector = _authenticationDelegate; if (authenticationSelector != null) { try @@ -778,7 +778,7 @@ internal HttpListenerContext HandleAuthentication(HttpListenerSession session, R stoleBlob = false; } - ExtendedProtectionSelector extendedProtectionSelector = _extendedProtectionSelectorDelegate; + ExtendedProtectionSelector? extendedProtectionSelector = _extendedProtectionSelectorDelegate; if (extendedProtectionSelector != null) { extendedProtectionPolicy = extendedProtectionSelector(httpContext.Request); @@ -856,12 +856,13 @@ internal HttpListenerContext HandleAuthentication(HttpListenerSession session, R else { // Perform Authentication - byte[] bytes = null; - byte[] decodedOutgoingBlob = null; - string outBlob = null; + byte[]? bytes = null; + byte[]? decodedOutgoingBlob = null; + string? outBlob = null; // Find the beginning of the blob. Trust that HTTP.SYS parsed out just our header ok. - for (index++; index < authorizationHeader.Length; index++) + Debug.Assert(authorizationHeader != null); + for (index++; index < authorizationHeader!.Length; index++) { if (authorizationHeader[index] != ' ' && authorizationHeader[index] != '\t' && authorizationHeader[index] != '\r' && authorizationHeader[index] != '\n') @@ -871,9 +872,9 @@ internal HttpListenerContext HandleAuthentication(HttpListenerSession session, R } string inBlob = index < authorizationHeader.Length ? authorizationHeader.Substring(index) : ""; - IPrincipal principal = null; + IPrincipal? principal = null; SecurityStatusPal statusCodeNew; - ChannelBinding binding; + ChannelBinding? binding; if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Performing Authentication headerScheme: {headerScheme}"); switch (headerScheme) { @@ -934,7 +935,7 @@ internal HttpListenerContext HandleAuthentication(HttpListenerSession session, R { if (context.IsCompleted) { - SecurityContextTokenHandle userContext = null; + SecurityContextTokenHandle? userContext = null; try { if (!CheckSpn(context, isSecureConnection, extendedProtectionPolicy)) @@ -945,7 +946,7 @@ internal HttpListenerContext HandleAuthentication(HttpListenerSession session, R { httpContext.Request.ServiceName = context.ClientSpecifiedSpn; - SafeDeleteContext securityContext = context.GetContext(out statusCodeNew); + SafeDeleteContext securityContext = context.GetContext(out statusCodeNew)!; if (statusCodeNew.ErrorCode != SecurityStatusPalErrorCode.OK) { if (NetEventSource.Log.IsEnabled()) @@ -1063,7 +1064,7 @@ internal HttpListenerContext HandleAuthentication(HttpListenerSession session, R { if (NetEventSource.Log.IsEnabled()) { - NetEventSource.Info(this, $"Got principal: {principal}, IdentityName: {principal.Identity.Name} for creating request."); + NetEventSource.Info(this, $"Got principal: {principal}, IdentityName: {principal!.Identity!.Name} for creating request."); } httpContext.SetIdentity(principal, outBlob); @@ -1080,7 +1081,7 @@ internal HttpListenerContext HandleAuthentication(HttpListenerSession session, R } // if we're not giving a request to the application, we need to send an error - ArrayList challenges = null; + ArrayList? challenges = null; if (httpContext == null) { // If we already have a challenge, just use it. Otherwise put a challenge for each acceptable scheme. @@ -1166,9 +1167,11 @@ internal HttpListenerContext HandleAuthentication(HttpListenerSession session, R context = null; } - NTAuthentication toClose = oldContext; + NTAuthentication? toClose = oldContext; oldContext = newContext; - disconnectResult.Session = newContext; + // TODO: Can disconnectResult be null here? + Debug.Assert(disconnectResult != null); + disconnectResult!.Session = newContext; if (toClose != null) { @@ -1249,7 +1252,7 @@ internal HttpListenerContext HandleAuthentication(HttpListenerSession session, R } } - private static void FreeContext(ref HttpListenerContext httpContext, RequestContextBase memoryBlob) + private static void FreeContext(ref HttpListenerContext? httpContext, RequestContextBase memoryBlob) { if (httpContext != null) { @@ -1270,8 +1273,8 @@ internal void SetAuthenticationHeaders(HttpListenerContext context) HttpListenerResponse response = context.Response; // We use the cached results from the delegates so that we don't have to call them again here. - NTAuthentication newContext; - ArrayList challenges = BuildChallenge(context.AuthenticationSchemes, request._connectionId, + NTAuthentication? newContext; + ArrayList? challenges = BuildChallenge(context.AuthenticationSchemes, request._connectionId, out newContext, context.ExtendedProtectionPolicy, request.IsSecureConnection); // Setting 401 without setting WWW-Authenticate is a protocol violation @@ -1286,7 +1289,7 @@ internal void SetAuthenticationHeaders(HttpListenerContext context) } } - private ChannelBinding GetChannelBinding(HttpListenerSession session, ulong connectionId, bool isSecureConnection, ExtendedProtectionPolicy policy) + private ChannelBinding? GetChannelBinding(HttpListenerSession session, ulong connectionId, bool isSecureConnection, ExtendedProtectionPolicy policy) { if (policy.PolicyEnforcement == PolicyEnforcement.Never) { @@ -1306,7 +1309,7 @@ private ChannelBinding GetChannelBinding(HttpListenerSession session, ulong conn return null; } - ChannelBinding result = GetChannelBindingFromTls(session, connectionId); + ChannelBinding? result = GetChannelBindingFromTls(session, connectionId); if (NetEventSource.Log.IsEnabled() && result != null) NetEventSource.Info(this, "GetChannelBindingFromTls returned null even though OS supposedly supports Extended Protection"); @@ -1345,7 +1348,7 @@ private bool CheckSpn(NTAuthentication context, bool isSecureConnection, Extende return true; } - string clientSpn = context.ClientSpecifiedSpn; + string? clientSpn = context.ClientSpecifiedSpn; // An empty SPN is only allowed in the WhenSupported case if (string.IsNullOrEmpty(clientSpn)) @@ -1512,7 +1515,7 @@ internal static bool IsClientFault(SecurityStatusPalErrorCode error) error == SecurityStatusPalErrorCode.UnsupportedPreauth; } - private static void AddChallenge(ref ArrayList challenges, string challenge) + private static void AddChallenge(ref ArrayList? challenges, string challenge) { if (challenge != null) { @@ -1529,11 +1532,11 @@ private static void AddChallenge(ref ArrayList challenges, string challenge) } } - private ArrayList BuildChallenge(AuthenticationSchemes authenticationScheme, ulong connectionId, - out NTAuthentication newContext, ExtendedProtectionPolicy policy, bool isSecureConnection) + private ArrayList? BuildChallenge(AuthenticationSchemes authenticationScheme, ulong connectionId, + out NTAuthentication? newContext, ExtendedProtectionPolicy policy, bool isSecureConnection) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "AuthenticationScheme:" + authenticationScheme.ToString()); - ArrayList challenges = null; + ArrayList? challenges = null; newContext = null; if ((authenticationScheme & AuthenticationSchemes.Negotiate) != 0) @@ -1554,7 +1557,7 @@ private ArrayList BuildChallenge(AuthenticationSchemes authenticationScheme, ulo return challenges; } - private static void RegisterForDisconnectNotification(HttpListenerSession session, ulong connectionId, ref DisconnectAsyncResult disconnectResult) + private static void RegisterForDisconnectNotification(HttpListenerSession session, ulong connectionId, ref DisconnectAsyncResult? disconnectResult) { Debug.Assert(disconnectResult == null); @@ -1593,7 +1596,7 @@ private static void RegisterForDisconnectNotification(HttpListenerSession sessio } } - private static void SendError(HttpListenerSession session, ulong requestId, HttpStatusCode httpStatusCode, ArrayList challenges) + private static void SendError(HttpListenerSession session, ulong requestId, HttpStatusCode httpStatusCode, ArrayList? challenges) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(session.Listener, $"RequestId: {requestId}"); Interop.HttpApi.HTTP_RESPONSE httpResponse = default; @@ -1601,10 +1604,10 @@ private static void SendError(HttpListenerSession session, ulong requestId, Http httpResponse.Version.MajorVersion = (ushort)1; httpResponse.Version.MinorVersion = (ushort)1; httpResponse.StatusCode = (ushort)httpStatusCode; - string statusDescription = HttpStatusDescription.Get(httpStatusCode); + string? statusDescription = HttpStatusDescription.Get(httpStatusCode); uint DataWritten = 0; uint statusCode; - byte[] byteReason = Encoding.Default.GetBytes(statusDescription); + byte[] byteReason = Encoding.Default.GetBytes(statusDescription!); fixed (byte* pReason = byteReason) { httpResponse.pReason = (sbyte*)pReason; @@ -1617,8 +1620,8 @@ private static void SendError(HttpListenerSession session, ulong requestId, Http (&httpResponse.Headers.KnownHeaders)[(int)HttpResponseHeader.ContentLength].RawValueLength = (ushort)byteContentLength.Length; httpResponse.Headers.UnknownHeaderCount = checked((ushort)(challenges == null ? 0 : challenges.Count)); - GCHandle[] challengeHandles = null; - Interop.HttpApi.HTTP_UNKNOWN_HEADER[] headersArray = null; + GCHandle[]? challengeHandles = null; + Interop.HttpApi.HTTP_UNKNOWN_HEADER[]? headersArray = null; GCHandle headersArrayHandle = default; GCHandle wwwAuthenticateHandle = default; if (httpResponse.Headers.UnknownHeaderCount > 0) @@ -1632,15 +1635,15 @@ private static void SendError(HttpListenerSession session, ulong requestId, Http if (httpResponse.Headers.UnknownHeaderCount > 0) { headersArrayHandle = GCHandle.Alloc(headersArray, GCHandleType.Pinned); - httpResponse.Headers.pUnknownHeaders = (Interop.HttpApi.HTTP_UNKNOWN_HEADER*)Marshal.UnsafeAddrOfPinnedArrayElement(headersArray, 0); + httpResponse.Headers.pUnknownHeaders = (Interop.HttpApi.HTTP_UNKNOWN_HEADER*)Marshal.UnsafeAddrOfPinnedArrayElement(headersArray!, 0); wwwAuthenticateHandle = GCHandle.Alloc(s_wwwAuthenticateBytes, GCHandleType.Pinned); sbyte* wwwAuthenticate = (sbyte*)Marshal.UnsafeAddrOfPinnedArrayElement(s_wwwAuthenticateBytes, 0); - for (int i = 0; i < challengeHandles.Length; i++) + for (int i = 0; i < challengeHandles!.Length; i++) { - byte[] byteChallenge = Encoding.Default.GetBytes((string)challenges[i]); + byte[] byteChallenge = Encoding.Default.GetBytes((string)challenges![i]!); challengeHandles[i] = GCHandle.Alloc(byteChallenge, GCHandleType.Pinned); - headersArray[i].pName = wwwAuthenticate; + headersArray![i].pName = wwwAuthenticate; headersArray[i].NameLength = (ushort)s_wwwAuthenticateBytes.Length; headersArray[i].pRawValue = (sbyte*)Marshal.UnsafeAddrOfPinnedArrayElement(byteChallenge, 0); headersArray[i].RawValueLength = checked((ushort)byteChallenge.Length); @@ -1708,7 +1711,7 @@ private static unsafe int GetTokenSizeFromBlob(IntPtr blob) return (int)((Interop.HttpApi.HTTP_REQUEST_CHANNEL_BIND_STATUS*)blob)->ChannelTokenSize; } - internal static ChannelBinding GetChannelBindingFromTls(HttpListenerSession session, ulong connectionId) + internal static ChannelBinding? GetChannelBindingFromTls(HttpListenerSession session, ulong connectionId) { // +128 since a CBT is usually <128 thus we need to call HRCC just once. If the CBT // is >128 we will get ERROR_MORE_DATA and call again @@ -1716,8 +1719,8 @@ internal static ChannelBinding GetChannelBindingFromTls(HttpListenerSession sess Debug.Assert(size > 0); - byte[] blob = null; - Interop.HttpApi.SafeLocalFreeChannelBinding token = null; + byte[]? blob = null; + Interop.HttpApi.SafeLocalFreeChannelBinding? token = null; uint bytesReceived = 0; uint statusCode; @@ -1786,8 +1789,8 @@ private class DisconnectAsyncResult : IAsyncResult private readonly NativeOverlapped* _nativeOverlapped; private int _ownershipState; // 0 = normal, 1 = in HandleAuthentication(), 2 = disconnected, 3 = cleaned up - private WindowsPrincipal _authenticatedConnection; - private NTAuthentication _session; + private WindowsPrincipal? _authenticatedConnection; + private NTAuthentication? _session; internal NativeOverlapped* NativeOverlapped { @@ -1882,7 +1885,7 @@ private static unsafe void WaitCallback(uint errorCode, uint numBytes, NativeOve { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"errorCode: {errorCode}, numBytes: {numBytes}, nativeOverlapped: {((IntPtr)nativeOverlapped).ToString("x")}"); // take the DisconnectAsyncResult object from the state - DisconnectAsyncResult asyncResult = (DisconnectAsyncResult)ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped); + DisconnectAsyncResult asyncResult = (DisconnectAsyncResult)ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped)!; IOCompleted(asyncResult, errorCode, numBytes, nativeOverlapped); } @@ -1900,9 +1903,9 @@ private void HandleDisconnect() // Clean up the identity. This is for scenarios where identity was not cleaned up before due to // identity caching for unsafe ntlm authentication - IDisposable identity = _authenticatedConnection == null ? null : _authenticatedConnection.Identity as IDisposable; + IDisposable? identity = _authenticatedConnection == null ? null : _authenticatedConnection.Identity as IDisposable; if ((identity != null) && - (_authenticatedConnection.Identity.AuthenticationType == AuthenticationTypes.NTLM) && + (_authenticatedConnection!.Identity.AuthenticationType == AuthenticationTypes.NTLM) && (listener.UnsafeConnectionNtlmAuthentication)) { identity.Dispose(); @@ -1912,7 +1915,7 @@ private void HandleDisconnect() Debug.Assert(oldValue == 2, $"Expected OwnershipState of 2, saw {oldValue}."); } - internal WindowsPrincipal AuthenticatedConnection + internal WindowsPrincipal? AuthenticatedConnection { get { @@ -1926,7 +1929,7 @@ internal WindowsPrincipal AuthenticatedConnection } } - internal NTAuthentication Session + internal NTAuthentication? Session { get { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerContext.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerContext.Windows.cs index e2bb4b982b8094..e3ff6294afaa7e 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerContext.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerContext.Windows.cs @@ -13,7 +13,7 @@ namespace System.Net { public sealed unsafe partial class HttpListenerContext { - private string _mutualAuthentication; + private string? _mutualAuthentication; internal HttpListenerSession ListenerSession { get; private set; } internal HttpListenerContext(HttpListenerSession session, RequestContextBase memoryBlob) @@ -28,7 +28,7 @@ internal HttpListenerContext(HttpListenerSession session, RequestContextBase mem } // Call this right after construction, and only once! Not after it's been handed to a user. - internal void SetIdentity(IPrincipal principal, string mutualAuthentication) + internal void SetIdentity(IPrincipal principal, string? mutualAuthentication) { _mutualAuthentication = mutualAuthentication; _user = principal; @@ -38,9 +38,9 @@ internal void SetIdentity(IPrincipal principal, string mutualAuthentication) // This can be used to cache the results of HttpListener.ExtendedProtectionSelectorDelegate. internal ExtendedProtectionPolicy ExtendedProtectionPolicy { get; set; } - internal string MutualAuthentication => _mutualAuthentication; + internal string? MutualAuthentication => _mutualAuthentication; - internal HttpListener Listener => _listener; + internal HttpListener? Listener => _listener; internal SafeHandle RequestQueueHandle => ListenerSession.RequestQueueHandle; @@ -88,12 +88,12 @@ internal void Close() } finally { - IDisposable user = _user == null ? null : _user.Identity as IDisposable; + IDisposable? user = _user == null ? null : _user.Identity as IDisposable; // For unsafe connection ntlm auth we dont dispose this identity as yet since its cached if ((user != null) && - (_user.Identity.AuthenticationType != NegotiationInfoClass.NTLM) && - (!_listener.UnsafeConnectionNtlmAuthentication)) + (_user!.Identity!.AuthenticationType != NegotiationInfoClass.NTLM) && + (!_listener!.UnsafeConnectionNtlmAuthentication)) { user.Dispose(); } @@ -139,13 +139,13 @@ internal void ForceCancelRequest(SafeHandle requestQueueHandle, ulong requestId) // The only way to cancel now is with CancelIoEx. if (statusCode == Interop.HttpApi.ERROR_CONNECTION_INVALID) { - _response.CancelLastWrite(requestQueueHandle); + _response!.CancelLastWrite(requestQueueHandle); } } internal void SetAuthenticationHeaders() { - Listener.SetAuthenticationHeaders(this); + Listener!.SetAuthenticationHeaders(this); } } } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequest.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequest.Windows.cs index 86629c7c596fb0..5000795ba543cd 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequest.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequest.Windows.cs @@ -21,22 +21,22 @@ public sealed unsafe partial class HttpListenerRequest private readonly ulong _requestId; internal ulong _connectionId; private readonly SslStatus _sslStatus; - private readonly string _cookedUrlHost; - private readonly string _cookedUrlPath; - private readonly string _cookedUrlQuery; + private readonly string? _cookedUrlHost; + private readonly string? _cookedUrlPath; + private readonly string? _cookedUrlQuery; private long _contentLength; - private Stream _requestStream; - private string _httpMethod; - private WebHeaderCollection _webHeaders; - private IPEndPoint _localEndPoint; - private IPEndPoint _remoteEndPoint; + private Stream? _requestStream; + private string? _httpMethod; + private WebHeaderCollection? _webHeaders; + private IPEndPoint? _localEndPoint; + private IPEndPoint? _remoteEndPoint; private BoundaryType _boundaryType; private int _clientCertificateError; - private RequestContextBase _memoryBlob; + private RequestContextBase? _memoryBlob; private readonly HttpListenerContext _httpContext; private bool _isDisposed; internal const uint CertBoblSize = 1500; - private string _serviceName; + private string? _serviceName; private enum SslStatus : byte { @@ -112,7 +112,7 @@ internal IntPtr RequestBuffer get { CheckDisposed(); - return _memoryBlob.RequestBuffer; + return _memoryBlob!.RequestBuffer; } } @@ -121,7 +121,7 @@ internal IntPtr OriginalBlobAddress get { CheckDisposed(); - return _memoryBlob.OriginalBlobAddress; + return _memoryBlob!.OriginalBlobAddress; } } @@ -129,7 +129,7 @@ internal IntPtr OriginalBlobAddress // disposed. internal void DetachBlob(RequestContextBase memoryBlob) { - if (memoryBlob != null && (object)memoryBlob == (object)_memoryBlob) + if (memoryBlob != null && (object)memoryBlob == (object)_memoryBlob!) { _memoryBlob = null; } @@ -138,7 +138,7 @@ internal void DetachBlob(RequestContextBase memoryBlob) // Finalizes ownership of the memory blob. DetachBlob can't be called after this. internal void ReleasePins() { - _memoryBlob.ReleasePins(); + _memoryBlob!.ReleasePins(); } internal ulong RequestId => _requestId; @@ -159,7 +159,7 @@ public long ContentLength64 { if (_boundaryType == BoundaryType.None) { - string transferEncodingHeader = Headers[HttpKnownHeaderNames.TransferEncoding]; + string? transferEncodingHeader = Headers[HttpKnownHeaderNames.TransferEncoding]; if (transferEncodingHeader != null && transferEncodingHeader.Equals("chunked", StringComparison.OrdinalIgnoreCase)) { _boundaryType = BoundaryType.Chunked; @@ -169,7 +169,7 @@ public long ContentLength64 { _contentLength = 0; _boundaryType = BoundaryType.ContentLength; - string length = Headers[HttpKnownHeaderNames.ContentLength]; + string? length = Headers[HttpKnownHeaderNames.ContentLength]; if (length != null) { bool success = long.TryParse(length, NumberStyles.None, CultureInfo.InvariantCulture.NumberFormat, out _contentLength); @@ -208,7 +208,7 @@ public string HttpMethod _httpMethod = Interop.HttpApi.GetVerb(RequestBuffer, OriginalBlobAddress); } if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"_httpMethod:{_httpMethod}"); - return _httpMethod; + return _httpMethod!; } } @@ -228,14 +228,14 @@ public bool IsAuthenticated { get { - IPrincipal user = HttpListenerContext.User; + IPrincipal? user = HttpListenerContext.User; return user != null && user.Identity != null && user.Identity.IsAuthenticated; } } public bool IsSecureConnection => _sslStatus != SslStatus.Insecure; - public string ServiceName + public string? ServiceName { get => _serviceName; internal set => _serviceName = value; @@ -252,15 +252,15 @@ internal void SetClientCertificateError(int clientCertificateError) _clientCertificateError = clientCertificateError; } - public X509Certificate2 EndGetClientCertificate(IAsyncResult asyncResult) + public X509Certificate2? EndGetClientCertificate(IAsyncResult asyncResult) { - X509Certificate2 clientCertificate = null; + X509Certificate2? clientCertificate = null; if (asyncResult == null) { throw new ArgumentNullException(nameof(asyncResult)); } - ListenerClientCertAsyncResult clientCertAsyncResult = asyncResult as ListenerClientCertAsyncResult; + ListenerClientCertAsyncResult? clientCertAsyncResult = asyncResult as ListenerClientCertAsyncResult; if (clientCertAsyncResult == null || clientCertAsyncResult.AsyncObject != this) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); @@ -297,7 +297,7 @@ public IPEndPoint RemoteEndPoint _remoteEndPoint = Interop.HttpApi.GetRemoteEndPoint(RequestBuffer, OriginalBlobAddress); } if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "_remoteEndPoint" + _remoteEndPoint); - return _remoteEndPoint; + return _remoteEndPoint!; } } @@ -310,14 +310,14 @@ public IPEndPoint LocalEndPoint _localEndPoint = Interop.HttpApi.GetLocalEndPoint(RequestBuffer, OriginalBlobAddress); } if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"_localEndPoint={_localEndPoint}"); - return _localEndPoint; + return _localEndPoint!; } } //should only be called from httplistenercontext internal void Close() { - RequestContextBase memoryBlob = _memoryBlob; + RequestContextBase? memoryBlob = _memoryBlob; if (memoryBlob != null) { memoryBlob.Close(); @@ -328,7 +328,7 @@ internal void Close() private ListenerClientCertAsyncResult BeginGetClientCertificateCore(AsyncCallback requestCallback, object state) { - ListenerClientCertAsyncResult asyncResult = null; + ListenerClientCertAsyncResult? asyncResult = null; //-------------------------------------------------------------------- //When you configure the HTTP.SYS with a flag value 2 //which means require client certificates, when the client makes the @@ -534,7 +534,7 @@ private Uri RequestUri if (_requestUri == null) { _requestUri = HttpListenerRequestUriBuilder.GetRequestUri( - _rawUrl, RequestScheme, _cookedUrlHost, _cookedUrlPath, _cookedUrlQuery); + _rawUrl!, RequestScheme, _cookedUrlHost!, _cookedUrlPath!, _cookedUrlQuery!); } if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"_requestUri:{_requestUri}"); @@ -542,7 +542,7 @@ private Uri RequestUri } } - internal ChannelBinding GetChannelBinding() + internal ChannelBinding? GetChannelBinding() { return HttpListener.GetChannelBindingFromTls(HttpListenerContext.ListenerSession, _connectionId); } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequestContext.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequestContext.cs index 97d2759fa10052..d49bc4aff1a7f0 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequestContext.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerRequestContext.cs @@ -24,7 +24,7 @@ public override ChannelBinding GetChannelBinding(ChannelBindingKind kind) throw new NotSupportedException(SR.Format( SR.net_listener_invalid_cbt_type, kind.ToString())); } - return _request.GetChannelBinding(); + return _request.GetChannelBinding()!; } } } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerResponse.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerResponse.Windows.cs index 3dcc2d7f76d351..0c4b36af8efc75 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerResponse.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerResponse.Windows.cs @@ -131,25 +131,26 @@ public void Close(byte[] responseEntity, bool willBlock) ContentLength64 = responseEntity.Length; } EnsureResponseStream(); + Debug.Assert(_responseStream != null); if (willBlock) { try { - _responseStream.Write(responseEntity, 0, responseEntity.Length); + _responseStream!.Write(responseEntity, 0, responseEntity.Length); } catch (Win32Exception) { } finally { - _responseStream.Close(); + _responseStream!.Close(); _responseState = ResponseState.Closed; - HttpListenerContext.Close(); + HttpListenerContext!.Close(); } } else { - _responseStream.BeginWrite(responseEntity, 0, responseEntity.Length, new AsyncCallback(NonBlockingCloseCallback), null); + _responseStream!.BeginWrite(responseEntity, 0, responseEntity.Length, new AsyncCallback(NonBlockingCloseCallback), null); } } @@ -160,10 +161,10 @@ private void Dispose() return; } EnsureResponseStream(); - _responseStream.Close(); + _responseStream!.Close(); _responseState = ResponseState.Closed; - HttpListenerContext.Close(); + HttpListenerContext!.Close(); } internal BoundaryType BoundaryType => _boundaryType; @@ -172,7 +173,7 @@ private void EnsureResponseStream() { if (_responseStream == null) { - _responseStream = new HttpResponseStream(HttpListenerContext); + _responseStream = new HttpResponseStream(HttpListenerContext!); } } @@ -180,14 +181,14 @@ private void NonBlockingCloseCallback(IAsyncResult asyncResult) { try { - _responseStream.EndWrite(asyncResult); + _responseStream!.EndWrite(asyncResult); } catch (Win32Exception) { } finally { - _responseStream.Close(); + _responseStream!.Close(); HttpListenerContext.Close(); _responseState = ResponseState.Closed; } @@ -217,7 +218,7 @@ actual HTTP header will be generated by the application and sent as entity body. not after. Thus, flag is not applicable to HttpSendHttpResponse. */ internal unsafe uint SendHeaders(Interop.HttpApi.HTTP_DATA_CHUNK* pDataChunk, - HttpResponseStreamAsyncResult asyncResult, + HttpResponseStreamAsyncResult? asyncResult, Interop.HttpApi.HTTP_FLAGS flags, bool isWebSocketHandshake) { @@ -251,7 +252,7 @@ internal unsafe uint SendHeaders(Interop.HttpApi.HTTP_DATA_CHUNK* pDataChunk, uint statusCode; uint bytesSent; - List pinnedHeaders = SerializeHeaders(ref _nativeResponse.Headers, isWebSocketHandshake); + List? pinnedHeaders = SerializeHeaders(ref _nativeResponse.Headers, isWebSocketHandshake); try { if (pDataChunk != null) @@ -360,7 +361,7 @@ internal Interop.HttpApi.HTTP_FLAGS ComputeHeaders() { _boundaryType = BoundaryType.Chunked; } - if (CanSendResponseBody(_httpContext.Response.StatusCode)) + if (CanSendResponseBody(_httpContext!.Response.StatusCode)) { _contentLength = -1; } @@ -420,10 +421,10 @@ internal void ComputeCoreHeaders() ComputeCookies(); } - private List SerializeHeaders(ref Interop.HttpApi.HTTP_RESPONSE_HEADERS headers, + private List? SerializeHeaders(ref Interop.HttpApi.HTTP_RESPONSE_HEADERS headers, bool isWebSocketHandshake) { - Interop.HttpApi.HTTP_UNKNOWN_HEADER[] unknownHeaders = null; + Interop.HttpApi.HTTP_UNKNOWN_HEADER[]? unknownHeaders = null; List pinnedHeaders; GCHandle gcHandle; @@ -435,7 +436,7 @@ private List SerializeHeaders(ref Interop.HttpApi.HTTP_RESPONSE_HEADER string headerName; string headerValue; int lookup; - byte[] bytes = null; + byte[]? bytes = null; pinnedHeaders = new List(); //--------------------------------------------------- @@ -490,7 +491,7 @@ private List SerializeHeaders(ref Interop.HttpApi.HTTP_RESPONSE_HEADER if (lookup == -1) { - string[] headerValues = Headers.GetValues(index); + string[] headerValues = Headers.GetValues(index)!; numUnknownHeaders += headerValues.Length; } } @@ -502,7 +503,7 @@ private List SerializeHeaders(ref Interop.HttpApi.HTTP_RESPONSE_HEADER for (int index = 0; index < Headers.Count; index++) { headerName = Headers.GetKey(index) as string; - headerValue = Headers.Get(index) as string; + headerValue = (Headers.Get(index) as string)!; lookup = Interop.HttpApi.HTTP_RESPONSE_HEADER_ID.IndexOfKnownHeader(headerName); if (lookup == (int)HttpResponseHeader.SetCookie || isWebSocketHandshake && lookup == (int)HttpResponseHeader.Connection) @@ -526,7 +527,7 @@ private List SerializeHeaders(ref Interop.HttpApi.HTTP_RESPONSE_HEADER //FOR UNKNOWN HEADERS //ALLOW MULTIPLE HEADERS to be added //--------------------------------------- - string[] headerValues = Headers.GetValues(index); + string[] headerValues = Headers.GetValues(index)!; for (int headerValueIndex = 0; headerValueIndex < headerValues.Length; headerValueIndex++) { //Add Name @@ -577,7 +578,7 @@ private List SerializeHeaders(ref Interop.HttpApi.HTTP_RESPONSE_HEADER return pinnedHeaders; } - private void FreePinnedHeaders(List pinnedHeaders) + private void FreePinnedHeaders(List? pinnedHeaders) { if (pinnedHeaders != null) { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerSession.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerSession.Windows.cs index 729f613bdf19d7..777335be91a983 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerSession.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpListenerSession.Windows.cs @@ -10,7 +10,7 @@ internal sealed class HttpListenerSession { public readonly HttpListener Listener; public readonly SafeHandle RequestQueueHandle; - private ThreadPoolBoundHandle _requestQueueBoundHandle; + private ThreadPoolBoundHandle? _requestQueueBoundHandle; public ThreadPoolBoundHandle RequestQueueBoundHandle { @@ -38,7 +38,7 @@ public unsafe HttpListenerSession(HttpListener listener) uint statusCode = Interop.HttpApi.HttpCreateRequestQueue( - Interop.HttpApi.s_version, null, null, 0, out HttpRequestQueueV2Handle requestQueueHandle); + Interop.HttpApi.s_version, null!, null, 0, out HttpRequestQueueV2Handle requestQueueHandle); if (statusCode != Interop.HttpApi.ERROR_SUCCESS) { diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpRequestStream.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpRequestStream.Windows.cs index 6bc057e5298ba0..3eadb3cf7e5e4a 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpRequestStream.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpRequestStream.Windows.cs @@ -117,7 +117,7 @@ private void UpdateAfterRead(uint statusCode, uint dataRead) if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "statusCode:" + statusCode + " _closed:" + _closed); } - public IAsyncResult BeginReadCore(byte[] buffer, int offset, int size, AsyncCallback callback, object state) + public IAsyncResult? BeginReadCore(byte[] buffer, int offset, int size, AsyncCallback? callback, object? state) { if (size == 0 || _closed) { @@ -126,7 +126,7 @@ public IAsyncResult BeginReadCore(byte[] buffer, int offset, int size, AsyncCall return result; } - HttpRequestStreamAsyncResult asyncResult = null; + HttpRequestStreamAsyncResult? asyncResult = null; uint dataRead = 0; if (_dataChunkIndex != -1) @@ -223,7 +223,7 @@ public override int EndRead(IAsyncResult asyncResult) { throw new ArgumentNullException(nameof(asyncResult)); } - HttpRequestStreamAsyncResult castedAsyncResult = asyncResult as HttpRequestStreamAsyncResult; + HttpRequestStreamAsyncResult? castedAsyncResult = asyncResult as HttpRequestStreamAsyncResult; if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); @@ -234,8 +234,8 @@ public override int EndRead(IAsyncResult asyncResult) } castedAsyncResult.EndCalled = true; // wait & then check for errors - object returnValue = castedAsyncResult.InternalWaitForCompletion(); - Exception exception = returnValue as Exception; + object? returnValue = castedAsyncResult.InternalWaitForCompletion(); + Exception? exception = returnValue as Exception; if (exception != null) { if (NetEventSource.Log.IsEnabled()) @@ -246,7 +246,7 @@ public override int EndRead(IAsyncResult asyncResult) ExceptionDispatchInfo.Throw(exception); } - uint dataRead = (uint)returnValue; + uint dataRead = (uint)returnValue!; UpdateAfterRead((uint)castedAsyncResult.ErrorCode, dataRead); if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"returnValue:{returnValue}"); @@ -275,23 +275,23 @@ internal uint GetChunks(byte[] buffer, int offset, int size) private sealed unsafe class HttpRequestStreamAsyncResult : LazyAsyncResult { - private readonly ThreadPoolBoundHandle _boundHandle; + private readonly ThreadPoolBoundHandle? _boundHandle; internal NativeOverlapped* _pOverlapped; internal void* _pPinnedBuffer; internal uint _dataAlreadyRead; private static readonly IOCompletionCallback s_IOCallback = new IOCompletionCallback(Callback); - internal HttpRequestStreamAsyncResult(object asyncObject, object userState, AsyncCallback callback) : base(asyncObject, userState, callback) + internal HttpRequestStreamAsyncResult(object asyncObject, object? userState, AsyncCallback? callback) : base(asyncObject, userState, callback) { } - internal HttpRequestStreamAsyncResult(object asyncObject, object userState, AsyncCallback callback, uint dataAlreadyRead) : base(asyncObject, userState, callback) + internal HttpRequestStreamAsyncResult(object asyncObject, object? userState, AsyncCallback? callback, uint dataAlreadyRead) : base(asyncObject, userState, callback) { _dataAlreadyRead = dataAlreadyRead; } - internal HttpRequestStreamAsyncResult(ThreadPoolBoundHandle boundHandle, object asyncObject, object userState, AsyncCallback callback, byte[] buffer, int offset, uint size, uint dataAlreadyRead) : base(asyncObject, userState, callback) + internal HttpRequestStreamAsyncResult(ThreadPoolBoundHandle boundHandle, object asyncObject, object? userState, AsyncCallback? callback, byte[] buffer, int offset, uint size, uint dataAlreadyRead) : base(asyncObject, userState, callback) { _dataAlreadyRead = dataAlreadyRead; _boundHandle = boundHandle; @@ -307,7 +307,7 @@ internal void IOCompleted(uint errorCode, uint numBytes) private static void IOCompleted(HttpRequestStreamAsyncResult asyncResult, uint errorCode, uint numBytes) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"asyncResult: {asyncResult} errorCode:0x {errorCode.ToString("x8")} numBytes: {numBytes}"); - object result = null; + object? result = null; try { if (errorCode != Interop.HttpApi.ERROR_SUCCESS && errorCode != Interop.HttpApi.ERROR_HANDLE_EOF) @@ -331,7 +331,7 @@ private static void IOCompleted(HttpRequestStreamAsyncResult asyncResult, uint e private static unsafe void Callback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped) { - HttpRequestStreamAsyncResult asyncResult = (HttpRequestStreamAsyncResult)ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped); + HttpRequestStreamAsyncResult asyncResult = (HttpRequestStreamAsyncResult)ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped)!; if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"asyncResult: {asyncResult} errorCode:0x {errorCode.ToString("x8")} numBytes: {numBytes} nativeOverlapped:0x {((IntPtr)nativeOverlapped).ToString("x8")}"); @@ -344,7 +344,7 @@ protected override void Cleanup() base.Cleanup(); if (_pOverlapped != null) { - _boundHandle.FreeNativeOverlapped(_pOverlapped); + _boundHandle!.FreeNativeOverlapped(_pOverlapped); } } } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStream.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStream.Windows.cs index 4f2e22cd92499e..6ab2f5bd54e459 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStream.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStream.Windows.cs @@ -15,7 +15,7 @@ internal sealed unsafe partial class HttpResponseStream : Stream private long _leftToWrite = long.MinValue; private bool _inOpaqueMode; // The last write needs special handling to cancel. - private HttpResponseStreamAsyncResult _lastWrite; + private HttpResponseStreamAsyncResult? _lastWrite; internal HttpResponseStream(HttpListenerContext httpContext) { @@ -61,7 +61,7 @@ private void WriteCore(byte[] buffer, int offset, int size) uint statusCode; uint dataToWrite = (uint)size; - SafeLocalAllocHandle bufferAsIntPtr = null; + SafeLocalAllocHandle? bufferAsIntPtr = null; IntPtr pBufferAsIntPtr = IntPtr.Zero; bool sentHeaders = _httpContext.Response.SentHeaders; try @@ -119,7 +119,7 @@ private void WriteCore(byte[] buffer, int offset, int size) null); if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "Call to Interop.HttpApi.HttpSendResponseEntityBody returned:" + statusCode); - if (_httpContext.Listener.IgnoreWriteExceptions) + if (_httpContext.Listener!.IgnoreWriteExceptions) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "Write() suppressing error"); statusCode = Interop.HttpApi.ERROR_SUCCESS; @@ -146,7 +146,7 @@ private void WriteCore(byte[] buffer, int offset, int size) if (NetEventSource.Log.IsEnabled()) NetEventSource.DumpBuffer(this, buffer, offset, (int)dataToWrite); } - private IAsyncResult BeginWriteCore(byte[] buffer, int offset, int size, AsyncCallback callback, object state) + private IAsyncResult BeginWriteCore(byte[] buffer, int offset, int size, AsyncCallback? callback, object? state) { Interop.HttpApi.HTTP_FLAGS flags = ComputeLeftToWrite(); if (_closed || (size == 0 && _leftToWrite != 0)) @@ -207,7 +207,7 @@ private IAsyncResult BeginWriteCore(byte[] buffer, int offset, int size, AsyncCa if (statusCode != Interop.HttpApi.ERROR_SUCCESS && statusCode != Interop.HttpApi.ERROR_IO_PENDING) { asyncResult.InternalCleanup(); - if (_httpContext.Listener.IgnoreWriteExceptions && sentHeaders) + if (_httpContext.Listener!.IgnoreWriteExceptions && sentHeaders) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "BeginWrite() Suppressing error"); } @@ -238,7 +238,7 @@ private IAsyncResult BeginWriteCore(byte[] buffer, int offset, int size, AsyncCa private void EndWriteCore(IAsyncResult asyncResult) { - HttpResponseStreamAsyncResult castedAsyncResult = asyncResult as HttpResponseStreamAsyncResult; + HttpResponseStreamAsyncResult? castedAsyncResult = asyncResult as HttpResponseStreamAsyncResult; if (castedAsyncResult == null || castedAsyncResult.AsyncObject != this) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); @@ -249,9 +249,9 @@ private void EndWriteCore(IAsyncResult asyncResult) } castedAsyncResult.EndCalled = true; // wait & then check for errors - object returnValue = castedAsyncResult.InternalWaitForCompletion(); + object? returnValue = castedAsyncResult.InternalWaitForCompletion(); - Exception exception = returnValue as Exception; + Exception? exception = returnValue as Exception; if (exception != null) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Error(this, "Rethrowing exception:" + exception); @@ -338,7 +338,7 @@ private void DisposeCore() if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "Call to Interop.HttpApi.HttpSendResponseEntityBody returned:" + statusCode); - if (_httpContext.Listener.IgnoreWriteExceptions) + if (_httpContext.Listener!.IgnoreWriteExceptions) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, "Suppressing error"); @@ -376,7 +376,7 @@ internal void SwitchToOpaqueMode() // Sync can only be cancelled by CancelSynchronousIo, but we don't attempt this right now. internal void CancelLastWrite(SafeHandle requestQueueHandle) { - HttpResponseStreamAsyncResult asyncState = _lastWrite; + HttpResponseStreamAsyncResult? asyncState = _lastWrite; if (asyncState != null && !asyncState.IsCompleted) { // It is safe to ignore the return value on a cancel operation because the connection is being closed diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStreamAsyncResult.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStreamAsyncResult.cs index bab03709c18c1d..5a41b0ddeed6a9 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStreamAsyncResult.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/HttpResponseStreamAsyncResult.cs @@ -8,9 +8,9 @@ namespace System.Net { internal sealed unsafe class HttpResponseStreamAsyncResult : LazyAsyncResult { - private readonly ThreadPoolBoundHandle _boundHandle; + private readonly ThreadPoolBoundHandle? _boundHandle; internal NativeOverlapped* _pOverlapped; - private readonly Interop.HttpApi.HTTP_DATA_CHUNK[] _dataChunks; + private readonly Interop.HttpApi.HTTP_DATA_CHUNK[]? _dataChunks; internal bool _sentHeaders; private static readonly IOCompletionCallback s_IOCallback = new IOCompletionCallback(Callback); @@ -45,7 +45,7 @@ internal Interop.HttpApi.HTTP_DATA_CHUNK* pDataChunks } } - internal HttpResponseStreamAsyncResult(object asyncObject, object userState, AsyncCallback callback) : base(asyncObject, userState, callback) + internal HttpResponseStreamAsyncResult(object asyncObject, object? userState, AsyncCallback? callback) : base(asyncObject, userState, callback) { } @@ -109,7 +109,7 @@ private static byte[] GetChunkHeader(int size, out int offset) private static readonly byte[] s_CRLFArray = new byte[] { (byte)'\r', (byte)'\n' }; - internal HttpResponseStreamAsyncResult(object asyncObject, object userState, AsyncCallback callback, byte[] buffer, int offset, int size, bool chunked, bool sentHeaders, ThreadPoolBoundHandle boundHandle) : base(asyncObject, userState, callback) + internal HttpResponseStreamAsyncResult(object asyncObject, object? userState, AsyncCallback? callback, byte[] buffer, int offset, int size, bool chunked, bool sentHeaders, ThreadPoolBoundHandle boundHandle) : base(asyncObject, userState, callback) { _boundHandle = boundHandle; _sentHeaders = sentHeaders; @@ -130,7 +130,7 @@ internal HttpResponseStreamAsyncResult(object asyncObject, object userState, Asy int chunkHeaderOffset = 0; - byte[] chunkHeaderBuffer = null; + byte[]? chunkHeaderBuffer = null; if (chunked) { chunkHeaderBuffer = GetChunkHeader(size, out chunkHeaderOffset); @@ -167,7 +167,7 @@ internal HttpResponseStreamAsyncResult(object asyncObject, object userState, Asy if (chunked) { - _dataChunks[0].pBuffer = (byte*)(Marshal.UnsafeAddrOfPinnedArrayElement(chunkHeaderBuffer, chunkHeaderOffset)); + _dataChunks[0].pBuffer = (byte*)(Marshal.UnsafeAddrOfPinnedArrayElement(chunkHeaderBuffer!, chunkHeaderOffset)); _dataChunks[1].pBuffer = (byte*)(Marshal.UnsafeAddrOfPinnedArrayElement(buffer, offset)); _dataChunks[2].pBuffer = (byte*)(Marshal.UnsafeAddrOfPinnedArrayElement(s_CRLFArray, 0)); } @@ -186,7 +186,7 @@ internal void IOCompleted(uint errorCode, uint numBytes) private static void IOCompleted(HttpResponseStreamAsyncResult asyncResult, uint errorCode, uint numBytes) { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"errorCode:0x {errorCode.ToString("x8")} numBytes: {numBytes}"); - object result = null; + object? result = null; try { if (errorCode != Interop.HttpApi.ERROR_SUCCESS && errorCode != Interop.HttpApi.ERROR_HANDLE_EOF) @@ -219,8 +219,8 @@ private static void IOCompleted(HttpResponseStreamAsyncResult asyncResult, uint private static unsafe void Callback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped) { - object state = ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped); - HttpResponseStreamAsyncResult asyncResult = state as HttpResponseStreamAsyncResult; + object state = ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped)!; + HttpResponseStreamAsyncResult asyncResult = (state as HttpResponseStreamAsyncResult)!; if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, "errorCode:0x" + errorCode.ToString("x8") + " numBytes:" + numBytes + " nativeOverlapped:0x" + ((IntPtr)nativeOverlapped).ToString("x8")); IOCompleted(asyncResult, errorCode, numBytes); @@ -232,7 +232,7 @@ protected override void Cleanup() base.Cleanup(); if (_pOverlapped != null) { - _boundHandle.FreeNativeOverlapped(_pOverlapped); + _boundHandle!.FreeNativeOverlapped(_pOverlapped); } } } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/ListenerAsyncResult.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/ListenerAsyncResult.Windows.cs index 1539301d09b646..ff0af808ca91ab 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/ListenerAsyncResult.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/ListenerAsyncResult.Windows.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System.Diagnostics; using System.Threading; namespace System.Net @@ -8,7 +9,7 @@ namespace System.Net internal sealed unsafe class ListenerAsyncResult : LazyAsyncResult { private static readonly IOCompletionCallback s_ioCallback = new IOCompletionCallback(WaitCallback); - private AsyncRequestContext _requestContext; + private AsyncRequestContext? _requestContext; internal static IOCompletionCallback IOCallback => s_ioCallback; @@ -20,7 +21,7 @@ internal ListenerAsyncResult(HttpListenerSession session, object userState, Asyn private static void IOCompleted(ListenerAsyncResult asyncResult, uint errorCode, uint numBytes) { - object result = null; + object? result = null; try { if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"errorCode:[{errorCode}] numBytes:[{numBytes}]"); @@ -33,7 +34,7 @@ private static void IOCompleted(ListenerAsyncResult asyncResult, uint errorCode, } else { - HttpListenerSession listenerSession = asyncResult.AsyncObject as HttpListenerSession; + HttpListenerSession listenerSession = (asyncResult.AsyncObject! as HttpListenerSession)!; if (errorCode == Interop.HttpApi.ERROR_SUCCESS) { // at this point we have received an unmanaged HTTP_REQUEST and memoryBlob @@ -41,9 +42,9 @@ private static void IOCompleted(ListenerAsyncResult asyncResult, uint errorCode, bool stoleBlob = false; try { - if (HttpListener.ValidateRequest(listenerSession, asyncResult._requestContext)) + if (HttpListener.ValidateRequest(listenerSession, asyncResult._requestContext!)) { - result = listenerSession.Listener.HandleAuthentication(listenerSession, asyncResult._requestContext, out stoleBlob); + result = listenerSession.Listener.HandleAuthentication(listenerSession, asyncResult._requestContext!, out stoleBlob); } } finally @@ -55,13 +56,13 @@ private static void IOCompleted(ListenerAsyncResult asyncResult, uint errorCode, } else { - asyncResult._requestContext.Reset(listenerSession.RequestQueueBoundHandle, 0, 0); + asyncResult._requestContext!.Reset(listenerSession.RequestQueueBoundHandle, 0, 0); } } } else { - asyncResult._requestContext.Reset(listenerSession.RequestQueueBoundHandle, asyncResult._requestContext.RequestBlob->RequestId, numBytes); + asyncResult._requestContext!.Reset(listenerSession.RequestQueueBoundHandle, asyncResult._requestContext.RequestBlob->RequestId, numBytes); } // We need to issue a new request, either because auth failed, or because our buffer was too small the first time. @@ -95,7 +96,7 @@ private static void IOCompleted(ListenerAsyncResult asyncResult, uint errorCode, private static unsafe void WaitCallback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped) { - ListenerAsyncResult asyncResult = (ListenerAsyncResult)ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped); + ListenerAsyncResult asyncResult = (ListenerAsyncResult)ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped)!; IOCompleted(asyncResult, errorCode, numBytes); } @@ -104,9 +105,11 @@ internal uint QueueBeginGetContext() uint statusCode = Interop.HttpApi.ERROR_SUCCESS; while (true) { + Debug.Assert(_requestContext != null); if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, $"Calling Interop.HttpApi.HttpReceiveHttpRequest RequestId: {_requestContext.RequestBlob->RequestId}Buffer:0x {((IntPtr)_requestContext.RequestBlob).ToString("x")} Size: {_requestContext.Size}"); uint bytesTransferred = 0; - HttpListenerSession listenerSession = (HttpListenerSession)AsyncObject; + Debug.Assert(AsyncObject != null); + HttpListenerSession listenerSession = (HttpListenerSession)AsyncObject!; statusCode = Interop.HttpApi.HttpReceiveHttpRequest( listenerSession.RequestQueueHandle, _requestContext.RequestBlob->RequestId, diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/ListenerClientCertAsyncResult.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/ListenerClientCertAsyncResult.Windows.cs index 8febf53d5f4914..e1969faff526fd 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/ListenerClientCertAsyncResult.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/ListenerClientCertAsyncResult.Windows.cs @@ -11,9 +11,9 @@ namespace System.Net { internal unsafe class ListenerClientCertAsyncResult : LazyAsyncResult { - private ThreadPoolBoundHandle _boundHandle; + private ThreadPoolBoundHandle? _boundHandle; private NativeOverlapped* _pOverlapped; - private byte[] _backingBuffer; + private byte[]? _backingBuffer; private Interop.HttpApi.HTTP_SSL_CLIENT_CERT_INFO* _memoryBlob; private uint _size; @@ -51,7 +51,7 @@ internal void Reset(uint size) } if (_size != 0) { - _boundHandle.FreeNativeOverlapped(_pOverlapped); + _boundHandle!.FreeNativeOverlapped(_pOverlapped); } _size = size; if (size == 0) @@ -62,7 +62,7 @@ internal void Reset(uint size) return; } _backingBuffer = new byte[checked((int)size)]; - _pOverlapped = _boundHandle.AllocateNativeOverlapped(s_IOCallback, state: this, pinData: _backingBuffer); + _pOverlapped = _boundHandle!.AllocateNativeOverlapped(s_IOCallback, state: this, pinData: _backingBuffer); _memoryBlob = (Interop.HttpApi.HTTP_SSL_CLIENT_CERT_INFO*)Marshal.UnsafeAddrOfPinnedArrayElement(_backingBuffer, 0); } @@ -73,8 +73,8 @@ internal unsafe void IOCompleted(uint errorCode, uint numBytes) private static unsafe void IOCompleted(ListenerClientCertAsyncResult asyncResult, uint errorCode, uint numBytes) { - HttpListenerRequest httpListenerRequest = (HttpListenerRequest)asyncResult.AsyncObject; - object result = null; + HttpListenerRequest httpListenerRequest = (HttpListenerRequest)asyncResult.AsyncObject!; + object? result = null; try { if (errorCode == Interop.HttpApi.ERROR_MORE_DATA) @@ -162,7 +162,7 @@ private static unsafe void IOCompleted(ListenerClientCertAsyncResult asyncResult private static unsafe void WaitCallback(uint errorCode, uint numBytes, NativeOverlapped* nativeOverlapped) { - ListenerClientCertAsyncResult asyncResult = (ListenerClientCertAsyncResult)ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped); + ListenerClientCertAsyncResult asyncResult = (ListenerClientCertAsyncResult)ThreadPoolBoundHandle.GetNativeOverlappedState(nativeOverlapped)!; if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(null, $"errorCode:[{errorCode}] numBytes:[{numBytes}] nativeOverlapped:[{((long)nativeOverlapped)}]"); IOCompleted(asyncResult, errorCode, numBytes); } @@ -173,7 +173,7 @@ protected override void Cleanup() if (_pOverlapped != null) { _memoryBlob = null; - _boundHandle.FreeNativeOverlapped(_pOverlapped); + _boundHandle!.FreeNativeOverlapped(_pOverlapped); _pOverlapped = null; _boundHandle = null; } @@ -185,7 +185,7 @@ protected override void Cleanup() { if (_pOverlapped != null && !Environment.HasShutdownStarted) { - _boundHandle.FreeNativeOverlapped(_pOverlapped); + _boundHandle!.FreeNativeOverlapped(_pOverlapped); _pOverlapped = null; // Must do this in case application calls GC.ReRegisterForFinalize(). _boundHandle = null; } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/HttpWebSocket.Windows.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/HttpWebSocket.Windows.cs index fbf3d1274f85b0..18c17879eebc3a 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/HttpWebSocket.Windows.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/HttpWebSocket.Windows.cs @@ -32,7 +32,7 @@ private static async Task AcceptWebSocketAsyncCore TimeSpan keepAliveInterval, ArraySegment internalBuffer) { - HttpListenerWebSocketContext webSocketContext = null; + HttpListenerWebSocketContext? webSocketContext = null; try { // get property will create a new response if one doesn't exist. @@ -40,10 +40,10 @@ private static async Task AcceptWebSocketAsyncCore HttpListenerRequest request = context.Request; ValidateWebSocketHeaders(context); - string secWebSocketVersion = request.Headers[HttpKnownHeaderNames.SecWebSocketVersion]; + string? secWebSocketVersion = request.Headers[HttpKnownHeaderNames.SecWebSocketVersion]; // Optional for non-browser client - string origin = request.Headers[HttpKnownHeaderNames.Origin]; + string? origin = request.Headers[HttpKnownHeaderNames.Origin]; List secWebSocketProtocols = new List(); string outgoingSecWebSocketProtocolString; @@ -61,7 +61,7 @@ private static async Task AcceptWebSocketAsyncCore } // negotiate the websocket key return value - string secWebSocketKey = request.Headers[HttpKnownHeaderNames.SecWebSocketKey]; + string? secWebSocketKey = request.Headers[HttpKnownHeaderNames.SecWebSocketKey]; string secWebSocketAccept = HttpWebSocket.GetSecWebSocketAcceptString(secWebSocketKey); response.Headers.Add(HttpKnownHeaderNames.Connection, HttpKnownHeaderNames.Upgrade); @@ -91,7 +91,7 @@ private static async Task AcceptWebSocketAsyncCore await response.OutputStream.FlushAsync().SuppressContextFlow(); - HttpResponseStream responseStream = response.OutputStream as HttpResponseStream; + HttpResponseStream responseStream = (response.OutputStream as HttpResponseStream)!; Debug.Assert(responseStream != null, "'responseStream' MUST be castable to System.Net.HttpResponseStream."); ((HttpResponseStream)response.OutputStream).SwitchToOpaqueMode(); HttpRequestStream requestStream = new HttpRequestStream(context); @@ -105,17 +105,17 @@ private static async Task AcceptWebSocketAsyncCore internalBuffer); webSocketContext = new HttpListenerWebSocketContext( - request.Url, + request.Url!, request.Headers, request.Cookies, - context.User, + context.User!, request.IsAuthenticated, request.IsLocal, request.IsSecureConnection, - origin, + origin!, secWebSocketProtocols.AsReadOnly(), - secWebSocketVersion, - secWebSocketKey, + secWebSocketVersion!, + secWebSocketKey!, webSocket); if (NetEventSource.Log.IsEnabled()) diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBase.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBase.cs index e0ea87b541fd49..ed859137e21dce 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBase.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBase.cs @@ -21,7 +21,7 @@ internal abstract class WebSocketBase : WebSocket, IDisposable private readonly OutstandingOperationHelper _receiveOutstandingOperationHelper; private readonly OutstandingOperationHelper _sendOutstandingOperationHelper; private readonly Stream _innerStream; - private readonly IWebSocketStream _innerStreamAsWebSocketStream; + private readonly IWebSocketStream? _innerStreamAsWebSocketStream; private readonly string _subProtocol; // We are not calling Dispose method on this object in Cleanup method to avoid a race condition while one thread is calling disposing on @@ -37,21 +37,21 @@ internal abstract class WebSocketBase : WebSocket, IDisposable private readonly WebSocketBuffer _internalBuffer; private readonly KeepAliveTracker _keepAliveTracker; private volatile bool _cleanedUp; - private volatile TaskCompletionSource _closeReceivedTaskCompletionSource; - private volatile Task _closeOutputTask; + private volatile TaskCompletionSource? _closeReceivedTaskCompletionSource; + private volatile Task? _closeOutputTask; private volatile bool _isDisposed; - private volatile Task _closeNetworkConnectionTask; + private volatile Task? _closeNetworkConnectionTask; private volatile bool _closeAsyncStartedReceive; private volatile WebSocketState _state; - private volatile Task _keepAliveTask; - private volatile WebSocketOperation.ReceiveOperation _receiveOperation; - private volatile WebSocketOperation.SendOperation _sendOperation; - private volatile WebSocketOperation.SendOperation _keepAliveOperation; - private volatile WebSocketOperation.CloseOutputOperation _closeOutputOperation; + private volatile Task? _keepAliveTask; + private volatile WebSocketOperation.ReceiveOperation? _receiveOperation; + private volatile WebSocketOperation.SendOperation? _sendOperation; + private volatile WebSocketOperation.SendOperation? _keepAliveOperation; + private volatile WebSocketOperation.CloseOutputOperation? _closeOutputOperation; private Nullable _closeStatus; - private string _closeStatusDescription; + private string? _closeStatusDescription; private int _receiveState; - private Exception _pendingException; + private Exception? _pendingException; protected WebSocketBase(Stream innerStream, string subProtocol, @@ -129,7 +129,7 @@ public override WebSocketCloseStatus? CloseStatus } } - public override string CloseStatusDescription + public override string? CloseStatusDescription { get { @@ -197,11 +197,11 @@ private async Task ReceiveAsyncCore(ArraySegment b } EnsureReceiveOperation(); - receiveResult = await _receiveOperation.Process(buffer, linkedCancellationToken).SuppressContextFlow(); + receiveResult = (await _receiveOperation!.Process(buffer, linkedCancellationToken).SuppressContextFlow())!; if (NetEventSource.Log.IsEnabled() && receiveResult.Count > 0) { - NetEventSource.DumpBuffer(this, buffer.Array, buffer.Offset, receiveResult.Count); + NetEventSource.DumpBuffer(this, buffer.Array!, buffer.Offset, receiveResult.Count); } } catch (Exception exception) @@ -270,7 +270,7 @@ private async Task SendAsyncCore(ArraySegment buffer, { while (!(ownsCancellationTokenSource = _sendOutstandingOperationHelper.TryStartOperation(cancellationToken, out linkedCancellationToken))) { - Task keepAliveTask; + Task? keepAliveTask; lock (SessionHandle) { @@ -306,7 +306,7 @@ private async Task SendAsyncCore(ArraySegment buffer, } EnsureSendOperation(); - _sendOperation.BufferType = GetBufferType(messageType, endOfMessage); + _sendOperation!.BufferType = GetBufferType(messageType, endOfMessage); await _sendOperation.Process(buffer, linkedCancellationToken).SuppressContextFlow(); } catch (Exception exception) @@ -341,7 +341,7 @@ await _innerStreamAsWebSocketStream.MultipleWriteAsync(sendBuffers, { foreach (ArraySegment buffer in sendBuffers) { - await _innerStream.WriteAsync(buffer.Array, + await _innerStream.WriteAsync(buffer.Array!, buffer.Offset, buffer.Count, cancellationToken).SuppressContextFlow(); @@ -409,12 +409,12 @@ public override void Abort() // MultiThreading: ThreadSafe; No-op if already in a terminal state public override Task CloseOutputAsync(WebSocketCloseStatus closeStatus, - string statusDescription, + string? statusDescription, CancellationToken cancellationToken) { WebSocketValidate.ValidateCloseStatus(closeStatus, statusDescription); - return CloseOutputAsyncCore(closeStatus, statusDescription, cancellationToken); + return CloseOutputAsyncCore(closeStatus, statusDescription!, cancellationToken); } private async Task CloseOutputAsyncCore(WebSocketCloseStatus closeStatus, @@ -458,7 +458,7 @@ private async Task CloseOutputAsyncCore(WebSocketCloseStatus closeStatus, ownsCloseOutputCancellationTokenSource = _closeOutputOutstandingOperationHelper.TryStartOperation(cancellationToken, out linkedCancellationToken); if (!ownsCloseOutputCancellationTokenSource) { - Task closeOutputTask = _closeOutputTask; + Task? closeOutputTask = _closeOutputTask; if (closeOutputTask != null) { @@ -494,9 +494,9 @@ private async Task CloseOutputAsyncCore(WebSocketCloseStatus closeStatus, } EnsureCloseOutputOperation(); - _closeOutputOperation.CloseStatus = closeStatus; - _closeOutputOperation.CloseReason = statusDescription; - _closeOutputTask = _closeOutputOperation.Process(null, linkedCancellationToken); + _closeOutputOperation!.CloseStatus = closeStatus; + _closeOutputOperation!.CloseReason = statusDescription; + _closeOutputTask = _closeOutputOperation!.Process(null, linkedCancellationToken); ReleaseLocks(ref thisLockTaken, ref sessionHandleLockTaken); await _closeOutputTask.SuppressContextFlow(); @@ -637,7 +637,7 @@ private void FinishOnCloseCompleted() // MultiThreading: ThreadSafe; No-op if already in a terminal state public override Task CloseAsync(WebSocketCloseStatus closeStatus, - string statusDescription, + string? statusDescription, CancellationToken cancellationToken) { WebSocketValidate.ValidateCloseStatus(closeStatus, statusDescription); @@ -645,7 +645,7 @@ public override Task CloseAsync(WebSocketCloseStatus closeStatus, } private async Task CloseAsyncCore(WebSocketCloseStatus closeStatus, - string statusDescription, + string? statusDescription, CancellationToken cancellationToken) { string inputParameter = string.Empty; @@ -679,7 +679,7 @@ private async Task CloseAsyncCore(WebSocketCloseStatus closeStatus, ThrowOnInvalidState(State, WebSocketState.Open, WebSocketState.CloseReceived, WebSocketState.CloseSent); - Task closeOutputTask; + Task? closeOutputTask; ownsCloseCancellationTokenSource = _closeOutstandingOperationHelper.TryStartOperation(cancellationToken, out linkedCancellationToken); if (ownsCloseCancellationTokenSource) { @@ -768,11 +768,11 @@ private async Task CloseAsyncCore(WebSocketCloseStatus closeStatus, ArraySegment closeMessageBuffer = new ArraySegment(new byte[HttpWebSocket.MinReceiveBufferSize]); EnsureReceiveOperation(); - Task receiveAsyncTask = _receiveOperation.Process(closeMessageBuffer, + Task receiveAsyncTask = _receiveOperation!.Process(closeMessageBuffer, linkedCancellationToken); ReleaseLock(_thisLock, ref lockTaken); - WebSocketReceiveResult receiveResult = null; + WebSocketReceiveResult? receiveResult = null; try { receiveResult = await receiveAsyncTask.SuppressContextFlow(); @@ -799,7 +799,7 @@ private async Task CloseAsyncCore(WebSocketCloseStatus closeStatus, { if (NetEventSource.Log.IsEnabled() && receiveResult.Count > 0) { - NetEventSource.DumpBuffer(this, closeMessageBuffer.Array, closeMessageBuffer.Offset, receiveResult.Count); + NetEventSource.DumpBuffer(this, closeMessageBuffer.Array!, closeMessageBuffer.Offset, receiveResult.Count); } if (receiveResult.MessageType != WebSocketMessageType.Close) @@ -816,7 +816,7 @@ private async Task CloseAsyncCore(WebSocketCloseStatus closeStatus, { _receiveOutstandingOperationHelper.CompleteOperation(ownsReceiveCancellationTokenSource); ReleaseLock(_thisLock, ref lockTaken); - await _closeReceivedTaskCompletionSource.Task.SuppressContextFlow(); + await _closeReceivedTaskCompletionSource!.Task.SuppressContextFlow(); } // When ownsReceiveCancellationTokenSource is true and an exception is thrown, the lock will be taken. @@ -1124,7 +1124,7 @@ error is HttpListenerException || // We only want to throw an OperationCanceledException if the CancellationToken passed // down from the caller is canceled - not when Abort is called on another thread and // the linkedCancellationToken is canceled. - private void ThrowIfConvertibleException(string methodName, + private void ThrowIfConvertibleException(string? methodName, Exception exception, CancellationToken cancellationToken, bool aborted) @@ -1136,7 +1136,7 @@ private void ThrowIfConvertibleException(string methodName, NetEventSource.Error(this, $"methodName: {methodName}, exception: {exception}"); } - OperationCanceledException operationCanceledException = exception as OperationCanceledException; + OperationCanceledException? operationCanceledException = exception as OperationCanceledException; if (operationCanceledException != null) { if (cancellationToken.IsCancellationRequested || @@ -1147,7 +1147,7 @@ private void ThrowIfConvertibleException(string methodName, ThrowIfAborted(aborted, exception); } - WebSocketException convertedException = exception as WebSocketException; + WebSocketException? convertedException = exception as WebSocketException; if (convertedException != null) { cancellationToken.ThrowIfCancellationRequested(); @@ -1155,19 +1155,19 @@ private void ThrowIfConvertibleException(string methodName, return; } - SocketException socketException = exception as SocketException; + SocketException? socketException = exception as SocketException; if (socketException != null) { convertedException = new WebSocketException(socketException.NativeErrorCode, socketException); } - HttpListenerException httpListenerException = exception as HttpListenerException; + HttpListenerException? httpListenerException = exception as HttpListenerException; if (httpListenerException != null) { convertedException = new WebSocketException(httpListenerException.ErrorCode, httpListenerException); } - IOException ioException = exception as IOException; + IOException? ioException = exception as IOException; if (ioException != null) { socketException = exception.InnerException as SocketException; @@ -1184,7 +1184,7 @@ private void ThrowIfConvertibleException(string methodName, throw convertedException; } - AggregateException aggregateException = exception as AggregateException; + AggregateException? aggregateException = exception as AggregateException; if (aggregateException != null) { // Collapse possibly nested graph into a flat list. @@ -1267,7 +1267,7 @@ private void CleanUp() private void OnBackgroundTaskException(Exception exception) { - if (Interlocked.CompareExchange(ref _pendingException, exception, null) == null) + if (Interlocked.CompareExchange(ref _pendingException!, exception, null!) == null) { if (NetEventSource.Log.IsEnabled()) { @@ -1279,7 +1279,7 @@ private void OnBackgroundTaskException(Exception exception) private void ThrowIfPendingException() { - Exception pendingException = Interlocked.Exchange(ref _pendingException, null); + Exception pendingException = Interlocked.Exchange(ref _pendingException!, null!); if (pendingException != null) { throw new WebSocketException(WebSocketError.Faulted, pendingException); @@ -1330,7 +1330,7 @@ private bool StartOnCloseReceived(ref bool thisLockTaken) } private void FinishOnCloseReceived(WebSocketCloseStatus closeStatus, - string closeStatusDescription) + string? closeStatusDescription) { _closeReceivedTaskCompletionSource?.TrySetResult(); @@ -1347,12 +1347,12 @@ private void FinishOnCloseReceived(WebSocketCloseStatus closeStatus, } } - private static async void OnKeepAlive(object sender) + private static async void OnKeepAlive(object? sender) { Debug.Assert(sender != null, "'sender' MUST NOT be NULL."); Debug.Assert((sender as WebSocketBase) != null, "'sender as WebSocketBase' MUST NOT be NULL."); - WebSocketBase thisPtr = sender as WebSocketBase; + WebSocketBase? thisPtr = (sender as WebSocketBase)!; bool lockTaken = false; CancellationToken linkedCancellationToken = CancellationToken.None; @@ -1376,9 +1376,9 @@ private static async void OnKeepAlive(object sender) if (ownsCancellationTokenSource) { thisPtr.EnsureKeepAliveOperation(); - thisPtr._keepAliveTask = thisPtr._keepAliveOperation.Process(null, linkedCancellationToken); + thisPtr._keepAliveTask = thisPtr._keepAliveOperation!.Process(null, linkedCancellationToken); ReleaseLock(thisPtr.SessionHandle, ref lockTaken); - await thisPtr._keepAliveTask.SuppressContextFlow(); + await thisPtr._keepAliveTask!.SuppressContextFlow(); } } finally @@ -1427,7 +1427,7 @@ internal WebSocketOperation(WebSocketBase webSocket) AsyncOperationCompleted = false; } - public WebSocketReceiveResult ReceiveResult { get; protected set; } + public WebSocketReceiveResult? ReceiveResult { get; protected set; } protected abstract int BufferCount { get; } protected abstract WebSocketProtocolComponent.ActionQueue ActionQueue { get; } protected abstract void Initialize(Nullable> buffer, CancellationToken cancellationToken); @@ -1451,7 +1451,7 @@ protected virtual void ProcessAction_IndicateReceiveComplete( protected abstract void Cleanup(); - internal async Task Process(Nullable> buffer, + internal async Task Process(Nullable> buffer, CancellationToken cancellationToken) { Debug.Assert(BufferCount >= 1 && BufferCount <= 2, "'bufferCount' MUST ONLY BE '1' or '2'."); @@ -1495,7 +1495,7 @@ internal async Task Process(Nullable> { // A close frame was received - Debug.Assert(ReceiveResult.Count == 0, "'receiveResult.Count' MUST be 0."); + Debug.Assert(ReceiveResult!.Count == 0, "'receiveResult.Count' MUST be 0."); Debug.Assert(ReceiveResult.CloseStatus != null, "'receiveResult.CloseStatus' MUST NOT be NULL for message type 'Close'."); bool thisLockTaken = false; try @@ -1557,7 +1557,7 @@ internal async Task Process(Nullable> HttpWebSocket.ThrowIfConnectionAborted(_webSocket._innerStream, true); try { - Task readTask = _webSocket._innerStream.ReadAsync(payload.Array, + Task readTask = _webSocket._innerStream.ReadAsync(payload.Array!, payload.Offset, payload.Count, cancellationToken); @@ -1816,7 +1816,7 @@ protected override void ProcessAction_IndicateReceiveComplete( if (bufferType == WebSocketProtocolComponent.BufferType.Close) { payload = ArraySegment.Empty; - _webSocket._internalBuffer.ConvertCloseBuffer(action, dataBuffers[0], out WebSocketCloseStatus closeStatus, out string reason); + _webSocket._internalBuffer.ConvertCloseBuffer(action, dataBuffers[0], out WebSocketCloseStatus closeStatus, out string? reason); receiveResult = new WebSocketReceiveResult(bytesTransferred, messageType, true, closeStatus, reason); @@ -1840,9 +1840,9 @@ protected override void ProcessAction_IndicateReceiveComplete( bytesTransferred = Math.Min(payload.Count, (int)buffer.Value.Count); if (bytesTransferred > 0) { - Buffer.BlockCopy(payload.Array, + Buffer.BlockCopy(payload.Array!, payload.Offset, - buffer.Value.Array, + buffer.Value.Array!, buffer.Value.Offset, bytesTransferred); } @@ -1953,7 +1953,7 @@ public CloseOutputOperation(WebSocketBase webSocket) } internal WebSocketCloseStatus CloseStatus { get; set; } - internal string CloseReason { get; set; } + internal string? CloseReason { get; set; } protected override Nullable CreateBuffer(Nullable> buffer) { @@ -2039,7 +2039,7 @@ private class DefaultKeepAliveTracker : KeepAliveTracker private readonly TimeSpan _keepAliveInterval; private readonly Stopwatch _lastSendActivity; private readonly Stopwatch _lastReceiveActivity; - private Timer _keepAliveTimer; + private Timer? _keepAliveTimer; public DefaultKeepAliveTracker(TimeSpan keepAliveInterval) { @@ -2095,12 +2095,12 @@ public override bool ShouldSendKeepAlive() public override void Dispose() { - _keepAliveTimer.Dispose(); + _keepAliveTimer!.Dispose(); } private void ResetTimer(int dueInMilliseconds) { - _keepAliveTimer.Change(dueInMilliseconds, Timeout.Infinite); + _keepAliveTimer!.Change(dueInMilliseconds, Timeout.Infinite); } private TimeSpan GetIdleTime() @@ -2131,7 +2131,7 @@ private TimeSpan GetTimeElapsed(Stopwatch watch) private class OutstandingOperationHelper : IDisposable { private volatile int _operationsOutstanding; - private volatile CancellationTokenSource _cancellationTokenSource; + private volatile CancellationTokenSource? _cancellationTokenSource; private volatile bool _isDisposed; private readonly object _thisLock = new object(); @@ -2163,7 +2163,7 @@ public void CompleteOperation(bool ownsCancellationTokenSource) return; } - CancellationTokenSource snapshot = null; + CancellationTokenSource? snapshot = null; lock (_thisLock) { @@ -2196,7 +2196,7 @@ private CancellationToken CreateLinkedCancellationToken(CancellationToken cancel public void CancelIO() { - CancellationTokenSource cancellationTokenSourceSnapshot = null; + CancellationTokenSource? cancellationTokenSourceSnapshot = null; lock (_thisLock) { @@ -2229,7 +2229,7 @@ public void Dispose() return; } - CancellationTokenSource snapshot = null; + CancellationTokenSource? snapshot = null; lock (_thisLock) { if (_isDisposed) diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBuffer.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBuffer.cs index 87610bf56b99ee..aa217407e66832 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBuffer.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketBuffer.cs @@ -38,7 +38,7 @@ internal class WebSocketBuffer : IDisposable private readonly ArraySegment _propertyBuffer; private readonly int _sendBufferSize; private volatile int _payloadOffset; - private volatile PayloadReceiveResult _bufferedPayloadReceiveResult; + private volatile PayloadReceiveResult? _bufferedPayloadReceiveResult; private long _pinnedSendBufferStartAddress; private long _pinnedSendBufferEndAddress; private ArraySegment _pinnedSendBuffer; @@ -173,7 +173,7 @@ internal Interop.WebSocket.Property[] CreateProperties(bool useZeroMaskingKey) internal void PinSendBuffer(ArraySegment payload, out bool bufferHasBeenPinned) { bufferHasBeenPinned = false; - WebSocketValidate.ValidateBuffer(payload.Array, payload.Offset, payload.Count); + WebSocketValidate.ValidateBuffer(payload.Array!, payload.Offset, payload.Count); int previousState = Interlocked.Exchange(ref _sendBufferState, SendBufferState.SendPayloadSpecified); if (previousState != SendBufferState.None) @@ -187,14 +187,14 @@ internal void PinSendBuffer(ArraySegment payload, out bool bufferHasBeenPi _pinnedSendBufferHandle = GCHandle.Alloc(_pinnedSendBuffer.Array, GCHandleType.Pinned); bufferHasBeenPinned = true; _pinnedSendBufferStartAddress = - Marshal.UnsafeAddrOfPinnedArrayElement(_pinnedSendBuffer.Array, _pinnedSendBuffer.Offset).ToInt64(); + Marshal.UnsafeAddrOfPinnedArrayElement(_pinnedSendBuffer.Array!, _pinnedSendBuffer.Offset).ToInt64(); _pinnedSendBufferEndAddress = _pinnedSendBufferStartAddress + _pinnedSendBuffer.Count; } // This method is not thread safe. It must only be called after enforcing at most 1 outstanding send operation internal IntPtr ConvertPinnedSendPayloadToNative(ArraySegment payload) { - return ConvertPinnedSendPayloadToNative(payload.Array, payload.Offset, payload.Count); + return ConvertPinnedSendPayloadToNative(payload.Array!, payload.Offset, payload.Count); } // This method is not thread safe. It must only be called after enforcing at most 1 outstanding send operation @@ -207,7 +207,7 @@ internal IntPtr ConvertPinnedSendPayloadToNative(byte[] buffer, int offset, int throw new AccessViolationException(); } - Debug.Assert(Marshal.UnsafeAddrOfPinnedArrayElement(_pinnedSendBuffer.Array, + Debug.Assert(Marshal.UnsafeAddrOfPinnedArrayElement(_pinnedSendBuffer.Array!, _pinnedSendBuffer.Offset).ToInt64() == _pinnedSendBufferStartAddress, "'m_PinnedSendBuffer.Array' MUST be pinned during the entire send operation."); @@ -225,7 +225,7 @@ internal ArraySegment ConvertPinnedSendPayloadFromNative(Interop.WebSocket throw new AccessViolationException(); } - Debug.Assert(Marshal.UnsafeAddrOfPinnedArrayElement(_pinnedSendBuffer.Array, + Debug.Assert(Marshal.UnsafeAddrOfPinnedArrayElement(_pinnedSendBuffer.Array!, _pinnedSendBuffer.Offset).ToInt64() == _pinnedSendBufferStartAddress, "'m_PinnedSendBuffer.Array' MUST be pinned during the entire send operation."); @@ -236,7 +236,7 @@ internal ArraySegment ConvertPinnedSendPayloadFromNative(Interop.WebSocket int internalOffset = (int)(bufferData.ToInt64() - _pinnedSendBufferStartAddress); - return new ArraySegment(_pinnedSendBuffer.Array, _pinnedSendBuffer.Offset + internalOffset, (int)bufferSize); + return new ArraySegment(_pinnedSendBuffer.Array!, _pinnedSendBuffer.Offset + internalOffset, (int)bufferSize); } // This method is not thread safe. It must only be called after enforcing at most 1 outstanding send operation @@ -306,9 +306,9 @@ internal void BufferPayload(ArraySegment payload, Debug.Assert(_bufferedPayloadReceiveResult == null || _bufferedPayloadReceiveResult.Count == 0, "'_bufferedPayloadReceiveResult.Count' MUST be '0' at this point."); - Buffer.BlockCopy(payload.Array, + Buffer.BlockCopy(payload.Array!, payload.Offset + unconsumedDataOffset, - _payloadBuffer.Array, + _payloadBuffer.Array!, _payloadBuffer.Offset, bytesBuffered); @@ -323,7 +323,7 @@ internal bool ReceiveFromBufferedPayload(ArraySegment buffer, out WebSocke ThrowIfDisposed(); ValidateBufferedPayload(); - int bytesTransferred = Math.Min(buffer.Count, _bufferedPayloadReceiveResult.Count); + int bytesTransferred = Math.Min(buffer.Count, _bufferedPayloadReceiveResult!.Count); _bufferedPayloadReceiveResult.Count -= bytesTransferred; @@ -332,9 +332,9 @@ internal bool ReceiveFromBufferedPayload(ArraySegment buffer, out WebSocke _bufferedPayloadReceiveResult.MessageType, _bufferedPayloadReceiveResult.Count == 0 && _bufferedPayloadReceiveResult.EndOfMessage); - Buffer.BlockCopy(_payloadBuffer.Array, + Buffer.BlockCopy(_payloadBuffer.Array!, _payloadBuffer.Offset + _payloadOffset, - buffer.Array, + buffer.Array!, buffer.Offset, bytesTransferred); @@ -373,7 +373,7 @@ internal ArraySegment ConvertNativeBuffer(WebSocketProtocolComponent.Actio if (this.IsNativeBuffer(bufferData, bufferLength)) { - return new ArraySegment(_internalBuffer.Array, + return new ArraySegment(_internalBuffer.Array!, this.GetOffset(bufferData), (int)bufferLength); } @@ -387,7 +387,7 @@ internal ArraySegment ConvertNativeBuffer(WebSocketProtocolComponent.Actio internal void ConvertCloseBuffer(WebSocketProtocolComponent.Action action, Interop.WebSocket.Buffer buffer, out WebSocketCloseStatus closeStatus, - out string reason) + out string? reason) { ThrowIfDisposed(); IntPtr bufferData; @@ -405,7 +405,7 @@ internal void ConvertCloseBuffer(WebSocketProtocolComponent.Action action, ArraySegment reasonBlob; if (this.IsNativeBuffer(bufferData, bufferLength)) { - reasonBlob = new ArraySegment(_internalBuffer.Array, + reasonBlob = new ArraySegment(_internalBuffer.Array!, this.GetOffset(bufferData), (int)bufferLength); } @@ -419,7 +419,7 @@ internal void ConvertCloseBuffer(WebSocketProtocolComponent.Action action, // No need to wrap DecoderFallbackException for invalid UTF8 chacters, because // Encoding.UTF8 will not throw but replace invalid characters instead. - reason = Encoding.UTF8.GetString(reasonBlob.Array, reasonBlob.Offset, reasonBlob.Count); + reason = Encoding.UTF8.GetString(reasonBlob.Array!, reasonBlob.Offset, reasonBlob.Count); } } @@ -608,7 +608,7 @@ private bool IsNativeBuffer(IntPtr pBuffer, uint bufferSize) long nativeBufferStartAddress = pBuffer.ToInt64(); long nativeBufferEndAddress = bufferSize + nativeBufferStartAddress; - Debug.Assert(Marshal.UnsafeAddrOfPinnedArrayElement(_internalBuffer.Array, _internalBuffer.Offset).ToInt64() == _startAddress, + Debug.Assert(Marshal.UnsafeAddrOfPinnedArrayElement(_internalBuffer.Array!, _internalBuffer.Offset).ToInt64() == _startAddress, "'m_InternalBuffer.Array' MUST be pinned for the whole lifetime of a WebSocket."); if (nativeBufferStartAddress >= _startAddress && diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketHttpListenerDuplexStream.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketHttpListenerDuplexStream.cs index 151a958f40911b..d9733f945e5773 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketHttpListenerDuplexStream.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketHttpListenerDuplexStream.cs @@ -18,16 +18,16 @@ internal sealed class WebSocketHttpListenerDuplexStream : Stream, WebSocketBase. private static readonly EventHandler s_OnWriteCompleted = new EventHandler(OnWriteCompleted); private static readonly Func s_CanHandleException = new Func(CanHandleException); - private static readonly Action s_OnCancel = new Action(OnCancel); + private static readonly Action s_OnCancel = new Action(OnCancel); private readonly HttpRequestStream _inputStream; private readonly HttpResponseStream _outputStream; private readonly HttpListenerContext _context; private bool _inOpaqueMode; - private WebSocketBase _webSocket; - private HttpListenerAsyncEventArgs _writeEventArgs; - private HttpListenerAsyncEventArgs _readEventArgs; - private TaskCompletionSource _writeTaskCompletionSource; - private TaskCompletionSource _readTaskCompletionSource; + private WebSocketBase? _webSocket; + private HttpListenerAsyncEventArgs? _writeEventArgs; + private HttpListenerAsyncEventArgs? _readEventArgs; + private TaskCompletionSource? _writeTaskCompletionSource; + private TaskCompletionSource? _readTaskCompletionSource; private int _cleanedUp; #if DEBUG @@ -151,7 +151,7 @@ private async Task ReadAsyncCore(byte[] buffer, int offset, int count, Canc "Only one outstanding read allowed at any given time."); #endif _readTaskCompletionSource = new TaskCompletionSource(); - _readEventArgs.SetBuffer(buffer, offset, count); + _readEventArgs!.SetBuffer(buffer, offset, count); if (!ReadAsyncFast(_readEventArgs)) { if (_readEventArgs.Exception != null) @@ -245,7 +245,7 @@ private unsafe bool ReadAsyncFast(HttpListenerAsyncEventArgs eventArgs) _inputStream.InternalHttpContext.RequestQueueHandle, _inputStream.InternalHttpContext.RequestId, flags, - (byte*)_webSocket.InternalBuffer.ToIntPtr(eventArgs.Offset), + (byte*)_webSocket!.InternalBuffer.ToIntPtr(eventArgs.Offset), (uint)eventArgs.Count, out bytesReturned, eventArgs.NativeOverlapped); @@ -276,7 +276,7 @@ private unsafe bool ReadAsyncFast(HttpListenerAsyncEventArgs eventArgs) } catch (Exception e) { - _readEventArgs.FinishOperationFailure(e, true); + _readEventArgs!.FinishOperationFailure(e, true); _outputStream.SetClosedFlag(); _outputStream.InternalHttpContext.Abort(); @@ -302,8 +302,8 @@ public bool SupportsMultipleWrite public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, - AsyncCallback callback, - object state) + AsyncCallback? callback, + object? state) { return _inputStream.BeginRead(buffer, offset, count, callback, state); } @@ -323,7 +323,7 @@ public Task MultipleWriteAsync(IList> sendBuffers, Cancellati if (sendBuffers.Count == 1) { ArraySegment buffer = sendBuffers[0]; - return WriteAsync(buffer.Array, buffer.Offset, buffer.Count, cancellationToken); + return WriteAsync(buffer.Array!, buffer.Offset, buffer.Count, cancellationToken); } return MultipleWriteAsyncCore(sendBuffers, cancellationToken); @@ -350,7 +350,7 @@ private async Task MultipleWriteAsyncCore(IList> sendBuffers, "Only one outstanding write allowed at any given time."); #endif _writeTaskCompletionSource = new TaskCompletionSource(); - _writeEventArgs.SetBuffer(null, 0, 0); + _writeEventArgs!.SetBuffer(null, 0, 0); _writeEventArgs.BufferList = sendBuffers; if (WriteAsyncFast(_writeEventArgs)) { @@ -409,7 +409,7 @@ private async Task WriteAsyncCore(byte[] buffer, int offset, int count, Cancella "Only one outstanding write allowed at any given time."); #endif _writeTaskCompletionSource = new TaskCompletionSource(); - _writeEventArgs.BufferList = null; + _writeEventArgs!.BufferList = null; _writeEventArgs.SetBuffer(buffer, offset, count); if (WriteAsyncFast(_writeEventArgs)) { @@ -499,7 +499,7 @@ private unsafe bool WriteAsyncFast(HttpListenerAsyncEventArgs eventArgs) } catch (Exception e) { - _writeEventArgs.FinishOperationFailure(e, true); + _writeEventArgs!.FinishOperationFailure(e, true); _outputStream.SetClosedFlag(); _outputStream.InternalHttpContext.Abort(); @@ -517,8 +517,8 @@ public override void WriteByte(byte value) public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, - AsyncCallback callback, - object state) + AsyncCallback? callback, + object? state) { return _outputStream.BeginWrite(buffer, offset, count, callback, state); } @@ -569,7 +569,7 @@ public async Task CloseNetworkConnectionAsync(CancellationToken cancellationToke "Only one outstanding write allowed at any given time."); #endif _writeTaskCompletionSource = new TaskCompletionSource(); - _writeEventArgs.SetShouldCloseOutput(); + _writeEventArgs!.SetShouldCloseOutput(); if (WriteAsyncFast(_writeEventArgs)) { await _writeTaskCompletionSource.Task.SuppressContextFlow(); @@ -636,10 +636,10 @@ error is ObjectDisposedException || error is IOException; } - private static void OnCancel(object state) + private static void OnCancel(object? state) { Debug.Assert(state != null, "'state' MUST NOT be NULL."); - WebSocketHttpListenerDuplexStream thisPtr = state as WebSocketHttpListenerDuplexStream; + WebSocketHttpListenerDuplexStream thisPtr = (state as WebSocketHttpListenerDuplexStream)!; Debug.Assert(thisPtr != null, "'thisPtr' MUST NOT be NULL."); try @@ -683,7 +683,7 @@ public void SwitchToOpaqueMode(WebSocketBase webSocket) } } - private static void OnWriteCompleted(object sender, HttpListenerAsyncEventArgs eventArgs) + private static void OnWriteCompleted(object? sender, HttpListenerAsyncEventArgs eventArgs) { Debug.Assert(eventArgs != null, "'eventArgs' MUST NOT be NULL."); WebSocketHttpListenerDuplexStream thisPtr = eventArgs.CurrentStream; @@ -695,15 +695,15 @@ private static void OnWriteCompleted(object sender, HttpListenerAsyncEventArgs e if (eventArgs.Exception != null) { - thisPtr._writeTaskCompletionSource.TrySetException(eventArgs.Exception); + thisPtr._writeTaskCompletionSource!.TrySetException(eventArgs.Exception); } else { - thisPtr._writeTaskCompletionSource.TrySetResult(); + thisPtr._writeTaskCompletionSource!.TrySetResult(); } } - private static void OnReadCompleted(object sender, HttpListenerAsyncEventArgs eventArgs) + private static void OnReadCompleted(object? sender, HttpListenerAsyncEventArgs eventArgs) { Debug.Assert(eventArgs != null, "'eventArgs' MUST NOT be NULL."); WebSocketHttpListenerDuplexStream thisPtr = eventArgs.CurrentStream; @@ -715,11 +715,11 @@ private static void OnReadCompleted(object sender, HttpListenerAsyncEventArgs ev if (eventArgs.Exception != null) { - thisPtr._readTaskCompletionSource.TrySetException(eventArgs.Exception); + thisPtr._readTaskCompletionSource!.TrySetException(eventArgs.Exception); } else { - thisPtr._readTaskCompletionSource.TrySetResult(eventArgs.BytesTransferred); + thisPtr._readTaskCompletionSource!.TrySetResult(eventArgs.BytesTransferred); } } @@ -732,18 +732,18 @@ internal class HttpListenerAsyncEventArgs : EventArgs, IDisposable private bool _disposeCalled; private unsafe NativeOverlapped* _ptrNativeOverlapped; - private ThreadPoolBoundHandle _boundHandle; - private event EventHandler m_Completed; - private byte[] _buffer; - private IList> _bufferList; + private ThreadPoolBoundHandle? _boundHandle; + private event EventHandler? m_Completed; + private byte[]? _buffer; + private IList>? _bufferList; private int _count; private int _offset; private int _bytesTransferred; private HttpListenerAsyncOperation _completedOperation; - private Interop.HttpApi.HTTP_DATA_CHUNK[] _dataChunks; + private Interop.HttpApi.HTTP_DATA_CHUNK[]? _dataChunks; private GCHandle _dataChunksGCHandle; private ushort _dataChunkCount; - private Exception _exception; + private Exception? _exception; private bool _shouldCloseOutput; private readonly WebSocketBase _webSocket; private readonly WebSocketHttpListenerDuplexStream _currentStream; @@ -776,7 +776,7 @@ public int BytesTransferred get { return _bytesTransferred; } } - public byte[] Buffer + public byte[]? Buffer { get { return _buffer; } } @@ -784,7 +784,7 @@ public byte[] Buffer // BufferList property. // Mutually exclusive with Buffer. // Setting this property with an existing non-null Buffer will cause an assert. - public IList> BufferList + public IList>? BufferList { get { return _bufferList; } set @@ -815,7 +815,7 @@ public int Count get { return _count; } } - public Exception Exception + public Exception? Exception { get { return _exception; } } @@ -922,7 +922,7 @@ private unsafe void FreeOverlapped(bool checkForShutdown) #if DEBUG DebugRefCountReleaseNativeOverlapped(); #endif - _boundHandle.FreeNativeOverlapped(_ptrNativeOverlapped); + _boundHandle!.FreeNativeOverlapped(_ptrNativeOverlapped); _ptrNativeOverlapped = null; } @@ -978,7 +978,7 @@ internal void StartOperationSend() _completedOperation = HttpListenerAsyncOperation.Send; } - public void SetBuffer(byte[] buffer, int offset, int count) + public void SetBuffer(byte[]? buffer, int offset, int count) { Debug.Assert(!_shouldCloseOutput, "'m_ShouldCloseOutput' MUST be 'false' at this point."); Debug.Assert(buffer == null || _bufferList == null, "Either 'm_Buffer' or 'm_BufferList' MUST be NULL."); @@ -1024,26 +1024,26 @@ private unsafe void UpdateDataChunk() } } - private unsafe void UpdateDataChunk(int index, byte[] buffer, int offset, int count) + private unsafe void UpdateDataChunk(int index, byte[]? buffer, int offset, int count) { if (buffer == null) { - _dataChunks[index].pBuffer = null; - _dataChunks[index].BufferLength = 0; + _dataChunks![index].pBuffer = null; + _dataChunks![index].BufferLength = 0; return; } if (_webSocket.InternalBuffer.IsInternalBuffer(buffer, offset, count)) { - _dataChunks[index].pBuffer = (byte*)(_webSocket.InternalBuffer.ToIntPtr(offset)); + _dataChunks![index].pBuffer = (byte*)(_webSocket.InternalBuffer.ToIntPtr(offset)); } else { - _dataChunks[index].pBuffer = + _dataChunks![index].pBuffer = (byte*)_webSocket.InternalBuffer.ConvertPinnedSendPayloadToNative(buffer, offset, count); } - _dataChunks[index].BufferLength = (uint)count; + _dataChunks![index].BufferLength = (uint)count; } // Method to mark this object as no longer "in-use". @@ -1064,7 +1064,7 @@ internal void Complete() } // Method to update internal state after sync or async completion. - private void SetResults(Exception exception, int bytesTransferred) + private void SetResults(Exception? exception, int bytesTransferred) { _exception = exception; _bytesTransferred = bytesTransferred; @@ -1100,9 +1100,9 @@ internal void FinishOperationSuccess(int bytesTransferred, bool syncCompletion) Debug.Assert(_completedOperation == HttpListenerAsyncOperation.Send, "'BufferList' is only supported for send operations."); - foreach (ArraySegment buffer in BufferList) + foreach (ArraySegment buffer in BufferList!) { - NetEventSource.DumpBuffer(this, buffer.Array, buffer.Offset, buffer.Count, nameof(WriteAsyncFast)); + NetEventSource.DumpBuffer(this, buffer.Array!, buffer.Offset, buffer.Count, nameof(WriteAsyncFast)); } } } diff --git a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketProtocolComponent.cs b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketProtocolComponent.cs index 72f9f4702ffa61..2402dd36c0f09e 100644 --- a/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketProtocolComponent.cs +++ b/src/libraries/System.Net.HttpListener/src/System/Net/Windows/WebSockets/WebSocketProtocolComponent.cs @@ -13,7 +13,7 @@ internal static class WebSocketProtocolComponent { private static readonly string s_dummyWebsocketKeyBase64 = Convert.ToBase64String(new byte[16]); private static readonly IntPtr s_webSocketDllHandle; - private static readonly string s_supportedVersion; + private static readonly string? s_supportedVersion; private static readonly Interop.WebSocket.HttpHeader[] s_initialClientRequestHeaders = new Interop.WebSocket.HttpHeader[] { @@ -33,7 +33,7 @@ internal static class WebSocketProtocolComponent } }; - private static readonly Interop.WebSocket.HttpHeader[] s_ServerFakeRequestHeaders; + private static readonly Interop.WebSocket.HttpHeader[]? s_ServerFakeRequestHeaders; internal enum Action { @@ -131,7 +131,7 @@ internal static string SupportedVersion HttpWebSocket.ThrowPlatformNotSupportedException_WSPC(); } - return s_supportedVersion; + return s_supportedVersion!; } } @@ -150,10 +150,10 @@ internal static string GetSupportedVersion() HttpWebSocket.ThrowPlatformNotSupportedException_WSPC(); } - SafeWebSocketHandle webSocketHandle = null; + SafeWebSocketHandle? webSocketHandle = null; try { - int errorCode = Interop.WebSocket.WebSocketCreateClientHandle(null, 0, out webSocketHandle); + int errorCode = Interop.WebSocket.WebSocketCreateClientHandle(null!, 0, out webSocketHandle); ThrowOnError(errorCode); if (webSocketHandle == null || @@ -165,7 +165,7 @@ internal static string GetSupportedVersion() IntPtr additionalHeadersPtr; uint additionalHeaderCount; - errorCode = Interop.WebSocket.WebSocketBeginClientHandshake(webSocketHandle, + errorCode = Interop.WebSocket.WebSocketBeginClientHandshake(webSocketHandle!, IntPtr.Zero, 0, IntPtr.Zero, @@ -178,7 +178,7 @@ internal static string GetSupportedVersion() Interop.WebSocket.HttpHeader[] additionalHeaders = MarshalHttpHeaders(additionalHeadersPtr, (int)additionalHeaderCount); - string version = null; + string? version = null; foreach (Interop.WebSocket.HttpHeader header in additionalHeaders) { if (string.Equals(header.Name, @@ -216,7 +216,7 @@ internal static void WebSocketCreateServerHandle(Interop.WebSocket.Property[] pr HttpWebSocket.ThrowPlatformNotSupportedException_WSPC(); } - int errorCode = Interop.WebSocket.WebSocketCreateServerHandle(properties, (uint)propertyCount, out webSocketHandle); + int errorCode = Interop.WebSocket.WebSocketCreateServerHandle(properties!, (uint)propertyCount, out webSocketHandle); ThrowOnError(errorCode); if (webSocketHandle == null || @@ -237,18 +237,18 @@ internal static void WebSocketCreateServerHandle(Interop.WebSocket.Property[] pr // just fake an HTTP handshake for the WSPC calling // WebSocketBeginServerHandshake and WebSocketEndServerHandshake // with statically defined dummy headers. - errorCode = Interop.WebSocket.WebSocketBeginServerHandshake(webSocketHandle, + errorCode = Interop.WebSocket.WebSocketBeginServerHandshake(webSocketHandle!, IntPtr.Zero, IntPtr.Zero, 0, - s_ServerFakeRequestHeaders, - (uint)s_ServerFakeRequestHeaders.Length, + s_ServerFakeRequestHeaders!, + (uint)s_ServerFakeRequestHeaders!.Length, out responseHeadersPtr, out responseHeaderCount); ThrowOnError(errorCode); - errorCode = Interop.WebSocket.WebSocketEndServerHandshake(webSocketHandle); + errorCode = Interop.WebSocket.WebSocketEndServerHandshake(webSocketHandle!); ThrowOnError(errorCode); @@ -370,7 +370,7 @@ internal static void WebSocketGetAction(WebSocketBase webSocket, { errorCode = Interop.WebSocket.WebSocketGetAction(webSocket.SessionHandle, actionQueue, - dataBuffers, + dataBuffers!, ref dataBufferCount, out action, out bufferType, @@ -383,11 +383,11 @@ internal static void WebSocketGetAction(WebSocketBase webSocket, } ThrowOnError(errorCode); - webSocket.ValidateNativeBuffers(action, bufferType, dataBuffers, dataBufferCount); + webSocket.ValidateNativeBuffers(action, bufferType, dataBuffers!, dataBufferCount); Debug.Assert(dataBufferCount >= 0); Debug.Assert((dataBufferCount == 0 && dataBuffers == null) || - (dataBufferCount <= dataBuffers.Length)); + (dataBufferCount <= dataBuffers!.Length)); } internal static void WebSocketCompleteAction(WebSocketBase webSocket, From 24fe3c9d7b01ff83388bb3975420afe03fd84280 Mon Sep 17 00:00:00 2001 From: Krzysztof Wicher Date: Thu, 27 Aug 2020 08:29:11 +0200 Subject: [PATCH 06/14] Nullable: System.Xml, part 7 (Serialization) (#41261) * Nullable: System.Xml, part 7 (Serialization) * Fix build errors on Release (ifdef-ed code) * fix incidental product bug * address PR feedback * Make XmlSerializer._rootType nullable --- .../Xml/Schema/SchemaNamespacemanager.cs | 8 +- .../src/System/Xml/Schema/XmlSchema.cs | 14 +- .../src/System/Xml/Schema/XmlSchemaElement.cs | 3 + .../src/System/Xml/Schema/XsdBuilder.cs | 2 +- .../Serialization/CodeGenerationoptions.cs | 1 + .../System/Xml/Serialization/CodeGenerator.cs | 298 +++---- .../Xml/Serialization/CodeIdentifier.cs | 14 +- .../Xml/Serialization/CodeIdentifiers.cs | 9 +- .../System/Xml/Serialization/Compilation.cs | 171 ++-- .../src/System/Xml/Serialization/Compiler.cs | 12 +- .../DateTimeSerializationSection.cs | 1 + .../src/System/Xml/Serialization/Globals.cs | 1 + .../Xml/Serialization/IXmlSerializable.cs | 3 +- .../Xml/Serialization/IXmlTextParser.cs | 1 + .../System/Xml/Serialization/ImportContext.cs | 90 +-- .../src/System/Xml/Serialization/Mappings.cs | 300 +++---- .../src/System/Xml/Serialization/Models.cs | 47 +- .../src/System/Xml/Serialization/NameTable.cs | 27 +- .../Serialization/PrimitiveXmlSerializers.cs | 193 ++--- .../ReflectionXmlSerializationReader.cs | 448 +++++------ .../ReflectionXmlSerializationWriter.cs | 265 +++---- .../Xml/Serialization/SchemaImporter.cs | 15 +- .../Xml/Serialization/SchemaObjectWriter.cs | 380 ++++----- .../Serialization/SoapAttributeAttribute.cs | 12 +- .../Serialization/SoapAttributeOverrides.cs | 15 +- .../Xml/Serialization/SoapAttributes.cs | 21 +- .../Xml/Serialization/SoapElementAttribute.cs | 8 +- .../Xml/Serialization/SoapEnumAttribute.cs | 5 +- .../Xml/Serialization/SoapIgnoreAttribute.cs | 1 + .../Xml/Serialization/SoapIncludeAttribute.cs | 1 + .../Serialization/SoapReflectionImporter.cs | 131 ++-- .../Xml/Serialization/SoapSchemamember.cs | 9 +- .../Xml/Serialization/SoapTypeAttribute.cs | 13 +- .../System/Xml/Serialization/SourceInfo.cs | 57 +- .../src/System/Xml/Serialization/TypeCode.cs | 1 + .../Xml/Serialization/TypeExtensions.cs | 3 +- .../src/System/Xml/Serialization/Types.cs | 151 ++-- .../Serialization/XmlAnyAttributeAttribute.cs | 2 +- .../Serialization/XmlAnyElementAttribute.cs | 14 +- .../Serialization/XmlAnyElementAttributes.cs | 15 +- .../Xml/Serialization/XmlArrayAttribute.cs | 12 +- .../Serialization/XmlArrayItemAttribute.cs | 23 +- .../Serialization/XmlArrayItemAttributes.cs | 15 +- .../Serialization/XmlAttributeAttribute.cs | 23 +- .../Serialization/XmlAttributeOverrides.cs | 17 +- .../System/Xml/Serialization/XmlAttributes.cs | 43 +- .../XmlChoiceIdentifierAttribute.cs | 16 +- .../Xml/Serialization/XmlElementAttribute.cs | 23 +- .../Xml/Serialization/XmlElementAttributes.cs | 15 +- .../Xml/Serialization/XmlEnumAttribute.cs | 8 +- .../Xml/Serialization/XmlIgnoreAttribute.cs | 2 +- .../Xml/Serialization/XmlIncludeAttribute.cs | 8 +- .../System/Xml/Serialization/XmlMapping.cs | 26 +- .../Xml/Serialization/XmlMemberMapping.cs | 24 +- .../Xml/Serialization/XmlMembersMapping.cs | 18 +- .../XmlNamespaceDeclarationsAttribute.cs | 2 +- .../Serialization/XmlReflectionImporter.cs | 345 ++++---- .../Xml/Serialization/XmlReflectionMember.cs | 8 +- .../Xml/Serialization/XmlRootAttribute.cs | 11 +- .../Xml/Serialization/XmlSchemaExporter.cs | 211 ++--- .../Xml/Serialization/XmlSchemaImporter.cs | 331 ++++---- .../XmlSchemaProviderAttribute.cs | 7 +- .../System/Xml/Serialization/XmlSchemas.cs | 77 +- .../XmlSerializationEventSource.cs | 1 + .../XmlSerializationGeneratedCode.cs | 43 +- .../Serialization/XmlSerializationILGen.cs | 100 +-- .../Serialization/XmlSerializationReader.cs | 738 +++++++++--------- .../XmlSerializationReaderILGen.cs | 661 ++++++++-------- .../Serialization/XmlSerializationWriter.cs | 599 +++++++------- .../XmlSerializationWriterILGen.cs | 494 ++++++------ .../System/Xml/Serialization/XmlSerializer.cs | 173 ++-- .../XmlSerializerAssemblyAttribute.cs | 13 +- .../Xml/Serialization/XmlSerializerFactory.cs | 15 +- .../Serialization/XmlSerializerNamespaces.cs | 23 +- .../XmlSerializerVersionAttribute.cs | 19 +- .../Xml/Serialization/XmlTextAttribute.cs | 12 +- .../Xml/Serialization/XmlTypeAttribute.cs | 12 +- .../Xml/Serialization/XmlTypeMapping.cs | 18 +- .../Xml/Serialization/Xmlcustomformatter.cs | 48 +- .../src/System/Xml/Serialization/_Events.cs | 43 +- .../Xml/Serialization/indentedWriter.cs | 5 +- 81 files changed, 3611 insertions(+), 3433 deletions(-) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaNamespacemanager.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaNamespacemanager.cs index d64c131d28b13c..2721d21c35d120 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaNamespacemanager.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaNamespacemanager.cs @@ -24,7 +24,7 @@ public SchemaNamespaceManager(XmlSchemaObject node) { //Special case for the XML namespace return XmlReservedNs.NsXml; } - Dictionary namespaces; + Dictionary namespaces; for (XmlSchemaObject? current = _node; current != null; current = current.Parent) { namespaces = current.Namespaces.Namespaces; @@ -44,15 +44,15 @@ public SchemaNamespaceManager(XmlSchemaObject node) { //Special case for the XML namespace return "xml"; } - Dictionary namespaces; + Dictionary namespaces; for (XmlSchemaObject? current = _node; current != null; current = current.Parent) { namespaces = current.Namespaces.Namespaces; if (namespaces != null && namespaces.Count > 0) { - foreach (KeyValuePair entry in namespaces) + foreach (KeyValuePair entry in namespaces) { - if (entry.Value.Equals(ns)) + if (entry.Value!.Equals(ns)) { return entry.Key; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchema.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchema.cs index f6b46e8e5179dd..5cb23353c26be7 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchema.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchema.cs @@ -56,17 +56,17 @@ public class XmlSchema : XmlSchemaObject public XmlSchema() { } - public static XmlSchema? Read(TextReader reader, ValidationEventHandler validationEventHandler) + public static XmlSchema? Read(TextReader reader, ValidationEventHandler? validationEventHandler) { return Read(new XmlTextReader(reader), validationEventHandler); } - public static XmlSchema? Read(Stream stream, ValidationEventHandler validationEventHandler) + public static XmlSchema? Read(Stream stream, ValidationEventHandler? validationEventHandler) { return Read(new XmlTextReader(stream), validationEventHandler); } - public static XmlSchema? Read(XmlReader reader, ValidationEventHandler validationEventHandler) + public static XmlSchema? Read(XmlReader reader, ValidationEventHandler? validationEventHandler) { XmlNameTable nameTable = reader.NameTable; Parser parser = new Parser(SchemaType.XSD, nameTable, new SchemaNames(nameTable), validationEventHandler); @@ -136,7 +136,7 @@ public void Write(XmlWriter writer, XmlNamespaceManager? namespaceManager) { ns.Add("xs", XmlReservedNs.NsXs); } - foreach (string? prefix in namespaceManager) + foreach (string prefix in namespaceManager) { if (prefix != "xml" && prefix != "xmlns") { @@ -146,7 +146,7 @@ public void Write(XmlWriter writer, XmlNamespaceManager? namespaceManager) } else if (this.Namespaces != null && this.Namespaces.Count > 0) { - Dictionary serializerNS = this.Namespaces.Namespaces; + Dictionary serializerNS = this.Namespaces.Namespaces; if (!serializerNS.ContainsKey("xs") && !serializerNS.ContainsValue(XmlReservedNs.NsXs)) { //Prefix xs not defined AND schema namespace not already mapped to a prefix serializerNS.Add("xs", XmlReservedNs.NsXs); @@ -166,7 +166,7 @@ public void Write(XmlWriter writer, XmlNamespaceManager? namespaceManager) } [Obsolete("Use System.Xml.Schema.XmlSchemaSet for schema compilation and validation. https://go.microsoft.com/fwlink/?linkid=14202")] - public void Compile(ValidationEventHandler validationEventHandler) + public void Compile(ValidationEventHandler? validationEventHandler) { SchemaInfo sInfo = new SchemaInfo(); sInfo.SchemaType = SchemaType.XSD; @@ -174,7 +174,7 @@ public void Compile(ValidationEventHandler validationEventHandler) } [Obsolete("Use System.Xml.Schema.XmlSchemaSet for schema compilation and validation. https://go.microsoft.com/fwlink/?linkid=14202")] - public void Compile(ValidationEventHandler validationEventHandler, XmlResolver resolver) + public void Compile(ValidationEventHandler? validationEventHandler, XmlResolver? resolver) { SchemaInfo sInfo = new SchemaInfo(); sInfo.SchemaType = SchemaType.XSD; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaElement.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaElement.cs index 7ea0845bf01b9f..58c68160b5584e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaElement.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaElement.cs @@ -112,6 +112,7 @@ internal bool HasAbstractAttribute } [XmlAttribute("ref")] + [AllowNull] public XmlQualifiedName RefName { get { return _refName; } @@ -119,6 +120,7 @@ public XmlQualifiedName RefName } [XmlAttribute("substitutionGroup")] + [AllowNull] public XmlQualifiedName SubstitutionGroup { get { return _substitutionGroup; } @@ -126,6 +128,7 @@ public XmlQualifiedName SubstitutionGroup } [XmlAttribute("type")] + [AllowNull] public XmlQualifiedName SchemaTypeName { get { return _typeName; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdBuilder.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdBuilder.cs index b1bb09829fca6a..74449d98725f0c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdBuilder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdBuilder.cs @@ -795,7 +795,7 @@ internal override void StartChildren() { if (_namespaces != null && _namespaces.Count > 0) { - _xso.Namespaces.Namespaces = _namespaces; + _xso.Namespaces.Namespaces = _namespaces!; _namespaces = null; } if (_unhandledAttributes.Count != 0) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeGenerationoptions.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeGenerationoptions.cs index 6f7ad17f4e4a36..42fbe3a3442a83 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeGenerationoptions.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeGenerationoptions.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeGenerator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeGenerator.cs index 14cd6dbdbd685f..22bbca0e50119a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeGenerator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeGenerator.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; using System.Collections; using System.Collections.Generic; @@ -32,14 +33,14 @@ internal class CodeGenerator internal static MethodAttributes PrivateMethodAttributes = MethodAttributes.Private | MethodAttributes.HideBySig; private readonly TypeBuilder _typeBuilder; - private MethodBuilder _methodBuilder; - private ILGenerator _ilGen; - private Dictionary _argList; - private LocalScope _currentScope; + private MethodBuilder? _methodBuilder; + private ILGenerator? _ilGen; + private Dictionary? _argList; + private LocalScope? _currentScope; // Stores a queue of free locals available in the context of the method, keyed by // type and name of the local - private Dictionary, Queue> _freeLocals; - private Stack _blockStack; + private Dictionary, Queue>? _freeLocals; + private Stack? _blockStack; private Label _methodEndLabel; internal CodeGenerator(TypeBuilder typeBuilder) @@ -85,7 +86,7 @@ internal void BeginMethod(Type returnType, MethodBuilderInfo methodBuilderInfo, private void InitILGeneration(Type[] argTypes, string[] argNames, bool isStatic) { - _methodEndLabel = _ilGen.DefineLabel(); + _methodEndLabel = _ilGen!.DefineLabel(); this.retLabel = _ilGen.DefineLabel(); _blockStack = new Stack(); _whileStack = new Stack(); @@ -94,21 +95,21 @@ private void InitILGeneration(Type[] argTypes, string[] argNames, bool isStatic) _argList = new Dictionary(); // this ptr is arg 0 for non static, assuming ref type (not value type) if (!isStatic) - _argList.Add("this", new ArgBuilder("this", 0, _typeBuilder.BaseType)); + _argList.Add("this", new ArgBuilder("this", 0, _typeBuilder.BaseType!)); for (int i = 0; i < argTypes.Length; i++) { ArgBuilder arg = new ArgBuilder(argNames[i], _argList.Count, argTypes[i]); _argList.Add(arg.Name, arg); - _methodBuilder.DefineParameter(arg.Index, ParameterAttributes.None, arg.Name); + _methodBuilder!.DefineParameter(arg.Index, ParameterAttributes.None, arg.Name); } } - internal MethodBuilder EndMethod() + internal MethodBuilder? EndMethod() { MarkLabel(_methodEndLabel); Ret(); - MethodBuilder retVal = null; + MethodBuilder? retVal = null; retVal = _methodBuilder; _methodBuilder = null; _ilGen = null; @@ -121,7 +122,7 @@ internal MethodBuilder EndMethod() return retVal; } - internal MethodBuilder MethodBuilder + internal MethodBuilder? MethodBuilder { get { return _methodBuilder; } } @@ -135,17 +136,17 @@ internal ArgBuilder GetArg(string name) internal LocalBuilder GetLocal(string name) { System.Diagnostics.Debug.Assert(_currentScope != null && _currentScope.ContainsKey(name)); - return _currentScope[name]; + return _currentScope[name]!; } - internal LocalBuilder retLocal; + internal LocalBuilder? retLocal; internal Label retLabel; internal LocalBuilder ReturnLocal { get { if (retLocal == null) - retLocal = DeclareLocal(_methodBuilder.ReturnType, "_ret"); + retLocal = DeclareLocal(_methodBuilder!.ReturnType, "_ret"); return retLocal; } } @@ -157,7 +158,7 @@ internal Label ReturnLabel private readonly Dictionary _tmpLocals = new Dictionary(); internal LocalBuilder GetTempLocal(Type type) { - LocalBuilder localTmp; + LocalBuilder? localTmp; if (!_tmpLocals.TryGetValue(type, out localTmp)) { localTmp = DeclareLocal(type, "_tmp" + _tmpLocals.Count); @@ -178,22 +179,22 @@ internal Type GetVariableType(object var) internal object GetVariable(string name) { - object var; + object? var; if (TryGetVariable(name, out var)) return var; System.Diagnostics.Debug.Fail("Variable not found"); return null; } - internal bool TryGetVariable(string name, out object variable) + internal bool TryGetVariable(string name, [NotNullWhen(true)] out object? variable) { - LocalBuilder loc; + LocalBuilder? loc; if (_currentScope != null && _currentScope.TryGetValue(name, out loc)) { variable = loc; return true; } - ArgBuilder arg; + ArgBuilder? arg; if (_argList != null && _argList.TryGetValue(name, out arg)) { variable = arg; @@ -217,18 +218,18 @@ internal void EnterScope() internal void ExitScope() { - Debug.Assert(_currentScope.parent != null); - _currentScope.AddToFreeLocals(_freeLocals); + Debug.Assert(_currentScope!.parent != null); + _currentScope.AddToFreeLocals(_freeLocals!); _currentScope = _currentScope.parent; } - private bool TryDequeueLocal(Type type, string name, out LocalBuilder local) + private bool TryDequeueLocal(Type type, string name, [NotNullWhen(true)] out LocalBuilder? local) { // This method can only be called between BeginMethod and EndMethod (i.e. // while we are emitting code for a method Debug.Assert(_freeLocals != null); - Queue freeLocalQueue; + Queue? freeLocalQueue; Tuple key = new Tuple(type, name); if (_freeLocals.TryGetValue(key, out freeLocalQueue)) { @@ -248,11 +249,11 @@ private bool TryDequeueLocal(Type type, string name, out LocalBuilder local) internal LocalBuilder DeclareLocal(Type type, string name) { - Debug.Assert(!_currentScope.ContainsKey(name)); - LocalBuilder local; + Debug.Assert(!_currentScope!.ContainsKey(name)); + LocalBuilder? local; if (!TryDequeueLocal(type, name, out local)) { - local = _ilGen.DeclareLocal(type, false); + local = _ilGen!.DeclareLocal(type, false); } _currentScope[name] = local; return local; @@ -260,8 +261,8 @@ internal LocalBuilder DeclareLocal(Type type, string name) internal LocalBuilder DeclareOrGetLocal(Type type, string name) { - LocalBuilder local; - if (!_currentScope.TryGetValue(name, out local)) + LocalBuilder? local; + if (!_currentScope!.TryGetValue(name, out local)) local = DeclareLocal(type, name); else Debug.Assert(local.LocalType == type); @@ -278,14 +279,14 @@ internal object For(LocalBuilder local, object start, object end) Br(forState.TestLabel); } MarkLabel(forState.BeginLabel); - _blockStack.Push(forState); + _blockStack!.Push(forState); return forState; } internal void EndFor() { - object stackTop = _blockStack.Pop(); - ForState forState = stackTop as ForState; + object stackTop = _blockStack!.Pop(); + ForState? forState = stackTop as ForState; Debug.Assert(forState != null); if (forState.Index != null) { @@ -310,7 +311,7 @@ internal void EndFor() "get_Count", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; Call(ICollection_get_Count); } Blt(forState.BeginLabel); @@ -348,11 +349,11 @@ internal void If(Cmp cmpOp) IfState ifState = new IfState(); ifState.EndIf = DefineLabel(); ifState.ElseBegin = DefineLabel(); - _ilGen.Emit(GetBranchCode(cmpOp), ifState.ElseBegin); - _blockStack.Push(ifState); + _ilGen!.Emit(GetBranchCode(cmpOp), ifState.ElseBegin); + _blockStack!.Push(ifState); } - internal void If(object value1, Cmp cmpOp, object value2) + internal void If(object value1, Cmp cmpOp, object? value2) { Load(value1); Load(value2); @@ -366,7 +367,7 @@ internal void Else() MarkLabel(ifState.ElseBegin); ifState.ElseBegin = ifState.EndIf; - _blockStack.Push(ifState); + _blockStack!.Push(ifState); } internal void EndIf() @@ -381,60 +382,60 @@ internal void EndIf() internal void BeginExceptionBlock() { _leaveLabels.Push(DefineLabel()); - _ilGen.BeginExceptionBlock(); + _ilGen!.BeginExceptionBlock(); } internal void BeginCatchBlock(Type exception) { - _ilGen.BeginCatchBlock(exception); + _ilGen!.BeginCatchBlock(exception); } internal void EndExceptionBlock() { - _ilGen.EndExceptionBlock(); + _ilGen!.EndExceptionBlock(); _ilGen.MarkLabel(_leaveLabels.Pop()); } internal void Leave() { - _ilGen.Emit(OpCodes.Leave, _leaveLabels.Peek()); + _ilGen!.Emit(OpCodes.Leave, _leaveLabels.Peek()); } internal void Call(MethodInfo methodInfo) { Debug.Assert(methodInfo != null); - if (methodInfo.IsVirtual && !methodInfo.DeclaringType.IsValueType) - _ilGen.Emit(OpCodes.Callvirt, methodInfo); + if (methodInfo.IsVirtual && !methodInfo.DeclaringType!.IsValueType) + _ilGen!.Emit(OpCodes.Callvirt, methodInfo); else - _ilGen.Emit(OpCodes.Call, methodInfo); + _ilGen!.Emit(OpCodes.Call, methodInfo); } internal void Call(ConstructorInfo ctor) { Debug.Assert(ctor != null); - _ilGen.Emit(OpCodes.Call, ctor); + _ilGen!.Emit(OpCodes.Call, ctor); } internal void New(ConstructorInfo constructorInfo) { Debug.Assert(constructorInfo != null); - _ilGen.Emit(OpCodes.Newobj, constructorInfo); + _ilGen!.Emit(OpCodes.Newobj, constructorInfo); } internal void InitObj(Type valueType) { - _ilGen.Emit(OpCodes.Initobj, valueType); + _ilGen!.Emit(OpCodes.Initobj, valueType); } internal void NewArray(Type elementType, object len) { Load(len); - _ilGen.Emit(OpCodes.Newarr, elementType); + _ilGen!.Emit(OpCodes.Newarr, elementType); } internal void LoadArrayElement(object obj, object arrayIndex) { - Type objType = GetVariableType(obj).GetElementType(); + Type objType = GetVariableType(obj).GetElementType()!; Load(obj); Load(arrayIndex); if (IsStruct(objType)) @@ -452,11 +453,11 @@ internal void StoreArrayElement(object obj, object arrayIndex, object value) if (arrayType == typeof(Array)) { Load(obj); - Call(typeof(Array).GetMethod("SetValue", new Type[] { typeof(object), typeof(int) })); + Call(typeof(Array).GetMethod("SetValue", new Type[] { typeof(object), typeof(int) })!); } else { - Type objType = arrayType.GetElementType(); + Type objType = arrayType.GetElementType()!; Load(obj); Load(arrayIndex); if (IsStruct(objType)) @@ -484,14 +485,14 @@ internal Type LoadMember(object obj, MemberInfo memberInfo) return LoadMember(memberInfo); } - private static MethodInfo GetPropertyMethodFromBaseType(PropertyInfo propertyInfo, bool isGetter) + private static MethodInfo? GetPropertyMethodFromBaseType(PropertyInfo propertyInfo, bool isGetter) { // we only invoke this when the propertyInfo does not have a GET or SET method on it - Type currentType = propertyInfo.DeclaringType.BaseType; - PropertyInfo currentProperty; + Type? currentType = propertyInfo.DeclaringType!.BaseType; + PropertyInfo? currentProperty; string propertyName = propertyInfo.Name; - MethodInfo result = null; + MethodInfo? result = null; while (currentType != null) { @@ -524,18 +525,18 @@ private static MethodInfo GetPropertyMethodFromBaseType(PropertyInfo propertyInf internal Type LoadMember(MemberInfo memberInfo) { - Type memberType = null; + Type? memberType = null; if (memberInfo is FieldInfo) { FieldInfo fieldInfo = (FieldInfo)memberInfo; memberType = fieldInfo.FieldType; if (fieldInfo.IsStatic) { - _ilGen.Emit(OpCodes.Ldsfld, fieldInfo); + _ilGen!.Emit(OpCodes.Ldsfld, fieldInfo); } else { - _ilGen.Emit(OpCodes.Ldfld, fieldInfo); + _ilGen!.Emit(OpCodes.Ldfld, fieldInfo); } } else @@ -545,7 +546,7 @@ internal Type LoadMember(MemberInfo memberInfo) memberType = property.PropertyType; if (property != null) { - MethodInfo getMethod = property.GetMethod; + MethodInfo? getMethod = property.GetMethod; if (getMethod == null) { @@ -562,18 +563,18 @@ internal Type LoadMember(MemberInfo memberInfo) internal Type LoadMemberAddress(MemberInfo memberInfo) { - Type memberType = null; + Type? memberType = null; if (memberInfo is FieldInfo) { FieldInfo fieldInfo = (FieldInfo)memberInfo; memberType = fieldInfo.FieldType; if (fieldInfo.IsStatic) { - _ilGen.Emit(OpCodes.Ldsflda, fieldInfo); + _ilGen!.Emit(OpCodes.Ldsflda, fieldInfo); } else { - _ilGen.Emit(OpCodes.Ldflda, fieldInfo); + _ilGen!.Emit(OpCodes.Ldflda, fieldInfo); } } else @@ -583,7 +584,7 @@ internal Type LoadMemberAddress(MemberInfo memberInfo) memberType = property.PropertyType; if (property != null) { - MethodInfo getMethod = property.GetMethod; + MethodInfo? getMethod = property.GetMethod; if (getMethod == null) { @@ -609,11 +610,11 @@ internal void StoreMember(MemberInfo memberInfo) FieldInfo fieldInfo = (FieldInfo)memberInfo; if (fieldInfo.IsStatic) { - _ilGen.Emit(OpCodes.Stsfld, fieldInfo); + _ilGen!.Emit(OpCodes.Stsfld, fieldInfo); } else { - _ilGen.Emit(OpCodes.Stfld, fieldInfo); + _ilGen!.Emit(OpCodes.Stfld, fieldInfo); } } else @@ -622,7 +623,7 @@ internal void StoreMember(MemberInfo memberInfo) PropertyInfo property = (PropertyInfo)memberInfo; if (property != null) { - MethodInfo setMethod = property.SetMethod; + MethodInfo? setMethod = property.SetMethod; if (setMethod == null) { @@ -635,10 +636,10 @@ internal void StoreMember(MemberInfo memberInfo) } } - internal void Load(object obj) + internal void Load(object? obj) { if (obj == null) - _ilGen.Emit(OpCodes.Ldnull); + _ilGen!.Emit(OpCodes.Ldnull); else if (obj is ArgBuilder) Ldarg((ArgBuilder)obj); else if (obj is LocalBuilder) @@ -670,17 +671,17 @@ internal void ConvertValue(Type source, Type target) internal void Castclass(Type target) { - _ilGen.Emit(OpCodes.Castclass, target); + _ilGen!.Emit(OpCodes.Castclass, target); } internal void Box(Type type) { - _ilGen.Emit(OpCodes.Box, type); + _ilGen!.Emit(OpCodes.Box, type); } internal void Unbox(Type type) { - _ilGen.Emit(OpCodes.Unbox, type); + _ilGen!.Emit(OpCodes.Unbox, type); } private static readonly OpCode[] s_ldindOpCodes = new OpCode[] { @@ -716,27 +717,27 @@ internal void Ldobj(Type type) OpCode opCode = GetLdindOpCode(type.GetTypeCode()); if (!opCode.Equals(OpCodes.Nop)) { - _ilGen.Emit(opCode); + _ilGen!.Emit(opCode); } else { - _ilGen.Emit(OpCodes.Ldobj, type); + _ilGen!.Emit(OpCodes.Ldobj, type); } } internal void Stobj(Type type) { - _ilGen.Emit(OpCodes.Stobj, type); + _ilGen!.Emit(OpCodes.Stobj, type); } internal void Ceq() { - _ilGen.Emit(OpCodes.Ceq); + _ilGen!.Emit(OpCodes.Ceq); } internal void Clt() { - _ilGen.Emit(OpCodes.Clt); + _ilGen!.Emit(OpCodes.Clt); } internal void Cne() @@ -748,17 +749,17 @@ internal void Cne() internal void Ble(Label label) { - _ilGen.Emit(OpCodes.Ble, label); + _ilGen!.Emit(OpCodes.Ble, label); } internal void Throw() { - _ilGen.Emit(OpCodes.Throw); + _ilGen!.Emit(OpCodes.Throw); } internal void Ldtoken(Type t) { - _ilGen.Emit(OpCodes.Ldtoken, t); + _ilGen!.Emit(OpCodes.Ldtoken, t); } internal void Ldc(object o) @@ -767,7 +768,7 @@ internal void Ldc(object o) if (o is Type) { Ldtoken((Type)o); - Call(typeof(Type).GetMethod("GetTypeFromHandle", BindingFlags.Static | BindingFlags.Public, new Type[] { typeof(RuntimeTypeHandle) })); + Call(typeof(Type).GetMethod("GetTypeFromHandle", BindingFlags.Static | BindingFlags.Public, new Type[] { typeof(RuntimeTypeHandle) })!); } else if (valueType.IsEnum) { @@ -814,7 +815,7 @@ internal void Ldc(object o) ConstructorInfo Decimal_ctor = typeof(decimal).GetConstructor( CodeGenerator.InstanceBindingFlags, new Type[] { typeof(int), typeof(int), typeof(int), typeof(bool), typeof(byte) } - ); + )!; int[] bits = decimal.GetBits((decimal)o); Ldc(bits[0]); // digit Ldc(bits[1]); // digit @@ -827,7 +828,7 @@ internal void Ldc(object o) ConstructorInfo DateTime_ctor = typeof(DateTime).GetConstructor( CodeGenerator.InstanceBindingFlags, new Type[] { typeof(long) } - ); + )!; Ldc(((DateTime)o).Ticks); // ticks New(DateTime_ctor); break; @@ -842,7 +843,7 @@ internal void Ldc(object o) null, new Type[] { typeof(long) }, null - ); + )!; Ldc(((TimeSpan)o).Ticks); // ticks New(TimeSpan_ctor); break; @@ -859,40 +860,40 @@ internal void Ldc(bool boolVar) { if (boolVar) { - _ilGen.Emit(OpCodes.Ldc_I4_1); + _ilGen!.Emit(OpCodes.Ldc_I4_1); } else { - _ilGen.Emit(OpCodes.Ldc_I4_0); + _ilGen!.Emit(OpCodes.Ldc_I4_0); } } internal void Ldc(int intVar) { - _ilGen.Emit(OpCodes.Ldc_I4, intVar); + _ilGen!.Emit(OpCodes.Ldc_I4, intVar); } internal void Ldc(long l) { - _ilGen.Emit(OpCodes.Ldc_I8, l); + _ilGen!.Emit(OpCodes.Ldc_I8, l); } internal void Ldc(float f) { - _ilGen.Emit(OpCodes.Ldc_R4, f); + _ilGen!.Emit(OpCodes.Ldc_R4, f); } internal void Ldc(double d) { - _ilGen.Emit(OpCodes.Ldc_R8, d); + _ilGen!.Emit(OpCodes.Ldc_R8, d); } - internal void Ldstr(string strVar) + internal void Ldstr(string? strVar) { if (strVar == null) - _ilGen.Emit(OpCodes.Ldnull); + _ilGen!.Emit(OpCodes.Ldnull); else - _ilGen.Emit(OpCodes.Ldstr, strVar); + _ilGen!.Emit(OpCodes.Ldstr, strVar); } internal void LdlocAddress(LocalBuilder localBuilder) @@ -905,20 +906,20 @@ internal void LdlocAddress(LocalBuilder localBuilder) internal void Ldloc(LocalBuilder localBuilder) { - _ilGen.Emit(OpCodes.Ldloc, localBuilder); + _ilGen!.Emit(OpCodes.Ldloc, localBuilder); } internal void Ldloc(string name) { - Debug.Assert(_currentScope.ContainsKey(name)); - LocalBuilder local = _currentScope[name]; + Debug.Assert(_currentScope!.ContainsKey(name)); + LocalBuilder local = _currentScope[name]!; Ldloc(local); } internal void Stloc(Type type, string name) { - LocalBuilder local = null; - if (!_currentScope.TryGetValue(name, out local)) + LocalBuilder? local = null; + if (!_currentScope!.TryGetValue(name, out local)) { local = DeclareLocal(type, name); } @@ -928,20 +929,20 @@ internal void Stloc(Type type, string name) internal void Stloc(LocalBuilder local) { - _ilGen.Emit(OpCodes.Stloc, local); + _ilGen!.Emit(OpCodes.Stloc, local); } internal void Ldloc(Type type, string name) { - Debug.Assert(_currentScope.ContainsKey(name)); - LocalBuilder local = _currentScope[name]; + Debug.Assert(_currentScope!.ContainsKey(name)); + LocalBuilder local = _currentScope[name]!; Debug.Assert(local.LocalType == type); Ldloc(local); } internal void Ldloca(LocalBuilder localBuilder) { - _ilGen.Emit(OpCodes.Ldloca, localBuilder); + _ilGen!.Emit(OpCodes.Ldloca, localBuilder); } internal void LdargAddress(ArgBuilder argBuilder) @@ -964,7 +965,7 @@ internal void Ldarg(ArgBuilder arg) internal void Ldarg(int slot) { - _ilGen.Emit(OpCodes.Ldarg, slot); + _ilGen!.Emit(OpCodes.Ldarg, slot); } internal void Ldarga(ArgBuilder argBuilder) @@ -974,12 +975,12 @@ internal void Ldarga(ArgBuilder argBuilder) internal void Ldarga(int slot) { - _ilGen.Emit(OpCodes.Ldarga, slot); + _ilGen!.Emit(OpCodes.Ldarga, slot); } internal void Ldlen() { - _ilGen.Emit(OpCodes.Ldlen); + _ilGen!.Emit(OpCodes.Ldlen); _ilGen.Emit(OpCodes.Conv_I4); } @@ -1022,13 +1023,13 @@ internal void Ldelem(Type arrayElementType) Debug.Assert(!opCode.Equals(OpCodes.Nop)); if (opCode.Equals(OpCodes.Nop)) throw new InvalidOperationException(SR.Format(SR.ArrayTypeIsNotSupported, arrayElementType.AssemblyQualifiedName)); - _ilGen.Emit(opCode); + _ilGen!.Emit(opCode); } } internal void Ldelema(Type arrayElementType) { OpCode opCode = OpCodes.Ldelema; - _ilGen.Emit(opCode, arrayElementType); + _ilGen!.Emit(opCode, arrayElementType); } private static readonly OpCode[] s_stelemOpCodes = new OpCode[] { @@ -1067,68 +1068,68 @@ internal void Stelem(Type arrayElementType) OpCode opCode = GetStelemOpCode(arrayElementType.GetTypeCode()); if (opCode.Equals(OpCodes.Nop)) throw new InvalidOperationException(SR.Format(SR.ArrayTypeIsNotSupported, arrayElementType.AssemblyQualifiedName)); - _ilGen.Emit(opCode); + _ilGen!.Emit(opCode); } } internal Label DefineLabel() { - return _ilGen.DefineLabel(); + return _ilGen!.DefineLabel(); } internal void MarkLabel(Label label) { - _ilGen.MarkLabel(label); + _ilGen!.MarkLabel(label); } internal void Nop() { - _ilGen.Emit(OpCodes.Nop); + _ilGen!.Emit(OpCodes.Nop); } internal void Add() { - _ilGen.Emit(OpCodes.Add); + _ilGen!.Emit(OpCodes.Add); } internal void Ret() { - _ilGen.Emit(OpCodes.Ret); + _ilGen!.Emit(OpCodes.Ret); } internal void Br(Label label) { - _ilGen.Emit(OpCodes.Br, label); + _ilGen!.Emit(OpCodes.Br, label); } internal void Br_S(Label label) { - _ilGen.Emit(OpCodes.Br_S, label); + _ilGen!.Emit(OpCodes.Br_S, label); } internal void Blt(Label label) { - _ilGen.Emit(OpCodes.Blt, label); + _ilGen!.Emit(OpCodes.Blt, label); } internal void Brfalse(Label label) { - _ilGen.Emit(OpCodes.Brfalse, label); + _ilGen!.Emit(OpCodes.Brfalse, label); } internal void Brtrue(Label label) { - _ilGen.Emit(OpCodes.Brtrue, label); + _ilGen!.Emit(OpCodes.Brtrue, label); } internal void Pop() { - _ilGen.Emit(OpCodes.Pop); + _ilGen!.Emit(OpCodes.Pop); } internal void Dup() { - _ilGen.Emit(OpCodes.Dup); + _ilGen!.Emit(OpCodes.Dup); } private void InternalIf(bool negate) @@ -1140,7 +1141,7 @@ private void InternalIf(bool negate) Brtrue(ifState.ElseBegin); else Brfalse(ifState.ElseBegin); - _blockStack.Push(ifState); + _blockStack!.Push(ifState); } private static readonly OpCode[] s_convOpCodes = new OpCode[] { @@ -1185,7 +1186,7 @@ private void InternalConvert(Type source, Type target, bool isAddress) } else { - _ilGen.Emit(opCode); + _ilGen!.Emit(opCode); } } else if (source.IsAssignableFrom(target)) @@ -1224,8 +1225,8 @@ private void InternalConvert(Type source, Type target, bool isAddress) private IfState PopIfState() { - object stackTop = _blockStack.Pop(); - IfState ifState = stackTop as IfState; + object stackTop = _blockStack!.Pop(); + IfState? ifState = stackTop as IfState; Debug.Assert(ifState != null); return ifState; } @@ -1250,11 +1251,11 @@ internal static TypeBuilder CreateTypeBuilder(ModuleBuilder moduleBuilder, strin } private int _initElseIfStack = -1; - private IfState _elseIfState; + private IfState? _elseIfState; internal void InitElseIf() { Debug.Assert(_initElseIfStack == -1); - _elseIfState = (IfState)_blockStack.Pop(); + _elseIfState = (IfState)_blockStack!.Pop(); _initElseIfStack = _blockStack.Count; Br(_elseIfState.EndIf); MarkLabel(_elseIfState.ElseBegin); @@ -1264,12 +1265,12 @@ internal void InitElseIf() internal void InitIf() { Debug.Assert(_initIfStack == -1); - _initIfStack = _blockStack.Count; + _initIfStack = _blockStack!.Count; } internal void AndIf(Cmp cmpOp) { - if (_initIfStack == _blockStack.Count) + if (_initIfStack == _blockStack!.Count) { _initIfStack = -1; If(cmpOp); @@ -1278,19 +1279,19 @@ internal void AndIf(Cmp cmpOp) if (_initElseIfStack == _blockStack.Count) { _initElseIfStack = -1; - _elseIfState.ElseBegin = DefineLabel(); - _ilGen.Emit(GetBranchCode(cmpOp), _elseIfState.ElseBegin); + _elseIfState!.ElseBegin = DefineLabel(); + _ilGen!.Emit(GetBranchCode(cmpOp), _elseIfState.ElseBegin); _blockStack.Push(_elseIfState); return; } Debug.Assert(_initIfStack == -1 && _initElseIfStack == -1); IfState ifState = (IfState)_blockStack.Peek(); - _ilGen.Emit(GetBranchCode(cmpOp), ifState.ElseBegin); + _ilGen!.Emit(GetBranchCode(cmpOp), ifState.ElseBegin); } internal void AndIf() { - if (_initIfStack == _blockStack.Count) + if (_initIfStack == _blockStack!.Count) { _initIfStack = -1; If(); @@ -1299,7 +1300,7 @@ internal void AndIf() if (_initElseIfStack == _blockStack.Count) { _initElseIfStack = -1; - _elseIfState.ElseBegin = DefineLabel(); + _elseIfState!.ElseBegin = DefineLabel(); Brfalse(_elseIfState.ElseBegin); _blockStack.Push(_elseIfState); return; @@ -1311,17 +1312,17 @@ internal void AndIf() internal void IsInst(Type type) { - _ilGen.Emit(OpCodes.Isinst, type); + _ilGen!.Emit(OpCodes.Isinst, type); } internal void Beq(Label label) { - _ilGen.Emit(OpCodes.Beq, label); + _ilGen!.Emit(OpCodes.Beq, label); } internal void Bne(Label label) { - _ilGen.Emit(OpCodes.Bne_Un, label); + _ilGen!.Emit(OpCodes.Bne_Un, label); } internal void GotoMethodEnd() @@ -1352,7 +1353,7 @@ public WhileState(CodeGenerator ilg) // (bool on stack) // WhileEndCondition() // WhileEnd() - private Stack _whileStack; + private Stack? _whileStack; internal void WhileBegin() { WhileState whileState = new WhileState(this); @@ -1366,24 +1367,24 @@ internal void WhileBegin() Ldc(true); Brtrue(whileState.CondLabel); MarkLabel(whileState.StartLabel); - _whileStack.Push(whileState); + _whileStack!.Push(whileState); } internal void WhileEnd() { - WhileState whileState = _whileStack.Pop(); + WhileState whileState = _whileStack!.Pop(); MarkLabel(whileState.EndLabel); } internal void WhileContinue() { - WhileState whileState = _whileStack.Peek(); + WhileState whileState = _whileStack!.Peek(); Br(whileState.CondLabel); } internal void WhileBeginCondition() { - WhileState whileState = _whileStack.Peek(); + WhileState whileState = _whileStack!.Peek(); // If there are two MarkLabel ILs consecutively, Labels will converge to one label. // This could cause the code to look different. We insert Nop here specifically // that the While label stands out. @@ -1393,7 +1394,7 @@ internal void WhileBeginCondition() internal void WhileEndCondition() { - WhileState whileState = _whileStack.Peek(); + WhileState whileState = _whileStack!.Peek(); Brtrue(whileState.StartLabel); } } @@ -1502,7 +1503,7 @@ internal Label ElseBegin internal class LocalScope { - public readonly LocalScope parent; + public readonly LocalScope? parent; private readonly Dictionary _locals; // Root scope @@ -1511,7 +1512,7 @@ public LocalScope() _locals = new Dictionary(); } - public LocalScope(LocalScope parent) : this() + public LocalScope(LocalScope? parent) : this() { this.parent = parent; } @@ -1521,7 +1522,7 @@ public bool ContainsKey(string key) return _locals.ContainsKey(key) || (parent != null && parent.ContainsKey(key)); } - public bool TryGetValue(string key, out LocalBuilder value) + public bool TryGetValue(string key, [NotNullWhen(true)] out LocalBuilder? value) { if (_locals.TryGetValue(key, out value)) { @@ -1538,11 +1539,12 @@ public bool TryGetValue(string key, out LocalBuilder value) } } - public LocalBuilder this[string key] + [DisallowNull] + public LocalBuilder? this[string key] { get { - LocalBuilder value; + LocalBuilder? value; TryGetValue(key, out value); return value; } @@ -1557,7 +1559,7 @@ public void AddToFreeLocals(Dictionary, Queue> foreach (var item in _locals) { Tuple key = new Tuple(item.Value.LocalType, item.Key); - Queue freeLocalQueue; + Queue? freeLocalQueue; if (freeLocals.TryGetValue(key, out freeLocalQueue)) { // Add to end of the queue so that it will be re-used in @@ -1584,7 +1586,7 @@ public MethodBuilderInfo(MethodBuilder methodBuilder, Type[] parameterTypes) this.ParameterTypes = parameterTypes; } - public void Validate(Type returnType, Type[] parameterTypes, MethodAttributes attributes) + public void Validate(Type? returnType, Type[] parameterTypes, MethodAttributes attributes) { #if DEBUG Debug.Assert(this.MethodBuilder.ReturnType == returnType); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeIdentifier.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeIdentifier.cs index b6a9ffd3f347e1..2393f70b554b34 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeIdentifier.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeIdentifier.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; using System.Text; using System.Collections; @@ -9,6 +10,7 @@ using System.Diagnostics; using System.Reflection; using System.Runtime.InteropServices; +using System.Diagnostics.CodeAnalysis; namespace System.Xml.Serialization { @@ -162,10 +164,12 @@ private static bool IsValid(char c) return true; } - internal static void CheckValidIdentifier(string ident) + internal static void CheckValidIdentifier([NotNull] string? ident) { if (!CSharpHelpers.IsValidLanguageIndependentIdentifier(ident)) throw new ArgumentException(SR.Format(SR.XmlInvalidIdentifier, ident), nameof(ident)); + + Debug.Assert(ident != null); } internal static string GetCSharpName(string name) @@ -213,12 +217,13 @@ internal static string GetCSharpName(Type t) int rank = 0; while (t.IsArray) { - t = t.GetElementType(); + t = t.GetElementType()!; rank++; } + StringBuilder sb = new StringBuilder(); sb.Append("global::"); - string ns = t.Namespace; + string? ns = t.Namespace; if (ns != null && ns.Length > 0) { string[] parts = ns.Split('.'); @@ -266,7 +271,8 @@ private static void EscapeKeywords(string identifier, StringBuilder sb) } } - private static string EscapeKeywords(string identifier) + [return: NotNullIfNotNull("identifier")] + private static string? EscapeKeywords(string? identifier) { if (identifier == null || identifier.Length == 0) return identifier; string originalIdentifier = identifier; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeIdentifiers.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeIdentifiers.cs index cd22fb63a5b6f7..66f28c88e857b3 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeIdentifiers.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeIdentifiers.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; @@ -14,14 +15,14 @@ public CaseInsensitiveKeyComparer() : base(CultureInfo.CurrentCulture) { } - bool IEqualityComparer.Equals(object x, object y) + bool IEqualityComparer.Equals(object? x, object? y) { return (Compare(x, y) == 0); } int IEqualityComparer.GetHashCode(object obj) { - string s = obj as string; + string? s = obj as string; if (s == null) throw new ArgumentException(null, nameof(obj)); @@ -131,7 +132,7 @@ public void RemoveReserved(string identifier) /// /// [To be supplied.] /// - public string AddUnique(string identifier, object value) + public string AddUnique(string identifier, object? value) { identifier = MakeUnique(identifier); Add(identifier, value); @@ -149,7 +150,7 @@ public bool IsInUse(string identifier) /// /// [To be supplied.] /// - public void Add(string identifier, object value) + public void Add(string identifier, object? value) { _identifiers.Add(identifier, value); _list.Add(value); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Compilation.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Compilation.cs index 67ce05acdec292..86d3ffaa6f81fb 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Compilation.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Compilation.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System.Reflection; using System.Reflection.Emit; using System.Collections; @@ -10,40 +11,41 @@ using System.Security; using System.Globalization; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; namespace System.Xml.Serialization { internal class TempAssembly { internal const string GeneratedAssemblyNamespace = "Microsoft.Xml.Serialization.GeneratedAssembly"; - private readonly Assembly _assembly; - private XmlSerializerImplementation _contract; - private IDictionary _writerMethods; - private IDictionary _readerMethods; - private TempMethodDictionary _methods; + private readonly Assembly? _assembly; + private XmlSerializerImplementation? _contract; + private IDictionary? _writerMethods; + private IDictionary? _readerMethods; + private TempMethodDictionary? _methods; internal class TempMethod { - internal MethodInfo writeMethod; - internal MethodInfo readMethod; - internal string name; - internal string ns; + internal MethodInfo? writeMethod; + internal MethodInfo? readMethod; + internal string? name; + internal string? ns; internal bool isSoap; - internal string methodKey; + internal string? methodKey; } private TempAssembly() { } - internal TempAssembly(XmlMapping[] xmlMappings, Assembly assembly, XmlSerializerImplementation contract) + internal TempAssembly(XmlMapping[] xmlMappings, Assembly assembly, XmlSerializerImplementation? contract) { _assembly = assembly; InitAssemblyMethods(xmlMappings); _contract = contract; } - internal TempAssembly(XmlMapping[] xmlMappings, Type[] types, string defaultNamespace, string location) + internal TempAssembly(XmlMapping[] xmlMappings, Type?[] types, string? defaultNamespace, string? location) { bool containsSoapMapping = false; for (int i = 0; i < xmlMappings.Length; i++) @@ -104,7 +106,7 @@ internal XmlSerializerImplementation Contract { if (_contract == null) { - _contract = (XmlSerializerImplementation)Activator.CreateInstance(GetTypeFromAssembly(_assembly, "XmlSerializerContract")); + _contract = (XmlSerializerImplementation)Activator.CreateInstance(GetTypeFromAssembly(_assembly!, "XmlSerializerContract"))!; } return _contract; } @@ -118,13 +120,13 @@ internal void InitAssemblyMethods(XmlMapping[] xmlMappings) TempMethod method = new TempMethod(); method.isSoap = xmlMappings[i].IsSoap; method.methodKey = xmlMappings[i].Key; - XmlTypeMapping xmlTypeMapping = xmlMappings[i] as XmlTypeMapping; + XmlTypeMapping? xmlTypeMapping = xmlMappings[i] as XmlTypeMapping; if (xmlTypeMapping != null) { method.name = xmlTypeMapping.ElementName; method.ns = xmlTypeMapping.Namespace; } - _methods.Add(xmlMappings[i].Key, method); + _methods.Add(xmlMappings[i].Key!, method); } } @@ -136,11 +138,11 @@ internal void InitAssemblyMethods(XmlMapping[] xmlMappings) /// // SxS: This method does not take any resource name and does not expose any resources to the caller. // It's OK to suppress the SxS warning. - internal static Assembly LoadGeneratedAssembly(Type type, string defaultNamespace, out XmlSerializerImplementation contract) + internal static Assembly? LoadGeneratedAssembly(Type type, string? defaultNamespace, out XmlSerializerImplementation? contract) { - Assembly serializer = null; + Assembly? serializer = null; contract = null; - string serializerName = null; + string? serializerName = null; // check to see if we loading explicit pre-generated assembly object[] attrs = type.GetCustomAttributes(typeof(System.Xml.Serialization.XmlSerializerAssemblyAttribute), false); @@ -154,18 +156,18 @@ internal static Assembly LoadGeneratedAssembly(Type type, string defaultNamespac name.CodeBase = null; name.CultureInfo = CultureInfo.InvariantCulture; - string serializerPath = null; + string? serializerPath = null; try { if (!string.IsNullOrEmpty(type.Assembly.Location)) { - serializerPath = Path.Combine(Path.GetDirectoryName(type.Assembly.Location), serializerName + ".dll"); + serializerPath = Path.Combine(Path.GetDirectoryName(type.Assembly.Location)!, serializerName + ".dll"); } if ((string.IsNullOrEmpty(serializerPath) || !File.Exists(serializerPath)) && !string.IsNullOrEmpty(Assembly.GetEntryAssembly()?.Location)) { - serializerPath = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), serializerName + ".dll"); + serializerPath = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly()!.Location)!, serializerName + ".dll"); } if (!string.IsNullOrEmpty(serializerPath)) @@ -179,7 +181,7 @@ internal static Assembly LoadGeneratedAssembly(Type type, string defaultNamespac { throw; } - byte[] token = name.GetPublicKeyToken(); + byte[]? token = name.GetPublicKeyToken(); if (token != null && token.Length > 0) { // the parent assembly was signed, so do not try to LoadWithPartialName @@ -199,7 +201,7 @@ internal static Assembly LoadGeneratedAssembly(Type type, string defaultNamespac if (!IsSerializerVersionMatch(serializer, type, defaultNamespace)) { - XmlSerializationEventSource.Log.XmlSerializerExpired(serializerName, type.FullName); + XmlSerializationEventSource.Log.XmlSerializerExpired(serializerName, type.FullName!); return null; } } @@ -233,14 +235,14 @@ internal static Assembly LoadGeneratedAssembly(Type type, string defaultNamespac } } Type contractType = GetTypeFromAssembly(serializer, "XmlSerializerContract"); - contract = (XmlSerializerImplementation)Activator.CreateInstance(contractType); + contract = (XmlSerializerImplementation)Activator.CreateInstance(contractType)!; if (contract.CanSerialize(type)) return serializer; return null; } - private static bool IsSerializerVersionMatch(Assembly serializer, Type type, string defaultNamespace) + private static bool IsSerializerVersionMatch(Assembly serializer, Type type, string? defaultNamespace) { if (serializer == null) return false; @@ -268,21 +270,21 @@ private static string GenerateAssemblyId(Type type) for (int i = 0; i < list.Count; i++) { - sb.Append(list[i].ToString()); + sb.Append(list[i]!.ToString()); sb.Append(','); } return sb.ToString(); } - internal static bool GenerateSerializerToStream(XmlMapping[] xmlMappings, Type[] types, string defaultNamespace, Assembly assembly, Hashtable assemblies, Stream stream) + internal static bool GenerateSerializerToStream(XmlMapping[] xmlMappings, Type?[] types, string? defaultNamespace, Assembly? assembly, Hashtable assemblies, Stream stream) { var compiler = new Compiler(); try { var scopeTable = new Hashtable(); foreach (XmlMapping mapping in xmlMappings) - scopeTable[mapping.Scope] = mapping; + scopeTable[mapping.Scope!] = mapping; var scopes = new TypeScope[scopeTable.Keys.Count]; scopeTable.Keys.CopyTo(scopes, 0); @@ -295,7 +297,7 @@ internal static bool GenerateSerializerToStream(XmlMapping[] xmlMappings, Type[] { compiler.AddImport(t, importedTypes); Assembly a = t.Assembly; - string name = a.FullName; + string name = a.FullName!; if (assemblies[name] != null) { continue; @@ -321,7 +323,7 @@ internal static bool GenerateSerializerToStream(XmlMapping[] xmlMappings, Type[] { for (int i = 0; i < types.Length; i++) { - Type type = types[i]; + Type? type = types[i]; if (type == null) { continue; @@ -329,7 +331,7 @@ internal static bool GenerateSerializerToStream(XmlMapping[] xmlMappings, Type[] if (DynamicAssemblies.IsTypeDynamic(type)) { - throw new InvalidOperationException(SR.Format(SR.XmlPregenTypeDynamic, types[i].FullName)); + throw new InvalidOperationException(SR.Format(SR.XmlPregenTypeDynamic, types[i]!.FullName)); } } @@ -337,7 +339,7 @@ internal static bool GenerateSerializerToStream(XmlMapping[] xmlMappings, Type[] writer.Write(typeof(XmlSerializerVersionAttribute).FullName); writer.Write("("); writer.Write("ParentAssemblyId="); - ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, GenerateAssemblyId(types[0])); + ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, GenerateAssemblyId(types[0]!)); writer.Write(", Version="); ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, ThisAssembly.Version); if (defaultNamespace != null) @@ -352,12 +354,12 @@ internal static bool GenerateSerializerToStream(XmlMapping[] xmlMappings, Type[] var classes = new CodeIdentifiers(); classes.AddUnique("XmlSerializationWriter", "XmlSerializationWriter"); classes.AddUnique("XmlSerializationReader", "XmlSerializationReader"); - string suffix = null; + string? suffix = null; if (types != null && types.Length == 1 && types[0] != null) { - suffix = CodeIdentifier.MakeValid(types[0].Name); - if (types[0].IsArray) + suffix = CodeIdentifier.MakeValid(types[0]!.Name); + if (types[0]!.IsArray) { suffix += "Array"; } @@ -371,7 +373,7 @@ internal static bool GenerateSerializerToStream(XmlMapping[] xmlMappings, Type[] writerClass = classes.AddUnique(writerClass, writerClass); var writerCodeGen = new XmlSerializationWriterCodeGen(writer, scopes, "public", writerClass); writerCodeGen.GenerateBegin(); - string[] writeMethodNames = new string[xmlMappings.Length]; + string?[] writeMethodNames = new string[xmlMappings.Length]; for (int i = 0; i < xmlMappings.Length; i++) { @@ -385,10 +387,10 @@ internal static bool GenerateSerializerToStream(XmlMapping[] xmlMappings, Type[] readerClass = classes.AddUnique(readerClass, readerClass); var readerCodeGen = new XmlSerializationReaderCodeGen(writer, scopes, "public", readerClass); readerCodeGen.GenerateBegin(); - string[] readMethodNames = new string[xmlMappings.Length]; + string?[] readMethodNames = new string[xmlMappings.Length]; for (int i = 0; i < xmlMappings.Length; i++) { - readMethodNames[i] = readerCodeGen.GenerateElement(xmlMappings[i]); + readMethodNames[i] = readerCodeGen.GenerateElement(xmlMappings[i])!; } readerCodeGen.GenerateEnd(readMethodNames, xmlMappings, types); @@ -397,17 +399,17 @@ internal static bool GenerateSerializerToStream(XmlMapping[] xmlMappings, Type[] var serializers = new Hashtable(); for (int i = 0; i < xmlMappings.Length; i++) { - if (serializers[xmlMappings[i].Key] == null) + if (serializers[xmlMappings[i].Key!] == null) { - serializers[xmlMappings[i].Key] = readerCodeGen.GenerateTypedSerializer(readMethodNames[i], writeMethodNames[i], xmlMappings[i], classes, baseSerializer, readerClass, writerClass); + serializers[xmlMappings[i].Key!] = readerCodeGen.GenerateTypedSerializer(readMethodNames[i], writeMethodNames[i], xmlMappings[i], classes, baseSerializer, readerClass, writerClass); } } - readerCodeGen.GenerateSerializerContract("XmlSerializerContract", xmlMappings, types, readerClass, readMethodNames, writerClass, writeMethodNames, serializers); + readerCodeGen.GenerateSerializerContract("XmlSerializerContract", xmlMappings, types!, readerClass, readMethodNames, writerClass, writeMethodNames, serializers); writer.Indent--; writer.WriteLine("}"); - string codecontent = compiler.Source.ToString(); + string codecontent = compiler.Source.ToString()!; byte[] info = new UTF8Encoding(true).GetBytes(codecontent); stream.Write(info, 0, info.Length); stream.Flush(); @@ -419,11 +421,11 @@ internal static bool GenerateSerializerToStream(XmlMapping[] xmlMappings, Type[] } } - internal static Assembly GenerateRefEmitAssembly(XmlMapping[] xmlMappings, Type[] types, string defaultNamespace) + internal static Assembly GenerateRefEmitAssembly(XmlMapping[] xmlMappings, Type?[]? types, string? defaultNamespace) { var scopeTable = new Dictionary(); foreach (XmlMapping mapping in xmlMappings) - scopeTable[mapping.Scope] = mapping; + scopeTable[mapping.Scope!] = mapping; TypeScope[] scopes = new TypeScope[scopeTable.Keys.Count]; scopeTable.Keys.CopyTo(scopes, 0); @@ -434,18 +436,18 @@ internal static Assembly GenerateRefEmitAssembly(XmlMapping[] xmlMappings, Type[ { ConstructorInfo AssemblyVersionAttribute_ctor = typeof(AssemblyVersionAttribute).GetConstructor( new Type[] { typeof(string) } - ); - string assemblyVersion = types[0].Assembly.GetName().Version.ToString(); + )!; + string assemblyVersion = types[0]!.Assembly.GetName().Version!.ToString(); assemblyBuilder.SetCustomAttribute(new CustomAttributeBuilder(AssemblyVersionAttribute_ctor, new object[] { assemblyVersion })); } CodeIdentifiers classes = new CodeIdentifiers(); classes.AddUnique("XmlSerializationWriter", "XmlSerializationWriter"); classes.AddUnique("XmlSerializationReader", "XmlSerializationReader"); - string suffix = null; + string? suffix = null; if (types != null && types.Length == 1 && types[0] != null) { - suffix = CodeIdentifier.MakeValid(types[0].Name); - if (types[0].IsArray) + suffix = CodeIdentifier.MakeValid(types[0]!.Name); + if (types[0]!.IsArray) { suffix += "Array"; } @@ -463,7 +465,7 @@ internal static Assembly GenerateRefEmitAssembly(XmlMapping[] xmlMappings, Type[ for (int i = 0; i < xmlMappings.Length; i++) { - writeMethodNames[i] = writerCodeGen.GenerateElement(xmlMappings[i]); + writeMethodNames[i] = writerCodeGen.GenerateElement(xmlMappings[i])!; } Type writerType = writerCodeGen.GenerateEnd(); @@ -478,27 +480,27 @@ internal static Assembly GenerateRefEmitAssembly(XmlMapping[] xmlMappings, Type[ string[] readMethodNames = new string[xmlMappings.Length]; for (int i = 0; i < xmlMappings.Length; i++) { - readMethodNames[i] = readerCodeGen.GenerateElement(xmlMappings[i]); + readMethodNames[i] = readerCodeGen.GenerateElement(xmlMappings[i])!; } - readerCodeGen.GenerateEnd(readMethodNames, xmlMappings, types); + readerCodeGen.GenerateEnd(readMethodNames, xmlMappings, types!); string baseSerializer = readerCodeGen.GenerateBaseSerializer("XmlSerializer1", readerClass, writerClass, classes); var serializers = new Dictionary(); for (int i = 0; i < xmlMappings.Length; i++) { - if (!serializers.ContainsKey(xmlMappings[i].Key)) + if (!serializers.ContainsKey(xmlMappings[i].Key!)) { - serializers[xmlMappings[i].Key] = readerCodeGen.GenerateTypedSerializer(readMethodNames[i], writeMethodNames[i], xmlMappings[i], classes, baseSerializer, readerClass, writerClass); + serializers[xmlMappings[i].Key!] = readerCodeGen.GenerateTypedSerializer(readMethodNames[i], writeMethodNames[i], xmlMappings[i], classes, baseSerializer, readerClass, writerClass); } } - readerCodeGen.GenerateSerializerContract("XmlSerializerContract", xmlMappings, types, readerClass, readMethodNames, writerClass, writeMethodNames, serializers); + readerCodeGen.GenerateSerializerContract("XmlSerializerContract", xmlMappings, types!, readerClass, readMethodNames, writerClass, writeMethodNames, serializers); return writerType.Assembly; } private static MethodInfo GetMethodFromType(Type type, string methodName) { - MethodInfo method = type.GetMethod(methodName); + MethodInfo? method = type.GetMethod(methodName); if (method != null) return method; @@ -510,7 +512,7 @@ private static MethodInfo GetMethodFromType(Type type, string methodName) internal static Type GetTypeFromAssembly(Assembly assembly, string typeName) { typeName = GeneratedAssemblyNamespace + "." + typeName; - Type type = assembly.GetType(typeName); + Type? type = assembly.GetType(typeName); if (type == null) throw new InvalidOperationException(SR.Format(SR.XmlMissingType, typeName, assembly.FullName)); return type; @@ -525,15 +527,16 @@ internal bool CanRead(XmlMapping mapping, XmlReader xmlReader) { return true; } - TempMethod method = _methods[mapping.Key]; - return xmlReader.IsStartElement(method.name, method.ns); + TempMethod method = _methods![mapping.Key!]; + return xmlReader.IsStartElement(method.name!, method.ns!); } - private string ValidateEncodingStyle(string encodingStyle, string methodKey) + [return: NotNullIfNotNull("encodingStyle")] + private string? ValidateEncodingStyle(string? encodingStyle, string methodKey) { if (encodingStyle != null && encodingStyle.Length > 0) { - if (_methods[methodKey].isSoap) + if (_methods![methodKey].isSoap) { if (encodingStyle != Soap.Encoding && encodingStyle != Soap12.Encoding) { @@ -547,7 +550,7 @@ private string ValidateEncodingStyle(string encodingStyle, string methodKey) } else { - if (_methods[methodKey].isSoap) + if (_methods![methodKey].isSoap) { encodingStyle = Soap.Encoding; } @@ -555,28 +558,28 @@ private string ValidateEncodingStyle(string encodingStyle, string methodKey) return encodingStyle; } - internal object InvokeReader(XmlMapping mapping, XmlReader xmlReader, XmlDeserializationEvents events, string encodingStyle) + internal object? InvokeReader(XmlMapping mapping, XmlReader xmlReader, XmlDeserializationEvents events, string? encodingStyle) { - XmlSerializationReader reader = null; + XmlSerializationReader? reader = null; try { - encodingStyle = ValidateEncodingStyle(encodingStyle, mapping.Key); + encodingStyle = ValidateEncodingStyle(encodingStyle, mapping.Key!); reader = Contract.Reader; reader.Init(xmlReader, events, encodingStyle, this); - if (_methods[mapping.Key].readMethod == null) + if (_methods![mapping.Key!].readMethod == null) { if (_readerMethods == null) { _readerMethods = Contract.ReadMethods; } - string methodName = (string)_readerMethods[mapping.Key]; + string? methodName = (string?)_readerMethods[mapping.Key!]; if (methodName == null) { throw new InvalidOperationException(SR.Format(SR.XmlNotSerializable, mapping.Accessor.Name)); } - _methods[mapping.Key].readMethod = GetMethodFromType(reader.GetType(), methodName); + _methods[mapping.Key!].readMethod = GetMethodFromType(reader.GetType(), methodName); } - return _methods[mapping.Key].readMethod.Invoke(reader, Array.Empty()); + return _methods[mapping.Key!].readMethod!.Invoke(reader, Array.Empty()); } catch (SecurityException e) { @@ -589,28 +592,28 @@ internal object InvokeReader(XmlMapping mapping, XmlReader xmlReader, XmlDeseria } } - internal void InvokeWriter(XmlMapping mapping, XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle, string id) + internal void InvokeWriter(XmlMapping mapping, XmlWriter xmlWriter, object? o, XmlSerializerNamespaces? namespaces, string? encodingStyle, string? id) { - XmlSerializationWriter writer = null; + XmlSerializationWriter? writer = null; try { - encodingStyle = ValidateEncodingStyle(encodingStyle, mapping.Key); + encodingStyle = ValidateEncodingStyle(encodingStyle, mapping.Key!); writer = Contract.Writer; writer.Init(xmlWriter, namespaces, encodingStyle, id, this); - if (_methods[mapping.Key].writeMethod == null) + if (_methods![mapping.Key!].writeMethod == null) { if (_writerMethods == null) { _writerMethods = Contract.WriteMethods; } - string methodName = (string)_writerMethods[mapping.Key]; + string? methodName = (string?)_writerMethods[mapping.Key!]; if (methodName == null) { throw new InvalidOperationException(SR.Format(SR.XmlNotSerializable, mapping.Accessor.Name)); } - _methods[mapping.Key].writeMethod = GetMethodFromType(writer.GetType(), methodName); + _methods[mapping.Key!].writeMethod = GetMethodFromType(writer.GetType(), methodName); } - _methods[mapping.Key].writeMethod.Invoke(writer, new object[] { o }); + _methods[mapping.Key!].writeMethod!.Invoke(writer, new object?[] { o }); } catch (SecurityException e) { @@ -630,18 +633,18 @@ internal sealed class TempMethodDictionary : Dictionary internal class TempAssemblyCacheKey { - private readonly string _ns; + private readonly string? _ns; private readonly object _type; - internal TempAssemblyCacheKey(string ns, object type) + internal TempAssemblyCacheKey(string? ns, object type) { _type = type; _ns = ns; } - public override bool Equals(object o) + public override bool Equals(object? o) { - TempAssemblyCacheKey key = o as TempAssemblyCacheKey; + TempAssemblyCacheKey? key = o as TempAssemblyCacheKey; if (key == null) return false; return (key._type == _type && key._ns == _ns); @@ -657,22 +660,22 @@ internal class TempAssemblyCache { private Dictionary _cache = new Dictionary(); - internal TempAssembly this[string ns, object o] + internal TempAssembly? this[string? ns, object o] { get { - TempAssembly tempAssembly; + TempAssembly? tempAssembly; _cache.TryGetValue(new TempAssemblyCacheKey(ns, o), out tempAssembly); return tempAssembly; } } - internal void Add(string ns, object o, TempAssembly assembly) + internal void Add(string? ns, object o, TempAssembly assembly) { TempAssemblyCacheKey key = new TempAssemblyCacheKey(ns, o); lock (this) { - TempAssembly tempAssembly; + TempAssembly? tempAssembly; if (_cache.TryGetValue(key, out tempAssembly) && tempAssembly == assembly) return; Dictionary _copy = new Dictionary(_cache); // clone diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Compiler.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Compiler.cs index c5782f3cff3fd0..5de0d1bb434a58 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Compiler.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Compiler.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System.Reflection; @@ -26,7 +27,7 @@ internal class Compiler // SxS: This method does not take any resource name and does not expose any resources to the caller. // It's OK to suppress the SxS warning. - internal void AddImport(Type type, Hashtable types) + internal void AddImport(Type? type, Hashtable types) { if (type == null) return; @@ -35,11 +36,11 @@ internal void AddImport(Type type, Hashtable types) if (types[type] != null) return; types[type] = type; - Type baseType = type.BaseType; + Type? baseType = type.BaseType; if (baseType != null) AddImport(baseType, types); - Type declaringType = type.DeclaringType; + Type? declaringType = type.DeclaringType; if (declaringType != null) AddImport(declaringType, types); @@ -76,7 +77,8 @@ internal void AddImport(Type type, Hashtable types) object[] typeForwardedFromAttribute = type.GetCustomAttributes(typeof(TypeForwardedFromAttribute), false); if (typeForwardedFromAttribute.Length > 0) { - TypeForwardedFromAttribute originalAssemblyInfo = typeForwardedFromAttribute[0] as TypeForwardedFromAttribute; + TypeForwardedFromAttribute? originalAssemblyInfo = typeForwardedFromAttribute[0] as TypeForwardedFromAttribute; + Debug.Assert(originalAssemblyInfo != null); Assembly originalAssembly = Assembly.Load(new AssemblyName(originalAssemblyInfo.AssemblyFullName)); } } @@ -94,7 +96,7 @@ internal TextWriter Source get { return _writer; } } - internal static string GetTempAssemblyName(AssemblyName parent, string ns) + internal static string GetTempAssemblyName(AssemblyName parent, string? ns) { return parent.Name + ".XmlSerializers" + (ns == null || ns.Length == 0 ? "" : "." + ns.GetHashCode()); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Configuration/DateTimeSerializationSection.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Configuration/DateTimeSerializationSection.cs index c841409eaea8c1..bad80f2ac8ae30 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Configuration/DateTimeSerializationSection.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Configuration/DateTimeSerializationSection.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization.Configuration { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Globals.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Globals.cs index 1a83cd547d992c..868c60cc311262 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Globals.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Globals.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System.Diagnostics.CodeAnalysis; using System.Security; using System.Reflection; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/IXmlSerializable.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/IXmlSerializable.cs index 7dcea55f073831..e2d444a36bf050 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/IXmlSerializable.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/IXmlSerializable.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System.Xml; @@ -12,7 +13,7 @@ namespace System.Xml.Serialization /// public interface IXmlSerializable { - XmlSchema GetSchema(); + XmlSchema? GetSchema(); void ReadXml(XmlReader reader); void WriteXml(XmlWriter writer); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/IXmlTextParser.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/IXmlTextParser.cs index 4e1acb19e25816..685485f3da0dfa 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/IXmlTextParser.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/IXmlTextParser.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System.Xml; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ImportContext.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ImportContext.cs index 79cedd9bb3bd3a..6af84291c6edf5 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ImportContext.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ImportContext.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; @@ -15,16 +16,17 @@ namespace System.Xml.Serialization public class ImportContext { private readonly bool _shareTypes; - private SchemaObjectCache _cache; // cached schema top-level items - private Hashtable _mappings; // XmlSchema -> SerializableMapping, XmlSchemaSimpleType -> EnumMapping, XmlSchemaComplexType -> StructMapping - private Hashtable _elements; // XmlSchemaElement -> ElementAccessor - private CodeIdentifiers _typeIdentifiers; + private SchemaObjectCache? _cache; // cached schema top-level items + private Hashtable? _mappings; // XmlSchema -> SerializableMapping, XmlSchemaSimpleType -> EnumMapping, XmlSchemaComplexType -> StructMapping + private Hashtable? _elements; // XmlSchemaElement -> ElementAccessor + private CodeIdentifiers? _typeIdentifiers; - public ImportContext(CodeIdentifiers identifiers, bool shareTypes) + public ImportContext(CodeIdentifiers? identifiers, bool shareTypes) { _typeIdentifiers = identifiers; _shareTypes = shareTypes; } + internal ImportContext() : this(null, false) { } internal SchemaObjectCache Cache @@ -80,10 +82,10 @@ public StringCollection Warnings internal class SchemaObjectCache { - private Hashtable _graph; - private Hashtable _hash; - private Hashtable _objectCache; - private StringCollection _warnings; + private Hashtable? _graph; + private Hashtable? _hash; + private Hashtable? _objectCache; + private StringCollection? _warnings; // UNDONE remove me soon, this is debug only code internal Hashtable looks = new Hashtable(); private Hashtable Graph @@ -126,7 +128,7 @@ internal StringCollection Warnings } } - internal XmlSchemaObject AddItem(XmlSchemaObject item, XmlQualifiedName qname, XmlSchemas schemas) + internal XmlSchemaObject? AddItem(XmlSchemaObject? item, XmlQualifiedName? qname, XmlSchemas schemas) { if (item == null) return null; @@ -134,7 +136,7 @@ internal XmlSchemaObject AddItem(XmlSchemaObject item, XmlQualifiedName qname, X return null; string key = item.GetType().Name + ":" + qname.ToString(); - ArrayList list = (ArrayList)ObjectCache[key]; + ArrayList? list = (ArrayList?)ObjectCache[key]; if (list == null) { list = new ArrayList(); @@ -143,7 +145,7 @@ internal XmlSchemaObject AddItem(XmlSchemaObject item, XmlQualifiedName qname, X for (int i = 0; i < list.Count; i++) { - XmlSchemaObject cachedItem = (XmlSchemaObject)list[i]; + XmlSchemaObject cachedItem = (XmlSchemaObject)list[i]!; if (cachedItem == item) return cachedItem; @@ -154,7 +156,7 @@ internal XmlSchemaObject AddItem(XmlSchemaObject item, XmlQualifiedName qname, X else { Warnings.Add(SR.Format(SR.XmlMismatchSchemaObjects, item.GetType().Name, qname.Name, qname.Namespace)); - Warnings.Add("DEBUG:Cached item key:\r\n" + (string)looks[cachedItem] + "\r\nnew item key:\r\n" + (string)looks[item]); + Warnings.Add("DEBUG:Cached item key:\r\n" + (string?)looks[cachedItem] + "\r\nnew item key:\r\n" + (string?)looks[item]); } } // no match found we need to insert the new type in the cache @@ -170,7 +172,7 @@ internal bool Match(XmlSchemaObject o1, XmlSchemaObject o2, bool shareTypes) return false; if (Hash[o1] == null) Hash[o1] = GetHash(o1); - int hash1 = (int)Hash[o1]; + int hash1 = (int)Hash[o1]!; int hash2 = GetHash(o2); if (hash1 != hash2) return false; @@ -186,12 +188,12 @@ private ArrayList GetDependencies(XmlSchemaObject o, ArrayList deps, Hashtable r { refs[o] = o; deps.Add(o); - ArrayList list = Graph[o] as ArrayList; + ArrayList? list = Graph[o] as ArrayList; if (list != null) { for (int i = 0; i < list.Count; i++) { - GetDependencies((XmlSchemaObject)list[i], deps, refs); + GetDependencies((XmlSchemaObject)list[i]!, deps, refs); } } } @@ -204,7 +206,7 @@ private int CompositeHash(XmlSchemaObject o, int hash) double tmp = 0; for (int i = 0; i < list.Count; i++) { - object cachedHash = Hash[list[i]]; + object? cachedHash = Hash[list[i]!]; if (cachedHash is int) { tmp += (int)cachedHash / list.Count; @@ -220,13 +222,13 @@ internal void GenerateSchemaGraph(XmlSchemas schemas) for (int i = 0; i < items.Count; i++) { - GetHash((XmlSchemaObject)items[i]); + GetHash((XmlSchemaObject)items[i]!); } } private int GetHash(XmlSchemaObject o) { - object hash = Hash[o]; + object? hash = Hash[o]; if (hash != null) { if (hash is XmlSchemaObject) @@ -279,15 +281,15 @@ internal ArrayList GetItems() return new ArrayList(_scope.Keys); } - internal void AddRef(ArrayList list, XmlSchemaObject o) + internal void AddRef(ArrayList list, XmlSchemaObject? o) { if (o == null) return; if (_schemas.IsReference(o)) return; - if (o.Parent is XmlSchema) + if (o.Parent is XmlSchema parent) { - string ns = ((XmlSchema)o.Parent).TargetNamespace; + string? ns = parent.TargetNamespace; if (ns == XmlSchema.Namespace) return; if (list.Contains(o)) @@ -301,7 +303,7 @@ internal ArrayList Depends(XmlSchemaObject item) if (item.Parent is XmlSchema) { if (_scope[item] != null) - return (ArrayList)_scope[item]; + return (ArrayList)_scope[item]!; ArrayList refs = new ArrayList(); Depends(item, refs); @@ -311,7 +313,7 @@ internal ArrayList Depends(XmlSchemaObject item) return _empty; } - internal void Depends(XmlSchemaObject item, ArrayList refs) + internal void Depends(XmlSchemaObject? item, ArrayList refs) { if (item == null || _scope[item] != null) return; @@ -320,16 +322,16 @@ internal void Depends(XmlSchemaObject item, ArrayList refs) if (typeof(XmlSchemaType).IsAssignableFrom(t)) { XmlQualifiedName baseName = XmlQualifiedName.Empty; - XmlSchemaType baseType = null; - XmlSchemaParticle particle = null; - XmlSchemaObjectCollection attributes = null; + XmlSchemaType? baseType = null; + XmlSchemaParticle? particle = null; + XmlSchemaObjectCollection? attributes = null; if (item is XmlSchemaComplexType) { XmlSchemaComplexType ct = (XmlSchemaComplexType)item; if (ct.ContentModel != null) { - XmlSchemaContent content = ct.ContentModel.Content; + XmlSchemaContent? content = ct.ContentModel.Content; if (content is XmlSchemaComplexContentRestriction) { baseName = ((XmlSchemaComplexContentRestriction)content).BaseTypeName; @@ -366,7 +368,7 @@ internal void Depends(XmlSchemaObject item, ArrayList refs) if (particle is XmlSchemaGroupRef) { XmlSchemaGroupRef refGroup = (XmlSchemaGroupRef)particle; - particle = ((XmlSchemaGroup)_schemas.Find(refGroup.RefName, typeof(XmlSchemaGroup), false)).Particle; + particle = ((XmlSchemaGroup)_schemas.Find(refGroup.RefName, typeof(XmlSchemaGroup), false)!).Particle; } else if (particle is XmlSchemaGroupBase) { @@ -376,7 +378,7 @@ internal void Depends(XmlSchemaObject item, ArrayList refs) else if (item is XmlSchemaSimpleType) { XmlSchemaSimpleType simpleType = (XmlSchemaSimpleType)item; - XmlSchemaSimpleTypeContent content = simpleType.Content; + XmlSchemaSimpleTypeContent? content = simpleType.Content; if (content is XmlSchemaSimpleTypeRestriction) { baseType = ((XmlSchemaSimpleTypeRestriction)content).BaseType; @@ -394,20 +396,20 @@ internal void Depends(XmlSchemaObject item, ArrayList refs) } else if (t == typeof(XmlSchemaSimpleTypeUnion)) { - XmlQualifiedName[] memberTypes = ((XmlSchemaSimpleTypeUnion)item).MemberTypes; + XmlQualifiedName[]? memberTypes = ((XmlSchemaSimpleTypeUnion)item).MemberTypes; if (memberTypes != null) { for (int i = 0; i < memberTypes.Length; i++) { - XmlSchemaType type = (XmlSchemaType)_schemas.Find(memberTypes[i], typeof(XmlSchemaType), false); + XmlSchemaType? type = (XmlSchemaType?)_schemas.Find(memberTypes[i], typeof(XmlSchemaType), false); AddRef(refs, type); } } } } if (baseType == null && !baseName.IsEmpty && baseName.Namespace != XmlSchema.Namespace) - baseType = (XmlSchemaType)_schemas.Find(baseName, typeof(XmlSchemaType), false); + baseType = (XmlSchemaType?)_schemas.Find(baseName, typeof(XmlSchemaType), false); if (baseType != null) { @@ -432,18 +434,18 @@ internal void Depends(XmlSchemaObject item, ArrayList refs) { if (el.SubstitutionGroup.Namespace != XmlSchema.Namespace) { - XmlSchemaElement head = (XmlSchemaElement)_schemas.Find(el.SubstitutionGroup, typeof(XmlSchemaElement), false); + XmlSchemaElement? head = (XmlSchemaElement?)_schemas.Find(el.SubstitutionGroup, typeof(XmlSchemaElement), false); AddRef(refs, head); } } if (!el.RefName.IsEmpty) { - el = (XmlSchemaElement)_schemas.Find(el.RefName, typeof(XmlSchemaElement), false); + el = (XmlSchemaElement)_schemas.Find(el.RefName, typeof(XmlSchemaElement), false)!; AddRef(refs, el); } else if (!el.SchemaTypeName.IsEmpty) { - XmlSchemaType type = (XmlSchemaType)_schemas.Find(el.SchemaTypeName, typeof(XmlSchemaType), false); + XmlSchemaType? type = (XmlSchemaType?)_schemas.Find(el.SchemaTypeName, typeof(XmlSchemaType), false); AddRef(refs, type); } else @@ -453,11 +455,11 @@ internal void Depends(XmlSchemaObject item, ArrayList refs) } else if (t == typeof(XmlSchemaGroup)) { - Depends(((XmlSchemaGroup)item).Particle); + Depends(((XmlSchemaGroup)item).Particle!); } else if (t == typeof(XmlSchemaGroupRef)) { - XmlSchemaGroup group = (XmlSchemaGroup)_schemas.Find(((XmlSchemaGroupRef)item).RefName, typeof(XmlSchemaGroup), false); + XmlSchemaGroup? group = (XmlSchemaGroup?)_schemas.Find(((XmlSchemaGroupRef)item).RefName, typeof(XmlSchemaGroup), false); AddRef(refs, group); } else if (typeof(XmlSchemaGroupBase).IsAssignableFrom(t)) @@ -469,7 +471,7 @@ internal void Depends(XmlSchemaObject item, ArrayList refs) } else if (t == typeof(XmlSchemaAttributeGroupRef)) { - XmlSchemaAttributeGroup group = (XmlSchemaAttributeGroup)_schemas.Find(((XmlSchemaAttributeGroupRef)item).RefName, typeof(XmlSchemaAttributeGroup), false); + XmlSchemaAttributeGroup? group = (XmlSchemaAttributeGroup?)_schemas.Find(((XmlSchemaAttributeGroupRef)item).RefName, typeof(XmlSchemaAttributeGroup), false); AddRef(refs, group); } else if (t == typeof(XmlSchemaAttributeGroup)) @@ -481,15 +483,15 @@ internal void Depends(XmlSchemaObject item, ArrayList refs) } else if (t == typeof(XmlSchemaAttribute)) { - XmlSchemaAttribute at = (XmlSchemaAttribute)item; + XmlSchemaAttribute? at = (XmlSchemaAttribute)item; if (!at.RefName.IsEmpty) { - at = (XmlSchemaAttribute)_schemas.Find(at.RefName, typeof(XmlSchemaAttribute), false); + at = (XmlSchemaAttribute?)_schemas.Find(at.RefName, typeof(XmlSchemaAttribute), false); AddRef(refs, at); } else if (!at.SchemaTypeName.IsEmpty) { - XmlSchemaType type = (XmlSchemaType)_schemas.Find(at.SchemaTypeName, typeof(XmlSchemaType), false); + XmlSchemaType? type = (XmlSchemaType?)_schemas.Find(at.SchemaTypeName, typeof(XmlSchemaType), false); AddRef(refs, type); } else @@ -499,7 +501,7 @@ internal void Depends(XmlSchemaObject item, ArrayList refs) } if (typeof(XmlSchemaAnnotated).IsAssignableFrom(t)) { - XmlAttribute[] attrs = (XmlAttribute[])((XmlSchemaAnnotated)item).UnhandledAttributes; + XmlAttribute[]? attrs = (XmlAttribute[]?)((XmlSchemaAnnotated)item).UnhandledAttributes; if (attrs != null) { @@ -510,7 +512,7 @@ internal void Depends(XmlSchemaObject item, ArrayList refs) { string dims; XmlQualifiedName qname = TypeScope.ParseWsdlArrayType(attribute.Value, out dims, item); - XmlSchemaType type = (XmlSchemaType)_schemas.Find(qname, typeof(XmlSchemaType), false); + XmlSchemaType? type = (XmlSchemaType?)_schemas.Find(qname, typeof(XmlSchemaType), false); AddRef(refs, type); } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Mappings.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Mappings.cs index d77c6828383e79..9a67c0df253350 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Mappings.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Mappings.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System.Reflection; @@ -11,6 +12,7 @@ namespace System.Xml.Serialization using System.ComponentModel; using System.Xml; using System.Xml.Serialization; + using System.Diagnostics.CodeAnalysis; // These classes represent a mapping between classes and a particular XML format. // There are two class of mapping information: accessors (such as elements and @@ -18,12 +20,12 @@ namespace System.Xml.Serialization internal abstract class Accessor { - private string _name; - private object _defaultValue; - private string _ns; - private TypeMapping _mapping; + private string? _name; + private object? _defaultValue; + private string? _ns; + private TypeMapping? _mapping; private bool _any; - private string _anyNs; + private string? _anyNs; private bool _topLevelInSchema; private bool _isFixed; private bool _isOptional; @@ -31,13 +33,13 @@ internal abstract class Accessor internal Accessor() { } - internal TypeMapping Mapping + internal TypeMapping? Mapping { get { return _mapping; } set { _mapping = value; } } - internal object Default + internal object? Default { get { return _defaultValue; } set { _defaultValue = value; } @@ -48,6 +50,7 @@ internal bool HasDefault get { return _defaultValue != null && _defaultValue != DBNull.Value; } } + [AllowNull] internal virtual string Name { get { return _name == null ? string.Empty : _name; } @@ -60,13 +63,13 @@ internal bool Any set { _any = value; } } - internal string AnyNamespaces + internal string? AnyNamespaces { get { return _anyNs; } set { _anyNs = value; } } - internal string Namespace + internal string? Namespace { get { return _ns; } set { _ns = value; } @@ -96,13 +99,15 @@ internal bool IsTopLevelInSchema set { _topLevelInSchema = value; } } - internal static string EscapeName(string name) + [return: NotNullIfNotNull("name")] + internal static string? EscapeName(string? name) { if (name == null || name.Length == 0) return name; return XmlConvert.EncodeLocalName(name); } - internal static string EscapeQName(string name) + [return: NotNullIfNotNull("name")] + internal static string? EscapeQName(string? name) { if (name == null || name.Length == 0) return name; int colon = name.LastIndexOf(':'); @@ -116,12 +121,13 @@ internal static string EscapeQName(string name) } } - internal static string UnescapeName(string name) + [return: NotNullIfNotNull("name")] + internal static string? UnescapeName(string? name) { return XmlConvert.DecodeName(name); } - internal string ToString(string defaultNs) + internal string ToString(string? defaultNs) { if (Any) { @@ -177,23 +183,23 @@ internal ElementAccessor Clone() internal class ChoiceIdentifierAccessor : Accessor { - private string _memberName; - private string[] _memberIds; - private MemberInfo _memberInfo; + private string? _memberName; + private string[]? _memberIds; + private MemberInfo? _memberInfo; - internal string MemberName + internal string? MemberName { get { return _memberName; } set { _memberName = value; } } - internal string[] MemberIds + internal string[]? MemberIds { get { return _memberIds; } set { _memberIds = value; } } - internal MemberInfo MemberInfo + internal MemberInfo? MemberInfo { get { return _memberInfo; } set { _memberInfo = value; } @@ -276,9 +282,9 @@ internal bool IsSoap internal abstract class TypeMapping : Mapping { - private TypeDesc _typeDesc; - private string _typeNs; - private string _typeName; + private TypeDesc? _typeDesc; + private string? _typeNs; + private string? _typeName; private bool _referencedByElement; private bool _referencedByTopLevelElement; private bool _includeInSchema = true; @@ -295,19 +301,19 @@ internal bool ReferencedByElement get { return _referencedByElement || _referencedByTopLevelElement; } set { _referencedByElement = value; } } - internal string Namespace + internal string? Namespace { get { return _typeNs; } set { _typeNs = value; } } - internal string TypeName + internal string? TypeName { get { return _typeName; } set { _typeName = value; } } - internal TypeDesc TypeDesc + internal TypeDesc? TypeDesc { get { return _typeDesc; } set { _typeDesc = value; } @@ -331,6 +337,7 @@ internal bool IsReference set { _reference = value; } } + [MemberNotNullWhen(false, nameof(_typeName))] internal bool IsAnonymousType { get { return _typeName == null || _typeName.Length == 0; } @@ -338,7 +345,7 @@ internal bool IsAnonymousType internal virtual string DefaultElementName { - get { return IsAnonymousType ? XmlConvert.EncodeLocalName(_typeDesc.Name) : _typeName; } + get { return IsAnonymousType ? XmlConvert.EncodeLocalName(_typeDesc!.Name) : _typeName; } } } @@ -355,9 +362,9 @@ internal override bool IsList internal class NullableMapping : TypeMapping { - private TypeMapping _baseMapping; + private TypeMapping? _baseMapping; - internal TypeMapping BaseMapping + internal TypeMapping? BaseMapping { get { return _baseMapping; } set { _baseMapping = value; } @@ -365,24 +372,24 @@ internal TypeMapping BaseMapping internal override string DefaultElementName { - get { return BaseMapping.DefaultElementName; } + get { return BaseMapping!.DefaultElementName; } } } internal class ArrayMapping : TypeMapping { - private ElementAccessor[] _elements; - private ElementAccessor[] _sortedElements; - private ArrayMapping _next; - private StructMapping _topLevelMapping; + private ElementAccessor[]? _elements; + private ElementAccessor[]? _sortedElements; + private ArrayMapping? _next; + private StructMapping? _topLevelMapping; - internal ElementAccessor[] Elements + internal ElementAccessor[]? Elements { get { return _elements; } set { _elements = value; _sortedElements = null; } } - internal ElementAccessor[] ElementsSortedByDerivation + internal ElementAccessor[]? ElementsSortedByDerivation { get { @@ -398,13 +405,13 @@ internal ElementAccessor[] ElementsSortedByDerivation } - internal ArrayMapping Next + internal ArrayMapping? Next { get { return _next; } set { _next = value; } } - internal StructMapping TopLevelMapping + internal StructMapping? TopLevelMapping { get { return _topLevelMapping; } set { _topLevelMapping = value; } @@ -413,7 +420,7 @@ internal StructMapping TopLevelMapping internal class EnumMapping : PrimitiveMapping { - private ConstantMapping[] _constants; + private ConstantMapping[]? _constants; private bool _isFlags; internal bool IsFlags @@ -422,7 +429,7 @@ internal bool IsFlags set { _isFlags = value; } } - internal ConstantMapping[] Constants + internal ConstantMapping[]? Constants { get { return _constants; } set { _constants = value; } @@ -431,16 +438,18 @@ internal ConstantMapping[] Constants internal class ConstantMapping : Mapping { - private string _xmlName; - private string _name; + private string? _xmlName; + private string? _name; private long _value; + [AllowNull] internal string XmlName { get { return _xmlName == null ? string.Empty : _xmlName; } set { _xmlName = value; } } + [AllowNull] internal string Name { get { return _name == null ? string.Empty : _name; } @@ -456,19 +465,20 @@ internal long Value internal class StructMapping : TypeMapping, INameScope { - private MemberMapping[] _members; - private StructMapping _baseMapping; - private StructMapping _derivedMappings; - private StructMapping _nextDerivedMapping; - private MemberMapping _xmlnsMember; + private MemberMapping[]? _members; + private StructMapping? _baseMapping; + private StructMapping? _derivedMappings; + private StructMapping? _nextDerivedMapping; + private MemberMapping? _xmlnsMember; private bool _hasSimpleContent; private bool _openModel; private bool _isSequence; - private NameTable _elements; - private NameTable _attributes; - private CodeIdentifiers _scope; + private NameTable? _elements; + private NameTable? _attributes; + private CodeIdentifiers? _scope; - internal StructMapping BaseMapping + [DisallowNull] + internal StructMapping? BaseMapping { get { return _baseMapping; } set @@ -482,9 +492,9 @@ internal StructMapping BaseMapping if (value._isSequence && !_isSequence) { _isSequence = true; - if (_baseMapping.IsSequence) + if (_baseMapping!.IsSequence) { - for (StructMapping derived = _derivedMappings; derived != null; derived = derived.NextDerivedMapping) + for (StructMapping? derived = _derivedMappings; derived != null; derived = derived.NextDerivedMapping) { derived.SetSequence(); } @@ -493,7 +503,7 @@ internal StructMapping BaseMapping } } - internal StructMapping DerivedMappings + internal StructMapping? DerivedMappings { get { return _derivedMappings; } } @@ -521,11 +531,11 @@ internal NameTable LocalAttributes return _attributes; } } - object INameScope.this[string name, string ns] + object? INameScope.this[string? name, string? ns] { get { - object named = LocalElements[name, ns]; + object? named = LocalElements[name, ns]; if (named != null) return named; if (_baseMapping != null) @@ -537,7 +547,7 @@ internal NameTable LocalAttributes LocalElements[name, ns] = value; } } - internal StructMapping NextDerivedMapping + internal StructMapping? NextDerivedMapping { get { return _nextDerivedMapping; } } @@ -551,7 +561,7 @@ internal bool HasXmlnsMember { get { - StructMapping mapping = this; + StructMapping? mapping = this; while (mapping != null) { if (mapping.XmlnsMember != null) @@ -562,13 +572,13 @@ internal bool HasXmlnsMember } } - internal MemberMapping[] Members + internal MemberMapping[]? Members { get { return _members; } set { _members = value; } } - internal MemberMapping XmlnsMember + internal MemberMapping? XmlnsMember { get { return _xmlnsMember; } set { _xmlnsMember = value; } @@ -591,12 +601,12 @@ internal CodeIdentifiers Scope set { _scope = value; } } - internal MemberMapping FindDeclaringMapping(MemberMapping member, out StructMapping declaringMapping, string parent) + internal MemberMapping? FindDeclaringMapping(MemberMapping member, out StructMapping? declaringMapping, string? parent) { declaringMapping = null; if (BaseMapping != null) { - MemberMapping baseMember = BaseMapping.FindDeclaringMapping(member, out declaringMapping, parent); + MemberMapping? baseMember = BaseMapping.FindDeclaringMapping(member, out declaringMapping, parent); if (baseMember != null) return baseMember; } if (_members == null) return null; @@ -606,7 +616,7 @@ internal MemberMapping FindDeclaringMapping(MemberMapping member, out StructMapp if (_members[i].Name == member.Name) { if (_members[i].TypeDesc != member.TypeDesc) - throw new InvalidOperationException(SR.Format(SR.XmlHiddenMember, parent, member.Name, member.TypeDesc.FullName, this.TypeName, _members[i].Name, _members[i].TypeDesc.FullName)); + throw new InvalidOperationException(SR.Format(SR.XmlHiddenMember, parent, member.Name, member.TypeDesc!.FullName, this.TypeName, _members[i].Name, _members[i].TypeDesc!.FullName)); else if (!_members[i].Match(member)) { throw new InvalidOperationException(SR.Format(SR.XmlInvalidXmlOverride, parent, member.Name, this.TypeName, _members[i].Name)); @@ -617,24 +627,24 @@ internal MemberMapping FindDeclaringMapping(MemberMapping member, out StructMapp } return null; } - internal bool Declares(MemberMapping member, string parent) + internal bool Declares(MemberMapping member, string? parent) { - StructMapping m; + StructMapping? m; return (FindDeclaringMapping(member, out m, parent) != null); } - internal void SetContentModel(TextAccessor text, bool hasElements) + internal void SetContentModel(TextAccessor? text, bool hasElements) { - if (BaseMapping == null || BaseMapping.TypeDesc.IsRoot) + if (BaseMapping == null || BaseMapping.TypeDesc!.IsRoot) { - _hasSimpleContent = !hasElements && text != null && !text.Mapping.IsList; + _hasSimpleContent = !hasElements && text != null && !text.Mapping!.IsList; } else if (BaseMapping.HasSimpleContent) { if (text != null || hasElements) { // we can only extent a simleContent type with attributes - throw new InvalidOperationException(SR.Format(SR.XmlIllegalSimpleContentExtension, TypeDesc.FullName, BaseMapping.TypeDesc.FullName)); + throw new InvalidOperationException(SR.Format(SR.XmlIllegalSimpleContentExtension, TypeDesc!.FullName, BaseMapping.TypeDesc.FullName)); } else { @@ -645,9 +655,9 @@ internal void SetContentModel(TextAccessor text, bool hasElements) { _hasSimpleContent = false; } - if (!_hasSimpleContent && text != null && !text.Mapping.TypeDesc.CanBeTextValue && !(BaseMapping != null && !BaseMapping.TypeDesc.IsRoot && (text.Mapping.TypeDesc.IsEnum || text.Mapping.TypeDesc.IsPrimitive))) + if (!_hasSimpleContent && text != null && !text.Mapping!.TypeDesc!.CanBeTextValue && !(BaseMapping != null && !BaseMapping.TypeDesc!.IsRoot && (text.Mapping.TypeDesc.IsEnum || text.Mapping.TypeDesc.IsPrimitive))) { - throw new InvalidOperationException(SR.Format(SR.XmlIllegalTypedTextAttribute, TypeDesc.FullName, text.Name, text.Mapping.TypeDesc.FullName)); + throw new InvalidOperationException(SR.Format(SR.XmlIllegalTypedTextAttribute, TypeDesc!.FullName, text.Name, text.Mapping.TypeDesc.FullName)); } } @@ -668,17 +678,17 @@ internal bool HasExplicitSequence() internal void SetSequence() { - if (TypeDesc.IsRoot) + if (TypeDesc!.IsRoot) return; StructMapping start = this; // find first mapping that does not have the sequence set - while (start.BaseMapping != null && !start.BaseMapping.IsSequence && !start.BaseMapping.TypeDesc.IsRoot) + while (start.BaseMapping != null && !start.BaseMapping.IsSequence && !start.BaseMapping.TypeDesc!.IsRoot) start = start.BaseMapping; start.IsSequence = true; - for (StructMapping derived = start.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) + for (StructMapping? derived = start.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) { derived.SetSequence(); } @@ -686,20 +696,20 @@ internal void SetSequence() internal bool IsSequence { - get { return _isSequence && !TypeDesc.IsRoot; } + get { return _isSequence && !TypeDesc!.IsRoot; } set { _isSequence = value; } } } internal abstract class AccessorMapping : Mapping { - private TypeDesc _typeDesc; - private AttributeAccessor _attribute; - private ElementAccessor[] _elements; - private ElementAccessor[] _sortedElements; - private TextAccessor _text; - private ChoiceIdentifierAccessor _choiceIdentifier; - private XmlnsAccessor _xmlns; + private TypeDesc? _typeDesc; + private AttributeAccessor? _attribute; + private ElementAccessor[]? _elements; + private ElementAccessor[]? _sortedElements; + private TextAccessor? _text; + private ChoiceIdentifierAccessor? _choiceIdentifier; + private XmlnsAccessor? _xmlns; private bool _ignore; internal AccessorMapping() @@ -733,19 +743,19 @@ internal bool IsParticle get { return (_elements != null && _elements.Length > 0); } } - internal TypeDesc TypeDesc + internal TypeDesc? TypeDesc { get { return _typeDesc; } set { _typeDesc = value; } } - internal AttributeAccessor Attribute + internal AttributeAccessor? Attribute { get { return _attribute; } set { _attribute = value; } } - internal ElementAccessor[] Elements + internal ElementAccessor[]? Elements { get { return _elements; } set { _elements = value; _sortedElements = null; } @@ -758,14 +768,14 @@ internal static void SortMostToLeastDerived(ElementAccessor[] elements) internal class AccessorComparer : IComparer { - public int Compare(object o1, object o2) + public int Compare(object? o1, object? o2) { if (o1 == o2) return 0; - Accessor a1 = (Accessor)o1; - Accessor a2 = (Accessor)o2; - int w1 = a1.Mapping.TypeDesc.Weight; - int w2 = a2.Mapping.TypeDesc.Weight; + Accessor a1 = (Accessor)o1!; + Accessor a2 = (Accessor)o2!; + int w1 = a1.Mapping!.TypeDesc!.Weight; + int w2 = a2.Mapping!.TypeDesc!.Weight; if (w1 == w2) return 0; if (w1 < w2) @@ -774,7 +784,7 @@ public int Compare(object o1, object o2) } } - internal ElementAccessor[] ElementsSortedByDerivation + internal ElementAccessor[]? ElementsSortedByDerivation { get { @@ -789,19 +799,19 @@ internal ElementAccessor[] ElementsSortedByDerivation } } - internal TextAccessor Text + internal TextAccessor? Text { get { return _text; } set { _text = value; } } - internal ChoiceIdentifierAccessor ChoiceIdentifier + internal ChoiceIdentifierAccessor? ChoiceIdentifier { get { return _choiceIdentifier; } set { _choiceIdentifier = value; } } - internal XmlnsAccessor Xmlns + internal XmlnsAccessor? Xmlns { get { return _xmlns; } set { _xmlns = value; } @@ -813,7 +823,7 @@ internal bool Ignore set { _ignore = value; } } - internal Accessor Accessor + internal Accessor? Accessor { get { @@ -824,7 +834,7 @@ internal Accessor Accessor } } - internal static bool ElementsMatch(ElementAccessor[] a, ElementAccessor[] b) + internal static bool ElementsMatch(ElementAccessor[]? a, ElementAccessor[]? b) { if (a == null) { @@ -873,10 +883,10 @@ internal bool Match(AccessorMapping mapping) internal class MemberMappingComparer : IComparer { - public int Compare(object o1, object o2) + public int Compare(object? o1, object? o2) { - MemberMapping m1 = (MemberMapping)o1; - MemberMapping m2 = (MemberMapping)o2; + MemberMapping m1 = (MemberMapping)o1!; + MemberMapping m2 = (MemberMapping)o2!; bool m1Text = m1.IsText; if (m1Text) @@ -904,15 +914,15 @@ public int Compare(object o1, object o2) internal class MemberMapping : AccessorMapping { - private string _name; + private string? _name; private bool _checkShouldPersist; private SpecifiedAccessor _checkSpecified; private bool _isReturnValue; private bool _readOnly; private int _sequenceId = -1; - private MemberInfo _memberInfo; - private MemberInfo _checkSpecifiedMemberInfo; - private MethodInfo _checkShouldPersistMethodInfo; + private MemberInfo? _memberInfo; + private MemberInfo? _checkSpecifiedMemberInfo; + private MethodInfo? _checkShouldPersistMethodInfo; internal MemberMapping() { } @@ -948,19 +958,19 @@ internal string Name set { _name = value; } } - internal MemberInfo MemberInfo + internal MemberInfo? MemberInfo { get { return _memberInfo; } set { _memberInfo = value; } } - internal MemberInfo CheckSpecifiedMemberInfo + internal MemberInfo? CheckSpecifiedMemberInfo { get { return _checkSpecifiedMemberInfo; } set { _checkSpecifiedMemberInfo = value; } } - internal MethodInfo CheckShouldPersistMethodInfo + internal MethodInfo? CheckShouldPersistMethodInfo { get { return _checkShouldPersistMethodInfo; } set { _checkShouldPersistMethodInfo = value; } @@ -992,7 +1002,7 @@ internal int SequenceId private string GetNullableType(TypeDesc td) { // SOAP encoded arrays not mapped to Nullable since they always derive from soapenc:Array - if (td.IsMappedType || (!td.IsValueType && (Elements[0].IsSoap || td.ArrayElementTypeDesc == null))) + if (td.IsMappedType || (!td.IsValueType && (Elements![0].IsSoap || td.ArrayElementTypeDesc == null))) return td.FullName; if (td.ArrayElementTypeDesc != null) { @@ -1009,19 +1019,19 @@ internal MemberMapping Clone() internal class MembersMapping : TypeMapping { - private MemberMapping[] _members; + private MemberMapping[]? _members; private bool _hasWrapperElement = true; private bool _validateRpcWrapperElement; private bool _writeAccessors = true; - private MemberMapping _xmlnsMember; + private MemberMapping? _xmlnsMember; - internal MemberMapping[] Members + internal MemberMapping[]? Members { get { return _members; } set { _members = value; } } - internal MemberMapping XmlnsMember + internal MemberMapping? XmlnsMember { get { return _xmlnsMember; } set { _xmlnsMember = value; } @@ -1059,25 +1069,25 @@ internal bool NamedAny internal class SerializableMapping : SpecialMapping { - private XmlSchema _schema; - private Type _type; + private XmlSchema? _schema; + private Type? _type; private bool _needSchema = true; // new implementation of the IXmlSerializable - private readonly MethodInfo _getSchemaMethod; - private XmlQualifiedName _xsiType; - private XmlSchemaType _xsdType; - private XmlSchemaSet _schemas; + private readonly MethodInfo? _getSchemaMethod; + private XmlQualifiedName? _xsiType; + private XmlSchemaType? _xsdType; + private XmlSchemaSet? _schemas; private bool _any; - private string _namespaces; + private string? _namespaces; - private SerializableMapping _baseMapping; - private SerializableMapping _derivedMappings; - private SerializableMapping _nextDerivedMapping; - private SerializableMapping _next; // all mappings with the same qname + private SerializableMapping? _baseMapping; + private SerializableMapping? _derivedMappings; + private SerializableMapping? _nextDerivedMapping; + private SerializableMapping? _next; // all mappings with the same qname internal SerializableMapping() { } - internal SerializableMapping(MethodInfo getSchemaMethod, bool any, string ns) + internal SerializableMapping(MethodInfo getSchemaMethod, bool any, string? ns) { _getSchemaMethod = getSchemaMethod; _any = any; @@ -1094,7 +1104,7 @@ internal SerializableMapping(XmlQualifiedName xsiType, XmlSchemaSet schemas) _needSchema = false; } - internal void SetBaseMapping(SerializableMapping mapping) + internal void SetBaseMapping(SerializableMapping? mapping) { _baseMapping = mapping; if (_baseMapping != null) @@ -1103,7 +1113,7 @@ internal void SetBaseMapping(SerializableMapping mapping) _baseMapping._derivedMappings = this; if (this == _nextDerivedMapping) { - throw new InvalidOperationException(SR.Format(SR.XmlCircularDerivation, TypeDesc.FullName)); + throw new InvalidOperationException(SR.Format(SR.XmlCircularDerivation, TypeDesc!.FullName)); } } } @@ -1153,7 +1163,7 @@ internal string NamespaceList } } - internal SerializableMapping DerivedMappings + internal SerializableMapping? DerivedMappings { get { @@ -1161,7 +1171,7 @@ internal SerializableMapping DerivedMappings } } - internal SerializableMapping NextDerivedMapping + internal SerializableMapping? NextDerivedMapping { get { @@ -1169,19 +1179,19 @@ internal SerializableMapping NextDerivedMapping } } - internal SerializableMapping Next + internal SerializableMapping? Next { get { return _next; } set { _next = value; } } - internal Type Type + internal Type? Type { get { return _type; } set { _type = value; } } - internal XmlSchemaSet Schemas + internal XmlSchemaSet? Schemas { get { @@ -1190,7 +1200,7 @@ internal XmlSchemaSet Schemas } } - internal XmlSchema Schema + internal XmlSchema? Schema { get { @@ -1199,7 +1209,7 @@ internal XmlSchema Schema } } - internal XmlQualifiedName XsiType + internal XmlQualifiedName? XsiType { get { @@ -1214,7 +1224,7 @@ internal XmlQualifiedName XsiType } } - internal XmlSchemaType XsdType + internal XmlSchemaType? XsdType { get { @@ -1223,14 +1233,14 @@ internal XmlSchemaType XsdType } } - internal static void ValidationCallbackWithErrorCode(object sender, ValidationEventArgs args) + internal static void ValidationCallbackWithErrorCode(object? sender, ValidationEventArgs args) { // CONSIDER: need the real type name if (args.Severity == XmlSeverityType.Error) throw new InvalidOperationException(SR.Format(SR.XmlSerializableSchemaError, typeof(IXmlSerializable).Name, args.Message)); } - internal void CheckDuplicateElement(XmlSchemaElement element, string elementNs) + internal void CheckDuplicateElement(XmlSchemaElement? element, string? elementNs) { if (element == null) return; @@ -1239,7 +1249,7 @@ internal void CheckDuplicateElement(XmlSchemaElement element, string elementNs) if (element.Parent == null || !(element.Parent is XmlSchema)) return; - XmlSchemaObjectTable elements = null; + XmlSchemaObjectTable? elements = null; if (Schema != null && Schema.TargetNamespace == elementNs) { XmlSchemas.Preprocess(Schema); @@ -1260,7 +1270,7 @@ internal void CheckDuplicateElement(XmlSchemaElement element, string elementNs) if (Match(e, element)) return; // XmlSerializableRootDupName=Cannot reconcile schema for '{0}'. Please use [XmlRoot] attribute to change name or namepace of the top-level element to avoid duplicate element declarations: element name='{1} namespace='{2}'. - throw new InvalidOperationException(SR.Format(SR.XmlSerializableRootDupName, _getSchemaMethod.DeclaringType.FullName, e.Name, elementNs)); + throw new InvalidOperationException(SR.Format(SR.XmlSerializableRootDupName, _getSchemaMethod!.DeclaringType!.FullName, e.Name, elementNs)); } } } @@ -1298,7 +1308,7 @@ private void RetrieveSerializableSchema() // get the type info if (_schemas == null) _schemas = new XmlSchemaSet(); - object typeInfo = _getSchemaMethod.Invoke(null, new object[] { _schemas }); + object? typeInfo = _getSchemaMethod.Invoke(null, new object[] { _schemas }); _xsiType = XmlQualifiedName.Empty; if (typeInfo != null) @@ -1314,12 +1324,12 @@ private void RetrieveSerializableSchema() _xsiType = (XmlQualifiedName)typeInfo; if (_xsiType.IsEmpty) { - throw new InvalidOperationException(SR.Format(SR.XmlGetSchemaEmptyTypeName, _type.FullName, _getSchemaMethod.Name)); + throw new InvalidOperationException(SR.Format(SR.XmlGetSchemaEmptyTypeName, _type!.FullName, _getSchemaMethod.Name)); } } else { - throw new InvalidOperationException(SR.Format(SR.XmlGetSchemaMethodReturnType, _type.Name, _getSchemaMethod.Name, typeof(XmlSchemaProviderAttribute).Name, typeof(XmlQualifiedName).FullName)); + throw new InvalidOperationException(SR.Format(SR.XmlGetSchemaMethodReturnType, _type!.Name, _getSchemaMethod.Name, typeof(XmlSchemaProviderAttribute).Name, typeof(XmlQualifiedName).FullName)); } } else @@ -1347,17 +1357,17 @@ private void RetrieveSerializableSchema() } if (srcSchemas.Count > 1) { - throw new InvalidOperationException(SR.Format(SR.XmlGetSchemaInclude, _xsiType.Namespace, _getSchemaMethod.DeclaringType.FullName, _getSchemaMethod.Name)); + throw new InvalidOperationException(SR.Format(SR.XmlGetSchemaInclude, _xsiType.Namespace, _getSchemaMethod.DeclaringType!.FullName, _getSchemaMethod.Name)); } - XmlSchema s = (XmlSchema)srcSchemas[0]; + XmlSchema? s = (XmlSchema?)srcSchemas[0]; if (s == null) { throw new InvalidOperationException(SR.Format(SR.XmlMissingSchema, _xsiType.Namespace)); } - _xsdType = (XmlSchemaType)s.SchemaTypes[_xsiType]; + _xsdType = (XmlSchemaType?)s.SchemaTypes[_xsiType]; if (_xsdType == null) { - throw new InvalidOperationException(SR.Format(SR.XmlGetSchemaTypeMissing, _getSchemaMethod.DeclaringType.FullName, _getSchemaMethod.Name, _xsiType.Name, _xsiType.Namespace)); + throw new InvalidOperationException(SR.Format(SR.XmlGetSchemaTypeMissing, _getSchemaMethod.DeclaringType!.FullName, _getSchemaMethod.Name, _xsiType.Name, _xsiType.Namespace)); } _xsdType = _xsdType.Redefined != null ? _xsdType.Redefined : _xsdType; } @@ -1365,12 +1375,12 @@ private void RetrieveSerializableSchema() } else { - IXmlSerializable serializable = (IXmlSerializable)Activator.CreateInstance(_type); + IXmlSerializable serializable = (IXmlSerializable)Activator.CreateInstance(_type!)!; _schema = serializable.GetSchema(); if (_schema != null) { - if (_schema.Id == null || _schema.Id.Length == 0) throw new InvalidOperationException(SR.Format(SR.XmlSerializableNameMissing1, _type.FullName)); + if (_schema.Id == null || _schema.Id.Length == 0) throw new InvalidOperationException(SR.Format(SR.XmlSerializableNameMissing1, _type!.FullName)); } } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Models.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Models.cs index 6bfa59fd802686..9d0010e2baaa73 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Models.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Models.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; @@ -37,7 +38,7 @@ internal TypeModel GetTypeModel(Type type) internal TypeModel GetTypeModel(Type type, bool directReference) { - TypeModel model; + TypeModel? model; if (_models.TryGetValue(type, out model)) return model; TypeDesc typeDesc = _typeScope.GetTypeDesc(type, null, directReference); @@ -72,7 +73,7 @@ internal TypeModel GetTypeModel(Type type, bool directReference) internal ArrayModel GetArrayModel(Type type) { - TypeModel model; + TypeModel? model; if (!_arrayModels.TryGetValue(type, out model)) { model = GetTypeModel(type); @@ -122,7 +123,7 @@ internal ArrayModel(Type type, TypeDesc typeDesc, ModelScope scope) : base(type, internal TypeModel Element { - get { return ModelScope.GetTypeModel(TypeScope.GetArrayElementType(Type, null)); } + get { return ModelScope.GetTypeModel(TypeScope.GetArrayElementType(Type, null)!); } } } @@ -168,9 +169,9 @@ internal MemberInfo[] GetMemberInfos() return fieldsAndProps; } - internal FieldModel GetFieldModel(MemberInfo memberInfo) + internal FieldModel? GetFieldModel(MemberInfo memberInfo) { - FieldModel model = null; + FieldModel? model = null; if (memberInfo is FieldInfo) model = GetFieldModel((FieldInfo)memberInfo); else if (memberInfo is PropertyInfo) @@ -183,7 +184,7 @@ internal FieldModel GetFieldModel(MemberInfo memberInfo) return model; } - private void CheckSupportedMember(TypeDesc typeDesc, MemberInfo member, Type type) + private void CheckSupportedMember(TypeDesc? typeDesc, MemberInfo member, Type type) { if (typeDesc == null) return; @@ -193,13 +194,13 @@ private void CheckSupportedMember(TypeDesc typeDesc, MemberInfo member, Type typ { typeDesc.Exception = new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, typeDesc.FullName)); } - throw new InvalidOperationException(SR.Format(SR.XmlSerializerUnsupportedMember, member.DeclaringType.FullName + "." + member.Name, type.FullName), typeDesc.Exception); + throw new InvalidOperationException(SR.Format(SR.XmlSerializerUnsupportedMember, member.DeclaringType!.FullName + "." + member.Name, type.FullName), typeDesc.Exception); } CheckSupportedMember(typeDesc.BaseTypeDesc, member, type); CheckSupportedMember(typeDesc.ArrayElementTypeDesc, member, type); } - private FieldModel GetFieldModel(FieldInfo fieldInfo) + private FieldModel? GetFieldModel(FieldInfo fieldInfo) { if (fieldInfo.IsStatic) return null; if (fieldInfo.DeclaringType != Type) return null; @@ -212,7 +213,7 @@ private FieldModel GetFieldModel(FieldInfo fieldInfo) return new FieldModel(fieldInfo, fieldInfo.FieldType, typeDesc); } - private FieldModel GetPropertyModel(PropertyInfo propertyInfo) + private FieldModel? GetPropertyModel(PropertyInfo propertyInfo) { if (propertyInfo.DeclaringType != Type) return null; if (CheckPropertyRead(propertyInfo)) @@ -232,7 +233,7 @@ internal static bool CheckPropertyRead(PropertyInfo propertyInfo) { if (!propertyInfo.CanRead) return false; - MethodInfo getMethod = propertyInfo.GetMethod; + MethodInfo getMethod = propertyInfo.GetMethod!; if (getMethod.IsStatic) return false; ParameterInfo[] parameters = getMethod.GetParameters(); if (parameters.Length > 0) return false; @@ -250,9 +251,9 @@ internal enum SpecifiedAccessor internal class FieldModel { private readonly SpecifiedAccessor _checkSpecified = SpecifiedAccessor.None; - private readonly MemberInfo _memberInfo; - private readonly MemberInfo _checkSpecifiedMemberInfo; - private readonly MethodInfo _checkShouldPersistMethodInfo; + private readonly MemberInfo? _memberInfo; + private readonly MemberInfo? _checkSpecifiedMemberInfo; + private readonly MethodInfo? _checkShouldPersistMethodInfo; private readonly bool _checkShouldPersist; private readonly bool _readOnly; private readonly bool _isProperty; @@ -280,10 +281,10 @@ internal FieldModel(MemberInfo memberInfo, Type fieldType, TypeDesc fieldTypeDes _fieldType = fieldType; _fieldTypeDesc = fieldTypeDesc; _memberInfo = memberInfo; - _checkShouldPersistMethodInfo = memberInfo.DeclaringType.GetMethod("ShouldSerialize" + memberInfo.Name, Array.Empty()); + _checkShouldPersistMethodInfo = memberInfo.DeclaringType!.GetMethod("ShouldSerialize" + memberInfo.Name, Array.Empty()); _checkShouldPersist = _checkShouldPersistMethodInfo != null; - FieldInfo specifiedField = memberInfo.DeclaringType.GetField(memberInfo.Name + "Specified"); + FieldInfo? specifiedField = memberInfo.DeclaringType.GetField(memberInfo.Name + "Specified"); if (specifiedField != null) { if (specifiedField.FieldType != typeof(bool)) @@ -295,7 +296,7 @@ internal FieldModel(MemberInfo memberInfo, Type fieldType, TypeDesc fieldTypeDes } else { - PropertyInfo specifiedProperty = memberInfo.DeclaringType.GetProperty(memberInfo.Name + "Specified"); + PropertyInfo? specifiedProperty = memberInfo.DeclaringType.GetProperty(memberInfo.Name + "Specified"); if (specifiedProperty != null) { if (StructModel.CheckPropertyRead(specifiedProperty)) @@ -345,15 +346,15 @@ internal SpecifiedAccessor CheckSpecified get { return _checkSpecified; } } - internal MemberInfo MemberInfo + internal MemberInfo? MemberInfo { get { return _memberInfo; } } - internal MemberInfo CheckSpecifiedMemberInfo + internal MemberInfo? CheckSpecifiedMemberInfo { get { return _checkSpecifiedMemberInfo; } } - internal MethodInfo CheckShouldPersistMethodInfo + internal MethodInfo? CheckShouldPersistMethodInfo { get { return _checkShouldPersistMethodInfo; } } @@ -398,7 +399,7 @@ internal FieldInfo FieldInfo internal class EnumModel : TypeModel { - private ConstantModel[] _constants; + private ConstantModel[]? _constants; internal EnumModel(Type type, TypeDesc typeDesc, ModelScope scope) : base(type, typeDesc, scope) { } @@ -413,7 +414,7 @@ internal ConstantModel[] Constants for (int i = 0; i < fields.Length; i++) { FieldInfo field = fields[i]; - ConstantModel constant = GetConstantModel(field); + ConstantModel? constant = GetConstantModel(field); if (constant != null) list.Add(constant); } _constants = list.ToArray(); @@ -422,10 +423,10 @@ internal ConstantModel[] Constants } } - private ConstantModel GetConstantModel(FieldInfo fieldInfo) + private ConstantModel? GetConstantModel(FieldInfo fieldInfo) { if (fieldInfo.IsSpecialName) return null; - return new ConstantModel(fieldInfo, ((IConvertible)fieldInfo.GetValue(null)).ToInt64(null)); + return new ConstantModel(fieldInfo, ((IConvertible)fieldInfo.GetValue(null)!).ToInt64(null)); } } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/NameTable.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/NameTable.cs index d00b04b1e005cb..f7f43ad4683a5a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/NameTable.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/NameTable.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System.Xml; @@ -10,16 +11,16 @@ namespace System.Xml.Serialization internal class NameKey { - private readonly string _ns; - private readonly string _name; + private readonly string? _ns; + private readonly string? _name; - internal NameKey(string name, string ns) + internal NameKey(string? name, string? ns) { _name = name; _ns = ns; } - public override bool Equals(object other) + public override bool Equals(object? other) { if (!(other is NameKey)) return false; NameKey key = (NameKey)other; @@ -33,28 +34,28 @@ public override int GetHashCode() } internal interface INameScope { - object this[string name, string ns] { get; set; } + object? this[string? name, string? ns] { get; set; } } internal class NameTable : INameScope { - private readonly Dictionary _table = new Dictionary(); + private readonly Dictionary _table = new Dictionary(); internal void Add(XmlQualifiedName qname, object value) { Add(qname.Name, qname.Namespace, value); } - internal void Add(string name, string ns, object value) + internal void Add(string? name, string? ns, object value) { NameKey key = new NameKey(name, ns); _table.Add(key, value); } - internal object this[XmlQualifiedName qname] + internal object? this[XmlQualifiedName qname] { get { - object obj; + object? obj; return _table.TryGetValue(new NameKey(qname.Name, qname.Namespace), out obj) ? obj : null; } set @@ -62,11 +63,11 @@ internal object this[XmlQualifiedName qname] _table[new NameKey(qname.Name, qname.Namespace)] = value; } } - internal object this[string name, string ns] + internal object? this[string? name, string? ns] { get { - object obj; + object? obj; return _table.TryGetValue(new NameKey(name, ns), out obj) ? obj : null; } set @@ -74,11 +75,11 @@ internal object this[XmlQualifiedName qname] _table[new NameKey(name, ns)] = value; } } - object INameScope.this[string name, string ns] + object? INameScope.this[string? name, string? ns] { get { - object obj; + object? obj; _table.TryGetValue(new NameKey(name, ns), out obj); return obj; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/PrimitiveXmlSerializers.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/PrimitiveXmlSerializers.cs index 4198fe1c4077fe..4eb47af828865d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/PrimitiveXmlSerializers.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/PrimitiveXmlSerializers.cs @@ -1,13 +1,14 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; namespace System.Xml.Serialization { internal class XmlSerializationPrimitiveWriter : System.Xml.Serialization.XmlSerializationWriter { - internal void Write_string(object o) + internal void Write_string(object? o) { WriteStartDocument(); if (o == null) @@ -19,7 +20,7 @@ internal void Write_string(object o) WriteNullableStringLiteral(@"string", @"", ((string)o)); } - internal void Write_int(object o) + internal void Write_int(object? o) { WriteStartDocument(); if (o == null) @@ -30,7 +31,7 @@ internal void Write_int(object o) WriteElementStringRaw(@"int", @"", System.Xml.XmlConvert.ToString((int)((int)o))); } - internal void Write_boolean(object o) + internal void Write_boolean(object? o) { WriteStartDocument(); if (o == null) @@ -41,7 +42,7 @@ internal void Write_boolean(object o) WriteElementStringRaw(@"boolean", @"", System.Xml.XmlConvert.ToString((bool)((bool)o))); } - internal void Write_short(object o) + internal void Write_short(object? o) { WriteStartDocument(); if (o == null) @@ -52,7 +53,7 @@ internal void Write_short(object o) WriteElementStringRaw(@"short", @"", System.Xml.XmlConvert.ToString((short)((short)o))); } - internal void Write_long(object o) + internal void Write_long(object? o) { WriteStartDocument(); if (o == null) @@ -63,7 +64,7 @@ internal void Write_long(object o) WriteElementStringRaw(@"long", @"", System.Xml.XmlConvert.ToString((long)((long)o))); } - internal void Write_float(object o) + internal void Write_float(object? o) { WriteStartDocument(); if (o == null) @@ -74,7 +75,7 @@ internal void Write_float(object o) WriteElementStringRaw(@"float", @"", System.Xml.XmlConvert.ToString((float)((float)o))); } - internal void Write_double(object o) + internal void Write_double(object? o) { WriteStartDocument(); if (o == null) @@ -85,7 +86,7 @@ internal void Write_double(object o) WriteElementStringRaw(@"double", @"", System.Xml.XmlConvert.ToString((double)((double)o))); } - internal void Write_decimal(object o) + internal void Write_decimal(object? o) { WriteStartDocument(); if (o == null) @@ -98,7 +99,7 @@ internal void Write_decimal(object o) WriteElementStringRaw(@"decimal", @"", System.Xml.XmlConvert.ToString(d)); } - internal void Write_dateTime(object o) + internal void Write_dateTime(object? o) { WriteStartDocument(); if (o == null) @@ -109,7 +110,7 @@ internal void Write_dateTime(object o) WriteElementStringRaw(@"dateTime", @"", FromDateTime(((System.DateTime)o))); } - internal void Write_unsignedByte(object o) + internal void Write_unsignedByte(object? o) { WriteStartDocument(); if (o == null) @@ -120,7 +121,7 @@ internal void Write_unsignedByte(object o) WriteElementStringRaw(@"unsignedByte", @"", System.Xml.XmlConvert.ToString((byte)((byte)o))); } - internal void Write_byte(object o) + internal void Write_byte(object? o) { WriteStartDocument(); if (o == null) @@ -131,7 +132,7 @@ internal void Write_byte(object o) WriteElementStringRaw(@"byte", @"", System.Xml.XmlConvert.ToString((sbyte)((sbyte)o))); } - internal void Write_unsignedShort(object o) + internal void Write_unsignedShort(object? o) { WriteStartDocument(); if (o == null) @@ -142,7 +143,7 @@ internal void Write_unsignedShort(object o) WriteElementStringRaw(@"unsignedShort", @"", System.Xml.XmlConvert.ToString((ushort)((ushort)o))); } - internal void Write_unsignedInt(object o) + internal void Write_unsignedInt(object? o) { WriteStartDocument(); if (o == null) @@ -153,7 +154,7 @@ internal void Write_unsignedInt(object o) WriteElementStringRaw(@"unsignedInt", @"", System.Xml.XmlConvert.ToString((uint)((uint)o))); } - internal void Write_unsignedLong(object o) + internal void Write_unsignedLong(object? o) { WriteStartDocument(); if (o == null) @@ -164,7 +165,7 @@ internal void Write_unsignedLong(object o) WriteElementStringRaw(@"unsignedLong", @"", System.Xml.XmlConvert.ToString((ulong)((ulong)o))); } - internal void Write_base64Binary(object o) + internal void Write_base64Binary(object? o) { WriteStartDocument(); if (o == null) @@ -176,7 +177,7 @@ internal void Write_base64Binary(object o) WriteNullableStringLiteralRaw(@"base64Binary", @"", FromByteArrayBase64(((byte[])o))); } - internal void Write_guid(object o) + internal void Write_guid(object? o) { WriteStartDocument(); if (o == null) @@ -189,7 +190,7 @@ internal void Write_guid(object o) WriteElementStringRaw(@"guid", @"", System.Xml.XmlConvert.ToString(guid)); } - internal void Write_TimeSpan(object o) + internal void Write_TimeSpan(object? o) { WriteStartDocument(); if (o == null) @@ -201,7 +202,7 @@ internal void Write_TimeSpan(object o) WriteElementStringRaw(@"TimeSpan", @"", System.Xml.XmlConvert.ToString(timeSpan)); } - internal void Write_char(object o) + internal void Write_char(object? o) { WriteStartDocument(); if (o == null) @@ -212,7 +213,7 @@ internal void Write_char(object o) WriteElementString(@"char", @"", FromChar(((char)o))); } - internal void Write_QName(object o) + internal void Write_QName(object? o) { WriteStartDocument(); if (o == null) @@ -231,9 +232,9 @@ protected override void InitCallbacks() internal class XmlSerializationPrimitiveReader : System.Xml.Serialization.XmlSerializationReader { - internal object Read_string() + internal object? Read_string() { - object o = null; + object? o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { @@ -257,12 +258,12 @@ internal object Read_string() { UnknownNode(null); } - return (object)o; + return (object?)o; } - internal object Read_int() + internal object? Read_int() { - object o = null; + object? o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { @@ -281,12 +282,12 @@ internal object Read_int() { UnknownNode(null); } - return (object)o; + return (object?)o; } - internal object Read_boolean() + internal object? Read_boolean() { - object o = null; + object? o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { @@ -305,12 +306,12 @@ internal object Read_boolean() { UnknownNode(null); } - return (object)o; + return (object?)o; } - internal object Read_short() + internal object? Read_short() { - object o = null; + object? o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { @@ -329,12 +330,12 @@ internal object Read_short() { UnknownNode(null); } - return (object)o; + return (object?)o; } - internal object Read_long() + internal object? Read_long() { - object o = null; + object? o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { @@ -353,12 +354,12 @@ internal object Read_long() { UnknownNode(null); } - return (object)o; + return (object?)o; } - internal object Read_float() + internal object? Read_float() { - object o = null; + object? o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { @@ -377,12 +378,12 @@ internal object Read_float() { UnknownNode(null); } - return (object)o; + return (object?)o; } - internal object Read_double() + internal object? Read_double() { - object o = null; + object? o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { @@ -401,12 +402,12 @@ internal object Read_double() { UnknownNode(null); } - return (object)o; + return (object?)o; } - internal object Read_decimal() + internal object? Read_decimal() { - object o = null; + object? o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { @@ -425,12 +426,12 @@ internal object Read_decimal() { UnknownNode(null); } - return (object)o; + return (object?)o; } - internal object Read_dateTime() + internal object? Read_dateTime() { - object o = null; + object? o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { @@ -449,12 +450,12 @@ internal object Read_dateTime() { UnknownNode(null); } - return (object)o; + return (object?)o; } - internal object Read_unsignedByte() + internal object? Read_unsignedByte() { - object o = null; + object? o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { @@ -473,12 +474,12 @@ internal object Read_unsignedByte() { UnknownNode(null); } - return (object)o; + return (object?)o; } - internal object Read_byte() + internal object? Read_byte() { - object o = null; + object? o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { @@ -497,12 +498,12 @@ internal object Read_byte() { UnknownNode(null); } - return (object)o; + return (object?)o; } - internal object Read_unsignedShort() + internal object? Read_unsignedShort() { - object o = null; + object? o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { @@ -521,12 +522,12 @@ internal object Read_unsignedShort() { UnknownNode(null); } - return (object)o; + return (object?)o; } - internal object Read_unsignedInt() + internal object? Read_unsignedInt() { - object o = null; + object? o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { @@ -545,12 +546,12 @@ internal object Read_unsignedInt() { UnknownNode(null); } - return (object)o; + return (object?)o; } - internal object Read_unsignedLong() + internal object? Read_unsignedLong() { - object o = null; + object? o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { @@ -569,12 +570,12 @@ internal object Read_unsignedLong() { UnknownNode(null); } - return (object)o; + return (object?)o; } - internal object Read_base64Binary() + internal object? Read_base64Binary() { - object o = null; + object? o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { @@ -598,12 +599,12 @@ internal object Read_base64Binary() { UnknownNode(null); } - return (object)o; + return (object?)o; } - internal object Read_guid() + internal object? Read_guid() { - object o = null; + object? o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { @@ -622,12 +623,12 @@ internal object Read_guid() { UnknownNode(null); } - return (object)o; + return (object?)o; } - internal object Read_TimeSpan() + internal object? Read_TimeSpan() { - object o = null; + object? o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { @@ -652,12 +653,12 @@ internal object Read_TimeSpan() { UnknownNode(null); } - return (object)o; + return (object?)o; } - internal object Read_char() + internal object? Read_char() { - object o = null; + object? o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { @@ -676,12 +677,12 @@ internal object Read_char() { UnknownNode(null); } - return (object)o; + return (object?)o; } - internal object Read_QName() + internal object? Read_QName() { - object o = null; + object? o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { @@ -705,33 +706,33 @@ internal object Read_QName() { UnknownNode(null); } - return (object)o; + return (object?)o; } protected override void InitCallbacks() { } - private string _id4_boolean; - private string _id14_unsignedInt; - private string _id15_unsignedLong; - private string _id7_float; - private string _id10_dateTime; - private string _id6_long; - private string _id9_decimal; - private string _id8_double; - private string _id17_guid; - private string _id19_TimeSpan; - private string _id2_Item; - private string _id13_unsignedShort; - private string _id18_char; - private string _id3_int; - private string _id12_byte; - private string _id16_base64Binary; - private string _id11_unsignedByte; - private string _id5_short; - private string _id1_string; - private string _id1_QName; + private string _id4_boolean = null!; + private string _id14_unsignedInt = null!; + private string _id15_unsignedLong = null!; + private string _id7_float = null!; + private string _id10_dateTime = null!; + private string _id6_long = null!; + private string _id9_decimal = null!; + private string _id8_double = null!; + private string _id17_guid = null!; + private string _id19_TimeSpan = null!; + private string _id2_Item = null!; + private string _id13_unsignedShort = null!; + private string _id18_char = null!; + private string _id3_int = null!; + private string _id12_byte = null!; + private string _id16_base64Binary = null!; + private string _id11_unsignedByte = null!; + private string _id5_short = null!; + private string _id1_string = null!; + private string _id1_QName = null!; protected override void InitIDs() { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationReader.cs index 597c4fa9b2a503..e39e7bf796d6e6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationReader.cs @@ -1,10 +1,12 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Linq.Expressions; using System.Reflection; using System.Xml.Extensions; @@ -12,7 +14,7 @@ namespace System.Xml.Serialization { - internal delegate void UnknownNodeAction(object o); + internal delegate void UnknownNodeAction(object? o); internal class ReflectionXmlSerializationReader : XmlSerializationReader { @@ -21,7 +23,7 @@ internal class ReflectionXmlSerializationReader : XmlSerializationReader private readonly XmlMapping _mapping; - public ReflectionXmlSerializationReader(XmlMapping mapping, XmlReader xmlReader, XmlDeserializationEvents events, string encodingStyle) + public ReflectionXmlSerializationReader(XmlMapping mapping, XmlReader xmlReader, XmlDeserializationEvents events, string? encodingStyle) { Init(xmlReader, events, encodingStyle, tempAssembly: null); _mapping = mapping; @@ -29,17 +31,17 @@ public ReflectionXmlSerializationReader(XmlMapping mapping, XmlReader xmlReader, protected override void InitCallbacks() { - TypeScope scope = _mapping.Scope; + TypeScope scope = _mapping.Scope!; foreach (TypeMapping mapping in scope.TypeMappings) { if (mapping.IsSoap && (mapping is StructMapping || mapping is EnumMapping || mapping is ArrayMapping || mapping is NullableMapping) && - !mapping.TypeDesc.IsRoot) + !mapping.TypeDesc!.IsRoot) { AddReadCallback( - mapping.TypeName, - mapping.Namespace, - mapping.TypeDesc.Type, + mapping.TypeName!, + mapping.Namespace!, + mapping.TypeDesc.Type!, CreateXmlSerializationReadCallback(mapping)); } } @@ -49,7 +51,7 @@ protected override void InitIDs() { } - public object ReadObject() + public object? ReadObject() { XmlMapping xmlMapping = _mapping; if (!xmlMapping.IsReadable) @@ -87,7 +89,7 @@ private object GenerateMembersElement(XmlMembersMapping xmlMembersMapping) private object GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping) { ElementAccessor element = xmlMembersMapping.Accessor; - MemberMapping[] mappings = ((MembersMapping)element.Mapping).Members; + MemberMapping[] mappings = ((MembersMapping)element.Mapping!).Members!; bool hasWrapperElement = ((MembersMapping)element.Mapping).HasWrapperElement; Reader.MoveToContent(); @@ -97,7 +99,7 @@ private object GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping if (hasWrapperElement) { string elementName = element.Name; - string elementNs = element.Form == XmlSchemaForm.Qualified ? element.Namespace : string.Empty; + string elementNs = element.Form == XmlSchemaForm.Qualified ? element.Namespace! : string.Empty; Reader.MoveToContent(); while (Reader.NodeType != XmlNodeType.EndElement && Reader.NodeType != XmlNodeType.None) { @@ -127,11 +129,11 @@ private object GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping return p; } - private bool GenerateLiteralMembersElementInternal(MemberMapping[] mappings, bool hasWrapperElement, object[] p) + private bool GenerateLiteralMembersElementInternal(MemberMapping[] mappings, bool hasWrapperElement, object?[] p) { - Member anyText = null; - Member anyElement = null; - Member anyAttribute = null; + Member? anyText = null; + Member? anyElement = null; + Member? anyAttribute = null; var membersList = new List(); var textOrArrayMembersList = new List(); @@ -141,7 +143,7 @@ private bool GenerateLiteralMembersElementInternal(MemberMapping[] mappings, boo { int index = i; MemberMapping mapping = mappings[index]; - Action source = (o) => p[index] = o; + Action source = (o) => p[index] = o; Member member = new Member(mapping); Member anyMember = new Member(mapping); @@ -198,7 +200,7 @@ private bool GenerateLiteralMembersElementInternal(MemberMapping[] mappings, boo if (!mapping.IsSequence) { - for (int j = 0; j < mapping.Elements.Length; j++) + for (int j = 0; j < mapping.Elements!.Length; j++) { if (mapping.Elements[j].Any && mapping.Elements[j].Name.Length == 0) { @@ -224,8 +226,8 @@ private bool GenerateLiteralMembersElementInternal(MemberMapping[] mappings, boo { membersList.Add(anyMember); } - else if (mapping.TypeDesc.IsArrayLike - && !(mapping.Elements.Length == 1 && mapping.Elements[0].Mapping is ArrayMapping)) + else if (mapping.TypeDesc!.IsArrayLike + && !(mapping.Elements!.Length == 1 && mapping.Elements[0].Mapping is ArrayMapping)) { anyMember.Collection = new CollectionMember(); anyMember.ArraySource = (item) => @@ -251,7 +253,7 @@ private bool GenerateLiteralMembersElementInternal(MemberMapping[] mappings, boo if (attributeMembersList.Count > 0) { Member[] attributeMembers = attributeMembersList.ToArray(); - object tempObject = null; + object? tempObject = null; WriteAttributes(attributeMembers, anyAttribute, UnknownNode, ref tempObject); Reader.MoveToElement(); } @@ -277,36 +279,36 @@ private bool GenerateLiteralMembersElementInternal(MemberMapping[] mappings, boo foreach (Member member in textOrArrayMembers) { - object value = null; - SetCollectionObjectWithCollectionMember(ref value, member.Collection, member.Mapping.TypeDesc.Type); - member.Source(value); + object? value = null; + SetCollectionObjectWithCollectionMember(ref value, member.Collection!, member.Mapping.TypeDesc!.Type!); + member.Source!(value); } if (anyAttribute != null) { - object value = null; - SetCollectionObjectWithCollectionMember(ref value, anyAttribute.Collection, anyAttribute.Mapping.TypeDesc.Type); - anyAttribute.ArraySource(value); + object? value = null; + SetCollectionObjectWithCollectionMember(ref value, anyAttribute.Collection!, anyAttribute.Mapping.TypeDesc!.Type!); + anyAttribute.ArraySource!(value); } return true; } - private void InitializeValueTypes(object[] p, MemberMapping[] mappings) + private void InitializeValueTypes(object?[] p, MemberMapping[] mappings) { for (int i = 0; i < mappings.Length; i++) { - if (!mappings[i].TypeDesc.IsValueType) + if (!mappings[i].TypeDesc!.IsValueType) continue; - if (mappings[i].TypeDesc.IsOptionalValue && mappings[i].TypeDesc.BaseTypeDesc.UseReflection) + if (mappings[i].TypeDesc!.IsOptionalValue && mappings[i].TypeDesc!.BaseTypeDesc!.UseReflection) { p[i] = null; } else { - p[i] = ReflectionCreateObject(mappings[i].TypeDesc.Type); + p[i] = ReflectionCreateObject(mappings[i].TypeDesc!.Type!); } } } @@ -314,14 +316,14 @@ private void InitializeValueTypes(object[] p, MemberMapping[] mappings) private object GenerateEncodedMembersElement(XmlMembersMapping xmlMembersMapping) { ElementAccessor element = xmlMembersMapping.Accessor; - var membersMapping = (MembersMapping)element.Mapping; - MemberMapping[] mappings = membersMapping.Members; + var membersMapping = (MembersMapping)element.Mapping!; + MemberMapping[] mappings = membersMapping.Members!; bool hasWrapperElement = membersMapping.HasWrapperElement; bool writeAccessors = membersMapping.WriteAccessors; Reader.MoveToContent(); - object[] p = new object[mappings.Length]; + object?[] p = new object[mappings.Length]; InitializeValueTypes(p, mappings); bool isEmptyWrapper = true; @@ -330,7 +332,7 @@ private object GenerateEncodedMembersElement(XmlMembersMapping xmlMembersMapping Reader.MoveToContent(); while (Reader.NodeType == XmlNodeType.Element) { - string root = Reader.GetAttribute("root", Soap.Encoding); + string? root = Reader.GetAttribute("root", Soap.Encoding); if (root == null || XmlConvert.ToBoolean(root)) break; @@ -341,7 +343,7 @@ private object GenerateEncodedMembersElement(XmlMembersMapping xmlMembersMapping if (membersMapping.ValidateRpcWrapperElement) { string name = element.Name; - string ns = element.Form == XmlSchemaForm.Qualified ? element.Namespace : string.Empty; + string? ns = element.Form == XmlSchemaForm.Qualified ? element.Namespace : string.Empty; if (!XmlNodeEqual(Reader, name, ns)) { throw CreateUnknownNodeException(); @@ -376,13 +378,13 @@ private object GenerateEncodedMembersElement(XmlMembersMapping xmlMembersMapping } - Fixup fixup = WriteMemberFixupBegin(members, p); + Fixup? fixup = WriteMemberFixupBegin(members, p); if (members.Length > 0 && members[0].Mapping.IsReturnValue) { IsReturnValue = true; } - List checkTypeHrefSource = null; + List? checkTypeHrefSource = null; if (!hasWrapperElement && !writeAccessors) { checkTypeHrefSource = new List(); @@ -426,7 +428,7 @@ private object GenerateEncodedMembersElement(XmlMembersMapping xmlMembersMapping { bool isReferenced = true; bool isObject = currentySource.IsObject; - object refObj = isObject ? currentySource.RefObject : GetTarget((string)currentySource.RefObject); + object? refObj = isObject ? currentySource.RefObject : GetTarget((string)currentySource.RefObject!); if (refObj == null) { continue; @@ -451,17 +453,17 @@ private object GenerateEncodedMembersElement(XmlMembersMapping xmlMembersMapping return p; } - private object GenerateTypeElement(XmlTypeMapping xmlTypeMapping) + private object? GenerateTypeElement(XmlTypeMapping xmlTypeMapping) { ElementAccessor element = xmlTypeMapping.Accessor; - TypeMapping mapping = element.Mapping; + TypeMapping mapping = element.Mapping!; Reader.MoveToContent(); var memberMapping = new MemberMapping(); memberMapping.TypeDesc = mapping.TypeDesc; memberMapping.Elements = new ElementAccessor[] { element }; - object o = null; + object? o = null; var holder = new ObjectHolder(); var member = new Member(memberMapping); member.Source = (value) => holder.Object = value; @@ -480,7 +482,7 @@ private object GenerateTypeElement(XmlTypeMapping xmlTypeMapping) return o; } - private void WriteMemberElements(Member[] expectedMembers, UnknownNodeAction elementElseAction, UnknownNodeAction elseAction, Member anyElement, Member anyText, Fixup fixup = null, List checkTypeHrefsSource = null) + private void WriteMemberElements(Member[] expectedMembers, UnknownNodeAction elementElseAction, UnknownNodeAction elseAction, Member? anyElement, Member? anyText, Fixup? fixup = null, List? checkTypeHrefsSource = null) { bool checkType = checkTypeHrefsSource != null; if (Reader.NodeType == XmlNodeType.Element) @@ -493,7 +495,7 @@ private void WriteMemberElements(Member[] expectedMembers, UnknownNodeAction ele return; } - WriteMemberElementsCheckType(checkTypeHrefsSource); + WriteMemberElementsCheckType(checkTypeHrefsSource!); } else { @@ -511,7 +513,7 @@ private void WriteMemberElements(Member[] expectedMembers, UnknownNodeAction ele private void WriteMemberElementsCheckType(List checkTypeHrefsSource) { - object RefElememnt = ReadReferencingElement(null, null, true, out string refElemId); + object? RefElememnt = ReadReferencingElement(null, null, true, out string? refElemId); var source = new CheckTypeSource(); if (refElemId != null) { @@ -532,7 +534,7 @@ private void ProcessUnknownNode(UnknownNodeAction action) action?.Invoke(null); } - private void WriteMembers(ref object o, Member[] members, UnknownNodeAction elementElseAction, UnknownNodeAction elseAction, Member anyElement, Member anyText) + private void WriteMembers(ref object? o, Member[] members, UnknownNodeAction elementElseAction, UnknownNodeAction elseAction, Member? anyElement, Member? anyText) { Reader.MoveToContent(); @@ -543,7 +545,7 @@ private void WriteMembers(ref object o, Member[] members, UnknownNodeAction elem } } - private void SetCollectionObjectWithCollectionMember(ref object collection, CollectionMember collectionMember, Type collectionType) + private void SetCollectionObjectWithCollectionMember([NotNull] ref object? collection, CollectionMember collectionMember, Type collectionType) { if (collectionType.IsArray) { @@ -554,7 +556,7 @@ private void SetCollectionObjectWithCollectionMember(ref object collection, Coll } else { - Type elementType = collectionType.GetElementType(); + Type elementType = collectionType.GetElementType()!; a = Array.CreateInstance(elementType, collectionMember.Count); } @@ -569,32 +571,32 @@ private void SetCollectionObjectWithCollectionMember(ref object collection, Coll { if (collection == null) { - collection = ReflectionCreateObject(collectionType); + collection = ReflectionCreateObject(collectionType)!; } AddObjectsIntoTargetCollection(collection, collectionMember, collectionType); } } - private static void AddObjectsIntoTargetCollection(object targetCollection, List sourceCollection, Type targetCollectionType) + private static void AddObjectsIntoTargetCollection(object targetCollection, List sourceCollection, Type targetCollectionType) { if (targetCollection is IList targetList) { - foreach (object item in sourceCollection) + foreach (object? item in sourceCollection) { targetList.Add(item); } } else { - MethodInfo addMethod = targetCollectionType.GetMethod("Add"); + MethodInfo? addMethod = targetCollectionType.GetMethod("Add"); if (addMethod == null) { throw new InvalidOperationException(SR.XmlInternalError); } - object[] arguments = new object[1]; - foreach (object item in sourceCollection) + object?[] arguments = new object?[1]; + foreach (object? item in sourceCollection) { arguments[0] = item; addMethod.Invoke(targetCollection, arguments); @@ -609,7 +611,7 @@ private static ReflectionXmlSerializationReaderHelper.SetMemberValueDelegate Get Debug.Assert(o != null, "Object o should not be null"); Debug.Assert(!string.IsNullOrEmpty(memberName), "memberName must have a value"); var typeMemberNameTuple = Tuple.Create(o.GetType(), memberName); - if (!s_setMemberValueDelegateCache.TryGetValue(typeMemberNameTuple, out ReflectionXmlSerializationReaderHelper.SetMemberValueDelegate result)) + if (!s_setMemberValueDelegateCache.TryGetValue(typeMemberNameTuple, out ReflectionXmlSerializationReaderHelper.SetMemberValueDelegate? result)) { MemberInfo memberInfo = ReflectionXmlSerializationHelper.GetMember(o.GetType(), memberName); Debug.Assert(memberInfo != null, "memberInfo could not be retrieved"); @@ -627,7 +629,7 @@ private static ReflectionXmlSerializationReaderHelper.SetMemberValueDelegate Get throw new InvalidOperationException(SR.XmlInternalError); } - MethodInfo getSetMemberValueDelegateWithTypeGenericMi = typeof(ReflectionXmlSerializationReaderHelper).GetMethod("GetSetMemberValueDelegateWithType", BindingFlags.Static | BindingFlags.Public); + MethodInfo getSetMemberValueDelegateWithTypeGenericMi = typeof(ReflectionXmlSerializationReaderHelper).GetMethod("GetSetMemberValueDelegateWithType", BindingFlags.Static | BindingFlags.Public)!; MethodInfo getSetMemberValueDelegateWithTypeMi = getSetMemberValueDelegateWithTypeGenericMi.MakeGenericMethod(o.GetType(), memberType); var getSetMemberValueDelegateWithType = (Func)getSetMemberValueDelegateWithTypeMi.CreateDelegate(typeof(Func)); result = getSetMemberValueDelegateWithType(memberInfo); @@ -637,7 +639,7 @@ private static ReflectionXmlSerializationReaderHelper.SetMemberValueDelegate Get return result; } - private object GetMemberValue(object o, MemberInfo memberInfo) + private object? GetMemberValue(object o, MemberInfo memberInfo) { if (memberInfo is PropertyInfo propertyInfo) { @@ -653,17 +655,17 @@ private object GetMemberValue(object o, MemberInfo memberInfo) private bool WriteMemberText(Member anyText) { - object value; + object? value; MemberMapping anyTextMapping = anyText.Mapping; if ((Reader.NodeType == XmlNodeType.Text || Reader.NodeType == XmlNodeType.CDATA || Reader.NodeType == XmlNodeType.Whitespace || Reader.NodeType == XmlNodeType.SignificantWhitespace)) { - TextAccessor text = anyTextMapping.Text; + TextAccessor text = anyTextMapping.Text!; if (text.Mapping is SpecialMapping special) { - if (special.TypeDesc.Kind == TypeKind.Node) + if (special.TypeDesc!.Kind == TypeKind.Node) { value = Document.CreateTextNode(Reader.ReadString()); } @@ -674,9 +676,9 @@ private bool WriteMemberText(Member anyText) } else { - if (anyTextMapping.TypeDesc.IsArrayLike) + if (anyTextMapping.TypeDesc!.IsArrayLike) { - if (text.Mapping.TypeDesc.CollapseWhitespace) + if (text.Mapping!.TypeDesc!.CollapseWhitespace) { value = CollapseWhitespace(Reader.ReadString()); } @@ -687,7 +689,7 @@ private bool WriteMemberText(Member anyText) } else { - if (text.Mapping.TypeDesc == StringTypeDesc || text.Mapping.TypeDesc.FormatterName == "String") + if (text.Mapping!.TypeDesc == StringTypeDesc || text.Mapping.TypeDesc!.FormatterName == "String") { value = ReadString(null, text.Mapping.TypeDesc.CollapseWhitespace); } @@ -698,7 +700,7 @@ private bool WriteMemberText(Member anyText) } } - anyText.Source(value); + anyText.Source!(value); return true; } @@ -713,7 +715,7 @@ private bool IsSequence(Member[] members) return false; } - private void WriteMemberElementsIf(Member[] expectedMembers, Member anyElementMember, UnknownNodeAction elementElseAction, Fixup fixup = null, CheckTypeSource checkTypeSource = null) + private void WriteMemberElementsIf(Member[] expectedMembers, Member? anyElementMember, UnknownNodeAction elementElseAction, Fixup? fixup = null, CheckTypeSource? checkTypeSource = null) { bool checkType = checkTypeSource != null; bool isSequence = IsSequence(expectedMembers); @@ -724,8 +726,8 @@ private void WriteMemberElementsIf(Member[] expectedMembers, Member anyElementMe // But potentially we can do some optimization for types that have ordered properties. } - ElementAccessor e = null; - Member member = null; + ElementAccessor? e = null; + Member? member = null; bool foundElement = false; int elementIndex = -1; foreach (Member m in expectedMembers) @@ -737,24 +739,24 @@ private void WriteMemberElementsIf(Member[] expectedMembers, Member anyElementMe if (isSequence && (m.Mapping.IsText || m.Mapping.IsAttribute)) continue; - for (int i = 0; i < m.Mapping.Elements.Length; i++) + for (int i = 0; i < m.Mapping.Elements!.Length; i++) { ElementAccessor ele = m.Mapping.Elements[i]; - string ns = ele.Form == XmlSchemaForm.Qualified ? ele.Namespace : string.Empty; + string? ns = ele.Form == XmlSchemaForm.Qualified ? ele.Namespace : string.Empty; if (checkType) { Type elementType; if (ele.Mapping is NullableMapping nullableMapping) { - TypeDesc td = nullableMapping.BaseMapping.TypeDesc; - elementType = td.Type; + TypeDesc td = nullableMapping.BaseMapping!.TypeDesc!; + elementType = td.Type!; } else { - elementType = ele.Mapping.TypeDesc.Type; + elementType = ele.Mapping!.TypeDesc!.Type!; } - if (elementType.IsAssignableFrom(checkTypeSource.Type)) + if (elementType.IsAssignableFrom(checkTypeSource!.Type)) { foundElement = true; } @@ -781,17 +783,17 @@ private void WriteMemberElementsIf(Member[] expectedMembers, Member anyElementMe { if (checkType) { - member.Source(checkTypeSource.RefObject); + member!.Source!(checkTypeSource!.RefObject!); if (member.FixupIndex >= 0) { - fixup.Ids[member.FixupIndex] = checkTypeSource.Id; + fixup!.Ids![member.FixupIndex] = checkTypeSource.Id; } } else { - string ns = e.Form == XmlSchemaForm.Qualified ? e.Namespace : string.Empty; - bool isList = member.Mapping.TypeDesc.IsArrayLike && !member.Mapping.TypeDesc.IsArray; + string? ns = e!.Form == XmlSchemaForm.Qualified ? e.Namespace : string.Empty; + bool isList = member!.Mapping.TypeDesc!.IsArrayLike && !member.Mapping.TypeDesc.IsArray; WriteElement(e, member.Mapping.CheckSpecified == SpecifiedAccessor.ReadWrite, isList && member.Mapping.TypeDesc.IsNullable, member.Mapping.ReadOnly, ns, member.FixupIndex, elementIndex, fixup, member); } } @@ -801,13 +803,13 @@ private void WriteMemberElementsIf(Member[] expectedMembers, Member anyElementMe { MemberMapping anyElement = anyElementMember.Mapping; member = anyElementMember; - ElementAccessor[] elements = anyElement.Elements; + ElementAccessor[] elements = anyElement.Elements!; for (int i = 0; i < elements.Length; i++) { ElementAccessor element = elements[i]; if (element.Any && element.Name.Length == 0) { - string ns = element.Form == XmlSchemaForm.Qualified ? element.Namespace : string.Empty; + string? ns = element.Form == XmlSchemaForm.Qualified ? element.Namespace : string.Empty; WriteElement(element, anyElement.CheckSpecified == SpecifiedAccessor.ReadWrite, false, false, ns, fixup: fixup, member: member); break; } @@ -821,9 +823,9 @@ private void WriteMemberElementsIf(Member[] expectedMembers, Member anyElementMe } } - private object WriteElement(ElementAccessor element, bool checkSpecified, bool checkForNull, bool readOnly, string defaultNamespace, int fixupIndex = -1, int elementIndex = -1, Fixup fixup = null, Member member = null) + private object? WriteElement(ElementAccessor element, bool checkSpecified, bool checkForNull, bool readOnly, string? defaultNamespace, int fixupIndex = -1, int elementIndex = -1, Fixup? fixup = null, Member? member = null) { - object value = null; + object? value = null; if (element.Mapping is ArrayMapping arrayMapping) { value = WriteArray(arrayMapping, readOnly, element.IsNullable, defaultNamespace, fixupIndex, fixup, member); @@ -832,25 +834,25 @@ private object WriteElement(ElementAccessor element, bool checkSpecified, bool c { value = WriteNullableMethod(nullableMapping, true, defaultNamespace); } - else if (!element.Mapping.IsSoap && (element.Mapping is PrimitiveMapping)) + else if (!element.Mapping!.IsSoap && (element.Mapping is PrimitiveMapping)) { if (element.IsNullable && ReadNull()) { - if (element.Mapping.TypeDesc.IsValueType) + if (element.Mapping.TypeDesc!.IsValueType) { - value = ReflectionCreateObject(element.Mapping.TypeDesc.Type); + value = ReflectionCreateObject(element.Mapping.TypeDesc.Type!); } else { value = null; } } - else if ((element.Default != null && element.Default != DBNull.Value && element.Mapping.TypeDesc.IsValueType) + else if ((element.Default != null && element.Default != DBNull.Value && element.Mapping.TypeDesc!.IsValueType) && (Reader.IsEmptyElement)) { Reader.Skip(); } - else if (element.Mapping.TypeDesc.Type == typeof(TimeSpan) && Reader.IsEmptyElement) + else if (element.Mapping.TypeDesc!.Type == typeof(TimeSpan) && Reader.IsEmptyElement) { Reader.Skip(); value = default(TimeSpan); @@ -884,11 +886,11 @@ private object WriteElement(ElementAccessor element, bool checkSpecified, bool c TypeMapping mapping = element.Mapping; if (mapping.IsSoap) { - object rre = fixupIndex >= 0 ? - ReadReferencingElement(mapping.TypeName, mapping.Namespace, out fixup.Ids[fixupIndex]) + object? rre = fixupIndex >= 0 ? + ReadReferencingElement(mapping.TypeName, mapping.Namespace, out fixup!.Ids![fixupIndex]) : ReadReferencedElement(mapping.TypeName, mapping.Namespace); - if (!mapping.TypeDesc.IsValueType || rre != null) + if (!mapping.TypeDesc!.IsValueType || rre != null) { value = rre; Referenced(value); @@ -901,13 +903,13 @@ private object WriteElement(ElementAccessor element, bool checkSpecified, bool c throw new InvalidOperationException(SR.XmlInternalError); } - member.Source(value); + member.Source!(value!); return value; } } else { - if (checkForNull && (member.Source == null && member.ArraySource == null)) + if (checkForNull && (member!.Source == null && member.ArraySource == null)) { Reader.Skip(); } @@ -915,7 +917,7 @@ private object WriteElement(ElementAccessor element, bool checkSpecified, bool c { value = WriteStructMethod( mapping: (StructMapping)mapping, - isNullable: mapping.TypeDesc.IsNullable && element.IsNullable, + isNullable: mapping.TypeDesc!.IsNullable && element.IsNullable, checkType: true, defaultNamespace: defaultNamespace ); @@ -924,7 +926,7 @@ private object WriteElement(ElementAccessor element, bool checkSpecified, bool c } else if (element.Mapping is SpecialMapping specialMapping) { - switch (specialMapping.TypeDesc.Kind) + switch (specialMapping.TypeDesc!.Kind) { case TypeKind.Node: bool isDoc = specialMapping.TypeDesc.FullName == typeof(XmlDocument).FullName; @@ -944,8 +946,8 @@ private object WriteElement(ElementAccessor element, bool checkSpecified, bool c bool flag = true; if (sm.DerivedMappings != null) { - XmlQualifiedName tser = GetXsiType(); - if (tser == null || QNameEqual(tser, sm.XsiType.Name, sm.XsiType.Namespace, defaultNamespace)) + XmlQualifiedName? tser = GetXsiType(); + if (tser == null || QNameEqual(tser, sm.XsiType!.Name, sm.XsiType.Namespace, defaultNamespace)) { } else @@ -957,7 +959,7 @@ private object WriteElement(ElementAccessor element, bool checkSpecified, bool c if (flag) { bool isWrappedAny = !element.Any && IsWildcard(sm); - value = ReadSerializable((IXmlSerializable)ReflectionCreateObject(sm.TypeDesc.Type), isWrappedAny); + value = ReadSerializable((IXmlSerializable)ReflectionCreateObject(sm.TypeDesc!.Type!)!, isWrappedAny); } if (sm.DerivedMappings != null) @@ -982,11 +984,11 @@ private object WriteElement(ElementAccessor element, bool checkSpecified, bool c if (member?.ArraySource != null) { - member?.ArraySource(value); + member?.ArraySource(value!); } else { - member?.Source?.Invoke(value); + member?.Source?.Invoke(value!); member?.CheckSpecifiedSource?.Invoke(true); } @@ -997,7 +999,7 @@ private XmlSerializationReadCallback CreateXmlSerializationReadCallback(TypeMapp { if (mapping is StructMapping structMapping) { - return () => WriteStructMethod(structMapping, mapping.TypeDesc.IsNullable, true, defaultNamespace: null); + return () => WriteStructMethod(structMapping, mapping.TypeDesc!.IsNullable, true, defaultNamespace: null); } else if (mapping is EnumMapping enumMapping) { @@ -1011,11 +1013,11 @@ private XmlSerializationReadCallback CreateXmlSerializationReadCallback(TypeMapp return DummyReadArrayMethod; } - private static void NoopAction(object o) + private static void NoopAction(object? o) { } - private object DummyReadArrayMethod() + private object? DummyReadArrayMethod() { UnknownNode(null); return null; @@ -1046,30 +1048,30 @@ private static bool IsWildcard(SpecialMapping mapping) if (mapping is SerializableMapping serializableMapping) return serializableMapping.IsAny; - return mapping.TypeDesc.CanBeElementValue; + return mapping.TypeDesc!.CanBeElementValue; } - private object WriteArray(ArrayMapping arrayMapping, bool readOnly, bool isNullable, string defaultNamespace, int fixupIndex = -1, Fixup fixup = null, Member member = null) + private object? WriteArray(ArrayMapping arrayMapping, bool readOnly, bool isNullable, string? defaultNamespace, int fixupIndex = -1, Fixup? fixup = null, Member? member = null) { - object o = null; + object? o = null; if (arrayMapping.IsSoap) { - object rre; + object? rre; if (fixupIndex >= 0) { - rre = ReadReferencingElement(arrayMapping.TypeName, arrayMapping.Namespace, out fixup.Ids[fixupIndex]); + rre = ReadReferencingElement(arrayMapping.TypeName, arrayMapping.Namespace, out fixup!.Ids![fixupIndex]); } else { rre = ReadReferencedElement(arrayMapping.TypeName, arrayMapping.Namespace); } - TypeDesc td = arrayMapping.TypeDesc; + TypeDesc td = arrayMapping.TypeDesc!; if (rre != null) { if (td.IsEnumerable || td.IsCollection) { - WriteAddCollectionFixup(member.GetSource, member.Source, rre, td, readOnly); + WriteAddCollectionFixup(member!.GetSource!, member.Source!, rre, td, readOnly); // member.Source has been set at this point. // Setting the source to no-op to avoid setting the @@ -1083,7 +1085,7 @@ private object WriteArray(ArrayMapping arrayMapping, bool readOnly, bool isNulla throw new InvalidOperationException(SR.XmlInternalError); } - member.Source(rre); + member.Source!(rre); } } @@ -1100,8 +1102,8 @@ private object WriteArray(ArrayMapping arrayMapping, bool readOnly, bool isNulla ReadOnly = readOnly }; - Type collectionType = memberMapping.TypeDesc.Type; - o = ReflectionCreateObject(memberMapping.TypeDesc.Type); + Type collectionType = memberMapping.TypeDesc!.Type!; + o = ReflectionCreateObject(memberMapping.TypeDesc.Type!); if (memberMapping.ChoiceIdentifier != null) { @@ -1150,7 +1152,7 @@ private object WritePrimitive(TypeMapping mapping, Func readFunc { return readFunc(funcState); } - else if (mapping.TypeDesc.FormatterName == "String") + else if (mapping.TypeDesc!.FormatterName == "String") { if (mapping.TypeDesc.CollapseWhitespace) { @@ -1190,18 +1192,18 @@ private object WritePrimitive(TypeMapping mapping, Func readFunc else { string methodName = "To" + mapping.TypeDesc.FormatterName; - MethodInfo method = typeof(XmlSerializationReader).GetMethod(methodName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, new Type[] { typeof(string) }); + MethodInfo? method = typeof(XmlSerializationReader).GetMethod(methodName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, new Type[] { typeof(string) }); if (method == null) { throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, $"unknown FormatterName: {mapping.TypeDesc.FormatterName}")); } - return method.Invoke(this, new object[] { readFunc(funcState) }); + return method.Invoke(this, new object[] { readFunc(funcState) })!; } } } - private object WriteStructMethod(StructMapping mapping, bool isNullable, bool checkType, string defaultNamespace) + private object? WriteStructMethod(StructMapping mapping, bool isNullable, bool checkType, string? defaultNamespace) { if (mapping.IsSoap) return WriteEncodedStructMethod(mapping); @@ -1209,15 +1211,15 @@ private object WriteStructMethod(StructMapping mapping, bool isNullable, bool ch return WriteLiteralStructMethod(mapping, isNullable, checkType, defaultNamespace); } - private object WriteNullableMethod(NullableMapping nullableMapping, bool checkType, string defaultNamespace) + private object? WriteNullableMethod(NullableMapping nullableMapping, bool checkType, string? defaultNamespace) { - object o = Activator.CreateInstance(nullableMapping.TypeDesc.Type); + object? o = Activator.CreateInstance(nullableMapping.TypeDesc!.Type!); if (!ReadNull()) { ElementAccessor element = new ElementAccessor(); element.Mapping = nullableMapping.BaseMapping; element.Any = false; - element.IsNullable = nullableMapping.BaseMapping.TypeDesc.IsNullable; + element.IsNullable = nullableMapping.BaseMapping!.TypeDesc!.IsNullable; o = WriteElement(element, false, false, false, defaultNamespace); } @@ -1242,27 +1244,27 @@ private object WriteEnumMethod(EnumMapping mapping, string source) { if (mapping.IsFlags) { - Hashtable table = WriteHashtable(mapping, mapping.TypeDesc.Name); - return Enum.ToObject(mapping.TypeDesc.Type, ToEnum(source, table, mapping.TypeDesc.Name)); + Hashtable table = WriteHashtable(mapping, mapping.TypeDesc!.Name); + return Enum.ToObject(mapping.TypeDesc.Type!, ToEnum(source, table, mapping.TypeDesc.Name)); } else { - foreach (ConstantMapping c in mapping.Constants) + foreach (ConstantMapping c in mapping.Constants!) { if (string.Equals(c.XmlName, source)) { - return Enum.Parse(mapping.TypeDesc.Type, c.Name); + return Enum.Parse(mapping.TypeDesc!.Type!, c.Name); } } - throw CreateUnknownConstantException(source, mapping.TypeDesc.Type); + throw CreateUnknownConstantException(source, mapping.TypeDesc!.Type!); } } private Hashtable WriteHashtable(EnumMapping mapping, string name) { var h = new Hashtable(); - ConstantMapping[] constants = mapping.Constants; + ConstantMapping[] constants = mapping.Constants!; for (int i = 0; i < constants.Length; i++) { h.Add(constants[i].XmlName, constants[i].Value); @@ -1271,16 +1273,16 @@ private Hashtable WriteHashtable(EnumMapping mapping, string name) return h; } - private object ReflectionCreateObject(Type type) + private object? ReflectionCreateObject(Type type) { - object obj; + object? obj; if (type.IsArray) { obj = Activator.CreateInstance(type, 32); } else { - ConstructorInfo ci = GetDefaultConstructor(type); + ConstructorInfo? ci = GetDefaultConstructor(type); if (ci != null) { obj = ci.Invoke(Array.Empty()); @@ -1294,16 +1296,16 @@ private object ReflectionCreateObject(Type type) return obj; } - private ConstructorInfo GetDefaultConstructor(Type type) + private ConstructorInfo? GetDefaultConstructor(Type type) { if (type.IsValueType) return null; - ConstructorInfo ctor = FindDefaultConstructor(type.GetTypeInfo()); + ConstructorInfo? ctor = FindDefaultConstructor(type.GetTypeInfo()); return ctor; } - private static ConstructorInfo FindDefaultConstructor(TypeInfo ti) + private static ConstructorInfo? FindDefaultConstructor(TypeInfo ti) { foreach (ConstructorInfo ci in ti.DeclaredConstructors) { @@ -1316,20 +1318,20 @@ private static ConstructorInfo FindDefaultConstructor(TypeInfo ti) return null; } - private object WriteEncodedStructMethod(StructMapping structMapping) + private object? WriteEncodedStructMethod(StructMapping structMapping) { - if (structMapping.TypeDesc.IsRoot) + if (structMapping.TypeDesc!.IsRoot) return null; - Member[] members = null; + Member[]? members = null; if (structMapping.TypeDesc.IsAbstract) { - throw CreateAbstractTypeException(structMapping.TypeName, structMapping.Namespace); + throw CreateAbstractTypeException(structMapping.TypeName!, structMapping.Namespace); } else { - object o = ReflectionCreateObject(structMapping.TypeDesc.Type); + object? o = ReflectionCreateObject(structMapping.TypeDesc.Type!); MemberMapping[] mappings = TypeScope.GetSettableMembers(structMapping); members = new Member[mappings.Length]; @@ -1338,14 +1340,14 @@ private object WriteEncodedStructMethod(StructMapping structMapping) MemberMapping mapping = mappings[i]; var member = new Member(mapping); - TypeDesc td = member.Mapping.TypeDesc; + TypeDesc td = member.Mapping.TypeDesc!; if (td.IsCollection || td.IsEnumerable) { - member.Source = (value) => WriteAddCollectionFixup(o, member, value); + member.Source = (value) => WriteAddCollectionFixup(o!, member, value!); } else if (!member.Mapping.ReadOnly) { - var setterDelegate = GetSetMemberValueDelegate(o, member.Mapping.MemberInfo.Name); + var setterDelegate = GetSetMemberValueDelegate(o!, member.Mapping.MemberInfo!.Name); member.Source = (value) => setterDelegate(o, value); } else @@ -1356,7 +1358,7 @@ private object WriteEncodedStructMethod(StructMapping structMapping) members[i] = member; } - Fixup fixup = WriteMemberFixupBegin(members, o); + Fixup? fixup = WriteMemberFixupBegin(members, o); UnknownNodeAction unknownNodeAction = (_) => UnknownNode(o); WriteAttributes(members, null, unknownNodeAction, ref o); Reader.MoveToElement(); @@ -1379,15 +1381,15 @@ private object WriteEncodedStructMethod(StructMapping structMapping) } } - private Fixup WriteMemberFixupBegin(Member[] members, object o) + private Fixup? WriteMemberFixupBegin(Member[] members, object? o) { int fixupCount = 0; foreach (Member member in members) { - if (member.Mapping.Elements.Length == 0) + if (member.Mapping.Elements!.Length == 0) continue; - TypeMapping mapping = member.Mapping.Elements[0].Mapping; + TypeMapping? mapping = member.Mapping.Elements[0].Mapping; if (mapping is StructMapping || mapping is ArrayMapping || mapping is PrimitiveMapping || mapping is NullableMapping) { member.MultiRef = true; @@ -1395,7 +1397,7 @@ private Fixup WriteMemberFixupBegin(Member[] members, object o) } } - Fixup fixup; + Fixup? fixup; if (fixupCount > 0) { fixup = new Fixup(o, CreateWriteFixupMethod(members), fixupCount); @@ -1414,7 +1416,7 @@ private XmlSerializationFixupCallback CreateWriteFixupMethod(Member[] members) return (fixupObject) => { var fixup = (Fixup)fixupObject; - string[] ids = fixup.Ids; + string[] ids = fixup.Ids!; foreach (Member member in members) { if (member.MultiRef) @@ -1423,7 +1425,7 @@ private XmlSerializationFixupCallback CreateWriteFixupMethod(Member[] members) if (ids[fixupIndex] != null) { var memberValue = GetTarget(ids[fixupIndex]); - member.Source(memberValue); + member.Source!(memberValue); } } } @@ -1432,17 +1434,17 @@ private XmlSerializationFixupCallback CreateWriteFixupMethod(Member[] members) private void WriteAddCollectionFixup(object o, Member member, object memberValue) { - TypeDesc typeDesc = member.Mapping.TypeDesc; + TypeDesc typeDesc = member.Mapping.TypeDesc!; bool readOnly = member.Mapping.ReadOnly; - Func getSource = () => GetMemberValue(o, member.Mapping.MemberInfo); - var setterDelegate = GetSetMemberValueDelegate(o, member.Mapping.MemberInfo.Name); - Action setSource = (value) => setterDelegate(o, value); + Func getSource = () => GetMemberValue(o, member.Mapping.MemberInfo!); + var setterDelegate = GetSetMemberValueDelegate(o, member.Mapping.MemberInfo!.Name); + Action setSource = (value) => setterDelegate(o, value); WriteAddCollectionFixup(getSource, setSource, memberValue, typeDesc, readOnly); } - private object WriteAddCollectionFixup(Func getSource, Action setSource, object memberValue, TypeDesc typeDesc, bool readOnly) + private object? WriteAddCollectionFixup(Func getSource, Action setSource, object memberValue, TypeDesc typeDesc, bool readOnly) { - object memberSource = getSource(); + object? memberSource = getSource(); if (memberSource == null) { if (readOnly) @@ -1450,13 +1452,13 @@ private object WriteAddCollectionFixup(Func getSource, Action se throw CreateReadOnlyCollectionException(typeDesc.CSharpName); } - memberSource = ReflectionCreateObject(typeDesc.Type); + memberSource = ReflectionCreateObject(typeDesc.Type!); setSource(memberSource); } var collectionFixup = new CollectionFixup( memberSource, - new XmlSerializationCollectionFixupCallback(GetCreateCollectionOfObjectsCallback(typeDesc.Type)), + new XmlSerializationCollectionFixupCallback(GetCreateCollectionOfObjectsCallback(typeDesc.Type!)), memberValue); AddFixup(collectionFixup); @@ -1473,7 +1475,7 @@ private XmlSerializationCollectionFixupCallback GetCreateCollectionOfObjectsCall if (collection == null) return; - var listOfItems = new List(); + var listOfItems = new List(); if (collectionItems is IEnumerable enumerableItems) { foreach (var item in enumerableItems) @@ -1490,9 +1492,9 @@ private XmlSerializationCollectionFixupCallback GetCreateCollectionOfObjectsCall }; } - private object WriteLiteralStructMethod(StructMapping structMapping, bool isNullable, bool checkType, string defaultNamespace) + private object? WriteLiteralStructMethod(StructMapping structMapping, bool isNullable, bool checkType, string? defaultNamespace) { - XmlQualifiedName xsiType = checkType ? GetXsiType() : null; + XmlQualifiedName? xsiType = checkType ? GetXsiType() : null; bool isNull = false; if (isNullable) { @@ -1501,7 +1503,7 @@ private object WriteLiteralStructMethod(StructMapping structMapping, bool isNull if (checkType) { - if (structMapping.TypeDesc.IsRoot && isNull) + if (structMapping.TypeDesc!.IsRoot && isNull) { if (xsiType != null) { @@ -1511,7 +1513,7 @@ private object WriteLiteralStructMethod(StructMapping structMapping, bool isNull { if (structMapping.TypeDesc.IsValueType) { - return ReflectionCreateObject(structMapping.TypeDesc.Type); + return ReflectionCreateObject(structMapping.TypeDesc.Type!); } else { @@ -1520,7 +1522,7 @@ private object WriteLiteralStructMethod(StructMapping structMapping, bool isNull } } - object o = null; + object? o = null; if (xsiType == null || (!structMapping.TypeDesc.IsRoot && QNameEqual(xsiType, structMapping.TypeName, structMapping.Namespace, defaultNamespace))) { if (structMapping.TypeDesc.IsRoot) @@ -1545,13 +1547,13 @@ private object WriteLiteralStructMethod(StructMapping structMapping, bool isNull } } - if (structMapping.TypeDesc.IsNullable && isNull) + if (structMapping.TypeDesc!.IsNullable && isNull) { return null; } else if (structMapping.TypeDesc.IsAbstract) { - throw CreateAbstractTypeException(structMapping.TypeName, structMapping.Namespace); + throw CreateAbstractTypeException(structMapping.TypeName!, structMapping.Namespace); } else { @@ -1562,14 +1564,14 @@ private object WriteLiteralStructMethod(StructMapping structMapping, bool isNull throw new NotImplementedException(nameof(XmlSchemaObject)); } - object o = ReflectionCreateObject(structMapping.TypeDesc.Type); + object? o = ReflectionCreateObject(structMapping.TypeDesc.Type!)!; MemberMapping[] mappings = TypeScope.GetSettableMembers(structMapping); - MemberMapping anyText = null; - MemberMapping anyElement = null; - Member anyAttribute = null; - Member anyElementMember = null; - Member anyTextMember = null; + MemberMapping? anyText = null; + MemberMapping? anyElement = null; + Member? anyAttribute = null; + Member? anyElementMember = null; + Member? anyTextMember = null; bool isSequence = structMapping.HasExplicitSequence(); @@ -1595,7 +1597,7 @@ private object WriteLiteralStructMethod(StructMapping structMapping, bool isNull if (mapping.Attribute != null) { - member.Source = (value) => SetOrAddValueToMember(o, value, member.Mapping.MemberInfo); + member.Source = (value) => SetOrAddValueToMember(o!, value!, member.Mapping.MemberInfo!); if (mapping.Attribute.Any) { anyAttribute = member; @@ -1605,7 +1607,7 @@ private object WriteLiteralStructMethod(StructMapping structMapping, bool isNull if (!isSequence) { // find anyElement if present. - for (int j = 0; j < mapping.Elements.Length; j++) + for (int j = 0; j < mapping.Elements!.Length; j++) { if (mapping.Elements[j].Any && (mapping.Elements[j].Name == null || mapping.Elements[j].Name.Length == 0)) { @@ -1616,13 +1618,13 @@ private object WriteLiteralStructMethod(StructMapping structMapping, bool isNull } else if (mapping.IsParticle && !mapping.IsSequence) { - structMapping.FindDeclaringMapping(mapping, out StructMapping declaringMapping, structMapping.TypeName); - throw new InvalidOperationException(SR.Format(SR.XmlSequenceHierarchy, structMapping.TypeDesc.FullName, mapping.Name, declaringMapping.TypeDesc.FullName, "Order")); + structMapping.FindDeclaringMapping(mapping, out StructMapping? declaringMapping, structMapping.TypeName!); + throw new InvalidOperationException(SR.Format(SR.XmlSequenceHierarchy, structMapping.TypeDesc.FullName, mapping.Name, declaringMapping!.TypeDesc!.FullName, "Order")); } - if (mapping.TypeDesc.IsArrayLike) + if (mapping.TypeDesc!.IsArrayLike) { - if (member.Source == null && mapping.TypeDesc.IsArrayLike && !(mapping.Elements.Length == 1 && mapping.Elements[0].Mapping is ArrayMapping)) + if (member.Source == null && mapping.TypeDesc.IsArrayLike && !(mapping.Elements!.Length == 1 && mapping.Elements[0].Mapping is ArrayMapping)) { member.Source = (item) => { @@ -1649,7 +1651,7 @@ private object WriteLiteralStructMethod(StructMapping structMapping, bool isNull { member.Source = (value) => { - var getOnlyList = (IList)pi.GetValue(o); + var getOnlyList = (IList)pi.GetValue(o)!; if (value is IList valueList) { foreach (var v in valueList) @@ -1668,7 +1670,7 @@ private object WriteLiteralStructMethod(StructMapping structMapping, bool isNull if (member.Mapping.Xmlns != null) { var xmlSerializerNamespaces = new XmlSerializerNamespaces(); - var setMemberValue = GetSetMemberValueDelegate(o, member.Mapping.Name); + var setMemberValue = GetSetMemberValueDelegate(o!, member.Mapping.Name); setMemberValue(o, xmlSerializerNamespaces); member.XmlnsSource = (ns, name) => { @@ -1677,7 +1679,7 @@ private object WriteLiteralStructMethod(StructMapping structMapping, bool isNull } else { - var setterDelegate = GetSetMemberValueDelegate(o, member.Mapping.Name); + var setterDelegate = GetSetMemberValueDelegate(o!, member.Mapping.Name); member.Source = (value) => setterDelegate(o, value); } } @@ -1688,7 +1690,7 @@ private object WriteLiteralStructMethod(StructMapping structMapping, bool isNull member.CheckSpecifiedSource = (_) => { string specifiedMemberName = member.Mapping.Name + "Specified"; - MethodInfo specifiedMethodInfo = o.GetType().GetMethod("set_" + specifiedMemberName); + MethodInfo? specifiedMethodInfo = o!.GetType().GetMethod("set_" + specifiedMemberName); if (specifiedMethodInfo != null) { specifiedMethodInfo.Invoke(o, new object[] { true }); @@ -1696,18 +1698,18 @@ private object WriteLiteralStructMethod(StructMapping structMapping, bool isNull }; } - ChoiceIdentifierAccessor choice = mapping.ChoiceIdentifier; + ChoiceIdentifierAccessor? choice = mapping.ChoiceIdentifier; if (choice != null && o != null) { member.ChoiceSource = (elementNameObject) => { - string elementName = elementNameObject as string; - foreach (var name in choice.MemberIds) + string? elementName = elementNameObject as string; + foreach (var name in choice.MemberIds!) { if (name == elementName) { - object choiceValue = Enum.Parse(choice.Mapping.TypeDesc.Type, name); - SetOrAddValueToMember(o, choiceValue, choice.MemberInfo); + object choiceValue = Enum.Parse(choice.Mapping!.TypeDesc!.Type!, name); + SetOrAddValueToMember(o, choiceValue, choice.MemberInfo!); break; } @@ -1756,10 +1758,10 @@ private object WriteLiteralStructMethod(StructMapping structMapping, bool isNull { if (member.Collection != null) { - MemberInfo[] memberInfos = o.GetType().GetMember(member.Mapping.Name); + MemberInfo[] memberInfos = o!.GetType().GetMember(member.Mapping.Name); MemberInfo memberInfo = memberInfos[0]; - object collection = null; - SetCollectionObjectWithCollectionMember(ref collection, member.Collection, member.Mapping.TypeDesc.Type); + object? collection = null; + SetCollectionObjectWithCollectionMember(ref collection, member.Collection, member.Mapping.TypeDesc!.Type!); var setMemberValue = GetSetMemberValueDelegate(o, memberInfo.Name); setMemberValue(o, collection); } @@ -1770,9 +1772,9 @@ private object WriteLiteralStructMethod(StructMapping structMapping, bool isNull } } - private bool WriteEnumAndArrayTypes(out object o, StructMapping mapping, XmlQualifiedName xsiType, string defaultNamespace) + private bool WriteEnumAndArrayTypes(out object? o, StructMapping mapping, XmlQualifiedName xsiType, string? defaultNamespace) { - foreach (var m in _mapping.Scope.TypeMappings) + foreach (var m in _mapping.Scope!.TypeMappings) { if (m is EnumMapping enumMapping) { @@ -1808,9 +1810,9 @@ private bool WriteEnumAndArrayTypes(out object o, StructMapping mapping, XmlQual return false; } - private bool WriteDerivedTypes(out object o, StructMapping mapping, XmlQualifiedName xsiType, string defaultNamespace, bool checkType, bool isNullable) + private bool WriteDerivedTypes(out object? o, StructMapping mapping, XmlQualifiedName xsiType, string? defaultNamespace, bool checkType, bool isNullable) { - for (StructMapping derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) + for (StructMapping? derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) { if (QNameEqual(xsiType, derived.TypeName, derived.Namespace, defaultNamespace)) { @@ -1828,9 +1830,9 @@ private bool WriteDerivedTypes(out object o, StructMapping mapping, XmlQualified return false; } - private void WriteAttributes(Member[] members, Member anyAttribute, UnknownNodeAction elseCall, ref object o) + private void WriteAttributes(Member[] members, Member? anyAttribute, UnknownNodeAction elseCall, ref object? o) { - Member xmlnsMember = null; + Member? xmlnsMember = null; var attributes = new List(); foreach (Member member in members) { @@ -1851,7 +1853,7 @@ private void WriteAttributes(Member[] members, Member anyAttribute, UnknownNodeA continue; } - AttributeAccessor attribute = member.Mapping.Attribute; + AttributeAccessor? attribute = member.Mapping.Attribute; if (attribute == null) continue; if (attribute.Any) continue; @@ -1902,7 +1904,7 @@ private void WriteAttributes(Member[] members, Member anyAttribute, UnknownNodeA { if (anyAttribute != null) { - var attr = Document.ReadNode(Reader) as XmlAttribute; + var attr = (Document.ReadNode(Reader) as XmlAttribute)!; ParseWsdlArrayType(attr); WriteAttribute(anyAttribute, attr); } @@ -1914,13 +1916,13 @@ private void WriteAttributes(Member[] members, Member anyAttribute, UnknownNodeA } } - private void WriteAttribute(Member member, object attr = null) + private void WriteAttribute(Member member, object? attr = null) { - AttributeAccessor attribute = member.Mapping.Attribute; - object value = null; + AttributeAccessor attribute = member.Mapping.Attribute!; + object? value = null; if (attribute.Mapping is SpecialMapping special) { - if (special.TypeDesc.Kind == TypeKind.Attribute) + if (special.TypeDesc!.Kind == TypeKind.Attribute) { value = attr; } @@ -1939,21 +1941,21 @@ private void WriteAttribute(Member member, object attr = null) { string listValues = Reader.Value; string[] vals = listValues.Split(null); - Array arrayValue = Array.CreateInstance(member.Mapping.TypeDesc.Type.GetElementType(), vals.Length); + Array arrayValue = Array.CreateInstance(member.Mapping.TypeDesc!.Type!.GetElementType()!, vals.Length); for (int i = 0; i < vals.Length; i++) { - arrayValue.SetValue(WritePrimitive(attribute.Mapping, (state) => ((string[])state)[i], vals), i); + arrayValue.SetValue(WritePrimitive(attribute.Mapping!, (state) => ((string[])state)[i], vals), i); } value = arrayValue; } else { - value = WritePrimitive(attribute.Mapping, (state) => ((XmlReader)state).Value, Reader); + value = WritePrimitive(attribute.Mapping!, (state) => ((XmlReader)state).Value, Reader); } } - member.Source(value); + member.Source!(value); if (member.Mapping.CheckSpecified == SpecifiedAccessor.ReadWrite) { @@ -1983,7 +1985,7 @@ private void SetOrAddValueToMember(object o, object value, MemberInfo memberInfo private void AddItemInArrayMember(object o, MemberInfo memberInfo, Type memberType, object item) { - var currentArray = (Array)GetMemberValue(o, memberInfo); + var currentArray = (Array?)GetMemberValue(o, memberInfo); int length; if (currentArray == null) { @@ -1994,7 +1996,7 @@ private void AddItemInArrayMember(object o, MemberInfo memberInfo, Type memberTy length = currentArray.Length; } - var newArray = Array.CreateInstance(memberType.GetElementType(), length + 1); + var newArray = Array.CreateInstance(memberType.GetElementType()!, length + 1); if (currentArray != null) { Array.Copy(currentArray, newArray, length); @@ -2006,37 +2008,37 @@ private void AddItemInArrayMember(object o, MemberInfo memberInfo, Type memberTy } // WriteXmlNodeEqual - private bool XmlNodeEqual(XmlReader source, string name, string ns) + private bool XmlNodeEqual(XmlReader source, string name, string? ns) { return source.LocalName == name && string.Equals(source.NamespaceURI, ns); } - private bool QNameEqual(XmlQualifiedName xsiType, string name, string ns, string defaultNamespace) + private bool QNameEqual(XmlQualifiedName xsiType, string? name, string? ns, string? defaultNamespace) { return xsiType.Name == name && string.Equals(xsiType.Namespace, defaultNamespace); } - private void CreateUnknownNodeException(object o) + private void CreateUnknownNodeException(object? o) { CreateUnknownNodeException(); } - internal class CollectionMember : List + internal class CollectionMember : List { } internal class Member { public MemberMapping Mapping; - public CollectionMember Collection; + public CollectionMember? Collection; public int FixupIndex = -1; public bool MultiRef; - public Action Source; - public Func GetSource; - public Action ArraySource; - public Action CheckSpecifiedSource; - public Action ChoiceSource; - public Action XmlnsSource; + public Action? Source; + public Func? GetSource; + public Action? ArraySource; + public Action? CheckSpecifiedSource; + public Action? ChoiceSource; + public Action? XmlnsSource; public Member(MemberMapping mapping) { @@ -2046,21 +2048,21 @@ public Member(MemberMapping mapping) internal class CheckTypeSource { - public string Id { get; set; } + public string? Id { get; set; } public bool IsObject { get; set; } - public Type Type { get; set; } - public object RefObject { get; set; } + public Type? Type { get; set; } + public object? RefObject { get; set; } } internal class ObjectHolder { - public object Object; + public object? Object; } } internal static class ReflectionXmlSerializationReaderHelper { - public delegate void SetMemberValueDelegate(object o, object val); + public delegate void SetMemberValueDelegate(object? o, object? val); public static SetMemberValueDelegate GetSetMemberValueDelegateWithType(MemberInfo memberInfo) { @@ -2068,14 +2070,14 @@ public static SetMemberValueDelegate GetSetMemberValueDelegateWithType setTypedDelegate = null; + Action? setTypedDelegate = null; if (memberInfo is PropertyInfo propInfo) { var setMethod = propInfo.GetSetMethod(true); if (setMethod == null) { - return delegate (object o, object p) + return delegate (object? o, object? p) { // Maintain the same failure behavior as non-cached delegate propInfo.SetValue(o, p); @@ -2109,9 +2111,9 @@ public static SetMemberValueDelegate GetSetMemberValueDelegateWithType>(assignExpr, objectParam, valueParam).Compile(); } - return delegate (object o, object p) + return delegate (object? o, object? p) { - setTypedDelegate((TObj)o, (TParam)p); + setTypedDelegate!((TObj)o!, (TParam)p!); }; } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs index 6d86828c7cf883..5258ec2c1cc615 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; using System.Collections; using System.Collections.Generic; @@ -21,7 +22,7 @@ internal class ReflectionXmlSerializationWriter : XmlSerializationWriter internal static TypeDesc StringTypeDesc { get; private set; } = (new TypeScope()).GetTypeDesc(typeof(string)); internal static TypeDesc QnameTypeDesc { get; private set; } = (new TypeScope()).GetTypeDesc(typeof(XmlQualifiedName)); - public ReflectionXmlSerializationWriter(XmlMapping xmlMapping, XmlWriter xmlWriter, XmlSerializerNamespaces namespaces, string encodingStyle, string id) + public ReflectionXmlSerializationWriter(XmlMapping xmlMapping, XmlWriter xmlWriter, XmlSerializerNamespaces namespaces, string? encodingStyle, string? id) { Init(xmlWriter, namespaces, encodingStyle, id, null); @@ -42,24 +43,24 @@ public ReflectionXmlSerializationWriter(XmlMapping xmlMapping, XmlWriter xmlWrit protected override void InitCallbacks() { - TypeScope scope = _mapping.Scope; + TypeScope scope = _mapping.Scope!; foreach (TypeMapping mapping in scope.TypeMappings) { if (mapping.IsSoap && (mapping is StructMapping || mapping is EnumMapping) && - !mapping.TypeDesc.IsRoot) + !mapping.TypeDesc!.IsRoot) { AddWriteCallback( - mapping.TypeDesc.Type, - mapping.TypeName, + mapping.TypeDesc.Type!, + mapping.TypeName!, mapping.Namespace, - CreateXmlSerializationWriteCallback(mapping, mapping.TypeName, mapping.Namespace, mapping.TypeDesc.IsNullable) + CreateXmlSerializationWriteCallback(mapping, mapping.TypeName!, mapping.Namespace, mapping.TypeDesc.IsNullable) ); } } } - public void WriteObject(object o) + public void WriteObject(object? o) { XmlMapping xmlMapping = _mapping; if (xmlMapping is XmlTypeMapping xmlTypeMapping) @@ -68,24 +69,24 @@ public void WriteObject(object o) } else if (xmlMapping is XmlMembersMapping xmlMembersMapping) { - GenerateMembersElement(o, xmlMembersMapping); + GenerateMembersElement(o!, xmlMembersMapping); } } - private void WriteObjectOfTypeElement(object o, XmlTypeMapping mapping) + private void WriteObjectOfTypeElement(object? o, XmlTypeMapping mapping) { GenerateTypeElement(o, mapping); } - private void GenerateTypeElement(object o, XmlTypeMapping xmlMapping) + private void GenerateTypeElement(object? o, XmlTypeMapping xmlMapping) { ElementAccessor element = xmlMapping.Accessor; - TypeMapping mapping = element.Mapping; + TypeMapping mapping = element.Mapping!; WriteStartDocument(); if (o == null) { - string ns = (element.Form == XmlSchemaForm.Qualified ? element.Namespace : string.Empty); + string? ns = (element.Form == XmlSchemaForm.Qualified ? element.Namespace : string.Empty); if (element.IsNullable) { if (mapping.IsSoap) @@ -105,7 +106,7 @@ private void GenerateTypeElement(object o, XmlTypeMapping xmlMapping) return; } - if (!mapping.TypeDesc.IsValueType && !mapping.TypeDesc.Type.IsPrimitive) + if (!mapping.TypeDesc!.IsValueType && !mapping.TypeDesc.Type!.IsPrimitive) { TopLevelElement(); } @@ -117,12 +118,12 @@ private void GenerateTypeElement(object o, XmlTypeMapping xmlMapping) } } - private void WriteMember(object o, object choiceSource, ElementAccessor[] elements, TextAccessor text, ChoiceIdentifierAccessor choice, TypeDesc memberTypeDesc, bool writeAccessors) + private void WriteMember(object? o, object? choiceSource, ElementAccessor[] elements, TextAccessor? text, ChoiceIdentifierAccessor? choice, TypeDesc memberTypeDesc, bool writeAccessors) { if (memberTypeDesc.IsArrayLike && !(elements.Length == 1 && elements[0].Mapping is ArrayMapping)) { - WriteArray(o, choiceSource, elements, text, choice, memberTypeDesc); + WriteArray(o!, choiceSource, elements, text, choice, memberTypeDesc); } else { @@ -130,7 +131,7 @@ private void WriteMember(object o, object choiceSource, ElementAccessor[] elemen } } - private void WriteArray(object o, object choiceSource, ElementAccessor[] elements, TextAccessor text, ChoiceIdentifierAccessor choice, TypeDesc arrayTypeDesc) + private void WriteArray(object o, object? choiceSource, ElementAccessor[] elements, TextAccessor? text, ChoiceIdentifierAccessor? choice, TypeDesc arrayTypeDesc) { if (elements.Length == 0 && text == null) { @@ -146,14 +147,14 @@ private void WriteArray(object o, object choiceSource, ElementAccessor[] element { if (choiceSource == null || ((Array)choiceSource).Length < ((Array)o).Length) { - throw CreateInvalidChoiceIdentifierValueException(choice.Mapping.TypeDesc.FullName, choice.MemberName); + throw CreateInvalidChoiceIdentifierValueException(choice.Mapping!.TypeDesc!.FullName, choice.MemberName!); } } WriteArrayItems(elements, text, choice, arrayTypeDesc, o); } - private void WriteArrayItems(ElementAccessor[] elements, TextAccessor text, ChoiceIdentifierAccessor choice, TypeDesc arrayTypeDesc, object o) + private void WriteArrayItems(ElementAccessor[] elements, TextAccessor? text, ChoiceIdentifierAccessor? choice, TypeDesc? arrayTypeDesc, object o) { var arr = o as IList; @@ -161,7 +162,7 @@ private void WriteArrayItems(ElementAccessor[] elements, TextAccessor text, Choi { for (int i = 0; i < arr.Count; i++) { - object ai = arr[i]; + object? ai = arr[i]; WriteElements(ai, null/*choiceName + "i"*/, elements, text, choice, true, true); } } @@ -182,7 +183,7 @@ private void WriteArrayItems(ElementAccessor[] elements, TextAccessor text, Choi } } - private void WriteElements(object o, object enumSource, ElementAccessor[] elements, TextAccessor text, ChoiceIdentifierAccessor choice, bool writeAccessors, bool isNullable) + private void WriteElements(object? o, object? enumSource, ElementAccessor[] elements, TextAccessor? text, ChoiceIdentifierAccessor? choice, bool writeAccessors, bool isNullable) { if (elements.Length == 0 && text == null) return; @@ -200,8 +201,8 @@ private void WriteElements(object o, object enumSource, ElementAccessor[] elemen int anyCount = 0; var namedAnys = new List(); - ElementAccessor unnamedAny = null; // can only have one - string enumTypeName = choice?.Mapping.TypeDesc.FullName; + ElementAccessor? unnamedAny = null; // can only have one + string? enumTypeName = (choice != null) ? choice.Mapping!.TypeDesc!.FullName : null; for (int i = 0; i < elements.Length; i++) { @@ -217,7 +218,7 @@ private void WriteElements(object o, object enumSource, ElementAccessor[] elemen } else if (choice != null) { - if (o != null && o.GetType() == element.Mapping.TypeDesc.Type) + if (o != null && o.GetType() == element.Mapping!.TypeDesc!.Type) { WriteElement(o, element, writeAccessors); return; @@ -225,8 +226,8 @@ private void WriteElements(object o, object enumSource, ElementAccessor[] elemen } else { - TypeDesc td = element.IsUnbounded ? element.Mapping.TypeDesc.CreateArrayTypeDesc() : element.Mapping.TypeDesc; - if (o.GetType() == td.Type) + TypeDesc td = element.IsUnbounded ? element.Mapping!.TypeDesc!.CreateArrayTypeDesc() : element.Mapping!.TypeDesc!; + if (o!.GetType() == td.Type) { WriteElement(o, element, writeAccessors); return; @@ -249,7 +250,7 @@ private void WriteElements(object o, object enumSource, ElementAccessor[] elemen if (choice != null) { - throw CreateChoiceIdentifierValueException(choice.Mapping.TypeDesc.FullName, choice.MemberName, elem.Name, elem.NamespaceURI); + throw CreateChoiceIdentifierValueException(choice.Mapping!.TypeDesc!.FullName, choice.MemberName!, elem.Name, elem.NamespaceURI); } if (unnamedAny != null) @@ -264,7 +265,7 @@ private void WriteElements(object o, object enumSource, ElementAccessor[] elemen if (text != null) { - WriteText(o, text); + WriteText(o!, text); return; } @@ -279,14 +280,14 @@ private void WriteText(object o, TextAccessor text) { if (text.Mapping is PrimitiveMapping primitiveMapping) { - string stringValue; + string? stringValue; if (text.Mapping is EnumMapping enumMapping) { stringValue = WriteEnumMethod(enumMapping, o); } else { - if (!WritePrimitiveValue(primitiveMapping.TypeDesc, o, false, out stringValue)) + if (!WritePrimitiveValue(primitiveMapping.TypeDesc!, o, false, out stringValue)) { Debug.Assert(o is byte[]); } @@ -303,7 +304,7 @@ private void WriteText(object o, TextAccessor text) } else if (text.Mapping is SpecialMapping specialMapping) { - switch (specialMapping.TypeDesc.Kind) + switch (specialMapping.TypeDesc!.Kind) { case TypeKind.Node: ((XmlNode)o).WriteTo(Writer); @@ -314,10 +315,10 @@ private void WriteText(object o, TextAccessor text) } } - private void WriteElement(object o, ElementAccessor element, bool writeAccessor) + private void WriteElement(object? o, ElementAccessor element, bool writeAccessor) { - string name = writeAccessor ? element.Name : element.Mapping.TypeName; - string ns = element.Any && element.Name.Length == 0 ? null : (element.Form == XmlSchemaForm.Qualified ? (writeAccessor ? element.Namespace : element.Mapping.Namespace) : string.Empty); + string name = writeAccessor ? element.Name : element.Mapping!.TypeName!; + string? ns = element.Any && element.Name.Length == 0 ? null : (element.Form == XmlSchemaForm.Qualified ? (writeAccessor ? element.Namespace : element.Mapping!.Namespace) : string.Empty); if (element.Mapping is NullableMapping nullableMapping) { @@ -339,7 +340,7 @@ private void WriteElement(object o, ElementAccessor element, bool writeAccessor) { WriteNullTagLiteral(element.Name, element.Form == XmlSchemaForm.Qualified ? element.Namespace : string.Empty); } - else if (mapping.IsSoap) + else if (mapping!.IsSoap) { if (mapping.Elements == null || mapping.Elements.Length != 1) { @@ -348,7 +349,7 @@ private void WriteElement(object o, ElementAccessor element, bool writeAccessor) if (!writeAccessor) { - WritePotentiallyReferencingElement(name, ns, o, mapping.TypeDesc.Type, true, element.IsNullable); + WritePotentiallyReferencingElement(name, ns, o, mapping.TypeDesc!.Type, true, element.IsNullable); } else { @@ -357,8 +358,8 @@ private void WriteElement(object o, ElementAccessor element, bool writeAccessor) } else if (element.IsUnbounded) { - TypeDesc arrayTypeDesc = mapping.TypeDesc.CreateArrayTypeDesc(); - var enumerable = (IEnumerable)o; + TypeDesc arrayTypeDesc = mapping.TypeDesc!.CreateArrayTypeDesc(); + var enumerable = (IEnumerable)o!; foreach (var e in enumerable) { element.IsUnbounded = false; @@ -371,7 +372,7 @@ private void WriteElement(object o, ElementAccessor element, bool writeAccessor) if (o != null) { WriteStartElement(name, ns, false); - WriteArrayItems(mapping.ElementsSortedByDerivation, null, null, mapping.TypeDesc, o); + WriteArrayItems(mapping.ElementsSortedByDerivation!, null, null, mapping.TypeDesc, o); WriteEndElement(); } } @@ -381,37 +382,37 @@ private void WriteElement(object o, ElementAccessor element, bool writeAccessor) if (element.Mapping.IsSoap) { Writer.WriteStartElement(name, ns); - WriteEnumMethod((EnumMapping)element.Mapping, o); + WriteEnumMethod((EnumMapping)element.Mapping, o!); WriteEndElement(); } else { - WritePrimitive(WritePrimitiveMethodRequirement.WriteElementString, name, ns, element.Default, o, element.Mapping, false, true, element.IsNullable); + WritePrimitive(WritePrimitiveMethodRequirement.WriteElementString, name, ns!, element.Default, o!, element.Mapping, false, true, element.IsNullable); } } else if (element.Mapping is PrimitiveMapping) { var mapping = element.Mapping as PrimitiveMapping; - if (mapping.TypeDesc == QnameTypeDesc) + if (mapping!.TypeDesc == QnameTypeDesc) { - WriteQualifiedNameElement(name, ns, element.Default, (XmlQualifiedName)o, element.IsNullable, mapping.IsSoap, mapping); + WriteQualifiedNameElement(name, ns!, element.Default, (XmlQualifiedName)o!, element.IsNullable, mapping.IsSoap, mapping); } else { WritePrimitiveMethodRequirement suffixNullable = mapping.IsSoap ? WritePrimitiveMethodRequirement.Encoded : WritePrimitiveMethodRequirement.None; - WritePrimitiveMethodRequirement suffixRaw = mapping.TypeDesc.XmlEncodingNotRequired ? WritePrimitiveMethodRequirement.Raw : WritePrimitiveMethodRequirement.None; + WritePrimitiveMethodRequirement suffixRaw = mapping.TypeDesc!.XmlEncodingNotRequired ? WritePrimitiveMethodRequirement.Raw : WritePrimitiveMethodRequirement.None; WritePrimitive(element.IsNullable ? WritePrimitiveMethodRequirement.WriteNullableStringLiteral | suffixNullable | suffixRaw : WritePrimitiveMethodRequirement.WriteElementString | suffixRaw, - name, ns, element.Default, o, mapping, mapping.IsSoap, true, element.IsNullable); + name, ns!, element.Default, o!, mapping, mapping.IsSoap, true, element.IsNullable); } } else if (element.Mapping is StructMapping) { var mapping = element.Mapping as StructMapping; - if (mapping.IsSoap) + if (mapping!.IsSoap) { - WritePotentiallyReferencingElement(name, ns, o, !writeAccessor ? mapping.TypeDesc.Type : null, !writeAccessor, element.IsNullable); + WritePotentiallyReferencingElement(name, ns, o, !writeAccessor ? mapping.TypeDesc!.Type : null, !writeAccessor, element.IsNullable); } else { @@ -422,7 +423,7 @@ private void WriteElement(object o, ElementAccessor element, bool writeAccessor) { if (element.Mapping is SerializableMapping) { - WriteSerializable((IXmlSerializable)o, name, ns, element.IsNullable, !element.Any); + WriteSerializable((IXmlSerializable)o!, name, ns, element.IsNullable, !element.Any); } else { @@ -433,7 +434,7 @@ private void WriteElement(object o, ElementAccessor element, bool writeAccessor) } else { - throw CreateInvalidAnyTypeException(o); + throw CreateInvalidAnyTypeException(o!); } } } @@ -443,7 +444,7 @@ private void WriteElement(object o, ElementAccessor element, bool writeAccessor) } } - private XmlSerializationWriteCallback CreateXmlSerializationWriteCallback(TypeMapping mapping, string name, string ns, bool isNullable) + private XmlSerializationWriteCallback CreateXmlSerializationWriteCallback(TypeMapping mapping, string name, string? ns, bool isNullable) { if (mapping is StructMapping structMapping) { @@ -465,10 +466,10 @@ private XmlSerializationWriteCallback CreateXmlSerializationWriteCallback(TypeMa } } - private void WriteQualifiedNameElement(string name, string ns, object defaultValue, XmlQualifiedName o, bool nullable, bool isSoap, PrimitiveMapping mapping) + private void WriteQualifiedNameElement(string name, string ns, object? defaultValue, XmlQualifiedName o, bool nullable, bool isSoap, PrimitiveMapping mapping) { - bool hasDefault = defaultValue != null && defaultValue != DBNull.Value && mapping.TypeDesc.HasDefaultSupport; - if (hasDefault && IsDefaultValue(mapping, o, defaultValue, nullable)) + bool hasDefault = defaultValue != null && defaultValue != DBNull.Value && mapping.TypeDesc!.HasDefaultSupport; + if (hasDefault && IsDefaultValue(mapping, o, defaultValue!, nullable)) return; if (isSoap) @@ -495,9 +496,9 @@ private void WriteQualifiedNameElement(string name, string ns, object defaultVal } } - private void WriteStructMethod(StructMapping mapping, string n, string ns, object o, bool isNullable, bool needType) + private void WriteStructMethod(StructMapping mapping, string n, string? ns, object? o, bool isNullable, bool needType) { - if (mapping.IsSoap && mapping.TypeDesc.IsRoot) return; + if (mapping.IsSoap && mapping.TypeDesc!.IsRoot) return; if (!mapping.IsSoap) { @@ -508,7 +509,7 @@ private void WriteStructMethod(StructMapping mapping, string n, string ns, objec } if (!needType - && o.GetType() != mapping.TypeDesc.Type) + && o.GetType() != mapping.TypeDesc!.Type) { if (WriteDerivedTypes(mapping, n, ns, o, isNullable)) { @@ -517,7 +518,7 @@ private void WriteStructMethod(StructMapping mapping, string n, string ns, objec if (mapping.TypeDesc.IsRoot) { - if (WriteEnumAndArrayTypes(mapping, o, n, ns)) + if (WriteEnumAndArrayTypes(mapping, o, n!, ns)) { return; } @@ -530,20 +531,20 @@ private void WriteStructMethod(StructMapping mapping, string n, string ns, objec } } - if (!mapping.TypeDesc.IsAbstract) + if (!mapping.TypeDesc!.IsAbstract) { if (mapping.TypeDesc.Type != null && typeof(XmlSchemaObject).IsAssignableFrom(mapping.TypeDesc.Type)) { EscapeName = false; } - XmlSerializerNamespaces xmlnsSource = null; + XmlSerializerNamespaces? xmlnsSource = null; MemberMapping[] members = TypeScope.GetAllMembers(mapping); int xmlnsMember = FindXmlnsIndex(members); if (xmlnsMember >= 0) { MemberMapping member = members[xmlnsMember]; - xmlnsSource = (XmlSerializerNamespaces)GetMemberValue(o, member.Name); + xmlnsSource = (XmlSerializerNamespaces?)GetMemberValue(o!, member.Name); } if (!mapping.IsSoap) @@ -554,7 +555,7 @@ private void WriteStructMethod(StructMapping mapping, string n, string ns, objec { if (needType) { - WriteXsiType(mapping.TypeName, mapping.Namespace); + WriteXsiType(mapping.TypeName!, mapping.Namespace); } } } @@ -572,22 +573,22 @@ private void WriteStructMethod(StructMapping mapping, string n, string ns, objec if (m.CheckSpecified != SpecifiedAccessor.None) { string specifiedMemberName = m.Name + "Specified"; - isSpecified = (bool)GetMemberValue(o, specifiedMemberName); + isSpecified = (bool)GetMemberValue(o!, specifiedMemberName)!; } if (m.CheckShouldPersist) { string methodInvoke = "ShouldSerialize" + m.Name; - MethodInfo method = o.GetType().GetTypeInfo().GetDeclaredMethod(methodInvoke); - shouldPersist = (bool)method.Invoke(o, Array.Empty()); + MethodInfo method = o!.GetType().GetTypeInfo().GetDeclaredMethod(methodInvoke)!; + shouldPersist = (bool)method.Invoke(o, Array.Empty())!; } if (m.Attribute != null) { if (isSpecified && shouldPersist) { - object memberValue = GetMemberValue(o, m.Name); - WriteMember(memberValue, m.Attribute, m.TypeDesc, o); + object? memberValue = GetMemberValue(o!, m.Name); + WriteMember(memberValue, m.Attribute, m.TypeDesc!, o); } } } @@ -604,17 +605,17 @@ private void WriteStructMethod(StructMapping mapping, string n, string ns, objec if (m.CheckSpecified != SpecifiedAccessor.None) { string specifiedMemberName = m.Name + "Specified"; - isSpecified = (bool)GetMemberValue(o, specifiedMemberName); + isSpecified = (bool)GetMemberValue(o!, specifiedMemberName)!; } if (m.CheckShouldPersist) { string methodInvoke = "ShouldSerialize" + m.Name; - MethodInfo method = o.GetType().GetTypeInfo().GetDeclaredMethod(methodInvoke); - shouldPersist = (bool)method.Invoke(o, Array.Empty()); + MethodInfo method = o!.GetType().GetTypeInfo().GetDeclaredMethod(methodInvoke)!; + shouldPersist = (bool)method.Invoke(o, Array.Empty())!; } - bool checkShouldPersist = m.CheckShouldPersist && (m.Elements.Length > 0 || m.Text != null); + bool checkShouldPersist = m.CheckShouldPersist && (m.Elements!.Length > 0 || m.Text != null); if (!checkShouldPersist) { @@ -623,14 +624,14 @@ private void WriteStructMethod(StructMapping mapping, string n, string ns, objec if (isSpecified && shouldPersist) { - object choiceSource = null; + object? choiceSource = null; if (m.ChoiceIdentifier != null) { - choiceSource = GetMemberValue(o, m.ChoiceIdentifier.MemberName); + choiceSource = GetMemberValue(o!, m.ChoiceIdentifier.MemberName!); } - object memberValue = GetMemberValue(o, m.Name); - WriteMember(memberValue, choiceSource, m.ElementsSortedByDerivation, m.Text, m.ChoiceIdentifier, m.TypeDesc, true); + object? memberValue = GetMemberValue(o!, m.Name); + WriteMember(memberValue, choiceSource, m.ElementsSortedByDerivation!, m.Text, m.ChoiceIdentifier, m.TypeDesc!, true); } } @@ -641,24 +642,24 @@ private void WriteStructMethod(StructMapping mapping, string n, string ns, objec } } - private object GetMemberValue(object o, string memberName) + private object? GetMemberValue(object o, string memberName) { MemberInfo memberInfo = ReflectionXmlSerializationHelper.GetMember(o.GetType(), memberName); - object memberValue = GetMemberValue(o, memberInfo); + object? memberValue = GetMemberValue(o, memberInfo); return memberValue; } - private bool WriteEnumAndArrayTypes(StructMapping structMapping, object o, string n, string ns) + private bool WriteEnumAndArrayTypes(StructMapping structMapping, object o, string n, string? ns) { if (o is Enum) { Writer.WriteStartElement(n, ns); - EnumMapping enumMapping = null; + EnumMapping? enumMapping = null; Type enumType = o.GetType(); - foreach (var m in _mapping.Scope.TypeMappings) + foreach (var m in _mapping.Scope!.TypeMappings) { - if (m is EnumMapping em && em.TypeDesc.Type == enumType) + if (m is EnumMapping em && em.TypeDesc!.Type == enumType) { enumMapping = em; break; @@ -668,7 +669,7 @@ private bool WriteEnumAndArrayTypes(StructMapping structMapping, object o, strin if (enumMapping == null) throw new InvalidOperationException(SR.XmlInternalError); - WriteXsiType(enumMapping.TypeName, ns); + WriteXsiType(enumMapping.TypeName!, ns); Writer.WriteString(WriteEnumMethod(enumMapping, o)); Writer.WriteEndElement(); return true; @@ -677,11 +678,11 @@ private bool WriteEnumAndArrayTypes(StructMapping structMapping, object o, strin if (o is Array) { Writer.WriteStartElement(n, ns); - ArrayMapping arrayMapping = null; + ArrayMapping? arrayMapping = null; Type arrayType = o.GetType(); - foreach (var m in _mapping.Scope.TypeMappings) + foreach (var m in _mapping.Scope!.TypeMappings) { - if (m is ArrayMapping am && am.TypeDesc.Type == arrayType) + if (m is ArrayMapping am && am.TypeDesc!.Type == arrayType) { arrayMapping = am; break; @@ -691,8 +692,8 @@ private bool WriteEnumAndArrayTypes(StructMapping structMapping, object o, strin if (arrayMapping == null) throw new InvalidOperationException(SR.XmlInternalError); - WriteXsiType(arrayMapping.TypeName, ns); - WriteMember(o, null, arrayMapping.ElementsSortedByDerivation, null, null, arrayMapping.TypeDesc, true); + WriteXsiType(arrayMapping.TypeName!, ns); + WriteMember(o, null, arrayMapping.ElementsSortedByDerivation!, null, null, arrayMapping.TypeDesc!, true); Writer.WriteEndElement(); return true; @@ -701,12 +702,12 @@ private bool WriteEnumAndArrayTypes(StructMapping structMapping, object o, strin return false; } - private string WriteEnumMethod(EnumMapping mapping, object v) + private string? WriteEnumMethod(EnumMapping mapping, object v) { - string returnString = null; + string? returnString = null; if (mapping != null) { - ConstantMapping[] constants = mapping.Constants; + ConstantMapping[] constants = mapping.Constants!; if (constants.Length > 0) { bool foundValue = false; @@ -739,7 +740,7 @@ private string WriteEnumMethod(EnumMapping mapping, object v) } else { - throw CreateInvalidEnumValueException(v, mapping.TypeDesc.FullName); + throw CreateInvalidEnumValueException(v, mapping.TypeDesc!.FullName); } } } @@ -749,9 +750,9 @@ private string WriteEnumMethod(EnumMapping mapping, object v) returnString = v.ToString(); } - if (mapping.IsSoap) + if (mapping!.IsSoap) { - WriteXsiType(mapping.TypeName, mapping.Namespace); + WriteXsiType(mapping.TypeName!, mapping.Namespace); Writer.WriteString(returnString); return null; } @@ -761,7 +762,7 @@ private string WriteEnumMethod(EnumMapping mapping, object v) } } - private object GetMemberValue(object o, MemberInfo memberInfo) + private object? GetMemberValue(object? o, MemberInfo memberInfo) { if (memberInfo is PropertyInfo memberProperty) { @@ -775,13 +776,13 @@ private object GetMemberValue(object o, MemberInfo memberInfo) throw new InvalidOperationException(SR.XmlInternalError); } - private void WriteMember(object memberValue, AttributeAccessor attribute, TypeDesc memberTypeDesc, object container) + private void WriteMember(object? memberValue, AttributeAccessor attribute, TypeDesc memberTypeDesc, object? container) { if (memberTypeDesc.IsAbstract) return; if (memberTypeDesc.IsArrayLike) { var sb = new StringBuilder(); - TypeDesc arrayElementTypeDesc = memberTypeDesc.ArrayElementTypeDesc; + TypeDesc? arrayElementTypeDesc = memberTypeDesc.ArrayElementTypeDesc; bool canOptimizeWriteListSequence = CanOptimizeWriteListSequence(arrayElementTypeDesc); if (attribute.IsList) { @@ -804,14 +805,14 @@ private void WriteMember(object memberValue, AttributeAccessor attribute, TypeDe if (attribute.IsList) { - string stringValue; + string? stringValue; if (attribute.Mapping is EnumMapping enumMapping) { stringValue = WriteEnumMethod(enumMapping, ai); } else { - if (!WritePrimitiveValue(arrayElementTypeDesc, ai, true, out stringValue)) + if (!WritePrimitiveValue(arrayElementTypeDesc!, ai, true, out stringValue)) { Debug.Assert(ai is byte[]); } @@ -863,7 +864,7 @@ private void WriteMember(object memberValue, AttributeAccessor attribute, TypeDe { if (sb.Length != 0) { - string ns = attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : string.Empty; + string? ns = attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : string.Empty; WriteAttribute(attribute.Name, ns, sb.ToString()); } } @@ -873,11 +874,11 @@ private void WriteMember(object memberValue, AttributeAccessor attribute, TypeDe } else { - WriteAttribute(memberValue, attribute, container); + WriteAttribute(memberValue!, attribute, container); } } - private bool CanOptimizeWriteListSequence(TypeDesc listElementTypeDesc) + private bool CanOptimizeWriteListSequence(TypeDesc? listElementTypeDesc) { // check to see if we can write values of the attribute sequentially // currently we have only one data type (XmlQualifiedName) that we can not write "inline", @@ -885,12 +886,12 @@ private bool CanOptimizeWriteListSequence(TypeDesc listElementTypeDesc) return (listElementTypeDesc != null && listElementTypeDesc != QnameTypeDesc); } - private void WriteAttribute(object memberValue, AttributeAccessor attribute, object container) + private void WriteAttribute(object memberValue, AttributeAccessor attribute, object? container) { // TODO: this block is never hit by our tests. if (attribute.Mapping is SpecialMapping special) { - if (special.TypeDesc.Kind == TypeKind.Attribute || special.TypeDesc.CanBeAttributeValue) + if (special.TypeDesc!.Kind == TypeKind.Attribute || special.TypeDesc.CanBeAttributeValue) { WriteXmlAttribute((XmlNode)memberValue, container); } @@ -901,8 +902,8 @@ private void WriteAttribute(object memberValue, AttributeAccessor attribute, obj } else { - string ns = attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : string.Empty; - WritePrimitive(WritePrimitiveMethodRequirement.WriteAttribute, attribute.Name, ns, attribute.Default, memberValue, attribute.Mapping, false, false, false); + string? ns = attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : string.Empty; + WritePrimitive(WritePrimitiveMethodRequirement.WriteAttribute, attribute.Name, ns, attribute.Default, memberValue, attribute.Mapping!, false, false, false); } } @@ -919,12 +920,12 @@ private int FindXmlnsIndex(MemberMapping[] members) return -1; } - private bool WriteDerivedTypes(StructMapping mapping, string n, string ns, object o, bool isNullable) + private bool WriteDerivedTypes(StructMapping mapping, string n, string? ns, object o, bool isNullable) { Type t = o.GetType(); - for (StructMapping derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) + for (StructMapping? derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) { - if (t == derived.TypeDesc.Type) + if (t == derived.TypeDesc!.Type) { WriteStructMethod(derived, n, ns, o, isNullable, needType: true); return true; @@ -939,17 +940,17 @@ private bool WriteDerivedTypes(StructMapping mapping, string n, string ns, objec return false; } - private void WritePrimitive(WritePrimitiveMethodRequirement method, string name, string ns, object defaultValue, object o, TypeMapping mapping, bool writeXsiType, bool isElement, bool isNullable) + private void WritePrimitive(WritePrimitiveMethodRequirement method, string name, string? ns, object? defaultValue, object o, TypeMapping mapping, bool writeXsiType, bool isElement, bool isNullable) { - TypeDesc typeDesc = mapping.TypeDesc; - bool hasDefault = defaultValue != null && defaultValue != DBNull.Value && mapping.TypeDesc.HasDefaultSupport; + TypeDesc typeDesc = mapping.TypeDesc!; + bool hasDefault = defaultValue != null && defaultValue != DBNull.Value && mapping.TypeDesc!.HasDefaultSupport; if (hasDefault) { if (mapping is EnumMapping) { if (((EnumMapping)mapping).IsFlags) { - IEnumerable defaultEnumFlagValues = defaultValue.ToString().Split((char[])null, StringSplitOptions.RemoveEmptyEntries); + IEnumerable defaultEnumFlagValues = defaultValue!.ToString()!.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries); string defaultEnumFlagString = string.Join(", ", defaultEnumFlagValues); if (o.ToString() == defaultEnumFlagString) @@ -957,26 +958,26 @@ private void WritePrimitive(WritePrimitiveMethodRequirement method, string name, } else { - if (o.ToString() == defaultValue.ToString()) + if (o.ToString() == defaultValue!.ToString()) return; } } else { - if (IsDefaultValue(mapping, o, defaultValue, isNullable)) + if (IsDefaultValue(mapping, o, defaultValue!, isNullable)) { return; } } } - XmlQualifiedName xmlQualifiedName = null; + XmlQualifiedName? xmlQualifiedName = null; if (writeXsiType) { xmlQualifiedName = new XmlQualifiedName(mapping.TypeName, mapping.Namespace); } - string stringValue = null; + string? stringValue = null; bool hasValidStringValue = false; if (mapping is EnumMapping enumMapping) { @@ -1048,7 +1049,7 @@ private void WritePrimitive(WritePrimitiveMethodRequirement method, string name, } else if (hasRequirement(method, WritePrimitiveMethodRequirement.WriteAttribute)) { - WriteAttribute(name, ns, a); + WriteAttribute(name, ns!, a); } else { @@ -1079,18 +1080,18 @@ private bool IsDefaultValue(TypeMapping mapping, object o, object value, bool is } } - private bool WritePrimitiveValue(TypeDesc typeDesc, object o, bool isElement, out string stringValue) + private bool WritePrimitiveValue(TypeDesc typeDesc, object? o, bool isElement, out string? stringValue) { if (typeDesc == StringTypeDesc || typeDesc.FormatterName == "String") { - stringValue = (string)o; + stringValue = (string?)o; return true; } else { if (!typeDesc.HasCustomFormatter) { - stringValue = ConvertPrimitiveToString(o, typeDesc); + stringValue = ConvertPrimitiveToString(o!, typeDesc); return true; } else if (o is byte[] && typeDesc.FormatterName == "ByteArrayHex") @@ -1122,7 +1123,7 @@ private bool WritePrimitiveValue(TypeDesc typeDesc, object o, bool isElement, ou } else if (typeDesc == QnameTypeDesc) { - stringValue = FromXmlQualifiedName((XmlQualifiedName)o); + stringValue = FromXmlQualifiedName((XmlQualifiedName?)o); return true; } else if (o is string) @@ -1187,7 +1188,7 @@ private string ConvertPrimitiveToString(object o, TypeDesc typeDesc) "Guid" => XmlConvert.ToString((Guid)o), "Char" => XmlConvert.ToString((char)o), "TimeSpan" => XmlConvert.ToString((TimeSpan)o), - _ => o.ToString(), + _ => o.ToString()!, }; return stringValue; } @@ -1195,7 +1196,7 @@ private string ConvertPrimitiveToString(object o, TypeDesc typeDesc) private void GenerateMembersElement(object o, XmlMembersMapping xmlMembersMapping) { ElementAccessor element = xmlMembersMapping.Accessor; - MembersMapping mapping = (MembersMapping)element.Mapping; + MembersMapping mapping = (MembersMapping)element.Mapping!; bool hasWrapperElement = mapping.HasWrapperElement; bool writeAccessors = mapping.WriteAccessors; bool isRpc = xmlMembersMapping.IsSoap && writeAccessors; @@ -1214,10 +1215,10 @@ private void GenerateMembersElement(object o, XmlMembersMapping xmlMembersMappin { WriteStartElement(element.Name, (element.Form == XmlSchemaForm.Qualified ? element.Namespace : string.Empty), mapping.IsSoap); - int xmlnsMember = FindXmlnsIndex(mapping.Members); + int xmlnsMember = FindXmlnsIndex(mapping.Members!); if (xmlnsMember >= 0) { - MemberMapping member = mapping.Members[xmlnsMember]; + MemberMapping member = mapping.Members![xmlnsMember]; var source = (XmlSerializerNamespaces)p[xmlnsMember]; if (pLength > xmlnsMember) @@ -1226,7 +1227,7 @@ private void GenerateMembersElement(object o, XmlMembersMapping xmlMembersMappin } } - for (int i = 0; i < mapping.Members.Length; i++) + for (int i = 0; i < mapping.Members!.Length; i++) { MemberMapping member = mapping.Members[i]; if (member.Attribute != null && !member.Ignore) @@ -1248,13 +1249,13 @@ private void GenerateMembersElement(object o, XmlMembersMapping xmlMembersMappin if (pLength > i && (specifiedSource == null || specifiedSource.Value)) { - WriteMember(source, member.Attribute, member.TypeDesc, null); + WriteMember(source, member.Attribute, member.TypeDesc!, null); } } } } - for (int i = 0; i < mapping.Members.Length; i++) + for (int i = 0; i < mapping.Members!.Length; i++) { MemberMapping member = mapping.Members[i]; if (member.Xmlns != null) @@ -1283,7 +1284,7 @@ private void GenerateMembersElement(object o, XmlMembersMapping xmlMembersMappin { object source = p[i]; - object enumSource = null; + object? enumSource = null; if (member.ChoiceIdentifier != null) { for (int j = 0; j < mapping.Members.Length; j++) @@ -1296,13 +1297,13 @@ private void GenerateMembersElement(object o, XmlMembersMapping xmlMembersMappin } } - if (isRpc && member.IsReturnValue && member.Elements.Length > 0) + if (isRpc && member.IsReturnValue && member.Elements!.Length > 0) { WriteRpcResult(member.Elements[0].Name, string.Empty); } // override writeAccessors choice when we've written a wrapper element - WriteMember(source, enumSource, member.ElementsSortedByDerivation, member.Text, member.ChoiceIdentifier, member.TypeDesc, writeAccessors || hasWrapperElement); + WriteMember(source, enumSource, member.ElementsSortedByDerivation!, member.Text, member.ChoiceIdentifier, member.TypeDesc!, writeAccessors || hasWrapperElement); } } } @@ -1353,7 +1354,7 @@ public static MemberInfo GetMember(Type declaringType, string memberName) if (memberInfos == null || memberInfos.Length == 0) { bool foundMatchedMember = false; - Type currentType = declaringType.BaseType; + Type? currentType = declaringType.BaseType; while (currentType != null) { memberInfos = currentType.GetMember(memberName); @@ -1371,10 +1372,10 @@ public static MemberInfo GetMember(Type declaringType, string memberName) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, $"Could not find member named {memberName} of type {declaringType}")); } - declaringType = currentType; + declaringType = currentType!; } - MemberInfo memberInfo = memberInfos[0]; + MemberInfo memberInfo = memberInfos![0]; if (memberInfos.Length != 1) { foreach (MemberInfo mi in memberInfos) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaImporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaImporter.cs index 2c14c351a3f2bc..c3ef906d46f5fa 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaImporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaImporter.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; @@ -18,13 +19,13 @@ namespace System.Xml.Serialization public abstract class SchemaImporter { private XmlSchemas _schemas; - private StructMapping _root; + private StructMapping? _root; private readonly CodeGenerationOptions _options; - private TypeScope _scope; + private TypeScope? _scope; private ImportContext _context; private bool _rootImported; - private NameTable _typesInUse; - private NameTable _groupsInUse; + private NameTable? _typesInUse; + private NameTable? _groupsInUse; internal SchemaImporter(XmlSchemas schemas, CodeGenerationOptions options, ImportContext context) { @@ -114,7 +115,7 @@ internal CodeGenerationOptions Options get { return _options; } } - internal void MakeDerived(StructMapping structMapping, Type baseType, bool baseTypeCanBeIndirect) + internal void MakeDerived(StructMapping structMapping, Type? baseType, bool baseTypeCanBeIndirect) { structMapping.ReferencedByTopLevelElement = true; TypeDesc baseTypeDesc; @@ -123,7 +124,7 @@ internal void MakeDerived(StructMapping structMapping, Type baseType, bool baseT baseTypeDesc = Scope.GetTypeDesc(baseType); if (baseTypeDesc != null) { - TypeDesc typeDescToChange = structMapping.TypeDesc; + TypeDesc typeDescToChange = structMapping.TypeDesc!; if (baseTypeCanBeIndirect) { // if baseTypeCanBeIndirect is true, we apply the supplied baseType to the top of the @@ -132,7 +133,7 @@ internal void MakeDerived(StructMapping structMapping, Type baseType, bool baseT typeDescToChange = typeDescToChange.BaseTypeDesc; } if (typeDescToChange.BaseTypeDesc != null && typeDescToChange.BaseTypeDesc != baseTypeDesc) - throw new InvalidOperationException(SR.Format(SR.XmlInvalidBaseType, structMapping.TypeDesc.FullName, baseType.FullName, typeDescToChange.BaseTypeDesc.FullName)); + throw new InvalidOperationException(SR.Format(SR.XmlInvalidBaseType, structMapping.TypeDesc!.FullName, baseType.FullName, typeDescToChange.BaseTypeDesc.FullName)); typeDescToChange.BaseTypeDesc = baseTypeDesc; } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaObjectWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaObjectWriter.cs index 7ede7de2b421f6..f4b469f61e4f99 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaObjectWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaObjectWriter.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; @@ -11,14 +12,14 @@ namespace System.Xml.Serialization using System.Xml.Serialization; using System.Collections; using System.Collections.Specialized; - + using System.Diagnostics.CodeAnalysis; internal class XmlAttributeComparer : IComparer { - public int Compare(object o1, object o2) + public int Compare(object? o1, object? o2) { - XmlAttribute a1 = (XmlAttribute)o1; - XmlAttribute a2 = (XmlAttribute)o2; + XmlAttribute a1 = (XmlAttribute)o1!; + XmlAttribute a2 = (XmlAttribute)o2!; int ns = string.Compare(a1.NamespaceURI, a2.NamespaceURI, StringComparison.Ordinal); if (ns == 0) { @@ -30,20 +31,20 @@ public int Compare(object o1, object o2) internal class XmlFacetComparer : IComparer { - public int Compare(object o1, object o2) + public int Compare(object? o1, object? o2) { - XmlSchemaFacet f1 = (XmlSchemaFacet)o1; - XmlSchemaFacet f2 = (XmlSchemaFacet)o2; + XmlSchemaFacet f1 = (XmlSchemaFacet)o1!; + XmlSchemaFacet f2 = (XmlSchemaFacet)o2!; return string.Compare(f1.GetType().Name + ":" + f1.Value, f2.GetType().Name + ":" + f2.Value, StringComparison.Ordinal); } } internal class QNameComparer : IComparer { - public int Compare(object o1, object o2) + public int Compare(object? o1, object? o2) { - XmlQualifiedName qn1 = (XmlQualifiedName)o1; - XmlQualifiedName qn2 = (XmlQualifiedName)o2; + XmlQualifiedName qn1 = (XmlQualifiedName)o1!; + XmlQualifiedName qn2 = (XmlQualifiedName)o2!; int ns = string.Compare(qn1.Namespace, qn2.Namespace, StringComparison.Ordinal); if (ns == 0) { @@ -56,12 +57,12 @@ public int Compare(object o1, object o2) internal class XmlSchemaObjectComparer : IComparer { private readonly QNameComparer _comparer = new QNameComparer(); - public int Compare(object o1, object o2) + public int Compare(object? o1, object? o2) { - return _comparer.Compare(NameOf((XmlSchemaObject)o1), NameOf((XmlSchemaObject)o2)); + return _comparer.Compare(NameOf((XmlSchemaObject?)o1), NameOf((XmlSchemaObject?)o2)); } - internal static XmlQualifiedName NameOf(XmlSchemaObject o) + internal static XmlQualifiedName NameOf(XmlSchemaObject? o) { if (o is XmlSchemaAttribute) { @@ -136,10 +137,10 @@ internal static XmlQualifiedName NameOf(XmlSchemaObjectCollection items) list.Add(NameOf(items[i])); } list.Sort(new QNameComparer()); - return (XmlQualifiedName)list[0]; + return (XmlQualifiedName)list[0]!; } - internal static string Namespace(XmlSchemaObject o) + internal static string? Namespace(XmlSchemaObject? o) { while (o != null && !(o is XmlSchema)) { @@ -161,7 +162,7 @@ private void WriteIndent() _w.Append(' '); } } - protected void WriteAttribute(string localName, string ns, string value) + protected void WriteAttribute(string localName, string ns, string? value) { if (value == null || value.Length == 0) return; @@ -211,7 +212,7 @@ private void WriteAttribute(XmlAttribute a) } } - private void WriteAttributes(XmlAttribute[] a, XmlSchemaObject o) + private void WriteAttributes(XmlAttribute[]? a, XmlSchemaObject o) { if (a == null) return; ArrayList attrs = new ArrayList(); @@ -222,12 +223,13 @@ private void WriteAttributes(XmlAttribute[] a, XmlSchemaObject o) attrs.Sort(new XmlAttributeComparer()); for (int i = 0; i < attrs.Count; i++) { - XmlAttribute attribute = (XmlAttribute)attrs[i]; + XmlAttribute attribute = (XmlAttribute)attrs[i]!; WriteAttribute(attribute); } } - internal static string ToString(NamespaceList list) + [return: NotNullIfNotNull("list")] + internal static string? ToString(NamespaceList? list) { if (list == null) return null; @@ -273,14 +275,14 @@ internal static string ToString(NamespaceList list) } } - internal string WriteXmlSchemaObject(XmlSchemaObject o) + internal string WriteXmlSchemaObject(XmlSchemaObject? o) { if (o == null) return string.Empty; - Write3_XmlSchemaObject((XmlSchemaObject)o); + Write3_XmlSchemaObject((XmlSchemaObject?)o); return GetString(); } - private void WriteSortedItems(XmlSchemaObjectCollection items) + private void WriteSortedItems(XmlSchemaObjectCollection? items) { if (items == null) return; @@ -292,18 +294,18 @@ private void WriteSortedItems(XmlSchemaObjectCollection items) list.Sort(new XmlSchemaObjectComparer()); for (int i = 0; i < list.Count; i++) { - Write3_XmlSchemaObject((XmlSchemaObject)list[i]); + Write3_XmlSchemaObject((XmlSchemaObject?)list[i]); } } - private void Write1_XmlSchemaAttribute(XmlSchemaAttribute o) + private void Write1_XmlSchemaAttribute(XmlSchemaAttribute? o) { - if ((object)o == null) return; + if ((object?)o == null) return; WriteStartElement("attribute"); - WriteAttribute(@"id", @"", ((string)o.@Id)); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); - WriteAttribute(@"default", @"", ((string)o.@DefaultValue)); - WriteAttribute(@"fixed", @"", ((string)o.@FixedValue)); + WriteAttribute(@"id", @"", ((string?)o.@Id)); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + WriteAttribute(@"default", @"", ((string?)o.@DefaultValue)); + WriteAttribute(@"fixed", @"", ((string?)o.@FixedValue)); if (o.Parent != null && !(o.Parent is XmlSchema)) { if (o.QualifiedName != null && !o.QualifiedName.IsEmpty && o.QualifiedName.Namespace != null && o.QualifiedName.Namespace.Length != 0) @@ -315,7 +317,7 @@ private void Write1_XmlSchemaAttribute(XmlSchemaAttribute o) WriteAttribute(@"form", @"", "unqualified"); } } - WriteAttribute(@"name", @"", ((string)o.@Name)); + WriteAttribute(@"name", @"", ((string?)o.@Name)); if (!o.RefName.IsEmpty) { @@ -327,14 +329,14 @@ private void Write1_XmlSchemaAttribute(XmlSchemaAttribute o) } XmlSchemaUse use = o.Use == XmlSchemaUse.None ? XmlSchemaUse.Optional : o.Use; WriteAttribute(@"use", @"", Write30_XmlSchemaUse(use)); - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); - Write9_XmlSchemaSimpleType((XmlSchemaSimpleType)o.@SchemaType); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); + Write9_XmlSchemaSimpleType((XmlSchemaSimpleType?)o.@SchemaType); WriteEndElement(); } - private void Write3_XmlSchemaObject(XmlSchemaObject o) + private void Write3_XmlSchemaObject(XmlSchemaObject? o) { - if ((object)o == null) return; + if ((object?)o == null) return; System.Type t = o.GetType(); if (t == typeof(XmlSchemaComplexType)) @@ -489,13 +491,13 @@ private void Write3_XmlSchemaObject(XmlSchemaObject o) } } - private void Write5_XmlSchemaAnnotation(XmlSchemaAnnotation o) + private void Write5_XmlSchemaAnnotation(XmlSchemaAnnotation? o) { - if ((object)o == null) return; + if ((object?)o == null) return; WriteStartElement("annotation"); - WriteAttribute(@"id", @"", ((string)o.@Id)); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); + WriteAttribute(@"id", @"", ((string?)o.@Id)); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); System.Xml.Schema.XmlSchemaObjectCollection a = (System.Xml.Schema.XmlSchemaObjectCollection)o.@Items; if (a != null) { @@ -520,9 +522,9 @@ private void Write6_XmlSchemaDocumentation(XmlSchemaDocumentation o) if ((object)o == null) return; WriteStartElement("documentation"); - WriteAttribute(@"source", @"", ((string)o.@Source)); - WriteAttribute(@"lang", @"http://www.w3.org/XML/1998/namespace", ((string)o.@Language)); - XmlNode[] a = (XmlNode[])o.@Markup; + WriteAttribute(@"source", @"", ((string?)o.@Source)); + WriteAttribute(@"lang", @"http://www.w3.org/XML/1998/namespace", ((string?)o.@Language)); + XmlNode[]? a = (XmlNode[]?)o.@Markup; if (a != null) { for (int ia = 0; ia < a.Length; ia++) @@ -535,13 +537,13 @@ private void Write6_XmlSchemaDocumentation(XmlSchemaDocumentation o) WriteEndElement(); } - private void Write7_XmlSchemaAppInfo(XmlSchemaAppInfo o) + private void Write7_XmlSchemaAppInfo(XmlSchemaAppInfo? o) { - if ((object)o == null) return; + if ((object?)o == null) return; WriteStartElement("appinfo"); WriteAttribute("source", "", o.Source); - XmlNode[] a = (XmlNode[])o.@Markup; + XmlNode[]? a = (XmlNode[]?)o.@Markup; if (a != null) { for (int ia = 0; ia < a.Length; ia++) @@ -554,16 +556,16 @@ private void Write7_XmlSchemaAppInfo(XmlSchemaAppInfo o) WriteEndElement(); } - private void Write9_XmlSchemaSimpleType(XmlSchemaSimpleType o) + private void Write9_XmlSchemaSimpleType(XmlSchemaSimpleType? o) { - if ((object)o == null) return; + if ((object?)o == null) return; WriteStartElement("simpleType"); - WriteAttribute(@"id", @"", ((string)o.@Id)); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); - WriteAttribute(@"name", @"", ((string)o.@Name)); + WriteAttribute(@"id", @"", ((string?)o.@Id)); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + WriteAttribute(@"name", @"", ((string?)o.@Name)); WriteAttribute(@"final", @"", Write11_XmlSchemaDerivationMethod(o.FinalResolved)); - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); if (o.@Content is XmlSchemaSimpleTypeUnion) { Write12_XmlSchemaSimpleTypeUnion((XmlSchemaSimpleTypeUnion)o.@Content); @@ -584,13 +586,13 @@ private string Write11_XmlSchemaDerivationMethod(XmlSchemaDerivationMethod v) return v.ToString(); } - private void Write12_XmlSchemaSimpleTypeUnion(XmlSchemaSimpleTypeUnion o) + private void Write12_XmlSchemaSimpleTypeUnion(XmlSchemaSimpleTypeUnion? o) { - if ((object)o == null) return; + if ((object?)o == null) return; WriteStartElement("union"); - WriteAttribute(@"id", @"", ((string)o.@Id)); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); + WriteAttribute(@"id", @"", ((string?)o.@Id)); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); if (o.MemberTypes != null) { @@ -606,12 +608,12 @@ private void Write12_XmlSchemaSimpleTypeUnion(XmlSchemaSimpleTypeUnion o) for (int i = 0; i < list.Count; i++) { - XmlQualifiedName q = (XmlQualifiedName)list[i]; + XmlQualifiedName q = (XmlQualifiedName)list[i]!; _w.Append(q.ToString()); _w.Append(','); } } - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); WriteSortedItems(o.@BaseTypes); WriteEndElement(); } @@ -621,34 +623,34 @@ private void Write14_XmlSchemaSimpleTypeList(XmlSchemaSimpleTypeList o) if ((object)o == null) return; WriteStartElement("list"); - WriteAttribute(@"id", @"", ((string)o.@Id)); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); + WriteAttribute(@"id", @"", ((string?)o.@Id)); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); if (!o.@ItemTypeName.IsEmpty) { WriteAttribute(@"itemType", @"", o.@ItemTypeName); } - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); - Write9_XmlSchemaSimpleType((XmlSchemaSimpleType)o.@ItemType); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); + Write9_XmlSchemaSimpleType((XmlSchemaSimpleType?)o.@ItemType); WriteEndElement(); } - private void Write15_XmlSchemaSimpleTypeRestriction(XmlSchemaSimpleTypeRestriction o) + private void Write15_XmlSchemaSimpleTypeRestriction(XmlSchemaSimpleTypeRestriction? o) { - if ((object)o == null) return; + if ((object?)o == null) return; WriteStartElement("restriction"); - WriteAttribute(@"id", @"", ((string)o.@Id)); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); + WriteAttribute(@"id", @"", ((string?)o.@Id)); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); if (!o.@BaseTypeName.IsEmpty) { WriteAttribute(@"base", @"", o.@BaseTypeName); } - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); - Write9_XmlSchemaSimpleType((XmlSchemaSimpleType)o.@BaseType); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); + Write9_XmlSchemaSimpleType((XmlSchemaSimpleType?)o.@BaseType); WriteFacets(o.Facets); WriteEndElement(); } - private void WriteFacets(XmlSchemaObjectCollection facets) + private void WriteFacets(XmlSchemaObjectCollection? facets) { if (facets == null) return; @@ -660,7 +662,7 @@ private void WriteFacets(XmlSchemaObjectCollection facets) a.Sort(new XmlFacetComparer()); for (int ia = 0; ia < a.Count; ia++) { - XmlSchemaObject ai = (XmlSchemaObject)a[ia]; + XmlSchemaObject? ai = (XmlSchemaObject?)a[ia]; if (ai is XmlSchemaMinExclusiveFacet) { Write_XmlSchemaFacet("minExclusive", (XmlSchemaFacet)ai); @@ -712,9 +714,9 @@ private void WriteFacets(XmlSchemaObjectCollection facets) } } - private void Write_XmlSchemaFacet(string name, XmlSchemaFacet o) + private void Write_XmlSchemaFacet(string name, XmlSchemaFacet? o) { - if ((object)o == null) return; + if ((object?)o == null) return; WriteStartElement(name); WriteAttribute("id", "", o.Id); @@ -723,14 +725,14 @@ private void Write_XmlSchemaFacet(string name, XmlSchemaFacet o) { WriteAttribute(@"fixed", @"", XmlConvert.ToString(o.IsFixed)); } - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); WriteEndElement(); } - private string Write30_XmlSchemaUse(XmlSchemaUse v) + private string? Write30_XmlSchemaUse(XmlSchemaUse v) { - string s = null; + string? s = null; switch (v) { case XmlSchemaUse.@Optional: s = @"optional"; break; @@ -741,53 +743,53 @@ private string Write30_XmlSchemaUse(XmlSchemaUse v) return s; } - private void Write31_XmlSchemaAttributeGroup(XmlSchemaAttributeGroup o) + private void Write31_XmlSchemaAttributeGroup(XmlSchemaAttributeGroup? o) { - if ((object)o == null) return; + if ((object?)o == null) return; WriteStartElement("attributeGroup"); - WriteAttribute(@"id", @"", ((string)o.@Id)); - WriteAttribute(@"name", @"", ((string)o.@Name)); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); + WriteAttribute(@"id", @"", ((string?)o.@Id)); + WriteAttribute(@"name", @"", ((string?)o.@Name)); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); WriteSortedItems(o.Attributes); - Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute)o.@AnyAttribute); + Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute?)o.@AnyAttribute); WriteEndElement(); } - private void Write32_XmlSchemaAttributeGroupRef(XmlSchemaAttributeGroupRef o) + private void Write32_XmlSchemaAttributeGroupRef(XmlSchemaAttributeGroupRef? o) { - if ((object)o == null) return; + if ((object?)o == null) return; WriteStartElement("attributeGroup"); - WriteAttribute(@"id", @"", ((string)o.@Id)); + WriteAttribute(@"id", @"", ((string?)o.@Id)); if (!o.RefName.IsEmpty) { WriteAttribute("ref", "", o.RefName); } - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); WriteEndElement(); } - private void Write33_XmlSchemaAnyAttribute(XmlSchemaAnyAttribute o) + private void Write33_XmlSchemaAnyAttribute(XmlSchemaAnyAttribute? o) { - if ((object)o == null) return; + if ((object?)o == null) return; WriteStartElement("anyAttribute"); - WriteAttribute(@"id", @"", ((string)o.@Id)); + WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttribute("namespace", "", ToString(o.NamespaceList)); XmlSchemaContentProcessing process = o.@ProcessContents == XmlSchemaContentProcessing.@None ? XmlSchemaContentProcessing.Strict : o.@ProcessContents; WriteAttribute(@"processContents", @"", Write34_XmlSchemaContentProcessing(process)); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); WriteEndElement(); } - private string Write34_XmlSchemaContentProcessing(XmlSchemaContentProcessing v) + private string? Write34_XmlSchemaContentProcessing(XmlSchemaContentProcessing v) { - string s = null; + string? s = null; switch (v) { case XmlSchemaContentProcessing.@Skip: s = @"skip"; break; @@ -803,8 +805,8 @@ private void Write35_XmlSchemaComplexType(XmlSchemaComplexType o) if ((object)o == null) return; WriteStartElement("complexType"); - WriteAttribute(@"id", @"", ((string)o.@Id)); - WriteAttribute(@"name", @"", ((string)o.@Name)); + WriteAttribute(@"id", @"", ((string?)o.@Id)); + WriteAttribute(@"name", @"", ((string?)o.@Name)); WriteAttribute(@"final", @"", Write11_XmlSchemaDerivationMethod(o.FinalResolved)); if (((bool)o.@IsAbstract) != false) { @@ -815,8 +817,8 @@ private void Write35_XmlSchemaComplexType(XmlSchemaComplexType o) { WriteAttribute(@"mixed", @"", XmlConvert.ToString((bool)((bool)o.@IsMixed))); } - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); if (o.@ContentModel is XmlSchemaComplexContent) { Write41_XmlSchemaComplexContent((XmlSchemaComplexContent)o.@ContentModel); @@ -842,18 +844,18 @@ private void Write35_XmlSchemaComplexType(XmlSchemaComplexType o) Write43_XmlSchemaAll((XmlSchemaAll)o.@Particle); } WriteSortedItems(o.Attributes); - Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute)o.@AnyAttribute); + Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute?)o.@AnyAttribute); WriteEndElement(); } - private void Write36_XmlSchemaSimpleContent(XmlSchemaSimpleContent o) + private void Write36_XmlSchemaSimpleContent(XmlSchemaSimpleContent? o) { - if ((object)o == null) return; + if ((object?)o == null) return; WriteStartElement("simpleContent"); - WriteAttribute(@"id", @"", ((string)o.@Id)); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); + WriteAttribute(@"id", @"", ((string?)o.@Id)); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); if (o.@Content is XmlSchemaSimpleContentRestriction) { Write40_XmlSchemaSimpleContentRestriction((XmlSchemaSimpleContentRestriction)o.@Content); @@ -870,45 +872,45 @@ private void Write38_XmlSchemaSimpleContentExtension(XmlSchemaSimpleContentExten if ((object)o == null) return; WriteStartElement("extension"); - WriteAttribute(@"id", @"", ((string)o.@Id)); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); + WriteAttribute(@"id", @"", ((string?)o.@Id)); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); if (!o.@BaseTypeName.IsEmpty) { WriteAttribute(@"base", @"", o.@BaseTypeName); } - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); WriteSortedItems(o.Attributes); - Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute)o.@AnyAttribute); + Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute?)o.@AnyAttribute); WriteEndElement(); } - private void Write40_XmlSchemaSimpleContentRestriction(XmlSchemaSimpleContentRestriction o) + private void Write40_XmlSchemaSimpleContentRestriction(XmlSchemaSimpleContentRestriction? o) { - if ((object)o == null) return; + if ((object?)o == null) return; WriteStartElement("restriction"); - WriteAttribute(@"id", @"", ((string)o.@Id)); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); + WriteAttribute(@"id", @"", ((string?)o.@Id)); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); if (!o.@BaseTypeName.IsEmpty) { WriteAttribute(@"base", @"", o.@BaseTypeName); } - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); - Write9_XmlSchemaSimpleType((XmlSchemaSimpleType)o.@BaseType); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); + Write9_XmlSchemaSimpleType((XmlSchemaSimpleType?)o.@BaseType); WriteFacets(o.Facets); WriteSortedItems(o.Attributes); - Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute)o.@AnyAttribute); + Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute?)o.@AnyAttribute); WriteEndElement(); } - private void Write41_XmlSchemaComplexContent(XmlSchemaComplexContent o) + private void Write41_XmlSchemaComplexContent(XmlSchemaComplexContent? o) { - if ((object)o == null) return; + if ((object?)o == null) return; WriteStartElement("complexContent"); - WriteAttribute(@"id", @"", ((string)o.@Id)); + WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttribute(@"mixed", @"", XmlConvert.ToString((bool)((bool)o.@IsMixed))); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); if (o.@Content is XmlSchemaComplexContentRestriction) { Write56_XmlSchemaComplexContentRestriction((XmlSchemaComplexContentRestriction)o.@Content); @@ -920,18 +922,18 @@ private void Write41_XmlSchemaComplexContent(XmlSchemaComplexContent o) WriteEndElement(); } - private void Write42_XmlSchemaComplexContentExtension(XmlSchemaComplexContentExtension o) + private void Write42_XmlSchemaComplexContentExtension(XmlSchemaComplexContentExtension? o) { - if ((object)o == null) return; + if ((object?)o == null) return; WriteStartElement("extension"); - WriteAttribute(@"id", @"", ((string)o.@Id)); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); + WriteAttribute(@"id", @"", ((string?)o.@Id)); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); if (!o.@BaseTypeName.IsEmpty) { WriteAttribute(@"base", @"", o.@BaseTypeName); } - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); if (o.@Particle is XmlSchemaSequence) { Write54_XmlSchemaSequence((XmlSchemaSequence)o.@Particle); @@ -949,7 +951,7 @@ private void Write42_XmlSchemaComplexContentExtension(XmlSchemaComplexContentExt Write43_XmlSchemaAll((XmlSchemaAll)o.@Particle); } WriteSortedItems(o.Attributes); - Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute)o.@AnyAttribute); + Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute?)o.@AnyAttribute); WriteEndElement(); } @@ -958,18 +960,18 @@ private void Write43_XmlSchemaAll(XmlSchemaAll o) if ((object)o == null) return; WriteStartElement("all"); - WriteAttribute(@"id", @"", ((string)o.@Id)); + WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs)); WriteAttribute("maxOccurs", "", o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs)); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); WriteSortedItems(o.@Items); WriteEndElement(); } - private void Write46_XmlSchemaElement(XmlSchemaElement o) + private void Write46_XmlSchemaElement(XmlSchemaElement? o) { - if ((object)o == null) return; + if ((object?)o == null) return; System.Type t = o.GetType(); WriteStartElement("element"); WriteAttribute(@"id", @"", o.Id); @@ -1015,7 +1017,7 @@ private void Write46_XmlSchemaElement(XmlSchemaElement o) WriteAttribute("type", "", o.SchemaTypeName); } - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation(o.Annotation); if (o.SchemaType is XmlSchemaComplexType) { @@ -1029,16 +1031,16 @@ private void Write46_XmlSchemaElement(XmlSchemaElement o) WriteEndElement(); } - private void Write47_XmlSchemaKey(XmlSchemaKey o) + private void Write47_XmlSchemaKey(XmlSchemaKey? o) { - if ((object)o == null) return; + if ((object?)o == null) return; System.Type t = o.GetType(); WriteStartElement("key"); - WriteAttribute(@"id", @"", ((string)o.@Id)); - WriteAttribute(@"name", @"", ((string)o.@Name)); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); - Write49_XmlSchemaXPath(@"selector", @"", (XmlSchemaXPath)o.@Selector); + WriteAttribute(@"id", @"", ((string?)o.@Id)); + WriteAttribute(@"name", @"", ((string?)o.@Name)); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); + Write49_XmlSchemaXPath(@"selector", @"", (XmlSchemaXPath?)o.@Selector); { XmlSchemaObjectCollection a = (XmlSchemaObjectCollection)o.@Fields; if (a != null) @@ -1052,9 +1054,9 @@ private void Write47_XmlSchemaKey(XmlSchemaKey o) WriteEndElement(); } - private void Write48_XmlSchemaIdentityConstraint(XmlSchemaIdentityConstraint o) + private void Write48_XmlSchemaIdentityConstraint(XmlSchemaIdentityConstraint? o) { - if ((object)o == null) return; + if ((object?)o == null) return; System.Type t = o.GetType(); if (t == typeof(XmlSchemaUnique)) { @@ -1073,30 +1075,30 @@ private void Write48_XmlSchemaIdentityConstraint(XmlSchemaIdentityConstraint o) } } - private void Write49_XmlSchemaXPath(string name, string ns, XmlSchemaXPath o) + private void Write49_XmlSchemaXPath(string name, string ns, XmlSchemaXPath? o) { - if ((object)o == null) return; + if ((object?)o == null) return; WriteStartElement(name); WriteAttribute(@"id", @"", o.@Id); WriteAttribute(@"xpath", @"", o.@XPath); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); WriteEndElement(); } - private void Write50_XmlSchemaKeyref(XmlSchemaKeyref o) + private void Write50_XmlSchemaKeyref(XmlSchemaKeyref? o) { - if ((object)o == null) return; + if ((object?)o == null) return; System.Type t = o.GetType(); WriteStartElement("keyref"); - WriteAttribute(@"id", @"", ((string)o.@Id)); - WriteAttribute(@"name", @"", ((string)o.@Name)); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); + WriteAttribute(@"id", @"", ((string?)o.@Id)); + WriteAttribute(@"name", @"", ((string?)o.@Name)); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); // UNDONE compare reference here WriteAttribute(@"refer", @"", o.@Refer); - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); - Write49_XmlSchemaXPath(@"selector", @"", (XmlSchemaXPath)o.@Selector); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); + Write49_XmlSchemaXPath(@"selector", @"", (XmlSchemaXPath?)o.@Selector); { XmlSchemaObjectCollection a = (XmlSchemaObjectCollection)o.@Fields; if (a != null) @@ -1110,17 +1112,17 @@ private void Write50_XmlSchemaKeyref(XmlSchemaKeyref o) WriteEndElement(); } - private void Write51_XmlSchemaUnique(XmlSchemaUnique o) + private void Write51_XmlSchemaUnique(XmlSchemaUnique? o) { - if ((object)o == null) return; + if ((object?)o == null) return; System.Type t = o.GetType(); WriteStartElement("unique"); - WriteAttribute(@"id", @"", ((string)o.@Id)); - WriteAttribute(@"name", @"", ((string)o.@Name)); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); - Write49_XmlSchemaXPath("selector", "", (XmlSchemaXPath)o.@Selector); + WriteAttribute(@"id", @"", ((string?)o.@Id)); + WriteAttribute(@"name", @"", ((string?)o.@Name)); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); + Write49_XmlSchemaXPath("selector", "", (XmlSchemaXPath?)o.@Selector); XmlSchemaObjectCollection a = (XmlSchemaObjectCollection)o.@Fields; if (a != null) { @@ -1132,24 +1134,24 @@ private void Write51_XmlSchemaUnique(XmlSchemaUnique o) WriteEndElement(); } - private void Write52_XmlSchemaChoice(XmlSchemaChoice o) + private void Write52_XmlSchemaChoice(XmlSchemaChoice? o) { - if ((object)o == null) return; + if ((object?)o == null) return; System.Type t = o.GetType(); WriteStartElement("choice"); - WriteAttribute(@"id", @"", ((string)o.@Id)); + WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs)); WriteAttribute(@"maxOccurs", @"", o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs)); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); WriteSortedItems(o.@Items); WriteEndElement(); } - private void Write53_XmlSchemaAny(XmlSchemaAny o) + private void Write53_XmlSchemaAny(XmlSchemaAny? o) { - if ((object)o == null) return; + if ((object?)o == null) return; WriteStartElement("any"); WriteAttribute(@"id", @"", o.@Id); @@ -1158,21 +1160,21 @@ private void Write53_XmlSchemaAny(XmlSchemaAny o) WriteAttribute(@"namespace", @"", ToString(o.NamespaceList)); XmlSchemaContentProcessing process = o.@ProcessContents == XmlSchemaContentProcessing.@None ? XmlSchemaContentProcessing.Strict : o.@ProcessContents; WriteAttribute(@"processContents", @"", Write34_XmlSchemaContentProcessing(process)); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); WriteEndElement(); } - private void Write54_XmlSchemaSequence(XmlSchemaSequence o) + private void Write54_XmlSchemaSequence(XmlSchemaSequence? o) { - if ((object)o == null) return; + if ((object?)o == null) return; WriteStartElement("sequence"); - WriteAttribute(@"id", @"", ((string)o.@Id)); + WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs)); WriteAttribute("maxOccurs", "", o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs)); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); XmlSchemaObjectCollection a = (XmlSchemaObjectCollection)o.@Items; if (a != null) { @@ -1204,12 +1206,12 @@ private void Write54_XmlSchemaSequence(XmlSchemaSequence o) WriteEndElement(); } - private void Write55_XmlSchemaGroupRef(XmlSchemaGroupRef o) + private void Write55_XmlSchemaGroupRef(XmlSchemaGroupRef? o) { - if ((object)o == null) return; + if ((object?)o == null) return; WriteStartElement("group"); - WriteAttribute(@"id", @"", ((string)o.@Id)); + WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs)); WriteAttribute(@"maxOccurs", @"", o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs)); @@ -1217,25 +1219,25 @@ private void Write55_XmlSchemaGroupRef(XmlSchemaGroupRef o) { WriteAttribute("ref", "", o.RefName); } - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); WriteEndElement(); } - private void Write56_XmlSchemaComplexContentRestriction(XmlSchemaComplexContentRestriction o) + private void Write56_XmlSchemaComplexContentRestriction(XmlSchemaComplexContentRestriction? o) { - if ((object)o == null) return; + if ((object?)o == null) return; WriteStartElement("restriction"); - WriteAttribute(@"id", @"", ((string)o.@Id)); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); + WriteAttribute(@"id", @"", ((string?)o.@Id)); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); if (!o.@BaseTypeName.IsEmpty) { WriteAttribute(@"base", @"", o.@BaseTypeName); } - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); if (o.@Particle is XmlSchemaSequence) { Write54_XmlSchemaSequence((XmlSchemaSequence)o.@Particle); @@ -1253,19 +1255,19 @@ private void Write56_XmlSchemaComplexContentRestriction(XmlSchemaComplexContentR Write43_XmlSchemaAll((XmlSchemaAll)o.@Particle); } WriteSortedItems(o.Attributes); - Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute)o.@AnyAttribute); + Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute?)o.@AnyAttribute); WriteEndElement(); } - private void Write57_XmlSchemaGroup(XmlSchemaGroup o) + private void Write57_XmlSchemaGroup(XmlSchemaGroup? o) { - if ((object)o == null) return; + if ((object?)o == null) return; WriteStartElement("group"); - WriteAttribute(@"id", @"", ((string)o.@Id)); - WriteAttribute(@"name", @"", ((string)o.@Name)); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); + WriteAttribute(@"id", @"", ((string?)o.@Id)); + WriteAttribute(@"name", @"", ((string?)o.@Name)); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); if (o.@Particle is XmlSchemaSequence) { Write54_XmlSchemaSequence((XmlSchemaSequence)o.@Particle); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapAttributeAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapAttributeAttribute.cs index fea02f71483475..5ba74b764905f9 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapAttributeAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapAttributeAttribute.cs @@ -1,16 +1,18 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; + using System.Diagnostics.CodeAnalysis; [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue)] public class SoapAttributeAttribute : System.Attribute { - private string _attributeName; - private string _ns; - private string _dataType; + private string? _attributeName; + private string? _ns; + private string? _dataType; public SoapAttributeAttribute() { @@ -21,18 +23,20 @@ public SoapAttributeAttribute(string attributeName) _attributeName = attributeName; } + [AllowNull] public string AttributeName { get { return _attributeName == null ? string.Empty : _attributeName; } set { _attributeName = value; } } - public string Namespace + public string? Namespace { get { return _ns; } set { _ns = value; } } + [AllowNull] public string DataType { get { return _dataType == null ? string.Empty : _dataType; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapAttributeOverrides.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapAttributeOverrides.cs index 38f970be4558ed..f9fb5d7de763f4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapAttributeOverrides.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapAttributeOverrides.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System.Reflection; @@ -14,14 +15,14 @@ public class SoapAttributeOverrides { private readonly Hashtable _types = new Hashtable(); - public void Add(Type type, SoapAttributes attributes) + public void Add(Type type, SoapAttributes? attributes) { Add(type, string.Empty, attributes); } - public void Add(Type type, string member, SoapAttributes attributes) + public void Add(Type type, string member, SoapAttributes? attributes) { - Hashtable members = (Hashtable)_types[type]; + Hashtable? members = (Hashtable?)_types[type]; if (members == null) { members = new Hashtable(); @@ -34,7 +35,7 @@ public void Add(Type type, string member, SoapAttributes attributes) members.Add(member, attributes); } - public SoapAttributes this[Type type] + public SoapAttributes? this[Type type] { get { @@ -42,13 +43,13 @@ public SoapAttributes this[Type type] } } - public SoapAttributes this[Type type, string member] + public SoapAttributes? this[Type type, string member] { get { - Hashtable members = (Hashtable)_types[type]; + Hashtable? members = (Hashtable?)_types[type]; if (members == null) return null; - return (SoapAttributes)members[member]; + return (SoapAttributes?)members[member]; } } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapAttributes.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapAttributes.cs index f632645a9c4951..0d57c9755fea88 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapAttributes.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapAttributes.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; @@ -20,11 +21,11 @@ internal enum SoapAttributeFlags public class SoapAttributes { private bool _soapIgnore; - private SoapTypeAttribute _soapType; - private SoapElementAttribute _soapElement; - private SoapAttributeAttribute _soapAttribute; - private SoapEnumAttribute _soapEnum; - private object _soapDefaultValue; + private SoapTypeAttribute? _soapType; + private SoapElementAttribute? _soapElement; + private SoapAttributeAttribute? _soapAttribute; + private SoapEnumAttribute? _soapEnum; + private object? _soapDefaultValue; public SoapAttributes() { @@ -89,13 +90,13 @@ internal SoapAttributeFlags GetSoapFlags() return SoapFlags; } - public SoapTypeAttribute SoapType + public SoapTypeAttribute? SoapType { get { return _soapType; } set { _soapType = value; } } - public SoapEnumAttribute SoapEnum + public SoapEnumAttribute? SoapEnum { get { return _soapEnum; } set { _soapEnum = value; } @@ -107,19 +108,19 @@ public bool SoapIgnore set { _soapIgnore = value; } } - public SoapElementAttribute SoapElement + public SoapElementAttribute? SoapElement { get { return _soapElement; } set { _soapElement = value; } } - public SoapAttributeAttribute SoapAttribute + public SoapAttributeAttribute? SoapAttribute { get { return _soapAttribute; } set { _soapAttribute = value; } } - public object SoapDefaultValue + public object? SoapDefaultValue { get { return _soapDefaultValue; } set { _soapDefaultValue = value; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapElementAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapElementAttribute.cs index ed56eb1ffccee4..98975be0429eed 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapElementAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapElementAttribute.cs @@ -1,15 +1,17 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; + using System.Diagnostics.CodeAnalysis; [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue)] public class SoapElementAttribute : System.Attribute { - private string _elementName; - private string _dataType; + private string? _elementName; + private string? _dataType; private bool _nullable; public SoapElementAttribute() @@ -21,12 +23,14 @@ public SoapElementAttribute(string elementName) _elementName = elementName; } + [AllowNull] public string ElementName { get { return _elementName == null ? string.Empty : _elementName; } set { _elementName = value; } } + [AllowNull] public string DataType { get { return _dataType == null ? string.Empty : _dataType; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapEnumAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapEnumAttribute.cs index 606ec240d0ed9b..23c86a4080df5a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapEnumAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapEnumAttribute.cs @@ -1,14 +1,16 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; + using System.Diagnostics.CodeAnalysis; [AttributeUsage(AttributeTargets.Field)] public class SoapEnumAttribute : System.Attribute { - private string _name; + private string? _name; public SoapEnumAttribute() { @@ -19,6 +21,7 @@ public SoapEnumAttribute(string name) _name = name; } + [AllowNull] public string Name { get { return _name == null ? string.Empty : _name; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapIgnoreAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapIgnoreAttribute.cs index 23c6971bbdda1d..2fdd91dc5b2533 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapIgnoreAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapIgnoreAttribute.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapIncludeAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapIncludeAttribute.cs index 1b66ac7409e761..1c41a6bf5b3c32 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapIncludeAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapIncludeAttribute.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapReflectionImporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapReflectionImporter.cs index 42cc5acdb9adcc..bc1ef880ff13ef 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapReflectionImporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapReflectionImporter.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System.Reflection; @@ -19,7 +20,7 @@ public class SoapReflectionImporter private readonly SoapAttributeOverrides _attributeOverrides; private readonly NameTable _types = new NameTable(); // xmltypename + xmlns -> Mapping private readonly NameTable _nullables = new NameTable(); // xmltypename + xmlns -> NullableMapping - private StructMapping _root; + private StructMapping? _root; private readonly string _defaultNs; private readonly ModelScope _modelScope; @@ -27,15 +28,15 @@ public SoapReflectionImporter() : this(null, null) { } - public SoapReflectionImporter(string defaultNamespace) : this(null, defaultNamespace) + public SoapReflectionImporter(string? defaultNamespace) : this(null, defaultNamespace) { } - public SoapReflectionImporter(SoapAttributeOverrides attributeOverrides) : this(attributeOverrides, null) + public SoapReflectionImporter(SoapAttributeOverrides? attributeOverrides) : this(attributeOverrides, null) { } - public SoapReflectionImporter(SoapAttributeOverrides attributeOverrides, string defaultNamespace) + public SoapReflectionImporter(SoapAttributeOverrides? attributeOverrides, string? defaultNamespace) { if (defaultNamespace == null) defaultNamespace = string.Empty; @@ -76,7 +77,7 @@ public XmlTypeMapping ImportTypeMapping(Type type) return ImportTypeMapping(type, null); } - public XmlTypeMapping ImportTypeMapping(Type type, string defaultNamespace) + public XmlTypeMapping ImportTypeMapping(Type type, string? defaultNamespace) { ElementAccessor element = new ElementAccessor(); element.IsSoap = true; @@ -91,22 +92,22 @@ public XmlTypeMapping ImportTypeMapping(Type type, string defaultNamespace) return xmlMapping; } - public XmlMembersMapping ImportMembersMapping(string elementName, string ns, XmlReflectionMember[] members) + public XmlMembersMapping ImportMembersMapping(string? elementName, string? ns, XmlReflectionMember[] members) { return ImportMembersMapping(elementName, ns, members, true, true, false); } - public XmlMembersMapping ImportMembersMapping(string elementName, string ns, XmlReflectionMember[] members, bool hasWrapperElement, bool writeAccessors) + public XmlMembersMapping ImportMembersMapping(string? elementName, string? ns, XmlReflectionMember[] members, bool hasWrapperElement, bool writeAccessors) { return ImportMembersMapping(elementName, ns, members, hasWrapperElement, writeAccessors, false); } - public XmlMembersMapping ImportMembersMapping(string elementName, string ns, XmlReflectionMember[] members, bool hasWrapperElement, bool writeAccessors, bool validate) + public XmlMembersMapping ImportMembersMapping(string? elementName, string? ns, XmlReflectionMember[] members, bool hasWrapperElement, bool writeAccessors, bool validate) { return ImportMembersMapping(elementName, ns, members, hasWrapperElement, writeAccessors, validate, XmlMappingAccess.Read | XmlMappingAccess.Write); } - public XmlMembersMapping ImportMembersMapping(string elementName, string ns, XmlReflectionMember[] members, bool hasWrapperElement, bool writeAccessors, bool validate, XmlMappingAccess access) + public XmlMembersMapping ImportMembersMapping(string? elementName, string? ns, XmlReflectionMember[] members, bool hasWrapperElement, bool writeAccessors, bool validate, XmlMappingAccess access) { ElementAccessor element = new ElementAccessor(); element.IsSoap = true; @@ -129,14 +130,14 @@ private Exception ReflectionException(string context, Exception e) private SoapAttributes GetAttributes(Type type) { - SoapAttributes attrs = _attributeOverrides[type]; + SoapAttributes? attrs = _attributeOverrides[type]; if (attrs != null) return attrs; return new SoapAttributes(type); } private SoapAttributes GetAttributes(MemberInfo memberInfo) { - SoapAttributes attrs = _attributeOverrides[memberInfo.DeclaringType, memberInfo.Name]; + SoapAttributes? attrs = _attributeOverrides[memberInfo.DeclaringType!, memberInfo.Name]; if (attrs != null) return attrs; return new SoapAttributes(memberInfo); } @@ -154,7 +155,7 @@ private TypeMapping ImportTypeMapping(TypeModel model, string dataType, Recursio { throw new InvalidOperationException(SR.Format(SR.XmlInvalidDataTypeUsage, dataType, "SoapElementAttribute.DataType")); } - TypeDesc td = _typeScope.GetTypeDesc(dataType, XmlSchema.Namespace); + TypeDesc? td = _typeScope.GetTypeDesc(dataType!, XmlSchema.Namespace); if (td == null) { throw new InvalidOperationException(SR.Format(SR.XmlInvalidXsdDataType, dataType, "SoapElementAttribute.DataType", new XmlQualifiedName(dataType, XmlSchema.Namespace).ToString())); @@ -185,17 +186,17 @@ private TypeMapping ImportTypeMapping(TypeModel model, string dataType, Recursio case TypeKind.Struct: if (model.TypeDesc.IsOptionalValue) { - TypeDesc baseTypeDesc = model.TypeDesc.BaseTypeDesc; - SoapAttributes baseAttributes = GetAttributes(baseTypeDesc.Type); + TypeDesc? baseTypeDesc = model.TypeDesc.BaseTypeDesc; + SoapAttributes baseAttributes = GetAttributes(baseTypeDesc!.Type!); string typeNs = _defaultNs; if (baseAttributes.SoapType != null && baseAttributes.SoapType.Namespace != null) typeNs = baseAttributes.SoapType.Namespace; - TypeDesc valueTypeDesc = string.IsNullOrEmpty(dataType) ? model.TypeDesc.BaseTypeDesc : _typeScope.GetTypeDesc(dataType, XmlSchema.Namespace); - string xsdTypeName = string.IsNullOrEmpty(dataType) ? model.TypeDesc.BaseTypeDesc.Name : dataType; - TypeMapping baseMapping = GetTypeMapping(xsdTypeName, typeNs, valueTypeDesc); + TypeDesc valueTypeDesc = string.IsNullOrEmpty(dataType) ? model.TypeDesc.BaseTypeDesc! : _typeScope.GetTypeDesc(dataType, XmlSchema.Namespace)!; + string xsdTypeName = string.IsNullOrEmpty(dataType) ? model.TypeDesc.BaseTypeDesc!.Name : dataType; + TypeMapping? baseMapping = GetTypeMapping(xsdTypeName, typeNs, valueTypeDesc); if (baseMapping == null) - baseMapping = ImportTypeMapping(_modelScope.GetTypeModel(baseTypeDesc.Type), dataType, limiter); - return CreateNullableMapping(baseMapping, model.TypeDesc.Type); + baseMapping = ImportTypeMapping(_modelScope.GetTypeModel(baseTypeDesc.Type!), dataType, limiter); + return CreateNullableMapping(baseMapping, model.TypeDesc.Type!); } else { @@ -229,19 +230,19 @@ private StructMapping GetRootMapping() return _root; } - private TypeMapping GetTypeMapping(string typeName, string ns, TypeDesc typeDesc) + private TypeMapping? GetTypeMapping(string typeName, string? ns, TypeDesc typeDesc) { - TypeMapping mapping = (TypeMapping)_types[typeName, ns]; + TypeMapping? mapping = (TypeMapping?)_types[typeName, ns]; if (mapping == null) return null; if (mapping.TypeDesc != typeDesc) - throw new InvalidOperationException(SR.Format(SR.XmlTypesDuplicate, typeDesc.FullName, mapping.TypeDesc.FullName, typeName, ns)); + throw new InvalidOperationException(SR.Format(SR.XmlTypesDuplicate, typeDesc.FullName, mapping.TypeDesc!.FullName, typeName, ns)); return mapping; } private NullableMapping CreateNullableMapping(TypeMapping baseMapping, Type type) { - TypeDesc typeDesc = baseMapping.TypeDesc.GetNullableTypeDesc(type); - TypeMapping existingMapping = (TypeMapping)_nullables[baseMapping.TypeName, baseMapping.Namespace]; + TypeDesc typeDesc = baseMapping.TypeDesc!.GetNullableTypeDesc(type); + TypeMapping? existingMapping = (TypeMapping?)_nullables[baseMapping.TypeName!, baseMapping.Namespace]; NullableMapping mapping; if (existingMapping != null) { @@ -256,12 +257,12 @@ private NullableMapping CreateNullableMapping(TypeMapping baseMapping, Type type } else { - throw new InvalidOperationException(SR.Format(SR.XmlTypesDuplicate, typeDesc.FullName, existingMapping.TypeDesc.FullName, typeDesc.Name, existingMapping.Namespace)); + throw new InvalidOperationException(SR.Format(SR.XmlTypesDuplicate, typeDesc.FullName, existingMapping.TypeDesc!.FullName, typeDesc.Name, existingMapping.Namespace)); } } else if (!(baseMapping is PrimitiveMapping)) { - throw new InvalidOperationException(SR.Format(SR.XmlTypesDuplicate, typeDesc.FullName, existingMapping.TypeDesc.FullName, typeDesc.Name, existingMapping.Namespace)); + throw new InvalidOperationException(SR.Format(SR.XmlTypesDuplicate, typeDesc.FullName, existingMapping.TypeDesc!.FullName, typeDesc.Name, existingMapping.Namespace)); } } mapping = new NullableMapping(); @@ -287,7 +288,7 @@ private StructMapping ImportStructLikeMapping(StructModel model, RecursionLimite string typeName = XsdTypeName(model.Type, a, model.TypeDesc.Name); typeName = XmlConvert.EncodeLocalName(typeName); - StructMapping mapping = (StructMapping)GetTypeMapping(typeName, typeNs, model.TypeDesc); + StructMapping? mapping = (StructMapping?)GetTypeMapping(typeName, typeNs, model.TypeDesc); if (mapping == null) { mapping = new StructMapping(); @@ -339,10 +340,10 @@ private bool InitializeStructMembers(StructMapping mapping, StructModel model, R return true; if (model.TypeDesc.BaseTypeDesc != null) { - StructMapping baseMapping = ImportStructLikeMapping((StructModel)_modelScope.GetTypeModel(model.Type.BaseType, false), limiter); + StructMapping baseMapping = ImportStructLikeMapping((StructModel)_modelScope.GetTypeModel(model.Type.BaseType!, false), limiter); // check to see if the import of the baseMapping was deferred - int baseIndex = limiter.DeferredWorkItems.IndexOf(mapping.BaseMapping); + int baseIndex = limiter.DeferredWorkItems.IndexOf(mapping.BaseMapping!); if (baseIndex < 0) { mapping.BaseMapping = baseMapping; @@ -372,12 +373,12 @@ private bool InitializeStructMembers(StructMapping mapping, StructModel model, R continue; SoapAttributes memberAttrs = GetAttributes(memberInfo); if (memberAttrs.SoapIgnore) continue; - FieldModel fieldModel = model.GetFieldModel(memberInfo); + FieldModel? fieldModel = model.GetFieldModel(memberInfo); if (fieldModel == null) continue; - MemberMapping member = ImportFieldMapping(fieldModel, memberAttrs, mapping.Namespace, limiter); + MemberMapping? member = ImportFieldMapping(fieldModel, memberAttrs, mapping.Namespace!, limiter); if (member == null) continue; - if (!member.TypeDesc.IsPrimitive && !member.TypeDesc.IsEnum && !member.TypeDesc.IsOptionalValue) + if (!member.TypeDesc!.IsPrimitive && !member.TypeDesc.IsEnum && !member.TypeDesc.IsOptionalValue) { if (model.TypeDesc.IsValueType) throw new NotSupportedException(SR.Format(SR.XmlRpcRefsInValueType, model.TypeDesc.FullName)); @@ -386,7 +387,7 @@ private bool InitializeStructMembers(StructMapping mapping, StructModel model, R } if (mapping.BaseMapping != null) { - if (mapping.BaseMapping.Declares(member, mapping.TypeName)) continue; + if (mapping.BaseMapping.Declares(member, mapping.TypeName!)) continue; } members.Add(member); } @@ -404,7 +405,7 @@ private ArrayMapping ImportArrayLikeMapping(ArrayModel model, RecursionLimiter l mapping.IsSoap = true; TypeMapping itemTypeMapping = ImportTypeMapping(model.Element, limiter); - if (itemTypeMapping.TypeDesc.IsValueType && !itemTypeMapping.TypeDesc.IsPrimitive && !itemTypeMapping.TypeDesc.IsEnum) + if (itemTypeMapping.TypeDesc!.IsValueType && !itemTypeMapping.TypeDesc.IsPrimitive && !itemTypeMapping.TypeDesc.IsEnum) throw new NotSupportedException(SR.Format(SR.XmlRpcArrayOfValueTypes, model.TypeDesc.FullName)); mapping.TypeDesc = model.TypeDesc; @@ -415,7 +416,7 @@ private ArrayMapping ImportArrayLikeMapping(ArrayModel model, RecursionLimiter l // in the case of an ArrayMapping we can have more that one mapping correspond to a type // examples of that are ArrayList and object[] both will map tp ArrayOfur-type // so we create a link list for all mappings of the same XSD type - ArrayMapping existingMapping = (ArrayMapping)_types[mapping.TypeName, mapping.Namespace]; + ArrayMapping? existingMapping = (ArrayMapping?)_types[mapping.TypeName!, mapping.Namespace]; if (existingMapping != null) { ArrayMapping first = existingMapping; @@ -426,7 +427,7 @@ private ArrayMapping ImportArrayLikeMapping(ArrayModel model, RecursionLimiter l existingMapping = existingMapping.Next; } mapping.Next = first; - _types[mapping.TypeName, mapping.Namespace] = mapping; + _types[mapping.TypeName!, mapping.Namespace] = mapping; return mapping; } _typeScope.AddTypeMapping(mapping); @@ -443,26 +444,26 @@ private void SetArrayMappingType(ArrayMapping mapping) string itemTypeName; string itemTypeNamespace; - TypeMapping itemTypeMapping; - if (mapping.Elements.Length == 1) + TypeMapping? itemTypeMapping; + if (mapping.Elements!.Length == 1) itemTypeMapping = mapping.Elements[0].Mapping; else itemTypeMapping = null; if (itemTypeMapping is EnumMapping) { - itemTypeNamespace = itemTypeMapping.Namespace; - itemTypeName = itemTypeMapping.TypeName; + itemTypeNamespace = itemTypeMapping.Namespace!; + itemTypeName = itemTypeMapping.TypeName!; } else if (itemTypeMapping is PrimitiveMapping) { - itemTypeNamespace = itemTypeMapping.TypeDesc.IsXsdType ? XmlSchema.Namespace : UrtTypes.Namespace; - itemTypeName = itemTypeMapping.TypeDesc.DataType.Name; + itemTypeNamespace = itemTypeMapping.TypeDesc!.IsXsdType ? XmlSchema.Namespace : UrtTypes.Namespace; + itemTypeName = itemTypeMapping.TypeDesc.DataType!.Name!; useDefaultNs = true; } else if (itemTypeMapping is StructMapping) { - if (itemTypeMapping.TypeDesc.IsRoot) + if (itemTypeMapping.TypeDesc!.IsRoot) { itemTypeNamespace = XmlSchema.Namespace; itemTypeName = Soap.UrType; @@ -470,25 +471,25 @@ private void SetArrayMappingType(ArrayMapping mapping) } else { - itemTypeNamespace = itemTypeMapping.Namespace; - itemTypeName = itemTypeMapping.TypeName; + itemTypeNamespace = itemTypeMapping.Namespace!; + itemTypeName = itemTypeMapping.TypeName!; } } else if (itemTypeMapping is ArrayMapping) { - itemTypeNamespace = itemTypeMapping.Namespace; - itemTypeName = itemTypeMapping.TypeName; + itemTypeNamespace = itemTypeMapping.Namespace!; + itemTypeName = itemTypeMapping.TypeName!; } else { - throw new InvalidOperationException(SR.Format(SR.XmlInvalidSoapArray, mapping.TypeDesc.FullName)); + throw new InvalidOperationException(SR.Format(SR.XmlInvalidSoapArray, mapping.TypeDesc!.FullName)); } itemTypeName = CodeIdentifier.MakePascal(itemTypeName); string uniqueName = "ArrayOf" + itemTypeName; string ns = useDefaultNs ? _defaultNs : itemTypeNamespace; int i = 1; - TypeMapping existingMapping = (TypeMapping)_types[uniqueName, ns]; + TypeMapping? existingMapping = (TypeMapping?)_types[uniqueName, ns]; while (existingMapping != null) { if (existingMapping is ArrayMapping) @@ -501,7 +502,7 @@ private void SetArrayMappingType(ArrayMapping mapping) } // need to re-name the mapping uniqueName = itemTypeName + i.ToString(CultureInfo.InvariantCulture); - existingMapping = (TypeMapping)_types[uniqueName, ns]; + existingMapping = (TypeMapping?)_types[uniqueName, ns]; i++; } mapping.Namespace = ns; @@ -529,7 +530,7 @@ private PrimitiveMapping ImportPrimitiveMapping(PrimitiveModel model, string dat { mapping.TypeDesc = model.TypeDesc; } - mapping.TypeName = mapping.TypeDesc.DataType.Name; + mapping.TypeName = mapping.TypeDesc.DataType!.Name; mapping.Namespace = mapping.TypeDesc.IsXsdType ? XmlSchema.Namespace : UrtTypes.Namespace; return mapping; } @@ -543,7 +544,7 @@ private EnumMapping ImportEnumMapping(EnumModel model) string typeName = XsdTypeName(model.Type, a, model.TypeDesc.Name); typeName = XmlConvert.EncodeLocalName(typeName); - EnumMapping mapping = (EnumMapping)GetTypeMapping(typeName, typeNs, model.TypeDesc); + EnumMapping? mapping = (EnumMapping?)GetTypeMapping(typeName, typeNs, model.TypeDesc); if (mapping == null) { mapping = new EnumMapping(); @@ -557,7 +558,7 @@ private EnumMapping ImportEnumMapping(EnumModel model) ArrayList constants = new ArrayList(); for (int i = 0; i < model.Constants.Length; i++) { - ConstantMapping constant = ImportConstantMapping(model.Constants[i]); + ConstantMapping? constant = ImportConstantMapping(model.Constants[i]); if (constant != null) constants.Add(constant); } if (constants.Count == 0) @@ -569,7 +570,7 @@ private EnumMapping ImportEnumMapping(EnumModel model) return mapping; } - private ConstantMapping ImportConstantMapping(ConstantModel model) + private ConstantMapping? ImportConstantMapping(ConstantModel model) { SoapAttributes a = GetAttributes(model.FieldInfo); if (a.SoapIgnore) return null; @@ -585,7 +586,7 @@ private ConstantMapping ImportConstantMapping(ConstantModel model) return constant; } - private MembersMapping ImportMembersMapping(XmlReflectionMember[] xmlReflectionMembers, string ns, bool hasWrapperElement, bool writeAccessors, bool validateWrapperElement, RecursionLimiter limiter) + private MembersMapping ImportMembersMapping(XmlReflectionMember[] xmlReflectionMembers, string? ns, bool hasWrapperElement, bool writeAccessors, bool validateWrapperElement, RecursionLimiter limiter) { MembersMapping members = new MembersMapping(); members.TypeDesc = _typeScope.GetTypeDesc(typeof(object[])); @@ -595,13 +596,13 @@ private MembersMapping ImportMembersMapping(XmlReflectionMember[] xmlReflectionM try { XmlReflectionMember member = xmlReflectionMembers[i]; - MemberMapping mapping = ImportMemberMapping(member, ns, xmlReflectionMembers, hasWrapperElement ? XmlSchemaForm.Unqualified : XmlSchemaForm.Qualified, limiter); + MemberMapping? mapping = ImportMemberMapping(member, ns, xmlReflectionMembers, hasWrapperElement ? XmlSchemaForm.Unqualified : XmlSchemaForm.Qualified, limiter); if (member.IsReturnValue && writeAccessors) { // no special treatment for return values with doc/enc if (i > 0) throw new InvalidOperationException(SR.XmlInvalidReturnPosition); - mapping.IsReturnValue = true; + mapping!.IsReturnValue = true; } - mappings[i] = mapping; + mappings[i] = mapping!; } catch (Exception e) { @@ -625,7 +626,7 @@ private MembersMapping ImportMembersMapping(XmlReflectionMember[] xmlReflectionM return members; } - private MemberMapping ImportMemberMapping(XmlReflectionMember xmlReflectionMember, string ns, XmlReflectionMember[] xmlReflectionMembers, XmlSchemaForm form, RecursionLimiter limiter) + private MemberMapping? ImportMemberMapping(XmlReflectionMember xmlReflectionMember, string? ns, XmlReflectionMember[] xmlReflectionMembers, XmlSchemaForm form, RecursionLimiter limiter) { SoapAttributes a = xmlReflectionMember.SoapAttributes; if (a.SoapIgnore) return null; @@ -633,17 +634,17 @@ private MemberMapping ImportMemberMapping(XmlReflectionMember xmlReflectionMembe member.IsSoap = true; member.Name = xmlReflectionMember.MemberName; bool checkSpecified = XmlReflectionImporter.FindSpecifiedMember(xmlReflectionMember.MemberName, xmlReflectionMembers) != null; - FieldModel model = new FieldModel(xmlReflectionMember.MemberName, xmlReflectionMember.MemberType, _typeScope.GetTypeDesc(xmlReflectionMember.MemberType), checkSpecified, false); + FieldModel model = new FieldModel(xmlReflectionMember.MemberName, xmlReflectionMember.MemberType!, _typeScope.GetTypeDesc(xmlReflectionMember.MemberType!), checkSpecified, false); member.CheckShouldPersist = model.CheckShouldPersist; member.CheckSpecified = model.CheckSpecified; member.ReadOnly = model.ReadOnly; // || !model.FieldTypeDesc.HasDefaultConstructor; ImportAccessorMapping(member, model, a, ns, form, limiter); if (xmlReflectionMember.OverrideIsNullable) - member.Elements[0].IsNullable = false; + member.Elements![0].IsNullable = false; return member; } - private MemberMapping ImportFieldMapping(FieldModel model, SoapAttributes a, string ns, RecursionLimiter limiter) + private MemberMapping? ImportFieldMapping(FieldModel model, SoapAttributes a, string ns, RecursionLimiter limiter) { if (a.SoapIgnore) return null; MemberMapping member = new MemberMapping(); @@ -659,7 +660,7 @@ private MemberMapping ImportFieldMapping(FieldModel model, SoapAttributes a, str return member; } - private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, SoapAttributes a, string ns, XmlSchemaForm form, RecursionLimiter limiter) + private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, SoapAttributes a, string? ns, XmlSchemaForm form, RecursionLimiter limiter) { Type accessorType = model.FieldType; string accessorName = model.Name; @@ -704,7 +705,7 @@ private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, Soa } } - private static ElementAccessor CreateElementAccessor(TypeMapping mapping, string ns) + private static ElementAccessor CreateElementAccessor(TypeMapping mapping, string? ns) { ElementAccessor element = new ElementAccessor(); element.IsSoap = true; @@ -714,7 +715,7 @@ private static ElementAccessor CreateElementAccessor(TypeMapping mapping, string return element; } - private object GetDefaultValue(TypeDesc fieldTypeDesc, SoapAttributes a) + private object? GetDefaultValue(TypeDesc fieldTypeDesc, SoapAttributes a) { if (a.SoapDefaultValue == null || a.SoapDefaultValue == DBNull.Value) return null; if (!(fieldTypeDesc.Kind == TypeKind.Primitive || fieldTypeDesc.Kind == TypeKind.Enum)) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapSchemamember.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapSchemamember.cs index 886ec02af9b97a..afeb107a56ec92 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapSchemamember.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapSchemamember.cs @@ -1,22 +1,25 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; + using System.Diagnostics.CodeAnalysis; using System.Xml; public class SoapSchemaMember { - private string _memberName; - private XmlQualifiedName _type = XmlQualifiedName.Empty; + private string? _memberName; + private XmlQualifiedName? _type = XmlQualifiedName.Empty; - public XmlQualifiedName MemberType + public XmlQualifiedName? MemberType { get { return _type; } set { _type = value; } } + [AllowNull] public string MemberName { get { return _memberName == null ? string.Empty : _memberName; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapTypeAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapTypeAttribute.cs index 2c205e8d6844b6..b816a34d4db3a0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapTypeAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapTypeAttribute.cs @@ -1,27 +1,29 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; + using System.Diagnostics.CodeAnalysis; [AttributeUsage(AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Struct)] public class SoapTypeAttribute : System.Attribute { - private string _ns; - private string _typeName; + private string? _ns; + private string? _typeName; private bool _includeInSchema = true; public SoapTypeAttribute() { } - public SoapTypeAttribute(string typeName) + public SoapTypeAttribute(string? typeName) { _typeName = typeName; } - public SoapTypeAttribute(string typeName, string ns) + public SoapTypeAttribute(string? typeName, string? ns) { _typeName = typeName; _ns = ns; @@ -33,13 +35,14 @@ public bool IncludeInSchema set { _includeInSchema = value; } } + [AllowNull] public string TypeName { get { return _typeName == null ? string.Empty : _typeName; } set { _typeName = value; } } - public string Namespace + public string? Namespace { get { return _ns; } set { _ns = value; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SourceInfo.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SourceInfo.cs index d510ba55f422de..ff16ce43b56768 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SourceInfo.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SourceInfo.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; using System.Collections; using System.Diagnostics; @@ -25,16 +26,16 @@ internal class SourceInfo return typeof(IList).GetMethod( "get_Item", new Type[] { typeof(int) } - ); + )!; }); public string Source; public readonly string Arg; - public readonly MemberInfo MemberInfo; - public readonly Type Type; + public readonly MemberInfo? MemberInfo; + public readonly Type? Type; public readonly CodeGenerator ILG; - public SourceInfo(string source, string arg, MemberInfo memberInfo, Type type, CodeGenerator ilg) + public SourceInfo(string source, string? arg, MemberInfo? memberInfo, Type? type, CodeGenerator ilg) { this.Source = source; this.Arg = arg ?? source; @@ -45,20 +46,20 @@ public SourceInfo(string source, string arg, MemberInfo memberInfo, Type type, C public SourceInfo CastTo(TypeDesc td) { - return new SourceInfo("((" + td.CSharpName + ")" + Source + ")", Arg, MemberInfo, td.Type, ILG); + return new SourceInfo("((" + td.CSharpName + ")" + Source + ")", Arg, MemberInfo, td.Type!, ILG); } - public void LoadAddress(Type elementType) + public void LoadAddress(Type? elementType) { InternalLoad(elementType, asAddress: true); } - public void Load(Type elementType) + public void Load(Type? elementType) { InternalLoad(elementType); } - private void InternalLoad(Type elementType, bool asAddress = false) + private void InternalLoad(Type? elementType, bool asAddress = false) { Match match = s_regex.Match(Arg); if (match.Success) @@ -70,11 +71,11 @@ private void InternalLoad(Type elementType, bool asAddress = false) { ILG.Load(varA); ILG.Load(varIA); - Type eType = varType.GetElementType(); + Type eType = varType.GetElementType()!; if (CodeGenerator.IsNullableGenericType(eType)) { ILG.Ldelema(eType); - ConvertNullableValue(eType, elementType); + ConvertNullableValue(eType, elementType!); } else { @@ -100,7 +101,7 @@ private void InternalLoad(Type elementType, bool asAddress = false) "get_Item", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(int) } - ); + )!; if (get_Item == null && typeof(IList).IsAssignableFrom(varType)) { @@ -115,7 +116,7 @@ private void InternalLoad(Type elementType, bool asAddress = false) LocalBuilder localTmp = ILG.GetTempLocal(eType); ILG.Stloc(localTmp); ILG.Ldloca(localTmp); - ConvertNullableValue(eType, elementType); + ConvertNullableValue(eType, elementType!); } else if ((elementType != null) && !(eType.IsAssignableFrom(elementType) || elementType.IsAssignableFrom(eType))) { @@ -171,7 +172,7 @@ private void InternalLoad(Type elementType, bool asAddress = false) if (CodeGenerator.IsNullableGenericType(memberType)) { ILG.LoadMemberAddress(MemberInfo); - ConvertNullableValue(memberType, elementType); + ConvertNullableValue(memberType, elementType!); } else { @@ -185,19 +186,19 @@ private void InternalLoad(Type elementType, bool asAddress = false) if (match.Success) { Debug.Assert(match.Groups["arg"].Value == Arg); - Debug.Assert(match.Groups["cast"].Value == CodeIdentifier.GetCSharpName(Type)); + Debug.Assert(match.Groups["cast"].Value == CodeIdentifier.GetCSharpName(Type!)); if (asAddress) - ILG.ConvertAddress(varType, Type); + ILG.ConvertAddress(varType, Type!); else - ILG.ConvertValue(varType, Type); - varType = Type; + ILG.ConvertValue(varType, Type!); + varType = Type!; } - Convert(varType, elementType, asAddress); + Convert(varType!, elementType, asAddress); } } } - private void Convert(Type sourceType, Type targetType, bool asAddress) + private void Convert(Type sourceType, Type? targetType, bool asAddress) { if (targetType != null) { @@ -217,7 +218,7 @@ private void ConvertNullableValue(Type nullableType, Type targetType) "get_Value", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ILG.Call(Nullable_get_Value); if (targetType != null) { @@ -231,25 +232,25 @@ public static implicit operator string(SourceInfo source) return source.Source; } - public static bool operator !=(SourceInfo a, SourceInfo b) + public static bool operator !=(SourceInfo? a, SourceInfo? b) { - if ((object)a != null) + if ((object?)a != null) return !a.Equals(b); - return (object)b != null; + return (object?)b != null; } - public static bool operator ==(SourceInfo a, SourceInfo b) + public static bool operator ==(SourceInfo? a, SourceInfo? b) { - if ((object)a != null) + if ((object?)a != null) return a.Equals(b); - return (object)b == null; + return (object?)b == null; } - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (obj == null) return Source == null; - SourceInfo info = obj as SourceInfo; + SourceInfo? info = obj as SourceInfo; if (info != null) return Source == info.Source; return false; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/TypeCode.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/TypeCode.cs index ccdd17406242fe..e980e75935be73 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/TypeCode.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/TypeCode.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/TypeExtensions.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/TypeExtensions.cs index 19db82bdb3b8d4..bde6ff093bd432 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/TypeExtensions.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/TypeExtensions.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; @@ -10,7 +11,7 @@ internal static class TypeExtensions { private const string ImplicitCastOperatorName = "op_Implicit"; - public static bool TryConvertTo(this Type targetType, object data, out object returnValue) + public static bool TryConvertTo(this Type targetType, object? data, out object? returnValue) { if (targetType == null) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Types.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Types.cs index db42b0d1f316d6..02739759f465d0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Types.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Types.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; @@ -66,22 +67,22 @@ internal class TypeDesc { private readonly string _name; private readonly string _fullName; - private string _cSharpName; - private TypeDesc _arrayElementTypeDesc; - private TypeDesc _arrayTypeDesc; - private TypeDesc _nullableTypeDesc; + private string? _cSharpName; + private TypeDesc? _arrayElementTypeDesc; + private TypeDesc? _arrayTypeDesc; + private TypeDesc? _nullableTypeDesc; private readonly TypeKind _kind; - private readonly XmlSchemaType _dataType; - private Type _type; - private TypeDesc _baseTypeDesc; + private readonly XmlSchemaType? _dataType; + private Type? _type; + private TypeDesc? _baseTypeDesc; private TypeFlags _flags; - private readonly string _formatterName; + private readonly string? _formatterName; private readonly bool _isXsdType; private bool _isMixed; private int _weight; - private Exception _exception; + private Exception? _exception; - internal TypeDesc(string name, string fullName, XmlSchemaType dataType, TypeKind kind, TypeDesc baseTypeDesc, TypeFlags flags, string formatterName) + internal TypeDesc(string name, string fullName, XmlSchemaType? dataType, TypeKind kind, TypeDesc? baseTypeDesc, TypeFlags flags, string? formatterName) { _name = name.Replace('+', '.'); _fullName = fullName.Replace('+', '.'); @@ -101,17 +102,17 @@ internal TypeDesc(string name, string fullName, XmlSchemaType dataType, TypeKind _formatterName = formatterName; } - internal TypeDesc(string name, string fullName, TypeKind kind, TypeDesc baseTypeDesc, TypeFlags flags) - : this(name, fullName, (XmlSchemaType)null, kind, baseTypeDesc, flags, null) + internal TypeDesc(string name, string fullName, TypeKind kind, TypeDesc? baseTypeDesc, TypeFlags flags) + : this(name, fullName, (XmlSchemaType?)null, kind, baseTypeDesc, flags, null) { } internal TypeDesc(Type type, bool isXsdType, XmlSchemaType dataType, string formatterName, TypeFlags flags) - : this(type.Name, type.FullName, dataType, TypeKind.Primitive, (TypeDesc)null, flags, formatterName) + : this(type!.Name, type.FullName!, dataType, TypeKind.Primitive, (TypeDesc?)null, flags, formatterName) { _isXsdType = isXsdType; _type = type; } - internal TypeDesc(Type type, string name, string fullName, TypeKind kind, TypeDesc baseTypeDesc, TypeFlags flags, TypeDesc arrayElementTypeDesc) + internal TypeDesc(Type? type, string name, string fullName, TypeKind kind, TypeDesc? baseTypeDesc, TypeFlags flags, TypeDesc? arrayElementTypeDesc) : this(name, fullName, null, kind, baseTypeDesc, flags, null) { _arrayElementTypeDesc = arrayElementTypeDesc; @@ -160,17 +161,17 @@ internal string CSharpName } } - internal XmlSchemaType DataType + internal XmlSchemaType? DataType { get { return _dataType; } } - internal Type Type + internal Type? Type { get { return _type; } } - internal string FormatterName + internal string? FormatterName { get { return _formatterName; } } @@ -341,7 +342,7 @@ internal bool ConstructorInaccessible get { return (_flags & TypeFlags.CtorInaccessible) != 0; } } - internal Exception Exception + internal Exception? Exception { get { return _exception; } set { _exception = value; } @@ -388,7 +389,7 @@ internal void CheckNeedConstructor() } } - internal TypeDesc ArrayElementTypeDesc + internal TypeDesc? ArrayElementTypeDesc { get { return _arrayElementTypeDesc; } set { _arrayElementTypeDesc = value; } @@ -406,7 +407,7 @@ internal TypeDesc CreateArrayTypeDesc() return _arrayTypeDesc; } - internal TypeDesc BaseTypeDesc + internal TypeDesc? BaseTypeDesc { get { return _baseTypeDesc; } set @@ -418,7 +419,7 @@ internal TypeDesc BaseTypeDesc internal bool IsDerivedFrom(TypeDesc baseTypeDesc) { - TypeDesc typeDesc = this; + TypeDesc? typeDesc = this; while (typeDesc != null) { if (typeDesc == baseTypeDesc) return true; @@ -427,10 +428,10 @@ internal bool IsDerivedFrom(TypeDesc baseTypeDesc) return baseTypeDesc.IsRoot; } - internal static TypeDesc FindCommonBaseTypeDesc(TypeDesc[] typeDescs) + internal static TypeDesc? FindCommonBaseTypeDesc(TypeDesc[] typeDescs) { if (typeDescs.Length == 0) return null; - TypeDesc leastDerivedTypeDesc = null; + TypeDesc? leastDerivedTypeDesc = null; int leastDerivedLevel = int.MaxValue; for (int i = 0; i < typeDescs.Length; i++) @@ -656,14 +657,14 @@ private static void AddSoapEncodedPrimitive(Type type, string dataTypeName, stri AddNonXsdPrimitive(type, dataTypeName, ns, formatterName, baseTypeName, Array.Empty(), flags); } - internal TypeDesc GetTypeDesc(string name, string ns) + internal TypeDesc? GetTypeDesc(string name, string ns) { return GetTypeDesc(name, ns, TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue | TypeFlags.CanBeAttributeValue); } - internal TypeDesc GetTypeDesc(string name, string ns, TypeFlags flags) + internal TypeDesc? GetTypeDesc(string name, string? ns, TypeFlags flags) { - TypeDesc typeDesc = (TypeDesc)s_primitiveNames[name, ns]; + TypeDesc? typeDesc = (TypeDesc?)s_primitiveNames[name, ns]; if (typeDesc != null) { if ((typeDesc.Flags & flags) != 0) @@ -674,9 +675,9 @@ internal TypeDesc GetTypeDesc(string name, string ns, TypeFlags flags) return null; } - internal TypeDesc GetTypeDesc(XmlSchemaSimpleType dataType) + internal TypeDesc? GetTypeDesc(XmlSchemaSimpleType dataType) { - return (TypeDesc)s_primitiveDataTypes[dataType]; + return (TypeDesc?)s_primitiveDataTypes[dataType]; } internal TypeDesc GetTypeDesc(Type type) @@ -684,21 +685,21 @@ internal TypeDesc GetTypeDesc(Type type) return GetTypeDesc(type, null, true, true); } - internal TypeDesc GetTypeDesc(Type type, MemberInfo source, bool directReference) + internal TypeDesc GetTypeDesc(Type type, MemberInfo? source, bool directReference) { return GetTypeDesc(type, source, directReference, true); } - internal TypeDesc GetTypeDesc(Type type, MemberInfo source, bool directReference, bool throwOnError) + internal TypeDesc GetTypeDesc(Type type, MemberInfo? source, bool directReference, bool throwOnError) { if (type.ContainsGenericParameters) { throw new InvalidOperationException(SR.Format(SR.XmlUnsupportedOpenGenericType, type)); } - TypeDesc typeDesc = (TypeDesc)s_primitiveTypes[type]; + TypeDesc? typeDesc = (TypeDesc?)s_primitiveTypes[type]; if (typeDesc == null) { - typeDesc = (TypeDesc)_typeDescs[type]; + typeDesc = (TypeDesc?)_typeDescs[type]; if (typeDesc == null) { typeDesc = ImportTypeDesc(type, source, directReference); @@ -713,7 +714,7 @@ internal TypeDesc GetTypeDesc(Type type, MemberInfo source, bool directReference internal TypeDesc GetArrayTypeDesc(Type type) { - TypeDesc typeDesc = (TypeDesc)_arrayTypeDescs[type]; + TypeDesc? typeDesc = (TypeDesc?)_arrayTypeDescs[type]; if (typeDesc == null) { typeDesc = GetTypeDesc(type); @@ -725,7 +726,7 @@ internal TypeDesc GetArrayTypeDesc(Type type) return typeDesc; } - internal TypeMapping GetTypeMappingFromTypeDesc(TypeDesc typeDesc) + internal TypeMapping? GetTypeMappingFromTypeDesc(TypeDesc typeDesc) { foreach (TypeMapping typeMapping in TypeMappings) { @@ -735,7 +736,7 @@ internal TypeMapping GetTypeMappingFromTypeDesc(TypeDesc typeDesc) return null; } - internal Type GetTypeFromTypeDesc(TypeDesc typeDesc) + internal Type? GetTypeFromTypeDesc(TypeDesc typeDesc) { if (typeDesc.Type != null) return typeDesc.Type; @@ -747,14 +748,14 @@ internal Type GetTypeFromTypeDesc(TypeDesc typeDesc) return null; } - private TypeDesc ImportTypeDesc(Type type, MemberInfo memberInfo, bool directReference) + private TypeDesc ImportTypeDesc(Type type, MemberInfo? memberInfo, bool directReference) { - TypeDesc typeDesc = null; + TypeDesc? typeDesc = null; TypeKind kind; - Type arrayElementType = null; - Type baseType = null; + Type? arrayElementType = null; + Type? baseType = null; TypeFlags flags = 0; - Exception exception = null; + Exception? exception = null; if (!type.IsVisible) { @@ -814,7 +815,7 @@ private TypeDesc ImportTypeDesc(Type type, MemberInfo memberInfo, bool directRef else if (typeof(ICollection).IsAssignableFrom(type) && !IsArraySegment(type)) { kind = TypeKind.Collection; - arrayElementType = GetCollectionElementType(type, memberInfo == null ? null : memberInfo.DeclaringType.FullName + "." + memberInfo.Name); + arrayElementType = GetCollectionElementType(type, memberInfo == null ? null : memberInfo.DeclaringType!.FullName + "." + memberInfo.Name); flags |= GetConstructorFlags(type, ref exception); } else if (type == typeof(XmlQualifiedName)) @@ -887,7 +888,7 @@ private TypeDesc ImportTypeDesc(Type type, MemberInfo memberInfo, bool directRef } else { - exception = new NotSupportedException(SR.Format(SR.XmlUnsupportedInterfaceDetails, memberInfo.DeclaringType.FullName + "." + memberInfo.Name, type.FullName)); + exception = new NotSupportedException(SR.Format(SR.XmlUnsupportedInterfaceDetails, memberInfo.DeclaringType!.FullName + "." + memberInfo.Name, type.FullName)); } } } @@ -948,7 +949,7 @@ private TypeDesc ImportTypeDesc(Type type, MemberInfo memberInfo, bool directRef } if (type.IsNestedPublic) { - for (Type t = type.DeclaringType; t != null && !t.ContainsGenericParameters && !(t.IsAbstract && t.IsSealed); t = t.DeclaringType) + for (Type? t = type.DeclaringType; t != null && !t.ContainsGenericParameters && !(t.IsAbstract && t.IsSealed); t = t.DeclaringType) GetTypeDesc(t, null, false); } return typeDesc; @@ -981,7 +982,7 @@ internal static string TypeName(Type t) { if (t.IsArray) { - return "ArrayOf" + TypeName(t.GetElementType()); + return "ArrayOf" + TypeName(t.GetElementType()!); } else if (t.IsGenericType) { @@ -1012,7 +1013,7 @@ internal static string TypeName(Type t) return t.Name; } - internal static Type GetArrayElementType(Type type, string memberInfo) + internal static Type? GetArrayElementType(Type type, string? memberInfo) { if (type.IsArray) return type.GetElementType(); @@ -1032,7 +1033,7 @@ internal static Type GetArrayElementType(Type type, string memberInfo) internal static MemberMapping[] GetAllMembers(StructMapping mapping) { if (mapping.BaseMapping == null) - return mapping.Members; + return mapping.Members!; ArrayList list = new ArrayList(); GetAllMembers(mapping, list); return (MemberMapping[])list.ToArray(typeof(MemberMapping)); @@ -1044,7 +1045,7 @@ internal static void GetAllMembers(StructMapping mapping, ArrayList list) { GetAllMembers(mapping.BaseMapping, list); } - for (int i = 0; i < mapping.Members.Length; i++) + for (int i = 0; i < mapping.Members!.Length; i++) { list.Add(mapping.Members[i]); } @@ -1075,9 +1076,9 @@ private static void GetSettableMembers(StructMapping mapping, ArrayList list) { foreach (MemberMapping memberMapping in mapping.Members) { - MemberInfo memberInfo = memberMapping.MemberInfo; - PropertyInfo propertyInfo = memberInfo as PropertyInfo; - if (propertyInfo != null && !CanWriteProperty(propertyInfo, memberMapping.TypeDesc)) + MemberInfo? memberInfo = memberMapping.MemberInfo; + PropertyInfo? propertyInfo = memberInfo as PropertyInfo; + if (propertyInfo != null && !CanWriteProperty(propertyInfo, memberMapping.TypeDesc!)) { throw new InvalidOperationException(SR.Format(SR.XmlReadOnlyPropertyError, propertyInfo.DeclaringType, propertyInfo.Name)); } @@ -1112,11 +1113,11 @@ private static void PopulateMemberInfos(StructMapping structMapping, MemberMappi memberInfos.Clear(); for (int i = 0; i < mappings.Length; ++i) { - memberInfos[mappings[i].Name] = mappings[i].MemberInfo; + memberInfos[mappings[i].Name] = mappings[i].MemberInfo!; if (mappings[i].ChoiceIdentifier != null) - memberInfos[mappings[i].ChoiceIdentifier.MemberName] = mappings[i].ChoiceIdentifier.MemberInfo; + memberInfos[mappings[i].ChoiceIdentifier!.MemberName!] = mappings[i].ChoiceIdentifier!.MemberInfo!; if (mappings[i].CheckSpecifiedMemberInfo != null) - memberInfos[mappings[i].Name + "Specified"] = mappings[i].CheckSpecifiedMemberInfo; + memberInfos[mappings[i].Name + "Specified"] = mappings[i].CheckSpecifiedMemberInfo!; } // The scenario here is that user has one base class A and one derived class B and wants to serialize/deserialize an object of B. @@ -1127,11 +1128,11 @@ private static void PopulateMemberInfos(StructMapping structMapping, MemberMappi // If so, replace the one on the base class with the one on the derived class. // 2) Do the same thing for the memberMapping array. Note that we need to create a new copy of MemberMapping object since the old one could still be referenced // by the StructMapping of the baseclass, so updating it directly could lead to other issues. - Dictionary replaceList = null; - MemberInfo replacedInfo = null; + Dictionary? replaceList = null; + MemberInfo? replacedInfo = null; foreach (KeyValuePair pair in memberInfos) { - if (ShouldBeReplaced(pair.Value, structMapping.TypeDesc.Type, out replacedInfo)) + if (ShouldBeReplaced(pair.Value, structMapping.TypeDesc!.Type!, out replacedInfo)) { if (replaceList == null) { @@ -1150,7 +1151,7 @@ private static void PopulateMemberInfos(StructMapping structMapping, MemberMappi } for (int i = 0; i < mappings.Length; i++) { - if (replaceList.TryGetValue(mappings[i].Name, out MemberInfo mi)) + if (replaceList.TryGetValue(mappings[i].Name, out MemberInfo? mi)) { MemberMapping newMapping = mappings[i].Clone(); newMapping.MemberInfo = mi; @@ -1164,7 +1165,7 @@ private static bool ShouldBeReplaced(MemberInfo memberInfoToBeReplaced, Type der { replacedInfo = memberInfoToBeReplaced; Type currentType = derivedType; - Type typeToBeReplaced = memberInfoToBeReplaced.DeclaringType; + Type typeToBeReplaced = memberInfoToBeReplaced.DeclaringType!; if (typeToBeReplaced.IsAssignableFrom(currentType)) { @@ -1180,9 +1181,9 @@ private static bool ShouldBeReplaced(MemberInfo memberInfoToBeReplaced, Type der replacedInfo = info; if (replacedInfo != memberInfoToBeReplaced) { - if (!info.GetMethod.IsPublic + if (!info.GetMethod!.IsPublic && memberInfoToBeReplaced is PropertyInfo - && ((PropertyInfo)memberInfoToBeReplaced).GetMethod.IsPublic + && ((PropertyInfo)memberInfoToBeReplaced).GetMethod!.IsPublic ) { break; @@ -1207,16 +1208,16 @@ private static bool ShouldBeReplaced(MemberInfo memberInfoToBeReplaced, Type der } // we go one level down and try again - currentType = currentType.BaseType; + currentType = currentType.BaseType!; } } return false; } - private static TypeFlags GetConstructorFlags(Type type, ref Exception exception) + private static TypeFlags GetConstructorFlags(Type type, ref Exception? exception) { - ConstructorInfo ctor = type.GetConstructor(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic, Array.Empty()); + ConstructorInfo? ctor = type.GetConstructor(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic, Array.Empty()); if (ctor != null) { TypeFlags flags = TypeFlags.HasDefaultConstructor; @@ -1239,11 +1240,11 @@ private static TypeFlags GetConstructorFlags(Type type, ref Exception exception) return 0; } - private static Type GetEnumeratorElementType(Type type, ref TypeFlags flags) + private static Type? GetEnumeratorElementType(Type type, ref TypeFlags flags) { if (typeof(IEnumerable).IsAssignableFrom(type)) { - MethodInfo enumerator = type.GetMethod("GetEnumerator", Array.Empty()); + MethodInfo? enumerator = type.GetMethod("GetEnumerator", Array.Empty()); if (enumerator == null || !typeof(IEnumerator).IsAssignableFrom(enumerator.ReturnType)) { @@ -1277,10 +1278,10 @@ private static Type GetEnumeratorElementType(Type type, ref TypeFlags flags) XmlAttributes methodAttrs = new XmlAttributes(enumerator); if (methodAttrs.XmlIgnore) return null; - PropertyInfo p = enumerator.ReturnType.GetProperty("Current"); + PropertyInfo? p = enumerator.ReturnType.GetProperty("Current"); Type currentType = (p == null ? typeof(object) : p.PropertyType); - MethodInfo addMethod = type.GetMethod("Add", new Type[] { currentType }); + MethodInfo? addMethod = type.GetMethod("Add", new Type[] { currentType }); if (addMethod == null && currentType != typeof(object)) { @@ -1299,7 +1300,7 @@ private static Type GetEnumeratorElementType(Type type, ref TypeFlags flags) } } - internal static PropertyInfo GetDefaultIndexer(Type type, string memberInfo) + internal static PropertyInfo GetDefaultIndexer(Type type, string? memberInfo) { if (typeof(IDictionary).IsAssignableFrom(type)) { @@ -1314,10 +1315,10 @@ internal static PropertyInfo GetDefaultIndexer(Type type, string memberInfo) } MemberInfo[] defaultMembers = type.GetDefaultMembers(); - PropertyInfo indexer = null; + PropertyInfo? indexer = null; if (defaultMembers != null && defaultMembers.Length > 0) { - for (Type t = type; t != null; t = t.BaseType) + for (Type? t = type; t != null; t = t.BaseType) { for (int i = 0; i < defaultMembers.Length; i++) { @@ -1326,7 +1327,7 @@ internal static PropertyInfo GetDefaultIndexer(Type type, string memberInfo) PropertyInfo defaultProp = (PropertyInfo)defaultMembers[i]; if (defaultProp.DeclaringType != t) continue; if (!defaultProp.CanRead) continue; - MethodInfo getMethod = defaultProp.GetMethod; + MethodInfo getMethod = defaultProp.GetMethod!; ParameterInfo[] parameters = getMethod.GetParameters(); if (parameters.Length == 1 && parameters[0].ParameterType == typeof(int)) { @@ -1342,19 +1343,19 @@ internal static PropertyInfo GetDefaultIndexer(Type type, string memberInfo) { throw new InvalidOperationException(SR.Format(SR.XmlNoDefaultAccessors, type.FullName)); } - MethodInfo addMethod = type.GetMethod("Add", new Type[] { indexer.PropertyType }); + MethodInfo? addMethod = type.GetMethod("Add", new Type[] { indexer.PropertyType }); if (addMethod == null) { throw new InvalidOperationException(SR.Format(SR.XmlNoAddMethod, type.FullName, indexer.PropertyType, "ICollection")); } return indexer; } - private static Type GetCollectionElementType(Type type, string memberInfo) + private static Type GetCollectionElementType(Type type, string? memberInfo) { return GetDefaultIndexer(type, memberInfo).PropertyType; } - internal static XmlQualifiedName ParseWsdlArrayType(string type, out string dims, XmlSchemaObject parent) + internal static XmlQualifiedName ParseWsdlArrayType(string type, out string dims, XmlSchemaObject? parent) { string ns; string name; @@ -1384,7 +1385,7 @@ internal static XmlQualifiedName ParseWsdlArrayType(string type, out string dims { if (parent.Namespaces != null) { - if (parent.Namespaces.Namespaces.TryGetValue(ns, out string wsdlNs) && wsdlNs != null) + if (parent.Namespaces.Namespaces.TryGetValue(ns, out string? wsdlNs) && wsdlNs != null) { ns = wsdlNs; break; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAnyAttributeAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAnyAttributeAttribute.cs index 8a1d0316bd616c..b57cbffc68df7a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAnyAttributeAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAnyAttributeAttribute.cs @@ -1,10 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; using System.Xml.Schema; - namespace System.Xml.Serialization { /// diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAnyElementAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAnyElementAttribute.cs index ee7d71dd895562..8c146c15abd881 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAnyElementAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAnyElementAttribute.cs @@ -1,10 +1,11 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; +using System.Diagnostics.CodeAnalysis; using System.Xml.Schema; - namespace System.Xml.Serialization { /// @@ -13,8 +14,8 @@ namespace System.Xml.Serialization [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true)] public class XmlAnyElementAttribute : System.Attribute { - private string _name; - private string _ns; + private string? _name; + private string? _ns; private int _order = -1; private bool _nsSpecified; @@ -28,7 +29,7 @@ public XmlAnyElementAttribute() /// /// [To be supplied.] /// - public XmlAnyElementAttribute(string name) + public XmlAnyElementAttribute(string? name) { _name = name; } @@ -36,7 +37,7 @@ public XmlAnyElementAttribute(string name) /// /// [To be supplied.] /// - public XmlAnyElementAttribute(string name, string ns) + public XmlAnyElementAttribute(string? name, string? ns) { _name = name; _ns = ns; @@ -46,6 +47,7 @@ public XmlAnyElementAttribute(string name, string ns) /// /// [To be supplied.] /// + [AllowNull] public string Name { get { return _name == null ? string.Empty : _name; } @@ -55,7 +57,7 @@ public string Name /// /// [To be supplied.] /// - public string Namespace + public string? Namespace { get { return _ns; } set diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAnyElementAttributes.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAnyElementAttributes.cs index 76b4216ce37c3f..ee3796482a3591 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAnyElementAttributes.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAnyElementAttributes.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; @@ -16,16 +17,16 @@ public class XmlAnyElementAttributes : CollectionBase /// /// [To be supplied.] /// - public XmlAnyElementAttribute this[int index] + public XmlAnyElementAttribute? this[int index] { - get { return (XmlAnyElementAttribute)List[index]; } + get { return (XmlAnyElementAttribute?)List[index]; } set { List[index] = value; } } /// /// [To be supplied.] /// - public int Add(XmlAnyElementAttribute attribute) + public int Add(XmlAnyElementAttribute? attribute) { return List.Add(attribute); } @@ -33,7 +34,7 @@ public int Add(XmlAnyElementAttribute attribute) /// /// [To be supplied.] /// - public void Insert(int index, XmlAnyElementAttribute attribute) + public void Insert(int index, XmlAnyElementAttribute? attribute) { List.Insert(index, attribute); } @@ -41,7 +42,7 @@ public void Insert(int index, XmlAnyElementAttribute attribute) /// /// [To be supplied.] /// - public int IndexOf(XmlAnyElementAttribute attribute) + public int IndexOf(XmlAnyElementAttribute? attribute) { return List.IndexOf(attribute); } @@ -49,7 +50,7 @@ public int IndexOf(XmlAnyElementAttribute attribute) /// /// [To be supplied.] /// - public bool Contains(XmlAnyElementAttribute attribute) + public bool Contains(XmlAnyElementAttribute? attribute) { return List.Contains(attribute); } @@ -57,7 +58,7 @@ public bool Contains(XmlAnyElementAttribute attribute) /// /// [To be supplied.] /// - public void Remove(XmlAnyElementAttribute attribute) + public void Remove(XmlAnyElementAttribute? attribute) { List.Remove(attribute); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlArrayAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlArrayAttribute.cs index a76a8cf2acceae..dec726faaf3904 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlArrayAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlArrayAttribute.cs @@ -1,10 +1,11 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; +using System.Diagnostics.CodeAnalysis; using System.Xml.Schema; - namespace System.Xml.Serialization { /// @@ -13,8 +14,8 @@ namespace System.Xml.Serialization [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = false)] public class XmlArrayAttribute : System.Attribute { - private string _elementName; - private string _ns; + private string? _elementName; + private string? _ns; private bool _nullable; private XmlSchemaForm _form = XmlSchemaForm.None; private int _order = -1; @@ -29,7 +30,7 @@ public XmlArrayAttribute() /// /// [To be supplied.] /// - public XmlArrayAttribute(string elementName) + public XmlArrayAttribute(string? elementName) { _elementName = elementName; } @@ -37,6 +38,7 @@ public XmlArrayAttribute(string elementName) /// /// [To be supplied.] /// + [AllowNull] public string ElementName { get { return _elementName == null ? string.Empty : _elementName; } @@ -46,7 +48,7 @@ public string ElementName /// /// [To be supplied.] /// - public string Namespace + public string? Namespace { get { return _ns; } set { _ns = value; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlArrayItemAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlArrayItemAttribute.cs index 31eb9de53e056e..b3bd0d98551212 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlArrayItemAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlArrayItemAttribute.cs @@ -1,10 +1,11 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; +using System.Diagnostics.CodeAnalysis; using System.Xml.Schema; - namespace System.Xml.Serialization { /// @@ -13,10 +14,10 @@ namespace System.Xml.Serialization [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true)] public class XmlArrayItemAttribute : System.Attribute { - private string _elementName; - private Type _type; - private string _ns; - private string _dataType; + private string? _elementName; + private Type? _type; + private string? _ns; + private string? _dataType; private bool _nullable; private bool _nullableSpecified; private XmlSchemaForm _form = XmlSchemaForm.None; @@ -32,7 +33,7 @@ public XmlArrayItemAttribute() /// /// [To be supplied.] /// - public XmlArrayItemAttribute(string elementName) + public XmlArrayItemAttribute(string? elementName) { _elementName = elementName; } @@ -40,7 +41,7 @@ public XmlArrayItemAttribute(string elementName) /// /// [To be supplied.] /// - public XmlArrayItemAttribute(Type type) + public XmlArrayItemAttribute(Type? type) { _type = type; } @@ -48,7 +49,7 @@ public XmlArrayItemAttribute(Type type) /// /// [To be supplied.] /// - public XmlArrayItemAttribute(string elementName, Type type) + public XmlArrayItemAttribute(string? elementName, Type? type) { _elementName = elementName; _type = type; @@ -57,7 +58,7 @@ public XmlArrayItemAttribute(string elementName, Type type) /// /// [To be supplied.] /// - public Type Type + public Type? Type { get { return _type; } set { _type = value; } @@ -66,6 +67,7 @@ public Type Type /// /// [To be supplied.] /// + [AllowNull] public string ElementName { get { return _elementName == null ? string.Empty : _elementName; } @@ -75,7 +77,7 @@ public string ElementName /// /// [To be supplied.] /// - public string Namespace + public string? Namespace { get { return _ns; } set { _ns = value; } @@ -90,6 +92,7 @@ public int NestingLevel /// /// [To be supplied.] /// + [AllowNull] public string DataType { get { return _dataType == null ? string.Empty : _dataType; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlArrayItemAttributes.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlArrayItemAttributes.cs index 21010185b35d31..dceec59f18997a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlArrayItemAttributes.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlArrayItemAttributes.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; @@ -16,16 +17,16 @@ public class XmlArrayItemAttributes : CollectionBase /// /// [To be supplied.] /// - public XmlArrayItemAttribute this[int index] + public XmlArrayItemAttribute? this[int index] { - get { return (XmlArrayItemAttribute)List[index]; } + get { return (XmlArrayItemAttribute?)List[index]; } set { List[index] = value; } } /// /// [To be supplied.] /// - public int Add(XmlArrayItemAttribute attribute) + public int Add(XmlArrayItemAttribute? attribute) { return List.Add(attribute); } @@ -33,7 +34,7 @@ public int Add(XmlArrayItemAttribute attribute) /// /// [To be supplied.] /// - public void Insert(int index, XmlArrayItemAttribute attribute) + public void Insert(int index, XmlArrayItemAttribute? attribute) { List.Insert(index, attribute); } @@ -41,7 +42,7 @@ public void Insert(int index, XmlArrayItemAttribute attribute) /// /// [To be supplied.] /// - public int IndexOf(XmlArrayItemAttribute attribute) + public int IndexOf(XmlArrayItemAttribute? attribute) { return List.IndexOf(attribute); } @@ -49,7 +50,7 @@ public int IndexOf(XmlArrayItemAttribute attribute) /// /// [To be supplied.] /// - public bool Contains(XmlArrayItemAttribute attribute) + public bool Contains(XmlArrayItemAttribute? attribute) { return List.Contains(attribute); } @@ -57,7 +58,7 @@ public bool Contains(XmlArrayItemAttribute attribute) /// /// [To be supplied.] /// - public void Remove(XmlArrayItemAttribute attribute) + public void Remove(XmlArrayItemAttribute? attribute) { List.Remove(attribute); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributeAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributeAttribute.cs index 797f9ecdf27076..a0b8eb7d9ad3ce 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributeAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributeAttribute.cs @@ -1,10 +1,11 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; +using System.Diagnostics.CodeAnalysis; using System.Xml.Schema; - namespace System.Xml.Serialization { /// @@ -13,10 +14,10 @@ namespace System.Xml.Serialization [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue)] public class XmlAttributeAttribute : System.Attribute { - private string _attributeName; - private Type _type; - private string _ns; - private string _dataType; + private string? _attributeName; + private Type? _type; + private string? _ns; + private string? _dataType; private XmlSchemaForm _form = XmlSchemaForm.None; /// @@ -29,7 +30,7 @@ public XmlAttributeAttribute() /// /// [To be supplied.] /// - public XmlAttributeAttribute(string attributeName) + public XmlAttributeAttribute(string? attributeName) { _attributeName = attributeName; } @@ -37,7 +38,7 @@ public XmlAttributeAttribute(string attributeName) /// /// [To be supplied.] /// - public XmlAttributeAttribute(Type type) + public XmlAttributeAttribute(Type? type) { _type = type; } @@ -45,7 +46,7 @@ public XmlAttributeAttribute(Type type) /// /// [To be supplied.] /// - public XmlAttributeAttribute(string attributeName, Type type) + public XmlAttributeAttribute(string? attributeName, Type? type) { _attributeName = attributeName; _type = type; @@ -54,7 +55,7 @@ public XmlAttributeAttribute(string attributeName, Type type) /// /// [To be supplied.] /// - public Type Type + public Type? Type { get { return _type; } set { _type = value; } @@ -63,6 +64,7 @@ public Type Type /// /// [To be supplied.] /// + [AllowNull] public string AttributeName { get { return _attributeName == null ? string.Empty : _attributeName; } @@ -72,7 +74,7 @@ public string AttributeName /// /// [To be supplied.] /// - public string Namespace + public string? Namespace { get { return _ns; } set { _ns = value; } @@ -81,6 +83,7 @@ public string Namespace /// /// [To be supplied.] /// + [AllowNull] public string DataType { get { return _dataType == null ? string.Empty : _dataType; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributeOverrides.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributeOverrides.cs index ddf4bdac2f7a6b..115a07e0d2589b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributeOverrides.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributeOverrides.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System.Reflection; @@ -16,7 +17,7 @@ namespace System.Xml.Serialization /// public class XmlAttributeOverrides { - private readonly Dictionary> _types = new Dictionary>(); + private readonly Dictionary> _types = new Dictionary>(); /// /// [To be supplied.] @@ -29,12 +30,12 @@ public void Add(Type type, XmlAttributes attributes) /// /// [To be supplied.] /// - public void Add(Type type, string member, XmlAttributes attributes) + public void Add(Type type, string member, XmlAttributes? attributes) { - Dictionary members; + Dictionary? members; if (!_types.TryGetValue(type, out members)) { - members = new Dictionary(); + members = new Dictionary(); _types.Add(type, members); } else if (members.ContainsKey(member)) @@ -47,7 +48,7 @@ public void Add(Type type, string member, XmlAttributes attributes) /// /// [To be supplied.] /// - public XmlAttributes this[Type type] + public XmlAttributes? this[Type type] { get { @@ -58,12 +59,12 @@ public XmlAttributes this[Type type] /// /// [To be supplied.] /// - public XmlAttributes this[Type type, string member] + public XmlAttributes? this[Type type, string member] { get { - Dictionary members; - XmlAttributes attributes; + Dictionary? members; + XmlAttributes? attributes; return _types.TryGetValue(type, out members) && members.TryGetValue(member, out attributes) ? attributes : null; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributes.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributes.cs index 0d10f57a94a72c..6c1e487b28ba86 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributes.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributes.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; @@ -35,18 +36,18 @@ public class XmlAttributes private readonly XmlElementAttributes _xmlElements = new XmlElementAttributes(); private readonly XmlArrayItemAttributes _xmlArrayItems = new XmlArrayItemAttributes(); private readonly XmlAnyElementAttributes _xmlAnyElements = new XmlAnyElementAttributes(); - private XmlArrayAttribute _xmlArray; - private XmlAttributeAttribute _xmlAttribute; - private XmlTextAttribute _xmlText; - private XmlEnumAttribute _xmlEnum; + private XmlArrayAttribute? _xmlArray; + private XmlAttributeAttribute? _xmlAttribute; + private XmlTextAttribute? _xmlText; + private XmlEnumAttribute? _xmlEnum; private bool _xmlIgnore; private bool _xmlns; - private object _xmlDefaultValue; - private XmlRootAttribute _xmlRoot; - private XmlTypeAttribute _xmlType; - private XmlAnyAttributeAttribute _xmlAnyAttribute; - private readonly XmlChoiceIdentifierAttribute _xmlChoiceIdentifier; - private static volatile Type s_ignoreAttributeType; + private object? _xmlDefaultValue; + private XmlRootAttribute? _xmlRoot; + private XmlTypeAttribute? _xmlType; + private XmlAnyAttributeAttribute? _xmlAnyAttribute; + private readonly XmlChoiceIdentifierAttribute? _xmlChoiceIdentifier; + private static volatile Type? s_ignoreAttributeType; /// @@ -101,7 +102,7 @@ public XmlAttributes(ICustomAttributeProvider provider) object[] attrs = provider.GetCustomAttributes(false); // most generic matches everything - XmlAnyElementAttribute wildcard = null; + XmlAnyElementAttribute? wildcard = null; for (int i = 0; i < attrs.Length; i++) { if (attrs[i] is XmlIgnoreAttribute || attrs[i] is ObsoleteAttribute || attrs[i].GetType() == IgnoreAttribute) @@ -195,7 +196,7 @@ public XmlAttributes(ICustomAttributeProvider provider) } } - internal static object GetAttr(MemberInfo memberInfo, Type attrType) + internal static object? GetAttr(MemberInfo memberInfo, Type attrType) { object[] attrs = memberInfo.GetCustomAttributes(attrType, false); if (attrs.Length == 0) return null; @@ -213,7 +214,7 @@ public XmlElementAttributes XmlElements /// /// [To be supplied.] /// - public XmlAttributeAttribute XmlAttribute + public XmlAttributeAttribute? XmlAttribute { get { return _xmlAttribute; } set { _xmlAttribute = value; } @@ -222,7 +223,7 @@ public XmlAttributeAttribute XmlAttribute /// /// [To be supplied.] /// - public XmlEnumAttribute XmlEnum + public XmlEnumAttribute? XmlEnum { get { return _xmlEnum; } set { _xmlEnum = value; } @@ -231,7 +232,7 @@ public XmlEnumAttribute XmlEnum /// /// [To be supplied.] /// - public XmlTextAttribute XmlText + public XmlTextAttribute? XmlText { get { return _xmlText; } set { _xmlText = value; } @@ -240,7 +241,7 @@ public XmlTextAttribute XmlText /// /// [To be supplied.] /// - public XmlArrayAttribute XmlArray + public XmlArrayAttribute? XmlArray { get { return _xmlArray; } set { _xmlArray = value; } @@ -257,7 +258,7 @@ public XmlArrayItemAttributes XmlArrayItems /// /// [To be supplied.] /// - public object XmlDefaultValue + public object? XmlDefaultValue { get { return _xmlDefaultValue; } set { _xmlDefaultValue = value; } @@ -275,7 +276,7 @@ public bool XmlIgnore /// /// [To be supplied.] /// - public XmlTypeAttribute XmlType + public XmlTypeAttribute? XmlType { get { return _xmlType; } set { _xmlType = value; } @@ -284,7 +285,7 @@ public XmlTypeAttribute XmlType /// /// [To be supplied.] /// - public XmlRootAttribute XmlRoot + public XmlRootAttribute? XmlRoot { get { return _xmlRoot; } set { _xmlRoot = value; } @@ -301,13 +302,13 @@ public XmlAnyElementAttributes XmlAnyElements /// /// [To be supplied.] /// - public XmlAnyAttributeAttribute XmlAnyAttribute + public XmlAnyAttributeAttribute? XmlAnyAttribute { get { return _xmlAnyAttribute; } set { _xmlAnyAttribute = value; } } - public XmlChoiceIdentifierAttribute XmlChoiceIdentifier + public XmlChoiceIdentifierAttribute? XmlChoiceIdentifier { get { return _xmlChoiceIdentifier; } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlChoiceIdentifierAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlChoiceIdentifierAttribute.cs index de9965ef658744..982badde112fad 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlChoiceIdentifierAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlChoiceIdentifierAttribute.cs @@ -1,10 +1,11 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; using System.Xml.Schema; using System.Reflection; - +using System.Diagnostics.CodeAnalysis; namespace System.Xml.Serialization { @@ -14,8 +15,8 @@ namespace System.Xml.Serialization [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = false)] public class XmlChoiceIdentifierAttribute : System.Attribute { - private string _name; - private MemberInfo _memberInfo; + private string? _name; + private MemberInfo? _memberInfo; /// /// [To be supplied.] @@ -27,7 +28,7 @@ public XmlChoiceIdentifierAttribute() /// /// [To be supplied.] /// - public XmlChoiceIdentifierAttribute(string name) + public XmlChoiceIdentifierAttribute(string? name) { _name = name; } @@ -35,24 +36,25 @@ public XmlChoiceIdentifierAttribute(string name) /// /// [To be supplied.] /// + [AllowNull] public string MemberName { get { return _name == null ? string.Empty : _name; } set { _name = value; } } - internal MemberInfo MemberInfo + internal MemberInfo? MemberInfo { get { return _memberInfo; } set { _memberInfo = value; } } - internal MemberInfo GetMemberInfo() + internal MemberInfo? GetMemberInfo() { return MemberInfo; } - internal void SetMemberInfo(MemberInfo memberInfo) + internal void SetMemberInfo(MemberInfo? memberInfo) { MemberInfo = memberInfo; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlElementAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlElementAttribute.cs index b2304321eb5a68..a809fb7ea6ca83 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlElementAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlElementAttribute.cs @@ -1,10 +1,11 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; +using System.Diagnostics.CodeAnalysis; using System.Xml.Schema; - namespace System.Xml.Serialization { /// @@ -13,10 +14,10 @@ namespace System.Xml.Serialization [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true)] public class XmlElementAttribute : System.Attribute { - private string _elementName; - private Type _type; - private string _ns; - private string _dataType; + private string? _elementName; + private Type? _type; + private string? _ns; + private string? _dataType; private bool _nullable; private bool _nullableSpecified; private XmlSchemaForm _form = XmlSchemaForm.None; @@ -32,7 +33,7 @@ public XmlElementAttribute() /// /// [To be supplied.] /// - public XmlElementAttribute(string elementName) + public XmlElementAttribute(string? elementName) { _elementName = elementName; } @@ -40,7 +41,7 @@ public XmlElementAttribute(string elementName) /// /// [To be supplied.] /// - public XmlElementAttribute(Type type) + public XmlElementAttribute(Type? type) { _type = type; } @@ -48,7 +49,7 @@ public XmlElementAttribute(Type type) /// /// [To be supplied.] /// - public XmlElementAttribute(string elementName, Type type) + public XmlElementAttribute(string? elementName, Type? type) { _elementName = elementName; _type = type; @@ -57,7 +58,7 @@ public XmlElementAttribute(string elementName, Type type) /// /// [To be supplied.] /// - public Type Type + public Type? Type { get { return _type; } set { _type = value; } @@ -66,6 +67,7 @@ public Type Type /// /// [To be supplied.] /// + [AllowNull] public string ElementName { get { return _elementName == null ? string.Empty : _elementName; } @@ -75,7 +77,7 @@ public string ElementName /// /// [To be supplied.] /// - public string Namespace + public string? Namespace { get { return _ns; } set { _ns = value; } @@ -84,6 +86,7 @@ public string Namespace /// /// [To be supplied.] /// + [AllowNull] public string DataType { get { return _dataType == null ? string.Empty : _dataType; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlElementAttributes.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlElementAttributes.cs index 794623f9853c8a..92392568b2dee1 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlElementAttributes.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlElementAttributes.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; @@ -16,16 +17,16 @@ public class XmlElementAttributes : CollectionBase /// /// [To be supplied.] /// - public XmlElementAttribute this[int index] + public XmlElementAttribute? this[int index] { - get { return (XmlElementAttribute)List[index]; } + get { return (XmlElementAttribute?)List[index]; } set { List[index] = value; } } /// /// [To be supplied.] /// - public int Add(XmlElementAttribute attribute) + public int Add(XmlElementAttribute? attribute) { return List.Add(attribute); } @@ -33,7 +34,7 @@ public int Add(XmlElementAttribute attribute) /// /// [To be supplied.] /// - public void Insert(int index, XmlElementAttribute attribute) + public void Insert(int index, XmlElementAttribute? attribute) { List.Insert(index, attribute); } @@ -41,7 +42,7 @@ public void Insert(int index, XmlElementAttribute attribute) /// /// [To be supplied.] /// - public int IndexOf(XmlElementAttribute attribute) + public int IndexOf(XmlElementAttribute? attribute) { return List.IndexOf(attribute); } @@ -49,7 +50,7 @@ public int IndexOf(XmlElementAttribute attribute) /// /// [To be supplied.] /// - public bool Contains(XmlElementAttribute attribute) + public bool Contains(XmlElementAttribute? attribute) { return List.Contains(attribute); } @@ -57,7 +58,7 @@ public bool Contains(XmlElementAttribute attribute) /// /// [To be supplied.] /// - public void Remove(XmlElementAttribute attribute) + public void Remove(XmlElementAttribute? attribute) { List.Remove(attribute); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlEnumAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlEnumAttribute.cs index 57065628bb2fe8..340c39353f9e2b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlEnumAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlEnumAttribute.cs @@ -1,9 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; - namespace System.Xml.Serialization { /// @@ -12,7 +12,7 @@ namespace System.Xml.Serialization [AttributeUsage(AttributeTargets.Field)] public class XmlEnumAttribute : System.Attribute { - private string _name; + private string? _name; /// /// [To be supplied.] @@ -24,7 +24,7 @@ public XmlEnumAttribute() /// /// [To be supplied.] /// - public XmlEnumAttribute(string name) + public XmlEnumAttribute(string? name) { _name = name; } @@ -32,7 +32,7 @@ public XmlEnumAttribute(string name) /// /// [To be supplied.] /// - public string Name + public string? Name { get { return _name; } set { _name = value; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlIgnoreAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlIgnoreAttribute.cs index f6526835f9e64c..6d1fd60586a3ea 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlIgnoreAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlIgnoreAttribute.cs @@ -1,9 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; - namespace System.Xml.Serialization { /// diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlIncludeAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlIncludeAttribute.cs index fd41d5e1a27e92..7993b4084ecfba 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlIncludeAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlIncludeAttribute.cs @@ -1,9 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; - namespace System.Xml.Serialization { /// @@ -12,12 +12,12 @@ namespace System.Xml.Serialization [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Method, AllowMultiple = true)] public class XmlIncludeAttribute : System.Attribute { - private Type _type; + private Type? _type; /// /// [To be supplied.] /// - public XmlIncludeAttribute(Type type) + public XmlIncludeAttribute(Type? type) { _type = type; } @@ -25,7 +25,7 @@ public XmlIncludeAttribute(Type type) /// /// [To be supplied.] /// - public Type Type + public Type? Type { get { return _type; } set { _type = value; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlMapping.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlMapping.cs index cdf16b04f52573..93d6a0c63a8863 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlMapping.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlMapping.cs @@ -1,13 +1,13 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; using System.ComponentModel; using System.Globalization; using System.Reflection; using System.Xml.Serialization; - namespace System.Xml.Serialization { [Flags] @@ -24,19 +24,19 @@ public enum XmlMappingAccess /// public abstract class XmlMapping { - private readonly TypeScope _scope; + private readonly TypeScope? _scope; private bool _generateSerializer; private bool _isSoap; private readonly ElementAccessor _accessor; - private string _key; + private string? _key; private readonly bool _shallow; private readonly XmlMappingAccess _access; - internal XmlMapping(TypeScope scope, ElementAccessor accessor) : this(scope, accessor, XmlMappingAccess.Read | XmlMappingAccess.Write) + internal XmlMapping(TypeScope? scope, ElementAccessor accessor) : this(scope, accessor, XmlMappingAccess.Read | XmlMappingAccess.Write) { } - internal XmlMapping(TypeScope scope, ElementAccessor accessor, XmlMappingAccess access) + internal XmlMapping(TypeScope? scope, ElementAccessor accessor, XmlMappingAccess access) { _scope = scope; _accessor = accessor; @@ -49,7 +49,7 @@ internal ElementAccessor Accessor get { return _accessor; } } - internal TypeScope Scope + internal TypeScope? Scope { get { return _scope; } } @@ -73,7 +73,7 @@ public string XsdElementName /// /// [To be supplied.] /// - public string Namespace + public string? Namespace { get { return _accessor.Namespace; } } @@ -101,27 +101,28 @@ internal bool IsSoap } /// - public void SetKey(string key) + public void SetKey(string? key) { SetKeyInternal(key); } /// - internal void SetKeyInternal(string key) + internal void SetKeyInternal(string? key) { _key = key; } - internal static string GenerateKey(Type type, XmlRootAttribute root, string ns) + internal static string GenerateKey(Type type, XmlRootAttribute? root, string? ns) { if (root == null) { - root = (XmlRootAttribute)XmlAttributes.GetAttr(type, typeof(XmlRootAttribute)); + root = (XmlRootAttribute?)XmlAttributes.GetAttr(type, typeof(XmlRootAttribute)); } return type.FullName + ":" + (root == null ? string.Empty : root.GetKey()) + ":" + (ns == null ? string.Empty : ns); } - internal string Key { get { return _key; } } + internal string? Key { get { return _key; } } + internal void CheckShallow() { if (_shallow) @@ -129,6 +130,7 @@ internal void CheckShallow() throw new InvalidOperationException(SR.XmlMelformMapping); } } + internal static bool IsShallow(XmlMapping[] mappings) { for (int i = 0; i < mappings.Length; i++) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlMemberMapping.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlMemberMapping.cs index 9b89b94237e24d..6abcd9cc90d507 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlMemberMapping.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlMemberMapping.cs @@ -1,10 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System.Reflection; using System; - namespace System.Xml.Serialization { /// @@ -22,14 +22,14 @@ internal MemberMapping Mapping get { return _mapping; } } - internal Accessor Accessor + internal Accessor? Accessor { get { return _mapping.Accessor; } } public bool Any { - get { return Accessor.Any; } + get { return Accessor!.Any; } } /// @@ -37,7 +37,7 @@ public bool Any /// public string ElementName { - get { return Accessor.UnescapeName(Accessor.Name); } + get { return Accessor.UnescapeName(Accessor!.Name); } } /// @@ -45,15 +45,15 @@ public string ElementName /// public string XsdElementName { - get { return Accessor.Name; } + get { return Accessor!.Name; } } /// /// [To be supplied.] /// - public string Namespace + public string? Namespace { - get { return Accessor.Namespace; } + get { return Accessor!.Namespace; } } /// @@ -67,17 +67,17 @@ public string MemberName /// /// [To be supplied.] /// - public string TypeName + public string? TypeName { - get { return Accessor.Mapping != null ? Accessor.Mapping.TypeName : string.Empty; } + get { return Accessor!.Mapping != null ? Accessor.Mapping.TypeName : string.Empty; } } /// /// [To be supplied.] /// - public string TypeNamespace + public string? TypeNamespace { - get { return Accessor.Mapping != null ? Accessor.Mapping.Namespace : null; } + get { return Accessor!.Mapping != null ? Accessor.Mapping.Namespace : null; } } /// @@ -85,7 +85,7 @@ public string TypeNamespace /// public string TypeFullName { - get { return _mapping.TypeDesc.FullName; } + get { return _mapping.TypeDesc!.FullName; } } /// diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlMembersMapping.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlMembersMapping.cs index ce8ba4ae0b1ef8..21fbe9afa9dffa 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlMembersMapping.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlMembersMapping.cs @@ -1,11 +1,11 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System.Reflection; using System; using System.Text; - namespace System.Xml.Serialization { /// @@ -18,15 +18,15 @@ public class XmlMembersMapping : XmlMapping internal XmlMembersMapping(TypeScope scope, ElementAccessor accessor, XmlMappingAccess access) : base(scope, accessor, access) { - MembersMapping mapping = (MembersMapping)accessor.Mapping; + MembersMapping mapping = (MembersMapping)accessor.Mapping!; StringBuilder key = new StringBuilder(); key.Append(':'); - _mappings = new XmlMemberMapping[mapping.Members.Length]; + _mappings = new XmlMemberMapping[mapping.Members!.Length]; for (int i = 0; i < _mappings.Length; i++) { - if (mapping.Members[i].TypeDesc.Type != null) + if (mapping.Members[i].TypeDesc!.Type != null) { - key.Append(GenerateKey(mapping.Members[i].TypeDesc.Type, null, null)); + key.Append(GenerateKey(mapping.Members[i].TypeDesc!.Type!, null, null)); key.Append(':'); } _mappings[i] = new XmlMemberMapping(mapping.Members[i]); @@ -37,17 +37,17 @@ internal XmlMembersMapping(TypeScope scope, ElementAccessor accessor, XmlMapping /// /// [To be supplied.] /// - public string TypeName + public string? TypeName { - get { return Accessor.Mapping.TypeName; } + get { return Accessor.Mapping!.TypeName; } } /// /// [To be supplied.] /// - public string TypeNamespace + public string? TypeNamespace { - get { return Accessor.Mapping.Namespace; } + get { return Accessor.Mapping!.Namespace; } } /// diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlNamespaceDeclarationsAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlNamespaceDeclarationsAttribute.cs index 34baf124fb383c..8f0bf641bbd986 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlNamespaceDeclarationsAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlNamespaceDeclarationsAttribute.cs @@ -1,10 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; using System.Xml.Schema; - namespace System.Xml.Serialization { /// diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs index 790ad1cce877c9..3fd048f33fab3f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System.Reflection; @@ -28,16 +29,16 @@ public class XmlReflectionImporter private readonly NameTable _types = new NameTable(); // xmltypename + xmlns -> Mapping private readonly NameTable _nullables = new NameTable(); // xmltypename + xmlns -> NullableMapping private readonly NameTable _elements = new NameTable(); // xmlelementname + xmlns -> ElementAccessor - private NameTable _xsdAttributes; // xmlattributetname + xmlns -> AttributeAccessor - private Hashtable _specials; // type -> SpecialMapping + private NameTable? _xsdAttributes; // xmlattributetname + xmlns -> AttributeAccessor + private Hashtable? _specials; // type -> SpecialMapping private readonly Hashtable _anonymous = new Hashtable(); // type -> AnonymousMapping - private NameTable _serializables; // type name --> new SerializableMapping - private StructMapping _root; + private NameTable? _serializables; // type name --> new SerializableMapping + private StructMapping? _root; private readonly string _defaultNs; private readonly ModelScope _modelScope; private int _arrayNestingLevel; - private XmlArrayItemAttributes _savedArrayItemAttributes; - private string _savedArrayNamespace; + private XmlArrayItemAttributes? _savedArrayItemAttributes; + private string? _savedArrayNamespace; private int _choiceNum = 1; private enum ImportContext @@ -57,21 +58,21 @@ public XmlReflectionImporter() : this(null, null) /// /// [To be supplied.] /// - public XmlReflectionImporter(string defaultNamespace) : this(null, defaultNamespace) + public XmlReflectionImporter(string? defaultNamespace) : this(null, defaultNamespace) { } /// /// [To be supplied.] /// - public XmlReflectionImporter(XmlAttributeOverrides attributeOverrides) : this(attributeOverrides, null) + public XmlReflectionImporter(XmlAttributeOverrides? attributeOverrides) : this(attributeOverrides, null) { } /// /// [To be supplied.] /// - public XmlReflectionImporter(XmlAttributeOverrides attributeOverrides, string defaultNamespace) + public XmlReflectionImporter(XmlAttributeOverrides? attributeOverrides, string? defaultNamespace) { if (defaultNamespace == null) defaultNamespace = string.Empty; @@ -96,7 +97,7 @@ private void IncludeTypes(ICustomAttributeProvider provider, RecursionLimiter li object[] attrs = provider.GetCustomAttributes(typeof(XmlIncludeAttribute), false); for (int i = 0; i < attrs.Length; i++) { - Type type = ((XmlIncludeAttribute)attrs[i]).Type; + Type type = ((XmlIncludeAttribute)attrs[i]).Type!; IncludeType(type, limiter); } } @@ -112,14 +113,14 @@ public void IncludeType(Type type) private void IncludeType(Type type, RecursionLimiter limiter) { int previousNestingLevel = _arrayNestingLevel; - XmlArrayItemAttributes previousArrayItemAttributes = _savedArrayItemAttributes; - string previousArrayNamespace = _savedArrayNamespace; + XmlArrayItemAttributes? previousArrayItemAttributes = _savedArrayItemAttributes; + string? previousArrayNamespace = _savedArrayNamespace; _arrayNestingLevel = 0; _savedArrayItemAttributes = null; _savedArrayNamespace = null; TypeMapping mapping = ImportTypeMapping(_modelScope.GetTypeModel(type), _defaultNs, ImportContext.Element, string.Empty, null, limiter); - if (mapping.IsAnonymousType && !mapping.TypeDesc.IsSpecial) + if (mapping.IsAnonymousType && !mapping.TypeDesc!.IsSpecial) { //XmlAnonymousInclude=Cannot include anonymous type '{0}'. throw new InvalidOperationException(SR.Format(SR.XmlAnonymousInclude, type.FullName)); @@ -140,7 +141,7 @@ public XmlTypeMapping ImportTypeMapping(Type type) /// /// [To be supplied.] /// - public XmlTypeMapping ImportTypeMapping(Type type, string defaultNamespace) + public XmlTypeMapping ImportTypeMapping(Type type, string? defaultNamespace) { return ImportTypeMapping(type, null, defaultNamespace); } @@ -148,7 +149,7 @@ public XmlTypeMapping ImportTypeMapping(Type type, string defaultNamespace) /// /// [To be supplied.] /// - public XmlTypeMapping ImportTypeMapping(Type type, XmlRootAttribute root) + public XmlTypeMapping ImportTypeMapping(Type type, XmlRootAttribute? root) { return ImportTypeMapping(type, root, null); } @@ -156,7 +157,7 @@ public XmlTypeMapping ImportTypeMapping(Type type, XmlRootAttribute root) /// /// [To be supplied.] /// - public XmlTypeMapping ImportTypeMapping(Type type, XmlRootAttribute root, string defaultNamespace) + public XmlTypeMapping ImportTypeMapping(Type type, XmlRootAttribute? root, string? defaultNamespace) { if (type == null) throw new ArgumentNullException(nameof(type)); @@ -169,7 +170,7 @@ public XmlTypeMapping ImportTypeMapping(Type type, XmlRootAttribute root, string /// /// [To be supplied.] /// - public XmlMembersMapping ImportMembersMapping(string elementName, string ns, XmlReflectionMember[] members, bool hasWrapperElement) + public XmlMembersMapping ImportMembersMapping(string? elementName, string? ns, XmlReflectionMember[] members, bool hasWrapperElement) { return ImportMembersMapping(elementName, ns, members, hasWrapperElement, false); } @@ -177,7 +178,7 @@ public XmlMembersMapping ImportMembersMapping(string elementName, string ns, Xml /// /// [To be supplied.] /// - public XmlMembersMapping ImportMembersMapping(string elementName, string ns, XmlReflectionMember[] members, bool hasWrapperElement, bool rpc) + public XmlMembersMapping ImportMembersMapping(string? elementName, string? ns, XmlReflectionMember[] members, bool hasWrapperElement, bool rpc) { return ImportMembersMapping(elementName, ns, members, hasWrapperElement, rpc, false); } @@ -186,7 +187,7 @@ public XmlMembersMapping ImportMembersMapping(string elementName, string ns, Xml /// [To be supplied.] /// /// - public XmlMembersMapping ImportMembersMapping(string elementName, string ns, XmlReflectionMember[] members, bool hasWrapperElement, bool rpc, bool openModel) + public XmlMembersMapping ImportMembersMapping(string? elementName, string? ns, XmlReflectionMember[] members, bool hasWrapperElement, bool rpc, bool openModel) { return ImportMembersMapping(elementName, ns, members, hasWrapperElement, rpc, openModel, XmlMappingAccess.Read | XmlMappingAccess.Write); } @@ -195,7 +196,7 @@ public XmlMembersMapping ImportMembersMapping(string elementName, string ns, Xml /// [To be supplied.] /// /// - public XmlMembersMapping ImportMembersMapping(string elementName, string ns, XmlReflectionMember[] members, bool hasWrapperElement, bool rpc, bool openModel, XmlMappingAccess access) + public XmlMembersMapping ImportMembersMapping(string? elementName, string? ns, XmlReflectionMember[] members, bool hasWrapperElement, bool rpc, bool openModel, XmlMappingAccess access) { ElementAccessor element = new ElementAccessor(); element.Name = elementName == null || elementName.Length == 0 ? elementName : XmlConvert.EncodeLocalName(elementName); @@ -210,7 +211,7 @@ public XmlMembersMapping ImportMembersMapping(string elementName, string ns, Xml element = (ElementAccessor)ReconcileAccessor(element, _elements); else { - foreach (MemberMapping mapping in membersMapping.Members) + foreach (MemberMapping mapping in membersMapping.Members!) { if (mapping.Elements != null && mapping.Elements.Length > 0) { @@ -226,7 +227,7 @@ public XmlMembersMapping ImportMembersMapping(string elementName, string ns, Xml private XmlAttributes GetAttributes(Type type, bool canBeSimpleType) { - XmlAttributes attrs = _attributeOverrides[type]; + XmlAttributes? attrs = _attributeOverrides[type]; if (attrs != null) return attrs; if (canBeSimpleType && TypeScope.IsKnownType(type)) { @@ -237,18 +238,18 @@ private XmlAttributes GetAttributes(Type type, bool canBeSimpleType) private XmlAttributes GetAttributes(MemberInfo memberInfo) { - XmlAttributes attrs = _attributeOverrides[memberInfo.DeclaringType, memberInfo.Name]; + XmlAttributes? attrs = _attributeOverrides[memberInfo.DeclaringType!, memberInfo.Name]; if (attrs != null) return attrs; return new XmlAttributes(memberInfo); } - private ElementAccessor ImportElement(TypeModel model, XmlRootAttribute root, string defaultNamespace, RecursionLimiter limiter) + private ElementAccessor ImportElement(TypeModel model, XmlRootAttribute? root, string? defaultNamespace, RecursionLimiter limiter) { XmlAttributes a = GetAttributes(model.Type, true); if (root == null) root = a.XmlRoot; - string ns = root == null ? null : root.Namespace; + string? ns = root == null ? null : root.Namespace; if (ns == null) ns = defaultNamespace; if (ns == null) ns = _defaultNs; @@ -263,9 +264,9 @@ private ElementAccessor ImportElement(TypeModel model, XmlRootAttribute root, st element.Name = XmlConvert.EncodeLocalName(root.ElementName); if (root.GetIsNullableSpecified() && !root.IsNullable && model.TypeDesc.IsOptionalValue) //XmlInvalidNotNullable=IsNullable may not be set to 'false' for a Nullable<{0}> type. Consider using '{0}' type or removing the IsNullable property from the XmlElement attribute. - throw new InvalidOperationException(SR.Format(SR.XmlInvalidNotNullable, model.TypeDesc.BaseTypeDesc.FullName, "XmlRoot")); + throw new InvalidOperationException(SR.Format(SR.XmlInvalidNotNullable, model.TypeDesc.BaseTypeDesc!.FullName, "XmlRoot")); element.IsNullable = root.GetIsNullableSpecified() ? root.IsNullable : model.TypeDesc.IsNullable || model.TypeDesc.IsOptionalValue; - CheckNullable(element.IsNullable, model.TypeDesc, element.Mapping); + CheckNullable(element.IsNullable, model.TypeDesc, element.Mapping!); } else element.IsNullable = model.TypeDesc.IsNullable || model.TypeDesc.IsOptionalValue; @@ -278,12 +279,12 @@ private static string GetMappingName(Mapping mapping) if (mapping is MembersMapping) return "(method)"; else if (mapping is TypeMapping) - return ((TypeMapping)mapping).TypeDesc.FullName; + return ((TypeMapping)mapping).TypeDesc!.FullName; else throw new ArgumentException(SR.XmlInternalError, nameof(mapping)); } - private ElementAccessor ReconcileLocalAccessor(ElementAccessor accessor, string ns) + private ElementAccessor ReconcileLocalAccessor(ElementAccessor accessor, string? ns) { if (accessor.Namespace == ns) return accessor; return (ElementAccessor)ReconcileAccessor(accessor, _elements); @@ -294,7 +295,7 @@ private Accessor ReconcileAccessor(Accessor accessor, NameTable accessors) if (accessor.Any && accessor.Name.Length == 0) return accessor; - Accessor existing = (Accessor)accessors[accessor.Name, accessor.Namespace]; + Accessor? existing = (Accessor?)accessors[accessor.Name, accessor.Namespace]; if (existing == null) { accessor.IsTopLevelInSchema = true; @@ -307,13 +308,13 @@ private Accessor ReconcileAccessor(Accessor accessor, NameTable accessors) if (!(accessor.Mapping is MembersMapping) && !(existing.Mapping is MembersMapping)) { - if (accessor.Mapping.TypeDesc == existing.Mapping.TypeDesc - || (existing.Mapping is NullableMapping && accessor.Mapping.TypeDesc == ((NullableMapping)existing.Mapping).BaseMapping.TypeDesc) - || (accessor.Mapping is NullableMapping && ((NullableMapping)accessor.Mapping).BaseMapping.TypeDesc == existing.Mapping.TypeDesc)) + if (accessor.Mapping!.TypeDesc == existing.Mapping!.TypeDesc + || (existing.Mapping is NullableMapping && accessor.Mapping.TypeDesc == ((NullableMapping)existing.Mapping).BaseMapping!.TypeDesc) + || (accessor.Mapping is NullableMapping && ((NullableMapping)accessor.Mapping).BaseMapping!.TypeDesc == existing.Mapping.TypeDesc)) { // need to compare default values - string value1 = Convert.ToString(accessor.Default, CultureInfo.InvariantCulture); - string value2 = Convert.ToString(existing.Default, CultureInfo.InvariantCulture); + string? value1 = Convert.ToString(accessor.Default, CultureInfo.InvariantCulture); + string? value2 = Convert.ToString(existing.Default, CultureInfo.InvariantCulture); if (value1 == value2) { return existing; @@ -329,11 +330,11 @@ private Accessor ReconcileAccessor(Accessor accessor, NameTable accessors) { if (!(existing.Mapping is ArrayMapping)) { - throw new InvalidOperationException(SR.Format(SR.XmlCannotReconcileAccessor, accessor.Name, accessor.Namespace, GetMappingName(existing.Mapping), GetMappingName(accessor.Mapping))); + throw new InvalidOperationException(SR.Format(SR.XmlCannotReconcileAccessor, accessor.Name, accessor.Namespace, GetMappingName(existing.Mapping!), GetMappingName(accessor.Mapping))); } ArrayMapping mapping = (ArrayMapping)accessor.Mapping; - ArrayMapping existingMapping = mapping.IsAnonymousType ? null : (ArrayMapping)_types[existing.Mapping.TypeName, existing.Mapping.Namespace]; - ArrayMapping first = existingMapping; + ArrayMapping? existingMapping = mapping.IsAnonymousType ? null : (ArrayMapping?)_types[existing.Mapping.TypeName!, existing.Mapping.Namespace]; + ArrayMapping? first = existingMapping; while (existingMapping != null) { if (existingMapping == accessor.Mapping) @@ -342,13 +343,13 @@ private Accessor ReconcileAccessor(Accessor accessor, NameTable accessors) } mapping.Next = first; if (!mapping.IsAnonymousType) - _types[existing.Mapping.TypeName, existing.Mapping.Namespace] = mapping; + _types[existing.Mapping.TypeName!, existing.Mapping.Namespace] = mapping; return existing; } if (accessor is AttributeAccessor) - throw new InvalidOperationException(SR.Format(SR.XmlCannotReconcileAttributeAccessor, accessor.Name, accessor.Namespace, GetMappingName(existing.Mapping), GetMappingName(accessor.Mapping))); + throw new InvalidOperationException(SR.Format(SR.XmlCannotReconcileAttributeAccessor, accessor.Name, accessor.Namespace, GetMappingName(existing.Mapping!), GetMappingName(accessor.Mapping!))); else - throw new InvalidOperationException(SR.Format(SR.XmlCannotReconcileAccessor, accessor.Name, accessor.Namespace, GetMappingName(existing.Mapping), GetMappingName(accessor.Mapping))); + throw new InvalidOperationException(SR.Format(SR.XmlCannotReconcileAccessor, accessor.Name, accessor.Namespace, GetMappingName(existing.Mapping!), GetMappingName(accessor.Mapping!))); } private Exception CreateReflectionException(string context, Exception e) @@ -366,23 +367,23 @@ private Exception CreateMemberReflectionException(FieldModel model, Exception e) return new InvalidOperationException(SR.Format(model.IsProperty ? SR.XmlPropertyReflectionError : SR.XmlFieldReflectionError, model.Name), e); } - private TypeMapping ImportTypeMapping(TypeModel model, string ns, ImportContext context, string dataType, XmlAttributes a, RecursionLimiter limiter) + private TypeMapping ImportTypeMapping(TypeModel model, string? ns, ImportContext context, string dataType, XmlAttributes? a, RecursionLimiter limiter) { return ImportTypeMapping(model, ns, context, dataType, a, false, false, limiter); } - private TypeMapping ImportTypeMapping(TypeModel model, string ns, ImportContext context, string dataType, XmlAttributes a, bool repeats, bool openModel, RecursionLimiter limiter) + private TypeMapping ImportTypeMapping(TypeModel model, string? ns, ImportContext context, string dataType, XmlAttributes? a, bool repeats, bool openModel, RecursionLimiter limiter) { try { if (dataType.Length > 0) { - TypeDesc modelTypeDesc = TypeScope.IsOptionalValue(model.Type) ? model.TypeDesc.BaseTypeDesc : model.TypeDesc; + TypeDesc modelTypeDesc = TypeScope.IsOptionalValue(model.Type) ? model.TypeDesc.BaseTypeDesc! : model.TypeDesc; if (!modelTypeDesc.IsPrimitive) { throw new InvalidOperationException(SR.Format(SR.XmlInvalidDataTypeUsage, dataType, "XmlElementAttribute.DataType")); } - TypeDesc td = _typeScope.GetTypeDesc(dataType, XmlSchema.Namespace); + TypeDesc? td = _typeScope.GetTypeDesc(dataType, XmlSchema.Namespace); if (td == null) { throw new InvalidOperationException(SR.Format(SR.XmlInvalidXsdDataType, dataType, "XmlElementAttribute.DataType", new XmlQualifiedName(dataType, XmlSchema.Namespace).ToString())); @@ -421,12 +422,12 @@ private TypeMapping ImportTypeMapping(TypeModel model, string ns, ImportContext if (context != ImportContext.Element) throw UnsupportedException(model.TypeDesc, context); if (model.TypeDesc.IsOptionalValue) { - TypeDesc valueTypeDesc = string.IsNullOrEmpty(dataType) ? model.TypeDesc.BaseTypeDesc : _typeScope.GetTypeDesc(dataType, XmlSchema.Namespace); - string xsdTypeName = valueTypeDesc.DataType == null ? valueTypeDesc.Name : valueTypeDesc.DataType.Name; - TypeMapping baseMapping = GetTypeMapping(xsdTypeName, ns, valueTypeDesc, _types, null); + TypeDesc valueTypeDesc = string.IsNullOrEmpty(dataType) ? model.TypeDesc.BaseTypeDesc! : _typeScope.GetTypeDesc(dataType, XmlSchema.Namespace)!; + string? xsdTypeName = valueTypeDesc.DataType == null ? valueTypeDesc.Name : valueTypeDesc.DataType.Name; + TypeMapping? baseMapping = GetTypeMapping(xsdTypeName, ns, valueTypeDesc, _types, null); if (baseMapping == null) - baseMapping = ImportTypeMapping(_modelScope.GetTypeModel(model.TypeDesc.BaseTypeDesc.Type), ns, context, dataType, null, repeats, openModel, limiter); - return CreateNullableMapping(baseMapping, model.TypeDesc.Type); + baseMapping = ImportTypeMapping(_modelScope.GetTypeModel(model.TypeDesc.BaseTypeDesc!.Type!), ns, context, dataType, null, repeats, openModel, limiter); + return CreateNullableMapping(baseMapping, model.TypeDesc.Type!); } else { @@ -460,7 +461,7 @@ private TypeMapping ImportTypeMapping(TypeModel model, string ns, ImportContext } } - internal static MethodInfo GetMethodFromSchemaProvider(XmlSchemaProviderAttribute provider, Type type) + internal static MethodInfo? GetMethodFromSchemaProvider(XmlSchemaProviderAttribute provider, Type type) { if (provider.IsAny) { @@ -474,7 +475,7 @@ internal static MethodInfo GetMethodFromSchemaProvider(XmlSchemaProviderAttribut if (!CSharpHelpers.IsValidLanguageIndependentIdentifier(provider.MethodName)) throw new ArgumentException(SR.Format(SR.XmlGetSchemaMethodName, provider.MethodName), nameof(provider.MethodName)); - MethodInfo getMethod = getMethod = type.GetMethod(provider.MethodName, /* BindingFlags.DeclaredOnly | */ BindingFlags.Static | BindingFlags.Public, new Type[] { typeof(XmlSchemaSet) }); + MethodInfo? getMethod = getMethod = type.GetMethod(provider.MethodName, /* BindingFlags.DeclaredOnly | */ BindingFlags.Static | BindingFlags.Public, new Type[] { typeof(XmlSchemaSet) }); if (getMethod == null) throw new InvalidOperationException(SR.Format(SR.XmlGetSchemaMethodMissing, provider.MethodName, typeof(XmlSchemaSet).Name, type.FullName)); @@ -484,19 +485,19 @@ internal static MethodInfo GetMethodFromSchemaProvider(XmlSchemaProviderAttribut return getMethod; } - private SpecialMapping ImportSpecialMapping(Type type, TypeDesc typeDesc, string ns, ImportContext context, RecursionLimiter limiter) + private SpecialMapping ImportSpecialMapping(Type type, TypeDesc typeDesc, string? ns, ImportContext context, RecursionLimiter limiter) { if (_specials == null) _specials = new Hashtable(); - SpecialMapping mapping = (SpecialMapping)_specials[type]; + SpecialMapping? mapping = (SpecialMapping?)_specials[type]; if (mapping != null) { - CheckContext(mapping.TypeDesc, context); + CheckContext(mapping.TypeDesc!, context); return mapping; } if (typeDesc.Kind == TypeKind.Serializable) { - SerializableMapping serializableMapping = null; + SerializableMapping? serializableMapping = null; // get the schema method info object[] attrs = type.GetCustomAttributes(typeof(XmlSchemaProviderAttribute), false); @@ -505,14 +506,14 @@ private SpecialMapping ImportSpecialMapping(Type type, TypeDesc typeDesc, string { // new IXmlSerializable XmlSchemaProviderAttribute provider = (XmlSchemaProviderAttribute)attrs[0]; - MethodInfo method = GetMethodFromSchemaProvider(provider, type); + MethodInfo method = GetMethodFromSchemaProvider(provider, type)!; serializableMapping = new SerializableMapping(method, provider.IsAny, ns); - XmlQualifiedName qname = serializableMapping.XsiType; + XmlQualifiedName? qname = serializableMapping.XsiType; if (qname != null && !qname.IsEmpty) { if (_serializables == null) _serializables = new NameTable(); - SerializableMapping existingMapping = (SerializableMapping)_serializables[qname]; + SerializableMapping? existingMapping = (SerializableMapping?)_serializables[qname]; if (existingMapping != null) { if (existingMapping.Type == null) @@ -521,14 +522,14 @@ private SpecialMapping ImportSpecialMapping(Type type, TypeDesc typeDesc, string } else if (existingMapping.Type != type) { - SerializableMapping next = existingMapping.Next; + SerializableMapping? next = existingMapping.Next; existingMapping.Next = serializableMapping; serializableMapping.Next = next; } } else { - XmlSchemaType xsdType = serializableMapping.XsdType; + XmlSchemaType? xsdType = serializableMapping.XsdType; if (xsdType != null) SetBase(serializableMapping, xsdType.DerivedFrom); _serializables[qname] = serializableMapping; @@ -565,7 +566,7 @@ internal void SetBase(SerializableMapping mapping, XmlQualifiedName baseQname) { if (baseQname.IsEmpty) return; if (baseQname.Namespace == XmlSchema.Namespace) return; - XmlSchemaSet schemas = mapping.Schemas; + XmlSchemaSet schemas = mapping.Schemas!; ArrayList srcSchemas = (ArrayList)schemas.Schemas(baseQname.Namespace); if (srcSchemas.Count == 0) @@ -576,18 +577,18 @@ internal void SetBase(SerializableMapping mapping, XmlQualifiedName baseQname) { throw new InvalidOperationException(SR.Format(SR.XmlGetSchemaInclude, baseQname.Namespace, typeof(IXmlSerializable).Name, "GetSchema")); } - XmlSchema s = (XmlSchema)srcSchemas[0]; + XmlSchema s = (XmlSchema)srcSchemas[0]!; - XmlSchemaType t = (XmlSchemaType)s.SchemaTypes[baseQname]; + XmlSchemaType t = (XmlSchemaType)s.SchemaTypes[baseQname]!; t = t.Redefined != null ? t.Redefined : t; - if (_serializables[baseQname] == null) + if (_serializables![baseQname] == null) { SerializableMapping baseMapping = new SerializableMapping(baseQname, schemas); SetBase(baseMapping, t.DerivedFrom); _serializables.Add(baseQname, baseMapping); } - mapping.SetBaseMapping((SerializableMapping)_serializables[baseQname]); + mapping.SetBaseMapping((SerializableMapping?)_serializables[baseQname]); } private static string GetContextName(ImportContext context) => @@ -623,15 +624,15 @@ private StructMapping CreateRootMapping() private NullableMapping CreateNullableMapping(TypeMapping baseMapping, Type type) { - TypeDesc typeDesc = baseMapping.TypeDesc.GetNullableTypeDesc(type); - TypeMapping existingMapping; + TypeDesc typeDesc = baseMapping.TypeDesc!.GetNullableTypeDesc(type); + TypeMapping? existingMapping; if (!baseMapping.IsAnonymousType) { - existingMapping = (TypeMapping)_nullables[baseMapping.TypeName, baseMapping.Namespace]; + existingMapping = (TypeMapping?)_nullables[baseMapping.TypeName!, baseMapping.Namespace]; } else { - existingMapping = (TypeMapping)_anonymous[type]; + existingMapping = (TypeMapping?)_anonymous[type]; } NullableMapping mapping; @@ -648,12 +649,12 @@ private NullableMapping CreateNullableMapping(TypeMapping baseMapping, Type type } else { - throw new InvalidOperationException(SR.Format(SR.XmlTypesDuplicate, typeDesc.FullName, existingMapping.TypeDesc.FullName, typeDesc.Name, existingMapping.Namespace)); + throw new InvalidOperationException(SR.Format(SR.XmlTypesDuplicate, typeDesc.FullName, existingMapping.TypeDesc!.FullName, typeDesc.Name, existingMapping.Namespace)); } } else { - throw new InvalidOperationException(SR.Format(SR.XmlTypesDuplicate, typeDesc.FullName, existingMapping.TypeDesc.FullName, typeDesc.Name, existingMapping.Namespace)); + throw new InvalidOperationException(SR.Format(SR.XmlTypesDuplicate, typeDesc.FullName, existingMapping.TypeDesc!.FullName, typeDesc.Name, existingMapping.Namespace)); } } mapping = new NullableMapping(); @@ -685,36 +686,36 @@ private StructMapping GetRootMapping() return _root; } - private TypeMapping GetTypeMapping(string typeName, string ns, TypeDesc typeDesc, NameTable typeLib, Type type) + private TypeMapping? GetTypeMapping(string? typeName, string? ns, TypeDesc typeDesc, NameTable typeLib, Type? type) { - TypeMapping mapping; + TypeMapping? mapping; if (typeName == null || typeName.Length == 0) - mapping = type == null ? null : (TypeMapping)_anonymous[type]; + mapping = type == null ? null : (TypeMapping?)_anonymous[type]; else - mapping = (TypeMapping)typeLib[typeName, ns]; + mapping = (TypeMapping?)typeLib[typeName, ns]; if (mapping == null) return null; if (!mapping.IsAnonymousType && mapping.TypeDesc != typeDesc) - throw new InvalidOperationException(SR.Format(SR.XmlTypesDuplicate, typeDesc.FullName, mapping.TypeDesc.FullName, typeName, ns)); + throw new InvalidOperationException(SR.Format(SR.XmlTypesDuplicate, typeDesc.FullName, mapping.TypeDesc!.FullName, typeName, ns)); return mapping; } - private StructMapping ImportStructLikeMapping(StructModel model, string ns, bool openModel, XmlAttributes a, RecursionLimiter limiter) + private StructMapping ImportStructLikeMapping(StructModel model, string? ns, bool openModel, XmlAttributes? a, RecursionLimiter limiter) { if (model.TypeDesc.Kind == TypeKind.Root) return GetRootMapping(); if (a == null) a = GetAttributes(model.Type, false); - string typeNs = ns; + string? typeNs = ns; if (a.XmlType != null && a.XmlType.Namespace != null) typeNs = a.XmlType.Namespace; else if (a.XmlRoot != null && a.XmlRoot.Namespace != null) typeNs = a.XmlRoot.Namespace; - string typeName = IsAnonymousType(a, ns) ? null : XsdTypeName(model.Type, a, model.TypeDesc.Name); + string? typeName = IsAnonymousType(a, ns) ? null : XsdTypeName(model.Type, a, model.TypeDesc.Name); typeName = XmlConvert.EncodeLocalName(typeName); - StructMapping mapping = (StructMapping)GetTypeMapping(typeName, typeNs, model.TypeDesc, _types, model.Type); + StructMapping? mapping = (StructMapping?)GetTypeMapping(typeName, typeNs, model.TypeDesc, _types, model.Type); if (mapping == null) { mapping = new StructMapping(); @@ -764,18 +765,18 @@ private StructMapping ImportStructLikeMapping(StructModel model, string ns, bool return mapping; } - private bool InitializeStructMembers(StructMapping mapping, StructModel model, bool openModel, string typeName, RecursionLimiter limiter) + private bool InitializeStructMembers(StructMapping mapping, StructModel model, bool openModel, string? typeName, RecursionLimiter limiter) { if (mapping.IsFullyInitialized) return true; if (model.TypeDesc.BaseTypeDesc != null) { - TypeModel baseModel = _modelScope.GetTypeModel(model.Type.BaseType, false); + TypeModel baseModel = _modelScope.GetTypeModel(model.Type.BaseType!, false); if (!(baseModel is StructModel)) { //XmlUnsupportedInheritance=Using '{0}' as a base type for a class is not supported by XmlSerializer. - throw new NotSupportedException(SR.Format(SR.XmlUnsupportedInheritance, model.Type.BaseType.FullName)); + throw new NotSupportedException(SR.Format(SR.XmlUnsupportedInheritance, model.Type.BaseType!.FullName)); } StructMapping baseMapping = ImportStructLikeMapping((StructModel)baseModel, mapping.Namespace, openModel, null, limiter); // check to see if the import of the baseMapping was deferred @@ -817,7 +818,7 @@ private bool InitializeStructMembers(StructMapping mapping, StructModel model, b } } ArrayList members = new ArrayList(); - TextAccessor textAccessor = null; + TextAccessor? textAccessor = null; bool hasElements = false; bool isSequence = false; @@ -827,11 +828,11 @@ private bool InitializeStructMembers(StructMapping mapping, StructModel model, b continue; XmlAttributes memberAttrs = GetAttributes(memberInfo); if (memberAttrs.XmlIgnore) continue; - FieldModel fieldModel = model.GetFieldModel(memberInfo); + FieldModel? fieldModel = model.GetFieldModel(memberInfo); if (fieldModel == null) continue; try { - MemberMapping member = ImportFieldMapping(model, fieldModel, memberAttrs, mapping.Namespace, limiter); + MemberMapping? member = ImportFieldMapping(model, fieldModel, memberAttrs, mapping.Namespace, limiter); if (member == null) continue; if (mapping.BaseMapping != null) { @@ -843,7 +844,7 @@ private bool InitializeStructMembers(StructMapping mapping, StructModel model, b if (member.Text != null) { - if (!member.Text.Mapping.TypeDesc.CanBeTextValue && member.Text.Mapping.IsList) + if (!member.Text.Mapping!.TypeDesc!.CanBeTextValue && member.Text.Mapping.IsList) throw new InvalidOperationException(SR.Format(SR.XmlIllegalTypedTextAttribute, typeName, member.Text.Name, member.Text.Mapping.TypeDesc.FullName)); if (textAccessor != null) { @@ -878,7 +879,7 @@ private bool InitializeStructMembers(StructMapping mapping, StructModel model, b Hashtable ids = new Hashtable(); for (int i = 0; i < members.Count; i++) { - MemberMapping member = (MemberMapping)members[i]; + MemberMapping member = (MemberMapping)members[i]!; if (!member.IsParticle) continue; if (member.IsSequence) @@ -910,7 +911,7 @@ private bool InitializeStructMembers(StructMapping mapping, StructModel model, b return true; } - private static bool IsAnonymousType(XmlAttributes a, string contextNs) + private static bool IsAnonymousType(XmlAttributes a, string? contextNs) { if (a.XmlType != null && a.XmlType.AnonymousType) { @@ -920,7 +921,7 @@ private static bool IsAnonymousType(XmlAttributes a, string contextNs) // matches the original referencing element, otherwise revert to // non-Anonymous handling for backward compatibility. // - string originalNs = a.XmlType.Namespace; + string? originalNs = a.XmlType.Namespace; return string.IsNullOrEmpty(originalNs) || originalNs == contextNs; } return false; @@ -967,11 +968,11 @@ private static int CountAtLevel(XmlArrayItemAttributes attributes, int level) { int sum = 0; for (int i = 0; i < attributes.Count; i++) - if (attributes[i].NestingLevel == level) sum++; + if (attributes[i]!.NestingLevel == level) sum++; return sum; } - private void SetArrayMappingType(ArrayMapping mapping, string defaultNs, Type type) + private void SetArrayMappingType(ArrayMapping mapping, string? defaultNs, Type type) { XmlAttributes a = GetAttributes(type, false); bool isAnonymous = IsAnonymousType(a, defaultNs); @@ -981,12 +982,12 @@ private void SetArrayMappingType(ArrayMapping mapping, string defaultNs, Type ty mapping.Namespace = defaultNs; return; } - string name; - string ns; - TypeMapping itemTypeMapping; - ElementAccessor element = null; + string? name; + string? ns; + TypeMapping? itemTypeMapping; + ElementAccessor? element = null; - if (mapping.Elements.Length == 1) + if (mapping.Elements!.Length == 1) { element = mapping.Elements[0]; itemTypeMapping = element.Mapping; @@ -1012,9 +1013,9 @@ private void SetArrayMappingType(ArrayMapping mapping, string defaultNs, Type ty else if (itemTypeMapping is PrimitiveMapping) { ns = defaultNs; - name = itemTypeMapping.TypeDesc.DataType.Name; + name = itemTypeMapping.TypeDesc!.DataType!.Name; } - else if (itemTypeMapping is StructMapping && itemTypeMapping.TypeDesc.IsRoot) + else if (itemTypeMapping is StructMapping && itemTypeMapping.TypeDesc!.IsRoot) { ns = defaultNs; name = Soap.UrType; @@ -1041,7 +1042,7 @@ private void SetArrayMappingType(ArrayMapping mapping, string defaultNs, Type ty string uniqueName = name = generateTypeName ? "ArrayOf" + CodeIdentifier.MakePascal(name) : name; int i = 1; - TypeMapping existingMapping = (TypeMapping)_types[uniqueName, ns]; + TypeMapping? existingMapping = (TypeMapping?)_types[uniqueName, ns]; while (existingMapping != null) { if (existingMapping is ArrayMapping) @@ -1054,14 +1055,14 @@ private void SetArrayMappingType(ArrayMapping mapping, string defaultNs, Type ty } // need to re-name the mapping uniqueName = name + i.ToString(CultureInfo.InvariantCulture); - existingMapping = (TypeMapping)_types[uniqueName, ns]; + existingMapping = (TypeMapping?)_types[uniqueName, ns]; i++; } mapping.TypeName = uniqueName; mapping.Namespace = ns; } - private ArrayMapping ImportArrayLikeMapping(ArrayModel model, string ns, RecursionLimiter limiter) + private ArrayMapping ImportArrayLikeMapping(ArrayModel model, string? ns, RecursionLimiter limiter) { ArrayMapping mapping = new ArrayMapping(); mapping.TypeDesc = model.TypeDesc; @@ -1074,7 +1075,7 @@ private ArrayMapping ImportArrayLikeMapping(ArrayModel model, string ns, Recursi SetArrayMappingType(mapping, ns, model.Type); // reconcile accessors now that we have the ArrayMapping namespace - for (int i = 0; i < mapping.Elements.Length; i++) + for (int i = 0; i < mapping.Elements!.Length; i++) { mapping.Elements[i] = ReconcileLocalAccessor(mapping.Elements[i], mapping.Namespace); } @@ -1084,10 +1085,10 @@ private ArrayMapping ImportArrayLikeMapping(ArrayModel model, string ns, Recursi // in the case of an ArrayMapping we can have more that one mapping correspond to a type // examples of that are ArrayList and object[] both will map tp ArrayOfur-type // so we create a link list for all mappings of the same XSD type - ArrayMapping existingMapping = (ArrayMapping)_types[mapping.TypeName, mapping.Namespace]; + ArrayMapping? existingMapping = (ArrayMapping?)_types[mapping.TypeName, mapping.Namespace]; if (existingMapping != null) { - ArrayMapping first = existingMapping; + ArrayMapping? first = existingMapping; while (existingMapping != null) { if (existingMapping.TypeDesc == model.TypeDesc) @@ -1149,24 +1150,24 @@ private PrimitiveMapping ImportPrimitiveMapping(PrimitiveModel model, ImportCont { mapping.TypeDesc = model.TypeDesc; } - mapping.TypeName = mapping.TypeDesc.DataType.Name; + mapping.TypeName = mapping.TypeDesc.DataType!.Name; mapping.Namespace = mapping.TypeDesc.IsXsdType ? XmlSchema.Namespace : UrtTypes.Namespace; mapping.IsList = repeats; CheckContext(mapping.TypeDesc, context); return mapping; } - private EnumMapping ImportEnumMapping(EnumModel model, string ns, bool repeats) + private EnumMapping ImportEnumMapping(EnumModel model, string? ns, bool repeats) { XmlAttributes a = GetAttributes(model.Type, false); - string typeNs = ns; + string? typeNs = ns; if (a.XmlType != null && a.XmlType.Namespace != null) typeNs = a.XmlType.Namespace; - string typeName = IsAnonymousType(a, ns) ? null : XsdTypeName(model.Type, a, model.TypeDesc.Name); + string? typeName = IsAnonymousType(a, ns) ? null : XsdTypeName(model.Type, a, model.TypeDesc.Name); typeName = XmlConvert.EncodeLocalName(typeName); - EnumMapping mapping = (EnumMapping)GetTypeMapping(typeName, typeNs, model.TypeDesc, _types, model.Type); + EnumMapping? mapping = (EnumMapping?)GetTypeMapping(typeName, typeNs, model.TypeDesc, _types, model.Type); if (mapping == null) { mapping = new EnumMapping(); @@ -1185,7 +1186,7 @@ private EnumMapping ImportEnumMapping(EnumModel model, string ns, bool repeats) ArrayList constants = new ArrayList(); for (int i = 0; i < model.Constants.Length; i++) { - ConstantMapping constant = ImportConstantMapping(model.Constants[i]); + ConstantMapping? constant = ImportConstantMapping(model.Constants[i]); if (constant != null) constants.Add(constant); } if (constants.Count == 0) @@ -1198,7 +1199,7 @@ private EnumMapping ImportEnumMapping(EnumModel model, string ns, bool repeats) return mapping; } - private ConstantMapping ImportConstantMapping(ConstantModel model) + private ConstantMapping? ImportConstantMapping(ConstantModel model) { XmlAttributes a = GetAttributes(model.FieldInfo); if (a.XmlIgnore) return null; @@ -1214,14 +1215,14 @@ private ConstantMapping ImportConstantMapping(ConstantModel model) return constant; } - private MembersMapping ImportMembersMapping(XmlReflectionMember[] xmlReflectionMembers, string ns, bool hasWrapperElement, bool rpc, bool openModel, RecursionLimiter limiter) + private MembersMapping ImportMembersMapping(XmlReflectionMember[] xmlReflectionMembers, string? ns, bool hasWrapperElement, bool rpc, bool openModel, RecursionLimiter limiter) { MembersMapping members = new MembersMapping(); members.TypeDesc = _typeScope.GetTypeDesc(typeof(object[])); MemberMapping[] mappings = new MemberMapping[xmlReflectionMembers.Length]; NameTable elements = new NameTable(); NameTable attributes = new NameTable(); - TextAccessor textAccessor = null; + TextAccessor? textAccessor = null; bool isSequence = false; for (int i = 0; i < mappings.Length; i++) @@ -1291,11 +1292,11 @@ private MembersMapping ImportMembersMapping(XmlReflectionMember[] xmlReflectionM return members; } - private MemberMapping ImportMemberMapping(XmlReflectionMember xmlReflectionMember, string ns, XmlReflectionMember[] xmlReflectionMembers, bool rpc, bool openModel, RecursionLimiter limiter) + private MemberMapping ImportMemberMapping(XmlReflectionMember xmlReflectionMember, string? ns, XmlReflectionMember[] xmlReflectionMembers, bool rpc, bool openModel, RecursionLimiter limiter) { XmlSchemaForm form = rpc ? XmlSchemaForm.Unqualified : XmlSchemaForm.Qualified; XmlAttributes a = xmlReflectionMember.XmlAttributes; - TypeDesc typeDesc = _typeScope.GetTypeDesc(xmlReflectionMember.MemberType); + TypeDesc typeDesc = _typeScope.GetTypeDesc(xmlReflectionMember.MemberType!); if (a.XmlFlags == 0) { @@ -1314,7 +1315,7 @@ private MemberMapping ImportMemberMapping(XmlReflectionMember xmlReflectionMembe // an XmlRoot attribute on the struct or class. if (typeDesc.IsStructLike) { - XmlAttributes structAttrs = new XmlAttributes(xmlReflectionMember.MemberType); + XmlAttributes structAttrs = new XmlAttributes(xmlReflectionMember.MemberType!); if (structAttrs.XmlRoot != null) { if (structAttrs.XmlRoot.ElementName.Length > 0) @@ -1347,23 +1348,23 @@ private MemberMapping ImportMemberMapping(XmlReflectionMember xmlReflectionMembe MemberMapping member = new MemberMapping(); member.Name = xmlReflectionMember.MemberName; bool checkSpecified = FindSpecifiedMember(xmlReflectionMember.MemberName, xmlReflectionMembers) != null; - FieldModel model = new FieldModel(xmlReflectionMember.MemberName, xmlReflectionMember.MemberType, _typeScope.GetTypeDesc(xmlReflectionMember.MemberType), checkSpecified, false); + FieldModel model = new FieldModel(xmlReflectionMember.MemberName, xmlReflectionMember.MemberType!, _typeScope.GetTypeDesc(xmlReflectionMember.MemberType!), checkSpecified, false); member.CheckShouldPersist = model.CheckShouldPersist; member.CheckSpecified = model.CheckSpecified; member.ReadOnly = model.ReadOnly; // || !model.FieldTypeDesc.HasDefaultConstructor; - Type choiceIdentifierType = null; + Type? choiceIdentifierType = null; if (a.XmlChoiceIdentifier != null) { choiceIdentifierType = GetChoiceIdentifierType(a.XmlChoiceIdentifier, xmlReflectionMembers, typeDesc.IsArrayLike, model.Name); } ImportAccessorMapping(member, model, a, ns, choiceIdentifierType, rpc, openModel, limiter); - if (xmlReflectionMember.OverrideIsNullable && member.Elements.Length > 0) + if (xmlReflectionMember.OverrideIsNullable && member.Elements!.Length > 0) member.Elements[0].IsNullable = false; return member; } - internal static XmlReflectionMember FindSpecifiedMember(string memberName, XmlReflectionMember[] reflectionMembers) + internal static XmlReflectionMember? FindSpecifiedMember(string memberName, XmlReflectionMember[] reflectionMembers) { for (int i = 0; i < reflectionMembers.Length; i++) if (string.Equals(reflectionMembers[i].MemberName, memberName + "Specified", StringComparison.Ordinal)) @@ -1371,7 +1372,7 @@ internal static XmlReflectionMember FindSpecifiedMember(string memberName, XmlRe return null; } - private MemberMapping ImportFieldMapping(StructModel parent, FieldModel model, XmlAttributes a, string ns, RecursionLimiter limiter) + private MemberMapping ImportFieldMapping(StructModel parent, FieldModel model, XmlAttributes a, string? ns, RecursionLimiter limiter) { MemberMapping member = new MemberMapping(); member.Name = model.Name; @@ -1381,7 +1382,7 @@ private MemberMapping ImportFieldMapping(StructModel parent, FieldModel model, X member.CheckSpecifiedMemberInfo = model.CheckSpecifiedMemberInfo; member.CheckShouldPersistMethodInfo = model.CheckShouldPersistMethodInfo; member.ReadOnly = model.ReadOnly; // || !model.FieldTypeDesc.HasDefaultConstructor; - Type choiceIdentifierType = null; + Type? choiceIdentifierType = null; if (a.XmlChoiceIdentifier != null) { choiceIdentifierType = GetChoiceIdentifierType(a.XmlChoiceIdentifier, parent, model.FieldTypeDesc.IsArrayLike, model.Name); @@ -1397,9 +1398,9 @@ private Type CheckChoiceIdentifierType(Type type, bool isArrayLike, string ident if (!isArrayLike) { // Inconsistent type of the choice identifier '{0}'. Please use {1}. - throw new InvalidOperationException(SR.Format(SR.XmlChoiceIdentifierType, identifierName, memberName, type.GetElementType().FullName)); + throw new InvalidOperationException(SR.Format(SR.XmlChoiceIdentifierType, identifierName, memberName, type.GetElementType()!.FullName)); } - type = type.GetElementType(); + type = type.GetElementType()!; } else if (isArrayLike) { @@ -1407,7 +1408,7 @@ private Type CheckChoiceIdentifierType(Type type, bool isArrayLike, string ident throw new InvalidOperationException(SR.Format(SR.XmlChoiceIdentifierArrayType, identifierName, memberName, type.FullName)); } - if (!type.IsEnum) + if (!type!.IsEnum) { // Choice identifier '{0}' must be an enum. throw new InvalidOperationException(SR.Format(SR.XmlChoiceIdentifierTypeEnum, identifierName)); @@ -1421,7 +1422,7 @@ private Type GetChoiceIdentifierType(XmlChoiceIdentifierAttribute choice, XmlRef { if (choice.MemberName == xmlReflectionMembers[i].MemberName) { - return CheckChoiceIdentifierType(xmlReflectionMembers[i].MemberType, isArrayLike, choice.MemberName, accessorName); + return CheckChoiceIdentifierType(xmlReflectionMembers[i].MemberType!, isArrayLike, choice.MemberName, accessorName); } } // Missing '{0}' needed for serialization of choice '{1}'. @@ -1436,7 +1437,7 @@ private Type GetChoiceIdentifierType(XmlChoiceIdentifierAttribute choice, Struct if (infos == null || infos.Length == 0) { // if we can not find the choice identifier between fields, check properties - PropertyInfo info = structModel.Type.GetProperty(choice.MemberName, BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static); + PropertyInfo? info = structModel.Type.GetProperty(choice.MemberName, BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static); if (info == null) { @@ -1451,7 +1452,7 @@ private Type GetChoiceIdentifierType(XmlChoiceIdentifierAttribute choice, Struct throw new InvalidOperationException(SR.Format(SR.XmlChoiceIdentiferAmbiguous, choice.MemberName)); } - FieldModel member = structModel.GetFieldModel(infos[0]); + FieldModel? member = structModel.GetFieldModel(infos[0]); if (member == null) { // Missing '{0}' needed for serialization of choice '{1}'. @@ -1463,13 +1464,13 @@ private Type GetChoiceIdentifierType(XmlChoiceIdentifierAttribute choice, Struct return enumType; } - private void CreateArrayElementsFromAttributes(ArrayMapping arrayMapping, XmlArrayItemAttributes attributes, Type arrayElementType, string arrayElementNs, RecursionLimiter limiter) + private void CreateArrayElementsFromAttributes(ArrayMapping arrayMapping, XmlArrayItemAttributes attributes, Type arrayElementType, string? arrayElementNs, RecursionLimiter limiter) { NameTable arrayItemElements = new NameTable(); // xmlelementname + xmlns -> ElementAccessor for (int i = 0; attributes != null && i < attributes.Count; i++) { - XmlArrayItemAttribute xmlArrayItem = attributes[i]; + XmlArrayItemAttribute xmlArrayItem = attributes[i]!; if (xmlArrayItem.NestingLevel != _arrayNestingLevel) continue; Type targetType = xmlArrayItem.Type != null ? xmlArrayItem.Type : arrayElementType; @@ -1487,13 +1488,13 @@ private void CreateArrayElementsFromAttributes(ArrayMapping arrayMapping, XmlArr arrayMapping.Elements = (ElementAccessor[])arrayItemElements.ToArray(typeof(ElementAccessor)); } - private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, XmlAttributes a, string ns, Type choiceIdentifierType, bool rpc, bool openModel, RecursionLimiter limiter) + private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, XmlAttributes a, string? ns, Type? choiceIdentifierType, bool rpc, bool openModel, RecursionLimiter limiter) { XmlSchemaForm elementFormDefault = XmlSchemaForm.Qualified; int previousNestingLevel = _arrayNestingLevel; int sequenceId = -1; - XmlArrayItemAttributes previousArrayItemAttributes = _savedArrayItemAttributes; - string previousArrayNamespace = _savedArrayNamespace; + XmlArrayItemAttributes? previousArrayItemAttributes = _savedArrayItemAttributes; + string? previousArrayNamespace = _savedArrayNamespace; _arrayNestingLevel = 0; _savedArrayItemAttributes = null; _savedArrayNamespace = null; @@ -1523,20 +1524,20 @@ private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, Xml accessor.ChoiceIdentifier = new ChoiceIdentifierAccessor(); accessor.ChoiceIdentifier.MemberName = a.XmlChoiceIdentifier.MemberName; accessor.ChoiceIdentifier.MemberInfo = a.XmlChoiceIdentifier.GetMemberInfo(); - accessor.ChoiceIdentifier.Mapping = ImportTypeMapping(_modelScope.GetTypeModel(choiceIdentifierType), ns, ImportContext.Element, string.Empty, null, limiter); + accessor.ChoiceIdentifier.Mapping = ImportTypeMapping(_modelScope.GetTypeModel(choiceIdentifierType!), ns, ImportContext.Element, string.Empty, null, limiter); CheckChoiceIdentifierMapping((EnumMapping)accessor.ChoiceIdentifier.Mapping); } if (accessor.TypeDesc.IsArrayLike) { - Type arrayElementType = TypeScope.GetArrayElementType(accessorType, model.FieldTypeDesc.FullName + "." + model.Name); + Type arrayElementType = TypeScope.GetArrayElementType(accessorType, model.FieldTypeDesc.FullName + "." + model.Name)!; if ((flags & attrFlags) != 0) { if ((flags & attrFlags) != flags) throw new InvalidOperationException(SR.XmlIllegalAttributesArrayAttribute); - if (a.XmlAttribute != null && !accessor.TypeDesc.ArrayElementTypeDesc.IsPrimitive && !accessor.TypeDesc.ArrayElementTypeDesc.IsEnum) + if (a.XmlAttribute != null && !accessor.TypeDesc.ArrayElementTypeDesc!.IsPrimitive && !accessor.TypeDesc.ArrayElementTypeDesc.IsEnum) { if (accessor.TypeDesc.ArrayElementTypeDesc.Kind == TypeKind.Serializable) { @@ -1548,7 +1549,7 @@ private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, Xml } } - bool isList = a.XmlAttribute != null && (accessor.TypeDesc.ArrayElementTypeDesc.IsPrimitive || accessor.TypeDesc.ArrayElementTypeDesc.IsEnum); + bool isList = a.XmlAttribute != null && (accessor.TypeDesc.ArrayElementTypeDesc!.IsPrimitive || accessor.TypeDesc.ArrayElementTypeDesc.IsEnum); if (a.XmlAnyAttribute != null) { @@ -1556,7 +1557,7 @@ private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, Xml } AttributeAccessor attribute = new AttributeAccessor(); - Type targetType = a.XmlAttribute.Type == null ? arrayElementType : a.XmlAttribute.Type; + Type targetType = a.XmlAttribute!.Type == null ? arrayElementType : a.XmlAttribute.Type!; TypeDesc targetTypeDesc = _typeScope.GetTypeDesc(targetType); attribute.Name = Accessor.EscapeQName(a.XmlAttribute.AttributeName.Length == 0 ? accessorName : a.XmlAttribute.AttributeName); attribute.Namespace = a.XmlAttribute.Namespace == null ? ns : a.XmlAttribute.Namespace; @@ -1601,7 +1602,7 @@ private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, Xml for (int i = 0; i < a.XmlElements.Count; i++) { - XmlElementAttribute xmlElement = a.XmlElements[i]; + XmlElementAttribute xmlElement = a.XmlElements[i]!; Type targetType = xmlElement.Type == null ? arrayElementType : xmlElement.Type; TypeDesc targetTypeDesc = _typeScope.GetTypeDesc(targetType); TypeModel typeModel = _modelScope.GetTypeModel(targetType); @@ -1620,7 +1621,7 @@ private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, Xml element.Default = GetDefaultValue(model.FieldTypeDesc, model.FieldType, a); if (xmlElement.GetIsNullableSpecified() && !xmlElement.IsNullable && typeModel.TypeDesc.IsOptionalValue) //XmlInvalidNotNullable=IsNullable may not be set to 'false' for a Nullable<{0}> type. Consider using '{0}' type or removing the IsNullable property from the XmlElement attribute. - throw new InvalidOperationException(SR.Format(SR.XmlInvalidNotNullable, typeModel.TypeDesc.BaseTypeDesc.FullName, "XmlElement")); + throw new InvalidOperationException(SR.Format(SR.XmlInvalidNotNullable, typeModel.TypeDesc.BaseTypeDesc!.FullName, "XmlElement")); element.IsNullable = xmlElement.GetIsNullableSpecified() ? xmlElement.IsNullable : typeModel.TypeDesc.IsOptionalValue; element.Form = rpc ? XmlSchemaForm.Unqualified : xmlElement.Form == XmlSchemaForm.None ? elementFormDefault : xmlElement.Form; @@ -1642,12 +1643,12 @@ private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, Xml NameTable anys = new NameTable(); for (int i = 0; i < a.XmlAnyElements.Count; i++) { - XmlAnyElementAttribute xmlAnyElement = a.XmlAnyElements[i]; + XmlAnyElementAttribute xmlAnyElement = a.XmlAnyElements[i]!; Type targetType = typeof(IXmlSerializable).IsAssignableFrom(arrayElementType) ? arrayElementType : typeof(XmlNode).IsAssignableFrom(arrayElementType) ? arrayElementType : typeof(XmlElement); if (!arrayElementType.IsAssignableFrom(targetType)) throw new InvalidOperationException(SR.Format(SR.XmlIllegalAnyElement, arrayElementType.FullName)); string anyName = xmlAnyElement.Name.Length == 0 ? xmlAnyElement.Name : XmlConvert.EncodeLocalName(xmlAnyElement.Name); - string anyNs = xmlAnyElement.GetNamespaceSpecified() ? xmlAnyElement.Namespace : null; + string? anyNs = xmlAnyElement.GetNamespaceSpecified() ? xmlAnyElement.Namespace : null; if (anys[anyName, anyNs] != null) { // ignore duplicate anys @@ -1777,8 +1778,8 @@ private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, Xml for (int i = 0; i < a.XmlElements.Count; i++) { - XmlElementAttribute xmlElement = a.XmlElements[i]; - if (xmlElement.Type != null) + XmlElementAttribute xmlElement = a.XmlElements[i]!; + if (xmlElement!.Type != null) { if (_typeScope.GetTypeDesc(xmlElement.Type) != accessor.TypeDesc) throw new InvalidOperationException(SR.Format(SR.XmlIllegalType, "XmlElement")); @@ -1788,14 +1789,14 @@ private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, Xml element.Namespace = rpc ? null : xmlElement.Namespace == null ? ns : xmlElement.Namespace; TypeModel typeModel = _modelScope.GetTypeModel(accessorType); element.Mapping = ImportTypeMapping(typeModel, rpc ? ns : element.Namespace, ImportContext.Element, xmlElement.DataType, null, limiter); - if (element.Mapping.TypeDesc.Kind == TypeKind.Node) + if (element.Mapping.TypeDesc!.Kind == TypeKind.Node) { element.Any = true; } element.Default = GetDefaultValue(model.FieldTypeDesc, model.FieldType, a); if (xmlElement.GetIsNullableSpecified() && !xmlElement.IsNullable && typeModel.TypeDesc.IsOptionalValue) //XmlInvalidNotNullable=IsNullable may not be set to 'false' for a Nullable<{0}> type. Consider using '{0}' type or removing the IsNullable property from the XmlElement attribute. - throw new InvalidOperationException(SR.Format(SR.XmlInvalidNotNullable, typeModel.TypeDesc.BaseTypeDesc.FullName, "XmlElement")); + throw new InvalidOperationException(SR.Format(SR.XmlInvalidNotNullable, typeModel.TypeDesc.BaseTypeDesc!.FullName, "XmlElement")); element.IsNullable = xmlElement.GetIsNullableSpecified() ? xmlElement.IsNullable : typeModel.TypeDesc.IsOptionalValue; element.Form = rpc ? XmlSchemaForm.Unqualified : xmlElement.Form == XmlSchemaForm.None ? elementFormDefault : xmlElement.Form; @@ -1845,7 +1846,7 @@ private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, Xml a.XmlElements.Add(CreateElementAttribute(accessor.TypeDesc)); for (int i = 0; i < a.XmlElements.Count; i++) { - XmlElementAttribute xmlElement = a.XmlElements[i]; + XmlElementAttribute xmlElement = a.XmlElements[i]!; Type targetType = xmlElement.Type == null ? accessorType : xmlElement.Type; TypeDesc targetTypeDesc = _typeScope.GetTypeDesc(targetType); ElementAccessor element = new ElementAccessor(); @@ -1863,7 +1864,7 @@ private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, Xml element.Default = GetDefaultValue(model.FieldTypeDesc, model.FieldType, a); if (xmlElement.GetIsNullableSpecified() && !xmlElement.IsNullable && typeModel.TypeDesc.IsOptionalValue) //XmlInvalidNotNullable=IsNullable may not be set to 'false' for a Nullable<{0}> type. Consider using '{0}' type or removing the IsNullable property from the XmlElement attribute. - throw new InvalidOperationException(SR.Format(SR.XmlInvalidNotNullable, typeModel.TypeDesc.BaseTypeDesc.FullName, "XmlElement")); + throw new InvalidOperationException(SR.Format(SR.XmlInvalidNotNullable, typeModel.TypeDesc.BaseTypeDesc!.FullName, "XmlElement")); element.IsNullable = xmlElement.GetIsNullableSpecified() ? xmlElement.IsNullable : typeModel.TypeDesc.IsOptionalValue; element.Form = rpc ? XmlSchemaForm.Unqualified : xmlElement.Form == XmlSchemaForm.None ? elementFormDefault : xmlElement.Form; CheckNullable(element.IsNullable, targetTypeDesc, element.Mapping); @@ -1885,13 +1886,13 @@ private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, Xml NameTable anys = new NameTable(); for (int i = 0; i < a.XmlAnyElements.Count; i++) { - XmlAnyElementAttribute xmlAnyElement = a.XmlAnyElements[i]; + XmlAnyElementAttribute xmlAnyElement = a.XmlAnyElements[i]!; Type targetType = typeof(IXmlSerializable).IsAssignableFrom(accessorType) ? accessorType : typeof(XmlNode).IsAssignableFrom(accessorType) ? accessorType : typeof(XmlElement); if (!accessorType.IsAssignableFrom(targetType)) throw new InvalidOperationException(SR.Format(SR.XmlIllegalAnyElement, accessorType.FullName)); string anyName = xmlAnyElement.Name.Length == 0 ? xmlAnyElement.Name : XmlConvert.EncodeLocalName(xmlAnyElement.Name); - string anyNs = xmlAnyElement.GetNamespaceSpecified() ? xmlAnyElement.Namespace : null; + string? anyNs = xmlAnyElement.GetNamespaceSpecified() ? xmlAnyElement.Namespace : null; if (anys[anyName, anyNs] != null) { // ignore duplicate anys @@ -1953,8 +1954,8 @@ private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, Xml { bool found = false; ElementAccessor element = accessor.Elements[i]; - EnumMapping choiceMapping = (EnumMapping)accessor.ChoiceIdentifier.Mapping; - for (int j = 0; j < choiceMapping.Constants.Length; j++) + EnumMapping choiceMapping = (EnumMapping)accessor.ChoiceIdentifier.Mapping!; + for (int j = 0; j < choiceMapping.Constants!.Length; j++) { string xmlName = choiceMapping.Constants[j].XmlName; @@ -1970,7 +1971,7 @@ private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, Xml continue; } int colon = xmlName.LastIndexOf(':'); - string choiceNs = colon < 0 ? choiceMapping.Namespace : xmlName.Substring(0, colon); + string? choiceNs = colon < 0 ? choiceMapping.Namespace : xmlName.Substring(0, colon); string choiceName = colon < 0 ? xmlName : xmlName.Substring(colon + 1); if (element.Name == choiceName) @@ -1988,13 +1989,13 @@ private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, Xml if (element.Any && element.Name.Length == 0) { // Type {0} is missing enumeration value '##any' for XmlAnyElementAttribute. - throw new InvalidOperationException(SR.Format(SR.XmlChoiceMissingAnyValue, accessor.ChoiceIdentifier.Mapping.TypeDesc.FullName)); + throw new InvalidOperationException(SR.Format(SR.XmlChoiceMissingAnyValue, accessor.ChoiceIdentifier.Mapping!.TypeDesc!.FullName)); } else { string id = element.Namespace != null && element.Namespace.Length > 0 ? element.Namespace + ":" + element.Name : element.Name; // Type {0} is missing value for '{1}'. - throw new InvalidOperationException(SR.Format(SR.XmlChoiceMissingValue, accessor.ChoiceIdentifier.Mapping.TypeDesc.FullName, id, element.Name, element.Namespace)); + throw new InvalidOperationException(SR.Format(SR.XmlChoiceMissingValue, accessor.ChoiceIdentifier.Mapping!.TypeDesc!.FullName, id, element.Name, element.Namespace)); } } } @@ -2021,7 +2022,7 @@ private void CheckTopLevelAttributes(XmlAttributes a, string accessorName) { throw new InvalidOperationException(SR.XmlRpcLitElements); } - XmlElementAttribute xmlElement = a.XmlElements[0]; + XmlElementAttribute xmlElement = a.XmlElements[0]!; if (xmlElement.Namespace != null) { throw new InvalidOperationException(SR.Format(SR.XmlRpcLitElementNamespace, "Namespace", xmlElement.Namespace)); @@ -2046,7 +2047,7 @@ private void CheckAmbiguousChoice(XmlAttributes a, Type accessorType, string acc { for (int i = 0; i < elements.Count; i++) { - Type type = elements[i].Type == null ? accessorType : elements[i].Type; + Type type = elements[i]!.Type == null ? accessorType : elements[i]!.Type!; if (choiceTypes.Contains(type)) { // You need to add {0} to the '{1}'. @@ -2071,12 +2072,12 @@ private void CheckAmbiguousChoice(XmlAttributes a, Type accessorType, string acc for (int i = 0; i < items.Count; i++) { - Type type = items[i].Type == null ? accessorType : items[i].Type; - string ns = items[i].NestingLevel.ToString(CultureInfo.InvariantCulture); - XmlArrayItemAttribute item = (XmlArrayItemAttribute)arrayTypes[type.FullName, ns]; + Type type = items[i]!.Type == null ? accessorType : items[i]!.Type!; + string ns = items[i]!.NestingLevel.ToString(CultureInfo.InvariantCulture); + XmlArrayItemAttribute? item = (XmlArrayItemAttribute?)arrayTypes[type.FullName, ns]; if (item != null) { - throw new InvalidOperationException(SR.Format(SR.XmlArrayItemAmbiguousTypes, accessorName, item.ElementName, items[i].ElementName, typeof(XmlElementAttribute).Name, typeof(XmlChoiceIdentifierAttribute).Name, accessorName)); + throw new InvalidOperationException(SR.Format(SR.XmlArrayItemAmbiguousTypes, accessorName, item.ElementName, items[i]!.ElementName, typeof(XmlElementAttribute).Name, typeof(XmlChoiceIdentifierAttribute).Name, accessorName)); } else { @@ -2089,7 +2090,7 @@ private void CheckAmbiguousChoice(XmlAttributes a, Type accessorType, string acc private void CheckChoiceIdentifierMapping(EnumMapping choiceMapping) { NameTable ids = new NameTable(); - for (int i = 0; i < choiceMapping.Constants.Length; i++) + for (int i = 0; i < choiceMapping.Constants!.Length; i++) { string choiceId = choiceMapping.Constants[i].XmlName; int colon = choiceId.LastIndexOf(':'); @@ -2105,7 +2106,7 @@ private void CheckChoiceIdentifierMapping(EnumMapping choiceMapping) } } - private object GetDefaultValue(TypeDesc fieldTypeDesc, Type t, XmlAttributes a) + private object? GetDefaultValue(TypeDesc fieldTypeDesc, Type t, XmlAttributes a) { if (a.XmlDefaultValue == null || a.XmlDefaultValue == DBNull.Value) return null; if (!(fieldTypeDesc.Kind == TypeKind.Primitive || fieldTypeDesc.Kind == TypeKind.Enum)) @@ -2148,7 +2149,7 @@ private static XmlElementAttribute CreateElementAttribute(TypeDesc typeDesc) private static void AddUniqueAccessor(INameScope scope, Accessor accessor) { - Accessor existing = (Accessor)scope[accessor.Name, accessor.Namespace]; + Accessor? existing = (Accessor?)scope[accessor.Name, accessor.Namespace]; if (existing != null) { if (accessor is ElementAccessor) @@ -2190,7 +2191,7 @@ private static void CheckForm(XmlSchemaForm form, bool isQualified) if (isQualified && form == XmlSchemaForm.Unqualified) throw new InvalidOperationException(SR.XmlInvalidFormUnqualified); } - private static void CheckNullable(bool isNullable, TypeDesc typeDesc, TypeMapping mapping) + private static void CheckNullable(bool isNullable, TypeDesc typeDesc, TypeMapping? mapping) { if (mapping is NullableMapping) return; if (mapping is SerializableMapping) return; @@ -2200,7 +2201,7 @@ private static void CheckNullable(bool isNullable, TypeDesc typeDesc, TypeMappin private static ElementAccessor CreateElementAccessor(TypeMapping mapping, string ns) { ElementAccessor element = new ElementAccessor(); - bool isAny = mapping.TypeDesc.Kind == TypeKind.Node; + bool isAny = mapping.TypeDesc!.Kind == TypeKind.Node; if (!isAny && mapping is SerializableMapping) { isAny = ((SerializableMapping)mapping).IsAny; @@ -2219,7 +2220,7 @@ private static ElementAccessor CreateElementAccessor(TypeMapping mapping, string } // will create a shallow type mapping for a top-level type - internal static XmlTypeMapping GetTopLevelMapping(Type type, string defaultNamespace) + internal static XmlTypeMapping GetTopLevelMapping(Type type, string? defaultNamespace) { defaultNamespace = defaultNamespace ?? string.Empty; XmlAttributes a = new XmlAttributes(type); @@ -2232,7 +2233,7 @@ internal static XmlTypeMapping GetTopLevelMapping(Type type, string defaultNames } else { - string ns = a.XmlRoot == null ? defaultNamespace : a.XmlRoot.Namespace; + string? ns = a.XmlRoot == null ? defaultNamespace : a.XmlRoot.Namespace; string typeName = string.Empty; if (a.XmlType != null) typeName = a.XmlType.TypeName; @@ -2270,7 +2271,7 @@ internal ImportStructWorkItem this[int index] { get { - return (ImportStructWorkItem)_list[index]; + return (ImportStructWorkItem)_list[index]!; } set { @@ -2316,7 +2317,7 @@ internal class RecursionLimiter { private readonly int _maxDepth; private int _depth; - private WorkItems _deferredWorkItems; + private WorkItems? _deferredWorkItems; internal RecursionLimiter() { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionMember.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionMember.cs index fa4e204cf73ab2..e7f33264760745 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionMember.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionMember.cs @@ -1,10 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; using System.Xml.Serialization; - namespace System.Xml.Serialization { /// @@ -13,8 +13,8 @@ namespace System.Xml.Serialization /// public class XmlReflectionMember { - private string _memberName; - private Type _type; + private string? _memberName; + private Type? _type; private XmlAttributes _xmlAttributes = new XmlAttributes(); private SoapAttributes _soapAttributes = new SoapAttributes(); private bool _isReturnValue; @@ -23,7 +23,7 @@ public class XmlReflectionMember /// /// [To be supplied.] /// - public Type MemberType + public Type? MemberType { get { return _type; } set { _type = value; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlRootAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlRootAttribute.cs index d4dda29a98296b..9caa2008b20d57 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlRootAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlRootAttribute.cs @@ -5,7 +5,9 @@ // //------------------------------------------------------------------------------ +#nullable enable using System; +using System.Diagnostics.CodeAnalysis; using System.Xml.Schema; @@ -17,9 +19,9 @@ namespace System.Xml.Serialization [AttributeUsage(AttributeTargets.ReturnValue | AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Struct)] public class XmlRootAttribute : System.Attribute { - private string _elementName; - private string _ns; - private string _dataType; + private string? _elementName; + private string? _ns; + private string? _dataType; private bool _nullable = true; private bool _nullableSpecified; @@ -50,7 +52,7 @@ public string ElementName /// /// [To be supplied.] /// - public string Namespace + public string? Namespace { get { return _ns; } set { _ns = value; } @@ -59,6 +61,7 @@ public string Namespace /// /// [To be supplied.] /// + [AllowNull] public string DataType { get { return _dataType == null ? string.Empty : _dataType; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaExporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaExporter.cs index f8ba7df0f1f90a..20662550ed0082 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaExporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaExporter.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; @@ -22,7 +23,7 @@ public class XmlSchemaExporter private readonly Hashtable _types = new Hashtable(); // StructMapping/EnumMapping -> XmlSchemaComplexType/XmlSchemaSimpleType private readonly Hashtable _references = new Hashtable(); // TypeMappings to keep track of circular references via anonymous types private bool _needToExportRoot; - private TypeScope _scope; + private TypeScope? _scope; public XmlSchemaExporter(XmlSchemas schemas) { @@ -34,24 +35,24 @@ public void ExportTypeMapping(XmlTypeMapping xmlTypeMapping) xmlTypeMapping.CheckShallow(); CheckScope(xmlTypeMapping.Scope); ExportElement(xmlTypeMapping.Accessor); - ExportRootIfNecessary(xmlTypeMapping.Scope); + ExportRootIfNecessary(xmlTypeMapping.Scope!); } - public XmlQualifiedName ExportTypeMapping(XmlMembersMapping xmlMembersMapping) + public XmlQualifiedName? ExportTypeMapping(XmlMembersMapping xmlMembersMapping) { xmlMembersMapping.CheckShallow(); - CheckScope(xmlMembersMapping.Scope); - MembersMapping mapping = (MembersMapping)xmlMembersMapping.Accessor.Mapping; - if (mapping.Members.Length == 1 && mapping.Members[0].Elements[0].Mapping is SpecialMapping) + CheckScope(xmlMembersMapping.Scope!); + MembersMapping mapping = (MembersMapping)xmlMembersMapping.Accessor.Mapping!; + if (mapping.Members!.Length == 1 && mapping.Members[0].Elements![0].Mapping is SpecialMapping) { - SpecialMapping special = (SpecialMapping)mapping.Members[0].Elements[0].Mapping; - XmlSchemaType type = ExportSpecialMapping(special, xmlMembersMapping.Accessor.Namespace, false, null); + SpecialMapping special = (SpecialMapping)mapping.Members[0].Elements![0].Mapping!; + XmlSchemaType? type = ExportSpecialMapping(special, xmlMembersMapping.Accessor.Namespace, false, null); if (type != null && type.Name != null && type.Name.Length > 0) { type.Name = xmlMembersMapping.Accessor.Name; AddSchemaItem(type, xmlMembersMapping.Accessor.Namespace, null); } - ExportRootIfNecessary(xmlMembersMapping.Scope); + ExportRootIfNecessary(xmlMembersMapping.Scope!); return (new XmlQualifiedName(xmlMembersMapping.Accessor.Name, xmlMembersMapping.Accessor.Namespace)); } return null; @@ -65,7 +66,7 @@ public void ExportMembersMapping(XmlMembersMapping xmlMembersMapping) public void ExportMembersMapping(XmlMembersMapping xmlMembersMapping, bool exportEnclosingType) { xmlMembersMapping.CheckShallow(); - MembersMapping mapping = (MembersMapping)xmlMembersMapping.Accessor.Mapping; + MembersMapping mapping = (MembersMapping)xmlMembersMapping.Accessor.Mapping!; CheckScope(xmlMembersMapping.Scope); if (mapping.HasWrapperElement && exportEnclosingType) { @@ -73,7 +74,7 @@ public void ExportMembersMapping(XmlMembersMapping xmlMembersMapping, bool expor } else { - foreach (MemberMapping member in mapping.Members) + foreach (MemberMapping member in mapping.Members!) { if (member.Attribute != null) throw new InvalidOperationException(SR.Format(SR.XmlBareAttributeMember, member.Attribute.Name)); @@ -82,7 +83,7 @@ public void ExportMembersMapping(XmlMembersMapping xmlMembersMapping, bool expor else if (member.Elements == null || member.Elements.Length == 0) continue; - if (member.TypeDesc.IsArrayLike && !(member.Elements[0].Mapping is ArrayMapping)) + if (member.TypeDesc!.IsArrayLike && !(member.Elements[0].Mapping is ArrayMapping)) throw new InvalidOperationException(SR.Format(SR.XmlIllegalArrayElement, member.Elements[0].Name)); if (exportEnclosingType) @@ -91,19 +92,19 @@ public void ExportMembersMapping(XmlMembersMapping xmlMembersMapping, bool expor } else { - ExportMapping(member.Elements[0].Mapping, member.Elements[0].Namespace, member.Elements[0].Any); + ExportMapping(member.Elements[0].Mapping!, member.Elements[0].Namespace, member.Elements[0].Any); } } } - ExportRootIfNecessary(xmlMembersMapping.Scope); + ExportRootIfNecessary(xmlMembersMapping.Scope!); } - private static XmlSchemaType FindSchemaType(string name, XmlSchemaObjectCollection items) + private static XmlSchemaType? FindSchemaType(string name, XmlSchemaObjectCollection items) { // Have to loop through the items because schema.SchemaTypes has not been populated yet. foreach (object o in items) { - XmlSchemaType type = o as XmlSchemaType; + XmlSchemaType? type = o as XmlSchemaType; if (type == null) continue; if (type.Name == name) @@ -114,7 +115,7 @@ private static XmlSchemaType FindSchemaType(string name, XmlSchemaObjectCollecti private static bool IsAnyType(XmlSchemaType schemaType, bool mixed, bool unbounded) { - XmlSchemaComplexType complexType = schemaType as XmlSchemaComplexType; + XmlSchemaComplexType? complexType = schemaType as XmlSchemaComplexType; if (complexType != null) { if (complexType.IsMixed != mixed) @@ -132,16 +133,16 @@ private static bool IsAnyType(XmlSchemaType schemaType, bool mixed, bool unbound return false; } - public string ExportAnyType(string ns) + public string ExportAnyType(string? ns) { string name = "any"; int i = 0; - XmlSchema schema = _schemas[ns]; + XmlSchema? schema = _schemas[ns]; if (schema != null) { while (true) { - XmlSchemaType schemaType = FindSchemaType(name, schema.Items); + XmlSchemaType? schemaType = FindSchemaType(name, schema.Items); if (schemaType == null) break; if (IsAnyType(schemaType, true, true)) @@ -164,13 +165,13 @@ public string ExportAnyType(string ns) return name; } - public string ExportAnyType(XmlMembersMapping members) + public string? ExportAnyType(XmlMembersMapping members) { if (members.Count == 1 && members[0].Any && members[0].ElementName.Length == 0) { XmlMemberMapping member = members[0]; - string ns = member.Namespace; - bool isUnbounded = member.Mapping.TypeDesc.IsArrayLike; + string? ns = member.Namespace; + bool isUnbounded = member.Mapping.TypeDesc!.IsArrayLike; bool isMixed = isUnbounded && member.Mapping.TypeDesc.ArrayElementTypeDesc != null ? member.Mapping.TypeDesc.ArrayElementTypeDesc.IsMixed : member.Mapping.TypeDesc.IsMixed; if (isMixed && member.Mapping.TypeDesc.IsMixed) @@ -181,12 +182,12 @@ public string ExportAnyType(XmlMembersMapping members) string baseName = isMixed ? "any" : isUnbounded ? "anyElements" : "anyElement"; string name = baseName; int i = 0; - XmlSchema schema = _schemas[ns]; + XmlSchema? schema = _schemas[ns]; if (schema != null) { while (true) { - XmlSchemaType schemaType = FindSchemaType(name, schema.Items); + XmlSchemaType? schemaType = FindSchemaType(name, schema.Items); if (schemaType == null) break; if (IsAnyType(schemaType, isMixed, isUnbounded)) @@ -215,7 +216,7 @@ public string ExportAnyType(XmlMembersMapping members) } } - private void CheckScope(TypeScope scope) + private void CheckScope(TypeScope? scope) { if (_scope == null) { @@ -227,15 +228,15 @@ private void CheckScope(TypeScope scope) } } - private XmlSchemaElement ExportElement(ElementAccessor accessor) + private XmlSchemaElement? ExportElement(ElementAccessor accessor) { - if (!accessor.Mapping.IncludeInSchema && !accessor.Mapping.TypeDesc.IsRoot) + if (!accessor.Mapping!.IncludeInSchema && !accessor.Mapping.TypeDesc!.IsRoot) { return null; } if (accessor.Any && accessor.Name.Length == 0) throw new InvalidOperationException(SR.XmlIllegalWildcard); - XmlSchemaElement element = (XmlSchemaElement)_elements[accessor]; + XmlSchemaElement? element = (XmlSchemaElement?)_elements[accessor]; if (element != null) return element; element = new XmlSchemaElement(); element.Name = accessor.Name; @@ -247,24 +248,24 @@ private XmlSchemaElement ExportElement(ElementAccessor accessor) return element; } - private void CheckForDuplicateType(TypeMapping mapping, string newNamespace) + private void CheckForDuplicateType(TypeMapping mapping, string? newNamespace) { if (mapping.IsAnonymousType) return; - string newTypeName = mapping.TypeName; - XmlSchema schema = _schemas[newNamespace]; + string? newTypeName = mapping.TypeName; + XmlSchema? schema = _schemas[newNamespace]; if (schema != null) { foreach (XmlSchemaObject o in schema.Items) { - XmlSchemaType type = o as XmlSchemaType; + XmlSchemaType? type = o as XmlSchemaType; if (type != null && type.Name == newTypeName) throw new InvalidOperationException(SR.Format(SR.XmlDuplicateTypeName, newTypeName, newNamespace)); } } } - private XmlSchema AddSchema(string targetNamespace) + private XmlSchema AddSchema(string? targetNamespace) { XmlSchema schema = new XmlSchema(); schema.TargetNamespace = string.IsNullOrEmpty(targetNamespace) ? null : targetNamespace; @@ -278,9 +279,9 @@ private XmlSchema AddSchema(string targetNamespace) return schema; } - private void AddSchemaItem(XmlSchemaObject item, string ns, string referencingNs) + private void AddSchemaItem(XmlSchemaObject item, string? ns, string? referencingNs) { - XmlSchema schema = _schemas[ns]; + XmlSchema? schema = _schemas[ns]; if (schema == null) { schema = AddSchema(ns); @@ -304,11 +305,11 @@ private void AddSchemaItem(XmlSchemaObject item, string ns, string referencingNs AddSchemaImport(ns, referencingNs); } - private void AddSchemaImport(string ns, string referencingNs) + private void AddSchemaImport(string? ns, string? referencingNs) { if (referencingNs == null) return; if (NamespacesEqual(ns, referencingNs)) return; - XmlSchema schema = _schemas[referencingNs]; + XmlSchema? schema = _schemas[referencingNs]; if (schema == null) { schema = AddSchema(referencingNs); @@ -322,7 +323,7 @@ private void AddSchemaImport(string ns, string referencingNs) } } - private static bool NamespacesEqual(string ns1, string ns2) + private static bool NamespacesEqual(string? ns1, string? ns2) { if (ns1 == null || ns1.Length == 0) return (ns2 == null || ns2.Length == 0); @@ -332,7 +333,7 @@ private static bool NamespacesEqual(string ns1, string ns2) private bool SchemaContainsItem(XmlSchemaObject item, string ns) { - XmlSchema schema = _schemas[ns]; + XmlSchema? schema = _schemas[ns]; if (schema != null) { return schema.Items.Contains(item); @@ -340,7 +341,7 @@ private bool SchemaContainsItem(XmlSchemaObject item, string ns) return false; } - private XmlSchemaImport FindImport(XmlSchema schema, string ns) + private XmlSchemaImport? FindImport(XmlSchema schema, string? ns) { foreach (object item in schema.Includes) { @@ -356,7 +357,7 @@ private XmlSchemaImport FindImport(XmlSchema schema, string ns) return null; } - private void ExportMapping(Mapping mapping, string ns, bool isAny) + private void ExportMapping(Mapping mapping, string? ns, bool isAny) { if (mapping is ArrayMapping) ExportArrayMapping((ArrayMapping)mapping, ns, null); @@ -371,12 +372,12 @@ private void ExportMapping(Mapping mapping, string ns, bool isAny) else if (mapping is SpecialMapping) ExportSpecialMapping((SpecialMapping)mapping, ns, isAny, null); else if (mapping is NullableMapping) - ExportMapping(((NullableMapping)mapping).BaseMapping, ns, isAny); + ExportMapping(((NullableMapping)mapping).BaseMapping!, ns, isAny); else throw new ArgumentException(SR.XmlInternalError, nameof(mapping)); } - private void ExportElementMapping(XmlSchemaElement element, Mapping mapping, string ns, bool isAny) + private void ExportElementMapping(XmlSchemaElement element, Mapping mapping, string? ns, bool isAny) { if (mapping is ArrayMapping) ExportArrayMapping((ArrayMapping)mapping, ns, element); @@ -402,15 +403,15 @@ private void ExportElementMapping(XmlSchemaElement element, Mapping mapping, str ExportSpecialMapping((SpecialMapping)mapping, ns, isAny, element); else if (mapping is NullableMapping) { - ExportElementMapping(element, ((NullableMapping)mapping).BaseMapping, ns, isAny); + ExportElementMapping(element, ((NullableMapping)mapping).BaseMapping!, ns, isAny); } else throw new ArgumentException(SR.XmlInternalError, nameof(mapping)); } - private XmlQualifiedName ExportNonXsdPrimitiveMapping(PrimitiveMapping mapping, string ns) + private XmlQualifiedName ExportNonXsdPrimitiveMapping(PrimitiveMapping mapping, string? ns) { - XmlSchemaSimpleType type = (XmlSchemaSimpleType)mapping.TypeDesc.DataType; + XmlSchemaSimpleType type = (XmlSchemaSimpleType)mapping.TypeDesc!.DataType!; if (!SchemaContainsItem(type, UrtTypes.Namespace)) { AddSchemaItem(type, UrtTypes.Namespace, ns); @@ -419,12 +420,12 @@ private XmlQualifiedName ExportNonXsdPrimitiveMapping(PrimitiveMapping mapping, { AddSchemaImport(mapping.Namespace, ns); } - return new XmlQualifiedName(mapping.TypeDesc.DataType.Name, UrtTypes.Namespace); + return new XmlQualifiedName(mapping.TypeDesc.DataType!.Name, UrtTypes.Namespace); } - private XmlSchemaType ExportSpecialMapping(SpecialMapping mapping, string ns, bool isAny, XmlSchemaElement element) + private XmlSchemaType? ExportSpecialMapping(SpecialMapping mapping, string? ns, bool isAny, XmlSchemaElement? element) { - switch (mapping.TypeDesc.Kind) + switch (mapping.TypeDesc!.Kind) { case TypeKind.Node: { @@ -482,21 +483,21 @@ private XmlSchemaType ExportSpecialMapping(SpecialMapping mapping, string ns, bo } else if (serializableMapping.XsiType != null || serializableMapping.XsdType != null) { - XmlSchemaType type = serializableMapping.XsdType; + XmlSchemaType? type = serializableMapping.XsdType; // for performance reasons we need to postpone merging of the serializable schemas - foreach (XmlSchema schema in serializableMapping.Schemas.Schemas()) + foreach (XmlSchema schema in serializableMapping.Schemas!.Schemas()) { if (schema.TargetNamespace != XmlSchema.Namespace) { _schemas.Add(schema, true); AddSchemaImport(schema.TargetNamespace, ns); - if (!serializableMapping.XsiType.IsEmpty && serializableMapping.XsiType.Namespace == schema.TargetNamespace) - type = (XmlSchemaType)schema.SchemaTypes[serializableMapping.XsiType]; + if (!serializableMapping.XsiType!.IsEmpty && serializableMapping.XsiType.Namespace == schema.TargetNamespace) + type = (XmlSchemaType?)schema.SchemaTypes[serializableMapping.XsiType]; } } if (element != null) { - element.SchemaTypeName = serializableMapping.XsiType; + element.SchemaTypeName = serializableMapping.XsiType!; if (element.SchemaTypeName.IsEmpty) element.SchemaType = type; } @@ -512,9 +513,9 @@ private XmlSchemaType ExportSpecialMapping(SpecialMapping mapping, string ns, bo XmlSchemaSequence seq = new XmlSchemaSequence(); seq.Items.Add(any); type.Particle = seq; - string anyNs = serializableMapping.Schema.TargetNamespace; + string? anyNs = serializableMapping.Schema.TargetNamespace; any.Namespace = anyNs == null ? "" : anyNs; - XmlSchema existingSchema = _schemas[anyNs]; + XmlSchema? existingSchema = _schemas[anyNs]; if (existingSchema == null) { _schemas.Add(serializableMapping.Schema); @@ -551,10 +552,10 @@ private XmlSchemaType ExportSpecialMapping(SpecialMapping mapping, string ns, bo } } - private XmlSchemaType ExportMembersMapping(MembersMapping mapping, string ns) + private XmlSchemaType ExportMembersMapping(MembersMapping mapping, string? ns) { XmlSchemaComplexType type = new XmlSchemaComplexType(); - ExportTypeMembers(type, mapping.Members, mapping.TypeName, ns, false, false); + ExportTypeMembers(type, mapping.Members!, mapping.TypeName!, ns, false, false); if (mapping.XmlnsMember != null) { @@ -576,7 +577,7 @@ private XmlSchemaType ExportAnonymousPrimitiveMapping(PrimitiveMapping mapping) } } - private XmlQualifiedName ExportPrimitiveMapping(PrimitiveMapping mapping, string ns) + private XmlQualifiedName ExportPrimitiveMapping(PrimitiveMapping mapping, string? ns) { XmlQualifiedName qname; if (mapping is EnumMapping) @@ -586,9 +587,9 @@ private XmlQualifiedName ExportPrimitiveMapping(PrimitiveMapping mapping, string } else { - if (mapping.TypeDesc.IsXsdType) + if (mapping.TypeDesc!.IsXsdType) { - qname = new XmlQualifiedName(mapping.TypeDesc.DataType.Name, XmlSchema.Namespace); + qname = new XmlQualifiedName(mapping.TypeDesc.DataType!.Name, XmlSchema.Namespace); } else { @@ -598,7 +599,7 @@ private XmlQualifiedName ExportPrimitiveMapping(PrimitiveMapping mapping, string return qname; } - private void ExportArrayMapping(ArrayMapping mapping, string ns, XmlSchemaElement element) + private void ExportArrayMapping(ArrayMapping mapping, string? ns, XmlSchemaElement? element) { // some of the items in the linked list differ only by CLR type. We don't need to // export different schema types for these. Look further down the list for another @@ -610,7 +611,7 @@ private void ExportArrayMapping(ArrayMapping mapping, string ns, XmlSchemaElemen { currentMapping = currentMapping.Next; } - XmlSchemaComplexType type = (XmlSchemaComplexType)_types[currentMapping]; + XmlSchemaComplexType? type = (XmlSchemaComplexType?)_types[currentMapping]; if (type == null) { CheckForDuplicateType(currentMapping, currentMapping.Namespace); @@ -623,7 +624,7 @@ private void ExportArrayMapping(ArrayMapping mapping, string ns, XmlSchemaElemen if (!currentMapping.IsAnonymousType) _types.Add(currentMapping, type); XmlSchemaSequence seq = new XmlSchemaSequence(); - ExportElementAccessors(seq, mapping.Elements, true, false, mapping.Namespace); + ExportElementAccessors(seq, mapping.Elements!, true, false, mapping.Namespace); if (seq.Items.Count > 0) { #if DEBUG @@ -658,7 +659,7 @@ private void ExportArrayMapping(ArrayMapping mapping, string ns, XmlSchemaElemen } } - private void ExportElementAccessors(XmlSchemaGroupBase group, ElementAccessor[] accessors, bool repeats, bool valueTypeOptional, string ns) + private void ExportElementAccessors(XmlSchemaGroupBase group, ElementAccessor[] accessors, bool repeats, bool valueTypeOptional, string? ns) { if (accessors.Length == 0) return; if (accessors.Length == 1) @@ -677,7 +678,7 @@ private void ExportElementAccessors(XmlSchemaGroupBase group, ElementAccessor[] } } - private void ExportAttributeAccessor(XmlSchemaComplexType type, AttributeAccessor accessor, bool valueTypeOptional, string ns) + private void ExportAttributeAccessor(XmlSchemaComplexType type, AttributeAccessor? accessor, bool valueTypeOptional, string? ns) { if (accessor == null) return; XmlSchemaObjectCollection attributes; @@ -691,7 +692,7 @@ private void ExportAttributeAccessor(XmlSchemaComplexType type, AttributeAccesso else if (type.ContentModel.Content is XmlSchemaSimpleContentExtension) attributes = ((XmlSchemaSimpleContentExtension)type.ContentModel.Content).Attributes; else - throw new InvalidOperationException(SR.Format(SR.XmlInvalidContent, type.ContentModel.Content.GetType().Name)); + throw new InvalidOperationException(SR.Format(SR.XmlInvalidContent, type.ContentModel.Content!.GetType().Name)); } else { @@ -717,7 +718,7 @@ private void ExportAttributeAccessor(XmlSchemaComplexType type, AttributeAccesso } else { - XmlSchemaContent content = type.ContentModel.Content; + XmlSchemaContent? content = type.ContentModel.Content; if (content is XmlSchemaComplexContentExtension) { XmlSchemaComplexContentExtension extension = (XmlSchemaComplexContentExtension)content; @@ -730,7 +731,7 @@ private void ExportAttributeAccessor(XmlSchemaComplexType type, AttributeAccesso } else if (type.ContentModel.Content is XmlSchemaSimpleContentExtension) { - XmlSchemaSimpleContentExtension extension = (XmlSchemaSimpleContentExtension)content; + XmlSchemaSimpleContentExtension extension = (XmlSchemaSimpleContentExtension)content!; extension.AnyAttribute = new XmlSchemaAnyAttribute(); } } @@ -739,7 +740,7 @@ private void ExportAttributeAccessor(XmlSchemaComplexType type, AttributeAccesso { XmlSchemaAttribute attribute = new XmlSchemaAttribute(); attribute.Use = XmlSchemaUse.None; - if (!accessor.HasDefault && !valueTypeOptional && accessor.Mapping.TypeDesc.IsValueType) + if (!accessor.HasDefault && !valueTypeOptional && accessor.Mapping!.TypeDesc!.IsValueType) { attribute.Use = XmlSchemaUse.Required; } @@ -747,7 +748,7 @@ private void ExportAttributeAccessor(XmlSchemaComplexType type, AttributeAccesso if (accessor.Namespace == null || accessor.Namespace == ns) { // determine the form attribute value - XmlSchema schema = _schemas[ns]; + XmlSchema? schema = _schemas[ns]; if (schema == null) attribute.Form = accessor.Form == attributeFormDefault ? XmlSchemaForm.None : accessor.Form; else @@ -813,7 +814,7 @@ private void ExportAttributeAccessor(XmlSchemaComplexType type, AttributeAccesso } } - private void ExportElementAccessor(XmlSchemaGroupBase group, ElementAccessor accessor, bool repeats, bool valueTypeOptional, string ns) + private void ExportElementAccessor(XmlSchemaGroupBase group, ElementAccessor accessor, bool repeats, bool valueTypeOptional, string? ns) { if (accessor.Any && accessor.Name.Length == 0) { @@ -826,8 +827,8 @@ private void ExportElementAccessor(XmlSchemaGroupBase group, ElementAccessor acc } else { - XmlSchemaElement element = (XmlSchemaElement)_elements[accessor]; - int minOccurs = repeats || accessor.HasDefault || (!accessor.IsNullable && !accessor.Mapping.TypeDesc.IsValueType) || valueTypeOptional ? 0 : 1; + XmlSchemaElement? element = (XmlSchemaElement?)_elements[accessor]; + int minOccurs = repeats || accessor.HasDefault || (!accessor.IsNullable && !accessor.Mapping!.TypeDesc!.IsValueType) || valueTypeOptional ? 0 : 1; decimal maxOccurs = repeats || accessor.IsUnbounded ? decimal.MaxValue : 1; if (element == null) @@ -836,7 +837,7 @@ private void ExportElementAccessor(XmlSchemaGroupBase group, ElementAccessor acc element.IsNillable = accessor.IsNullable; element.Name = accessor.Name; if (accessor.HasDefault) - element.DefaultValue = ExportDefaultValue(accessor.Mapping, accessor.Default); + element.DefaultValue = ExportDefaultValue(accessor.Mapping!, accessor.Default); if (accessor.IsTopLevelInSchema) { @@ -849,7 +850,7 @@ private void ExportElementAccessor(XmlSchemaGroupBase group, ElementAccessor acc element.MinOccurs = minOccurs; element.MaxOccurs = maxOccurs; // determine the form attribute value - XmlSchema schema = _schemas[ns]; + XmlSchema? schema = _schemas[ns]; if (schema == null) element.Form = accessor.Form == elementFormDefault ? XmlSchemaForm.None : accessor.Form; else @@ -857,7 +858,7 @@ private void ExportElementAccessor(XmlSchemaGroupBase group, ElementAccessor acc element.Form = accessor.Form == schema.ElementFormDefault ? XmlSchemaForm.None : accessor.Form; } } - ExportElementMapping(element, (TypeMapping)accessor.Mapping, accessor.Namespace, accessor.Any); + ExportElementMapping(element, (TypeMapping)accessor.Mapping!, accessor.Namespace, accessor.Any); } if (accessor.IsTopLevelInSchema) { @@ -875,7 +876,7 @@ private void ExportElementAccessor(XmlSchemaGroupBase group, ElementAccessor acc } } - internal static string ExportDefaultValue(TypeMapping mapping, object value) + internal static string? ExportDefaultValue(TypeMapping mapping, object? value) { if (!(mapping is PrimitiveMapping)) // should throw, but it will be a breaking change; @@ -894,7 +895,7 @@ internal static string ExportDefaultValue(TypeMapping mapping, object value) #endif // check the validity of the value - ConstantMapping[] c = em.Constants; + ConstantMapping[] c = em.Constants!; if (em.IsFlags) { string[] names = new string[c.Length]; @@ -907,7 +908,7 @@ internal static string ExportDefaultValue(TypeMapping mapping, object value) values.Add(c[i].Name, ids[i]); } long val = XmlCustomFormatter.ToEnum((string)value, values, em.TypeName, false); - return val != 0 ? XmlCustomFormatter.FromEnum(val, names, ids, mapping.TypeDesc.FullName) : null; + return val != 0 ? XmlCustomFormatter.FromEnum(val, names, ids, mapping.TypeDesc!.FullName) : null; } else { @@ -924,7 +925,7 @@ internal static string ExportDefaultValue(TypeMapping mapping, object value) PrimitiveMapping pm = (PrimitiveMapping)mapping; - if (!pm.TypeDesc.HasCustomFormatter) + if (!pm.TypeDesc!.HasCustomFormatter) { #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe @@ -938,13 +939,13 @@ internal static string ExportDefaultValue(TypeMapping mapping, object value) return (string)value; Type formatter = typeof(XmlConvert); - System.Reflection.MethodInfo format = formatter.GetMethod("ToString", new Type[] { pm.TypeDesc.Type }); + System.Reflection.MethodInfo? format = formatter.GetMethod("ToString", new Type[] { pm.TypeDesc.Type! }); if (format != null) - return (string)format.Invoke(formatter, new object[] { value }); + return (string)format.Invoke(formatter, new object[] { value })!; } else { - string defaultValue = XmlCustomFormatter.FromDefaultValue(value, pm.TypeDesc.FormatterName); + string defaultValue = XmlCustomFormatter.FromDefaultValue(value, pm.TypeDesc.FormatterName!); if (defaultValue == null) throw new InvalidOperationException(SR.Format(SR.XmlInvalidDefaultValue, value, pm.TypeDesc.Name)); return defaultValue; @@ -958,7 +959,7 @@ private void ExportRootIfNecessary(TypeScope typeScope) return; foreach (TypeMapping mapping in typeScope.TypeMappings) { - if (mapping is StructMapping && mapping.TypeDesc.IsRoot) + if (mapping is StructMapping && mapping.TypeDesc!.IsRoot) { ExportDerivedMappings((StructMapping)mapping); } @@ -973,9 +974,9 @@ private void ExportRootIfNecessary(TypeScope typeScope) } } - private XmlQualifiedName ExportStructMapping(StructMapping mapping, string ns, XmlSchemaElement element) + private XmlQualifiedName ExportStructMapping(StructMapping mapping, string? ns, XmlSchemaElement? element) { - if (mapping.TypeDesc.IsRoot) + if (mapping.TypeDesc!.IsRoot) { _needToExportRoot = true; return XmlQualifiedName.Empty; @@ -986,7 +987,7 @@ private XmlQualifiedName ExportStructMapping(StructMapping mapping, string ns, X throw new InvalidOperationException(SR.Format(SR.XmlCircularReference2, mapping.TypeDesc.Name, "AnonymousType", "false")); _references[mapping] = mapping; } - XmlSchemaComplexType type = (XmlSchemaComplexType)_types[mapping]; + XmlSchemaComplexType? type = (XmlSchemaComplexType?)_types[mapping]; if (type == null) { if (!mapping.IncludeInSchema) throw new InvalidOperationException(SR.Format(SR.XmlCannotIncludeInSchema, mapping.TypeDesc.Name)); @@ -1004,7 +1005,7 @@ private XmlQualifiedName ExportStructMapping(StructMapping mapping, string ns, X { if (mapping.BaseMapping.IsAnonymousType) { - throw new InvalidOperationException(SR.Format(SR.XmlAnonymousBaseType, mapping.TypeDesc.Name, mapping.BaseMapping.TypeDesc.Name, "AnonymousType", "false")); + throw new InvalidOperationException(SR.Format(SR.XmlAnonymousBaseType, mapping.TypeDesc.Name, mapping.BaseMapping.TypeDesc!.Name, "AnonymousType", "false")); } if (mapping.HasSimpleContent) { @@ -1020,12 +1021,12 @@ private XmlQualifiedName ExportStructMapping(StructMapping mapping, string ns, X extension.BaseTypeName = ExportStructMapping(mapping.BaseMapping, mapping.Namespace, null); XmlSchemaComplexContent model = new XmlSchemaComplexContent(); model.Content = extension; - model.IsMixed = XmlSchemaImporter.IsMixed((XmlSchemaComplexType)_types[mapping.BaseMapping]); + model.IsMixed = XmlSchemaImporter.IsMixed((XmlSchemaComplexType)_types[mapping.BaseMapping]!); type.ContentModel = model; } openModel = false; } - ExportTypeMembers(type, mapping.Members, mapping.TypeName, mapping.Namespace, mapping.HasSimpleContent, openModel); + ExportTypeMembers(type, mapping.Members!, mapping.TypeName!, mapping.Namespace, mapping.HasSimpleContent, openModel); ExportDerivedMappings(mapping); if (mapping.XmlnsMember != null) { @@ -1051,10 +1052,10 @@ private XmlQualifiedName ExportStructMapping(StructMapping mapping, string ns, X } } - private void ExportTypeMembers(XmlSchemaComplexType type, MemberMapping[] members, string name, string ns, bool hasSimpleContent, bool openModel) + private void ExportTypeMembers(XmlSchemaComplexType type, MemberMapping[] members, string name, string? ns, bool hasSimpleContent, bool openModel) { XmlSchemaGroupBase seq = new XmlSchemaSequence(); - TypeMapping textMapping = null; + TypeMapping? textMapping = null; for (int i = 0; i < members.Length; i++) { @@ -1069,9 +1070,9 @@ private void ExportTypeMembers(XmlSchemaComplexType type, MemberMapping[] member } textMapping = member.Text.Mapping; } - if (member.Elements.Length > 0) + if (member.Elements!.Length > 0) { - bool repeats = member.TypeDesc.IsArrayLike && + bool repeats = member.TypeDesc!.IsArrayLike && !(member.Elements.Length == 1 && member.Elements[0].Mapping is ArrayMapping); bool valueTypeOptional = member.CheckSpecified != SpecifiedAccessor.None || member.CheckShouldPersist; @@ -1088,7 +1089,7 @@ private void ExportTypeMembers(XmlSchemaComplexType type, MemberMapping[] member else if (type.ContentModel.Content is XmlSchemaComplexContentExtension) ((XmlSchemaComplexContentExtension)type.ContentModel.Content).Particle = seq; else - throw new InvalidOperationException(SR.Format(SR.XmlInvalidContent, type.ContentModel.Content.GetType().Name)); + throw new InvalidOperationException(SR.Format(SR.XmlInvalidContent, type.ContentModel.Content!.GetType().Name)); } else { @@ -1110,7 +1111,7 @@ private void ExportTypeMembers(XmlSchemaComplexType type, MemberMapping[] member { if (pm.IsAnonymousType) { - throw new InvalidOperationException(SR.Format(SR.XmlAnonymousBaseType, textMapping.TypeDesc.Name, pm.TypeDesc.Name, "AnonymousType", "false")); + throw new InvalidOperationException(SR.Format(SR.XmlAnonymousBaseType, textMapping.TypeDesc!.Name, pm.TypeDesc!.Name, "AnonymousType", "false")); } // Create simpleContent XmlSchemaSimpleContent model = new XmlSchemaSimpleContent(); @@ -1129,11 +1130,11 @@ private void ExportTypeMembers(XmlSchemaComplexType type, MemberMapping[] member bool anyAttribute = false; for (int i = 0; i < members.Length; i++) { - AttributeAccessor accessor = members[i].Attribute; + AttributeAccessor? accessor = members[i].Attribute; if (accessor != null) { ExportAttributeAccessor(type, members[i].Attribute, members[i].CheckSpecified != SpecifiedAccessor.None || members[i].CheckShouldPersist, ns); - if (members[i].Attribute.Any) + if (members[i].Attribute!.Any) anyAttribute = true; } } @@ -1149,16 +1150,16 @@ private void ExportDerivedMappings(StructMapping mapping) { if (mapping.IsAnonymousType) return; - for (StructMapping derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) + for (StructMapping? derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) { if (derived.IncludeInSchema) ExportStructMapping(derived, derived.Namespace, null); } } - private XmlSchemaType ExportEnumMapping(EnumMapping mapping, string ns) + private XmlSchemaType ExportEnumMapping(EnumMapping mapping, string? ns) { - if (!mapping.IncludeInSchema) throw new InvalidOperationException(SR.Format(SR.XmlCannotIncludeInSchema, mapping.TypeDesc.Name)); - XmlSchemaSimpleType dataType = (XmlSchemaSimpleType)_types[mapping]; + if (!mapping.IncludeInSchema) throw new InvalidOperationException(SR.Format(SR.XmlCannotIncludeInSchema, mapping.TypeDesc!.Name)); + XmlSchemaSimpleType? dataType = (XmlSchemaSimpleType?)_types[mapping]; if (dataType == null) { CheckForDuplicateType(mapping, mapping.Namespace); @@ -1172,7 +1173,7 @@ private XmlSchemaType ExportEnumMapping(EnumMapping mapping, string ns) XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction(); restriction.BaseTypeName = new XmlQualifiedName("string", XmlSchema.Namespace); - for (int i = 0; i < mapping.Constants.Length; i++) + for (int i = 0; i < mapping.Constants!.Length; i++) { ConstantMapping constant = mapping.Constants[i]; XmlSchemaEnumerationFacet enumeration = new XmlSchemaEnumerationFacet(); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaImporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaImporter.cs index a9cb30c25eb8e3..a4b64f5bf587cc 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaImporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaImporter.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; @@ -21,9 +22,9 @@ public class XmlSchemaImporter : SchemaImporter { public XmlSchemaImporter(XmlSchemas schemas) : base(schemas, CodeGenerationOptions.GenerateProperties, new ImportContext()) { } - public XmlSchemaImporter(XmlSchemas schemas, CodeIdentifiers typeIdentifiers) : base(schemas, CodeGenerationOptions.GenerateProperties, new ImportContext(typeIdentifiers, false)) { } + public XmlSchemaImporter(XmlSchemas schemas, CodeIdentifiers? typeIdentifiers) : base(schemas, CodeGenerationOptions.GenerateProperties, new ImportContext(typeIdentifiers, false)) { } - public XmlTypeMapping ImportDerivedTypeMapping(XmlQualifiedName name, Type baseType) + public XmlTypeMapping ImportDerivedTypeMapping(XmlQualifiedName name, Type? baseType) { return ImportDerivedTypeMapping(name, baseType, false); } @@ -37,12 +38,12 @@ internal TypeMapping GetDefaultMapping(TypeFlags flags) { PrimitiveMapping mapping = new PrimitiveMapping(); mapping.TypeDesc = Scope.GetTypeDesc("string", XmlSchema.Namespace, flags); - mapping.TypeName = mapping.TypeDesc.DataType.Name; + mapping.TypeName = mapping.TypeDesc!.DataType!.Name; mapping.Namespace = XmlSchema.Namespace; return mapping; } - public XmlTypeMapping ImportDerivedTypeMapping(XmlQualifiedName name, Type baseType, bool baseTypeCanBeIndirect) + public XmlTypeMapping ImportDerivedTypeMapping(XmlQualifiedName name, Type? baseType, bool baseTypeCanBeIndirect) { ElementAccessor element = ImportElement(name, typeof(TypeMapping), baseType); @@ -56,7 +57,7 @@ public XmlTypeMapping ImportDerivedTypeMapping(XmlQualifiedName name, Type baseT { // in the case of the ArrayMapping we can use the top-level StructMapping, because it does not have base base type element.Mapping = ((ArrayMapping)element.Mapping).TopLevelMapping; - MakeDerived((StructMapping)element.Mapping, baseType, baseTypeCanBeIndirect); + MakeDerived((StructMapping)element.Mapping!, baseType, baseTypeCanBeIndirect); } else { @@ -72,14 +73,14 @@ public XmlTypeMapping ImportSchemaType(XmlQualifiedName typeName) return ImportSchemaType(typeName, null, false); } - public XmlTypeMapping ImportSchemaType(XmlQualifiedName typeName, Type baseType) + public XmlTypeMapping ImportSchemaType(XmlQualifiedName typeName, Type? baseType) { return ImportSchemaType(typeName, baseType, false); } - public XmlTypeMapping ImportSchemaType(XmlQualifiedName typeName, Type baseType, bool baseTypeCanBeIndirect) + public XmlTypeMapping ImportSchemaType(XmlQualifiedName typeName, Type? baseType, bool baseTypeCanBeIndirect) { - TypeMapping typeMapping = ImportType(typeName, typeof(TypeMapping), baseType, TypeFlags.CanBeElementValue, true); + TypeMapping typeMapping = ImportType(typeName, typeof(TypeMapping), baseType, TypeFlags.CanBeElementValue, true)!; typeMapping.ReferencedByElement = false; ElementAccessor accessor = new ElementAccessor(); @@ -90,7 +91,7 @@ public XmlTypeMapping ImportSchemaType(XmlQualifiedName typeName, Type baseType, if (typeMapping is SpecialMapping && ((SpecialMapping)typeMapping).NamedAny) accessor.Any = true; - accessor.IsNullable = typeMapping.TypeDesc.IsNullable; + accessor.IsNullable = typeMapping.TypeDesc!.IsNullable; accessor.Form = XmlSchemaForm.Qualified; if (accessor.Mapping is StructMapping) @@ -103,7 +104,7 @@ public XmlTypeMapping ImportSchemaType(XmlQualifiedName typeName, Type baseType, { // in the case of the ArrayMapping we can use the top-level StructMapping, because it does not have base base type accessor.Mapping = ((ArrayMapping)accessor.Mapping).TopLevelMapping; - MakeDerived((StructMapping)accessor.Mapping, baseType, baseTypeCanBeIndirect); + MakeDerived((StructMapping)accessor.Mapping!, baseType, baseTypeCanBeIndirect); } else { @@ -124,10 +125,10 @@ public XmlMembersMapping ImportMembersMapping(XmlQualifiedName name) return new XmlMembersMapping(Scope, ImportElement(name, typeof(MembersMapping), null), XmlMappingAccess.Read | XmlMappingAccess.Write); } - public XmlMembersMapping ImportAnyType(XmlQualifiedName typeName, string elementName) + public XmlMembersMapping? ImportAnyType(XmlQualifiedName typeName, string elementName) { - TypeMapping typeMapping = ImportType(typeName, typeof(MembersMapping), null, TypeFlags.CanBeElementValue, true); - MembersMapping mapping = typeMapping as MembersMapping; + TypeMapping? typeMapping = ImportType(typeName, typeof(MembersMapping), null, TypeFlags.CanBeElementValue, true); + MembersMapping? mapping = typeMapping as MembersMapping; if (mapping == null) { @@ -141,7 +142,7 @@ public XmlMembersMapping ImportAnyType(XmlQualifiedName typeName, string element mapping = ImportMembersType(type, typeName.Namespace, elementName); } - if (mapping.Members.Length != 1 || !mapping.Members[0].Accessor.Any) + if (mapping.Members!.Length != 1 || !mapping.Members[0].Accessor!.Any) return null; mapping.Members[0].Name = elementName; ElementAccessor accessor = new ElementAccessor(); @@ -150,10 +151,10 @@ public XmlMembersMapping ImportAnyType(XmlQualifiedName typeName, string element accessor.Mapping = mapping; accessor.Any = true; - XmlSchemaObject xso = Schemas.SchemaSet.GlobalTypes[typeName]; + XmlSchemaObject? xso = Schemas.SchemaSet.GlobalTypes[typeName]; if (xso != null) { - XmlSchema schema = xso.Parent as XmlSchema; + XmlSchema? schema = xso.Parent as XmlSchema; if (schema != null) { accessor.Form = schema.ElementFormDefault == XmlSchemaForm.None ? XmlSchemaForm.Unqualified : schema.ElementFormDefault; @@ -168,7 +169,7 @@ public XmlMembersMapping ImportMembersMapping(XmlQualifiedName[] names) return ImportMembersMapping(names, null, false); } - public XmlMembersMapping ImportMembersMapping(XmlQualifiedName[] names, Type baseType, bool baseTypeCanBeIndirect) + public XmlMembersMapping ImportMembersMapping(XmlQualifiedName[] names, Type? baseType, bool baseTypeCanBeIndirect) { CodeIdentifiers memberScope = new CodeIdentifiers(); memberScope.UseCamelCasing = true; @@ -183,7 +184,7 @@ public XmlMembersMapping ImportMembersMapping(XmlQualifiedName[] names, Type bas MemberMapping member = new MemberMapping(); member.Name = CodeIdentifier.MakeValid(Accessor.UnescapeName(accessor.Name)); member.Name = memberScope.AddUnique(member.Name, member); - member.TypeDesc = accessor.Mapping.TypeDesc; + member.TypeDesc = accessor.Mapping!.TypeDesc; member.Elements = new ElementAccessor[] { accessor }; members[i] = member; } @@ -196,7 +197,7 @@ public XmlMembersMapping ImportMembersMapping(XmlQualifiedName[] names, Type bas return new XmlMembersMapping(Scope, element, XmlMappingAccess.Read | XmlMappingAccess.Write); } - public XmlMembersMapping ImportMembersMapping(string name, string ns, SoapSchemaMember[] members) + public XmlMembersMapping ImportMembersMapping(string name, string? ns, SoapSchemaMember[] members) { XmlSchemaComplexType type = new XmlSchemaComplexType(); XmlSchemaSequence seq = new XmlSchemaSequence(); @@ -219,13 +220,13 @@ public XmlMembersMapping ImportMembersMapping(string name, string ns, SoapSchema return new XmlMembersMapping(Scope, accessor, XmlMappingAccess.Read | XmlMappingAccess.Write); } - private ElementAccessor ImportElement(XmlQualifiedName name, Type desiredMappingType, Type baseType) + private ElementAccessor ImportElement(XmlQualifiedName name, Type desiredMappingType, Type? baseType) { XmlSchemaElement element = FindElement(name); - ElementAccessor accessor = (ElementAccessor)ImportedElements[element]; + ElementAccessor? accessor = (ElementAccessor?)ImportedElements[element]; if (accessor != null) return accessor; accessor = ImportElement(element, string.Empty, desiredMappingType, baseType, name.Namespace, true); - ElementAccessor existing = (ElementAccessor)ImportedElements[element]; + ElementAccessor? existing = (ElementAccessor?)ImportedElements[element]; if (existing != null) { return existing; @@ -234,7 +235,7 @@ private ElementAccessor ImportElement(XmlQualifiedName name, Type desiredMapping return accessor; } - private ElementAccessor ImportElement(XmlSchemaElement element, string identifier, Type desiredMappingType, Type baseType, string ns, bool topLevelElement) + private ElementAccessor ImportElement(XmlSchemaElement element, string identifier, Type desiredMappingType, Type? baseType, string? ns, bool topLevelElement) { if (!element.RefName.IsEmpty) { @@ -244,13 +245,13 @@ private ElementAccessor ImportElement(XmlSchemaElement element, string identifie { ElementAccessor refAccessor = topAccessor.Clone(); refAccessor.IsTopLevelInSchema = false; - refAccessor.Mapping.ReferencedByElement = true; + refAccessor.Mapping!.ReferencedByElement = true; return refAccessor; } return topAccessor; } - if (element.Name.Length == 0) + if (element.Name!.Length == 0) { XmlQualifiedName parentType = XmlSchemas.GetParentName(element); throw new InvalidOperationException(SR.Format(SR.XmlElementHasNoName, parentType.Name, parentType.Namespace)); @@ -292,15 +293,15 @@ private ElementAccessor ImportElement(XmlSchemaElement element, string identifie return accessor; } - private TypeMapping ImportElementType(XmlSchemaElement element, string identifier, Type desiredMappingType, Type baseType, string ns) + private TypeMapping ImportElementType(XmlSchemaElement element, string identifier, Type desiredMappingType, Type? baseType, string? ns) { - TypeMapping mapping; + TypeMapping? mapping; if (!element.SchemaTypeName.IsEmpty) { - mapping = ImportType(element.SchemaTypeName, desiredMappingType, baseType, TypeFlags.CanBeElementValue, false); + mapping = ImportType(element.SchemaTypeName, desiredMappingType, baseType, TypeFlags.CanBeElementValue, false)!; if (!mapping.ReferencedByElement) { - object type = FindType(element.SchemaTypeName, TypeFlags.CanBeElementValue); + object? type = FindType(element.SchemaTypeName, TypeFlags.CanBeElementValue); XmlSchemaObject parent = element; while (parent.Parent != null && type != parent) { @@ -314,8 +315,8 @@ private TypeMapping ImportElementType(XmlSchemaElement element, string identifie if (element.SchemaType is XmlSchemaComplexType) mapping = ImportType((XmlSchemaComplexType)element.SchemaType, ns, identifier, desiredMappingType, baseType, TypeFlags.CanBeElementValue); else - mapping = ImportDataType((XmlSchemaSimpleType)element.SchemaType, ns, identifier, baseType, TypeFlags.CanBeElementValue | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeTextValue, false); - mapping.ReferencedByElement = true; + mapping = ImportDataType((XmlSchemaSimpleType)element.SchemaType, ns, identifier, baseType, TypeFlags.CanBeElementValue | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeTextValue, false)!; + mapping!.ReferencedByElement = true; } else if (!element.SubstitutionGroup.IsEmpty) mapping = ImportElementType(FindElement(element.SubstitutionGroup), identifier, desiredMappingType, baseType, ns); @@ -334,18 +335,18 @@ private TypeMapping ImportElementType(XmlSchemaElement element, string identifie throw new InvalidOperationException(SR.Format(SR.XmlElementImportedTwice, element.Name, ns, mapping.GetType().Name, desiredMappingType.Name)); // let the extensions to run - if (!mapping.TypeDesc.IsMappedType) + if (!mapping.TypeDesc!.IsMappedType) { RunSchemaExtensions(mapping, element.SchemaTypeName, element.SchemaType, element, TypeFlags.CanBeElementValue); } return mapping; } - private void RunSchemaExtensions(TypeMapping mapping, XmlQualifiedName qname, XmlSchemaType type, XmlSchemaObject context, TypeFlags flags) + private void RunSchemaExtensions(TypeMapping mapping, XmlQualifiedName qname, XmlSchemaType? type, XmlSchemaObject context, TypeFlags flags) { // nop } - private string GenerateUniqueTypeName(string desiredName, string ns) + private string GenerateUniqueTypeName(string desiredName, string? ns) { int i = 1; @@ -354,7 +355,7 @@ private string GenerateUniqueTypeName(string desiredName, string ns) { XmlQualifiedName qname = new XmlQualifiedName(typeName, ns); - object type = Schemas.Find(qname, typeof(XmlSchemaType)); + object? type = Schemas.Find(qname, typeof(XmlSchemaType)); if (type == null) { break; @@ -387,13 +388,13 @@ internal override void ImportDerivedTypes(XmlQualifiedName baseName) } } - private TypeMapping ImportType(XmlQualifiedName name, Type desiredMappingType, Type baseType, TypeFlags flags, bool addref) + private TypeMapping? ImportType(XmlQualifiedName name, Type desiredMappingType, Type? baseType, TypeFlags flags, bool addref) { if (name.Name == Soap.UrType && name.Namespace == XmlSchema.Namespace) return ImportRootMapping(); - object type = FindType(name, flags); + object type = FindType(name, flags)!; - TypeMapping mapping = (TypeMapping)ImportedMappings[type]; + TypeMapping? mapping = (TypeMapping?)ImportedMappings[type]; if (mapping != null && desiredMappingType.IsAssignableFrom(mapping.GetType())) return mapping; @@ -414,7 +415,7 @@ private TypeMapping ImportType(XmlQualifiedName name, Type desiredMappingType, T return mapping; } - private TypeMapping ImportType(XmlSchemaComplexType type, string typeNs, string identifier, Type desiredMappingType, Type baseType, TypeFlags flags) + private TypeMapping? ImportType(XmlSchemaComplexType type, string? typeNs, string identifier, Type desiredMappingType, Type? baseType, TypeFlags flags) { if (type.Redefined != null) { @@ -423,7 +424,7 @@ private TypeMapping ImportType(XmlSchemaComplexType type, string typeNs, string } if (desiredMappingType == typeof(TypeMapping)) { - TypeMapping mapping = null; + TypeMapping? mapping = null; if (baseType == null) { @@ -447,7 +448,7 @@ private TypeMapping ImportType(XmlSchemaComplexType type, string typeNs, string throw new ArgumentException(SR.XmlInternalError, nameof(desiredMappingType)); } - private MembersMapping ImportMembersType(XmlSchemaType type, string typeNs, string identifier) + private MembersMapping ImportMembersType(XmlSchemaType type, string? typeNs, string identifier) { if (!type.DerivedFrom.IsEmpty) throw new InvalidOperationException(SR.XmlMembersDeriveError); CodeIdentifiers memberScope = new CodeIdentifiers(); @@ -461,10 +462,10 @@ private MembersMapping ImportMembersType(XmlSchemaType type, string typeNs, stri return mappings; } - private StructMapping ImportStructType(XmlSchemaType type, string typeNs, string identifier, Type baseType, bool arrayLike) + private StructMapping ImportStructType(XmlSchemaType type, string? typeNs, string identifier, Type? baseType, bool arrayLike) { - TypeDesc baseTypeDesc = null; - TypeMapping baseMapping = null; + TypeDesc? baseTypeDesc = null; + TypeMapping? baseMapping = null; bool isRootType = false; if (!type.DerivedFrom.IsEmpty) @@ -493,7 +494,7 @@ private StructMapping ImportStructType(XmlSchemaType type, string typeNs, string baseMapping = GetRootMapping(); isRootType = true; } - Mapping previousMapping = (Mapping)ImportedMappings[type]; + Mapping? previousMapping = (Mapping?)ImportedMappings[type]; if (previousMapping != null) { if (previousMapping is StructMapping) @@ -554,10 +555,10 @@ private StructMapping ImportStructType(XmlSchemaType type, string typeNs, string for (int i = 0; i < structMapping.Members.Length; i++) { - StructMapping declaringMapping; - MemberMapping baseMember = ((StructMapping)baseMapping).FindDeclaringMapping(structMapping.Members[i], out declaringMapping, structMapping.TypeName); + StructMapping? declaringMapping; + MemberMapping? baseMember = ((StructMapping)baseMapping).FindDeclaringMapping(structMapping.Members[i], out declaringMapping, structMapping.TypeName); if (baseMember != null && baseMember.TypeDesc != structMapping.Members[i].TypeDesc) - throw new InvalidOperationException(SR.Format(SR.XmlIllegalOverride, type.Name, baseMember.Name, baseMember.TypeDesc.FullName, structMapping.Members[i].TypeDesc.FullName, declaringMapping.TypeDesc.FullName)); + throw new InvalidOperationException(SR.Format(SR.XmlIllegalOverride, type.Name, baseMember.Name, baseMember.TypeDesc!.FullName, structMapping.Members[i].TypeDesc!.FullName, declaringMapping!.TypeDesc!.FullName)); } structMapping.Scope = membersScope; Scope.AddTypeMapping(structMapping); @@ -570,7 +571,7 @@ private bool IsAllGroup(XmlSchemaType type) return (items.Particle != null) && (items.Particle is XmlSchemaAll); } - private StructMapping ImportStructDataType(XmlSchemaSimpleType dataType, string typeNs, string identifier, Type baseType) + private StructMapping ImportStructDataType(XmlSchemaSimpleType dataType, string? typeNs, string identifier, Type baseType) { identifier = Accessor.UnescapeName(identifier); string typeName = GenerateUniqueTypeName(identifier); @@ -594,13 +595,13 @@ private StructMapping ImportStructDataType(XmlSchemaSimpleType dataType, string private class TypeItems { internal XmlSchemaObjectCollection Attributes = new XmlSchemaObjectCollection(); - internal XmlSchemaAnyAttribute AnyAttribute; - internal XmlSchemaGroupBase Particle; - internal XmlQualifiedName baseSimpleType; + internal XmlSchemaAnyAttribute? AnyAttribute; + internal XmlSchemaGroupBase? Particle; + internal XmlQualifiedName? baseSimpleType; internal bool IsUnbounded; } - private MemberMapping[] ImportTypeMembers(XmlSchemaType type, string typeNs, string identifier, CodeIdentifiers members, CodeIdentifiers membersScope, INameScope elementsScope, ref bool needExplicitOrder, bool order, bool allowUnboundedElements) + private MemberMapping[] ImportTypeMembers(XmlSchemaType type, string? typeNs, string identifier, CodeIdentifiers members, CodeIdentifiers membersScope, INameScope elementsScope, ref bool needExplicitOrder, bool order, bool allowUnboundedElements) { TypeItems items = GetTypeItems(type); bool mixed = IsMixed(type); @@ -611,7 +612,7 @@ private MemberMapping[] ImportTypeMembers(XmlSchemaType type, string typeNs, str XmlSchemaType t = type; while (!t.DerivedFrom.IsEmpty) { - t = FindType(t.DerivedFrom, TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue); + t = FindType(t.DerivedFrom, TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue)!; if (IsMixed(t)) { // keep the mixed attribute on the base class @@ -677,11 +678,11 @@ private TypeItems GetTypeItems(XmlSchemaType type) TypeItems items = new TypeItems(); if (type is XmlSchemaComplexType) { - XmlSchemaParticle particle = null; + XmlSchemaParticle? particle = null; XmlSchemaComplexType ct = (XmlSchemaComplexType)type; if (ct.ContentModel != null) { - XmlSchemaContent content = ct.ContentModel.Content; + XmlSchemaContent? content = ct.ContentModel.Content; if (content is XmlSchemaComplexContentExtension) { XmlSchemaComplexContentExtension extension = (XmlSchemaComplexContentExtension)content; @@ -718,7 +719,7 @@ private TypeItems GetTypeItems(XmlSchemaType type) return items; } - private void ImportGroup(XmlSchemaGroupBase group, string identifier, CodeIdentifiers members, CodeIdentifiers membersScope, INameScope elementsScope, string ns, bool mixed, ref bool needExplicitOrder, bool allowDuplicates, bool groupRepeats, bool allowUnboundedElements) + private void ImportGroup(XmlSchemaGroupBase group, string identifier, CodeIdentifiers members, CodeIdentifiers membersScope, INameScope elementsScope, string? ns, bool mixed, ref bool needExplicitOrder, bool allowDuplicates, bool groupRepeats, bool allowUnboundedElements) { if (group is XmlSchemaChoice) ImportChoiceGroup((XmlSchemaChoice)group, identifier, members, membersScope, elementsScope, ns, groupRepeats, ref needExplicitOrder, allowDuplicates); @@ -731,7 +732,7 @@ private void ImportGroup(XmlSchemaGroupBase group, string identifier, CodeIdenti } } - private MemberMapping ImportChoiceGroup(XmlSchemaGroupBase group, string identifier, CodeIdentifiers members, CodeIdentifiers membersScope, INameScope elementsScope, string ns, bool groupRepeats, ref bool needExplicitOrder, bool allowDuplicates) + private MemberMapping ImportChoiceGroup(XmlSchemaGroupBase group, string identifier, CodeIdentifiers? members, CodeIdentifiers? membersScope, INameScope? elementsScope, string? ns, bool groupRepeats, ref bool needExplicitOrder, bool allowDuplicates) { NameTable choiceElements = new NameTable(); if (GatherGroupChoices(group, choiceElements, identifier, ns, ref needExplicitOrder, allowDuplicates)) @@ -748,8 +749,8 @@ private MemberMapping ImportChoiceGroup(XmlSchemaGroupBase group, string identif for (int i = 0; i < member.Elements.Length; i++) { ElementAccessor element = member.Elements[i]; - string tdFullName = element.Mapping.TypeDesc.FullName; - object val = uniqueTypeDescs[tdFullName]; + string tdFullName = element.Mapping!.TypeDesc!.FullName; + object? val = uniqueTypeDescs[tdFullName]; if (val != null) { duplicateTypes = true; @@ -762,14 +763,14 @@ private MemberMapping ImportChoiceGroup(XmlSchemaGroupBase group, string identif uniqueTypeDescs.Add(tdFullName, element); } - ArrayMapping arrayMapping = element.Mapping as ArrayMapping; + ArrayMapping? arrayMapping = element.Mapping as ArrayMapping; if (arrayMapping != null) { if (IsNeedXmlSerializationAttributes(arrayMapping)) { // we cannot use ArrayMapping in choice if additional custom // serialization attributes are needed to serialize it - element.Mapping = arrayMapping.TopLevelMapping; + element.Mapping = arrayMapping.TopLevelMapping!; element.Mapping.ReferencedByTopLevelElement = false; element.Mapping.ReferencedByElement = true; } @@ -785,7 +786,7 @@ private MemberMapping ImportChoiceGroup(XmlSchemaGroupBase group, string identif { if (!enumerator.MoveNext()) break; - typeDescs[i] = ((ElementAccessor)enumerator.Current).Mapping.TypeDesc; + typeDescs[i] = ((ElementAccessor)enumerator.Current).Mapping!.TypeDesc!; } member.TypeDesc = TypeDesc.FindCommonBaseTypeDesc(typeDescs); if (member.TypeDesc == null) member.TypeDesc = Scope.GetTypeDesc(typeof(object)); @@ -810,7 +811,7 @@ private MemberMapping ImportChoiceGroup(XmlSchemaGroupBase group, string identif // we need to create the EnumMapping to store all of the element names member.ChoiceIdentifier.Mapping = ImportEnumeratedChoice(member.Elements, ns, member.Name + "ChoiceType"); member.ChoiceIdentifier.MemberIds = new string[member.Elements.Length]; - ConstantMapping[] constants = ((EnumMapping)member.ChoiceIdentifier.Mapping).Constants; + ConstantMapping[] constants = ((EnumMapping)member.ChoiceIdentifier.Mapping).Constants!; for (int i = 0; i < member.Elements.Length; i++) { member.ChoiceIdentifier.MemberIds[i] = constants[i].Name; @@ -820,7 +821,7 @@ private MemberMapping ImportChoiceGroup(XmlSchemaGroupBase group, string identif choiceIdentifier.Name = member.ChoiceIdentifier.MemberName; if (groupRepeats) { - choiceIdentifier.TypeDesc = member.ChoiceIdentifier.Mapping.TypeDesc.CreateArrayTypeDesc(); + choiceIdentifier.TypeDesc = member.ChoiceIdentifier.Mapping.TypeDesc!.CreateArrayTypeDesc(); } else { @@ -849,11 +850,11 @@ private MemberMapping ImportChoiceGroup(XmlSchemaGroupBase group, string identif private bool IsNeedXmlSerializationAttributes(ArrayMapping arrayMapping) { - if (arrayMapping.Elements.Length != 1) + if (arrayMapping.Elements!.Length != 1) return true; ElementAccessor item = arrayMapping.Elements[0]; - TypeMapping itemMapping = item.Mapping; + TypeMapping itemMapping = item.Mapping!; if (item.Name != itemMapping.DefaultElementName) return true; @@ -861,7 +862,7 @@ private bool IsNeedXmlSerializationAttributes(ArrayMapping arrayMapping) if (item.Form != XmlSchemaForm.None && item.Form != XmlSchemaExporter.elementFormDefault) return true; - if (item.Mapping.TypeDesc != null) + if (item.Mapping!.TypeDesc != null) { if (item.IsNullable != item.Mapping.TypeDesc.IsNullable) return true; @@ -872,12 +873,12 @@ private bool IsNeedXmlSerializationAttributes(ArrayMapping arrayMapping) return false; } - private bool GatherGroupChoices(XmlSchemaGroup group, NameTable choiceElements, string identifier, string ns, ref bool needExplicitOrder, bool allowDuplicates) + private bool GatherGroupChoices(XmlSchemaGroup group, NameTable choiceElements, string identifier, string? ns, ref bool needExplicitOrder, bool allowDuplicates) { return GatherGroupChoices(group.Particle, choiceElements, identifier, ns, ref needExplicitOrder, allowDuplicates); } - private bool GatherGroupChoices(XmlSchemaParticle particle, NameTable choiceElements, string identifier, string ns, ref bool needExplicitOrder, bool allowDuplicates) + private bool GatherGroupChoices(XmlSchemaParticle? particle, NameTable choiceElements, string identifier, string? ns, ref bool needExplicitOrder, bool allowDuplicates) { if (particle is XmlSchemaGroupRef) { @@ -897,7 +898,7 @@ private bool GatherGroupChoices(XmlSchemaParticle particle, NameTable choiceElem { XmlSchemaGroupBase group = (XmlSchemaGroupBase)particle; bool groupRepeats = group.IsMultipleOccurrence; - XmlSchemaAny any = null; + XmlSchemaAny? any = null; bool duplicateElements = false; for (int i = 0; i < group.Items.Count; i++) { @@ -921,7 +922,7 @@ private bool GatherGroupChoices(XmlSchemaParticle particle, NameTable choiceElem else if (item is XmlSchemaElement) { XmlSchemaElement element = (XmlSchemaElement)item; - XmlSchemaElement headElement = GetTopLevelElement(element); + XmlSchemaElement? headElement = GetTopLevelElement(element); if (headElement != null) { XmlSchemaElement[] elements = GetEquivalentElements(headElement); @@ -948,19 +949,19 @@ private bool GatherGroupChoices(XmlSchemaParticle particle, NameTable choiceElem return false; } - private void AddScopeElement(INameScope scope, ElementAccessor element, ref bool duplicateElements, bool allowDuplicates) + private void AddScopeElement(INameScope? scope, ElementAccessor element, ref bool duplicateElements, bool allowDuplicates) { if (scope == null) return; - ElementAccessor scopeElement = (ElementAccessor)scope[element.Name, element.Namespace]; + ElementAccessor? scopeElement = (ElementAccessor?)scope[element.Name, element.Namespace]; if (scopeElement != null) { if (!allowDuplicates) { throw new InvalidOperationException(SR.Format(SR.XmlDuplicateElementInScope, element.Name, element.Namespace)); } - if (scopeElement.Mapping.TypeDesc != element.Mapping.TypeDesc) + if (scopeElement.Mapping!.TypeDesc != element.Mapping!.TypeDesc) { throw new InvalidOperationException(SR.Format(SR.XmlDuplicateElementInScope1, element.Name, element.Namespace)); } @@ -972,7 +973,7 @@ private void AddScopeElement(INameScope scope, ElementAccessor element, ref bool } } - private void AddScopeElements(INameScope scope, ElementAccessor[] elements, ref bool duplicateElements, bool allowDuplicates) + private void AddScopeElements(INameScope? scope, ElementAccessor[] elements, ref bool duplicateElements, bool allowDuplicates) { for (int i = 0; i < elements.Length; i++) { @@ -980,7 +981,7 @@ private void AddScopeElements(INameScope scope, ElementAccessor[] elements, ref } } - private void ImportGroupMembers(XmlSchemaParticle particle, string identifier, CodeIdentifiers members, CodeIdentifiers membersScope, INameScope elementsScope, string ns, bool groupRepeats, ref bool mixed, ref bool needExplicitOrder, bool allowDuplicates, bool allowUnboundedElements) + private void ImportGroupMembers(XmlSchemaParticle? particle, string identifier, CodeIdentifiers members, CodeIdentifiers membersScope, INameScope elementsScope, string? ns, bool groupRepeats, ref bool mixed, ref bool needExplicitOrder, bool allowDuplicates, bool allowUnboundedElements) { if (particle is XmlSchemaGroupRef) { @@ -1025,7 +1026,7 @@ private void ImportGroupMembers(XmlSchemaParticle particle, string identifier, C } } - private XmlSchemaElement GetTopLevelElement(XmlSchemaElement element) + private XmlSchemaElement? GetTopLevelElement(XmlSchemaElement element) { if (!element.RefName.IsEmpty) return FindElement(element.RefName); @@ -1057,7 +1058,7 @@ private XmlSchemaElement[] GetEquivalentElements(XmlSchemaElement element) return (XmlSchemaElement[])equivalentElements.ToArray(typeof(XmlSchemaElement)); } - private bool ImportSubstitutionGroupMember(XmlSchemaElement element, string identifier, CodeIdentifiers members, CodeIdentifiers membersScope, string ns, bool repeats, ref bool needExplicitOrder, bool allowDuplicates) + private bool ImportSubstitutionGroupMember(XmlSchemaElement element, string identifier, CodeIdentifiers members, CodeIdentifiers membersScope, string? ns, bool repeats, ref bool needExplicitOrder, bool allowDuplicates) { XmlSchemaElement[] elements = GetEquivalentElements(element); if (elements.Length == 0) @@ -1068,24 +1069,24 @@ private bool ImportSubstitutionGroupMember(XmlSchemaElement element, string iden if (!element.IsAbstract) choice.Items.Add(element); if (identifier.Length == 0) - identifier = CodeIdentifier.MakeValid(Accessor.UnescapeName(element.Name)); + identifier = CodeIdentifier.MakeValid(Accessor.UnescapeName(element.Name!)); else - identifier += CodeIdentifier.MakePascal(Accessor.UnescapeName(element.Name)); + identifier += CodeIdentifier.MakePascal(Accessor.UnescapeName(element.Name!)); ImportChoiceGroup(choice, identifier, members, membersScope, null, ns, repeats, ref needExplicitOrder, allowDuplicates); return true; } - private void ImportTextMember(CodeIdentifiers members, CodeIdentifiers membersScope, XmlQualifiedName simpleContentType) + private void ImportTextMember(CodeIdentifiers members, CodeIdentifiers membersScope, XmlQualifiedName? simpleContentType) { - TypeMapping mapping; + TypeMapping? mapping; bool isMixed = false; if (simpleContentType != null) { // allow to use all primitive types mapping = ImportType(simpleContentType, typeof(TypeMapping), null, TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue, false); - if (!(mapping is PrimitiveMapping || mapping.TypeDesc.CanBeTextValue)) + if (!(mapping is PrimitiveMapping || mapping!.TypeDesc!.CanBeTextValue)) { return; } @@ -1106,7 +1107,7 @@ private void ImportTextMember(CodeIdentifiers members, CodeIdentifiers membersSc if (isMixed) { // just generate code for the standard mixed case (string[] text) - member.TypeDesc = accessor.Mapping.TypeDesc.CreateArrayTypeDesc(); + member.TypeDesc = accessor.Mapping.TypeDesc!.CreateArrayTypeDesc(); member.Name = members.MakeRightCase("Text"); } else @@ -1115,7 +1116,7 @@ private void ImportTextMember(CodeIdentifiers members, CodeIdentifiers membersSc PrimitiveMapping pm = (PrimitiveMapping)accessor.Mapping; if (pm.IsList) { - member.TypeDesc = accessor.Mapping.TypeDesc.CreateArrayTypeDesc(); + member.TypeDesc = accessor.Mapping.TypeDesc!.CreateArrayTypeDesc(); member.Name = members.MakeRightCase("Text"); } else @@ -1128,7 +1129,7 @@ private void ImportTextMember(CodeIdentifiers members, CodeIdentifiers membersSc members.Add(member.Name, member); } - private MemberMapping ImportAnyMember(XmlSchemaAny any, string identifier, CodeIdentifiers members, CodeIdentifiers membersScope, INameScope elementsScope, string ns, ref bool mixed, ref bool needExplicitOrder, bool allowDuplicates) + private MemberMapping ImportAnyMember(XmlSchemaAny any, string identifier, CodeIdentifiers members, CodeIdentifiers membersScope, INameScope elementsScope, string? ns, ref bool mixed, ref bool needExplicitOrder, bool allowDuplicates) { ElementAccessor[] accessors = ImportAny(any, !mixed, ns); AddScopeElements(elementsScope, accessors, ref needExplicitOrder, allowDuplicates); @@ -1137,7 +1138,7 @@ private MemberMapping ImportAnyMember(XmlSchemaAny any, string identifier, CodeI member.Name = membersScope.MakeRightCase("Any"); member.Name = membersScope.AddUnique(member.Name, member); members.Add(member.Name, member); - member.TypeDesc = ((TypeMapping)accessors[0].Mapping).TypeDesc; + member.TypeDesc = ((TypeMapping)accessors[0].Mapping!).TypeDesc; bool repeats = any.IsMultipleOccurrence; @@ -1156,11 +1157,11 @@ private MemberMapping ImportAnyMember(XmlSchemaAny any, string identifier, CodeI if (repeats) { - member.TypeDesc = member.TypeDesc.CreateArrayTypeDesc(); + member.TypeDesc = member.TypeDesc!.CreateArrayTypeDesc(); } return member; } - private ElementAccessor[] ImportAny(XmlSchemaAny any, bool makeElement, string targetNamespace) + private ElementAccessor[] ImportAny(XmlSchemaAny any, bool makeElement, string? targetNamespace) { SpecialMapping mapping = new SpecialMapping(); @@ -1177,7 +1178,7 @@ private ElementAccessor[] ImportAny(XmlSchemaAny any, bool makeElement, string t if (GenerateOrder && any.Namespace != null) { - NamespaceList list = new NamespaceList(any.Namespace, targetNamespace); + NamespaceList list = new NamespaceList(any.Namespace, targetNamespace!); if (list.Type == NamespaceList.ListType.Set) { @@ -1205,31 +1206,31 @@ private ElementAccessor[] ImportAny(XmlSchemaAny any, bool makeElement, string t return new ElementAccessor[] { anyAccessor }; } - private ElementAccessor ImportArray(XmlSchemaElement element, string identifier, string ns, bool repeats) + private ElementAccessor? ImportArray(XmlSchemaElement element, string identifier, string? ns, bool repeats) { if (repeats) return null; if (element.SchemaType == null) return null; if (element.IsMultipleOccurrence) return null; XmlSchemaType type = element.SchemaType; - ArrayMapping arrayMapping = ImportArrayMapping(type, identifier, ns, repeats); + ArrayMapping? arrayMapping = ImportArrayMapping(type, identifier, ns, repeats); if (arrayMapping == null) return null; ElementAccessor arrayAccessor = new ElementAccessor(); arrayAccessor.Name = element.Name; arrayAccessor.Namespace = ns; arrayAccessor.Mapping = arrayMapping; - if (arrayMapping.TypeDesc.IsNullable) + if (arrayMapping.TypeDesc!.IsNullable) arrayAccessor.IsNullable = element.IsNillable; arrayAccessor.Form = ElementForm(ns, element); return arrayAccessor; } - private ArrayMapping ImportArrayMapping(XmlSchemaType type, string identifier, string ns, bool repeats) + private ArrayMapping? ImportArrayMapping(XmlSchemaType type, string identifier, string? ns, bool repeats) { if (!(type is XmlSchemaComplexType)) return null; if (!type.DerivedFrom.IsEmpty) return null; if (IsMixed(type)) return null; - Mapping previousMapping = (Mapping)ImportedMappings[type]; + Mapping? previousMapping = (Mapping?)ImportedMappings[type]; if (previousMapping != null) { if (previousMapping is ArrayMapping) @@ -1260,7 +1261,7 @@ private ArrayMapping ImportArrayMapping(XmlSchemaType type, string identifier, s if (choiceMember.ChoiceIdentifier != null) return null; arrayMapping.TypeDesc = choiceMember.TypeDesc; arrayMapping.Elements = choiceMember.Elements; - arrayMapping.TypeName = (type.Name == null || type.Name.Length == 0) ? "ArrayOf" + CodeIdentifier.MakePascal(arrayMapping.TypeDesc.Name) : type.Name; + arrayMapping.TypeName = (type.Name == null || type.Name.Length == 0) ? "ArrayOf" + CodeIdentifier.MakePascal(arrayMapping.TypeDesc!.Name) : type.Name; } else if (item is XmlSchemaAll || item is XmlSchemaSequence) { @@ -1276,7 +1277,7 @@ private ArrayMapping ImportArrayMapping(XmlSchemaType type, string identifier, s if (itemAccessor.Any) return null; arrayMapping.Elements = new ElementAccessor[] { itemAccessor }; - arrayMapping.TypeDesc = ((TypeMapping)itemAccessor.Mapping).TypeDesc.CreateArrayTypeDesc(); + arrayMapping.TypeDesc = ((TypeMapping)itemAccessor.Mapping!).TypeDesc!.CreateArrayTypeDesc(); arrayMapping.TypeName = (type.Name == null || type.Name.Length == 0) ? "ArrayOf" + CodeIdentifier.MakePascal(itemAccessor.Mapping.TypeDesc.Name) : type.Name; } else @@ -1300,7 +1301,7 @@ private bool IsCyclicReferencedType(XmlSchemaElement element, List ident if (!element.RefName.IsEmpty) { XmlSchemaElement refElement = FindElement(element.RefName); - string refElementIdentifier = CodeIdentifier.MakeValid(Accessor.UnescapeName(refElement.Name)); + string refElementIdentifier = CodeIdentifier.MakeValid(Accessor.UnescapeName(refElement.Name!)); foreach (string identifier in identifiers) { if (refElementIdentifier == identifier) @@ -1310,7 +1311,7 @@ private bool IsCyclicReferencedType(XmlSchemaElement element, List ident } identifiers.Add(refElementIdentifier); - XmlSchemaType refType = refElement.SchemaType; + XmlSchemaType? refType = refElement.SchemaType; if (refType is XmlSchemaComplexType) { TypeItems items = GetTypeItems(refType); @@ -1327,7 +1328,7 @@ private bool IsCyclicReferencedType(XmlSchemaElement element, List ident return false; } - private SpecialMapping ImportAnyMapping(XmlSchemaType type, string identifier, string ns, bool repeats) + private SpecialMapping? ImportAnyMapping(XmlSchemaType? type, string identifier, string? ns, bool repeats) { if (type == null) return null; if (!type.DerivedFrom.IsEmpty) return null; @@ -1373,15 +1374,15 @@ private SpecialMapping ImportAnyMapping(XmlSchemaType type, string identifier, s return mapping; } - private void ImportElementMember(XmlSchemaElement element, string identifier, CodeIdentifiers members, CodeIdentifiers membersScope, INameScope elementsScope, string ns, bool repeats, ref bool needExplicitOrder, bool allowDuplicates, bool allowUnboundedElements) + private void ImportElementMember(XmlSchemaElement element, string identifier, CodeIdentifiers members, CodeIdentifiers membersScope, INameScope elementsScope, string? ns, bool repeats, ref bool needExplicitOrder, bool allowDuplicates, bool allowUnboundedElements) { repeats = repeats | element.IsMultipleOccurrence; - XmlSchemaElement headElement = GetTopLevelElement(element); + XmlSchemaElement? headElement = GetTopLevelElement(element); if (headElement != null && ImportSubstitutionGroupMember(headElement, identifier, members, membersScope, ns, repeats, ref needExplicitOrder, allowDuplicates)) { return; } - ElementAccessor accessor; + ElementAccessor? accessor; if ((accessor = ImportArray(element, identifier, ns, repeats)) == null) { accessor = ImportElement(element, identifier, typeof(TypeMapping), null, ns, false); @@ -1399,7 +1400,7 @@ private void ImportElementMember(XmlSchemaElement element, string identifier, Co } members.Add(member.Name, member); // we do not support lists for elements - if (accessor.Mapping.IsList) + if (accessor.Mapping!.IsList) { accessor.Mapping = GetDefaultMapping(TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue); member.TypeDesc = accessor.Mapping.TypeDesc; @@ -1416,22 +1417,22 @@ private void ImportElementMember(XmlSchemaElement element, string identifier, Co { if (!allowUnboundedElements && accessor.Mapping is ArrayMapping) { - accessor.Mapping = ((ArrayMapping)accessor.Mapping).TopLevelMapping; + accessor.Mapping = ((ArrayMapping)accessor.Mapping).TopLevelMapping!; accessor.Mapping.ReferencedByTopLevelElement = false; accessor.Mapping.ReferencedByElement = true; } - member.TypeDesc = accessor.Mapping.TypeDesc.CreateArrayTypeDesc(); + member.TypeDesc = accessor.Mapping.TypeDesc!.CreateArrayTypeDesc(); } - if (element.MinOccurs == 0 && member.TypeDesc.IsValueType && !element.HasDefault && !member.TypeDesc.HasIsEmpty) + if (element.MinOccurs == 0 && member.TypeDesc!.IsValueType && !element.HasDefault && !member.TypeDesc.HasIsEmpty) { member.CheckSpecified = SpecifiedAccessor.ReadWrite; } } - private void ImportAttributeMember(XmlSchemaAttribute attribute, string identifier, CodeIdentifiers members, CodeIdentifiers membersScope, string ns) + private void ImportAttributeMember(XmlSchemaAttribute attribute, string identifier, CodeIdentifiers members, CodeIdentifiers membersScope, string? ns) { - AttributeAccessor accessor = ImportAttribute(attribute, identifier, ns, attribute); + AttributeAccessor? accessor = ImportAttribute(attribute, identifier, ns, attribute); if (accessor == null) return; MemberMapping member = new MemberMapping(); member.Elements = Array.Empty(); @@ -1445,9 +1446,9 @@ private void ImportAttributeMember(XmlSchemaAttribute attribute, string identifi membersScope.Remove(name); } members.Add(member.Name, member); - member.TypeDesc = accessor.IsList ? accessor.Mapping.TypeDesc.CreateArrayTypeDesc() : accessor.Mapping.TypeDesc; + member.TypeDesc = accessor.IsList ? accessor.Mapping!.TypeDesc!.CreateArrayTypeDesc() : accessor.Mapping!.TypeDesc; - if ((attribute.Use == XmlSchemaUse.Optional || attribute.Use == XmlSchemaUse.None) && member.TypeDesc.IsValueType && !attribute.HasDefault && !member.TypeDesc.HasIsEmpty) + if ((attribute.Use == XmlSchemaUse.Optional || attribute.Use == XmlSchemaUse.None) && member.TypeDesc!.IsValueType && !attribute.HasDefault && !member.TypeDesc.HasIsEmpty) { member.CheckSpecified = SpecifiedAccessor.ReadWrite; } @@ -1473,7 +1474,7 @@ private void ImportAnyAttributeMember(XmlSchemaAnyAttribute any, CodeIdentifiers member.TypeDesc = member.TypeDesc.CreateArrayTypeDesc(); } - private bool KeepXmlnsDeclarations(XmlSchemaType type, out string xmlnsMemberName) + private bool KeepXmlnsDeclarations(XmlSchemaType type, out string? xmlnsMemberName) { xmlnsMemberName = null; if (type.Annotation == null) @@ -1485,7 +1486,7 @@ private bool KeepXmlnsDeclarations(XmlSchemaType type, out string xmlnsMemberNam { if (o is XmlSchemaAppInfo) { - XmlNode[] nodes = ((XmlSchemaAppInfo)o).Markup; + XmlNode[]? nodes = ((XmlSchemaAppInfo)o).Markup; if (nodes != null && nodes.Length > 0) { foreach (XmlNode node in nodes) @@ -1497,7 +1498,7 @@ private bool KeepXmlnsDeclarations(XmlSchemaType type, out string xmlnsMemberNam { if (e.LastNode is XmlText) { - xmlnsMemberName = (((XmlText)e.LastNode).Value).Trim(null); + xmlnsMemberName = (((XmlText)e.LastNode).Value!).Trim(null); } return true; } @@ -1511,7 +1512,7 @@ private bool KeepXmlnsDeclarations(XmlSchemaType type, out string xmlnsMemberNam private void ImportXmlnsDeclarationsMember(XmlSchemaType type, CodeIdentifiers members, CodeIdentifiers membersScope) { - string xmlnsMemberName; + string? xmlnsMemberName; if (!KeepXmlnsDeclarations(type, out xmlnsMemberName)) return; TypeDesc xmlnsTypeDesc = Scope.GetTypeDesc(typeof(System.Xml.Serialization.XmlSerializerNamespaces)); @@ -1554,7 +1555,7 @@ private AttributeAccessor ImportSpecialAttribute(XmlQualifiedName name, string i { PrimitiveMapping mapping = new PrimitiveMapping(); mapping.TypeDesc = Scope.GetTypeDesc(typeof(string)); - mapping.TypeName = mapping.TypeDesc.DataType.Name; + mapping.TypeName = mapping.TypeDesc.DataType!.Name; AttributeAccessor accessor = new AttributeAccessor(); accessor.Name = name.Name; accessor.Namespace = XmlReservedNs.NsXml; @@ -1563,7 +1564,7 @@ private AttributeAccessor ImportSpecialAttribute(XmlQualifiedName name, string i return accessor; } - private AttributeAccessor ImportAttribute(XmlSchemaAttribute attribute, string identifier, string ns, XmlSchemaAttribute defaultValueProvider) + private AttributeAccessor? ImportAttribute(XmlSchemaAttribute attribute, string identifier, string? ns, XmlSchemaAttribute defaultValueProvider) { if (attribute.Use == XmlSchemaUse.Prohibited) return null; if (!attribute.RefName.IsEmpty) @@ -1573,14 +1574,14 @@ private AttributeAccessor ImportAttribute(XmlSchemaAttribute attribute, string i else return ImportAttribute(FindAttribute(attribute.RefName), identifier, attribute.RefName.Namespace, defaultValueProvider); } - TypeMapping mapping; - if (attribute.Name.Length == 0) throw new InvalidOperationException(SR.XmlAttributeHasNoName); + TypeMapping? mapping; + if (attribute.Name!.Length == 0) throw new InvalidOperationException(SR.XmlAttributeHasNoName); if (identifier.Length == 0) identifier = CodeIdentifier.MakeValid(attribute.Name); else identifier += CodeIdentifier.MakePascal(attribute.Name); if (!attribute.SchemaTypeName.IsEmpty) - mapping = (TypeMapping)ImportType(attribute.SchemaTypeName, typeof(TypeMapping), null, TypeFlags.CanBeAttributeValue, false); + mapping = (TypeMapping?)ImportType(attribute.SchemaTypeName, typeof(TypeMapping), null, TypeFlags.CanBeAttributeValue, false); else if (attribute.SchemaType != null) mapping = ImportDataType((XmlSchemaSimpleType)attribute.SchemaType, ns, identifier, null, TypeFlags.CanBeAttributeValue, false); else @@ -1589,7 +1590,7 @@ private AttributeAccessor ImportAttribute(XmlSchemaAttribute attribute, string i } // let the extensions to run - if (mapping != null && !mapping.TypeDesc.IsMappedType) + if (mapping != null && !mapping.TypeDesc!.IsMappedType) { RunSchemaExtensions(mapping, attribute.SchemaTypeName, attribute.SchemaType, attribute, TypeFlags.CanBeElementValue | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeTextValue); } @@ -1599,7 +1600,7 @@ private AttributeAccessor ImportAttribute(XmlSchemaAttribute attribute, string i accessor.Form = AttributeForm(ns, attribute); accessor.CheckSpecial(); accessor.Mapping = mapping; - accessor.IsList = mapping.IsList; + accessor.IsList = mapping!.IsList; accessor.IsOptional = attribute.Use != XmlSchemaUse.Required; if (defaultValueProvider.DefaultValue != null) @@ -1626,12 +1627,12 @@ private AttributeAccessor ImportAttribute(XmlSchemaAttribute attribute, string i return accessor; } - private TypeMapping ImportDataType(XmlSchemaSimpleType dataType, string typeNs, string identifier, Type baseType, TypeFlags flags, bool isList) + private TypeMapping? ImportDataType(XmlSchemaSimpleType dataType, string? typeNs, string identifier, Type? baseType, TypeFlags flags, bool isList) { if (baseType != null) return ImportStructDataType(dataType, typeNs, identifier, baseType); - TypeMapping mapping = ImportNonXsdPrimitiveDataType(dataType, typeNs, flags); + TypeMapping? mapping = ImportNonXsdPrimitiveDataType(dataType, typeNs, flags); if (mapping != null) return mapping; @@ -1652,7 +1653,7 @@ private TypeMapping ImportDataType(XmlSchemaSimpleType dataType, string typeNs, else { AddReference(restriction.BaseTypeName, TypesInUse, SR.XmlCircularTypeReference); - mapping = ImportDataType(FindDataType(restriction.BaseTypeName, flags), restriction.BaseTypeName.Namespace, identifier, null, flags, false); + mapping = ImportDataType(FindDataType(restriction.BaseTypeName, flags)!, restriction.BaseTypeName.Namespace, identifier, null, flags, false); if (restriction.BaseTypeName.Namespace != XmlSchema.Namespace) RemoveReference(restriction.BaseTypeName, TypesInUse); return mapping; @@ -1688,19 +1689,19 @@ private TypeMapping ImportDataType(XmlSchemaSimpleType dataType, string typeNs, return ImportPrimitiveDataType(dataType, flags); } - private TypeMapping ImportEnumeratedDataType(XmlSchemaSimpleType dataType, string typeNs, string identifier, TypeFlags flags, bool isList) + private TypeMapping? ImportEnumeratedDataType(XmlSchemaSimpleType dataType, string? typeNs, string identifier, TypeFlags flags, bool isList) { - TypeMapping mapping = (TypeMapping)ImportedMappings[dataType]; + TypeMapping? mapping = (TypeMapping?)ImportedMappings[dataType]; if (mapping != null) return mapping; XmlSchemaType sourceType = dataType; while (!sourceType.DerivedFrom.IsEmpty) { - sourceType = FindType(sourceType.DerivedFrom, TypeFlags.CanBeElementValue | TypeFlags.CanBeAttributeValue); + sourceType = FindType(sourceType.DerivedFrom, TypeFlags.CanBeElementValue | TypeFlags.CanBeAttributeValue)!; } if (sourceType is XmlSchemaComplexType) return null; - TypeDesc sourceTypeDesc = Scope.GetTypeDesc((XmlSchemaSimpleType)sourceType); + TypeDesc? sourceTypeDesc = Scope.GetTypeDesc((XmlSchemaSimpleType)sourceType); if (sourceTypeDesc != null && sourceTypeDesc.FullName != typeof(string).FullName) return ImportPrimitiveDataType(dataType, flags); identifier = Accessor.UnescapeName(identifier); @@ -1714,7 +1715,7 @@ private TypeMapping ImportEnumeratedDataType(XmlSchemaSimpleType dataType, strin enumMapping.IsFlags = isList; CodeIdentifiers constants = new CodeIdentifiers(); - XmlSchemaSimpleTypeContent content = dataType.Content; + XmlSchemaSimpleTypeContent? content = dataType.Content; if (content is XmlSchemaSimpleTypeRestriction) { @@ -1727,15 +1728,16 @@ private TypeMapping ImportEnumeratedDataType(XmlSchemaSimpleType dataType, strin // validate the enumeration value if (sourceTypeDesc != null && sourceTypeDesc.HasCustomFormatter) { - XmlCustomFormatter.ToDefaultValue(enumeration.Value, sourceTypeDesc.FormatterName); + XmlCustomFormatter.ToDefaultValue(enumeration.Value!, sourceTypeDesc.FormatterName!); } ConstantMapping constant = new ConstantMapping(); - string constantName = CodeIdentifier.MakeValid(enumeration.Value); + string constantName = CodeIdentifier.MakeValid(enumeration.Value!); constant.Name = constants.AddUnique(constantName, constant); constant.XmlName = enumeration.Value; constant.Value = i; } } + enumMapping.Constants = (ConstantMapping[])constants.ToArray(typeof(ConstantMapping)); if (isList && enumMapping.Constants.Length > 63) { @@ -1751,15 +1753,15 @@ private TypeMapping ImportEnumeratedDataType(XmlSchemaSimpleType dataType, strin internal class ElementComparer : IComparer { - public int Compare(object o1, object o2) + public int Compare(object? o1, object? o2) { - ElementAccessor e1 = (ElementAccessor)o1; - ElementAccessor e2 = (ElementAccessor)o2; + ElementAccessor e1 = (ElementAccessor)o1!; + ElementAccessor e2 = (ElementAccessor)o2!; return string.Compare(e1.ToString(string.Empty), e2.ToString(string.Empty), StringComparison.Ordinal); } } - private EnumMapping ImportEnumeratedChoice(ElementAccessor[] choice, string typeNs, string typeName) + private EnumMapping ImportEnumeratedChoice(ElementAccessor[] choice, string? typeNs, string typeName) { typeName = GenerateUniqueTypeName(Accessor.UnescapeName(typeName), typeNs); EnumMapping enumMapping = new EnumMapping(); @@ -1793,15 +1795,15 @@ private PrimitiveMapping ImportPrimitiveDataType(XmlSchemaSimpleType dataType, T TypeDesc sourceTypeDesc = GetDataTypeSource(dataType, flags); PrimitiveMapping mapping = new PrimitiveMapping(); mapping.TypeDesc = sourceTypeDesc; - mapping.TypeName = sourceTypeDesc.DataType.Name; + mapping.TypeName = sourceTypeDesc.DataType!.Name; mapping.Namespace = mapping.TypeDesc.IsXsdType ? XmlSchema.Namespace : UrtTypes.Namespace; return mapping; } - private PrimitiveMapping ImportNonXsdPrimitiveDataType(XmlSchemaSimpleType dataType, string ns, TypeFlags flags) + private PrimitiveMapping? ImportNonXsdPrimitiveDataType(XmlSchemaSimpleType dataType, string? ns, TypeFlags flags) { - PrimitiveMapping mapping = null; - TypeDesc typeDesc = null; + PrimitiveMapping? mapping = null; + TypeDesc? typeDesc = null; if (dataType.Name != null && dataType.Name.Length != 0) { typeDesc = Scope.GetTypeDesc(dataType.Name, ns, flags); @@ -1809,7 +1811,7 @@ private PrimitiveMapping ImportNonXsdPrimitiveDataType(XmlSchemaSimpleType dataT { mapping = new PrimitiveMapping(); mapping.TypeDesc = typeDesc; - mapping.TypeName = typeDesc.DataType.Name; + mapping.TypeName = typeDesc.DataType!.Name; mapping.Namespace = mapping.TypeDesc.IsXsdType ? XmlSchema.Namespace : ns; } } @@ -1818,7 +1820,7 @@ private PrimitiveMapping ImportNonXsdPrimitiveDataType(XmlSchemaSimpleType dataT private XmlSchemaGroup FindGroup(XmlQualifiedName name) { - XmlSchemaGroup group = (XmlSchemaGroup)Schemas.Find(name, typeof(XmlSchemaGroup)); + XmlSchemaGroup? group = (XmlSchemaGroup?)Schemas.Find(name, typeof(XmlSchemaGroup)); if (group == null) throw new InvalidOperationException(SR.Format(SR.XmlMissingGroup, name.Name)); @@ -1827,7 +1829,7 @@ private XmlSchemaGroup FindGroup(XmlQualifiedName name) private XmlSchemaAttributeGroup FindAttributeGroup(XmlQualifiedName name) { - XmlSchemaAttributeGroup group = (XmlSchemaAttributeGroup)Schemas.Find(name, typeof(XmlSchemaAttributeGroup)); + XmlSchemaAttributeGroup? group = (XmlSchemaAttributeGroup?)Schemas.Find(name, typeof(XmlSchemaAttributeGroup)); if (group == null) throw new InvalidOperationException(SR.Format(SR.XmlMissingAttributeGroup, name.Name)); @@ -1836,7 +1838,7 @@ private XmlSchemaAttributeGroup FindAttributeGroup(XmlQualifiedName name) internal static XmlQualifiedName BaseTypeName(XmlSchemaSimpleType dataType) { - XmlSchemaSimpleTypeContent content = dataType.Content; + XmlSchemaSimpleTypeContent? content = dataType.Content; if (content is XmlSchemaSimpleTypeRestriction) { return ((XmlSchemaSimpleTypeRestriction)content).BaseTypeName; @@ -1856,7 +1858,7 @@ internal static XmlQualifiedName BaseTypeName(XmlSchemaSimpleType dataType) private TypeDesc GetDataTypeSource(XmlSchemaSimpleType dataType, TypeFlags flags) { - TypeDesc typeDesc = null; + TypeDesc? typeDesc = null; if (dataType.Name != null && dataType.Name.Length != 0) { typeDesc = Scope.GetTypeDesc(dataType); @@ -1864,29 +1866,34 @@ private TypeDesc GetDataTypeSource(XmlSchemaSimpleType dataType, TypeFlags flags } XmlQualifiedName qname = BaseTypeName(dataType); AddReference(qname, TypesInUse, SR.XmlCircularTypeReference); - typeDesc = GetDataTypeSource(FindDataType(qname, flags), flags); + typeDesc = GetDataTypeSource(FindDataType(qname, flags)!, flags); if (qname.Namespace != XmlSchema.Namespace) RemoveReference(qname, TypesInUse); return typeDesc; } - private XmlSchemaSimpleType FindDataType(XmlQualifiedName name, TypeFlags flags) + private XmlSchemaSimpleType? FindDataType(XmlQualifiedName? name, TypeFlags flags) { if (name == null || name.IsEmpty) { - return (XmlSchemaSimpleType)Scope.GetTypeDesc(typeof(string)).DataType; + return (XmlSchemaSimpleType?)Scope.GetTypeDesc(typeof(string)).DataType; } - TypeDesc typeDesc = Scope.GetTypeDesc(name.Name, name.Namespace, flags); + + TypeDesc? typeDesc = Scope.GetTypeDesc(name.Name, name.Namespace, flags); if (typeDesc != null && typeDesc.DataType is XmlSchemaSimpleType) return (XmlSchemaSimpleType)typeDesc.DataType; - XmlSchemaSimpleType dataType = (XmlSchemaSimpleType)Schemas.Find(name, typeof(XmlSchemaSimpleType)); + + XmlSchemaSimpleType? dataType = (XmlSchemaSimpleType?)Schemas.Find(name, typeof(XmlSchemaSimpleType)); if (dataType != null) { return dataType; } + if (name.Namespace == XmlSchema.Namespace) - return (XmlSchemaSimpleType)Scope.GetTypeDesc("string", XmlSchema.Namespace, flags).DataType; + { + return (XmlSchemaSimpleType?)Scope.GetTypeDesc("string", XmlSchema.Namespace, flags)!.DataType; + } else { if (name.Name == Soap.Array && name.Namespace == Soap.Encoding) @@ -1900,23 +1907,25 @@ private XmlSchemaSimpleType FindDataType(XmlQualifiedName name, TypeFlags flags) } } - private XmlSchemaType FindType(XmlQualifiedName name, TypeFlags flags) + private XmlSchemaType? FindType(XmlQualifiedName? name, TypeFlags flags) { if (name == null || name.IsEmpty) { return Scope.GetTypeDesc(typeof(string)).DataType; } - object type = Schemas.Find(name, typeof(XmlSchemaComplexType)); + + object? type = Schemas.Find(name, typeof(XmlSchemaComplexType)); if (type != null) { - return (XmlSchemaComplexType)type; + return (XmlSchemaComplexType?)type; } + return FindDataType(name, flags); } private XmlSchemaElement FindElement(XmlQualifiedName name) { - XmlSchemaElement element = (XmlSchemaElement)Schemas.Find(name, typeof(XmlSchemaElement)); + XmlSchemaElement? element = (XmlSchemaElement?)Schemas.Find(name, typeof(XmlSchemaElement)); if (element == null) throw new InvalidOperationException(SR.Format(SR.XmlMissingElement, name)); return element; @@ -1924,14 +1933,14 @@ private XmlSchemaElement FindElement(XmlQualifiedName name) private XmlSchemaAttribute FindAttribute(XmlQualifiedName name) { - XmlSchemaAttribute attribute = (XmlSchemaAttribute)Schemas.Find(name, typeof(XmlSchemaAttribute)); + XmlSchemaAttribute? attribute = (XmlSchemaAttribute?)Schemas.Find(name, typeof(XmlSchemaAttribute)); if (attribute == null) throw new InvalidOperationException(SR.Format(SR.XmlMissingAttribute, name.Name)); return attribute; } - private XmlSchemaForm ElementForm(string ns, XmlSchemaElement element) + private XmlSchemaForm ElementForm(string? ns, XmlSchemaElement element) { if (element.Form == XmlSchemaForm.None) { @@ -1940,7 +1949,7 @@ private XmlSchemaForm ElementForm(string ns, XmlSchemaElement element) { parent = parent.Parent; } - XmlSchema schema = parent as XmlSchema; + XmlSchema? schema = parent as XmlSchema; if (schema != null) { @@ -1959,7 +1968,7 @@ private XmlSchemaForm ElementForm(string ns, XmlSchemaElement element) return element.Form; } - private XmlSchemaForm AttributeForm(string ns, XmlSchemaAttribute attribute) + private XmlSchemaForm AttributeForm(string? ns, XmlSchemaAttribute attribute) { if (attribute.Form == XmlSchemaForm.None) { @@ -1968,7 +1977,7 @@ private XmlSchemaForm AttributeForm(string ns, XmlSchemaAttribute attribute) { parent = parent.Parent; } - XmlSchema schema = parent as XmlSchema; + XmlSchema? schema = parent as XmlSchema; if (schema != null) { if (ns == null || ns.Length == 0) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaProviderAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaProviderAttribute.cs index 9979421d7d4743..36095d9a673300 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaProviderAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaProviderAttribute.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; @@ -12,13 +13,13 @@ namespace System.Xml.Serialization [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct)] public sealed class XmlSchemaProviderAttribute : System.Attribute { - private readonly string _methodName; + private readonly string? _methodName; private bool _any; /// /// [To be supplied.] /// - public XmlSchemaProviderAttribute(string methodName) + public XmlSchemaProviderAttribute(string? methodName) { _methodName = methodName; } @@ -26,7 +27,7 @@ public XmlSchemaProviderAttribute(string methodName) /// /// [To be supplied.] /// - public string MethodName + public string? MethodName { get { return _methodName; } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemas.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemas.cs index 06f9c236fde007..e0e3f2cb5810a6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemas.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemas.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System.Collections; @@ -16,26 +17,27 @@ namespace System.Xml.Serialization using System.Security; using System.Net; using System.Reflection; + using System.Diagnostics.CodeAnalysis; public class XmlSchemas : CollectionBase, IEnumerable { - private XmlSchemaSet _schemaSet; - private Hashtable _references; - private SchemaObjectCache _cache; // cached schema top-level items + private XmlSchemaSet? _schemaSet; + private Hashtable? _references; + private SchemaObjectCache? _cache; // cached schema top-level items private bool _shareTypes; - private Hashtable _mergedSchemas; + private Hashtable? _mergedSchemas; internal Hashtable delayedSchemas = new Hashtable(); private bool _isCompiled; - private static volatile XmlSchema s_xsd; - private static volatile XmlSchema s_xml; + private static volatile XmlSchema? s_xsd; + private static volatile XmlSchema? s_xml; public XmlSchema this[int index] { - get { return (XmlSchema)List[index]; } + get { return (XmlSchema)List[index]!; } set { List[index] = value; } } - public XmlSchema this[string ns] + public XmlSchema? this[string? ns] { get { @@ -43,13 +45,13 @@ public XmlSchema this[string ns] if (values.Count == 0) return null; if (values.Count == 1) - return (XmlSchema)values[0]; + return (XmlSchema?)values[0]; throw new InvalidOperationException(SR.Format(SR.XmlSchemaDuplicateNamespace, ns)); } } - public IList GetSchemas(string ns) + public IList GetSchemas(string? ns) { return (IList)SchemaSet.Schemas(ns); } @@ -118,7 +120,7 @@ public int Add(XmlSchema schema) return List.Add(schema); } - public int Add(XmlSchema schema, Uri baseUri) + public int Add(XmlSchema schema, Uri? baseUri) { if (List.Contains(schema)) return List.IndexOf(schema); @@ -155,7 +157,7 @@ public bool Contains(XmlSchema schema) return List.Contains(schema); } - public bool Contains(string targetNamespace) + public bool Contains(string? targetNamespace) { return SchemaSet.Contains(targetNamespace); } @@ -170,14 +172,14 @@ public void CopyTo(XmlSchema[] array, int index) List.CopyTo(array, index); } - protected override void OnInsert(int index, object value) + protected override void OnInsert(int index, object? value) { - AddName((XmlSchema)value); + AddName((XmlSchema)value!); } - protected override void OnRemove(int index, object value) + protected override void OnRemove(int index, object? value) { - RemoveName((XmlSchema)value); + RemoveName((XmlSchema)value!); } protected override void OnClear() @@ -185,10 +187,10 @@ protected override void OnClear() _schemaSet = null; } - protected override void OnSet(int index, object oldValue, object newValue) + protected override void OnSet(int index, object? oldValue, object? newValue) { - RemoveName((XmlSchema)oldValue); - AddName((XmlSchema)newValue); + RemoveName((XmlSchema)oldValue!); + AddName((XmlSchema)newValue!); } private void AddName(XmlSchema schema) @@ -207,7 +209,7 @@ private void Prepare(XmlSchema schema) { // need to remove illegal externals; ArrayList removes = new ArrayList(); - string ns = schema.TargetNamespace; + string? ns = schema.TargetNamespace; foreach (XmlSchemaExternal external in schema.Includes) { if (external is XmlSchemaImport) @@ -229,11 +231,11 @@ private void RemoveName(XmlSchema schema) SchemaSet.Remove(schema); } - public object Find(XmlQualifiedName name, Type type) + public object? Find(XmlQualifiedName name, Type type) { return Find(name, type, true); } - internal object Find(XmlQualifiedName name, Type type, bool checkCache) + internal object? Find(XmlQualifiedName name, Type type, bool checkCache) { if (!IsCompiled) { @@ -249,7 +251,7 @@ internal object Find(XmlQualifiedName name, Type type, bool checkCache) { Preprocess(schema); - XmlSchemaObject ret = null; + XmlSchemaObject? ret = null; if (typeof(XmlSchemaType).IsAssignableFrom(type)) { ret = schema.SchemaTypes[name]; @@ -359,7 +361,7 @@ private void Merge(XmlSchema schema) } } - private void AddImport(IList schemas, string ns) + private void AddImport(IList schemas, string? ns) { foreach (XmlSchema s in schemas) { @@ -429,7 +431,7 @@ private void Merge(IList originals, XmlSchema schema) for (int i = 0; i < schema.Items.Count; i++) { XmlSchemaObject o = schema.Items[i]; - XmlSchemaObject dest = Find(o, originals); + XmlSchemaObject? dest = Find(o, originals); if (dest != null) { if (!Cache.Match(dest, o, _shareTypes)) @@ -442,7 +444,7 @@ private void Merge(IList originals, XmlSchema schema) } if (count != schema.Items.Count) { - XmlSchema destination = (XmlSchema)originals[0]; + XmlSchema destination = (XmlSchema)originals[0]!; for (int i = 0; i < schema.Items.Count; i++) { if (!matchedItems[i]) @@ -455,7 +457,7 @@ private void Merge(IList originals, XmlSchema schema) } } - private static string ItemName(XmlSchemaObject o) + private static string? ItemName(XmlSchemaObject o) { if (o is XmlSchemaNotation) { @@ -501,7 +503,8 @@ internal static XmlQualifiedName GetParentName(XmlSchemaObject item) return XmlQualifiedName.Empty; } - private static string GetSchemaItem(XmlSchemaObject o, string ns, string details) + [return: NotNullIfNotNull("o")] + private static string? GetSchemaItem(XmlSchemaObject? o, string? ns, string? details) { if (o == null) { @@ -523,7 +526,7 @@ private static string GetSchemaItem(XmlSchemaObject o, string ns, string details ns = ((XmlSchema)tmp).TargetNamespace; } } - string item = null; + string? item = null; if (o is XmlSchemaNotation) { item = SR.Format(SR.XmlSchemaNamedItem, ns, "notation", ((XmlSchemaNotation)o).Name, details); @@ -604,7 +607,7 @@ private static string Dump(XmlSchemaObject o) s.Serialize(xmlWriter, o, ns); return sw.ToString(); } - private static string MergeFailedMessage(XmlSchemaObject src, XmlSchemaObject dest, string ns) + private static string MergeFailedMessage(XmlSchemaObject src, XmlSchemaObject dest, string? ns) { string err = SR.Format(SR.XmlSerializableMergeItem, ns, GetSchemaItem(src, ns, null)); err += "\r\n" + Dump(src); @@ -612,9 +615,9 @@ private static string MergeFailedMessage(XmlSchemaObject src, XmlSchemaObject de return err; } - internal XmlSchemaObject Find(XmlSchemaObject o, IList originals) + internal XmlSchemaObject? Find(XmlSchemaObject o, IList originals) { - string name = ItemName(o); + string? name = ItemName(o); if (name == null) return null; @@ -638,7 +641,7 @@ public bool IsCompiled get { return _isCompiled; } } - public void Compile(ValidationEventHandler handler, bool fullCompile) + public void Compile(ValidationEventHandler? handler, bool fullCompile) { if (_isCompiled) return; @@ -706,14 +709,14 @@ public void Compile(ValidationEventHandler handler, bool fullCompile) internal static Exception CreateValidationException(XmlSchemaException exception, string message) { - XmlSchemaObject source = exception.SourceSchemaObject; + XmlSchemaObject? source = exception.SourceSchemaObject; if (exception.LineNumber == 0 && exception.LinePosition == 0) { throw new InvalidOperationException(GetSchemaItem(source, null, message), exception); } else { - string ns = null; + string? ns = null; if (source != null) { while (source.Parent != null) @@ -729,7 +732,7 @@ internal static Exception CreateValidationException(XmlSchemaException exception } } - internal static void IgnoreCompileErrors(object sender, ValidationEventArgs args) + internal static void IgnoreCompileErrors(object? sender, ValidationEventArgs args) { return; } @@ -752,7 +755,7 @@ internal static XmlSchema XmlSchema { if (s_xml == null) { - s_xml = XmlSchema.Read(new StringReader(xmlSchema), null); + s_xml = XmlSchema.Read(new StringReader(xmlSchema), null)!; } return s_xml; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationEventSource.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationEventSource.cs index 605cc23c4d1712..3e8d6f20db9e5d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationEventSource.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationEventSource.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; using System.Collections.Generic; using System.Linq; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationGeneratedCode.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationGeneratedCode.cs index 67e10d34cc1b22..8cd499f58ddf77 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationGeneratedCode.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationGeneratedCode.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; @@ -15,7 +16,7 @@ namespace System.Xml.Serialization /// public abstract class XmlSerializationGeneratedCode { - internal void Init(TempAssembly tempAssembly) + internal void Init(TempAssembly? tempAssembly) { } @@ -31,11 +32,11 @@ internal class XmlSerializationCodeGen private readonly Hashtable _methodNames = new Hashtable(); private readonly ReflectionAwareCodeGen _raCodeGen; private readonly TypeScope[] _scopes; - private readonly TypeDesc _stringTypeDesc; - private readonly TypeDesc _qnameTypeDesc; + private readonly TypeDesc? _stringTypeDesc; + private readonly TypeDesc? _qnameTypeDesc; private readonly string _access; private readonly string _className; - private TypeMapping[] _referencedMethods; + private TypeMapping[]? _referencedMethods; private int _references; private readonly Hashtable _generatedMethods = new Hashtable(); @@ -56,8 +57,8 @@ internal XmlSerializationCodeGen(IndentedWriter writer, TypeScope[] scopes, stri internal IndentedWriter Writer { get { return _writer; } } internal int NextMethodNumber { get { return _nextMethodNumber; } set { _nextMethodNumber = value; } } internal ReflectionAwareCodeGen RaCodeGen { get { return _raCodeGen; } } - internal TypeDesc StringTypeDesc { get { return _stringTypeDesc; } } - internal TypeDesc QnameTypeDesc { get { return _qnameTypeDesc; } } + internal TypeDesc? StringTypeDesc { get { return _stringTypeDesc; } } + internal TypeDesc? QnameTypeDesc { get { return _qnameTypeDesc; } } internal string ClassName { get { return _className; } } internal string Access { get { return _access; } } internal TypeScope[] Scopes { get { return _scopes; } } @@ -70,22 +71,22 @@ internal void GenerateReferencedMethods() { while (_references > 0) { - TypeMapping mapping = _referencedMethods[--_references]; + TypeMapping mapping = _referencedMethods![--_references]; GenerateMethod(mapping); } } - internal string ReferenceMapping(TypeMapping mapping) + internal string? ReferenceMapping(TypeMapping mapping) { if (!mapping.IsSoap) { if (_generatedMethods[mapping] == null) { - _referencedMethods = EnsureArrayIndex(_referencedMethods, _references); + _referencedMethods = EnsureArrayIndex(_referencedMethods!, _references); _referencedMethods[_references++] = mapping; } } - return (string)_methodNames[mapping]; + return (string?)_methodNames[mapping]; } private TypeMapping[] EnsureArrayIndex(TypeMapping[] a, int index) @@ -97,7 +98,7 @@ private TypeMapping[] EnsureArrayIndex(TypeMapping[] a, int index) return b; } - internal void WriteQuotedCSharpString(string value) + internal void WriteQuotedCSharpString(string? value) { _raCodeGen.WriteQuotedCSharpString(value); } @@ -149,7 +150,7 @@ internal void GenerateHashtableGetEnd(string privateName) _writer.Indent--; _writer.WriteLine("}"); } - internal void GeneratePublicMethods(string privateName, string publicName, string[] methods, XmlMapping[] xmlMappings) + internal void GeneratePublicMethods(string privateName, string publicName, string?[] methods, XmlMapping[] xmlMappings) { GenerateHashtableGetBegin(privateName, publicName); if (methods != null && methods.Length != 0 && xmlMappings != null && xmlMappings.Length == methods.Length) @@ -168,7 +169,7 @@ internal void GeneratePublicMethods(string privateName, string publicName, strin GenerateHashtableGetEnd(privateName); } - internal void GenerateSupportedTypes(Type[] types) + internal void GenerateSupportedTypes(Type?[] types) { _writer.Write("public override "); _writer.Write(typeof(bool).FullName); @@ -179,7 +180,7 @@ internal void GenerateSupportedTypes(Type[] types) Hashtable uniqueTypes = new Hashtable(); for (int i = 0; i < types.Length; i++) { - Type type = types[i]; + Type? type = types[i]; if (type == null) continue; @@ -240,9 +241,9 @@ internal string GenerateBaseSerializer(string baseSerializer, string readerClass return baseSerializer; } - internal string GenerateTypedSerializer(string readMethod, string writeMethod, XmlMapping mapping, CodeIdentifiers classes, string baseSerializer, string readerClass, string writerClass) + internal string GenerateTypedSerializer(string? readMethod, string? writeMethod, XmlMapping mapping, CodeIdentifiers classes, string baseSerializer, string readerClass, string writerClass) { - string serializerName = CodeIdentifier.MakeValid(Accessor.UnescapeName(mapping.Accessor.Mapping.TypeDesc.Name)); + string serializerName = CodeIdentifier.MakeValid(Accessor.UnescapeName(mapping.Accessor.Mapping!.TypeDesc!.Name)); serializerName = classes.AddUnique(serializerName + "Serializer", mapping); _writer.WriteLine(); @@ -327,7 +328,7 @@ private void GenerateTypedSerializers(Hashtable serializers) _writer.Write("_tmp.Add("); WriteQuotedCSharpString(key); _writer.Write(", new "); - _writer.Write((string)serializers[key]); + _writer.Write((string?)serializers[key]); _writer.WriteLine("());"); } GenerateHashtableGetEnd("typedSerializers"); @@ -347,7 +348,7 @@ private void GenerateGetSerializer(Hashtable serializers, XmlMapping[] xmlMappin { if (xmlMappings[i] is XmlTypeMapping) { - Type type = xmlMappings[i].Accessor.Mapping.TypeDesc.Type; + Type? type = xmlMappings[i].Accessor.Mapping!.TypeDesc!.Type; if (type == null) continue; if (!type.IsPublic && !type.IsNestedPublic) @@ -359,7 +360,7 @@ private void GenerateGetSerializer(Hashtable serializers, XmlMapping[] xmlMappin _writer.Write("if (type == typeof("); _writer.Write(CodeIdentifier.GetCSharpName(type)); _writer.Write(")) return new "); - _writer.Write((string)serializers[xmlMappings[i].Key]); + _writer.Write((string?)serializers[xmlMappings[i].Key!]); _writer.WriteLine("();"); } } @@ -368,7 +369,7 @@ private void GenerateGetSerializer(Hashtable serializers, XmlMapping[] xmlMappin _writer.WriteLine("}"); } - internal void GenerateSerializerContract(string className, XmlMapping[] xmlMappings, Type[] types, string readerType, string[] readMethods, string writerType, string[] writerMethods, Hashtable serializers) + internal void GenerateSerializerContract(string className, XmlMapping[] xmlMappings, Type?[] types, string readerType, string?[] readMethods, string writerType, string?[] writerMethods, Hashtable serializers) { _writer.WriteLine(); _writer.Write("public class XmlSerializerContract : global::"); @@ -402,7 +403,7 @@ internal static bool IsWildcard(SpecialMapping mapping) { if (mapping is SerializableMapping) return ((SerializableMapping)mapping).IsAny; - return mapping.TypeDesc.CanBeElementValue; + return mapping.TypeDesc!.CanBeElementValue; } } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationILGen.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationILGen.cs index a014179f33b98c..fe017660a9a700 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationILGen.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationILGen.cs @@ -1,11 +1,13 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; using System.Collections; using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Reflection.Emit; using System.Text.RegularExpressions; @@ -23,16 +25,16 @@ internal class XmlSerializationILGen internal Dictionary memberInfos = new Dictionary(); private readonly ReflectionAwareILGen _raCodeGen; private readonly TypeScope[] _scopes; - private readonly TypeDesc _stringTypeDesc; - private readonly TypeDesc _qnameTypeDesc; + private readonly TypeDesc? _stringTypeDesc; + private readonly TypeDesc? _qnameTypeDesc; private readonly string _className; - private TypeMapping[] _referencedMethods; + private TypeMapping[]? _referencedMethods; private int _references; private readonly HashSet _generatedMethods = new HashSet(); - private ModuleBuilder _moduleBuilder; + private ModuleBuilder? _moduleBuilder; private readonly TypeAttributes _typeAttributes; - protected TypeBuilder typeBuilder; - protected CodeGenerator ilg; + protected TypeBuilder typeBuilder = null!; + protected CodeGenerator ilg = null!; internal XmlSerializationILGen(TypeScope[] scopes, string access, string className) { @@ -50,8 +52,8 @@ internal XmlSerializationILGen(TypeScope[] scopes, string access, string classNa internal int NextMethodNumber { get { return _nextMethodNumber; } set { _nextMethodNumber = value; } } internal ReflectionAwareILGen RaCodeGen { get { return _raCodeGen; } } - internal TypeDesc StringTypeDesc { get { return _stringTypeDesc; } } - internal TypeDesc QnameTypeDesc { get { return _qnameTypeDesc; } } + internal TypeDesc? StringTypeDesc { get { return _stringTypeDesc; } } + internal TypeDesc? QnameTypeDesc { get { return _qnameTypeDesc; } } internal string ClassName { get { return _className; } } internal TypeScope[] Scopes { get { return _scopes; } } internal Dictionary MethodNames { get { return _methodNames; } } @@ -67,7 +69,7 @@ internal ModuleBuilder ModuleBuilder private static readonly Dictionary s_regexs = new Dictionary(); internal static Regex NewRegex(string pattern) { - Regex regex; + Regex? regex; lock (s_regexs) { if (!s_regexs.TryGetValue(pattern, out regex)) @@ -80,9 +82,9 @@ internal static Regex NewRegex(string pattern) } internal MethodBuilder EnsureMethodBuilder(TypeBuilder typeBuilder, string methodName, - MethodAttributes attributes, Type returnType, Type[] parameterTypes) + MethodAttributes attributes, Type? returnType, Type[] parameterTypes) { - MethodBuilderInfo methodBuilderInfo; + MethodBuilderInfo? methodBuilderInfo; if (!_methodBuilders.TryGetValue(methodName, out methodBuilderInfo)) { MethodBuilder methodBuilder = typeBuilder.DefineMethod( @@ -113,24 +115,25 @@ internal void GenerateReferencedMethods() { while (_references > 0) { - TypeMapping mapping = _referencedMethods[--_references]; + TypeMapping mapping = _referencedMethods![--_references]; GenerateMethod(mapping); } } - internal string ReferenceMapping(TypeMapping mapping) + internal string? ReferenceMapping(TypeMapping mapping) { if (!_generatedMethods.Contains(mapping)) { _referencedMethods = EnsureArrayIndex(_referencedMethods, _references); _referencedMethods[_references++] = mapping; } - string methodName; + + string? methodName; _methodNames.TryGetValue(mapping, out methodName); return methodName; } - private TypeMapping[] EnsureArrayIndex(TypeMapping[] a, int index) + private TypeMapping[] EnsureArrayIndex(TypeMapping[]? a, int index) { if (a == null) return new TypeMapping[32]; if (index < a.Length) return a; @@ -139,7 +142,8 @@ private TypeMapping[] EnsureArrayIndex(TypeMapping[] a, int index) return b; } - internal string GetCSharpString(string value) + [return: NotNullIfNotNull("value")] + internal string? GetCSharpString(string? value) { return ReflectionAwareILGen.GetCSharpString(value); } @@ -165,7 +169,7 @@ internal FieldBuilder GenerateHashtableGetBegin(string privateName, string publi Array.Empty(), Array.Empty(), CodeGenerator.PublicOverrideMethodAttributes | MethodAttributes.SpecialName); - propertyBuilder.SetGetMethod(ilg.MethodBuilder); + propertyBuilder.SetGetMethod(ilg.MethodBuilder!); ilg.Ldarg(0); ilg.LoadMember(fieldBuilder); @@ -176,7 +180,7 @@ internal FieldBuilder GenerateHashtableGetBegin(string privateName, string publi ConstructorInfo Hashtable_ctor = typeof(Hashtable).GetConstructor( CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; LocalBuilder _tmpLoc = ilg.DeclareLocal(typeof(Hashtable), "_tmp"); ilg.New(Hashtable_ctor); ilg.Stloc(_tmpLoc); @@ -186,7 +190,7 @@ internal FieldBuilder GenerateHashtableGetBegin(string privateName, string publi internal void GenerateHashtableGetEnd(FieldBuilder fieldBuilder) { - ilg.Ldarg(0); + ilg!.Ldarg(0); ilg.LoadMember(fieldBuilder); ilg.Load(null); ilg.If(Cmp.EqualTo); @@ -213,12 +217,12 @@ internal FieldBuilder GeneratePublicMethods(string privateName, string publicNam MethodInfo Hashtable_set_Item = typeof(Hashtable).GetMethod( "set_Item", new Type[] { typeof(object), typeof(object) } - ); + )!; for (int i = 0; i < methods.Length; i++) { if (methods[i] == null) continue; - ilg.Ldloc(typeof(Hashtable), "_tmp"); + ilg!.Ldloc(typeof(Hashtable), "_tmp"); ilg.Ldstr(GetCSharpString(xmlMappings[i].Key)); ilg.Ldstr(GetCSharpString(methods[i])); ilg.Call(Hashtable_set_Item); @@ -271,7 +275,7 @@ internal string GenerateBaseSerializer(string baseSerializer, string readerClass baseSerializer = classes.AddUnique(baseSerializer, baseSerializer); TypeBuilder baseSerializerTypeBuilder = CodeGenerator.CreateTypeBuilder( - _moduleBuilder, + _moduleBuilder!, CodeIdentifier.GetCSharpName(baseSerializer), TypeAttributes.Public | TypeAttributes.Abstract | TypeAttributes.BeforeFieldInit, typeof(XmlSerializer), @@ -280,7 +284,7 @@ internal string GenerateBaseSerializer(string baseSerializer, string readerClass ConstructorInfo readerCtor = CreatedTypes[readerClass].GetConstructor( CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg = new CodeGenerator(baseSerializerTypeBuilder); ilg.BeginMethod(typeof(XmlSerializationReader), "CreateReader", @@ -293,7 +297,7 @@ internal string GenerateBaseSerializer(string baseSerializer, string readerClass ConstructorInfo writerCtor = CreatedTypes[writerClass].GetConstructor( CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.BeginMethod(typeof(XmlSerializationWriter), "CreateWriter", Array.Empty(), @@ -304,7 +308,7 @@ internal string GenerateBaseSerializer(string baseSerializer, string readerClass baseSerializerTypeBuilder.DefineDefaultConstructor( MethodAttributes.Family | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName); - Type baseSerializerType = baseSerializerTypeBuilder.CreateTypeInfo().AsType(); + Type baseSerializerType = baseSerializerTypeBuilder.CreateTypeInfo()!.AsType(); CreatedTypes.Add(baseSerializerType.Name, baseSerializerType); return baseSerializer; @@ -312,11 +316,11 @@ internal string GenerateBaseSerializer(string baseSerializer, string readerClass internal string GenerateTypedSerializer(string readMethod, string writeMethod, XmlMapping mapping, CodeIdentifiers classes, string baseSerializer, string readerClass, string writerClass) { - string serializerName = CodeIdentifier.MakeValid(Accessor.UnescapeName(mapping.Accessor.Mapping.TypeDesc.Name)); + string serializerName = CodeIdentifier.MakeValid(Accessor.UnescapeName(mapping.Accessor.Mapping!.TypeDesc!.Name)); serializerName = classes.AddUnique(serializerName + "Serializer", mapping); TypeBuilder typedSerializerTypeBuilder = CodeGenerator.CreateTypeBuilder( - _moduleBuilder, + _moduleBuilder!, CodeIdentifier.GetCSharpName(serializerName), TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, CreatedTypes[baseSerializer], @@ -344,7 +348,7 @@ internal string GenerateTypedSerializer(string readMethod, string writeMethod, X "IsStartElement", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string) } - ); + )!; ilg.Ldarg(ilg.GetArg("xmlReader")); ilg.Ldstr(GetCSharpString(mapping.Accessor.Name)); ilg.Ldstr(GetCSharpString(mapping.Accessor.Namespace)); @@ -369,7 +373,7 @@ internal string GenerateTypedSerializer(string readMethod, string writeMethod, X writeMethod, CodeGenerator.InstanceBindingFlags, new Type[] { (mapping is XmlMembersMapping) ? typeof(object[]) : typeof(object) } - ); + )!; ilg.Ldarg("writer"); ilg.Castclass(CreatedTypes[writerClass]); ilg.Ldarg("objectToSerialize"); @@ -393,14 +397,14 @@ internal string GenerateTypedSerializer(string readMethod, string writeMethod, X readMethod, CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg("reader"); ilg.Castclass(CreatedTypes[readerClass]); ilg.Call(readerType_readMethod); ilg.EndMethod(); } typedSerializerTypeBuilder.DefineDefaultConstructor(CodeGenerator.PublicMethodAttributes); - Type typedSerializerType = typedSerializerTypeBuilder.CreateTypeInfo().AsType(); + Type typedSerializerType = typedSerializerTypeBuilder.CreateTypeInfo()!.AsType(); CreatedTypes.Add(typedSerializerType.Name, typedSerializerType); return typedSerializerType.Name; @@ -414,15 +418,15 @@ private FieldBuilder GenerateTypedSerializers(Dictionary seriali "Add", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(object), typeof(object) } - ); + )!; foreach (string key in serializers.Keys) { ConstructorInfo ctor = CreatedTypes[(string)serializers[key]].GetConstructor( CodeGenerator.InstanceBindingFlags, Array.Empty() - ); - ilg.Ldloc(typeof(Hashtable), "_tmp"); + )!; + ilg!.Ldloc(typeof(Hashtable), "_tmp"); ilg.Ldstr(GetCSharpString(key)); ilg.New(ctor); ilg.Call(Hashtable_Add); @@ -446,7 +450,7 @@ private void GenerateGetSerializer(Dictionary serializers, XmlMa { if (xmlMappings[i] is XmlTypeMapping) { - Type type = xmlMappings[i].Accessor.Mapping.TypeDesc.Type; + Type? type = xmlMappings[i].Accessor.Mapping!.TypeDesc!.Type; if (type == null) continue; if (!type.IsPublic && !type.IsNestedPublic) @@ -458,10 +462,10 @@ private void GenerateGetSerializer(Dictionary serializers, XmlMa ilg.Ldc(type); ilg.If(Cmp.EqualTo); { - ConstructorInfo ctor = CreatedTypes[(string)serializers[xmlMappings[i].Key]].GetConstructor( + ConstructorInfo ctor = CreatedTypes[(string)serializers[xmlMappings[i].Key!]].GetConstructor( CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.New(ctor); ilg.Stloc(ilg.ReturnLocal); ilg.Br(ilg.ReturnLabel); @@ -480,7 +484,7 @@ private void GenerateGetSerializer(Dictionary serializers, XmlMa internal void GenerateSerializerContract(string className, XmlMapping[] xmlMappings, Type[] types, string readerType, string[] readMethods, string writerType, string[] writerMethods, Dictionary serializers) { TypeBuilder serializerContractTypeBuilder = CodeGenerator.CreateTypeBuilder( - _moduleBuilder, + _moduleBuilder!, "XmlSerializerContract", TypeAttributes.Public | TypeAttributes.BeforeFieldInit, typeof(XmlSerializerImplementation), @@ -499,11 +503,11 @@ internal void GenerateSerializerContract(string className, XmlMapping[] xmlMappi Array.Empty(), Array.Empty(), CodeGenerator.PublicOverrideMethodAttributes | MethodAttributes.SpecialName); - propertyBuilder.SetGetMethod(ilg.MethodBuilder); + propertyBuilder.SetGetMethod(ilg.MethodBuilder!); ConstructorInfo ctor = CreatedTypes[readerType].GetConstructor( CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.New(ctor); ilg.EndMethod(); @@ -519,11 +523,11 @@ internal void GenerateSerializerContract(string className, XmlMapping[] xmlMappi Array.Empty(), Array.Empty(), CodeGenerator.PublicOverrideMethodAttributes | MethodAttributes.SpecialName); - propertyBuilder.SetGetMethod(ilg.MethodBuilder); + propertyBuilder.SetGetMethod(ilg.MethodBuilder!); ctor = CreatedTypes[writerType].GetConstructor( CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.New(ctor); ilg.EndMethod(); @@ -537,7 +541,7 @@ internal void GenerateSerializerContract(string className, XmlMapping[] xmlMappi ConstructorInfo baseCtor = typeof(XmlSerializerImplementation).GetConstructor( CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg = new CodeGenerator(serializerContractTypeBuilder); ilg.BeginMethod( typeof(void), @@ -559,7 +563,7 @@ internal void GenerateSerializerContract(string className, XmlMapping[] xmlMappi ilg.Call(baseCtor); ilg.EndMethod(); // Instantiate type - Type serializerContractType = serializerContractTypeBuilder.CreateTypeInfo().AsType(); + Type serializerContractType = serializerContractTypeBuilder.CreateTypeInfo()!.AsType(); CreatedTypes.Add(serializerContractType.Name, serializerContractType); } @@ -567,19 +571,19 @@ internal static bool IsWildcard(SpecialMapping mapping) { if (mapping is SerializableMapping) return ((SerializableMapping)mapping).IsAny; - return mapping.TypeDesc.CanBeElementValue; + return mapping.TypeDesc!.CanBeElementValue; } internal void ILGenLoad(string source) { ILGenLoad(source, null); } - internal void ILGenLoad(string source, Type type) + internal void ILGenLoad(string source, Type? type) { if (source.StartsWith("o.@", StringComparison.Ordinal)) { System.Diagnostics.Debug.Assert(memberInfos.ContainsKey(source.Substring(3))); MemberInfo memInfo = memberInfos[source.Substring(3)]; - ilg.LoadMember(ilg.GetVariable("o"), memInfo); + ilg!.LoadMember(ilg.GetVariable("o"), memInfo); if (type != null) { Type memType = (memInfo is FieldInfo) ? ((FieldInfo)memInfo).FieldType : ((PropertyInfo)memInfo).PropertyType; @@ -588,7 +592,7 @@ internal void ILGenLoad(string source, Type type) } else { - SourceInfo info = new SourceInfo(source, null, null, null, ilg); + SourceInfo info = new SourceInfo(source, null, null, null, ilg!); info.Load(type); } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs index 4ecd35f0670c2a..828104e74a1048 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs @@ -1,10 +1,13 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; using System.Collections; + using System.Diagnostics; + using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Reflection; @@ -15,98 +18,98 @@ namespace System.Xml.Serialization /// public abstract class XmlSerializationReader : XmlSerializationGeneratedCode { - private XmlReader _r; - private XmlDocument _d; - private Hashtable _callbacks; - private Hashtable _types; - private Hashtable _typesReverse; + private XmlReader _r = null!; + private XmlDocument? _d; + private Hashtable? _callbacks; + private Hashtable _types = null!; + private Hashtable _typesReverse = null!; private XmlDeserializationEvents _events; - private Hashtable _targets; - private Hashtable _referencedTargets; - private ArrayList _targetsWithoutIds; - private ArrayList _fixups; - private ArrayList _collectionFixups; + private Hashtable? _targets; + private Hashtable? _referencedTargets; + private ArrayList? _targetsWithoutIds; + private ArrayList? _fixups; + private ArrayList? _collectionFixups; private bool _soap12; private bool _isReturnValue; private bool _decodeName = true; - private string _schemaNsID; - private string _schemaNs1999ID; - private string _schemaNs2000ID; - private string _schemaNonXsdTypesNsID; - private string _instanceNsID; - private string _instanceNs2000ID; - private string _instanceNs1999ID; - private string _soapNsID; - private string _soap12NsID; - private string _schemaID; - private string _wsdlNsID; - private string _wsdlArrayTypeID; - private string _nullID; - private string _nilID; - private string _typeID; - private string _arrayTypeID; - private string _itemTypeID; - private string _arraySizeID; - private string _arrayID; - private string _urTypeID; - private string _stringID; - private string _intID; - private string _booleanID; - private string _shortID; - private string _longID; - private string _floatID; - private string _doubleID; - private string _decimalID; - private string _dateTimeID; - private string _qnameID; - private string _dateID; - private string _timeID; - private string _hexBinaryID; - private string _base64BinaryID; - private string _base64ID; - private string _unsignedByteID; - private string _byteID; - private string _unsignedShortID; - private string _unsignedIntID; - private string _unsignedLongID; - private string _oldDecimalID; - private string _oldTimeInstantID; - - private string _anyURIID; - private string _durationID; - private string _ENTITYID; - private string _ENTITIESID; - private string _gDayID; - private string _gMonthID; - private string _gMonthDayID; - private string _gYearID; - private string _gYearMonthID; - private string _IDID; - private string _IDREFID; - private string _IDREFSID; - private string _integerID; - private string _languageID; - private string _nameID; - private string _NCNameID; - private string _NMTOKENID; - private string _NMTOKENSID; - private string _negativeIntegerID; - private string _nonPositiveIntegerID; - private string _nonNegativeIntegerID; - private string _normalizedStringID; - private string _NOTATIONID; - private string _positiveIntegerID; - private string _tokenID; - - private string _charID; - private string _guidID; - private string _timeSpanID; + private string _schemaNsID = null!; + private string _schemaNs1999ID = null!; + private string _schemaNs2000ID = null!; + private string _schemaNonXsdTypesNsID = null!; + private string _instanceNsID = null!; + private string _instanceNs2000ID = null!; + private string _instanceNs1999ID = null!; + private string _soapNsID = null!; + private string _soap12NsID = null!; + private string _schemaID = null!; + private string _wsdlNsID = null!; + private string _wsdlArrayTypeID = null!; + private string _nullID = null!; + private string _nilID = null!; + private string _typeID = null!; + private string _arrayTypeID = null!; + private string _itemTypeID = null!; + private string _arraySizeID = null!; + private string _arrayID = null!; + private string _urTypeID = null!; + private string _stringID = null!; + private string _intID = null!; + private string _booleanID = null!; + private string _shortID = null!; + private string _longID = null!; + private string _floatID = null!; + private string _doubleID = null!; + private string _decimalID = null!; + private string _dateTimeID = null!; + private string _qnameID = null!; + private string _dateID = null!; + private string _timeID = null!; + private string _hexBinaryID = null!; + private string _base64BinaryID = null!; + private string _base64ID = null!; + private string _unsignedByteID = null!; + private string _byteID = null!; + private string _unsignedShortID = null!; + private string _unsignedIntID = null!; + private string _unsignedLongID = null!; + private string _oldDecimalID = null!; + private string _oldTimeInstantID = null!; + + private string _anyURIID = null!; + private string _durationID = null!; + private string _ENTITYID = null!; + private string _ENTITIESID = null!; + private string _gDayID = null!; + private string _gMonthID = null!; + private string _gMonthDayID = null!; + private string _gYearID = null!; + private string _gYearMonthID = null!; + private string _IDID = null!; + private string _IDREFID = null!; + private string _IDREFSID = null!; + private string _integerID = null!; + private string _languageID = null!; + private string _nameID = null!; + private string _NCNameID = null!; + private string _NMTOKENID = null!; + private string _NMTOKENSID = null!; + private string _negativeIntegerID = null!; + private string _nonPositiveIntegerID = null!; + private string _nonNegativeIntegerID = null!; + private string _normalizedStringID = null!; + private string _NOTATIONID = null!; + private string _positiveIntegerID = null!; + private string _tokenID = null!; + + private string _charID = null!; + private string _guidID = null!; + private string _timeSpanID = null!; protected abstract void InitIDs(); // this method must be called before any generated deserialization methods are called - internal void Init(XmlReader r, XmlDeserializationEvents events, string encodingStyle, TempAssembly tempAssembly) + internal void Init(XmlReader r, XmlDeserializationEvents events, string? encodingStyle, TempAssembly? tempAssembly) { _events = events; _r = r; @@ -169,14 +172,14 @@ protected XmlDocument Document if (_d == null) { _d = new XmlDocument(_r.NameTable); - _d.SetBaseURI(_r.BaseURI); + _d.SetBaseURI(_r.BaseURI!); // TODO-NULLABLE: string.Empty should be passed in case of null URI } return _d; } } /// - protected static Assembly ResolveDynamicAssembly(string assemblyFullName) + protected static Assembly? ResolveDynamicAssembly(string assemblyFullName) { return DynamicAssemblies.Get(assemblyFullName); } @@ -243,9 +246,9 @@ private void InitPrimitiveIDs() /// /// [To be supplied.] /// - protected XmlQualifiedName GetXsiType() + protected XmlQualifiedName? GetXsiType() { - string type = _r.GetAttribute(_typeID, _instanceNsID); + string? type = _r.GetAttribute(_typeID, _instanceNsID); if (type == null) { type = _r.GetAttribute(_typeID, _instanceNs2000ID); @@ -262,7 +265,7 @@ protected XmlQualifiedName GetXsiType() // throwOnUnknown flag controls whether this method throws an exception or just returns // null if typeName.Namespace is unknown. the method still throws if typeName.Namespace // is recognized but typeName.Name isn't. - private Type GetPrimitiveType(XmlQualifiedName typeName, bool throwOnUnknown) + private Type? GetPrimitiveType(XmlQualifiedName typeName, bool throwOnUnknown) { InitPrimitiveIDs(); @@ -507,15 +510,15 @@ private byte[] ReadByteArray(bool isBase64) return result; } - protected object ReadTypedPrimitive(XmlQualifiedName type) + protected object? ReadTypedPrimitive(XmlQualifiedName type) { return ReadTypedPrimitive(type, false); } - private object ReadTypedPrimitive(XmlQualifiedName type, bool elementCanBeType) + private object? ReadTypedPrimitive(XmlQualifiedName type, bool elementCanBeType) { InitPrimitiveIDs(); - object value = null; + object? value = null; if (!IsPrimitiveNamespace(type.Namespace) || (object)type.Name == (object)_urTypeID) return ReadXmlNodes(elementCanBeType); @@ -672,10 +675,10 @@ private object ReadTypedPrimitive(XmlQualifiedName type, bool elementCanBeType) return value; } - protected object ReadTypedNull(XmlQualifiedName type) + protected object? ReadTypedNull(XmlQualifiedName type) { InitPrimitiveIDs(); - object value = null; + object? value = null; if (!IsPrimitiveNamespace(type.Namespace) || (object)type.Name == (object)_urTypeID) { return null; @@ -820,7 +823,7 @@ protected bool ReadNull() protected bool GetNullAttr() { - string isNull = _r.GetAttribute(_nilID, _instanceNsID); + string? isNull = _r.GetAttribute(_nilID, _instanceNsID); if (isNull == null) isNull = _r.GetAttribute(_nullID, _instanceNsID); if (isNull == null) @@ -833,7 +836,7 @@ protected bool GetNullAttr() return true; } - protected string ReadNullableString() + protected string? ReadNullableString() { if (ReadNull()) return null; return _r.ReadElementString(); @@ -842,7 +845,7 @@ protected string ReadNullableString() /// /// [To be supplied.] /// - protected XmlQualifiedName ReadNullableQualifiedName() + protected XmlQualifiedName? ReadNullableQualifiedName() { if (ReadNull()) return null; return ReadElementQualifiedName(); @@ -864,9 +867,9 @@ protected XmlQualifiedName ReadElementQualifiedName() return qname; } - protected XmlDocument ReadXmlDocument(bool wrapped) + protected XmlDocument? ReadXmlDocument(bool wrapped) { - XmlNode n = ReadXmlNode(wrapped); + XmlNode? n = ReadXmlNode(wrapped); if (n == null) return null; XmlDocument doc = new XmlDocument(); @@ -874,16 +877,17 @@ protected XmlDocument ReadXmlDocument(bool wrapped) return doc; } - protected string CollapseWhitespace(string value) + [return: NotNullIfNotNull("value")] + protected string? CollapseWhitespace(string? value) { if (value == null) return null; return value.Trim(); } - protected XmlNode ReadXmlNode(bool wrapped) + protected XmlNode? ReadXmlNode(bool wrapped) { - XmlNode node = null; + XmlNode? node = null; if (wrapped) { if (ReadNull()) return null; @@ -904,12 +908,13 @@ protected XmlNode ReadXmlNode(bool wrapped) return node; } - protected static byte[] ToByteArrayBase64(string value) + [return: NotNullIfNotNull("value")] + protected static byte[]? ToByteArrayBase64(string? value) { return XmlCustomFormatter.ToByteArrayBase64(value); } - protected byte[] ToByteArrayBase64(bool isNull) + protected byte[]? ToByteArrayBase64(bool isNull) { if (isNull) { @@ -918,12 +923,13 @@ protected byte[] ToByteArrayBase64(bool isNull) return ReadByteArray(true); //means use Base64 } - protected static byte[] ToByteArrayHex(string value) + [return: NotNullIfNotNull("value")] + protected static byte[]? ToByteArrayHex(string? value) { return XmlCustomFormatter.ToByteArrayHex(value); } - protected byte[] ToByteArrayHex(bool isNull) + protected byte[]? ToByteArrayHex(bool isNull) { if (isNull) { @@ -935,7 +941,7 @@ protected byte[] ToByteArrayHex(bool isNull) protected int GetArrayLength(string name, string ns) { if (GetNullAttr()) return 0; - string arrayType = _r.GetAttribute(_arrayTypeID, _soapNsID); + string? arrayType = _r.GetAttribute(_arrayTypeID, _soapNsID); SoapArrayInfo arrayInfo = ParseArrayType(arrayType); if (arrayInfo.dimensions != 1) throw new InvalidOperationException(SR.Format(SR.XmlInvalidArrayDimentions, CurrentTag())); XmlQualifiedName qname = ToXmlQualifiedName(arrayInfo.qname, false); @@ -952,7 +958,7 @@ private struct SoapArrayInfo public int jaggedDimensions; } - private SoapArrayInfo ParseArrayType(string value) + private SoapArrayInfo ParseArrayType(string? value) { if (value == null) { @@ -1036,7 +1042,7 @@ private SoapArrayInfo ParseArrayType(string value) return soapArrayInfo; } - private SoapArrayInfo ParseSoap12ArrayType(string itemType, string arraySize) + private SoapArrayInfo ParseSoap12ArrayType(string? itemType, string? arraySize) { SoapArrayInfo soapArrayInfo = default; @@ -1110,36 +1116,40 @@ protected static long ToEnum(string value, Hashtable h, string typeName) return XmlCustomFormatter.ToEnum(value, h, typeName, true); } - protected static string ToXmlName(string value) + [return: NotNullIfNotNull("value")] + protected static string? ToXmlName(string? value) { return XmlCustomFormatter.ToXmlName(value); } - protected static string ToXmlNCName(string value) + [return: NotNullIfNotNull("value")] + protected static string? ToXmlNCName(string? value) { return XmlCustomFormatter.ToXmlNCName(value); } - protected static string ToXmlNmToken(string value) + [return: NotNullIfNotNull("value")] + protected static string? ToXmlNmToken(string? value) { return XmlCustomFormatter.ToXmlNmToken(value); } - protected static string ToXmlNmTokens(string value) + [return: NotNullIfNotNull("value")] + protected static string? ToXmlNmTokens(string? value) { return XmlCustomFormatter.ToXmlNmTokens(value); } - protected XmlQualifiedName ToXmlQualifiedName(string value) + protected XmlQualifiedName ToXmlQualifiedName(string? value) { return ToXmlQualifiedName(value, DecodeName); } - internal XmlQualifiedName ToXmlQualifiedName(string value, bool decodeName) + internal XmlQualifiedName ToXmlQualifiedName(string? value, bool decodeName) { int colon = value == null ? -1 : value.LastIndexOf(':'); - string prefix = colon < 0 ? null : value.Substring(0, colon); - string localName = value.Substring(colon + 1); + string? prefix = colon < 0 ? null : value!.Substring(0, colon); + string localName = value!.Substring(colon + 1); if (decodeName) { @@ -1152,7 +1162,7 @@ internal XmlQualifiedName ToXmlQualifiedName(string value, bool decodeName) } else { - string ns = _r.LookupNamespace(prefix); + string? ns = _r.LookupNamespace(prefix); if (ns == null) { // Namespace prefix '{0}' is not defined. @@ -1161,12 +1171,12 @@ internal XmlQualifiedName ToXmlQualifiedName(string value, bool decodeName) return new XmlQualifiedName(_r.NameTable.Add(localName), ns); } } - protected void UnknownAttribute(object o, XmlAttribute attr) + protected void UnknownAttribute(object? o, XmlAttribute attr) { UnknownAttribute(o, attr, null); } - protected void UnknownAttribute(object o, XmlAttribute attr, string qnames) + protected void UnknownAttribute(object? o, XmlAttribute attr, string? qnames) { if (_events.OnUnknownAttribute != null) { @@ -1177,12 +1187,12 @@ protected void UnknownAttribute(object o, XmlAttribute attr, string qnames) } } - protected void UnknownElement(object o, XmlElement elem) + protected void UnknownElement(object? o, XmlElement elem) { UnknownElement(o, elem, null); } - protected void UnknownElement(object o, XmlElement elem, string qnames) + protected void UnknownElement(object? o, XmlElement elem, string? qnames) { if (_events.OnUnknownElement != null) { @@ -1193,12 +1203,12 @@ protected void UnknownElement(object o, XmlElement elem, string qnames) } } - protected void UnknownNode(object o) + protected void UnknownNode(object? o) { UnknownNode(o, null); } - protected void UnknownNode(object o, string qnames) + protected void UnknownNode(object? o, string? qnames) { if (_r.NodeType == XmlNodeType.None || _r.NodeType == XmlNodeType.Whitespace) { @@ -1226,7 +1236,7 @@ protected void UnknownNode(object o, string qnames) } } - private void UnknownNode(XmlNode unknownNode, object o, string qnames) + private void UnknownNode(XmlNode? unknownNode, object? o, string? qnames) { if (unknownNode == null) return; @@ -1259,7 +1269,7 @@ private void GetCurrentPosition(out int lineNumber, out int linePosition) lineNumber = linePosition = -1; } - protected void UnreferencedObject(string id, object o) + protected void UnreferencedObject(string? id, object? o) { if (_events.OnUnreferencedObject != null) { @@ -1290,7 +1300,7 @@ protected Exception CreateReadOnlyCollectionException(string name) return new InvalidOperationException(SR.Format(SR.XmlReadOnlyCollection, name)); } - protected Exception CreateAbstractTypeException(string name, string ns) + protected Exception CreateAbstractTypeException(string name, string? ns) { return new InvalidOperationException(SR.Format(SR.XmlAbstractType, name, ns, CurrentTag())); } @@ -1310,17 +1320,17 @@ protected Exception CreateUnknownNodeException() return new InvalidOperationException(SR.Format(SR.XmlUnknownNode, CurrentTag())); } - protected Exception CreateUnknownConstantException(string value, Type enumType) + protected Exception CreateUnknownConstantException(string? value, Type enumType) { return new InvalidOperationException(SR.Format(SR.XmlUnknownConstant, value, enumType.Name)); } - protected Exception CreateInvalidCastException(Type type, object value) + protected Exception CreateInvalidCastException(Type type, object? value) { return CreateInvalidCastException(type, value, null); } - protected Exception CreateInvalidCastException(Type type, object value, string id) + protected Exception CreateInvalidCastException(Type type, object? value, string? id) { if (value == null) return new InvalidCastException(SR.Format(SR.XmlInvalidNullCast, type.FullName)); @@ -1330,18 +1340,18 @@ protected Exception CreateInvalidCastException(Type type, object value, string i return new InvalidCastException(SR.Format(SR.XmlInvalidCastWithId, value.GetType().FullName, type.FullName, id)); } - protected Exception CreateBadDerivationException(string xsdDerived, string nsDerived, string xsdBase, string nsBase, string clrDerived, string clrBase) + protected Exception CreateBadDerivationException(string? xsdDerived, string? nsDerived, string? xsdBase, string? nsBase, string? clrDerived, string? clrBase) { return new InvalidOperationException(SR.Format(SR.XmlSerializableBadDerivation, xsdDerived, nsDerived, xsdBase, nsBase, clrDerived, clrBase)); } - protected Exception CreateMissingIXmlSerializableType(string name, string ns, string clrType) + protected Exception CreateMissingIXmlSerializableType(string? name, string? ns, string? clrType) { return new InvalidOperationException(SR.Format(SR.XmlSerializableMissingClrType, name, ns, typeof(XmlIncludeAttribute).Name, clrType)); //XmlSerializableMissingClrType= Type '{0}' from namespace '{1}' doesnot have corresponding IXmlSerializable type. Please consider adding {2} to '{3}'. } - protected Array EnsureArrayIndex(Array a, int index, Type elementType) + protected Array EnsureArrayIndex(Array? a, int index, Type elementType) { if (a == null) return Array.CreateInstance(elementType, 32); if (index < a.Length) return a; @@ -1350,7 +1360,7 @@ protected Array EnsureArrayIndex(Array a, int index, Type elementType) return b; } - protected Array ShrinkArray(Array a, int length, Type elementType, bool isNullable) + protected Array? ShrinkArray(Array? a, int length, Type elementType, bool isNullable) { if (a == null) { @@ -1363,12 +1373,14 @@ protected Array ShrinkArray(Array a, int length, Type elementType, bool isNullab return b; } - protected string ReadString(string value) + [return: NotNullIfNotNull("value")] + protected string? ReadString(string? value) { return ReadString(value, false); } - protected string ReadString(string value, bool trim) + [return: NotNullIfNotNull("value")] + protected string? ReadString(string? value, bool trim) { string str = _r.ReadString(); if (str != null && trim) @@ -1385,8 +1397,8 @@ protected IXmlSerializable ReadSerializable(IXmlSerializable serializable) protected IXmlSerializable ReadSerializable(IXmlSerializable serializable, bool wrappedAny) { - string name = null; - string ns = null; + string? name = null; + string? ns = null; if (wrappedAny) { @@ -1409,9 +1421,9 @@ protected IXmlSerializable ReadSerializable(IXmlSerializable serializable, bool return serializable; } - protected bool ReadReference(out string fixupReference) + protected bool ReadReference([NotNullWhen(true)] out string? fixupReference) { - string href = _soap12 ? _r.GetAttribute("ref", Soap12.Encoding) : _r.GetAttribute("href"); + string? href = _soap12 ? _r.GetAttribute("ref", Soap12.Encoding) : _r.GetAttribute("href"); if (href == null) { fixupReference = null; @@ -1438,7 +1450,7 @@ protected bool ReadReference(out string fixupReference) return true; } - protected void AddTarget(string id, object o) + protected void AddTarget(string? id, object? o) { if (id == null) { @@ -1455,15 +1467,13 @@ protected void AddTarget(string id, object o) } } - - - protected void AddFixup(Fixup fixup) + protected void AddFixup(Fixup? fixup) { if (_fixups == null) _fixups = new ArrayList(); _fixups.Add(fixup); } - protected void AddFixup(CollectionFixup fixup) + protected void AddFixup(CollectionFixup? fixup) { if (_collectionFixups == null) _collectionFixups = new ArrayList(); _collectionFixups.Add(fixup); @@ -1471,7 +1481,7 @@ protected void AddFixup(CollectionFixup fixup) protected object GetTarget(string id) { - object target = _targets != null ? _targets[id] : null; + object? target = _targets != null ? _targets[id] : null; if (target == null) { throw new InvalidOperationException(SR.Format(SR.XmlInvalidHref, id)); @@ -1480,7 +1490,7 @@ protected object GetTarget(string id) return target; } - protected void Referenced(object o) + protected void Referenced(object? o) { if (o == null) return; if (_referencedTargets == null) _referencedTargets = new Hashtable(); @@ -1493,9 +1503,9 @@ private void HandleUnreferencedObjects() { foreach (DictionaryEntry target in _targets) { - if (_referencedTargets == null || !_referencedTargets.Contains(target.Value)) + if (_referencedTargets == null || !_referencedTargets.Contains(target.Value!)) { - UnreferencedObject((string)target.Key, target.Value); + UnreferencedObject((string)target.Key, target.Value!); } } } @@ -1516,14 +1526,14 @@ private void DoFixups() if (_fixups == null) return; for (int i = 0; i < _fixups.Count; i++) { - Fixup fixup = (Fixup)_fixups[i]; + Fixup fixup = (Fixup)_fixups[i]!; fixup.Callback(fixup); } if (_collectionFixups == null) return; for (int i = 0; i < _collectionFixups.Count; i++) { - CollectionFixup collectionFixup = (CollectionFixup)_collectionFixups[i]; + CollectionFixup collectionFixup = (CollectionFixup)_collectionFixups[i]!; collectionFixup.Callback(collectionFixup.Collection, collectionFixup.CollectionItems); } } @@ -1531,10 +1541,10 @@ private void DoFixups() protected void FixupArrayRefs(object fixup) { Fixup f = (Fixup)fixup; - Array array = (Array)f.Source; + Array array = (Array)f.Source!; for (int i = 0; i < array.Length; i++) { - string id = f.Ids[i]; + string? id = f.Ids![i]; if (id == null) continue; object o = GetTarget(id); try @@ -1548,15 +1558,15 @@ protected void FixupArrayRefs(object fixup) } } - private object ReadArray(string typeName, string typeNs) + private object? ReadArray(string? typeName, string? typeNs) { SoapArrayInfo arrayInfo; - Type fallbackElementType = null; + Type? fallbackElementType = null; if (_soap12) { - string itemType = _r.GetAttribute(_itemTypeID, _soap12NsID); - string arraySize = _r.GetAttribute(_arraySizeID, _soap12NsID); - Type arrayType = (Type)_types[new XmlQualifiedName(typeName, typeNs)]; + string? itemType = _r.GetAttribute(_itemTypeID, _soap12NsID); + string? arraySize = _r.GetAttribute(_arraySizeID, _soap12NsID); + Type? arrayType = (Type?)_types[new XmlQualifiedName(typeName, typeNs)]; // no indication that this is an array? if (itemType == null && arraySize == null && (arrayType == null || !arrayType.IsArray)) return null; @@ -1567,7 +1577,7 @@ private object ReadArray(string typeName, string typeNs) } else { - string arrayType = _r.GetAttribute(_arrayTypeID, _soapNsID); + string? arrayType = _r.GetAttribute(_arrayTypeID, _soapNsID); if (arrayType == null) return null; @@ -1581,12 +1591,12 @@ private object ReadArray(string typeName, string typeNs) XmlQualifiedName qname; bool isPrimitive; - Type elementType = null; + Type? elementType = null; XmlQualifiedName urTypeName = new XmlQualifiedName(_urTypeID, _schemaNsID); if (arrayInfo.qname.Length > 0) { qname = ToXmlQualifiedName(arrayInfo.qname, false); - elementType = (Type)_types[qname]; + elementType = (Type?)_types[qname]; } else qname = urTypeName; @@ -1599,7 +1609,7 @@ private object ReadArray(string typeName, string typeNs) { if (!_soap12) { - elementType = GetPrimitiveType(qname, true); + elementType = GetPrimitiveType(qname, true)!; isPrimitive = true; } else @@ -1622,7 +1632,7 @@ private object ReadArray(string typeName, string typeNs) else { elementType = fallbackElementType; - XmlQualifiedName newQname = (XmlQualifiedName)_typesReverse[elementType]; + XmlQualifiedName? newQname = (XmlQualifiedName?)_typesReverse[elementType]; if (newQname == null) { newQname = XmlSerializationWriter.GetPrimitiveTypeNameInternal(elementType); @@ -1654,7 +1664,7 @@ private object ReadArray(string typeName, string typeNs) _r.MoveToContent(); int arrayLength = 0; - Array array = null; + Array? array = null; if (elementType.IsValueType) { @@ -1677,7 +1687,7 @@ private object ReadArray(string typeName, string typeNs) { string type; string typens; - string[] ids = null; + string[]? ids = null; int idsLength = 0; while (_r.NodeType != XmlNodeType.EndElement) @@ -1698,7 +1708,7 @@ private object ReadArray(string typeName, string typeNs) type = qname.Name; typens = qname.Namespace; } - array.SetValue(ReadReferencingElement(type, typens, out ids[idsLength]), arrayLength); + array.SetValue(ReadReferencingElement(type, typens, out ids[idsLength]!), arrayLength); arrayLength++; idsLength++; // CONSIDER, erikc, sparse arrays, perhaps? @@ -1709,10 +1719,10 @@ private object ReadArray(string typeName, string typeNs) // this applies in the doc/enc/bare case if (_soap12 && elementType == typeof(object)) { - Type itemType = null; + Type? itemType = null; for (int i = 0; i < arrayLength; i++) { - object currItem = array.GetValue(i); + object? currItem = array!.GetValue(i); if (currItem != null) { Type currItemType = currItem.GetType(); @@ -1735,7 +1745,7 @@ private object ReadArray(string typeName, string typeNs) if (itemType != null) elementType = itemType; } - ids = (string[])ShrinkArray(ids, idsLength, typeof(string), false); + ids = (string[]?)ShrinkArray(ids, idsLength, typeof(string), false); array = ShrinkArray(array, arrayLength, elementType, false); Fixup fixupArray = new Fixup(array, new XmlSerializationFixupCallback(this.FixupArrayRefs), ids); AddFixup(fixupArray); @@ -1752,7 +1762,7 @@ private object ReadArray(string typeName, string typeNs) protected void ReadReferencedElements() { _r.MoveToContent(); - string dummy; + string? dummy; while (_r.NodeType != XmlNodeType.EndElement && _r.NodeType != XmlNodeType.None) { ReadReferencingElement(null, null, true, out dummy); @@ -1763,30 +1773,31 @@ protected void ReadReferencedElements() HandleUnreferencedObjects(); } - protected object ReadReferencedElement() + protected object? ReadReferencedElement() { return ReadReferencedElement(null, null); } - protected object ReadReferencedElement(string name, string ns) + protected object? ReadReferencedElement(string? name, string? ns) { - string dummy; + string? dummy; return ReadReferencingElement(name, ns, out dummy); } - protected object ReadReferencingElement(out string fixupReference) + protected object? ReadReferencingElement(out string? fixupReference) { return ReadReferencingElement(null, null, out fixupReference); } - protected object ReadReferencingElement(string name, string ns, out string fixupReference) + protected object? ReadReferencingElement(string? name, string? ns, out string? fixupReference) { return ReadReferencingElement(name, ns, false, out fixupReference); } - protected object ReadReferencingElement(string name, string ns, bool elementCanBeType, out string fixupReference) + [MemberNotNull(nameof(_callbacks))] + protected object? ReadReferencingElement(string? name, string? ns, bool elementCanBeType, out string? fixupReference) { - object o = null; + object? o = null; EnsureCallbackTables(); _r.MoveToContent(); @@ -1795,19 +1806,19 @@ protected object ReadReferencingElement(string name, string ns, bool elementCanB if (ReadNull()) return null; - string id = _soap12 ? _r.GetAttribute("id", Soap12.Encoding) : _r.GetAttribute("id", null); + string? id = _soap12 ? _r.GetAttribute("id", Soap12.Encoding) : _r.GetAttribute("id", null); if ((o = ReadArray(name, ns)) == null) { - XmlQualifiedName typeId = GetXsiType(); + XmlQualifiedName? typeId = GetXsiType(); if (typeId == null) { if (name == null) typeId = new XmlQualifiedName(_r.NameTable.Add(_r.LocalName), _r.NameTable.Add(_r.NamespaceURI)); else - typeId = new XmlQualifiedName(_r.NameTable.Add(name), _r.NameTable.Add(ns)); + typeId = new XmlQualifiedName(_r.NameTable.Add(name), _r.NameTable.Add(ns!)); } - XmlSerializationReadCallback callback = (XmlSerializationReadCallback)_callbacks[typeId]; + XmlSerializationReadCallback? callback = (XmlSerializationReadCallback?)_callbacks[typeId]; if (callback != null) { o = callback(); @@ -1821,6 +1832,7 @@ protected object ReadReferencingElement(string name, string ns, bool elementCanB return o; } + [MemberNotNull(nameof(_callbacks))] internal void EnsureCallbackTables() { if (_callbacks == null) @@ -1838,7 +1850,7 @@ internal void EnsureCallbackTables() protected void AddReadCallback(string name, string ns, Type type, XmlSerializationReadCallback read) { XmlQualifiedName typeName = new XmlQualifiedName(_r.NameTable.Add(name), _r.NameTable.Add(ns)); - _callbacks[typeName] = read; + _callbacks![typeName] = read; _types[typeName] = type; _typesReverse[type] = typeName; } @@ -1856,11 +1868,11 @@ private object ReadXmlNodes(bool elementCanBeType) string elemLocalName = Reader.LocalName; string elemNs = Reader.NamespaceURI; string elemName = Reader.Name; - string xsiTypeName = null; - string xsiTypeNs = null; + string? xsiTypeName = null; + string? xsiTypeNs = null; int skippableNodeCount = 0; int lineNumber = -1, linePosition = -1; - XmlNode unknownNode = null; + XmlNode? unknownNode = null; if (Reader.NodeType == XmlNodeType.Attribute) { XmlAttribute attr = Document.CreateAttribute(elemName, elemNs); @@ -1870,7 +1882,7 @@ private object ReadXmlNodes(bool elementCanBeType) else unknownNode = Document.CreateElement(elemName, elemNs); GetCurrentPosition(out lineNumber, out linePosition); - XmlElement unknownElement = unknownNode as XmlElement; + XmlElement? unknownElement = unknownNode as XmlElement; while (Reader.MoveToNextAttribute()) { @@ -1888,7 +1900,7 @@ private object ReadXmlNodes(bool elementCanBeType) xsiTypeName = (colon >= 0) ? value.Substring(colon + 1) : value; xsiTypeNs = Reader.LookupNamespace((colon >= 0) ? value.Substring(0, colon) : ""); } - XmlAttribute xmlAttribute = (XmlAttribute)Document.ReadNode(_r); + XmlAttribute xmlAttribute = (XmlAttribute)Document.ReadNode(_r)!; xmlNodeList.Add(xmlAttribute); if (unknownElement != null) unknownElement.SetAttributeNode(xmlAttribute); } @@ -1905,9 +1917,9 @@ private object ReadXmlNodes(bool elementCanBeType) xmlNodeList.Add(xsiTypeAttribute); } if (xsiTypeName == Soap.UrType && - ((object)xsiTypeNs == (object)_schemaNsID || - (object)xsiTypeNs == (object)_schemaNs1999ID || - (object)xsiTypeNs == (object)_schemaNs2000ID + ((object?)xsiTypeNs == (object)_schemaNsID || + (object?)xsiTypeNs == (object)_schemaNs1999ID || + (object?)xsiTypeNs == (object)_schemaNs2000ID ) ) skippableNodeCount++; @@ -1924,7 +1936,7 @@ private object ReadXmlNodes(bool elementCanBeType) Reader.MoveToContent(); while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) { - XmlNode xmlNode = Document.ReadNode(_r); + XmlNode xmlNode = Document.ReadNode(_r)!; xmlNodeList.Add(xmlNode); if (unknownElement != null) unknownElement.AppendChild(xmlNode); Reader.MoveToContent(); @@ -1950,15 +1962,15 @@ protected void CheckReaderCount(ref int whileIterations, ref int readerCount) protected class Fixup { private readonly XmlSerializationFixupCallback _callback; - private object _source; - private readonly string[] _ids; + private object? _source; + private readonly string?[]? _ids; - public Fixup(object o, XmlSerializationFixupCallback callback, int count) + public Fixup(object? o, XmlSerializationFixupCallback callback, int count) : this(o, callback, new string[count]) { } - public Fixup(object o, XmlSerializationFixupCallback callback, string[] ids) + public Fixup(object? o, XmlSerializationFixupCallback callback, string?[]? ids) { _callback = callback; this.Source = o; @@ -1970,13 +1982,13 @@ public XmlSerializationFixupCallback Callback get { return _callback; } } - public object Source + public object? Source { get { return _source; } set { _source = value; } } - public string[] Ids + public string?[]? Ids { get { return _ids; } } @@ -1985,10 +1997,10 @@ public string[] Ids protected class CollectionFixup { private readonly XmlSerializationCollectionFixupCallback _callback; - private readonly object _collection; + private readonly object? _collection; private readonly object _collectionItems; - public CollectionFixup(object collection, XmlSerializationCollectionFixupCallback callback, object collectionItems) + public CollectionFixup(object? collection, XmlSerializationCollectionFixupCallback callback, object collectionItems) { _callback = callback; _collection = collection; @@ -2000,7 +2012,7 @@ public XmlSerializationCollectionFixupCallback Callback get { return _callback; } } - public object Collection + public object? Collection { get { return _collection; } } @@ -2017,15 +2029,15 @@ public object CollectionItems /// - public delegate void XmlSerializationCollectionFixupCallback(object collection, object collectionItems); + public delegate void XmlSerializationCollectionFixupCallback(object? collection, object? collectionItems); /// - public delegate object XmlSerializationReadCallback(); + public delegate object? XmlSerializationReadCallback(); internal class XmlSerializationReaderCodeGen : XmlSerializationCodeGen { private readonly Hashtable _idNames = new Hashtable(); - private Hashtable _enums; + private Hashtable? _enums; private readonly Hashtable _createMethods = new Hashtable(); private int _nextCreateMethodNumber; private int _nextIdNumber; @@ -2068,22 +2080,22 @@ private class Member private readonly string _arrayName; private readonly string _arraySource; private readonly string _choiceArrayName; - private readonly string _choiceSource; - private readonly string _choiceArraySource; + private readonly string? _choiceSource; + private readonly string? _choiceArraySource; private readonly MemberMapping _mapping; private readonly bool _isArray; private readonly bool _isList; private bool _isNullable; private bool _multiRef; private int _fixupIndex = -1; - private string _paramsReadSource; - private string _checkSpecifiedSource; + private string? _paramsReadSource; + private string? _checkSpecifiedSource; internal Member(XmlSerializationReaderCodeGen outerClass, string source, string arrayName, int i, MemberMapping mapping) : this(outerClass, source, null, arrayName, i, mapping, false, null) { } - internal Member(XmlSerializationReaderCodeGen outerClass, string source, string arrayName, int i, MemberMapping mapping, string choiceSource) + internal Member(XmlSerializationReaderCodeGen outerClass, string source, string arrayName, int i, MemberMapping mapping, string? choiceSource) : this(outerClass, source, null, arrayName, i, mapping, false, choiceSource) { } @@ -2091,23 +2103,23 @@ internal Member(XmlSerializationReaderCodeGen outerClass, string source, string : this(outerClass, source, arraySource, arrayName, i, mapping, false, null) { } - internal Member(XmlSerializationReaderCodeGen outerClass, string source, string arraySource, string arrayName, int i, MemberMapping mapping, string choiceSource) + internal Member(XmlSerializationReaderCodeGen outerClass, string source, string? arraySource, string arrayName, int i, MemberMapping mapping, string? choiceSource) : this(outerClass, source, arraySource, arrayName, i, mapping, false, choiceSource) { } - internal Member(XmlSerializationReaderCodeGen outerClass, string source, string arrayName, int i, MemberMapping mapping, bool multiRef) + internal Member(XmlSerializationReaderCodeGen outerClass, string source, string? arrayName, int i, MemberMapping mapping, bool multiRef) : this(outerClass, source, null, arrayName, i, mapping, multiRef, null) { } - internal Member(XmlSerializationReaderCodeGen outerClass, string source, string arraySource, string arrayName, int i, MemberMapping mapping, bool multiRef, string choiceSource) + internal Member(XmlSerializationReaderCodeGen outerClass, string source, string? arraySource, string? arrayName, int i, MemberMapping mapping, bool multiRef, string? choiceSource) { _source = source; _arrayName = arrayName + "_" + i.ToString(CultureInfo.InvariantCulture); _choiceArrayName = "choice_" + _arrayName; _choiceSource = choiceSource; - ElementAccessor[] elements = mapping.Elements; + ElementAccessor[]? elements = mapping.Elements; - if (mapping.TypeDesc.IsArrayLike) + if (mapping.TypeDesc!.IsArrayLike) { if (arraySource != null) _arraySource = arraySource; @@ -2121,7 +2133,7 @@ internal Member(XmlSerializationReaderCodeGen outerClass, string source, string string a = _choiceArrayName; string c = "c" + a; - bool choiceUseReflection = mapping.ChoiceIdentifier.Mapping.TypeDesc.UseReflection; + bool choiceUseReflection = mapping.ChoiceIdentifier.Mapping!.TypeDesc!.UseReflection; string choiceTypeFullName = mapping.ChoiceIdentifier.Mapping.TypeDesc.CSharpName; string castString = choiceUseReflection ? "" : "(" + choiceTypeFullName + "[])"; @@ -2190,19 +2202,19 @@ internal int FixupIndex set { _fixupIndex = value; } } - internal string ParamsReadSource + internal string? ParamsReadSource { get { return _paramsReadSource; } set { _paramsReadSource = value; } } - internal string CheckSpecifiedSource + internal string? CheckSpecifiedSource { get { return _checkSpecifiedSource; } set { _checkSpecifiedSource = value; } } - internal string ChoiceSource + internal string? ChoiceSource { get { return _choiceSource; } } @@ -2210,7 +2222,7 @@ internal string ChoiceArrayName { get { return _choiceArrayName; } } - internal string ChoiceArraySource + internal string? ChoiceArraySource { get { return _choiceArraySource; } } @@ -2234,7 +2246,7 @@ internal void GenerateBegin() foreach (TypeMapping mapping in scope.TypeMappings) { if (mapping is StructMapping || mapping is EnumMapping || mapping is NullableMapping) - MethodNames.Add(mapping, NextMethodName(mapping.TypeDesc.Name)); + MethodNames.Add(mapping, NextMethodName(mapping.TypeDesc!.Name)); } RaCodeGen.WriteReflectionInit(scope); } @@ -2277,7 +2289,7 @@ internal override void GenerateMethod(TypeMapping mapping) } } - internal void GenerateEnd(string[] methods, XmlMapping[] xmlMappings, Type[] types) + internal void GenerateEnd(string?[] methods, XmlMapping[] xmlMappings, Type?[]? types) { GenerateReferencedMethods(); GenerateInitCallbacksMethod(); @@ -2301,7 +2313,7 @@ internal void GenerateEnd(string[] methods, XmlMapping[] xmlMappings, Type[] typ foreach (string id in _idNames.Keys) { // CONSIDER, erikc, switch to enumerating via DictionaryEntry when issue recolved in BCL - string idName = (string)_idNames[id]; + string idName = (string)_idNames[id]!; Writer.Write(idName); Writer.Write(" = Reader.NameTable.Add("); WriteQuotedCSharpString(id); @@ -2314,7 +2326,7 @@ internal void GenerateEnd(string[] methods, XmlMapping[] xmlMappings, Type[] typ Writer.WriteLine("}"); } - internal string GenerateElement(XmlMapping xmlMapping) + internal string? GenerateElement(XmlMapping xmlMapping) { if (!xmlMapping.IsReadable) return null; @@ -2328,7 +2340,7 @@ internal string GenerateElement(XmlMapping xmlMapping) throw new ArgumentException(SR.XmlInternalError, nameof(xmlMapping)); } - private void WriteIsStartTag(string name, string ns) + private void WriteIsStartTag(string name, string? ns) { Writer.Write("if (Reader.IsStartElement("); WriteID(name); @@ -2338,7 +2350,7 @@ private void WriteIsStartTag(string name, string ns) Writer.Indent++; } - private void WriteUnknownNode(string func, string node, ElementAccessor e, bool anyIfs) + private void WriteUnknownNode(string func, string node, ElementAccessor? e, bool anyIfs) { if (anyIfs) { @@ -2351,7 +2363,7 @@ private void WriteUnknownNode(string func, string node, ElementAccessor e, bool if (e != null) { Writer.Write(", "); - string expectedElement = e.Form == XmlSchemaForm.Qualified ? e.Namespace : ""; + string? expectedElement = e.Form == XmlSchemaForm.Qualified ? e.Namespace : ""; expectedElement += ":"; expectedElement += e.Name; ReflectionAwareCodeGen.WriteQuotedCSharpString(Writer, expectedElement); @@ -2378,7 +2390,7 @@ private void GenerateInitCallbacksMethod() { if (mapping.IsSoap && (mapping is StructMapping || mapping is EnumMapping || mapping is ArrayMapping || mapping is NullableMapping) && - !mapping.TypeDesc.IsRoot) + !mapping.TypeDesc!.IsRoot) { string methodName; if (mapping is ArrayMapping) @@ -2387,7 +2399,7 @@ private void GenerateInitCallbacksMethod() needDummyArrayMethod = true; } else - methodName = (string)MethodNames[mapping]; + methodName = (string)MethodNames[mapping]!; Writer.Write("AddReadCallback("); WriteID(mapping.TypeName); @@ -2431,9 +2443,9 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) return GenerateLiteralMembersElement(xmlMembersMapping); } - private string GetChoiceIdentifierSource(MemberMapping[] mappings, MemberMapping member) + private string? GetChoiceIdentifierSource(MemberMapping[] mappings, MemberMapping member) { - string choiceSource = null; + string? choiceSource = null; if (member.ChoiceIdentifier != null) { for (int j = 0; j < mappings.Length; j++) @@ -2463,7 +2475,7 @@ private string GetChoiceIdentifierSource(MemberMapping mapping, string parent, T private string GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping) { ElementAccessor element = xmlMembersMapping.Accessor; - MemberMapping[] mappings = ((MembersMapping)element.Mapping).Members; + MemberMapping[] mappings = ((MembersMapping)element.Mapping!).Members!; bool hasWrapperElement = ((MembersMapping)element.Mapping).HasWrapperElement; string methodName = NextMethodName(element.Name); Writer.WriteLine(); @@ -2485,9 +2497,9 @@ private string GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping WriteIsStartTag(element.Name, element.Form == XmlSchemaForm.Qualified ? element.Namespace : ""); } - Member anyText = null; - Member anyElement = null; - Member anyAttribute = null; + Member? anyText = null; + Member? anyElement = null; + Member? anyAttribute = null; ArrayList membersList = new ArrayList(); ArrayList textOrArrayMembersList = new ArrayList(); @@ -2500,9 +2512,9 @@ private string GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping string arraySource = source; if (mapping.Xmlns != null) { - arraySource = "((" + mapping.TypeDesc.CSharpName + ")" + source + ")"; + arraySource = "((" + mapping.TypeDesc!.CSharpName + ")" + source + ")"; } - string choiceSource = GetChoiceIdentifierSource(mappings, mapping); + string? choiceSource = GetChoiceIdentifierSource(mappings, mapping); Member member = new Member(this, source, arraySource, "a", i, mapping, choiceSource); Member anyMember = new Member(this, source, null, "a", i, mapping, choiceSource); if (!mapping.IsSequence) @@ -2530,7 +2542,7 @@ private string GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping if (!mapping.IsSequence) { - for (int j = 0; j < mapping.Elements.Length; j++) + for (int j = 0; j < mapping.Elements!.Length; j++) { if (mapping.Elements[j].Any && mapping.Elements[j].Name.Length == 0) { @@ -2544,7 +2556,7 @@ private string GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping } if (mapping.Attribute != null || mapping.Text != null || foundAnyElement) membersList.Add(anyMember); - else if (mapping.TypeDesc.IsArrayLike && !(mapping.Elements.Length == 1 && mapping.Elements[0].Mapping is ArrayMapping)) + else if (mapping.TypeDesc!.IsArrayLike && !(mapping.Elements!.Length == 1 && mapping.Elements[0].Mapping is ArrayMapping)) { membersList.Add(anyMember); textOrArrayMembersList.Add(anyMember); @@ -2618,20 +2630,20 @@ private void InitializeValueTypes(string arrayName, MemberMapping[] mappings) { for (int i = 0; i < mappings.Length; i++) { - if (!mappings[i].TypeDesc.IsValueType) + if (!mappings[i].TypeDesc!.IsValueType) continue; Writer.Write(arrayName); Writer.Write("["); Writer.Write(i.ToString(CultureInfo.InvariantCulture)); Writer.Write("] = "); - if (mappings[i].TypeDesc.IsOptionalValue && mappings[i].TypeDesc.BaseTypeDesc.UseReflection) + if (mappings[i].TypeDesc!.IsOptionalValue && mappings[i].TypeDesc!.BaseTypeDesc!.UseReflection) { Writer.Write("null"); } else { - Writer.Write(RaCodeGen.GetStringForCreateInstance(mappings[i].TypeDesc.CSharpName, mappings[i].TypeDesc.UseReflection, false, false)); + Writer.Write(RaCodeGen.GetStringForCreateInstance(mappings[i].TypeDesc!.CSharpName, mappings[i].TypeDesc!.UseReflection, false, false)); } Writer.WriteLine(";"); } @@ -2640,8 +2652,8 @@ private void InitializeValueTypes(string arrayName, MemberMapping[] mappings) private string GenerateEncodedMembersElement(XmlMembersMapping xmlMembersMapping) { ElementAccessor element = xmlMembersMapping.Accessor; - MembersMapping membersMapping = (MembersMapping)element.Mapping; - MemberMapping[] mappings = membersMapping.Members; + MembersMapping membersMapping = (MembersMapping)element.Mapping!; + MemberMapping[] mappings = membersMapping.Members!; bool hasWrapperElement = membersMapping.HasWrapperElement; bool writeAccessors = membersMapping.WriteAccessors; string methodName = NextMethodName(element.Name); @@ -2680,7 +2692,7 @@ private string GenerateEncodedMembersElement(XmlMembersMapping xmlMembersMapping string arraySource = source; if (mapping.Xmlns != null) { - arraySource = "((" + mapping.TypeDesc.CSharpName + ")" + source + ")"; + arraySource = "((" + mapping.TypeDesc!.CSharpName + ")" + source + ")"; } Member member = new Member(this, source, arraySource, "a", i, mapping); if (!mapping.IsSequence) @@ -2706,7 +2718,7 @@ private string GenerateEncodedMembersElement(XmlMembersMapping xmlMembersMapping if (members.Length > 0 && members[0].Mapping.IsReturnValue) Writer.WriteLine("IsReturnValue = true;"); - string checkTypeHrefSource = (!hasWrapperElement && !writeAccessors) ? "hrefList" : null; + string? checkTypeHrefSource = (!hasWrapperElement && !writeAccessors) ? "hrefList" : null; if (checkTypeHrefSource != null) WriteInitCheckTypeHrefList(checkTypeHrefSource); @@ -2746,7 +2758,7 @@ private void WriteCreateCollection(TypeDesc td, string source) //cannot call WriteArrayLocalDecl since 'ci' is always //array and 'td' corresponds to 'c' if (arrayElementUseReflection) - item = typeof(Array).FullName; + item = typeof(Array).FullName!; Writer.Write(item); Writer.Write(" "); Writer.Write("ci ="); @@ -2763,7 +2775,7 @@ private void WriteCreateCollection(TypeDesc td, string source) if (!arrayElementUseReflection) Writer.Write("ci[i]"); else - Writer.Write(RaCodeGen.GetReflectionVariable(typeof(Array).FullName, "0") + "[ci , i]"); + Writer.Write(RaCodeGen.GetReflectionVariable(typeof(Array).FullName!, "0") + "[ci , i]"); if (useReflection) Writer.WriteLine("}"); @@ -2775,7 +2787,7 @@ private void WriteCreateCollection(TypeDesc td, string source) private string GenerateTypeElement(XmlTypeMapping xmlTypeMapping) { ElementAccessor element = xmlTypeMapping.Accessor; - TypeMapping mapping = element.Mapping; + TypeMapping mapping = element.Mapping!; string methodName = NextMethodName(element.Name); Writer.WriteLine(); Writer.Write("public object "); @@ -2816,13 +2828,13 @@ private void WritePrimitive(TypeMapping mapping, string source) { if (mapping is EnumMapping) { - string enumMethodName = ReferenceMapping(mapping); - if (enumMethodName == null) throw new InvalidOperationException(SR.Format(SR.XmlMissingMethodEnum, mapping.TypeDesc.Name)); + string? enumMethodName = ReferenceMapping(mapping); + if (enumMethodName == null) throw new InvalidOperationException(SR.Format(SR.XmlMissingMethodEnum, mapping.TypeDesc!.Name)); if (mapping.IsSoap) { // SOAP methods are not strongly-typed (the return object), so we need to add a cast Writer.Write("("); - Writer.Write(mapping.TypeDesc.CSharpName); + Writer.Write(mapping.TypeDesc!.CSharpName); Writer.Write(")"); } Writer.Write(enumMethodName); @@ -2834,7 +2846,7 @@ private void WritePrimitive(TypeMapping mapping, string source) { Writer.Write(source); } - else if (mapping.TypeDesc.FormatterName == "String") + else if (mapping.TypeDesc!.FormatterName == "String") { if (mapping.TypeDesc.CollapseWhitespace) { @@ -2862,10 +2874,10 @@ private void WritePrimitive(TypeMapping mapping, string source) } } - private string MakeUnique(EnumMapping mapping, string name) + private string? MakeUnique(EnumMapping mapping, string name) { string uniqueName = name; - object m = Enums[uniqueName]; + object? m = Enums[uniqueName]; if (m != null) { if (m == mapping) @@ -2888,9 +2900,9 @@ private string MakeUnique(EnumMapping mapping, string name) private string WriteHashtable(EnumMapping mapping, string typeName) { CodeIdentifier.CheckValidIdentifier(typeName); - string propName = MakeUnique(mapping, typeName + "Values"); + string? propName = MakeUnique(mapping, typeName + "Values"); if (propName == null) return CodeIdentifier.GetCSharpName(typeName); - string memberName = MakeUnique(mapping, "_" + propName); + string? memberName = MakeUnique(mapping, "_" + propName); propName = CodeIdentifier.GetCSharpName(propName); Writer.WriteLine(); @@ -2920,13 +2932,13 @@ private string WriteHashtable(EnumMapping mapping, string typeName) Writer.Write(typeof(Hashtable).FullName); Writer.WriteLine("();"); - ConstantMapping[] constants = mapping.Constants; + ConstantMapping[] constants = mapping.Constants!; for (int i = 0; i < constants.Length; i++) { Writer.Write("h.Add("); WriteQuotedCSharpString(constants[i].XmlName); - if (!mapping.TypeDesc.UseReflection) + if (!mapping.TypeDesc!.UseReflection) { Writer.Write(", (long)"); Writer.Write(mapping.TypeDesc.CSharpName); @@ -2964,13 +2976,13 @@ private string WriteHashtable(EnumMapping mapping, string typeName) private void WriteEnumMethod(EnumMapping mapping) { - string tableName = null; + string? tableName = null; if (mapping.IsFlags) - tableName = WriteHashtable(mapping, mapping.TypeDesc.Name); + tableName = WriteHashtable(mapping, mapping.TypeDesc!.Name); - string methodName = (string)MethodNames[mapping]; + string methodName = (string)MethodNames[mapping]!; Writer.WriteLine(); - bool useReflection = mapping.TypeDesc.UseReflection; + bool useReflection = mapping.TypeDesc!.UseReflection; string fullTypeName = mapping.TypeDesc.CSharpName; if (mapping.IsSoap) @@ -2991,7 +3003,7 @@ private void WriteEnumMethod(EnumMapping mapping) Writer.Indent++; } - ConstantMapping[] constants = mapping.Constants; + ConstantMapping[] constants = mapping.Constants!; if (mapping.IsFlags) { if (useReflection) @@ -3022,7 +3034,7 @@ private void WriteEnumMethod(EnumMapping mapping) Writer.WriteLine("switch (s) {"); Writer.Indent++; Hashtable cases = new Hashtable(); - for (int i = 0; i < constants.Length; i++) + for (int i = 0; i < constants!.Length; i++) { ConstantMapping c = constants[i]; @@ -3051,21 +3063,21 @@ private void WriteEnumMethod(EnumMapping mapping) private void WriteDerivedTypes(StructMapping mapping, bool isTypedReturn, string returnTypeName) { - for (StructMapping derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) + for (StructMapping? derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) { Writer.Write("if ("); WriteQNameEqual("xsiType", derived.TypeName, derived.Namespace); Writer.WriteLine(")"); Writer.Indent++; - string methodName = ReferenceMapping(derived); + string? methodName = ReferenceMapping(derived); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe - if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, derived.TypeDesc.Name)); + if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, derived.TypeDesc!.Name)); #endif Writer.Write("return "); - if (derived.TypeDesc.UseReflection && isTypedReturn) + if (derived.TypeDesc!.UseReflection && isTypedReturn) Writer.Write("(" + returnTypeName + ")"); Writer.Write(methodName); Writer.Write("("); @@ -3095,10 +3107,10 @@ private void WriteEnumAndArrayTypes() Writer.WriteLine(") {"); Writer.Indent++; Writer.WriteLine("Reader.ReadStartElement();"); - string methodName = ReferenceMapping(mapping); + string? methodName = ReferenceMapping(mapping); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe - if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc.Name)); + if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc!.Name)); #endif Writer.Write("object e = "); Writer.Write(methodName); @@ -3111,7 +3123,7 @@ private void WriteEnumAndArrayTypes() else if (m is ArrayMapping) { ArrayMapping mapping = (ArrayMapping)m; - if (mapping.TypeDesc.HasDefaultConstructor) + if (mapping.TypeDesc!.HasDefaultConstructor) { Writer.Write("if ("); WriteQNameEqual("xsiType", mapping.TypeName, mapping.Namespace); @@ -3154,9 +3166,9 @@ private void WriteEnumAndArrayTypes() private void WriteNullableMethod(NullableMapping nullableMapping) { - string methodName = (string)MethodNames[nullableMapping]; - bool useReflection = nullableMapping.BaseMapping.TypeDesc.UseReflection; - string typeName = useReflection ? "object" : nullableMapping.TypeDesc.CSharpName; + string methodName = (string)MethodNames[nullableMapping]!; + bool useReflection = nullableMapping.BaseMapping!.TypeDesc!.UseReflection; + string typeName = useReflection ? "object" : nullableMapping.TypeDesc!.CSharpName; Writer.WriteLine(); Writer.Write(typeName); @@ -3208,8 +3220,8 @@ private void WriteStructMethod(StructMapping structMapping) private void WriteLiteralStructMethod(StructMapping structMapping) { - string methodName = (string)MethodNames[structMapping]; - bool useReflection = structMapping.TypeDesc.UseReflection; + string methodName = (string)MethodNames[structMapping]!; + bool useReflection = structMapping.TypeDesc!.UseReflection; string typeName = useReflection ? "object" : structMapping.TypeDesc.CSharpName; Writer.WriteLine(); Writer.Write(typeName); @@ -3296,9 +3308,9 @@ private void WriteLiteralStructMethod(StructMapping structMapping) MemberMapping[] mappings = TypeScope.GetSettableMembers(structMapping); - Member anyText = null; - Member anyElement = null; - Member anyAttribute = null; + Member? anyText = null; + Member? anyElement = null; + Member? anyAttribute = null; bool isSequence = structMapping.HasExplicitSequence(); ArrayList arraysToDeclareList = new ArrayList(mappings.Length); @@ -3313,7 +3325,7 @@ private void WriteLiteralStructMethod(StructMapping structMapping) Member member = new Member(this, source, "a", i, mapping, GetChoiceIdentifierSource(mapping, "o", structMapping.TypeDesc)); if (!mapping.IsSequence) member.ParamsReadSource = "paramsRead[" + i.ToString(CultureInfo.InvariantCulture) + "]"; - member.IsNullable = mapping.TypeDesc.IsNullable; + member.IsNullable = mapping.TypeDesc!.IsNullable; if (mapping.CheckSpecified == SpecifiedAccessor.ReadWrite) member.CheckSpecifiedSource = RaCodeGen.GetStringForMember("o", mapping.Name + "Specified", structMapping.TypeDesc); if (mapping.Text != null) @@ -3323,7 +3335,7 @@ private void WriteLiteralStructMethod(StructMapping structMapping) if (!isSequence) { // find anyElement if present. - for (int j = 0; j < mapping.Elements.Length; j++) + for (int j = 0; j < mapping.Elements!.Length; j++) { if (mapping.Elements[j].Any && (mapping.Elements[j].Name == null || mapping.Elements[j].Name.Length == 0)) { @@ -3334,11 +3346,11 @@ private void WriteLiteralStructMethod(StructMapping structMapping) } else if (mapping.IsParticle && !mapping.IsSequence) { - StructMapping declaringMapping; + StructMapping? declaringMapping; structMapping.FindDeclaringMapping(mapping, out declaringMapping, structMapping.TypeName); - throw new InvalidOperationException(SR.Format(SR.XmlSequenceHierarchy, structMapping.TypeDesc.FullName, mapping.Name, declaringMapping.TypeDesc.FullName, "Order")); + throw new InvalidOperationException(SR.Format(SR.XmlSequenceHierarchy, structMapping.TypeDesc.FullName, mapping.Name, declaringMapping!.TypeDesc!.FullName, "Order")); } - if (mapping.Attribute == null && mapping.Elements.Length == 1 && mapping.Elements[0].Mapping is ArrayMapping) + if (mapping.Attribute == null && mapping.Elements!.Length == 1 && mapping.Elements[0].Mapping is ArrayMapping) { Member arrayMember = new Member(this, source, source, "a", i, mapping, GetChoiceIdentifierSource(mapping, "o", structMapping.TypeDesc)); arrayMember.CheckSpecifiedSource = member.CheckSpecifiedSource; @@ -3352,7 +3364,7 @@ private void WriteLiteralStructMethod(StructMapping structMapping) if (mapping.TypeDesc.IsArrayLike) { arraysToDeclareList.Add(member); - if (mapping.TypeDesc.IsArrayLike && !(mapping.Elements.Length == 1 && mapping.Elements[0].Mapping is ArrayMapping)) + if (mapping.TypeDesc.IsArrayLike && !(mapping.Elements!.Length == 1 && mapping.Elements[0].Mapping is ArrayMapping)) { member.ParamsReadSource = null; // flat arrays -- don't want to count params read. if (member != anyText && member != anyElement) @@ -3413,10 +3425,10 @@ private void WriteLiteralStructMethod(StructMapping structMapping) private void WriteEncodedStructMethod(StructMapping structMapping) { - if (structMapping.TypeDesc.IsRoot) + if (structMapping.TypeDesc!.IsRoot) return; bool useReflection = structMapping.TypeDesc.UseReflection; - string methodName = (string)MethodNames[structMapping]; + string methodName = (string)MethodNames[structMapping]!; Writer.WriteLine(); Writer.Write("object"); Writer.Write(" "); @@ -3427,7 +3439,7 @@ private void WriteEncodedStructMethod(StructMapping structMapping) Member[] members; bool anyFixups; - string fixupMethodName; + string? fixupMethodName; if (structMapping.TypeDesc.IsAbstract) { @@ -3488,7 +3500,7 @@ private void WriteEncodedStructMethod(StructMapping structMapping) if (anyFixups) WriteFixupMethod(fixupMethodName, members, structMapping.TypeDesc.CSharpName, structMapping.TypeDesc.UseReflection, true, "o"); } - private void WriteFixupMethod(string fixupMethodName, Member[] members, string typeName, bool useReflection, bool typed, string source) + private void WriteFixupMethod(string? fixupMethodName, Member[] members, string typeName, bool useReflection, bool typed, string source) { Writer.WriteLine(); Writer.Write("void "); @@ -3513,7 +3525,7 @@ private void WriteFixupMethod(string fixupMethodName, Member[] members, string t string memberSource = /*member.IsList ? source + ".Add(" :*/ member.ArraySource; string targetSource = "GetTarget(ids[" + fixupIndex + "])"; - TypeDesc td = member.Mapping.TypeDesc; + TypeDesc td = member.Mapping.TypeDesc!; if (td.IsCollection || td.IsEnumerable) { WriteAddCollectionFixup(td, member.Mapping.ReadOnly, memberSource, targetSource); @@ -3541,7 +3553,7 @@ private void WriteFixupMethod(string fixupMethodName, Member[] members, string t if (typed) { - WriteCatchCastException(member.Mapping.TypeDesc, targetSource, "ids[" + fixupIndex + "]"); + WriteCatchCastException(member.Mapping.TypeDesc!, targetSource, "ids[" + fixupIndex + "]"); } } Writer.Indent--; @@ -3556,7 +3568,7 @@ private void WriteAddCollectionFixup(TypeDesc typeDesc, bool readOnly, string me { Writer.WriteLine("// get array of the collection items"); bool useReflection = typeDesc.UseReflection; - CreateCollectionInfo create = (CreateCollectionInfo)_createMethods[typeDesc]; + CreateCollectionInfo? create = (CreateCollectionInfo?)_createMethods[typeDesc]; if (create == null) { string createName = "create" + (++_nextCreateMethodNumber).ToString(CultureInfo.InvariantCulture) + "_" + typeDesc.Name; @@ -3620,7 +3632,7 @@ private void WriteCreateCollectionMethod(CreateCollectionInfo c) Writer.WriteLine("}"); } - private void WriteQNameEqual(string source, string name, string ns) + private void WriteQNameEqual(string? source, string? name, string? ns) { Writer.Write("((object) (("); Writer.Write(typeof(XmlQualifiedName).FullName); @@ -3637,7 +3649,7 @@ private void WriteQNameEqual(string source, string name, string ns) Writer.Write(")"); } - private void WriteXmlNodeEqual(string source, string name, string ns) + private void WriteXmlNodeEqual(string? source, string? name, string? ns) { Writer.Write("("); if (name != null && name.Length > 0) @@ -3655,7 +3667,7 @@ private void WriteXmlNodeEqual(string source, string name, string ns) Writer.Write(")"); } - private void WriteID(string name) + private void WriteID(string? name) { if (name == null) { @@ -3663,7 +3675,7 @@ private void WriteID(string name) //return; name = ""; } - string idName = (string)_idNames[name]; + string? idName = (string?)_idNames[name]; if (idName == null) { idName = NextIdName(name); @@ -3672,10 +3684,10 @@ private void WriteID(string name) Writer.Write(idName); } - private void WriteAttributes(Member[] members, Member anyAttribute, string elseCall, string firstParam) + private void WriteAttributes(Member[] members, Member? anyAttribute, string elseCall, string firstParam) { int count = 0; - Member xmlnsMember = null; + Member? xmlnsMember = null; ArrayList attributes = new ArrayList(); Writer.WriteLine("while (Reader.MoveToNextAttribute()) {"); @@ -3691,7 +3703,7 @@ private void WriteAttributes(Member[] members, Member anyAttribute, string elseC } if (member.Mapping.Ignore) continue; - AttributeAccessor attribute = member.Mapping.Attribute; + AttributeAccessor? attribute = member.Mapping.Attribute; if (attribute == null) continue; if (attribute.Any) continue; @@ -3736,7 +3748,7 @@ private void WriteAttributes(Member[] members, Member anyAttribute, string elseC Writer.Write(" == null) "); Writer.Write(xmlnsMember.Source); Writer.Write(" = new "); - Writer.Write(xmlnsMember.Mapping.TypeDesc.CSharpName); + Writer.Write(xmlnsMember.Mapping.TypeDesc!.CSharpName); Writer.WriteLine("();"); //Writer.Write(xmlnsMember.ArraySource); @@ -3776,7 +3788,7 @@ private void WriteAttributes(Member[] members, Member anyAttribute, string elseC for (int i = 0; i < attributes.Count; i++) { - AttributeAccessor attribute = (AttributeAccessor)attributes[i]; + AttributeAccessor attribute = (AttributeAccessor)attributes[i]!; if (i > 0) qnames += ", "; qnames += attribute.IsSpecialXmlNamespace ? XmlReservedNs.NsXml : (attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : "") + ":" + attribute.Name; @@ -3794,13 +3806,13 @@ private void WriteAttributes(Member[] members, Member anyAttribute, string elseC private void WriteAttribute(Member member) { - AttributeAccessor attribute = member.Mapping.Attribute; + AttributeAccessor attribute = member.Mapping.Attribute!; if (attribute.Mapping is SpecialMapping) { SpecialMapping special = (SpecialMapping)attribute.Mapping; - if (special.TypeDesc.Kind == TypeKind.Attribute) + if (special.TypeDesc!.Kind == TypeKind.Attribute) { WriteSourceBegin(member.ArraySource); Writer.Write("attr"); @@ -3834,10 +3846,10 @@ private void WriteAttribute(Member member) Writer.WriteLine("for (int i = 0; i < vals.Length; i++) {"); Writer.Indent++; - string attributeSource = GetArraySource(member.Mapping.TypeDesc, member.ArrayName); + string attributeSource = GetArraySource(member.Mapping.TypeDesc!, member.ArrayName); WriteSourceBegin(attributeSource); - WritePrimitive(attribute.Mapping, "vals[i]"); + WritePrimitive(attribute.Mapping!, "vals[i]"); WriteSourceEnd(attributeSource); Writer.WriteLine(";"); Writer.Indent--; @@ -3846,7 +3858,7 @@ private void WriteAttribute(Member member) else { WriteSourceBegin(member.ArraySource); - WritePrimitive(attribute.Mapping, attribute.IsList ? "vals[i]" : "Reader.Value"); + WritePrimitive(attribute.Mapping!, attribute.IsList ? "vals[i]" : "Reader.Value"); WriteSourceEnd(member.ArraySource); Writer.WriteLine(";"); } @@ -3869,10 +3881,10 @@ private bool WriteMemberFixupBegin(Member[] members, string fixupMethodName, str for (int i = 0; i < members.Length; i++) { Member member = (Member)members[i]; - if (member.Mapping.Elements.Length == 0) + if (member.Mapping.Elements!.Length == 0) continue; - TypeMapping mapping = member.Mapping.Elements[0].Mapping; + TypeMapping? mapping = member.Mapping.Elements[0].Mapping; if (mapping is StructMapping || mapping is ArrayMapping || mapping is PrimitiveMapping || mapping is NullableMapping) { member.MultiRef = true; @@ -3909,10 +3921,10 @@ private void WriteMemberBegin(Member[] members) string a = member.ArrayName; string c = "c" + a; - TypeDesc typeDesc = member.Mapping.TypeDesc; + TypeDesc typeDesc = member.Mapping.TypeDesc!; string typeDescFullName = typeDesc.CSharpName; - if (member.Mapping.TypeDesc.IsArray) + if (member.Mapping.TypeDesc!.IsArray) { WriteArrayLocalDecl(typeDesc.CSharpName, a, "null", typeDesc); @@ -3922,7 +3934,7 @@ private void WriteMemberBegin(Member[] members) if (member.Mapping.ChoiceIdentifier != null) { - WriteArrayLocalDecl(member.Mapping.ChoiceIdentifier.Mapping.TypeDesc.CSharpName + "[]", + WriteArrayLocalDecl(member.Mapping.ChoiceIdentifier.Mapping!.TypeDesc!.CSharpName + "[]", member.ChoiceArrayName, "null", member.Mapping.ChoiceIdentifier.Mapping.TypeDesc); Writer.Write("int c"); @@ -3988,12 +4000,12 @@ private string ExpectedElements(Member[] members) if (member.Mapping.IsText || member.Mapping.IsAttribute) continue; - ElementAccessor[] elements = member.Mapping.Elements; + ElementAccessor[] elements = member.Mapping.Elements!; for (int j = 0; j < elements.Length; j++) { ElementAccessor e = elements[j]; - string ns = e.Form == XmlSchemaForm.Qualified ? e.Namespace : ""; + string? ns = e.Form == XmlSchemaForm.Qualified ? e.Namespace : ""; if (e.Any && (e.Name == null || e.Name.Length == 0)) continue; if (!firstElement) @@ -4007,7 +4019,7 @@ private string ExpectedElements(Member[] members) return writer.ToString(); } - private void WriteMemberElements(Member[] members, string elementElseString, string elseString, Member anyElement, Member anyText, string checkTypeHrefsSource) + private void WriteMemberElements(Member[] members, string elementElseString, string elseString, Member? anyElement, Member? anyText, string? checkTypeHrefsSource) { bool checkType = (checkTypeHrefsSource != null && checkTypeHrefsSource.Length > 0); @@ -4075,13 +4087,13 @@ private void WriteMemberText(Member anyText, string elseString) private void WriteText(Member member) { - TextAccessor text = member.Mapping.Text; + TextAccessor text = member.Mapping.Text!; if (text.Mapping is SpecialMapping) { SpecialMapping special = (SpecialMapping)text.Mapping; WriteSourceBeginTyped(member.ArraySource, special.TypeDesc); - switch (special.TypeDesc.Kind) + switch (special.TypeDesc!.Kind) { case TypeKind.Node: Writer.Write("Document.CreateTextNode(Reader.ReadString())"); @@ -4096,7 +4108,7 @@ private void WriteText(Member member) if (member.IsArrayLike) { WriteSourceBegin(member.ArraySource); - if (text.Mapping.TypeDesc.CollapseWhitespace) + if (text.Mapping!.TypeDesc!.CollapseWhitespace) { Writer.Write("CollapseWhitespace(Reader.ReadString())"); } @@ -4107,10 +4119,10 @@ private void WriteText(Member member) } else { - if (text.Mapping.TypeDesc == StringTypeDesc || text.Mapping.TypeDesc.FormatterName == "String") + if (text.Mapping!.TypeDesc == StringTypeDesc || text.Mapping.TypeDesc!.FormatterName == "String") { Writer.Write("tmp = ReadString(tmp, "); - if (text.Mapping.TypeDesc.CollapseWhitespace) + if (text.Mapping.TypeDesc!.CollapseWhitespace) Writer.WriteLine("true);"); else Writer.WriteLine("false);"); @@ -4130,7 +4142,7 @@ private void WriteText(Member member) Writer.WriteLine(";"); } - private void WriteMemberElementsCheckType(string checkTypeHrefsSource) + private void WriteMemberElementsCheckType(string? checkTypeHrefsSource) { Writer.WriteLine("string refElemId = null;"); Writer.WriteLine("object refElem = ReadReferencingElement(null, null, true, out refElemId);"); @@ -4153,11 +4165,11 @@ private void WriteMemberElementsCheckType(string checkTypeHrefsSource) Writer.WriteLine("}"); } - private void WriteMemberElementsElse(Member anyElement, string elementElseString) + private void WriteMemberElementsElse(Member? anyElement, string elementElseString) { if (anyElement != null) { - ElementAccessor[] elements = anyElement.Mapping.Elements; + ElementAccessor[] elements = anyElement.Mapping.Elements!; for (int i = 0; i < elements.Length; i++) { ElementAccessor element = elements[i]; @@ -4183,7 +4195,7 @@ private bool IsSequence(Member[] members) } return false; } - private void WriteMemberElementsIf(Member[] members, Member anyElement, string elementElseString, string checkTypeSource) + private void WriteMemberElementsIf(Member[] members, Member? anyElement, string elementElseString, string? checkTypeSource) { bool checkType = checkTypeSource != null && checkTypeSource.Length > 0; //int count = checkType ? 1 : 0; @@ -4207,13 +4219,13 @@ private void WriteMemberElementsIf(Member[] members, Member anyElement, string e continue; bool firstElement = true; - ChoiceIdentifierAccessor choice = member.Mapping.ChoiceIdentifier; - ElementAccessor[] elements = member.Mapping.Elements; + ChoiceIdentifierAccessor? choice = member.Mapping.ChoiceIdentifier; + ElementAccessor[] elements = member.Mapping.Elements!; for (int j = 0; j < elements.Length; j++) { ElementAccessor e = elements[j]; - string ns = e.Form == XmlSchemaForm.Qualified ? e.Namespace : ""; + string? ns = e.Form == XmlSchemaForm.Qualified ? e.Namespace : ""; if (!isSequence && e.Any && (e.Name == null || e.Name.Length == 0)) continue; if (!isSequence) { @@ -4250,12 +4262,12 @@ private void WriteMemberElementsIf(Member[] members, Member anyElement, string e { if (e.Mapping is NullableMapping) { - TypeDesc td = ((NullableMapping)e.Mapping).BaseMapping.TypeDesc; + TypeDesc td = ((NullableMapping)e.Mapping).BaseMapping!.TypeDesc!; Writer.Write(RaCodeGen.GetStringForTypeof(td.CSharpName, td.UseReflection)); } else { - Writer.Write(RaCodeGen.GetStringForTypeof(e.Mapping.TypeDesc.CSharpName, e.Mapping.TypeDesc.UseReflection)); + Writer.Write(RaCodeGen.GetStringForTypeof(e.Mapping!.TypeDesc!.CSharpName, e.Mapping.TypeDesc.UseReflection)); } Writer.Write(".IsAssignableFrom("); Writer.Write(checkTypeSource); @@ -4280,7 +4292,7 @@ private void WriteMemberElementsIf(Member[] members, Member anyElement, string e Writer.Indent++; if (checkType) { - if (e.Mapping.TypeDesc.IsValueType || e.Mapping is NullableMapping) + if (e.Mapping!.TypeDesc!.IsValueType || e.Mapping is NullableMapping) { Writer.Write("if ("); Writer.Write(checkTypeSource); @@ -4290,7 +4302,7 @@ private void WriteMemberElementsIf(Member[] members, Member anyElement, string e if (e.Mapping is NullableMapping) { WriteSourceBegin(member.ArraySource); - TypeDesc td = ((NullableMapping)e.Mapping).BaseMapping.TypeDesc; + TypeDesc td = ((NullableMapping)e.Mapping).BaseMapping!.TypeDesc!; Writer.Write(RaCodeGen.GetStringForCreateInstance(e.Mapping.TypeDesc.CSharpName, e.Mapping.TypeDesc.UseReflection, false, true, "(" + td.CSharpName + ")" + checkTypeSource)); } else @@ -4316,7 +4328,7 @@ private void WriteMemberElementsIf(Member[] members, Member anyElement, string e } else { - WriteElement(member.ArraySource, member.ArrayName, member.ChoiceArraySource, e, choice, member.Mapping.CheckSpecified == SpecifiedAccessor.ReadWrite ? member.CheckSpecifiedSource : null, member.IsList && member.Mapping.TypeDesc.IsNullable, member.Mapping.ReadOnly, member.FixupIndex, j); + WriteElement(member.ArraySource, member.ArrayName, member.ChoiceArraySource, e, choice, member.Mapping.CheckSpecified == SpecifiedAccessor.ReadWrite ? member.CheckSpecifiedSource : null, member.IsList && member.Mapping.TypeDesc!.IsNullable, member.Mapping.ReadOnly, member.FixupIndex, j); } if (member.Mapping.IsReturnValue) Writer.WriteLine("IsReturnValue = false;"); @@ -4396,7 +4408,7 @@ private string GetArraySource(TypeDesc typeDesc, string arrayName, bool multiRef bool useReflection = typeDesc.UseReflection; if (typeDesc.IsArray) { - string arrayTypeFullName = typeDesc.ArrayElementTypeDesc.CSharpName; + string arrayTypeFullName = typeDesc.ArrayElementTypeDesc!.CSharpName; bool arrayUseReflection = typeDesc.ArrayElementTypeDesc.UseReflection; string castString = useReflection ? "" : "(" + arrayTypeFullName + "[])"; init = init + a + " = " + castString + @@ -4429,7 +4441,7 @@ private void WriteMemberEnd(Member[] members, bool soapRefs) if (member.IsArrayLike) { - TypeDesc typeDesc = member.Mapping.TypeDesc; + TypeDesc typeDesc = member.Mapping.TypeDesc!; if (typeDesc.IsArray) { @@ -4441,7 +4453,7 @@ private void WriteMemberEnd(Member[] members, bool soapRefs) string a = member.ArrayName; string c = "c" + a; - bool arrayUseReflection = typeDesc.ArrayElementTypeDesc.UseReflection; + bool arrayUseReflection = typeDesc.ArrayElementTypeDesc!.UseReflection; string arrayTypeFullName = typeDesc.ArrayElementTypeDesc.CSharpName; if (!arrayUseReflection) Writer.Write("(" + arrayTypeFullName + "[])"); @@ -4459,11 +4471,11 @@ private void WriteMemberEnd(Member[] members, bool soapRefs) if (member.Mapping.ChoiceIdentifier != null) { - WriteSourceBegin(member.ChoiceSource); + WriteSourceBegin(member.ChoiceSource!); a = member.ChoiceArrayName; c = "c" + a; - bool choiceUseReflection = member.Mapping.ChoiceIdentifier.Mapping.TypeDesc.UseReflection; + bool choiceUseReflection = member.Mapping.ChoiceIdentifier.Mapping!.TypeDesc!.UseReflection; string choiceTypeName = member.Mapping.ChoiceIdentifier.Mapping.TypeDesc.CSharpName; if (!choiceUseReflection) Writer.Write("(" + choiceTypeName + "[])"); @@ -4476,7 +4488,7 @@ private void WriteMemberEnd(Member[] members, bool soapRefs) Writer.Write(", "); WriteBooleanValue(member.IsNullable); Writer.Write(")"); - WriteSourceEnd(member.ChoiceSource); + WriteSourceEnd(member.ChoiceSource!); Writer.WriteLine(";"); } } @@ -4491,7 +4503,7 @@ private void WriteMemberEnd(Member[] members, bool soapRefs) } } - private void WriteSourceBeginTyped(string source, TypeDesc typeDesc) + private void WriteSourceBeginTyped(string source, TypeDesc? typeDesc) { WriteSourceBegin(source); if (typeDesc != null && !typeDesc.UseReflection) @@ -4519,7 +4531,7 @@ private void WriteSourceEnd(string source) Writer.Write("})"); } - private void WriteArray(string source, string arrayName, ArrayMapping arrayMapping, bool readOnly, bool isNullable, int fixupIndex) + private void WriteArray(string source, string? arrayName, ArrayMapping arrayMapping, bool readOnly, bool isNullable, int fixupIndex) { if (arrayMapping.IsSoap) { @@ -4538,7 +4550,7 @@ private void WriteArray(string source, string arrayName, ArrayMapping arrayMappi } Writer.WriteLine(");"); - TypeDesc td = arrayMapping.TypeDesc; + TypeDesc td = arrayMapping.TypeDesc!; if (td.IsEnumerable || td.IsCollection) { Writer.WriteLine("if (rre != null) {"); @@ -4555,7 +4567,7 @@ private void WriteArray(string source, string arrayName, ArrayMapping arrayMappi Writer.Write("rre"); WriteSourceEnd(source); Writer.WriteLine(";"); - WriteCatchCastException(arrayMapping.TypeDesc, "rre", null); + WriteCatchCastException(arrayMapping.TypeDesc!, "rre", null); } } else @@ -4621,7 +4633,7 @@ private void WriteArray(string source, string arrayName, ArrayMapping arrayMappi } } - private void WriteElement(string source, string arrayName, string choiceSource, ElementAccessor element, ChoiceIdentifierAccessor choice, string checkSpecified, bool checkForNull, bool readOnly, int fixupIndex, int elementIndex) + private void WriteElement(string source, string? arrayName, string? choiceSource, ElementAccessor element, ChoiceIdentifierAccessor? choice, string? checkSpecified, bool checkForNull, bool readOnly, int fixupIndex, int elementIndex) { if (checkSpecified != null && checkSpecified.Length > 0) { @@ -4635,10 +4647,10 @@ private void WriteElement(string source, string arrayName, string choiceSource, } else if (element.Mapping is NullableMapping) { - string methodName = ReferenceMapping(element.Mapping); + string? methodName = ReferenceMapping(element.Mapping); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe - if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, element.Mapping.TypeDesc.Name)); + if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, element.Mapping.TypeDesc!.Name)); #endif WriteSourceBegin(source); Writer.Write(methodName); @@ -4646,14 +4658,14 @@ private void WriteElement(string source, string arrayName, string choiceSource, WriteSourceEnd(source); Writer.WriteLine(";"); } - else if (!element.Mapping.IsSoap && (element.Mapping is PrimitiveMapping)) + else if (!element.Mapping!.IsSoap && (element.Mapping is PrimitiveMapping)) { if (element.IsNullable) { Writer.WriteLine("if (ReadNull()) {"); Writer.Indent++; WriteSourceBegin(source); - if (element.Mapping.TypeDesc.IsValueType) + if (element.Mapping.TypeDesc!.IsValueType) { Writer.Write(RaCodeGen.GetStringForCreateInstance(element.Mapping.TypeDesc.CSharpName, element.Mapping.TypeDesc.UseReflection, false, false)); } @@ -4667,7 +4679,7 @@ private void WriteElement(string source, string arrayName, string choiceSource, Writer.WriteLine("}"); Writer.Write("else "); } - if (element.Default != null && element.Default != DBNull.Value && element.Mapping.TypeDesc.IsValueType) + if (element.Default != null && element.Default != DBNull.Value && element.Mapping.TypeDesc!.IsValueType) { Writer.WriteLine("if (Reader.IsEmptyElement) {"); Writer.Indent++; @@ -4682,7 +4694,7 @@ private void WriteElement(string source, string arrayName, string choiceSource, } Writer.Indent++; - if (element.Mapping.TypeDesc.Type == typeof(TimeSpan)) + if (element.Mapping.TypeDesc!.Type == typeof(TimeSpan)) { Writer.WriteLine("if (Reader.IsEmptyElement) {"); Writer.Indent++; @@ -4751,7 +4763,7 @@ private void WriteElement(string source, string arrayName, string choiceSource, WriteSourceEnd(source); Writer.WriteLine(";"); - if (mapping.TypeDesc.IsValueType) + if (mapping.TypeDesc!.IsValueType) { Writer.WriteLine("if (rre != null) {"); Writer.Indent++; @@ -4775,10 +4787,10 @@ private void WriteElement(string source, string arrayName, string choiceSource, } else { - string methodName = ReferenceMapping(mapping); + string? methodName = ReferenceMapping(mapping); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe - if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc.Name)); + if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc!.Name)); #endif if (checkForNull) @@ -4790,7 +4802,7 @@ private void WriteElement(string source, string arrayName, string choiceSource, WriteSourceBegin(source); Writer.Write(methodName); Writer.Write("("); - if (mapping.TypeDesc.IsNullable) + if (mapping.TypeDesc!.IsNullable) { WriteBooleanValue(element.IsNullable); Writer.Write(", "); @@ -4804,7 +4816,7 @@ private void WriteElement(string source, string arrayName, string choiceSource, else if (element.Mapping is SpecialMapping) { SpecialMapping special = (SpecialMapping)element.Mapping; - switch (special.TypeDesc.Kind) + switch (special.TypeDesc!.Kind) { case TypeKind.Node: bool isDoc = special.TypeDesc.FullName == typeof(XmlDocument).FullName; @@ -4824,7 +4836,7 @@ private void WriteElement(string source, string arrayName, string choiceSource, Writer.WriteLine(" tser = GetXsiType();"); Writer.Write("if (tser == null"); Writer.Write(" || "); - WriteQNameEqual("tser", sm.XsiType.Name, sm.XsiType.Namespace); + WriteQNameEqual("tser", sm.XsiType!.Name, sm.XsiType.Namespace); Writer.WriteLine(") {"); Writer.Indent++; @@ -4833,7 +4845,7 @@ private void WriteElement(string source, string arrayName, string choiceSource, Writer.Write("ReadSerializable(( "); Writer.Write(typeof(IXmlSerializable).FullName); Writer.Write(")"); - Writer.Write(RaCodeGen.GetStringForCreateInstance(sm.TypeDesc.CSharpName, sm.TypeDesc.UseReflection, sm.TypeDesc.CannotNew, false)); + Writer.Write(RaCodeGen.GetStringForCreateInstance(sm.TypeDesc!.CSharpName, sm.TypeDesc.UseReflection, sm.TypeDesc.CannotNew, false)); bool isWrappedAny = !element.Any && IsWildcard(sm); if (isWrappedAny) { @@ -4865,10 +4877,10 @@ private void WriteElement(string source, string arrayName, string choiceSource, if (choiceSource == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, "need parent for the " + source)); #endif - string enumTypeName = choice.Mapping.TypeDesc.CSharpName; + string enumTypeName = choice.Mapping!.TypeDesc!.CSharpName; Writer.Write(choiceSource); Writer.Write(" = "); - CodeIdentifier.CheckValidIdentifier(choice.MemberIds[elementIndex]); + CodeIdentifier.CheckValidIdentifier(choice.MemberIds![elementIndex]); Writer.Write(RaCodeGen.GetStringForEnumMember(enumTypeName, choice.MemberIds[elementIndex], choice.Mapping.TypeDesc.UseReflection)); Writer.WriteLine(";"); } @@ -4878,24 +4890,24 @@ private void WriteDerivedSerializable(SerializableMapping head, SerializableMapp { if (mapping == null) return; - for (SerializableMapping derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) + for (SerializableMapping? derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) { Writer.Write("else if (tser == null"); Writer.Write(" || "); - WriteQNameEqual("tser", derived.XsiType.Name, derived.XsiType.Namespace); + WriteQNameEqual("tser", derived.XsiType!.Name, derived.XsiType.Namespace); Writer.WriteLine(") {"); Writer.Indent++; if (derived.Type != null) { - if (head.Type.IsAssignableFrom(derived.Type)) + if (head.Type!.IsAssignableFrom(derived.Type)) { WriteSourceBeginTyped(source, head.TypeDesc); Writer.Write("ReadSerializable(( "); Writer.Write(typeof(IXmlSerializable).FullName); Writer.Write(")"); - Writer.Write(RaCodeGen.GetStringForCreateInstance(derived.TypeDesc.CSharpName, derived.TypeDesc.UseReflection, derived.TypeDesc.CannotNew, false)); + Writer.Write(RaCodeGen.GetStringForCreateInstance(derived.TypeDesc!.CSharpName, derived.TypeDesc.UseReflection, derived.TypeDesc.CannotNew, false)); if (isWrappedAny) { Writer.WriteLine(", true"); @@ -4911,7 +4923,7 @@ private void WriteDerivedSerializable(SerializableMapping head, SerializableMapp Writer.Write(", "); WriteQuotedCSharpString(derived.XsiType.Namespace); Writer.Write(", "); - WriteQuotedCSharpString(head.XsiType.Name); + WriteQuotedCSharpString(head.XsiType!.Name); Writer.Write(", "); WriteQuotedCSharpString(head.XsiType.Namespace); Writer.Write(", "); @@ -4929,7 +4941,7 @@ private void WriteDerivedSerializable(SerializableMapping head, SerializableMapp Writer.Write(", "); WriteQuotedCSharpString(derived.XsiType.Namespace); Writer.Write(", "); - WriteQuotedCSharpString(head.Type.FullName); + WriteQuotedCSharpString(head.Type!.FullName); Writer.WriteLine(");"); } @@ -5040,7 +5052,7 @@ private void WriteIfNotSoapRoot(string source) private void WriteCreateMapping(TypeMapping mapping, string local) { - string fullTypeName = mapping.TypeDesc.CSharpName; + string fullTypeName = mapping.TypeDesc!.CSharpName; bool useReflection = mapping.TypeDesc.UseReflection; bool ctorInaccessible = mapping.TypeDesc.CannotNew; @@ -5087,7 +5099,7 @@ private void WriteCatchException(Type exceptionType) Writer.WriteLine(") {"); } - private void WriteCatchCastException(TypeDesc typeDesc, string source, string id) + private void WriteCatchCastException(TypeDesc typeDesc, string source, string? id) { WriteCatchException(typeof(InvalidCastException)); Writer.Indent++; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs index 549f2b7b7d72b2..872dcbfc47570d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs @@ -1,7 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. - +#nullable enable namespace System.Xml.Serialization { using System; @@ -22,7 +22,7 @@ internal class XmlSerializationReaderILGen : XmlSerializationILGen private readonly Dictionary _idNames = new Dictionary(); // Mapping name->id_XXXNN field private readonly Dictionary _idNameFields = new Dictionary(); - private Dictionary _enums; + private Dictionary? _enums; private int _nextIdNumber; internal Dictionary Enums @@ -43,44 +43,44 @@ private class Member private readonly string _arrayName; private readonly string _arraySource; private readonly string _choiceArrayName; - private readonly string _choiceSource; - private readonly string _choiceArraySource; + private readonly string? _choiceSource; + private readonly string? _choiceArraySource; private readonly MemberMapping _mapping; private readonly bool _isArray; private readonly bool _isList; private bool _isNullable; private int _fixupIndex = -1; - private string _paramsReadSource; - private string _checkSpecifiedSource; + private string? _paramsReadSource; + private string? _checkSpecifiedSource; - internal Member(XmlSerializationReaderILGen outerClass, string source, string arrayName, int i, MemberMapping mapping) + internal Member(XmlSerializationReaderILGen outerClass, string source, string? arrayName, int i, MemberMapping mapping) : this(outerClass, source, null, arrayName, i, mapping, false, null) { } - internal Member(XmlSerializationReaderILGen outerClass, string source, string arrayName, int i, MemberMapping mapping, string choiceSource) + internal Member(XmlSerializationReaderILGen outerClass, string source, string? arrayName, int i, MemberMapping mapping, string? choiceSource) : this(outerClass, source, null, arrayName, i, mapping, false, choiceSource) { } - internal Member(XmlSerializationReaderILGen outerClass, string source, string arraySource, string arrayName, int i, MemberMapping mapping) + internal Member(XmlSerializationReaderILGen outerClass, string source, string? arraySource, string? arrayName, int i, MemberMapping mapping) : this(outerClass, source, arraySource, arrayName, i, mapping, false, null) { } - internal Member(XmlSerializationReaderILGen outerClass, string source, string arraySource, string arrayName, int i, MemberMapping mapping, string choiceSource) + internal Member(XmlSerializationReaderILGen outerClass, string source, string? arraySource, string? arrayName, int i, MemberMapping mapping, string? choiceSource) : this(outerClass, source, arraySource, arrayName, i, mapping, false, choiceSource) { } - internal Member(XmlSerializationReaderILGen outerClass, string source, string arrayName, int i, MemberMapping mapping, bool multiRef) + internal Member(XmlSerializationReaderILGen outerClass, string source, string? arrayName, int i, MemberMapping mapping, bool multiRef) : this(outerClass, source, null, arrayName, i, mapping, multiRef, null) { } - internal Member(XmlSerializationReaderILGen outerClass, string source, string arraySource, string arrayName, int i, MemberMapping mapping, bool multiRef, string choiceSource) + internal Member(XmlSerializationReaderILGen outerClass, string source, string? arraySource, string? arrayName, int i, MemberMapping mapping, bool multiRef, string? choiceSource) { _source = source; _arrayName = arrayName + "_" + i.ToString(CultureInfo.InvariantCulture); _choiceArrayName = "choice_" + _arrayName; _choiceSource = choiceSource; - if (mapping.TypeDesc.IsArrayLike) + if (mapping.TypeDesc!.IsArrayLike) { if (arraySource != null) _arraySource = arraySource; @@ -94,7 +94,7 @@ internal Member(XmlSerializationReaderILGen outerClass, string source, string ar string a = _choiceArrayName; string c = "c" + a; - string choiceTypeFullName = mapping.ChoiceIdentifier.Mapping.TypeDesc.CSharpName; + string choiceTypeFullName = mapping.ChoiceIdentifier.Mapping!.TypeDesc!.CSharpName; string castString = "(" + choiceTypeFullName + "[])"; string init = a + " = " + castString + @@ -156,19 +156,19 @@ internal int FixupIndex set { _fixupIndex = value; } } - internal string ParamsReadSource + internal string? ParamsReadSource { get { return _paramsReadSource; } set { _paramsReadSource = value; } } - internal string CheckSpecifiedSource + internal string? CheckSpecifiedSource { get { return _checkSpecifiedSource; } set { _checkSpecifiedSource = value; } } - internal string ChoiceSource + internal string? ChoiceSource { get { return _choiceSource; } } @@ -176,7 +176,7 @@ internal string ChoiceArrayName { get { return _choiceArrayName; } } - internal string ChoiceArraySource + internal string? ChoiceArraySource { get { return _choiceArraySource; } } @@ -200,7 +200,7 @@ internal void GenerateBegin() foreach (TypeMapping mapping in scope.TypeMappings) { if (mapping is StructMapping || mapping is EnumMapping || mapping is NullableMapping) - MethodNames.Add(mapping, NextMethodName(mapping.TypeDesc.Name)); + MethodNames.Add(mapping, NextMethodName(mapping.TypeDesc!.Name)); } RaCodeGen.WriteReflectionInit(scope); } @@ -237,17 +237,17 @@ internal void GenerateEnd(string[] methods, XmlMapping[] xmlMappings, Type[] typ "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_get_NameTable = typeof(XmlReader).GetMethod( "get_NameTable", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlNameTable_Add = typeof(XmlNameTable).GetMethod( "Add", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } - ); + )!; foreach (string id in _idNames.Keys) { ilg.Ldarg(0); @@ -263,11 +263,11 @@ internal void GenerateEnd(string[] methods, XmlMapping[] xmlMappings, Type[] typ this.typeBuilder.DefineDefaultConstructor( CodeGenerator.PublicMethodAttributes); - Type readerType = this.typeBuilder.CreateTypeInfo().AsType(); + Type readerType = this.typeBuilder.CreateTypeInfo()!.AsType(); CreatedTypes.Add(readerType.Name, readerType); } - internal string GenerateElement(XmlMapping xmlMapping) + internal string? GenerateElement(XmlMapping xmlMapping) { if (!xmlMapping.IsReadable) return null; @@ -281,7 +281,7 @@ internal string GenerateElement(XmlMapping xmlMapping) throw new ArgumentException(SR.XmlInternalError, nameof(xmlMapping)); } - private void WriteIsStartTag(string name, string ns) + private void WriteIsStartTag(string? name, string? ns) { WriteID(name); WriteID(ns); @@ -289,12 +289,12 @@ private void WriteIsStartTag(string name, string ns) "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_IsStartElement = typeof(XmlReader).GetMethod( "IsStartElement", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Ldarg(0); @@ -305,7 +305,7 @@ private void WriteIsStartTag(string name, string ns) ilg.If(); } - private void WriteUnknownNode(string func, string node, ElementAccessor e, bool anyIfs) + private void WriteUnknownNode(string func, string node, ElementAccessor? e, bool anyIfs) { if (anyIfs) { @@ -325,7 +325,7 @@ private void WriteUnknownNode(string func, string node, ElementAccessor e, bool argTypes.Add(typeof(object)); if (e != null) { - string expectedElement = e.Form == XmlSchemaForm.Qualified ? e.Namespace : ""; + string? expectedElement = e.Form == XmlSchemaForm.Qualified ? e.Namespace : ""; expectedElement += ":"; expectedElement += e.Name; ilg.Ldstr(ReflectionAwareILGen.GetCSharpString(expectedElement)); @@ -335,7 +335,7 @@ private void WriteUnknownNode(string func, string node, ElementAccessor e, bool func, CodeGenerator.InstanceBindingFlags, argTypes.ToArray() - ); + )!; ilg.Call(method); if (anyIfs) { @@ -358,7 +358,7 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) private string GetChoiceIdentifierSource(MemberMapping[] mappings, MemberMapping member) { - string choiceSource = null; + string? choiceSource = null; if (member.ChoiceIdentifier != null) { for (int j = 0; j < mappings.Length; j++) @@ -375,7 +375,7 @@ private string GetChoiceIdentifierSource(MemberMapping[] mappings, MemberMapping #endif } - return choiceSource; + return choiceSource!; } private string GetChoiceIdentifierSource(MemberMapping mapping, string parent, TypeDesc parentTypeDesc) @@ -388,7 +388,7 @@ private string GetChoiceIdentifierSource(MemberMapping mapping, string parent, T private string GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping) { ElementAccessor element = xmlMembersMapping.Accessor; - MemberMapping[] mappings = ((MembersMapping)element.Mapping).Members; + MemberMapping[] mappings = ((MembersMapping)element.Mapping!).Members!; bool hasWrapperElement = ((MembersMapping)element.Mapping).HasWrapperElement; string methodName = NextMethodName(element.Name); ilg = new CodeGenerator(this.typeBuilder); @@ -405,12 +405,12 @@ private string GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_MoveToContent = typeof(XmlReader).GetMethod( "MoveToContent", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_MoveToContent); @@ -427,9 +427,9 @@ private string GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping WriteIsStartTag(element.Name, element.Form == XmlSchemaForm.Qualified ? element.Namespace : ""); } - Member anyText = null; - Member anyElement = null; - Member anyAttribute = null; + Member? anyText = null; + Member? anyElement = null; + Member? anyAttribute = null; var membersList = new List(); var textOrArrayMembersList = new List(); @@ -442,7 +442,7 @@ private string GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping string arraySource = source; if (mapping.Xmlns != null) { - arraySource = "((" + mapping.TypeDesc.CSharpName + ")" + source + ")"; + arraySource = "((" + mapping.TypeDesc!.CSharpName + ")" + source + ")"; } string choiceSource = GetChoiceIdentifierSource(mappings, mapping); Member member = new Member(this, source, arraySource, "a", i, mapping, choiceSource); @@ -472,7 +472,7 @@ private string GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping if (!mapping.IsSequence) { - for (int j = 0; j < mapping.Elements.Length; j++) + for (int j = 0; j < mapping.Elements!.Length; j++) { if (mapping.Elements[j].Any && mapping.Elements[j].Name.Length == 0) { @@ -486,7 +486,7 @@ private string GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping } if (mapping.Attribute != null || mapping.Text != null || foundAnyElement) membersList.Add(anyMember); - else if (mapping.TypeDesc.IsArrayLike && !(mapping.Elements.Length == 1 && mapping.Elements[0].Mapping is ArrayMapping)) + else if (mapping.TypeDesc!.IsArrayLike && !(mapping.Elements!.Length == 1 && mapping.Elements[0].Mapping is ArrayMapping)) { membersList.Add(anyMember); textOrArrayMembersList.Add(anyMember); @@ -507,7 +507,7 @@ private string GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping "set_IsReturnValue", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(bool) } - ); + )!; ilg.Ldarg(0); ilg.Ldc(true); ilg.Call(XmlSerializationReader_set_IsReturnValue); @@ -525,7 +525,7 @@ private string GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping "MoveToElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_MoveToElement); @@ -540,7 +540,7 @@ private string GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping "get_IsEmptyElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_IsEmptyElement); @@ -550,7 +550,7 @@ private string GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping "Skip", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_Skip); @@ -565,7 +565,7 @@ private string GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping "ReadStartElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_ReadStartElement); @@ -594,7 +594,7 @@ private string GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping "ReadEndElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_ReadEndElement); @@ -618,21 +618,21 @@ private void InitializeValueTypes(string arrayName, MemberMapping[] mappings) { for (int i = 0; i < mappings.Length; i++) { - if (!mappings[i].TypeDesc.IsValueType) + if (!mappings[i].TypeDesc!.IsValueType) continue; LocalBuilder arrayLoc = ilg.GetLocal(arrayName); ilg.Ldloc(arrayLoc); ilg.Ldc(i); - RaCodeGen.ILGenForCreateInstance(ilg, mappings[i].TypeDesc.Type, false, false); - ilg.ConvertValue(mappings[i].TypeDesc.Type, typeof(object)); - ilg.Stelem(arrayLoc.LocalType.GetElementType()); + RaCodeGen.ILGenForCreateInstance(ilg, mappings[i].TypeDesc!.Type!, false, false); + ilg.ConvertValue(mappings[i].TypeDesc!.Type!, typeof(object)); + ilg.Stelem(arrayLoc.LocalType.GetElementType()!); } } private string GenerateTypeElement(XmlTypeMapping xmlTypeMapping) { ElementAccessor element = xmlTypeMapping.Accessor; - TypeMapping mapping = element.Mapping; + TypeMapping mapping = element.Mapping!; string methodName = NextMethodName(element.Name); ilg = new CodeGenerator(this.typeBuilder); ilg.BeginMethod( @@ -654,12 +654,12 @@ private string GenerateTypeElement(XmlTypeMapping xmlTypeMapping) "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_MoveToContent = typeof(XmlReader).GetMethod( "MoveToContent", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_MoveToContent); @@ -690,14 +690,14 @@ private void WritePrimitive(TypeMapping mapping, string source) || source == "false" || source == "Reader.Value" || source == "vals[i]"); if (mapping is EnumMapping) { - string enumMethodName = ReferenceMapping(mapping); - if (enumMethodName == null) throw new InvalidOperationException(SR.Format(SR.XmlMissingMethodEnum, mapping.TypeDesc.Name)); + string? enumMethodName = ReferenceMapping(mapping); + if (enumMethodName == null) throw new InvalidOperationException(SR.Format(SR.XmlMissingMethodEnum, mapping.TypeDesc!.Name)); // For enum, its read method (eg. Read1_Gender) could be called multiple times // prior to its declaration. MethodBuilder methodBuilder = EnsureMethodBuilder(typeBuilder, enumMethodName, CodeGenerator.PrivateMethodAttributes, - mapping.TypeDesc.Type, + mapping.TypeDesc!.Type, new Type[] { typeof(string) } ); ilg.Ldarg(0); @@ -707,12 +707,12 @@ private void WritePrimitive(TypeMapping mapping, string source) "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_ReadXXXString = typeof(XmlReader).GetMethod( source == "Reader.ReadElementString()" ? "ReadElementContentAsString" : "ReadContentAsString", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_ReadXXXString); @@ -723,12 +723,12 @@ private void WritePrimitive(TypeMapping mapping, string source) "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_get_Value = typeof(XmlReader).GetMethod( "get_Value", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_Value); @@ -757,12 +757,12 @@ private void WritePrimitive(TypeMapping mapping, string source) "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_ReadXXXString = typeof(XmlReader).GetMethod( source == "Reader.ReadElementString()" ? "ReadElementContentAsString" : "ReadContentAsString", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_ReadXXXString); @@ -773,12 +773,12 @@ private void WritePrimitive(TypeMapping mapping, string source) "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_get_Value = typeof(XmlReader).GetMethod( "get_Value", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_Value); @@ -794,7 +794,7 @@ private void WritePrimitive(TypeMapping mapping, string source) throw Globals.NotSupported("Unexpected: " + source); } } - else if (mapping.TypeDesc.FormatterName == "String") + else if (mapping.TypeDesc!.FormatterName == "String") { System.Diagnostics.Debug.Assert(source == "Reader.Value" || source == "Reader.ReadElementString()" || source == "vals[i]"); if (source == "vals[i]") @@ -812,7 +812,7 @@ private void WritePrimitive(TypeMapping mapping, string source) null, new Type[] { typeof(string) }, null - ); + )!; ilg.Call(XmlSerializationReader_CollapseWhitespace); } } @@ -822,12 +822,12 @@ private void WritePrimitive(TypeMapping mapping, string source) "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_method = typeof(XmlReader).GetMethod( source == "Reader.Value" ? "get_Value" : "ReadElementContentAsString", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; if (mapping.TypeDesc.CollapseWhitespace) ilg.Ldarg(0); ilg.Ldarg(0); @@ -839,7 +839,7 @@ private void WritePrimitive(TypeMapping mapping, string source) "CollapseWhitespace", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } - ); + )!; ilg.Call(XmlSerializationReader_CollapseWhitespace); } } @@ -864,7 +864,7 @@ private void WritePrimitive(TypeMapping mapping, string source) "To" + mapping.TypeDesc.FormatterName, bindingFlags, new Type[] { argType } - ); + )!; } else { @@ -872,7 +872,7 @@ private void WritePrimitive(TypeMapping mapping, string source) "To" + mapping.TypeDesc.FormatterName, CodeGenerator.StaticBindingFlags, new Type[] { argType } - ); + )!; } if (source == "Reader.ReadElementString()" || source == "Reader.ReadString()") { @@ -880,12 +880,12 @@ private void WritePrimitive(TypeMapping mapping, string source) "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_ReadXXXString = typeof(XmlReader).GetMethod( source == "Reader.ReadElementString()" ? "ReadElementContentAsString" : "ReadContentAsString", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_ReadXXXString); @@ -896,12 +896,12 @@ private void WritePrimitive(TypeMapping mapping, string source) "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_get_Value = typeof(XmlReader).GetMethod( "get_Value", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_Value); @@ -921,10 +921,10 @@ private void WritePrimitive(TypeMapping mapping, string source) } } - private string MakeUnique(EnumMapping mapping, string name) + private string? MakeUnique(EnumMapping mapping, string name) { string uniqueName = name; - EnumMapping m; + EnumMapping? m; if (Enums.TryGetValue(uniqueName, out m)) { if (m == mapping) @@ -944,14 +944,14 @@ private string MakeUnique(EnumMapping mapping, string name) return uniqueName; } - private string WriteHashtable(EnumMapping mapping, string typeName, out MethodBuilder get_TableName) + private string WriteHashtable(EnumMapping mapping, string typeName, out MethodBuilder? get_TableName) { get_TableName = null; CodeIdentifier.CheckValidIdentifier(typeName); - string propName = MakeUnique(mapping, typeName + "Values"); + string? propName = MakeUnique(mapping, typeName + "Values"); if (propName == null) return CodeIdentifier.GetCSharpName(typeName); - string memberName = MakeUnique(mapping, "_" + propName); + string memberName = MakeUnique(mapping, "_" + propName)!; propName = CodeIdentifier.GetCSharpName(propName); FieldBuilder fieldBuilder = this.typeBuilder.DefineField( @@ -983,24 +983,24 @@ private string WriteHashtable(EnumMapping mapping, string typeName, out MethodBu ConstructorInfo Hashtable_ctor = typeof(Hashtable).GetConstructor( CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; LocalBuilder hLoc = ilg.DeclareLocal(typeof(Hashtable), "h"); ilg.New(Hashtable_ctor); ilg.Stloc(hLoc); - ConstantMapping[] constants = mapping.Constants; + ConstantMapping[] constants = mapping.Constants!; MethodInfo Hashtable_Add = typeof(Hashtable).GetMethod( "Add", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(object), typeof(object) } - ); + )!; for (int i = 0; i < constants.Length; i++) { ilg.Ldloc(hLoc); ilg.Ldstr(GetCSharpString(constants[i].XmlName)); - ilg.Ldc(Enum.ToObject(mapping.TypeDesc.Type, constants[i].Value)); - ilg.ConvertValue(mapping.TypeDesc.Type, typeof(long)); + ilg.Ldc(Enum.ToObject(mapping.TypeDesc!.Type!, constants[i].Value)); + ilg.ConvertValue(mapping.TypeDesc.Type!, typeof(long)); ilg.ConvertValue(typeof(long), typeof(object)); ilg.Call(Hashtable_Add); @@ -1016,38 +1016,38 @@ private string WriteHashtable(EnumMapping mapping, string typeName, out MethodBu ilg.LoadMember(fieldBuilder); get_TableName = ilg.EndMethod(); - propertyBuilder.SetGetMethod(get_TableName); + propertyBuilder.SetGetMethod(get_TableName!); return propName; } private void WriteEnumMethod(EnumMapping mapping) { - MethodBuilder get_TableName = null; + MethodBuilder? get_TableName = null; if (mapping.IsFlags) - WriteHashtable(mapping, mapping.TypeDesc.Name, out get_TableName); + WriteHashtable(mapping, mapping.TypeDesc!.Name, out get_TableName); - string methodName; + string? methodName; MethodNames.TryGetValue(mapping, out methodName); - string fullTypeName = mapping.TypeDesc.CSharpName; + string fullTypeName = mapping.TypeDesc!.CSharpName; List argTypes = new List(); List argNames = new List(); Type returnType; Type underlyingType; - returnType = mapping.TypeDesc.Type; + returnType = mapping.TypeDesc.Type!; underlyingType = Enum.GetUnderlyingType(returnType); argTypes.Add(typeof(string)); argNames.Add("s"); ilg = new CodeGenerator(this.typeBuilder); ilg.BeginMethod( returnType, - GetMethodBuilder(methodName), + GetMethodBuilder(methodName!), argTypes.ToArray(), argNames.ToArray(), CodeGenerator.PrivateMethodAttributes); - ConstantMapping[] constants = mapping.Constants; + ConstantMapping[] constants = mapping.Constants!; if (mapping.IsFlags) { { @@ -1055,7 +1055,7 @@ private void WriteEnumMethod(EnumMapping mapping) "ToEnum", CodeGenerator.StaticBindingFlags, new Type[] { typeof(string), typeof(Hashtable), typeof(string) } - ); + )!; ilg.Ldarg("s"); ilg.Ldarg(0); Debug.Assert(get_TableName != null); @@ -1098,11 +1098,11 @@ private void WriteEnumMethod(EnumMapping mapping) "op_Equality", CodeGenerator.StaticBindingFlags, new Type[] { typeof(string), typeof(string) } - ); + )!; ilg.Call(String_op_Equality); ilg.Brtrue(caseLabel); caseLabels.Add(caseLabel); - retValues.Add(Enum.ToObject(mapping.TypeDesc.Type, c.Value)); + retValues.Add(Enum.ToObject(mapping.TypeDesc.Type!, c.Value)); } } @@ -1119,13 +1119,13 @@ private void WriteEnumMethod(EnumMapping mapping) "CreateUnknownConstantException", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(Type) } - ); + )!; // Default body ilg.MarkLabel(defaultLabel); ilg.Ldarg(0); ilg.Ldarg("s"); // typeof(..) - ilg.Ldc(mapping.TypeDesc.Type); + ilg.Ldc(mapping.TypeDesc.Type!); ilg.Call(XmlSerializationReader_CreateUnknownConstantException); ilg.Throw(); // End switch @@ -1139,21 +1139,21 @@ private void WriteEnumMethod(EnumMapping mapping) private void WriteDerivedTypes(StructMapping mapping, bool isTypedReturn, string returnTypeName) { - for (StructMapping derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) + for (StructMapping? derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) { ilg.InitElseIf(); WriteQNameEqual("xsiType", derived.TypeName, derived.Namespace); ilg.AndIf(); - string methodName = ReferenceMapping(derived); + string? methodName = ReferenceMapping(derived); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe - if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, derived.TypeDesc.Name)); + if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, derived.TypeDesc!.Name)); #endif List argTypes = new List(); ilg.Ldarg(0); - if (derived.TypeDesc.IsNullable) + if (derived.TypeDesc!.IsNullable) { ilg.Ldarg("isNullable"); argTypes.Add(typeof(bool)); @@ -1162,7 +1162,7 @@ private void WriteDerivedTypes(StructMapping mapping, bool isTypedReturn, string argTypes.Add(typeof(bool)); MethodBuilder methodBuilder = EnsureMethodBuilder(typeBuilder, - methodName, + methodName!, CodeGenerator.PrivateMethodAttributes, derived.TypeDesc.Type, argTypes.ToArray() @@ -1192,37 +1192,37 @@ private void WriteEnumAndArrayTypes() "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_ReadStartElement = typeof(XmlReader).GetMethod( "ReadStartElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_ReadStartElement); - string methodName = ReferenceMapping(mapping); + string? methodName = ReferenceMapping(mapping); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe - if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc.Name)); + if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc!.Name)); #endif LocalBuilder eLoc = ilg.DeclareOrGetLocal(typeof(object), "e"); MethodBuilder methodBuilder = EnsureMethodBuilder(typeBuilder, - methodName, + methodName!, CodeGenerator.PrivateMethodAttributes, - mapping.TypeDesc.Type, + mapping.TypeDesc!.Type, new Type[] { typeof(string) } ); MethodInfo XmlSerializationReader_CollapseWhitespace = typeof(XmlSerializationReader).GetMethod( "CollapseWhitespace", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } - ); + )!; MethodInfo XmlReader_ReadString = typeof(XmlReader).GetMethod( "ReadContentAsString", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Ldarg(0); ilg.Ldarg(0); @@ -1236,7 +1236,7 @@ private void WriteEnumAndArrayTypes() "ReadEndElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_ReadEndElement); ilg.Ldloc(eLoc); @@ -1247,7 +1247,7 @@ private void WriteEnumAndArrayTypes() else if (m is ArrayMapping) { ArrayMapping mapping = (ArrayMapping)m; - if (mapping.TypeDesc.HasDefaultConstructor) + if (mapping.TypeDesc!.HasDefaultConstructor) { ilg.InitElseIf(); WriteQNameEqual("xsiType", mapping.TypeName, mapping.Namespace); @@ -1261,10 +1261,10 @@ private void WriteEnumAndArrayTypes() Member member = new Member(this, aVar, zVar, 0, memberMapping); TypeDesc td = mapping.TypeDesc; - LocalBuilder aLoc = ilg.DeclareLocal(mapping.TypeDesc.Type, aVar); + LocalBuilder aLoc = ilg.DeclareLocal(mapping.TypeDesc.Type!, aVar); if (mapping.TypeDesc.IsValueType) { - RaCodeGen.ILGenForCreateInstance(ilg, td.Type, false, false); + RaCodeGen.ILGenForCreateInstance(ilg, td.Type!, false, false); } else ilg.Load(null); @@ -1284,24 +1284,24 @@ private void WriteEnumAndArrayTypes() private void WriteNullableMethod(NullableMapping nullableMapping) { - string methodName; + string? methodName; MethodNames.TryGetValue(nullableMapping, out methodName); ilg = new CodeGenerator(this.typeBuilder); ilg.BeginMethod( - nullableMapping.TypeDesc.Type, - GetMethodBuilder(methodName), + nullableMapping.TypeDesc!.Type!, + GetMethodBuilder(methodName!), new Type[] { typeof(bool) }, new string[] { "checkType" }, CodeGenerator.PrivateMethodAttributes); - LocalBuilder oLoc = ilg.DeclareLocal(nullableMapping.TypeDesc.Type, "o"); + LocalBuilder oLoc = ilg.DeclareLocal(nullableMapping.TypeDesc.Type!, "o"); ilg.LoadAddress(oLoc); - ilg.InitObj(nullableMapping.TypeDesc.Type); + ilg.InitObj(nullableMapping.TypeDesc.Type!); MethodInfo XmlSerializationReader_ReadNull = typeof(XmlSerializationReader).GetMethod( "ReadNull", CodeGenerator.InstanceBindingFlags, - Array.Empty()); + Array.Empty())!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_ReadNull); ilg.If(); @@ -1315,7 +1315,7 @@ private void WriteNullableMethod(NullableMapping nullableMapping) ElementAccessor element = new ElementAccessor(); element.Mapping = nullableMapping.BaseMapping; element.Any = false; - element.IsNullable = nullableMapping.BaseMapping.TypeDesc.IsNullable; + element.IsNullable = nullableMapping.BaseMapping!.TypeDesc!.IsNullable; WriteElement("o", null, null, element, null, null, false, false, -1, -1); ilg.Ldloc(oLoc); @@ -1334,9 +1334,9 @@ private void WriteStructMethod(StructMapping structMapping) private void WriteLiteralStructMethod(StructMapping structMapping) { - string methodName; + string? methodName; MethodNames.TryGetValue(structMapping, out methodName); - string typeName = structMapping.TypeDesc.CSharpName; + string typeName = structMapping.TypeDesc!.CSharpName; ilg = new CodeGenerator(this.typeBuilder); List argTypes = new List(); List argNames = new List(); @@ -1348,8 +1348,8 @@ private void WriteLiteralStructMethod(StructMapping structMapping) argTypes.Add(typeof(bool)); argNames.Add("checkType"); ilg.BeginMethod( - structMapping.TypeDesc.Type, - GetMethodBuilder(methodName), + structMapping.TypeDesc.Type!, + GetMethodBuilder(methodName!), argTypes.ToArray(), argNames.ToArray(), CodeGenerator.PrivateMethodAttributes); @@ -1360,12 +1360,12 @@ private void WriteLiteralStructMethod(StructMapping structMapping) "GetXsiType", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlSerializationReader_ReadNull = typeof(XmlSerializationReader).GetMethod( "ReadNull", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; Label labelTrue = ilg.DefineLabel(); Label labelEnd = ilg.DefineLabel(); ilg.Ldarg("checkType"); @@ -1404,7 +1404,7 @@ private void WriteLiteralStructMethod(StructMapping structMapping) "ReadTypedNull", CodeGenerator.InstanceBindingFlags, new Type[] { locXsiType.LocalType } - ); + )!; ilg.Ldarg(0); ilg.Ldloc(locXsiType); ilg.Call(XmlSerializationReader_ReadTypedNull); @@ -1447,12 +1447,12 @@ private void WriteLiteralStructMethod(StructMapping structMapping) ConstructorInfo XmlQualifiedName_ctor = typeof(XmlQualifiedName).GetConstructor( CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string) } - ); + )!; MethodInfo XmlSerializationReader_ReadTypedPrimitive = typeof(XmlSerializationReader).GetMethod( "ReadTypedPrimitive", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(XmlQualifiedName) } - ); + )!; ilg.Ldarg(0); ilg.Ldstr(Soap.UrType); ilg.Ldstr(XmlSchema.Namespace); @@ -1470,7 +1470,7 @@ private void WriteLiteralStructMethod(StructMapping structMapping) "ReadTypedPrimitive", CodeGenerator.InstanceBindingFlags, new Type[] { locXsiType.LocalType } - ); + )!; ilg.Ldarg(0); ilg.Ldloc(locXsiType); ilg.Call(XmlSerializationReader_ReadTypedPrimitive); @@ -1483,7 +1483,7 @@ private void WriteLiteralStructMethod(StructMapping structMapping) "CreateUnknownTypeException", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(XmlQualifiedName) } - ); + )!; ilg.Ldarg(0); ilg.Ldloc(locXsiType); ilg.Call(XmlSerializationReader_CreateUnknownTypeException); @@ -1510,7 +1510,7 @@ private void WriteLiteralStructMethod(StructMapping structMapping) "CreateAbstractTypeException", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Ldstr(GetCSharpString(structMapping.TypeName)); ilg.Ldstr(GetCSharpString(structMapping.Namespace)); @@ -1525,7 +1525,7 @@ private void WriteLiteralStructMethod(StructMapping structMapping) "set_DecodeName", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(bool) } - ); + )!; ilg.Ldarg(0); ilg.Ldc(false); ilg.Call(XmlSerializationReader_set_DecodeName); @@ -1536,9 +1536,9 @@ private void WriteLiteralStructMethod(StructMapping structMapping) // this method populates the memberInfos dictionary based on the structMapping MemberMapping[] mappings = TypeScope.GetSettableMembers(structMapping, memberInfos); - Member anyText = null; - Member anyElement = null; - Member anyAttribute = null; + Member? anyText = null; + Member? anyElement = null; + Member? anyAttribute = null; bool isSequence = structMapping.HasExplicitSequence(); var arraysToDeclareList = new List(mappings.Length); @@ -1553,7 +1553,7 @@ private void WriteLiteralStructMethod(StructMapping structMapping) Member member = new Member(this, source, "a", i, mapping, GetChoiceIdentifierSource(mapping, "o", structMapping.TypeDesc)); if (!mapping.IsSequence) member.ParamsReadSource = "paramsRead[" + i.ToString(CultureInfo.InvariantCulture) + "]"; - member.IsNullable = mapping.TypeDesc.IsNullable; + member.IsNullable = mapping.TypeDesc!.IsNullable; if (mapping.CheckSpecified == SpecifiedAccessor.ReadWrite) member.CheckSpecifiedSource = RaCodeGen.GetStringForMember("o", mapping.Name + "Specified", structMapping.TypeDesc); if (mapping.Text != null) @@ -1563,7 +1563,7 @@ private void WriteLiteralStructMethod(StructMapping structMapping) if (!isSequence) { // find anyElement if present. - for (int j = 0; j < mapping.Elements.Length; j++) + for (int j = 0; j < mapping.Elements!.Length; j++) { if (mapping.Elements[j].Any && (mapping.Elements[j].Name == null || mapping.Elements[j].Name.Length == 0)) { @@ -1574,11 +1574,11 @@ private void WriteLiteralStructMethod(StructMapping structMapping) } else if (mapping.IsParticle && !mapping.IsSequence) { - StructMapping declaringMapping; + StructMapping? declaringMapping; structMapping.FindDeclaringMapping(mapping, out declaringMapping, structMapping.TypeName); - throw new InvalidOperationException(SR.Format(SR.XmlSequenceHierarchy, structMapping.TypeDesc.FullName, mapping.Name, declaringMapping.TypeDesc.FullName, "Order")); + throw new InvalidOperationException(SR.Format(SR.XmlSequenceHierarchy, structMapping.TypeDesc.FullName, mapping.Name, declaringMapping!.TypeDesc!.FullName, "Order")); } - if (mapping.Attribute == null && mapping.Elements.Length == 1 && mapping.Elements[0].Mapping is ArrayMapping) + if (mapping.Attribute == null && mapping.Elements!.Length == 1 && mapping.Elements[0].Mapping is ArrayMapping) { Member arrayMember = new Member(this, source, source, "a", i, mapping, GetChoiceIdentifierSource(mapping, "o", structMapping.TypeDesc)); arrayMember.CheckSpecifiedSource = member.CheckSpecifiedSource; @@ -1592,7 +1592,7 @@ private void WriteLiteralStructMethod(StructMapping structMapping) if (mapping.TypeDesc.IsArrayLike) { arraysToDeclareList.Add(member); - if (mapping.TypeDesc.IsArrayLike && !(mapping.Elements.Length == 1 && mapping.Elements[0].Mapping is ArrayMapping)) + if (mapping.TypeDesc.IsArrayLike && !(mapping.Elements!.Length == 1 && mapping.Elements[0].Mapping is ArrayMapping)) { member.ParamsReadSource = null; // flat arrays -- don't want to count params read. if (member != anyText && member != anyElement) @@ -1624,12 +1624,12 @@ private void WriteLiteralStructMethod(StructMapping structMapping) "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_MoveToElement = typeof(XmlReader).GetMethod( "MoveToElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_MoveToElement); @@ -1639,7 +1639,7 @@ private void WriteLiteralStructMethod(StructMapping structMapping) "get_IsEmptyElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_IsEmptyElement); @@ -1648,7 +1648,7 @@ private void WriteLiteralStructMethod(StructMapping structMapping) "Skip", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_Skip); @@ -1662,7 +1662,7 @@ private void WriteLiteralStructMethod(StructMapping structMapping) "ReadStartElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_ReadStartElement); @@ -1678,7 +1678,7 @@ private void WriteLiteralStructMethod(StructMapping structMapping) "MoveToContent", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_MoveToContent); @@ -1691,10 +1691,10 @@ private void WriteLiteralStructMethod(StructMapping structMapping) "ReadEndElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_ReadEndElement); - ilg.Ldloc(structMapping.TypeDesc.Type, "o"); + ilg.Ldloc(structMapping.TypeDesc.Type!, "o"); ilg.Stloc(ilg.ReturnLocal); } ilg.MarkLabel(ilg.ReturnLabel); @@ -1702,7 +1702,7 @@ private void WriteLiteralStructMethod(StructMapping structMapping) ilg.EndMethod(); } - private void WriteQNameEqual(string source, string name, string ns) + private void WriteQNameEqual(string source, string? name, string? ns) { WriteID(name); WriteID(ns); @@ -1712,12 +1712,12 @@ private void WriteQNameEqual(string source, string name, string ns) "get_Name", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlQualifiedName_get_Namespace = typeof(XmlQualifiedName).GetMethod( "get_Namespace", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; Label labelEnd = ilg.DefineLabel(); Label labelFalse = ilg.DefineLabel(); LocalBuilder sLoc = ilg.GetLocal(source); @@ -1737,11 +1737,11 @@ private void WriteQNameEqual(string source, string name, string ns) ilg.MarkLabel(labelEnd); } - private void WriteXmlNodeEqual(string source, string name, string ns) + private void WriteXmlNodeEqual(string source, string name, string? ns) { WriteXmlNodeEqual(source, name, ns, true); } - private void WriteXmlNodeEqual(string source, string name, string ns, bool doAndIf) + private void WriteXmlNodeEqual(string source, string name, string? ns, bool doAndIf) { bool isNameNullOrEmpty = string.IsNullOrEmpty(name); if (!isNameNullOrEmpty) @@ -1755,17 +1755,17 @@ private void WriteXmlNodeEqual(string source, string name, string ns, bool doAnd "get_" + source, CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_get_LocalName = typeof(XmlReader).GetMethod( "get_LocalName", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_get_NamespaceURI = typeof(XmlReader).GetMethod( "get_NamespaceURI", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; Label labelFalse = ilg.DefineLabel(); Label labelEnd = ilg.DefineLabel(); @@ -1798,7 +1798,7 @@ private void WriteXmlNodeEqual(string source, string name, string ns, bool doAnd ilg.AndIf(); } - private void WriteID(string name) + private void WriteID(string? name) { if (name == null) { @@ -1806,7 +1806,7 @@ private void WriteID(string name) //return; name = ""; } - string idName; + string? idName; if (!_idNames.TryGetValue(name, out idName)) { idName = NextIdName(name); @@ -1815,10 +1815,10 @@ private void WriteID(string name) } } - private void WriteAttributes(Member[] members, Member anyAttribute, string elseCall, LocalBuilder firstParam) + private void WriteAttributes(Member[] members, Member? anyAttribute, string elseCall, LocalBuilder firstParam) { int count = 0; - Member xmlnsMember = null; + Member? xmlnsMember = null; var attributes = new List(); // Condition do at the end, so C# looks the same @@ -1826,12 +1826,12 @@ private void WriteAttributes(Member[] members, Member anyAttribute, string elseC "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_MoveToNextAttribute = typeof(XmlReader).GetMethod( "MoveToNextAttribute", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.WhileBegin(); for (int i = 0; i < members.Length; i++) @@ -1844,7 +1844,8 @@ private void WriteAttributes(Member[] members, Member anyAttribute, string elseC } if (member.Mapping.Ignore) continue; - AttributeAccessor attribute = member.Mapping.Attribute; + + AttributeAccessor? attribute = member.Mapping.Attribute; if (attribute == null) continue; if (attribute.Any) continue; @@ -1884,22 +1885,22 @@ private void WriteAttributes(Member[] members, Member anyAttribute, string elseC "IsXmlnsAttribute", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } - ); + )!; MethodInfo XmlReader_get_Name = typeof(XmlReader).GetMethod( "get_Name", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_get_LocalName = typeof(XmlReader).GetMethod( "get_LocalName", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_get_Value = typeof(XmlReader).GetMethod( "get_Value", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); @@ -1912,26 +1913,26 @@ private void WriteAttributes(Member[] members, Member anyAttribute, string elseC ilg.Load(null); ilg.If(Cmp.EqualTo); WriteSourceBegin(xmlnsMember.Source); - ConstructorInfo ctor = xmlnsMember.Mapping.TypeDesc.Type.GetConstructor( + ConstructorInfo ctor = xmlnsMember.Mapping.TypeDesc!.Type!.GetConstructor( CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.New(ctor); - WriteSourceEnd(xmlnsMember.Source, xmlnsMember.Mapping.TypeDesc.Type); + WriteSourceEnd(xmlnsMember.Source, xmlnsMember.Mapping.TypeDesc.Type!); ilg.EndIf(); // if (xmlnsMember.Source == null Label labelEqual5 = ilg.DefineLabel(); Label labelEndLength = ilg.DefineLabel(); - MethodInfo Add = xmlnsMember.Mapping.TypeDesc.Type.GetMethod( + MethodInfo Add = xmlnsMember.Mapping.TypeDesc.Type!.GetMethod( "Add", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string) } - ); + )!; MethodInfo String_get_Length = typeof(string).GetMethod( "get_Length", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ILGenLoad(xmlnsMember.ArraySource, xmlnsMember.Mapping.TypeDesc.Type); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); @@ -1959,12 +1960,12 @@ private void WriteAttributes(Member[] members, Member anyAttribute, string elseC "IsXmlnsAttribute", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } - ); + )!; MethodInfo XmlReader_get_Name = typeof(XmlReader).GetMethod( "get_Name", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); @@ -1980,12 +1981,12 @@ private void WriteAttributes(Member[] members, Member anyAttribute, string elseC "get_Document", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlDocument_ReadNode = typeof(XmlDocument).GetMethod( "ReadNode", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(XmlReader) } - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Document); ilg.Ldarg(0); @@ -1997,7 +1998,7 @@ private void WriteAttributes(Member[] members, Member anyAttribute, string elseC "ParseWsdlArrayType", CodeGenerator.InstanceBindingFlags, new Type[] { localAttr.LocalType } - ); + )!; ilg.Ldarg(0); ilg.Ldloc(localAttr); ilg.Call(XmlSerializationReader_ParseWsdlArrayType); @@ -2029,7 +2030,7 @@ private void WriteAttributes(Member[] members, Member anyAttribute, string elseC elseCall, CodeGenerator.InstanceBindingFlags, argTypes.ToArray() - ); + )!; ilg.Call(elseCallMethod); } ilg.EndIf(); @@ -2046,17 +2047,17 @@ private void WriteAttributes(Member[] members, Member anyAttribute, string elseC private void WriteAttribute(Member member) { - AttributeAccessor attribute = member.Mapping.Attribute; + AttributeAccessor attribute = member.Mapping.Attribute!; if (attribute.Mapping is SpecialMapping) { SpecialMapping special = (SpecialMapping)attribute.Mapping; - if (special.TypeDesc.Kind == TypeKind.Attribute) + if (special.TypeDesc!.Kind == TypeKind.Attribute) { WriteSourceBegin(member.ArraySource); ilg.Ldloc("attr"); - WriteSourceEnd(member.ArraySource, member.Mapping.TypeDesc.IsArrayLike ? member.Mapping.TypeDesc.ArrayElementTypeDesc.Type : member.Mapping.TypeDesc.Type); + WriteSourceEnd(member.ArraySource, member.Mapping.TypeDesc!.IsArrayLike ? member.Mapping.TypeDesc.ArrayElementTypeDesc!.Type! : member.Mapping.TypeDesc.Type!); } else if (special.TypeDesc.CanBeAttributeValue) { @@ -2074,7 +2075,7 @@ private void WriteAttribute(Member member) WriteSourceBegin(member.ArraySource); ilg.Ldloc(attrLoc); ilg.ConvertValue(attrLoc.LocalType, typeof(XmlAttribute)); - WriteSourceEnd(member.ArraySource, member.Mapping.TypeDesc.IsArrayLike ? member.Mapping.TypeDesc.ArrayElementTypeDesc.Type : member.Mapping.TypeDesc.Type); + WriteSourceEnd(member.ArraySource, member.Mapping.TypeDesc!.IsArrayLike ? member.Mapping.TypeDesc.ArrayElementTypeDesc!.Type! : member.Mapping.TypeDesc.Type!); ilg.EndIf(); } else @@ -2090,17 +2091,17 @@ private void WriteAttribute(Member member) "Split", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(char[]) } - ); + )!; MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_get_Value = typeof(XmlReader).GetMethod( "get_Value", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_Value); @@ -2112,18 +2113,18 @@ private void WriteAttribute(Member member) LocalBuilder localI = ilg.DeclareOrGetLocal(typeof(int), "i"); ilg.For(localI, 0, locVals); - string attributeSource = GetArraySource(member.Mapping.TypeDesc, member.ArrayName); + string attributeSource = GetArraySource(member.Mapping.TypeDesc!, member.ArrayName); WriteSourceBegin(attributeSource); - WritePrimitive(attribute.Mapping, "vals[i]"); - WriteSourceEnd(attributeSource, member.Mapping.TypeDesc.ArrayElementTypeDesc.Type); + WritePrimitive(attribute.Mapping!, "vals[i]"); + WriteSourceEnd(attributeSource, member.Mapping.TypeDesc!.ArrayElementTypeDesc!.Type!); ilg.EndFor(); } else { WriteSourceBegin(member.ArraySource); - WritePrimitive(attribute.Mapping, attribute.IsList ? "vals[i]" : "Reader.Value"); - WriteSourceEnd(member.ArraySource, member.Mapping.TypeDesc.IsArrayLike ? member.Mapping.TypeDesc.ArrayElementTypeDesc.Type : member.Mapping.TypeDesc.Type); + WritePrimitive(attribute.Mapping!, attribute.IsList ? "vals[i]" : "Reader.Value"); + WriteSourceEnd(member.ArraySource, member.Mapping.TypeDesc!.IsArrayLike ? member.Mapping.TypeDesc.ArrayElementTypeDesc!.Type! : member.Mapping.TypeDesc.Type!); } } if (member.Mapping.CheckSpecified == SpecifiedAccessor.ReadWrite && member.CheckSpecifiedSource != null && member.CheckSpecifiedSource.Length > 0) @@ -2147,9 +2148,9 @@ private void WriteMemberBegin(Member[] members) string a = member.ArrayName; string c = "c" + a; - TypeDesc typeDesc = member.Mapping.TypeDesc; + TypeDesc typeDesc = member.Mapping.TypeDesc!; - if (member.Mapping.TypeDesc.IsArray) + if (member.Mapping.TypeDesc!.IsArray) { WriteArrayLocalDecl(typeDesc.CSharpName, a, "null", typeDesc); @@ -2158,7 +2159,7 @@ private void WriteMemberBegin(Member[] members) if (member.Mapping.ChoiceIdentifier != null) { - WriteArrayLocalDecl(member.Mapping.ChoiceIdentifier.Mapping.TypeDesc.CSharpName + "[]", + WriteArrayLocalDecl(member.Mapping.ChoiceIdentifier.Mapping!.TypeDesc!.CSharpName + "[]", member.ChoiceArrayName, "null", member.Mapping.ChoiceIdentifier.Mapping.TypeDesc); ilg.Ldc(0); @@ -2169,10 +2170,10 @@ private void WriteMemberBegin(Member[] members) { if (member.Source[member.Source.Length - 1] == '(' || member.Source[member.Source.Length - 1] == '{') { - WriteCreateInstance(a, typeDesc.CannotNew, typeDesc.Type); + WriteCreateInstance(a, typeDesc.CannotNew, typeDesc.Type!); WriteSourceBegin(member.Source); ilg.Ldloc(ilg.GetLocal(a)); - WriteSourceEnd(member.Source, typeDesc.Type); + WriteSourceEnd(member.Source, typeDesc.Type!); } else { @@ -2188,7 +2189,7 @@ private void WriteMemberBegin(Member[] members) "CreateReadOnlyCollectionException", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Ldstr(GetCSharpString(member.Mapping.TypeDesc.CSharpName)); ilg.Call(XmlSerializationReader_CreateReadOnlyCollectionException); @@ -2197,8 +2198,8 @@ private void WriteMemberBegin(Member[] members) else { WriteSourceBegin(member.Source); - RaCodeGen.ILGenForCreateInstance(ilg, member.Mapping.TypeDesc.Type, typeDesc.CannotNew, true); - WriteSourceEnd(member.Source, member.Mapping.TypeDesc.Type); + RaCodeGen.ILGenForCreateInstance(ilg, member.Mapping.TypeDesc.Type!, typeDesc.CannotNew, true); + WriteSourceEnd(member.Source, member.Mapping.TypeDesc.Type!); } ilg.EndIf(); // if ((object)(member.Source) == null } @@ -2225,12 +2226,12 @@ private string ExpectedElements(Member[] members) if (member.Mapping.IsText || member.Mapping.IsAttribute) continue; - ElementAccessor[] elements = member.Mapping.Elements; + ElementAccessor[] elements = member.Mapping.Elements!; for (int j = 0; j < elements.Length; j++) { ElementAccessor e = elements[j]; - string ns = e.Form == XmlSchemaForm.Qualified ? e.Namespace : ""; + string? ns = e.Form == XmlSchemaForm.Qualified ? e.Namespace : ""; if (e.Any && (e.Name == null || e.Name.Length == 0)) continue; if (!firstElement) @@ -2242,7 +2243,7 @@ private string ExpectedElements(Member[] members) return ReflectionAwareILGen.GetQuotedCSharpString(qnames); } - private void WriteMemberElements(Member[] members, string elementElseString, string elseString, Member anyElement, Member anyText) + private void WriteMemberElements(Member[] members, string elementElseString, string elseString, Member? anyElement, Member? anyText) { if (anyText != null) { @@ -2254,12 +2255,12 @@ private void WriteMemberElements(Member[] members, string elementElseString, str "get_NodeType", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; int XmlNodeType_Element = 1; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); @@ -2286,12 +2287,12 @@ private void WriteMemberText(Member anyText, string elseString) "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_get_NodeType = typeof(XmlReader).GetMethod( "get_NodeType", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_NodeType); @@ -2330,35 +2331,35 @@ private void WriteMemberText(Member anyText, string elseString) private void WriteText(Member member) { - TextAccessor text = member.Mapping.Text; + TextAccessor text = member.Mapping.Text!; if (text.Mapping is SpecialMapping) { SpecialMapping special = (SpecialMapping)text.Mapping; WriteSourceBeginTyped(member.ArraySource, special.TypeDesc); - switch (special.TypeDesc.Kind) + switch (special.TypeDesc!.Kind) { case TypeKind.Node: MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_ReadString = typeof(XmlReader).GetMethod( "ReadContentAsString", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlSerializationReader_get_Document = typeof(XmlSerializationReader).GetMethod( "get_Document", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlDocument_CreateTextNode = typeof(XmlDocument).GetMethod( "CreateTextNode", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Document); ilg.Ldarg(0); @@ -2369,14 +2370,14 @@ private void WriteText(Member member) default: throw new InvalidOperationException(SR.XmlInternalError); } - WriteSourceEnd(member.ArraySource, special.TypeDesc.Type); + WriteSourceEnd(member.ArraySource, special.TypeDesc.Type!); } else { if (member.IsArrayLike) { WriteSourceBegin(member.ArraySource); - if (text.Mapping.TypeDesc.CollapseWhitespace) + if (text.Mapping!.TypeDesc!.CollapseWhitespace) { ilg.Ldarg(0); // for calling CollapseWhitespace } @@ -2387,12 +2388,12 @@ private void WriteText(Member member) "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_ReadString = typeof(XmlReader).GetMethod( "ReadContentAsString", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_ReadString); @@ -2402,23 +2403,23 @@ private void WriteText(Member member) "CollapseWhitespace", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } - ); + )!; ilg.Call(XmlSerializationReader_CollapseWhitespace); } } else { - if (text.Mapping.TypeDesc == StringTypeDesc || text.Mapping.TypeDesc.FormatterName == "String") + if (text.Mapping!.TypeDesc == StringTypeDesc || text.Mapping.TypeDesc!.FormatterName == "String") { LocalBuilder tmpLoc = ilg.GetLocal("tmp"); MethodInfo XmlSerializationReader_ReadString = typeof(XmlSerializationReader).GetMethod( "ReadString", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(bool) } - ); + )!; ilg.Ldarg(0); ilg.Ldloc(tmpLoc); - ilg.Ldc(text.Mapping.TypeDesc.CollapseWhitespace); + ilg.Ldc(text.Mapping.TypeDesc!.CollapseWhitespace); ilg.Call(XmlSerializationReader_ReadString); ilg.Stloc(tmpLoc); @@ -2431,16 +2432,16 @@ private void WriteText(Member member) WritePrimitive(text.Mapping, "Reader.ReadString()"); } } - WriteSourceEnd(member.ArraySource, text.Mapping.TypeDesc.Type); + WriteSourceEnd(member.ArraySource, text.Mapping.TypeDesc.Type!); } } - private void WriteMemberElementsElse(Member anyElement, string elementElseString) + private void WriteMemberElementsElse(Member? anyElement, string elementElseString) { if (anyElement != null) { - ElementAccessor[] elements = anyElement.Mapping.Elements; + ElementAccessor[] elements = anyElement.Mapping.Elements!; for (int i = 0; i < elements.Length; i++) { ElementAccessor element = elements[i]; @@ -2466,7 +2467,7 @@ private bool IsSequence(Member[] members) } return false; } - private void WriteMemberElementsIf(Member[] members, Member anyElement, string elementElseString) + private void WriteMemberElementsIf(Member[] members, Member? anyElement, string elementElseString) { int count = 0; @@ -2484,13 +2485,13 @@ private void WriteMemberElementsIf(Member[] members, Member anyElement, string e continue; bool firstElement = true; - ChoiceIdentifierAccessor choice = member.Mapping.ChoiceIdentifier; - ElementAccessor[] elements = member.Mapping.Elements; + ChoiceIdentifierAccessor? choice = member.Mapping.ChoiceIdentifier; + ElementAccessor[] elements = member.Mapping.Elements!; for (int j = 0; j < elements.Length; j++) { ElementAccessor e = elements[j]; - string ns = e.Form == XmlSchemaForm.Qualified ? e.Namespace : ""; + string? ns = e.Form == XmlSchemaForm.Qualified ? e.Namespace : ""; if (!isSequence && e.Any && (e.Name == null || e.Name.Length == 0)) continue; if (!firstElement || (!isSequence && count > 0)) { @@ -2527,7 +2528,7 @@ private void WriteMemberElementsIf(Member[] members, Member anyElement, string e "get_IsReturnValue", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_IsReturnValue); ilg.Brtrue(labelTrue); @@ -2549,14 +2550,14 @@ private void WriteMemberElementsIf(Member[] members, Member anyElement, string e } ilg.AndIf(); - WriteElement(member.ArraySource, member.ArrayName, member.ChoiceArraySource, e, choice, member.Mapping.CheckSpecified == SpecifiedAccessor.ReadWrite ? member.CheckSpecifiedSource : null, member.IsList && member.Mapping.TypeDesc.IsNullable, member.Mapping.ReadOnly, member.FixupIndex, j); + WriteElement(member.ArraySource, member.ArrayName, member.ChoiceArraySource, e, choice, member.Mapping.CheckSpecified == SpecifiedAccessor.ReadWrite ? member.CheckSpecifiedSource : null, member.IsList && member.Mapping.TypeDesc!.IsNullable, member.Mapping.ReadOnly, member.FixupIndex, j); if (member.Mapping.IsReturnValue) { MethodInfo XmlSerializationReader_set_IsReturnValue = typeof(XmlSerializationReader).GetMethod( "set_IsReturnValue", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(bool) } - ); + )!; ilg.Ldarg(0); ilg.Ldc(false); ilg.Call(XmlSerializationReader_set_IsReturnValue); @@ -2612,7 +2613,7 @@ private string GetArraySource(TypeDesc typeDesc, string arrayName, bool multiRef } if (typeDesc.IsArray) { - string arrayTypeFullName = typeDesc.ArrayElementTypeDesc.CSharpName; + string arrayTypeFullName = typeDesc.ArrayElementTypeDesc!.CSharpName; string castString = "(" + arrayTypeFullName + "[])"; init = init + a + " = " + castString + "EnsureArrayIndex(" + a + ", " + c + ", " + RaCodeGen.GetStringForTypeof(arrayTypeFullName) + ");"; @@ -2644,7 +2645,7 @@ private void WriteMemberEnd(Member[] members, bool soapRefs) if (member.IsArrayLike) { - TypeDesc typeDesc = member.Mapping.TypeDesc; + TypeDesc typeDesc = member.Mapping.TypeDesc!; if (typeDesc.IsArray) { @@ -2659,30 +2660,30 @@ private void WriteMemberEnd(Member[] members, bool soapRefs) "ShrinkArray", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(Array), typeof(int), typeof(Type), typeof(bool) } - ); + )!; ilg.Ldarg(0); ilg.Ldloc(ilg.GetLocal(a)); ilg.Ldloc(ilg.GetLocal(c)); - ilg.Ldc(typeDesc.ArrayElementTypeDesc.Type); + ilg.Ldc(typeDesc.ArrayElementTypeDesc!.Type!); ilg.Ldc(member.IsNullable); ilg.Call(XmlSerializationReader_ShrinkArray); - ilg.ConvertValue(XmlSerializationReader_ShrinkArray.ReturnType, typeDesc.Type); - WriteSourceEnd(member.Source, typeDesc.Type); + ilg.ConvertValue(XmlSerializationReader_ShrinkArray.ReturnType, typeDesc.Type!); + WriteSourceEnd(member.Source, typeDesc.Type!); if (member.Mapping.ChoiceIdentifier != null) { - WriteSourceBegin(member.ChoiceSource); + WriteSourceBegin(member.ChoiceSource!); a = member.ChoiceArrayName; c = "c" + a; ilg.Ldarg(0); ilg.Ldloc(ilg.GetLocal(a)); ilg.Ldloc(ilg.GetLocal(c)); - ilg.Ldc(member.Mapping.ChoiceIdentifier.Mapping.TypeDesc.Type); + ilg.Ldc(member.Mapping.ChoiceIdentifier.Mapping!.TypeDesc!.Type!); ilg.Ldc(member.IsNullable); ilg.Call(XmlSerializationReader_ShrinkArray); - ilg.ConvertValue(XmlSerializationReader_ShrinkArray.ReturnType, member.Mapping.ChoiceIdentifier.Mapping.TypeDesc.Type.MakeArrayType()); - WriteSourceEnd(member.ChoiceSource, member.Mapping.ChoiceIdentifier.Mapping.TypeDesc.Type.MakeArrayType()); + ilg.ConvertValue(XmlSerializationReader_ShrinkArray.ReturnType, member.Mapping.ChoiceIdentifier.Mapping.TypeDesc.Type!.MakeArrayType()); + WriteSourceEnd(member.ChoiceSource!, member.Mapping.ChoiceIdentifier.Mapping.TypeDesc.Type!.MakeArrayType()); } } else if (typeDesc.IsValueType) @@ -2696,14 +2697,14 @@ private void WriteMemberEnd(Member[] members, bool soapRefs) } } - private void WriteSourceBeginTyped(string source, TypeDesc typeDesc) + private void WriteSourceBeginTyped(string source, TypeDesc? typeDesc) { WriteSourceBegin(source); } private void WriteSourceBegin(string source) { - object variable; + object? variable; if (ilg.TryGetVariable(source, out variable)) { Type varType = ilg.GetVariableType(variable); @@ -2731,12 +2732,12 @@ private void WriteSourceBegin(string source) LocalBuilder localA = ilg.GetLocal(match.Groups["locA1"].Value); LocalBuilder localI = ilg.GetLocal(match.Groups["locI1"].Value); - Type arrayElementType = localA.LocalType.GetElementType(); + Type arrayElementType = localA.LocalType.GetElementType()!; MethodInfo XmlSerializationReader_EnsureArrayIndex = typeof(XmlSerializationReader).GetMethod( "EnsureArrayIndex", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(Array), typeof(int), typeof(Type) } - ); + )!; ilg.Ldarg(0); ilg.Ldloc(localA); ilg.Ldloc(localI); @@ -2786,13 +2787,13 @@ private void WriteSourceEnd(string source, Type elementType) } private void WriteSourceEnd(string source, Type elementType, Type stackType) { - object variable; + object? variable; if (ilg.TryGetVariable(source, out variable)) { Type varType = ilg.GetVariableType(variable); if (CodeGenerator.IsNullableGenericType(varType)) { - ilg.Call(varType.GetConstructor(varType.GetGenericArguments())); + ilg.Call(varType.GetConstructor(varType.GetGenericArguments())!); } else { @@ -2818,7 +2819,7 @@ private void WriteSourceEnd(string source, Type elementType, Type stackType) if (match.Success) { object oVar = ilg.GetVariable(match.Groups["locA1"].Value); - Type arrayElementType = ilg.GetVariableType(oVar).GetElementType(); + Type arrayElementType = ilg.GetVariableType(oVar).GetElementType()!; ilg.ConvertValue(elementType, arrayElementType); if (CodeGenerator.IsNullableGenericType(arrayElementType) || arrayElementType.IsValueType) { @@ -2840,7 +2841,7 @@ private void WriteSourceEnd(string source, Type elementType, Type stackType) "Add", CodeGenerator.InstanceBindingFlags, new Type[] { elementType } - ); + )!; Debug.Assert(Add != null); Type addParameterType = Add.GetParameters()[0].ParameterType; ilg.ConvertValue(stackType, addParameterType); @@ -2856,7 +2857,7 @@ private void WriteSourceEnd(string source, Type elementType, Type stackType) { Type varType = ilg.GetVariableType(ilg.GetVariable(match.Groups["a"].Value)); System.Diagnostics.Debug.Assert(varType.IsArray); - Type varElementType = varType.GetElementType(); + Type varElementType = varType.GetElementType()!; ilg.ConvertValue(stackType, varElementType); ilg.Stelem(varElementType); return; @@ -2864,13 +2865,13 @@ private void WriteSourceEnd(string source, Type elementType, Type stackType) throw Globals.NotSupported("Unexpected: " + source); } - private void WriteArray(string source, string arrayName, ArrayMapping arrayMapping, bool readOnly, bool isNullable, int fixupIndex, int elementIndex) + private void WriteArray(string source, string? arrayName, ArrayMapping arrayMapping, bool readOnly, bool isNullable, int fixupIndex, int elementIndex) { MethodInfo XmlSerializationReader_ReadNull = typeof(XmlSerializationReader).GetMethod( "ReadNull", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_ReadNull); ilg.IfNot(); @@ -2905,12 +2906,12 @@ private void WriteArray(string source, string arrayName, ArrayMapping arrayMappi "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_get_IsEmptyElement = typeof(XmlReader).GetMethod( "get_IsEmptyElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_IsEmptyElement); @@ -2926,7 +2927,7 @@ private void WriteArray(string source, string arrayName, ArrayMapping arrayMappi "Skip", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_Skip); @@ -2936,7 +2937,7 @@ private void WriteArray(string source, string arrayName, ArrayMapping arrayMappi "ReadStartElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_ReadStartElement); @@ -2948,7 +2949,7 @@ private void WriteArray(string source, string arrayName, ArrayMapping arrayMappi "MoveToContent", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_MoveToContent); @@ -2959,7 +2960,7 @@ private void WriteArray(string source, string arrayName, ArrayMapping arrayMappi "ReadEndElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_ReadEndElement); ilg.EndIf(); @@ -2976,7 +2977,7 @@ private void WriteArray(string source, string arrayName, ArrayMapping arrayMappi ilg.EndIf(); } - private void WriteElement(string source, string arrayName, string choiceSource, ElementAccessor element, ChoiceIdentifierAccessor choice, string checkSpecified, bool checkForNull, bool readOnly, int fixupIndex, int elementIndex) + private void WriteElement(string source, string? arrayName, string? choiceSource, ElementAccessor element, ChoiceIdentifierAccessor? choice, string? checkSpecified, bool checkForNull, bool readOnly, int fixupIndex, int elementIndex) { if (checkSpecified != null && checkSpecified.Length > 0) { @@ -2989,23 +2990,23 @@ private void WriteElement(string source, string arrayName, string choiceSource, } else if (element.Mapping is NullableMapping) { - string methodName = ReferenceMapping(element.Mapping); + string? methodName = ReferenceMapping(element.Mapping); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe - if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, element.Mapping.TypeDesc.Name)); + if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, element.Mapping.TypeDesc!.Name)); #endif WriteSourceBegin(source); ilg.Ldarg(0); ilg.Ldc(true); MethodBuilder methodBuilder = EnsureMethodBuilder(typeBuilder, - methodName, + methodName!, CodeGenerator.PrivateMethodAttributes, // See WriteNullableMethod for different return type logic - element.Mapping.TypeDesc.Type, + element.Mapping.TypeDesc!.Type, new Type[] { typeof(bool) } ); ilg.Call(methodBuilder); - WriteSourceEnd(source, element.Mapping.TypeDesc.Type); + WriteSourceEnd(source, element.Mapping.TypeDesc.Type!); } else if (element.Mapping is PrimitiveMapping) { @@ -3016,12 +3017,12 @@ private void WriteElement(string source, string arrayName, string choiceSource, "ReadNull", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_ReadNull); ilg.If(); WriteSourceBegin(source); - if (element.Mapping.TypeDesc.IsValueType) + if (element.Mapping.TypeDesc!.IsValueType) { throw Globals.NotSupported("No such condition. PrimitiveMapping && IsNullable = String, XmlQualifiedName and never IsValueType"); } @@ -3029,22 +3030,22 @@ private void WriteElement(string source, string arrayName, string choiceSource, { ilg.Load(null); } - WriteSourceEnd(source, element.Mapping.TypeDesc.Type); + WriteSourceEnd(source, element.Mapping.TypeDesc.Type!); ilg.Else(); doEndIf = true; } - if (element.Default != null && element.Default != DBNull.Value && element.Mapping.TypeDesc.IsValueType) + if (element.Default != null && element.Default != DBNull.Value && element.Mapping.TypeDesc!.IsValueType) { MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_get_IsEmptyElement = typeof(XmlReader).GetMethod( "get_IsEmptyElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_IsEmptyElement); @@ -3053,7 +3054,7 @@ private void WriteElement(string source, string arrayName, string choiceSource, "Skip", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_Skip); @@ -3064,18 +3065,18 @@ private void WriteElement(string source, string arrayName, string choiceSource, { } - if (element.Mapping.TypeDesc.Type == typeof(TimeSpan)) + if (element.Mapping.TypeDesc!.Type == typeof(TimeSpan)) { MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_get_IsEmptyElement = typeof(XmlReader).GetMethod( "get_IsEmptyElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_IsEmptyElement); @@ -3085,7 +3086,7 @@ private void WriteElement(string source, string arrayName, string choiceSource, "Skip", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_Skip); @@ -3094,7 +3095,7 @@ private void WriteElement(string source, string arrayName, string choiceSource, null, new Type[] { typeof(long) }, null - ); + )!; ilg.Ldc(default(TimeSpan).Ticks); ilg.New(TimeSpan_ctor); WriteSourceEnd(source, element.Mapping.TypeDesc.Type); @@ -3113,7 +3114,7 @@ private void WriteElement(string source, string arrayName, string choiceSource, "ReadElementQualifiedName", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_ReadElementQualifiedName); } @@ -3133,7 +3134,7 @@ private void WriteElement(string source, string arrayName, string choiceSource, WritePrimitive(element.Mapping, readFunc); } - WriteSourceEnd(source, element.Mapping.TypeDesc.Type); + WriteSourceEnd(source, element.Mapping.TypeDesc.Type!); } if (doEndIf) @@ -3142,10 +3143,10 @@ private void WriteElement(string source, string arrayName, string choiceSource, else if (element.Mapping is StructMapping) { TypeMapping mapping = element.Mapping; - string methodName = ReferenceMapping(mapping); + string? methodName = ReferenceMapping(mapping); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe - if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc.Name)); + if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc!.Name)); #endif if (checkForNull) @@ -3154,13 +3155,13 @@ private void WriteElement(string source, string arrayName, string choiceSource, "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_Skip = typeof(XmlReader).GetMethod( "Skip", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); - ilg.Ldloc(arrayName); + )!; + ilg.Ldloc(arrayName!); ilg.Load(null); ilg.If(Cmp.EqualTo); ilg.Ldarg(0); @@ -3171,7 +3172,7 @@ private void WriteElement(string source, string arrayName, string choiceSource, WriteSourceBegin(source); List argTypes = new List(); ilg.Ldarg(0); - if (mapping.TypeDesc.IsNullable) + if (mapping.TypeDesc!.IsNullable) { ilg.Load(element.IsNullable); argTypes.Add(typeof(bool)); @@ -3179,13 +3180,13 @@ private void WriteElement(string source, string arrayName, string choiceSource, ilg.Ldc(true); argTypes.Add(typeof(bool)); MethodBuilder methodBuilder = EnsureMethodBuilder(typeBuilder, - methodName, + methodName!, CodeGenerator.PrivateMethodAttributes, mapping.TypeDesc.Type, argTypes.ToArray() ); ilg.Call(methodBuilder); - WriteSourceEnd(source, mapping.TypeDesc.Type); + WriteSourceEnd(source, mapping.TypeDesc.Type!); if (checkForNull) // 'If' begins in checkForNull above ilg.EndIf(); @@ -3193,7 +3194,7 @@ private void WriteElement(string source, string arrayName, string choiceSource, else if (element.Mapping is SpecialMapping) { SpecialMapping special = (SpecialMapping)element.Mapping; - switch (special.TypeDesc.Kind) + switch (special.TypeDesc!.Kind) { case TypeKind.Node: bool isDoc = special.TypeDesc.FullName == typeof(XmlDocument).FullName; @@ -3202,14 +3203,14 @@ private void WriteElement(string source, string arrayName, string choiceSource, isDoc ? "ReadXmlDocument" : "ReadXmlNode", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(bool) } - ); + )!; ilg.Ldarg(0); ilg.Ldc(element.Any ? false : true); ilg.Call(XmlSerializationReader_ReadXmlXXX); // See logic in WriteSourceBeginTyped whether or not to castclass. if (special.TypeDesc != null) - ilg.Castclass(special.TypeDesc.Type); - WriteSourceEnd(source, special.TypeDesc.Type); + ilg.Castclass(special.TypeDesc.Type!); + WriteSourceEnd(source, special.TypeDesc!.Type!); break; case TypeKind.Serializable: SerializableMapping sm = (SerializableMapping)element.Mapping; @@ -3220,7 +3221,7 @@ private void WriteElement(string source, string arrayName, string choiceSource, "GetXsiType", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; Label labelTrue = ilg.DefineLabel(); Label labelEnd = ilg.DefineLabel(); LocalBuilder tserLoc = ilg.DeclareOrGetLocal(typeof(XmlQualifiedName), "tser"); @@ -3231,7 +3232,7 @@ private void WriteElement(string source, string arrayName, string choiceSource, ilg.Load(null); ilg.Ceq(); ilg.Brtrue(labelTrue); - WriteQNameEqual("tser", sm.XsiType.Name, sm.XsiType.Namespace); + WriteQNameEqual("tser", sm.XsiType!.Name, sm.XsiType.Namespace); ilg.Br_S(labelEnd); ilg.MarkLabel(labelTrue); @@ -3239,15 +3240,15 @@ private void WriteElement(string source, string arrayName, string choiceSource, ilg.MarkLabel(labelEnd); ilg.If(); } - WriteSourceBeginTyped(source, sm.TypeDesc); + WriteSourceBeginTyped(source, sm.TypeDesc!); bool isWrappedAny = !element.Any && IsWildcard(sm); MethodInfo XmlSerializationReader_ReadSerializable = typeof(XmlSerializationReader).GetMethod( "ReadSerializable", CodeGenerator.InstanceBindingFlags, isWrappedAny ? new Type[] { typeof(IXmlSerializable), typeof(bool) } : new Type[] { typeof(IXmlSerializable) } - ); + )!; ilg.Ldarg(0); - RaCodeGen.ILGenForCreateInstance(ilg, sm.TypeDesc.Type, sm.TypeDesc.CannotNew, false); + RaCodeGen.ILGenForCreateInstance(ilg, sm.TypeDesc!.Type!, sm.TypeDesc.CannotNew, false); if (sm.TypeDesc.CannotNew) ilg.ConvertValue(typeof(object), typeof(IXmlSerializable)); if (isWrappedAny) @@ -3255,8 +3256,8 @@ private void WriteElement(string source, string arrayName, string choiceSource, ilg.Call(XmlSerializationReader_ReadSerializable); // See logic in WriteSourceBeginTyped whether or not to castclass. if (sm.TypeDesc != null) - ilg.ConvertValue(typeof(IXmlSerializable), sm.TypeDesc.Type); - WriteSourceEnd(source, sm.TypeDesc.Type); + ilg.ConvertValue(typeof(IXmlSerializable), sm.TypeDesc.Type!); + WriteSourceEnd(source, sm.TypeDesc!.Type!); if (sm.DerivedMappings != null) { WriteDerivedSerializable(sm, sm, source, isWrappedAny); @@ -3278,18 +3279,18 @@ private void WriteElement(string source, string arrayName, string choiceSource, if (choiceSource == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, "need parent for the " + source)); #endif - WriteSourceBegin(choiceSource); - CodeIdentifier.CheckValidIdentifier(choice.MemberIds[elementIndex]); - RaCodeGen.ILGenForEnumMember(ilg, choice.Mapping.TypeDesc.Type, choice.MemberIds[elementIndex]); - WriteSourceEnd(choiceSource, choice.Mapping.TypeDesc.Type); + WriteSourceBegin(choiceSource!); + CodeIdentifier.CheckValidIdentifier(choice.MemberIds![elementIndex]); + RaCodeGen.ILGenForEnumMember(ilg, choice.Mapping!.TypeDesc!.Type!, choice.MemberIds[elementIndex]); + WriteSourceEnd(choiceSource!, choice.Mapping.TypeDesc.Type!); } } - private void WriteDerivedSerializable(SerializableMapping head, SerializableMapping mapping, string source, bool isWrappedAny) + private void WriteDerivedSerializable(SerializableMapping head, SerializableMapping? mapping, string source, bool isWrappedAny) { if (mapping == null) return; - for (SerializableMapping derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) + for (SerializableMapping? derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) { Label labelTrue = ilg.DefineLabel(); Label labelEnd = ilg.DefineLabel(); @@ -3299,7 +3300,7 @@ private void WriteDerivedSerializable(SerializableMapping head, SerializableMapp ilg.Load(null); ilg.Ceq(); ilg.Brtrue(labelTrue); - WriteQNameEqual("tser", derived.XsiType.Name, derived.XsiType.Namespace); + WriteQNameEqual("tser", derived.XsiType!.Name, derived.XsiType.Namespace); ilg.Br_S(labelEnd); ilg.MarkLabel(labelTrue); @@ -3309,16 +3310,16 @@ private void WriteDerivedSerializable(SerializableMapping head, SerializableMapp if (derived.Type != null) { - if (head.Type.IsAssignableFrom(derived.Type)) + if (head.Type!.IsAssignableFrom(derived.Type)) { - WriteSourceBeginTyped(source, head.TypeDesc); + WriteSourceBeginTyped(source, head.TypeDesc!); MethodInfo XmlSerializationReader_ReadSerializable = typeof(XmlSerializationReader).GetMethod( "ReadSerializable", CodeGenerator.InstanceBindingFlags, isWrappedAny ? new Type[] { typeof(IXmlSerializable), typeof(bool) } : new Type[] { typeof(IXmlSerializable) } - ); + )!; ilg.Ldarg(0); - RaCodeGen.ILGenForCreateInstance(ilg, derived.TypeDesc.Type, derived.TypeDesc.CannotNew, false); + RaCodeGen.ILGenForCreateInstance(ilg, derived.TypeDesc!.Type!, derived.TypeDesc.CannotNew, false); if (derived.TypeDesc.CannotNew) ilg.ConvertValue(typeof(object), typeof(IXmlSerializable)); if (isWrappedAny) @@ -3326,8 +3327,8 @@ private void WriteDerivedSerializable(SerializableMapping head, SerializableMapp ilg.Call(XmlSerializationReader_ReadSerializable); // See logic in WriteSourceBeginTyped whether or not to castclass. if (head.TypeDesc != null) - ilg.ConvertValue(typeof(IXmlSerializable), head.TypeDesc.Type); - WriteSourceEnd(source, head.TypeDesc.Type); + ilg.ConvertValue(typeof(IXmlSerializable), head.TypeDesc.Type!); + WriteSourceEnd(source, head.TypeDesc!.Type!); } else { @@ -3335,11 +3336,11 @@ private void WriteDerivedSerializable(SerializableMapping head, SerializableMapp "CreateBadDerivationException", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string), typeof(string), typeof(string), typeof(string), typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Ldstr(GetCSharpString(derived.XsiType.Name)); ilg.Ldstr(GetCSharpString(derived.XsiType.Namespace)); - ilg.Ldstr(GetCSharpString(head.XsiType.Name)); + ilg.Ldstr(GetCSharpString(head.XsiType!.Name)); ilg.Ldstr(GetCSharpString(head.XsiType.Namespace)); ilg.Ldstr(GetCSharpString(derived.Type.FullName)); ilg.Ldstr(GetCSharpString(head.Type.FullName)); @@ -3353,11 +3354,11 @@ private void WriteDerivedSerializable(SerializableMapping head, SerializableMapp "CreateMissingIXmlSerializableType", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string), typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Ldstr(GetCSharpString(derived.XsiType.Name)); ilg.Ldstr(GetCSharpString(derived.XsiType.Namespace)); - ilg.Ldstr(GetCSharpString(head.Type.FullName)); + ilg.Ldstr(GetCSharpString(head.Type!.FullName)); ilg.Call(XmlSerializationReader_CreateMissingIXmlSerializableType); ilg.Throw(); } @@ -3373,12 +3374,12 @@ private void WriteWhileNotLoopStart() "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_MoveToContent = typeof(XmlReader).GetMethod( "MoveToContent", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_MoveToContent); @@ -3398,12 +3399,12 @@ private void WriteWhileLoopEnd() "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_get_NodeType = typeof(XmlReader).GetMethod( "get_NodeType", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; Label labelFalse = ilg.DefineLabel(); Label labelEnd = ilg.DefineLabel(); ilg.Ldarg(0); @@ -3434,18 +3435,18 @@ private void WriteParamsRead(int length) private void WriteCreateMapping(TypeMapping mapping, string local) { - string fullTypeName = mapping.TypeDesc.CSharpName; + string fullTypeName = mapping.TypeDesc!.CSharpName; bool ctorInaccessible = mapping.TypeDesc.CannotNew; LocalBuilder loc = ilg.DeclareLocal( - mapping.TypeDesc.Type, + mapping.TypeDesc.Type!, local); if (ctorInaccessible) { ilg.BeginExceptionBlock(); } - RaCodeGen.ILGenForCreateInstance(ilg, mapping.TypeDesc.Type, mapping.TypeDesc.CannotNew, true); + RaCodeGen.ILGenForCreateInstance(ilg, mapping.TypeDesc.Type!, mapping.TypeDesc.CannotNew, true); ilg.Stloc(loc); if (ctorInaccessible) { @@ -3455,7 +3456,7 @@ private void WriteCreateMapping(TypeMapping mapping, string local) "CreateInaccessibleConstructorException", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Ldstr(GetCSharpString(fullTypeName)); ilg.Call(XmlSerializationReader_CreateInaccessibleConstructorException); @@ -3466,7 +3467,7 @@ private void WriteCreateMapping(TypeMapping mapping, string local) "CreateCtorHasSecurityException", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Ldstr(GetCSharpString(fullTypeName)); ilg.Call(XmlSerializationReader_CreateCtorHasSecurityException); @@ -3500,12 +3501,12 @@ private void ILGenElseString(string elseString) "UnknownNode", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(object) } - ); + )!; MethodInfo XmlSerializationReader_UnknownNode2 = typeof(XmlSerializationReader).GetMethod( "UnknownNode", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(object), typeof(string) } - ); + )!; // UnknownNode(null, @":anyType"); Regex regex = NewRegex("UnknownNode[(]null, @[\"](?[^\"]*)[\"][)];"); Match match = regex.Match(elseString); @@ -3587,7 +3588,7 @@ private void ILGenElementElseString(string elementElseString) "CreateUnknownNodeException", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_CreateUnknownNodeException); ilg.Throw(); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs index 0cfe356e676f5f..50a1632df0678d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; @@ -18,26 +19,27 @@ namespace System.Xml.Serialization using System.Collections.Generic; using System.Xml.Serialization; using System.Xml; + using System.Diagnostics.CodeAnalysis; /// public abstract class XmlSerializationWriter : XmlSerializationGeneratedCode { - private XmlWriter _w; - private XmlSerializerNamespaces _namespaces; + private XmlWriter _w = null!; + private XmlSerializerNamespaces? _namespaces; private int _tempNamespacePrefix; - private HashSet _usedPrefixes; - private Hashtable _references; - private string _idBase; + private HashSet? _usedPrefixes; + private Hashtable? _references; + private string? _idBase; private int _nextId; - private Hashtable _typeEntries; - private ArrayList _referencesToWrite; - private Hashtable _objectsInUse; + private Hashtable? _typeEntries; + private ArrayList? _referencesToWrite; + private Hashtable? _objectsInUse; private readonly string _aliasBase = "q"; private bool _soap12; private bool _escapeName = true; // this method must be called before any generated serialization methods are called - internal void Init(XmlWriter w, XmlSerializerNamespaces namespaces, string encodingStyle, string idBase, TempAssembly tempAssembly) + internal void Init(XmlWriter w, XmlSerializerNamespaces? namespaces, string? encodingStyle, string? idBase, TempAssembly? tempAssembly) { _w = w; _namespaces = namespaces; @@ -73,7 +75,7 @@ protected XmlWriter Writer /// /// [To be supplied.] /// - protected ArrayList Namespaces + protected ArrayList? Namespaces { get { @@ -103,12 +105,13 @@ protected static byte[] FromByteArrayBase64(byte[] value) } /// - protected static Assembly ResolveDynamicAssembly(string assemblyFullName) + protected static Assembly? ResolveDynamicAssembly(string assemblyFullName) { return DynamicAssemblies.Get(assemblyFullName); } - protected static string FromByteArrayHex(byte[] value) + [return: NotNullIfNotNull("value")] + protected static string? FromByteArrayHex(byte[]? value) { return XmlCustomFormatter.FromByteArrayHex(value); } @@ -143,45 +146,49 @@ protected static string FromEnum(long value, string[] values, long[] ids, string return XmlCustomFormatter.FromEnum(value, values, ids, typeName); } - protected static string FromXmlName(string name) + [return: NotNullIfNotNull("name")] + protected static string? FromXmlName(string? name) { return XmlCustomFormatter.FromXmlName(name); } - protected static string FromXmlNCName(string ncName) + [return: NotNullIfNotNull("ncName")] + protected static string? FromXmlNCName(string? ncName) { return XmlCustomFormatter.FromXmlNCName(ncName); } - protected static string FromXmlNmToken(string nmToken) + [return: NotNullIfNotNull("nmToken")] + protected static string? FromXmlNmToken(string? nmToken) { return XmlCustomFormatter.FromXmlNmToken(nmToken); } - protected static string FromXmlNmTokens(string nmTokens) + [return: NotNullIfNotNull("nmTokens")] + protected static string? FromXmlNmTokens(string? nmTokens) { return XmlCustomFormatter.FromXmlNmTokens(nmTokens); } - protected void WriteXsiType(string name, string ns) + protected void WriteXsiType(string name, string? ns) { WriteAttribute("type", XmlSchema.InstanceNamespace, GetQualifiedName(name, ns)); } private XmlQualifiedName GetPrimitiveTypeName(Type type) { - return GetPrimitiveTypeName(type, true); + return GetPrimitiveTypeName(type, true)!; } - private XmlQualifiedName GetPrimitiveTypeName(Type type, bool throwIfUnknown) + private XmlQualifiedName? GetPrimitiveTypeName(Type type, bool throwIfUnknown) { - XmlQualifiedName qname = GetPrimitiveTypeNameInternal(type); + XmlQualifiedName? qname = GetPrimitiveTypeNameInternal(type); if (throwIfUnknown && qname == null) throw CreateUnknownTypeException(type); return qname; } - internal static XmlQualifiedName GetPrimitiveTypeNameInternal(Type type) + internal static XmlQualifiedName? GetPrimitiveTypeNameInternal(Type type) { string typeName; string typeNs = XmlSchema.Namespace; @@ -230,9 +237,9 @@ internal static XmlQualifiedName GetPrimitiveTypeNameInternal(Type type) return new XmlQualifiedName(typeName, typeNs); } - protected void WriteTypedPrimitive(string name, string ns, object o, bool xsiType) + protected void WriteTypedPrimitive(string? name, string? ns, object o, bool xsiType) { - string value = null; + string? value = null; string type; string typeNs = XmlSchema.Namespace; bool writeRaw = true; @@ -385,10 +392,10 @@ protected void WriteTypedPrimitive(string name, string ns, object o, bool xsiTyp _w.WriteEndElement(); } - private string GetQualifiedName(string name, string ns) + private string GetQualifiedName(string name, string? ns) { if (ns == null || ns.Length == 0) return name; - string prefix = _w.LookupPrefix(ns); + string? prefix = _w.LookupPrefix(ns); if (prefix == null) { if (ns == XmlReservedNs.NsXml) @@ -408,12 +415,12 @@ private string GetQualifiedName(string name, string ns) return prefix + ":" + name; } - protected string FromXmlQualifiedName(XmlQualifiedName xmlQualifiedName) + protected string? FromXmlQualifiedName(XmlQualifiedName? xmlQualifiedName) { return FromXmlQualifiedName(xmlQualifiedName, true); } - protected string FromXmlQualifiedName(XmlQualifiedName xmlQualifiedName, bool ignoreEmpty) + protected string? FromXmlQualifiedName(XmlQualifiedName? xmlQualifiedName, bool ignoreEmpty) { if (xmlQualifiedName == null) return null; if (xmlQualifiedName.IsEmpty && ignoreEmpty) return null; @@ -425,27 +432,27 @@ protected void WriteStartElement(string name) WriteStartElement(name, null, null, false, null); } - protected void WriteStartElement(string name, string ns) + protected void WriteStartElement(string name, string? ns) { WriteStartElement(name, ns, null, false, null); } - protected void WriteStartElement(string name, string ns, bool writePrefixed) + protected void WriteStartElement(string name, string? ns, bool writePrefixed) { WriteStartElement(name, ns, null, writePrefixed, null); } - protected void WriteStartElement(string name, string ns, object o) + protected void WriteStartElement(string name, string? ns, object? o) { WriteStartElement(name, ns, o, false, null); } - protected void WriteStartElement(string name, string ns, object o, bool writePrefixed) + protected void WriteStartElement(string name, string? ns, object? o, bool writePrefixed) { WriteStartElement(name, ns, o, writePrefixed, null); } - protected void WriteStartElement(string name, string ns, object o, bool writePrefixed, XmlSerializerNamespaces xmlns) + protected void WriteStartElement(string name, string? ns, object? o, bool writePrefixed, XmlSerializerNamespaces? xmlns) { if (o != null && _objectsInUse != null) { @@ -453,13 +460,13 @@ protected void WriteStartElement(string name, string ns, object o, bool writePre _objectsInUse.Add(o, o); } - string prefix = null; + string? prefix = null; bool needEmptyDefaultNamespace = false; if (_namespaces != null) { foreach (string alias in _namespaces.Namespaces.Keys) { - string aliasNs = (string)_namespaces.Namespaces[alias]; + string? aliasNs = (string?)_namespaces.Namespaces[alias]; if (alias.Length > 0 && aliasNs == ns) prefix = alias; @@ -492,7 +499,7 @@ protected void WriteStartElement(string name, string ns, object o, bool writePre { foreach (string alias in _namespaces.Namespaces.Keys) { - string aliasNs = (string)_namespaces.Namespaces[alias]; + string? aliasNs = (string?)_namespaces.Namespaces[alias]; if (alias.Length == 0 && (aliasNs == null || aliasNs.Length == 0)) continue; if (aliasNs == null || aliasNs.Length == 0) @@ -516,12 +523,12 @@ protected void WriteStartElement(string name, string ns, object o, bool writePre WriteNamespaceDeclarations(xmlns); } - private HashSet ListUsedPrefixes(Dictionary nsList, string prefix) + private HashSet? ListUsedPrefixes(Dictionary? nsList, string prefix) { var qnIndexes = new HashSet(); int prefixLength = prefix.Length; const string MaxInt32 = "2147483647"; - foreach (string alias in _namespaces.Namespaces.Keys) + foreach (string alias in _namespaces!.Namespaces.Keys) { string name; if (alias.Length > prefixLength) @@ -557,12 +564,12 @@ private HashSet ListUsedPrefixes(Dictionary nsList, string return null; } - protected void WriteNullTagEncoded(string name) + protected void WriteNullTagEncoded(string? name) { WriteNullTagEncoded(name, null); } - protected void WriteNullTagEncoded(string name, string ns) + protected void WriteNullTagEncoded(string? name, string? ns) { if (name == null || name.Length == 0) return; @@ -571,12 +578,12 @@ protected void WriteNullTagEncoded(string name, string ns) _w.WriteEndElement(); } - protected void WriteNullTagLiteral(string name) + protected void WriteNullTagLiteral(string? name) { WriteNullTagLiteral(name, null); } - protected void WriteNullTagLiteral(string name, string ns) + protected void WriteNullTagLiteral(string? name, string? ns) { if (name == null || name.Length == 0) return; @@ -585,12 +592,12 @@ protected void WriteNullTagLiteral(string name, string ns) _w.WriteEndElement(); } - protected void WriteEmptyTag(string name) + protected void WriteEmptyTag(string? name) { WriteEmptyTag(name, null); } - protected void WriteEmptyTag(string name, string ns) + protected void WriteEmptyTag(string? name, string? ns) { if (name == null || name.Length == 0) return; @@ -603,7 +610,7 @@ protected void WriteEndElement() _w.WriteEndElement(); } - protected void WriteEndElement(object o) + protected void WriteEndElement(object? o) { _w.WriteEndElement(); @@ -618,12 +625,12 @@ protected void WriteEndElement(object o) } } - protected void WriteSerializable(IXmlSerializable serializable, string name, string ns, bool isNullable) + protected void WriteSerializable(IXmlSerializable? serializable, string name, string ns, bool isNullable) { WriteSerializable(serializable, name, ns, isNullable, true); } - protected void WriteSerializable(IXmlSerializable serializable, string name, string ns, bool isNullable, bool wrapped) + protected void WriteSerializable(IXmlSerializable? serializable, string name, string? ns, bool isNullable, bool wrapped) { if (serializable == null) { @@ -641,7 +648,7 @@ protected void WriteSerializable(IXmlSerializable serializable, string name, str } } - protected void WriteNullableStringEncoded(string name, string ns, string value, XmlQualifiedName xsiType) + protected void WriteNullableStringEncoded(string name, string? ns, string? value, XmlQualifiedName? xsiType) { if (value == null) WriteNullTagEncoded(name, ns); @@ -649,7 +656,7 @@ protected void WriteNullableStringEncoded(string name, string ns, string value, WriteElementString(name, ns, value, xsiType); } - protected void WriteNullableStringLiteral(string name, string ns, string value) + protected void WriteNullableStringLiteral(string name, string? ns, string? value) { if (value == null) WriteNullTagLiteral(name, ns); @@ -658,7 +665,7 @@ protected void WriteNullableStringLiteral(string name, string ns, string value) } - protected void WriteNullableStringEncodedRaw(string name, string ns, string value, XmlQualifiedName xsiType) + protected void WriteNullableStringEncodedRaw(string name, string? ns, string? value, XmlQualifiedName? xsiType) { if (value == null) WriteNullTagEncoded(name, ns); @@ -666,7 +673,7 @@ protected void WriteNullableStringEncodedRaw(string name, string ns, string valu WriteElementStringRaw(name, ns, value, xsiType); } - protected void WriteNullableStringEncodedRaw(string name, string ns, byte[] value, XmlQualifiedName xsiType) + protected void WriteNullableStringEncodedRaw(string name, string? ns, byte[]? value, XmlQualifiedName? xsiType) { if (value == null) WriteNullTagEncoded(name, ns); @@ -674,7 +681,7 @@ protected void WriteNullableStringEncodedRaw(string name, string ns, byte[] valu WriteElementStringRaw(name, ns, value, xsiType); } - protected void WriteNullableStringLiteralRaw(string name, string ns, string value) + protected void WriteNullableStringLiteralRaw(string name, string? ns, string? value) { if (value == null) WriteNullTagLiteral(name, ns); @@ -682,7 +689,7 @@ protected void WriteNullableStringLiteralRaw(string name, string ns, string valu WriteElementStringRaw(name, ns, value, null); } - protected void WriteNullableStringLiteralRaw(string name, string ns, byte[] value) + protected void WriteNullableStringLiteralRaw(string name, string? ns, byte[]? value) { if (value == null) WriteNullTagLiteral(name, ns); @@ -693,7 +700,7 @@ protected void WriteNullableStringLiteralRaw(string name, string ns, byte[] valu /// /// [To be supplied.] /// - protected void WriteNullableQualifiedNameEncoded(string name, string ns, XmlQualifiedName value, XmlQualifiedName xsiType) + protected void WriteNullableQualifiedNameEncoded(string name, string? ns, XmlQualifiedName? value, XmlQualifiedName? xsiType) { if (value == null) WriteNullTagEncoded(name, ns); @@ -704,7 +711,7 @@ protected void WriteNullableQualifiedNameEncoded(string name, string ns, XmlQual /// /// [To be supplied.] /// - protected void WriteNullableQualifiedNameLiteral(string name, string ns, XmlQualifiedName value) + protected void WriteNullableQualifiedNameLiteral(string name, string? ns, XmlQualifiedName? value) { if (value == null) WriteNullTagLiteral(name, ns); @@ -713,7 +720,7 @@ protected void WriteNullableQualifiedNameLiteral(string name, string ns, XmlQual } - protected void WriteElementEncoded(XmlNode node, string name, string ns, bool isNullable, bool any) + protected void WriteElementEncoded(XmlNode? node, string name, string? ns, bool isNullable, bool any) { if (node == null) { @@ -723,7 +730,7 @@ protected void WriteElementEncoded(XmlNode node, string name, string ns, bool is WriteElement(node, name, ns, isNullable, any); } - protected void WriteElementLiteral(XmlNode node, string name, string ns, bool isNullable, bool any) + protected void WriteElementLiteral(XmlNode? node, string name, string? ns, bool isNullable, bool any) { if (node == null) { @@ -733,13 +740,13 @@ protected void WriteElementLiteral(XmlNode node, string name, string ns, bool is WriteElement(node, name, ns, isNullable, any); } - private void WriteElement(XmlNode node, string name, string ns, bool isNullable, bool any) + private void WriteElement(XmlNode node, string name, string? ns, bool isNullable, bool any) { if (typeof(XmlAttribute).IsAssignableFrom(node.GetType())) throw new InvalidOperationException(SR.XmlNoAttributeHere); if (node is XmlDocument) { - node = ((XmlDocument)node).DocumentElement; + node = ((XmlDocument)node).DocumentElement!; if (node == null) { if (isNullable) WriteNullTagEncoded(name, ns); @@ -814,23 +821,25 @@ protected Exception CreateInvalidAnyTypeException(Type type) return new InvalidOperationException(SR.Format(SR.XmlIllegalAnyElement, type.FullName)); } - protected void WriteReferencingElement(string n, string ns, object o) + protected void WriteReferencingElement(string n, string? ns, object? o) { WriteReferencingElement(n, ns, o, false); } - protected void WriteReferencingElement(string n, string ns, object o, bool isNullable) + protected void WriteReferencingElement(string n, string? ns, object? o, bool isNullable) { if (o == null) { if (isNullable) WriteNullTagEncoded(n, ns); return; } + WriteStartElement(n, ns, null, true); if (_soap12) _w.WriteAttributeString("ref", Soap12.Encoding, GetId(o, true)); else _w.WriteAttributeString("href", "#" + GetId(o, true)); + _w.WriteEndElement(); } @@ -847,12 +856,12 @@ private string GetId(object o, bool addToReferencesList) _references = new Hashtable(); _referencesToWrite = new ArrayList(); } - string id = (string)_references[o]; + string? id = (string?)_references[o]; if (id == null) { id = _idBase + "id" + (++_nextId).ToString(CultureInfo.InvariantCulture); _references.Add(o, id); - if (addToReferencesList) _referencesToWrite.Add(o); + if (addToReferencesList) _referencesToWrite!.Add(o); } return id; } @@ -875,9 +884,9 @@ protected void WriteXmlAttribute(XmlNode node) WriteXmlAttribute(node, null); } - protected void WriteXmlAttribute(XmlNode node, object container) + protected void WriteXmlAttribute(XmlNode node, object? container) { - XmlAttribute attr = node as XmlAttribute; + XmlAttribute? attr = node as XmlAttribute; if (attr == null) throw new InvalidOperationException(SR.XmlNeedAttributeHere); if (attr.Value != null) { @@ -886,7 +895,7 @@ protected void WriteXmlAttribute(XmlNode node, object container) string dims; XmlQualifiedName qname = TypeScope.ParseWsdlArrayType(attr.Value, out dims, (container is XmlSchemaObject) ? (XmlSchemaObject)container : null); - string value = FromXmlQualifiedName(qname, true) + dims; + string? value = FromXmlQualifiedName(qname, true) + dims; // WriteAttribute(Wsdl.ArrayType, Wsdl.Namespace, value); @@ -898,7 +907,7 @@ protected void WriteXmlAttribute(XmlNode node, object container) } } - protected void WriteAttribute(string localName, string ns, string value) + protected void WriteAttribute(string localName, string? ns, string? value) { if (value == null) return; if (localName == "xmlns" || localName.StartsWith("xmlns:", StringComparison.Ordinal)) @@ -912,7 +921,7 @@ protected void WriteAttribute(string localName, string ns, string value) { if (ns == XmlReservedNs.NsXml) { - string prefix = _w.LookupPrefix(ns); + string? prefix = _w.LookupPrefix(ns); if (prefix == null || prefix.Length == 0) prefix = "xml"; _w.WriteAttributeString(prefix, localName, ns, value); @@ -930,7 +939,7 @@ protected void WriteAttribute(string localName, string ns, string value) } } - protected void WriteAttribute(string localName, string ns, byte[] value) + protected void WriteAttribute(string localName, string ns, byte[]? value) { if (value == null) return; if (localName == "xmlns" || localName.StartsWith("xmlns:", StringComparison.Ordinal)) @@ -944,7 +953,7 @@ protected void WriteAttribute(string localName, string ns, byte[] value) { if (ns == XmlReservedNs.NsXml) { - string prefix = _w.LookupPrefix(ns); + string? prefix = _w.LookupPrefix(ns); if (prefix == null || prefix.Length == 0) prefix = "xml"; _w.WriteStartAttribute("xml", localName, ns); @@ -956,7 +965,7 @@ protected void WriteAttribute(string localName, string ns, byte[] value) } else { - string prefix = _w.LookupPrefix(ns); + string? prefix = _w.LookupPrefix(ns); _w.WriteStartAttribute(prefix, localName.Substring(colon + 1), ns); } XmlCustomFormatter.WriteArrayBase64(_w, value, 0, value.Length); @@ -964,34 +973,34 @@ protected void WriteAttribute(string localName, string ns, byte[] value) } } - protected void WriteAttribute(string localName, string value) + protected void WriteAttribute(string localName, string? value) { if (value == null) return; _w.WriteAttributeString(localName, null, value); } - protected void WriteAttribute(string localName, byte[] value) + protected void WriteAttribute(string localName, byte[]? value) { if (value == null) return; - _w.WriteStartAttribute(null, localName, (string)null); + _w.WriteStartAttribute(null, localName, (string?)null); XmlCustomFormatter.WriteArrayBase64(_w, value, 0, value.Length); _w.WriteEndAttribute(); } - protected void WriteAttribute(string prefix, string localName, string ns, string value) + protected void WriteAttribute(string? prefix, string localName, string? ns, string? value) { if (value == null) return; _w.WriteAttributeString(prefix, localName, null, value); } - protected void WriteValue(string value) + protected void WriteValue(string? value) { if (value == null) return; _w.WriteString(value); } - protected void WriteValue(byte[] value) + protected void WriteValue(byte[]? value) { if (value == null) return; XmlCustomFormatter.WriteArrayBase64(_w, value, 0, value.Length); @@ -1005,22 +1014,22 @@ protected void WriteStartDocument() } } - protected void WriteElementString(string localName, string value) + protected void WriteElementString(string localName, string? value) { WriteElementString(localName, null, value, null); } - protected void WriteElementString(string localName, string ns, string value) + protected void WriteElementString(string localName, string? ns, string? value) { WriteElementString(localName, ns, value, null); } - protected void WriteElementString(string localName, string value, XmlQualifiedName xsiType) + protected void WriteElementString(string localName, string? value, XmlQualifiedName? xsiType) { WriteElementString(localName, null, value, xsiType); } - protected void WriteElementString(string localName, string ns, string value, XmlQualifiedName xsiType) + protected void WriteElementString(string localName, string? ns, string? value, XmlQualifiedName? xsiType) { if (value == null) return; if (xsiType == null) @@ -1034,37 +1043,37 @@ protected void WriteElementString(string localName, string ns, string value, Xml } } - protected void WriteElementStringRaw(string localName, string value) + protected void WriteElementStringRaw(string localName, string? value) { WriteElementStringRaw(localName, null, value, null); } - protected void WriteElementStringRaw(string localName, byte[] value) + protected void WriteElementStringRaw(string localName, byte[]? value) { WriteElementStringRaw(localName, null, value, null); } - protected void WriteElementStringRaw(string localName, string ns, string value) + protected void WriteElementStringRaw(string localName, string? ns, string? value) { WriteElementStringRaw(localName, ns, value, null); } - protected void WriteElementStringRaw(string localName, string ns, byte[] value) + protected void WriteElementStringRaw(string localName, string? ns, byte[]? value) { WriteElementStringRaw(localName, ns, value, null); } - protected void WriteElementStringRaw(string localName, string value, XmlQualifiedName xsiType) + protected void WriteElementStringRaw(string localName, string? value, XmlQualifiedName? xsiType) { WriteElementStringRaw(localName, null, value, xsiType); } - protected void WriteElementStringRaw(string localName, byte[] value, XmlQualifiedName xsiType) + protected void WriteElementStringRaw(string localName, byte[]? value, XmlQualifiedName? xsiType) { WriteElementStringRaw(localName, null, value, xsiType); } - protected void WriteElementStringRaw(string localName, string ns, string value, XmlQualifiedName xsiType) + protected void WriteElementStringRaw(string localName, string? ns, string? value, XmlQualifiedName? xsiType) { if (value == null) return; _w.WriteStartElement(localName, ns); @@ -1074,7 +1083,7 @@ protected void WriteElementStringRaw(string localName, string ns, string value, _w.WriteEndElement(); } - protected void WriteElementStringRaw(string localName, string ns, byte[] value, XmlQualifiedName xsiType) + protected void WriteElementStringRaw(string localName, string? ns, byte[]? value, XmlQualifiedName? xsiType) { if (value == null) return; _w.WriteStartElement(localName, ns); @@ -1084,7 +1093,7 @@ protected void WriteElementStringRaw(string localName, string ns, byte[] value, _w.WriteEndElement(); } - protected void WriteRpcResult(string name, string ns) + protected void WriteRpcResult(string name, string? ns) { if (!_soap12) return; WriteElementQualifiedName(Soap12.RpcResult, Soap12.RpcNamespace, new XmlQualifiedName(name, ns), null); @@ -1093,12 +1102,12 @@ protected void WriteRpcResult(string name, string ns) /// /// [To be supplied.] /// - protected void WriteElementQualifiedName(string localName, XmlQualifiedName value) + protected void WriteElementQualifiedName(string localName, XmlQualifiedName? value) { WriteElementQualifiedName(localName, null, value, null); } - protected void WriteElementQualifiedName(string localName, XmlQualifiedName value, XmlQualifiedName xsiType) + protected void WriteElementQualifiedName(string localName, XmlQualifiedName? value, XmlQualifiedName? xsiType) { WriteElementQualifiedName(localName, null, value, xsiType); } @@ -1106,12 +1115,12 @@ protected void WriteElementQualifiedName(string localName, XmlQualifiedName valu /// /// [To be supplied.] /// - protected void WriteElementQualifiedName(string localName, string ns, XmlQualifiedName value) + protected void WriteElementQualifiedName(string localName, string? ns, XmlQualifiedName? value) { WriteElementQualifiedName(localName, ns, value, null); } - protected void WriteElementQualifiedName(string localName, string ns, XmlQualifiedName value, XmlQualifiedName xsiType) + protected void WriteElementQualifiedName(string localName, string? ns, XmlQualifiedName? value, XmlQualifiedName? xsiType) { if (value == null) return; if (value.Namespace == null || value.Namespace.Length == 0) @@ -1127,28 +1136,28 @@ protected void WriteElementQualifiedName(string localName, string ns, XmlQualifi _w.WriteEndElement(); } - protected void AddWriteCallback(Type type, string typeName, string typeNs, XmlSerializationWriteCallback callback) + protected void AddWriteCallback(Type type, string typeName, string? typeNs, XmlSerializationWriteCallback callback) { TypeEntry entry = new TypeEntry(); entry.typeName = typeName; entry.typeNs = typeNs; entry.type = type; entry.callback = callback; - _typeEntries[type] = entry; + _typeEntries![type] = entry; } - private void WriteArray(string name, string ns, object o, Type type) + private void WriteArray(string name, string? ns, object o, Type type) { - Type elementType = TypeScope.GetArrayElementType(type, null); + Type elementType = TypeScope.GetArrayElementType(type, null)!; string typeName; - string typeNs; + string? typeNs; StringBuilder arrayDims = new StringBuilder(); if (!_soap12) { while ((elementType.IsArray || typeof(IEnumerable).IsAssignableFrom(elementType)) && GetPrimitiveTypeName(elementType, false) == null) { - elementType = TypeScope.GetArrayElementType(elementType, null); + elementType = TypeScope.GetArrayElementType(elementType, null)!; arrayDims.Append("[]"); } } @@ -1160,15 +1169,15 @@ private void WriteArray(string name, string ns, object o, Type type) } else { - TypeEntry entry = GetTypeEntry(elementType); + TypeEntry? entry = GetTypeEntry(elementType); if (entry != null) { - typeName = entry.typeName; + typeName = entry.typeName!; typeNs = entry.typeNs; } else if (_soap12) { - XmlQualifiedName qualName = GetPrimitiveTypeName(elementType, false); + XmlQualifiedName? qualName = GetPrimitiveTypeName(elementType, false); if (qualName != null) { typeName = qualName.Name; @@ -1176,7 +1185,7 @@ private void WriteArray(string name, string ns, object o, Type type) } else { - Type elementBaseType = elementType.BaseType; + Type? elementBaseType = elementType.BaseType; while (elementBaseType != null) { entry = GetTypeEntry(elementBaseType); @@ -1185,7 +1194,7 @@ private void WriteArray(string name, string ns, object o, Type type) } if (entry != null) { - typeName = entry.typeName; + typeName = entry.typeName!; typeNs = entry.typeNs; } else @@ -1261,22 +1270,22 @@ private void WriteArray(string name, string ns, object o, Type type) } _w.WriteEndElement(); } - protected void WritePotentiallyReferencingElement(string n, string ns, object o) + protected void WritePotentiallyReferencingElement(string? n, string? ns, object? o) { WritePotentiallyReferencingElement(n, ns, o, null, false, false); } - protected void WritePotentiallyReferencingElement(string n, string ns, object o, Type ambientType) + protected void WritePotentiallyReferencingElement(string? n, string? ns, object? o, Type? ambientType) { WritePotentiallyReferencingElement(n, ns, o, ambientType, false, false); } - protected void WritePotentiallyReferencingElement(string n, string ns, object o, Type ambientType, bool suppressReference) + protected void WritePotentiallyReferencingElement(string n, string? ns, object? o, Type? ambientType, bool suppressReference) { WritePotentiallyReferencingElement(n, ns, o, ambientType, suppressReference, false); } - protected void WritePotentiallyReferencingElement(string n, string ns, object o, Type ambientType, bool suppressReference, bool isNullable) + protected void WritePotentiallyReferencingElement(string? n, string? ns, object? o, Type? ambientType, bool suppressReference, bool isNullable) { if (o == null) { @@ -1294,8 +1303,8 @@ protected void WritePotentiallyReferencingElement(string n, string ns, object o, { if (n == null) { - TypeEntry entry = GetTypeEntry(t); - WriteReferencingElement(entry.typeName, entry.typeNs, o, isNullable); + TypeEntry entry = GetTypeEntry(t)!; + WriteReferencingElement(entry.typeName!, entry.typeNs, o, isNullable); } else WriteReferencingElement(n, ns, o, isNullable); @@ -1305,16 +1314,16 @@ protected void WritePotentiallyReferencingElement(string n, string ns, object o, { // Enums always write xsi:type, so don't write it again here. bool needXsiType = t != ambientType && !t.IsEnum; - TypeEntry entry = GetTypeEntry(t); + TypeEntry? entry = GetTypeEntry(t); if (entry != null) { if (n == null) - WriteStartElement(entry.typeName, entry.typeNs, null, true); + WriteStartElement(entry.typeName!, entry.typeNs, null, true); else WriteStartElement(n, ns, null, true); - if (needXsiType) WriteXsiType(entry.typeName, entry.typeNs); - entry.callback(o); + if (needXsiType) WriteXsiType(entry.typeName!, entry.typeNs); + entry.callback!(o); _w.WriteEndElement(); } else @@ -1325,12 +1334,12 @@ protected void WritePotentiallyReferencingElement(string n, string ns, object o, } - private void WriteReferencedElement(object o, Type ambientType) + private void WriteReferencedElement(object o, Type? ambientType) { WriteReferencedElement(null, null, o, ambientType); } - private void WriteReferencedElement(string name, string ns, object o, Type ambientType) + private void WriteReferencedElement(string? name, string? ns, object o, Type? ambientType) { if (name == null) name = string.Empty; Type t = o.GetType(); @@ -1340,24 +1349,24 @@ private void WriteReferencedElement(string name, string ns, object o, Type ambie } else { - TypeEntry entry = GetTypeEntry(t); + TypeEntry? entry = GetTypeEntry(t); if (entry == null) throw CreateUnknownTypeException(t); - WriteStartElement(name.Length == 0 ? entry.typeName : name, ns == null ? entry.typeNs : ns, null, true); + WriteStartElement(name.Length == 0 ? entry.typeName! : name!, ns == null ? entry.typeNs : ns, null, true); WriteId(o, false); - if (ambientType != t) WriteXsiType(entry.typeName, entry.typeNs); - entry.callback(o); + if (ambientType != t) WriteXsiType(entry.typeName!, entry.typeNs); + entry.callback!(o); _w.WriteEndElement(); } } - private TypeEntry GetTypeEntry(Type t) + private TypeEntry? GetTypeEntry(Type t) { if (_typeEntries == null) { _typeEntries = new Hashtable(); InitCallbacks(); } - return (TypeEntry)_typeEntries[t]; + return (TypeEntry?)_typeEntries[t]; } protected abstract void InitCallbacks(); @@ -1368,7 +1377,7 @@ protected void WriteReferencedElements() for (int i = 0; i < _referencesToWrite.Count; i++) { - WriteReferencedElement(_referencesToWrite[i], null); + WriteReferencedElement(_referencesToWrite[i]!, null); } } @@ -1378,23 +1387,23 @@ protected void TopLevelElement() } /// - protected void WriteNamespaceDeclarations(XmlSerializerNamespaces xmlns) + protected void WriteNamespaceDeclarations(XmlSerializerNamespaces? xmlns) { if (xmlns != null) { - foreach (KeyValuePair entry in xmlns.Namespaces) + foreach (KeyValuePair entry in xmlns.Namespaces) { string prefix = (string)entry.Key; - string ns = (string)entry.Value; + string? ns = (string?)entry.Value; if (_namespaces != null) { - string oldNs; + string? oldNs; if (_namespaces.Namespaces.TryGetValue(prefix, out oldNs) && oldNs != null && oldNs != ns) { throw new InvalidOperationException(SR.Format(SR.XmlDuplicateNs, prefix, ns)); } } - string oldPrefix = (ns == null || ns.Length == 0) ? null : Writer.LookupPrefix(ns); + string? oldPrefix = (ns == null || ns.Length == 0) ? null : Writer.LookupPrefix(ns); if (oldPrefix == null || oldPrefix != prefix) { @@ -1402,6 +1411,7 @@ protected void WriteNamespaceDeclarations(XmlSerializerNamespaces xmlns) } } } + _namespaces = null; } @@ -1417,14 +1427,13 @@ private string NextPrefix() internal class TypeEntry { - internal XmlSerializationWriteCallback callback; - internal string typeNs; - internal string typeName; - internal Type type; + internal XmlSerializationWriteCallback? callback; + internal string? typeNs; + internal string? typeName; + internal Type? type; } } - /// public delegate void XmlSerializationWriteCallback(object o); @@ -1439,7 +1448,7 @@ internal static class DynamicAssemblies // It's OK to suppress the SxS warning. internal static bool IsTypeDynamic(Type type) { - object oIsTypeDynamic = s_tableIsTypeDynamic[type]; + object? oIsTypeDynamic = s_tableIsTypeDynamic[type]; if (oIsTypeDynamic == null) { Assembly assembly = type.Assembly; @@ -1448,7 +1457,7 @@ internal static bool IsTypeDynamic(Type type) { if (type.IsArray) { - isTypeDynamic = IsTypeDynamic(type.GetElementType()); + isTypeDynamic = IsTypeDynamic(type.GetElementType()!); } else if (type.IsGenericType) { @@ -1494,8 +1503,8 @@ internal static void Add(Assembly a) //already added return; } - Assembly oldAssembly = s_nameToAssemblyMap[a.FullName] as Assembly; - string key = null; + Assembly? oldAssembly = s_nameToAssemblyMap[a.FullName!] as Assembly; + string? key = null; if (oldAssembly == null) { key = a.FullName; @@ -1513,14 +1522,14 @@ internal static void Add(Assembly a) } } - internal static Assembly Get(string fullName) + internal static Assembly? Get(string fullName) { - return s_nameToAssemblyMap != null ? (Assembly)s_nameToAssemblyMap[fullName] : null; + return s_nameToAssemblyMap != null ? (Assembly?)s_nameToAssemblyMap[fullName] : null; } - internal static string GetName(Assembly a) + internal static string? GetName(Assembly a) { - return s_assemblyToNameMap != null ? (string)s_assemblyToNameMap[a] : null; + return s_assemblyToNameMap != null ? (string?)s_assemblyToNameMap[a] : null; } } @@ -1543,7 +1552,7 @@ internal class ReflectionAwareCodeGen // ArrayAccessor "0:"+CodeIdentifier.EscapedKeywords(typeof(Array).FullName) // MyCollectionAccessor "0:"+CodeIdentifier.EscapedKeywords(typeof(MyCollection).FullName) // ---------------------------------------------------------------------------------- - private Hashtable _reflectionVariables; + private Hashtable _reflectionVariables = null!; private int _nextReflectionVariableNumber; private readonly IndentedWriter _writer; internal ReflectionAwareCodeGen(IndentedWriter writer) @@ -1565,17 +1574,17 @@ private string WriteTypeInfo(TypeScope scope, TypeDesc typeDesc, Type type) { InitTheFirstTime(); string typeFullName = typeDesc.CSharpName; - string typeVariable = (string)_reflectionVariables[typeFullName]; + string? typeVariable = (string?)_reflectionVariables[typeFullName]; if (typeVariable != null) return typeVariable; if (type.IsArray) { typeVariable = GenerateVariableName("array", typeDesc.CSharpName); - TypeDesc elementTypeDesc = typeDesc.ArrayElementTypeDesc; + TypeDesc elementTypeDesc = typeDesc.ArrayElementTypeDesc!; if (elementTypeDesc.UseReflection) { - string elementTypeVariable = WriteTypeInfo(scope, elementTypeDesc, scope.GetTypeFromTypeDesc(elementTypeDesc)); + string elementTypeVariable = WriteTypeInfo(scope, elementTypeDesc, scope.GetTypeFromTypeDesc(elementTypeDesc)!); _writer.WriteLine("static " + typeof(Type).FullName + " " + typeVariable + " = " + elementTypeVariable + ".MakeArrayType();"); } else @@ -1590,7 +1599,7 @@ private string WriteTypeInfo(TypeScope scope, TypeDesc typeDesc, Type type) { typeVariable = GenerateVariableName(nameof(type), typeDesc.CSharpName); - Type parameterType = Nullable.GetUnderlyingType(type); + Type? parameterType = Nullable.GetUnderlyingType(type); if (parameterType != null) { string parameterTypeVariable = WriteTypeInfo(scope, scope.GetTypeDesc(parameterType), parameterType); @@ -1607,19 +1616,21 @@ private string WriteTypeInfo(TypeScope scope, TypeDesc typeDesc, Type type) _reflectionVariables.Add(typeFullName, typeVariable); - TypeMapping mapping = scope.GetTypeMappingFromTypeDesc(typeDesc); + TypeMapping? mapping = scope.GetTypeMappingFromTypeDesc(typeDesc); if (mapping != null) WriteMappingInfo(mapping, typeVariable, type); if (typeDesc.IsCollection || typeDesc.IsEnumerable) {// Arrays use the generic item_Array - TypeDesc elementTypeDesc = typeDesc.ArrayElementTypeDesc; + TypeDesc elementTypeDesc = typeDesc.ArrayElementTypeDesc!; if (elementTypeDesc.UseReflection) - WriteTypeInfo(scope, elementTypeDesc, scope.GetTypeFromTypeDesc(elementTypeDesc)); + WriteTypeInfo(scope, elementTypeDesc, scope.GetTypeFromTypeDesc(elementTypeDesc)!); WriteCollectionInfo(typeVariable, typeDesc, type); } + return typeVariable; } + [MemberNotNull(nameof(_reflectionVariables))] private void InitTheFirstTime() { if (_reflectionVariables == null) @@ -1629,17 +1640,17 @@ private void InitTheFirstTime() "object", "string", typeof(Type).FullName, typeof(FieldInfo).FullName, typeof(PropertyInfo).FullName)); - WriteDefaultIndexerInit(typeof(IList), typeof(Array).FullName, false, false); + WriteDefaultIndexerInit(typeof(IList), typeof(Array).FullName!, false, false); } } private void WriteMappingInfo(TypeMapping mapping, string typeVariable, Type type) { - string typeFullName = mapping.TypeDesc.CSharpName; + string typeFullName = mapping.TypeDesc!.CSharpName; if (mapping is StructMapping) { - StructMapping structMapping = mapping as StructMapping; - for (int i = 0; i < structMapping.Members.Length; i++) + StructMapping structMapping = (mapping as StructMapping)!; + for (int i = 0; i < structMapping.Members!.Length; i++) { MemberMapping member = structMapping.Members[i]; string memberVariable = WriteMemberInfo(type, typeFullName, typeVariable, member.Name); @@ -1655,7 +1666,7 @@ private void WriteMappingInfo(TypeMapping mapping, string typeVariable, Type typ } if (member.ChoiceIdentifier != null) { - string memberName = member.ChoiceIdentifier.MemberName; + string memberName = member.ChoiceIdentifier.MemberName!; memberVariable = WriteMemberInfo(type, typeFullName, typeVariable, memberName); } } @@ -1672,7 +1683,7 @@ private void WriteMappingInfo(TypeMapping mapping, string typeVariable, Type typ private void WriteCollectionInfo(string typeVariable, TypeDesc typeDesc, Type type) { string typeFullName = CodeIdentifier.GetCSharpName(type); - string elementTypeFullName = typeDesc.ArrayElementTypeDesc.CSharpName; + string elementTypeFullName = typeDesc.ArrayElementTypeDesc!.CSharpName; bool elementUseReflection = typeDesc.ArrayElementTypeDesc.UseReflection; if (typeDesc.IsCollection) { @@ -1694,8 +1705,8 @@ private void WriteCollectionInfo(string typeVariable, TypeDesc typeDesc, Type ty private string WriteAssemblyInfo(Type type) { - string assemblyFullName = type.Assembly.FullName; - string assemblyVariable = (string)_reflectionVariables[assemblyFullName]; + string assemblyFullName = type.Assembly.FullName!; + string? assemblyVariable = (string?)_reflectionVariables[assemblyFullName]; if (assemblyVariable == null) { int iComma = assemblyFullName.IndexOf(','); @@ -1744,7 +1755,7 @@ private string WriteMethodInfo(string escapedName, string typeVariable, string m WriteQuotedCSharpString(memberName); _writer.Write(", "); - string bindingFlags = typeof(BindingFlags).FullName; + string bindingFlags = typeof(BindingFlags).FullName!; _writer.Write(bindingFlags); _writer.Write(".Public | "); _writer.Write(bindingFlags); @@ -1797,14 +1808,14 @@ private string GenerateVariableName(string prefix, string fullName) return prefix + _nextReflectionVariableNumber + "_" + CodeIdentifier.MakeValidInternal(fullName.Replace('.', '_')); } - internal string GetReflectionVariable(string typeFullName, string memberName) + internal string? GetReflectionVariable(string typeFullName, string? memberName) { string key; if (memberName == null) key = typeFullName; else key = memberName + ":" + typeFullName; - return (string)_reflectionVariables[key]; + return (string?)_reflectionVariables[key]; } @@ -1843,9 +1854,9 @@ internal string GetStringForEnumCompare(EnumMapping mapping, string memberName, if (!useReflection) { CodeIdentifier.CheckValidIdentifier(memberName); - return mapping.TypeDesc.CSharpName + ".@" + memberName; + return mapping.TypeDesc!.CSharpName + ".@" + memberName; } - string memberAccess = GetStringForEnumMember(mapping.TypeDesc.CSharpName, memberName, useReflection); + string memberAccess = GetStringForEnumMember(mapping.TypeDesc!.CSharpName, memberName, useReflection); return GetStringForEnumLongValue(memberAccess, useReflection); } internal string GetStringForEnumLongValue(string variable, bool useReflection) @@ -1859,7 +1870,7 @@ internal string GetStringForTypeof(string typeFullName, bool useReflection) { if (useReflection) { - return GetReflectionVariable(typeFullName, null); + return GetReflectionVariable(typeFullName, null)!; } else { @@ -1875,11 +1886,11 @@ internal string GetStringForMember(string obj, string memberName, TypeDesc typeD while (typeDesc != null) { string typeFullName = typeDesc.CSharpName; - string memberInfoName = GetReflectionVariable(typeFullName, memberName); + string? memberInfoName = GetReflectionVariable(typeFullName, memberName); if (memberInfoName != null) return memberInfoName + "[" + obj + "]"; // member may be part of the basetype - typeDesc = typeDesc.BaseTypeDesc; + typeDesc = typeDesc.BaseTypeDesc!; if (typeDesc != null && !typeDesc.UseReflection) return "((" + typeDesc.CSharpName + ")" + obj + ").@" + memberName; } @@ -1909,17 +1920,18 @@ internal string GetStringForEnumMember(string typeFullName, string memberName, b if (!useReflection) return typeFullName + ".@" + memberName; - string memberInfoName = GetReflectionVariable(typeFullName, memberName); + string? memberInfoName = GetReflectionVariable(typeFullName, memberName); return memberInfoName + "[null]"; } + internal string GetStringForArrayMember(string arrayName, string subscript, TypeDesc arrayTypeDesc) { if (!arrayTypeDesc.UseReflection) { return arrayName + "[" + subscript + "]"; } - string typeFullName = arrayTypeDesc.IsCollection ? arrayTypeDesc.CSharpName : typeof(Array).FullName; - string arrayInfo = GetReflectionVariable(typeFullName, arrayMemberKey); + string typeFullName = arrayTypeDesc.IsCollection ? arrayTypeDesc.CSharpName : typeof(Array).FullName!; + string? arrayInfo = GetReflectionVariable(typeFullName, arrayMemberKey); return arrayInfo + "[" + arrayName + ", " + subscript + "]"; } internal string GetStringForMethod(string obj, string typeFullName, string memberName, bool useReflection) @@ -1927,7 +1939,7 @@ internal string GetStringForMethod(string obj, string typeFullName, string membe if (!useReflection) return obj + "." + memberName + "("; - string memberInfoName = GetReflectionVariable(typeFullName, memberName); + string? memberInfoName = GetReflectionVariable(typeFullName, memberName); return memberInfoName + ".Invoke(" + obj + ", new object[]{"; } internal string GetStringForCreateInstance(string escapedTypeName, bool useReflection, bool ctorInaccessible, bool cast) @@ -1942,7 +1954,7 @@ internal string GetStringForCreateInstance(string escapedTypeName, bool useRefle return GetStringForCreateInstance(GetStringForTypeof(escapedTypeName, useReflection), cast && !useReflection ? escapedTypeName : null, ctorInaccessible, arg); } - internal string GetStringForCreateInstance(string type, string cast, bool nonPublic, string arg) + internal string GetStringForCreateInstance(string type, string? cast, bool nonPublic, string? arg) { StringBuilder createInstance = new StringBuilder(); if (cast != null && cast.Length > 0) @@ -1955,7 +1967,7 @@ internal string GetStringForCreateInstance(string type, string cast, bool nonPub createInstance.Append(".CreateInstance("); createInstance.Append(type); createInstance.Append(", "); - string bindingFlags = typeof(BindingFlags).FullName; + string bindingFlags = typeof(BindingFlags).FullName!; createInstance.Append(bindingFlags); createInstance.Append(".Instance | "); createInstance.Append(bindingFlags); @@ -1969,6 +1981,7 @@ internal string GetStringForCreateInstance(string type, string cast, bool nonPub createInstance.Append(bindingFlags); createInstance.Append(".NonPublic"); } + if (arg == null || arg.Length == 0) { createInstance.Append(", null, new object[0], null)"); @@ -2025,16 +2038,16 @@ internal void WriteInstanceOf(string source, string escapedTypeName, bool useRef _writer.Write(".GetType())"); } - internal void WriteArrayLocalDecl(string typeName, string variableName, string initValue, TypeDesc arrayTypeDesc) + internal void WriteArrayLocalDecl(string typeName, string variableName, string? initValue, TypeDesc arrayTypeDesc) { if (arrayTypeDesc.UseReflection) { if (arrayTypeDesc.IsEnumerable) - typeName = typeof(IEnumerable).FullName; + typeName = typeof(IEnumerable).FullName!; else if (arrayTypeDesc.IsCollection) - typeName = typeof(ICollection).FullName; + typeName = typeof(ICollection).FullName!; else - typeName = typeof(Array).FullName; + typeName = typeof(Array).FullName!; } _writer.Write(typeName); _writer.Write(" "); @@ -2086,7 +2099,7 @@ internal void WriteArrayTypeCompare(string variable, string escapedTypeName, str WriteTypeCompare(variable + ".GetElementType()", elementTypeName, useReflection); } - internal static void WriteQuotedCSharpString(IndentedWriter writer, string value) + internal static void WriteQuotedCSharpString(IndentedWriter writer, string? value) { if (value == null) { @@ -2124,7 +2137,7 @@ internal static void WriteQuotedCSharpString(IndentedWriter writer, string value writer.Write("\""); } - internal void WriteQuotedCSharpString(string value) + internal void WriteQuotedCSharpString(string? value) { WriteQuotedCSharpString(_writer, value); } @@ -2198,9 +2211,10 @@ internal void GenerateBegin() { if (mapping is StructMapping || mapping is EnumMapping) { - MethodNames.Add(mapping, NextMethodName(mapping.TypeDesc.Name)); + MethodNames.Add(mapping, NextMethodName(mapping.TypeDesc!.Name)); } } + RaCodeGen.WriteReflectionInit(scope); } @@ -2243,7 +2257,7 @@ internal void GenerateEnd() Writer.WriteLine("}"); } - internal string GenerateElement(XmlMapping xmlMapping) + internal string? GenerateElement(XmlMapping xmlMapping) { if (!xmlMapping.IsWriteable) return null; @@ -2269,9 +2283,9 @@ private void GenerateInitCallbacksMethod() { if (typeMapping.IsSoap && (typeMapping is StructMapping || typeMapping is EnumMapping) && - !typeMapping.TypeDesc.IsRoot) + !typeMapping.TypeDesc!.IsRoot) { - string methodName = (string)MethodNames[typeMapping]; + string methodName = (string)MethodNames[typeMapping]!; Writer.Write("AddWriteCallback("); Writer.Write(RaCodeGen.GetStringForTypeof(typeMapping.TypeDesc.CSharpName, typeMapping.TypeDesc.UseReflection)); Writer.Write(", "); @@ -2286,16 +2300,17 @@ private void GenerateInitCallbacksMethod() } } } + Writer.Indent--; Writer.WriteLine("}"); } - private void WriteQualifiedNameElement(string name, string ns, object defaultValue, string source, bool nullable, bool IsSoap, TypeMapping mapping) + private void WriteQualifiedNameElement(string name, string? ns, object? defaultValue, string source, bool nullable, bool IsSoap, TypeMapping mapping) { bool hasDefault = defaultValue != null && defaultValue != DBNull.Value; if (hasDefault) { - WriteCheckDefault(mapping, source, defaultValue, nullable); + WriteCheckDefault(mapping, source, defaultValue!, nullable); Writer.WriteLine(" {"); Writer.Indent++; } @@ -2331,11 +2346,11 @@ private void WriteQualifiedNameElement(string name, string ns, object defaultVal private void WriteEnumValue(EnumMapping mapping, string source) { - string methodName = ReferenceMapping(mapping); + string? methodName = ReferenceMapping(mapping); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe - if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc.Name) + Environment.StackTrace); + if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc!.Name) + Environment.StackTrace); #endif Writer.Write(methodName); @@ -2372,21 +2387,21 @@ private void WritePrimitiveValue(TypeDesc typeDesc, string source, bool isElemen } } - private void WritePrimitive(string method, string name, string ns, object defaultValue, string source, TypeMapping mapping, bool writeXsiType, bool isElement, bool isNullable) + private void WritePrimitive(string method, string name, string? ns, object? defaultValue, string source, TypeMapping mapping, bool writeXsiType, bool isElement, bool isNullable) { - TypeDesc typeDesc = mapping.TypeDesc; - bool hasDefault = defaultValue != null && defaultValue != DBNull.Value && mapping.TypeDesc.HasDefaultSupport; + TypeDesc typeDesc = mapping.TypeDesc!; + bool hasDefault = defaultValue != null && defaultValue != DBNull.Value && mapping.TypeDesc!.HasDefaultSupport; if (hasDefault) { if (mapping is EnumMapping) { #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe - if (defaultValue.GetType() != typeof(string)) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, name + " has invalid default type " + defaultValue.GetType().Name)); + if (defaultValue!.GetType() != typeof(string)) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, name + " has invalid default type " + defaultValue.GetType().Name)); #endif Writer.Write("if ("); - if (mapping.TypeDesc.UseReflection) + if (mapping.TypeDesc!.UseReflection) Writer.Write(RaCodeGen.GetStringForEnumLongValue(source, mapping.TypeDesc.UseReflection)); else Writer.Write(source); @@ -2394,7 +2409,7 @@ private void WritePrimitive(string method, string name, string ns, object defaul if (((EnumMapping)mapping).IsFlags) { Writer.Write("("); - string[] values = ((string)defaultValue).Split(null); + string[] values = ((string)defaultValue!).Split(null); for (int i = 0; i < values.Length; i++) { if (values[i] == null || values[i].Length == 0) @@ -2407,17 +2422,18 @@ private void WritePrimitive(string method, string name, string ns, object defaul } else { - Writer.Write(RaCodeGen.GetStringForEnumCompare((EnumMapping)mapping, (string)defaultValue, mapping.TypeDesc.UseReflection)); + Writer.Write(RaCodeGen.GetStringForEnumCompare((EnumMapping)mapping, (string)defaultValue!, mapping.TypeDesc.UseReflection)); } Writer.Write(")"); } else { - WriteCheckDefault(mapping, source, defaultValue, isNullable); + WriteCheckDefault(mapping, source, defaultValue!, isNullable); } Writer.WriteLine(" {"); Writer.Indent++; } + Writer.Write(method); Writer.Write("("); WriteQuotedCSharpString(name); @@ -2426,6 +2442,7 @@ private void WritePrimitive(string method, string name, string ns, object defaul Writer.Write(", "); WriteQuotedCSharpString(ns); } + Writer.Write(", "); if (mapping is EnumMapping) @@ -2455,7 +2472,7 @@ private void WritePrimitive(string method, string name, string ns, object defaul } } - private void WriteTag(string methodName, string name, string ns) + private void WriteTag(string methodName, string name, string? ns) { Writer.Write(methodName); Writer.Write("("); @@ -2472,7 +2489,7 @@ private void WriteTag(string methodName, string name, string ns) Writer.WriteLine(");"); } - private void WriteTag(string methodName, string name, string ns, bool writePrefixed) + private void WriteTag(string methodName, string name, string? ns, bool writePrefixed) { Writer.Write(methodName); Writer.Write("("); @@ -2494,7 +2511,7 @@ private void WriteTag(string methodName, string name, string ns, bool writePrefi Writer.WriteLine(");"); } - private void WriteStartElement(string name, string ns, bool writePrefixed) + private void WriteStartElement(string name, string? ns, bool writePrefixed) { WriteTag("WriteStartElement", name, ns, writePrefixed); } @@ -2510,17 +2527,17 @@ private void WriteEndElement(string source) Writer.WriteLine(");"); } - private void WriteEncodedNullTag(string name, string ns) + private void WriteEncodedNullTag(string name, string? ns) { WriteTag("WriteNullTagEncoded", name, ns); } - private void WriteLiteralNullTag(string name, string ns) + private void WriteLiteralNullTag(string name, string? ns) { WriteTag("WriteNullTagLiteral", name, ns); } - private void WriteEmptyTag(string name, string ns) + private void WriteEmptyTag(string name, string? ns) { WriteTag("WriteEmptyTag", name, ns); } @@ -2528,7 +2545,7 @@ private void WriteEmptyTag(string name, string ns) private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) { ElementAccessor element = xmlMembersMapping.Accessor; - MembersMapping mapping = (MembersMapping)element.Mapping; + MembersMapping mapping = (MembersMapping)element.Mapping!; bool hasWrapperElement = mapping.HasWrapperElement; bool writeAccessors = mapping.WriteAccessors; bool isRpc = xmlMembersMapping.IsSoap && writeAccessors; @@ -2555,10 +2572,10 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) { WriteStartElement(element.Name, (element.Form == XmlSchemaForm.Qualified ? element.Namespace : ""), mapping.IsSoap); - int xmlnsMember = FindXmlnsIndex(mapping.Members); + int xmlnsMember = FindXmlnsIndex(mapping.Members!); if (xmlnsMember >= 0) { - MemberMapping member = mapping.Members[xmlnsMember]; + MemberMapping member = mapping.Members![xmlnsMember]; string source = "((" + typeof(System.Xml.Serialization.XmlSerializerNamespaces).FullName + ")p[" + xmlnsMember.ToString(CultureInfo.InvariantCulture) + "])"; Writer.Write("if (pLength > "); @@ -2570,7 +2587,7 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) Writer.WriteLine("}"); } - for (int i = 0; i < mapping.Members.Length; i++) + for (int i = 0; i < mapping.Members!.Length; i++) { MemberMapping member = mapping.Members[i]; @@ -2579,7 +2596,7 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) string index = i.ToString(CultureInfo.InvariantCulture); string source = "p[" + index + "]"; - string specifiedSource = null; + string? specifiedSource = null; int specifiedPosition = 0; if (member.CheckSpecified != SpecifiedAccessor.None) { @@ -2610,7 +2627,7 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) Writer.Indent++; } - WriteMember(source, member.Attribute, member.TypeDesc, "p"); + WriteMember(source, member.Attribute, member.TypeDesc!, "p"); if (specifiedSource != null) { @@ -2624,7 +2641,7 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) } } - for (int i = 0; i < mapping.Members.Length; i++) + for (int i = 0; i < mapping.Members!.Length; i++) { MemberMapping member = mapping.Members[i]; if (member.Xmlns != null) @@ -2632,7 +2649,7 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) if (member.Ignore) continue; - string specifiedSource = null; + string? specifiedSource = null; int specifiedPosition = 0; if (member.CheckSpecified != SpecifiedAccessor.None) { @@ -2666,17 +2683,17 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) } string source = "p[" + index + "]"; - string enumSource = null; + string? enumSource = null; if (member.ChoiceIdentifier != null) { for (int j = 0; j < mapping.Members.Length; j++) { if (mapping.Members[j].Name == member.ChoiceIdentifier.MemberName) { - if (member.ChoiceIdentifier.Mapping.TypeDesc.UseReflection) + if (member.ChoiceIdentifier.Mapping!.TypeDesc!.UseReflection) enumSource = "p[" + j.ToString(CultureInfo.InvariantCulture) + "]"; else - enumSource = "((" + mapping.Members[j].TypeDesc.CSharpName + ")p[" + j.ToString(CultureInfo.InvariantCulture) + "]" + ")"; + enumSource = "((" + mapping.Members[j].TypeDesc!.CSharpName + ")p[" + j.ToString(CultureInfo.InvariantCulture) + "]" + ")"; break; } } @@ -2687,7 +2704,7 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) #endif } - if (isRpc && member.IsReturnValue && member.Elements.Length > 0) + if (isRpc && member.IsReturnValue && member.Elements!.Length > 0) { Writer.Write("WriteRpcResult("); WriteQuotedCSharpString(member.Elements[0].Name); @@ -2697,7 +2714,7 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) } // override writeAccessors choice when we've written a wrapper element - WriteMember(source, enumSource, member.ElementsSortedByDerivation, member.Text, member.ChoiceIdentifier, member.TypeDesc, writeAccessors || hasWrapperElement); + WriteMember(source, enumSource, member.ElementsSortedByDerivation!, member.Text, member.ChoiceIdentifier, member.TypeDesc!, writeAccessors || hasWrapperElement); if (specifiedSource != null) { @@ -2738,7 +2755,7 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) private string GenerateTypeElement(XmlTypeMapping xmlTypeMapping) { ElementAccessor element = xmlTypeMapping.Accessor; - TypeMapping mapping = element.Mapping; + TypeMapping mapping = element.Mapping!; string methodName = NextMethodName(element.Name); Writer.WriteLine(); Writer.Write("public void "); @@ -2763,12 +2780,12 @@ private string GenerateTypeElement(XmlTypeMapping xmlTypeMapping) Writer.Indent--; Writer.WriteLine("}"); - if (!mapping.IsSoap && !mapping.TypeDesc.IsValueType && !mapping.TypeDesc.Type.IsPrimitive) + if (!mapping.IsSoap && !mapping.TypeDesc!.IsValueType && !mapping.TypeDesc.Type!.IsPrimitive) { Writer.WriteLine("TopLevelElement();"); } - WriteMember("o", null, new ElementAccessor[] { element }, null, null, mapping.TypeDesc, !element.IsSoap); + WriteMember("o", null, new ElementAccessor[] { element }, null, null, mapping.TypeDesc!, !element.IsSoap); if (mapping.IsSoap) { @@ -2786,9 +2803,9 @@ private string NextMethodName(string name) private void WriteEnumMethod(EnumMapping mapping) { - string methodName = (string)MethodNames[mapping]; + string methodName = (string)MethodNames[mapping]!; Writer.WriteLine(); - string fullTypeName = mapping.TypeDesc.CSharpName; + string fullTypeName = mapping.TypeDesc!.CSharpName; if (mapping.IsSoap) { Writer.Write("void "); @@ -2806,7 +2823,7 @@ private void WriteEnumMethod(EnumMapping mapping) } Writer.Indent++; Writer.WriteLine("string s = null;"); - ConstantMapping[] constants = mapping.Constants; + ConstantMapping[] constants = mapping.Constants!; if (constants.Length > 0) { @@ -2898,19 +2915,19 @@ private void WriteEnumMethod(EnumMapping mapping) private void WriteDerivedTypes(StructMapping mapping) { - for (StructMapping derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) + for (StructMapping? derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) { - string fullTypeName = derived.TypeDesc.CSharpName; + string fullTypeName = derived.TypeDesc!.CSharpName; Writer.Write("if ("); WriteTypeCompare("t", fullTypeName, derived.TypeDesc.UseReflection); Writer.WriteLine(") {"); Writer.Indent++; - string methodName = ReferenceMapping(derived); + string? methodName = ReferenceMapping(derived); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe - if (methodName == null) throw new InvalidOperationException("derived from " + mapping.TypeDesc.FullName + ", " + SR.Format(SR.XmlInternalErrorMethod, derived.TypeDesc.Name) + Environment.StackTrace); + if (methodName == null) throw new InvalidOperationException("derived from " + mapping.TypeDesc!.FullName + ", " + SR.Format(SR.XmlInternalErrorMethod, derived.TypeDesc.Name) + Environment.StackTrace); #endif Writer.Write(methodName); @@ -2938,13 +2955,13 @@ private void WriteEnumAndArrayTypes() if (m is EnumMapping && !m.IsSoap) { EnumMapping mapping = (EnumMapping)m; - string fullTypeName = mapping.TypeDesc.CSharpName; + string fullTypeName = mapping.TypeDesc!.CSharpName; Writer.Write("if ("); WriteTypeCompare("t", fullTypeName, mapping.TypeDesc.UseReflection); Writer.WriteLine(") {"); Writer.Indent++; - string methodName = ReferenceMapping(mapping); + string? methodName = ReferenceMapping(mapping); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe @@ -2968,12 +2985,12 @@ private void WriteEnumAndArrayTypes() } else if (m is ArrayMapping && !m.IsSoap) { - ArrayMapping mapping = m as ArrayMapping; + ArrayMapping? mapping = m as ArrayMapping; if (mapping == null || m.IsSoap) continue; - string fullTypeName = mapping.TypeDesc.CSharpName; + string fullTypeName = mapping.TypeDesc!.CSharpName; Writer.Write("if ("); if (mapping.TypeDesc.IsArray) - WriteArrayTypeCompare("t", fullTypeName, mapping.TypeDesc.ArrayElementTypeDesc.CSharpName, mapping.TypeDesc.UseReflection); + WriteArrayTypeCompare("t", fullTypeName, mapping.TypeDesc.ArrayElementTypeDesc!.CSharpName, mapping.TypeDesc.UseReflection); else WriteTypeCompare("t", fullTypeName, mapping.TypeDesc.UseReflection); Writer.WriteLine(") {"); @@ -2986,7 +3003,7 @@ private void WriteEnumAndArrayTypes() WriteQuotedCSharpString(mapping.Namespace); Writer.WriteLine(");"); - WriteMember("o", null, mapping.ElementsSortedByDerivation, null, null, mapping.TypeDesc, true); + WriteMember("o", null, mapping.ElementsSortedByDerivation!, null, null, mapping.TypeDesc, true); Writer.WriteLine("Writer.WriteEndElement();"); Writer.WriteLine("return;"); @@ -2999,14 +3016,14 @@ private void WriteEnumAndArrayTypes() private void WriteStructMethod(StructMapping mapping) { - if (mapping.IsSoap && mapping.TypeDesc.IsRoot) return; - string methodName = (string)MethodNames[mapping]; + if (mapping.IsSoap && mapping.TypeDesc!.IsRoot) return; + string? methodName = (string?)MethodNames[mapping]; Writer.WriteLine(); Writer.Write("void "); Writer.Write(methodName); - string fullTypeName = mapping.TypeDesc.CSharpName; + string fullTypeName = mapping.TypeDesc!.CSharpName; if (mapping.IsSoap) { @@ -3069,7 +3086,7 @@ private void WriteStructMethod(StructMapping mapping) Writer.WriteLine("EscapeName = false;"); } - string xmlnsSource = null; + string? xmlnsSource = null; MemberMapping[] members = TypeScope.GetAllMembers(mapping); int xmlnsMember = FindXmlnsIndex(members); if (xmlnsMember >= 0) @@ -3079,7 +3096,7 @@ private void WriteStructMethod(StructMapping mapping) xmlnsSource = RaCodeGen.GetStringForMember("o", member.Name, mapping.TypeDesc); if (mapping.TypeDesc.UseReflection) { - xmlnsSource = "((" + member.TypeDesc.CSharpName + ")" + xmlnsSource + ")"; + xmlnsSource = "((" + member.TypeDesc!.CSharpName + ")" + xmlnsSource + ")"; } } @@ -3129,7 +3146,7 @@ private void WriteStructMethod(StructMapping mapping) Writer.WriteLine(") {"); Writer.Indent++; } - WriteMember(RaCodeGen.GetStringForMember("o", m.Name, mapping.TypeDesc), m.Attribute, m.TypeDesc, "o"); + WriteMember(RaCodeGen.GetStringForMember("o", m.Name, mapping.TypeDesc), m.Attribute, m.TypeDesc!, "o"); if (m.CheckSpecified != SpecifiedAccessor.None) { @@ -3150,7 +3167,7 @@ private void WriteStructMethod(StructMapping mapping) if (m.Xmlns != null) continue; CodeIdentifier.CheckValidIdentifier(m.Name); - bool checkShouldPersist = m.CheckShouldPersist && (m.Elements.Length > 0 || m.Text != null); + bool checkShouldPersist = m.CheckShouldPersist && (m.Elements!.Length > 0 || m.Text != null); if (checkShouldPersist) { @@ -3171,13 +3188,13 @@ private void WriteStructMethod(StructMapping mapping) Writer.Indent++; } - string choiceSource = null; + string? choiceSource = null; if (m.ChoiceIdentifier != null) { CodeIdentifier.CheckValidIdentifier(m.ChoiceIdentifier.MemberName); choiceSource = RaCodeGen.GetStringForMember("o", m.ChoiceIdentifier.MemberName, mapping.TypeDesc); } - WriteMember(RaCodeGen.GetStringForMember("o", m.Name, mapping.TypeDesc), choiceSource, m.ElementsSortedByDerivation, m.Text, m.ChoiceIdentifier, m.TypeDesc, true); + WriteMember(RaCodeGen.GetStringForMember("o", m.Name, mapping.TypeDesc), choiceSource, m.ElementsSortedByDerivation!, m.Text, m.ChoiceIdentifier, m.TypeDesc!, true); if (m.CheckSpecified != SpecifiedAccessor.None) { @@ -3199,7 +3216,7 @@ private void WriteStructMethod(StructMapping mapping) Writer.WriteLine("}"); } - private bool CanOptimizeWriteListSequence(TypeDesc listElementTypeDesc) + private bool CanOptimizeWriteListSequence(TypeDesc? listElementTypeDesc) { // check to see if we can write values of the attribute sequentially // currently we have only one data type (XmlQualifiedName) that we can not write "inline", @@ -3229,7 +3246,7 @@ private void WriteMember(string source, AttributeAccessor attribute, TypeDesc me Writer.Write("Writer.WriteStartAttribute(null, "); WriteQuotedCSharpString(attribute.Name); Writer.Write(", "); - string ns = attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : string.Empty; + string? ns = attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : string.Empty; if (ns != null) { WriteQuotedCSharpString(ns); @@ -3248,7 +3265,7 @@ private void WriteMember(string source, AttributeAccessor attribute, TypeDesc me Writer.WriteLine("();"); } } - TypeDesc arrayElementTypeDesc = memberTypeDesc.ArrayElementTypeDesc; + TypeDesc arrayElementTypeDesc = memberTypeDesc.ArrayElementTypeDesc!; if (memberTypeDesc.IsEnumerable) { @@ -3353,7 +3370,7 @@ private void WriteMember(string source, AttributeAccessor attribute, TypeDesc me Writer.Write("WriteAttribute("); WriteQuotedCSharpString(attribute.Name); Writer.Write(", "); - string ns = attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : string.Empty; + string? ns = attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : string.Empty; if (ns != null) { WriteQuotedCSharpString(ns); @@ -3384,7 +3401,7 @@ private void WriteAttribute(string source, AttributeAccessor attribute, string p if (attribute.Mapping is SpecialMapping) { SpecialMapping special = (SpecialMapping)attribute.Mapping; - if (special.TypeDesc.Kind == TypeKind.Attribute || special.TypeDesc.CanBeAttributeValue) + if (special.TypeDesc!.Kind == TypeKind.Attribute || special.TypeDesc.CanBeAttributeValue) { Writer.Write("WriteXmlAttribute("); Writer.Write(source); @@ -3397,13 +3414,13 @@ private void WriteAttribute(string source, AttributeAccessor attribute, string p } else { - TypeDesc typeDesc = attribute.Mapping.TypeDesc; + TypeDesc typeDesc = attribute.Mapping!.TypeDesc!; if (!typeDesc.UseReflection) source = "((" + typeDesc.CSharpName + ")" + source + ")"; WritePrimitive("WriteAttribute", attribute.Name, attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : "", attribute.Default, source, attribute.Mapping, false, false, false); } } - private void WriteMember(string source, string choiceSource, ElementAccessor[] elements, TextAccessor text, ChoiceIdentifierAccessor choice, TypeDesc memberTypeDesc, bool writeAccessors) + private void WriteMember(string source, string? choiceSource, ElementAccessor[] elements, TextAccessor? text, ChoiceIdentifierAccessor? choice, TypeDesc memberTypeDesc, bool writeAccessors) { if (memberTypeDesc.IsArrayLike && !(elements.Length == 1 && elements[0].Mapping is ArrayMapping)) @@ -3413,7 +3430,7 @@ private void WriteMember(string source, string choiceSource, ElementAccessor[] e } - private void WriteArray(string source, string choiceSource, ElementAccessor[] elements, TextAccessor text, ChoiceIdentifierAccessor choice, TypeDesc arrayTypeDesc) + private void WriteArray(string source, string? choiceSource, ElementAccessor[] elements, TextAccessor? text, ChoiceIdentifierAccessor? choice, TypeDesc arrayTypeDesc) { if (elements.Length == 0 && text == null) return; Writer.WriteLine("{"); @@ -3428,7 +3445,7 @@ private void WriteArray(string source, string choiceSource, ElementAccessor[] el if (choice != null) { - bool choiceUseReflection = choice.Mapping.TypeDesc.UseReflection; + bool choiceUseReflection = choice.Mapping!.TypeDesc!.UseReflection; string choiceFullName = choice.Mapping.TypeDesc.CSharpName; WriteArrayLocalDecl(choiceFullName + "[]", "c", choiceSource, choice.Mapping.TypeDesc); // write check for the choice identifier array @@ -3453,9 +3470,9 @@ private void WriteArray(string source, string choiceSource, ElementAccessor[] el Writer.WriteLine("}"); } - private void WriteArrayItems(ElementAccessor[] elements, TextAccessor text, ChoiceIdentifierAccessor choice, TypeDesc arrayTypeDesc, string arrayName, string choiceName) + private void WriteArrayItems(ElementAccessor[] elements, TextAccessor? text, ChoiceIdentifierAccessor? choice, TypeDesc arrayTypeDesc, string arrayName, string? choiceName) { - TypeDesc arrayElementTypeDesc = arrayTypeDesc.ArrayElementTypeDesc; + TypeDesc arrayElementTypeDesc = arrayTypeDesc.ArrayElementTypeDesc!; if (arrayTypeDesc.IsEnumerable) { @@ -3540,8 +3557,8 @@ private void WriteArrayItems(ElementAccessor[] elements, TextAccessor text, Choi WriteLocalDecl(arrayTypeFullName, arrayName + "i", RaCodeGen.GetStringForArrayMember(arrayName, "i" + arrayName, arrayTypeDesc), arrayElementTypeDesc.UseReflection); if (choice != null) { - string choiceFullName = choice.Mapping.TypeDesc.CSharpName; - WriteLocalDecl(choiceFullName, choiceName + "i", RaCodeGen.GetStringForArrayMember(choiceName, "i" + arrayName, choice.Mapping.TypeDesc), choice.Mapping.TypeDesc.UseReflection); + string choiceFullName = choice.Mapping!.TypeDesc!.CSharpName; + WriteLocalDecl(choiceFullName, choiceName + "i", RaCodeGen.GetStringForArrayMember(choiceName!, "i" + arrayName, choice.Mapping.TypeDesc), choice.Mapping.TypeDesc.UseReflection); } WriteElements(arrayName + "i", choiceName + "i", elements, text, choice, arrayName + "a", true, arrayElementTypeDesc.IsNullable); } @@ -3554,18 +3571,18 @@ private void WriteArrayItems(ElementAccessor[] elements, TextAccessor text, Choi Writer.WriteLine("}"); } - private void WriteElements(string source, ElementAccessor[] elements, TextAccessor text, ChoiceIdentifierAccessor choice, string arrayName, bool writeAccessors, bool isNullable) + private void WriteElements(string source, ElementAccessor[] elements, TextAccessor? text, ChoiceIdentifierAccessor? choice, string arrayName, bool writeAccessors, bool isNullable) { WriteElements(source, null, elements, text, choice, arrayName, writeAccessors, isNullable); } - private void WriteElements(string source, string enumSource, ElementAccessor[] elements, TextAccessor text, ChoiceIdentifierAccessor choice, string arrayName, bool writeAccessors, bool isNullable) + private void WriteElements(string source, string? enumSource, ElementAccessor[] elements, TextAccessor? text, ChoiceIdentifierAccessor? choice, string arrayName, bool writeAccessors, bool isNullable) { if (elements.Length == 0 && text == null) return; if (elements.Length == 1 && text == null) { - TypeDesc td = elements[0].IsUnbounded ? elements[0].Mapping.TypeDesc.CreateArrayTypeDesc() : elements[0].Mapping.TypeDesc; - if (!elements[0].Any && !elements[0].Mapping.TypeDesc.UseReflection && !elements[0].Mapping.TypeDesc.IsOptionalValue) + TypeDesc td = elements[0].IsUnbounded ? elements[0].Mapping!.TypeDesc!.CreateArrayTypeDesc() : elements[0].Mapping!.TypeDesc!; + if (!elements[0].Any && !elements[0].Mapping!.TypeDesc!.UseReflection && !elements[0].Mapping!.TypeDesc!.IsOptionalValue) source = "((" + td.CSharpName + ")" + source + ")"; WriteElement(source, elements[0], arrayName, writeAccessors); } @@ -3581,9 +3598,9 @@ private void WriteElements(string source, string enumSource, ElementAccessor[] e Writer.Indent++; int anyCount = 0; ArrayList namedAnys = new ArrayList(); - ElementAccessor unnamedAny = null; // can only have one + ElementAccessor? unnamedAny = null; // can only have one bool wroteFirstIf = false; - string enumTypeName = choice == null ? null : choice.Mapping.TypeDesc.FullName; + string? enumTypeName = choice == null ? null : choice.Mapping!.TypeDesc!.FullName; for (int i = 0; i < elements.Length; i++) { @@ -3599,15 +3616,15 @@ private void WriteElements(string source, string enumSource, ElementAccessor[] e } else if (choice != null) { - bool useReflection = element.Mapping.TypeDesc.UseReflection; + bool useReflection = element.Mapping!.TypeDesc!.UseReflection; string fullTypeName = element.Mapping.TypeDesc.CSharpName; - bool enumUseReflection = choice.Mapping.TypeDesc.UseReflection; + bool enumUseReflection = choice.Mapping!.TypeDesc!.UseReflection; string enumFullName = (enumUseReflection ? "" : enumTypeName + ".@") + FindChoiceEnumValue(element, (EnumMapping)choice.Mapping, enumUseReflection); if (wroteFirstIf) Writer.Write("else "); else wroteFirstIf = true; Writer.Write("if ("); - Writer.Write(enumUseReflection ? RaCodeGen.GetStringForEnumLongValue(enumSource, enumUseReflection) : enumSource); + Writer.Write(enumUseReflection ? RaCodeGen.GetStringForEnumLongValue(enumSource!, enumUseReflection) : enumSource); Writer.Write(" == "); Writer.Write(enumFullName); if (isNullable && !element.IsNullable) @@ -3630,7 +3647,7 @@ private void WriteElements(string source, string enumSource, ElementAccessor[] e } else { - bool useReflection = element.Mapping.TypeDesc.UseReflection; + bool useReflection = element.Mapping!.TypeDesc!.UseReflection; TypeDesc td = element.IsUnbounded ? element.Mapping.TypeDesc.CreateArrayTypeDesc() : element.Mapping.TypeDesc; string fullTypeName = td.CSharpName; if (wroteFirstIf) Writer.Write("else "); @@ -3651,7 +3668,7 @@ private void WriteElements(string source, string enumSource, ElementAccessor[] e { if (elements.Length - anyCount > 0) Writer.Write("else "); - string fullTypeName = typeof(XmlElement).FullName; + string fullTypeName = typeof(XmlElement).FullName!; Writer.Write("if ("); Writer.Write(source); @@ -3673,15 +3690,15 @@ private void WriteElements(string source, string enumSource, ElementAccessor[] e { if (c++ > 0) Writer.Write("else "); - string enumFullName = null; + string? enumFullName = null; - bool useReflection = element.Mapping.TypeDesc.UseReflection; + bool useReflection = element.Mapping!.TypeDesc!.UseReflection; if (choice != null) { - bool enumUseReflection = choice.Mapping.TypeDesc.UseReflection; + bool enumUseReflection = choice.Mapping!.TypeDesc!.UseReflection; enumFullName = (enumUseReflection ? "" : enumTypeName + ".@") + FindChoiceEnumValue(element, (EnumMapping)choice.Mapping, enumUseReflection); Writer.Write("if ("); - Writer.Write(enumUseReflection ? RaCodeGen.GetStringForEnumLongValue(enumSource, enumUseReflection) : enumSource); + Writer.Write(enumUseReflection ? RaCodeGen.GetStringForEnumLongValue(enumSource!, enumUseReflection) : enumSource); Writer.Write(" == "); Writer.Write(enumFullName); if (isNullable && !element.IsNullable) @@ -3744,7 +3761,7 @@ private void WriteElements(string source, string enumSource, ElementAccessor[] e } if (text != null) { - bool useReflection = text.Mapping.TypeDesc.UseReflection; + bool useReflection = text.Mapping!.TypeDesc!.UseReflection; string fullTypeName = text.Mapping.TypeDesc.CSharpName; if (elements.Length > 0) { @@ -3806,14 +3823,14 @@ private void WriteText(string source, TextAccessor text) } else { - WritePrimitiveValue(mapping.TypeDesc, source, false); + WritePrimitiveValue(mapping.TypeDesc!, source, false); } Writer.WriteLine(");"); } else if (text.Mapping is SpecialMapping) { SpecialMapping mapping = (SpecialMapping)text.Mapping; - switch (mapping.TypeDesc.Kind) + switch (mapping.TypeDesc!.Kind) { case TypeKind.Node: Writer.Write(source); @@ -3827,15 +3844,15 @@ private void WriteText(string source, TextAccessor text) private void WriteElement(string source, ElementAccessor element, string arrayName, bool writeAccessor) { - string name = writeAccessor ? element.Name : element.Mapping.TypeName; - string ns = element.Any && element.Name.Length == 0 ? null : (element.Form == XmlSchemaForm.Qualified ? (writeAccessor ? element.Namespace : element.Mapping.Namespace) : ""); + string name = writeAccessor ? element.Name : element.Mapping!.TypeName!; + string? ns = element.Any && element.Name.Length == 0 ? null : (element.Form == XmlSchemaForm.Qualified ? (writeAccessor ? element.Namespace : element.Mapping!.Namespace) : ""); if (element.Mapping is NullableMapping) { Writer.Write("if ("); Writer.Write(source); Writer.WriteLine(" != null) {"); Writer.Indent++; - string fullTypeName = element.Mapping.TypeDesc.BaseTypeDesc.CSharpName; + string fullTypeName = element.Mapping.TypeDesc!.BaseTypeDesc!.CSharpName; string castedSource = source; if (!element.Mapping.TypeDesc.BaseTypeDesc.UseReflection) castedSource = "((" + fullTypeName + ")" + source + ")"; @@ -3867,7 +3884,7 @@ private void WriteElement(string source, ElementAccessor element, string arrayNa if (!writeAccessor) { Writer.Write(", "); - Writer.Write(RaCodeGen.GetStringForTypeof(mapping.TypeDesc.CSharpName, mapping.TypeDesc.UseReflection)); + Writer.Write(RaCodeGen.GetStringForTypeof(mapping.TypeDesc!.CSharpName, mapping.TypeDesc.UseReflection)); Writer.Write(", true, "); } else @@ -3879,7 +3896,7 @@ private void WriteElement(string source, ElementAccessor element, string arrayNa } else if (element.IsUnbounded) { - TypeDesc td = mapping.TypeDesc.CreateArrayTypeDesc(); + TypeDesc td = mapping.TypeDesc!.CreateArrayTypeDesc(); string fullTypeName = td.CSharpName; string elementArrayName = "el" + arrayName; string arrayIndex = "c" + elementArrayName; @@ -3940,7 +3957,7 @@ private void WriteElement(string source, ElementAccessor element, string arrayNa } else { - string fullTypeName = mapping.TypeDesc.CSharpName; + string fullTypeName = mapping.TypeDesc!.CSharpName; Writer.WriteLine("{"); Writer.Indent++; WriteArrayLocalDecl(fullTypeName, arrayName, source, mapping.TypeDesc); @@ -3960,7 +3977,7 @@ private void WriteElement(string source, ElementAccessor element, string arrayNa Writer.Indent++; } WriteStartElement(name, ns, false); - WriteArrayItems(mapping.ElementsSortedByDerivation, null, null, mapping.TypeDesc, arrayName, null); + WriteArrayItems(mapping.ElementsSortedByDerivation!, null, null, mapping.TypeDesc, arrayName, null); WriteEndElement(); Writer.Indent--; Writer.WriteLine("}"); @@ -3972,7 +3989,7 @@ private void WriteElement(string source, ElementAccessor element, string arrayNa { if (element.Mapping.IsSoap) { - string methodName = (string)MethodNames[element.Mapping]; + string methodName = (string)MethodNames[element.Mapping]!; Writer.Write("Writer.WriteStartElement("); WriteQuotedCSharpString(name); Writer.Write(", "); @@ -3997,7 +4014,7 @@ private void WriteElement(string source, ElementAccessor element, string arrayNa else { string suffixNullable = mapping.IsSoap ? "Encoded" : "Literal"; - string suffixRaw = mapping.TypeDesc.XmlEncodingNotRequired ? "Raw" : ""; + string suffixRaw = mapping.TypeDesc!.XmlEncodingNotRequired ? "Raw" : ""; WritePrimitive(element.IsNullable ? ("WriteNullableString" + suffixNullable + suffixRaw) : ("WriteElementString" + suffixRaw), name, ns, element.Default, source, mapping, mapping.IsSoap, true, element.IsNullable); } @@ -4017,7 +4034,7 @@ private void WriteElement(string source, ElementAccessor element, string arrayNa if (!writeAccessor) { Writer.Write(", "); - Writer.Write(RaCodeGen.GetStringForTypeof(mapping.TypeDesc.CSharpName, mapping.TypeDesc.UseReflection)); + Writer.Write(RaCodeGen.GetStringForTypeof(mapping.TypeDesc!.CSharpName, mapping.TypeDesc.UseReflection)); Writer.Write(", true, "); } else @@ -4028,11 +4045,11 @@ private void WriteElement(string source, ElementAccessor element, string arrayNa } else { - string methodName = ReferenceMapping(mapping); + string? methodName = ReferenceMapping(mapping); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe - if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc.Name) + Environment.StackTrace); + if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc!.Name) + Environment.StackTrace); #endif Writer.Write(methodName); Writer.Write("("); @@ -4046,7 +4063,7 @@ private void WriteElement(string source, ElementAccessor element, string arrayNa } Writer.Write(", "); Writer.Write(source); - if (mapping.TypeDesc.IsNullable) + if (mapping.TypeDesc!.IsNullable) { Writer.Write(", "); WriteValue(element.IsNullable); @@ -4058,7 +4075,7 @@ private void WriteElement(string source, ElementAccessor element, string arrayNa else if (element.Mapping is SpecialMapping) { SpecialMapping mapping = (SpecialMapping)element.Mapping; - bool useReflection = mapping.TypeDesc.UseReflection; + bool useReflection = mapping.TypeDesc!.UseReflection; TypeDesc td = mapping.TypeDesc; string fullTypeName = td.CSharpName; @@ -4101,7 +4118,7 @@ private void WriteElement(string source, ElementAccessor element, string arrayNa } } - private void WriteElementCall(string func, Type cast, string source, string name, string ns, bool isNullable, bool isAny) + private void WriteElementCall(string func, Type cast, string source, string name, string? ns, bool isNullable, bool isAny) { Writer.Write(func); Writer.Write("(("); @@ -4140,7 +4157,7 @@ private void WriteCheckDefault(TypeMapping mapping, string source, object value, Writer.Write("!"); Writer.Write(source); Writer.Write(".Equals("); - Type type = Type.GetType(mapping.TypeDesc.Type.FullName); + Type? type = Type.GetType(mapping.TypeDesc!.Type!.FullName!); WriteValue(type != null ? Convert.ChangeType(value, type) : value); Writer.Write(")"); } @@ -4148,7 +4165,7 @@ private void WriteCheckDefault(TypeMapping mapping, string source, object value, { Writer.Write(source); Writer.Write(" != "); - Type type = Type.GetType(mapping.TypeDesc.Type.FullName); + Type? type = Type.GetType(mapping.TypeDesc!.Type!.FullName!); WriteValue(type != null ? Convert.ChangeType(value, type) : value); } Writer.Write(")"); @@ -4335,7 +4352,7 @@ private void WriteLocalDecl(string typeName, string variableName, string initVal RaCodeGen.WriteLocalDecl(typeName, variableName, initValue, useReflection); } - private void WriteArrayLocalDecl(string typeName, string variableName, string initValue, TypeDesc arrayTypeDesc) + private void WriteArrayLocalDecl(string typeName, string variableName, string? initValue, TypeDesc arrayTypeDesc) { RaCodeGen.WriteArrayLocalDecl(typeName, variableName, initValue, arrayTypeDesc); } @@ -4359,9 +4376,9 @@ private void WriteEnumCase(string fullTypeName, ConstantMapping c, bool useRefle private string FindChoiceEnumValue(ElementAccessor element, EnumMapping choiceMapping, bool useReflection) { - string enumValue = null; + string? enumValue = null; - for (int i = 0; i < choiceMapping.Constants.Length; i++) + for (int i = 0; i < choiceMapping.Constants!.Length; i++) { string xmlName = choiceMapping.Constants[i].XmlName; @@ -4378,7 +4395,7 @@ private string FindChoiceEnumValue(ElementAccessor element, EnumMapping choiceMa continue; } int colon = xmlName.LastIndexOf(':'); - string choiceNs = colon < 0 ? choiceMapping.Namespace : xmlName.Substring(0, colon); + string? choiceNs = colon < 0 ? choiceMapping.Namespace : xmlName.Substring(0, colon); string choiceName = colon < 0 ? xmlName : xmlName.Substring(colon + 1); if (element.Name == choiceName) @@ -4398,10 +4415,10 @@ private string FindChoiceEnumValue(ElementAccessor element, EnumMapping choiceMa if (element.Any && element.Name.Length == 0) { // Type {0} is missing enumeration value '##any' for XmlAnyElementAttribute. - throw new InvalidOperationException(SR.Format(SR.XmlChoiceMissingAnyValue, choiceMapping.TypeDesc.FullName)); + throw new InvalidOperationException(SR.Format(SR.XmlChoiceMissingAnyValue, choiceMapping.TypeDesc!.FullName)); } // Type {0} is missing value for '{1}'. - throw new InvalidOperationException(SR.Format(SR.XmlChoiceMissingValue, choiceMapping.TypeDesc.FullName, element.Namespace + ":" + element.Name, element.Name, element.Namespace)); + throw new InvalidOperationException(SR.Format(SR.XmlChoiceMissingValue, choiceMapping.TypeDesc!.FullName, element.Namespace + ":" + element.Name, element.Name, element.Namespace)); } if (!useReflection) CodeIdentifier.CheckValidIdentifier(enumValue); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriterILGen.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriterILGen.cs index 99972df52fed01..e907ffc6471e24 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriterILGen.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriterILGen.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; using System.Collections; using System.Collections.Generic; @@ -11,6 +12,7 @@ using System.Text; using System.Xml.Schema; using System.Xml.Extensions; +using System.Diagnostics.CodeAnalysis; namespace System.Xml.Serialization { @@ -36,7 +38,7 @@ internal void GenerateBegin() { if (mapping is StructMapping || mapping is EnumMapping) { - MethodNames.Add(mapping, NextMethodName(mapping.TypeDesc.Name)); + MethodNames.Add(mapping, NextMethodName(mapping.TypeDesc!.Name)); } } RaCodeGen.WriteReflectionInit(scope); @@ -63,10 +65,10 @@ internal Type GenerateEnd() GenerateInitCallbacksMethod(); this.typeBuilder.DefineDefaultConstructor( CodeGenerator.PublicMethodAttributes); - return this.typeBuilder.CreateTypeInfo().AsType(); + return this.typeBuilder.CreateTypeInfo()!.AsType(); } - internal string GenerateElement(XmlMapping xmlMapping) + internal string? GenerateElement(XmlMapping xmlMapping) { if (!xmlMapping.IsWriteable) return null; @@ -88,7 +90,7 @@ private void GenerateInitCallbacksMethod() ilg.EndMethod(); } - private void WriteQualifiedNameElement(string name, string ns, object defaultValue, SourceInfo source, bool nullable, TypeMapping mapping) + private void WriteQualifiedNameElement(string name, string? ns, object? defaultValue, SourceInfo source, bool nullable, TypeMapping mapping) { bool hasDefault = defaultValue != null && defaultValue != DBNull.Value; if (hasDefault) @@ -104,14 +106,14 @@ private void WriteQualifiedNameElement(string name, string ns, object defaultVal ilg.Ldstr(GetCSharpString(ns)); argTypes.Add(typeof(string)); } - source.Load(mapping.TypeDesc.Type); - argTypes.Add(mapping.TypeDesc.Type); + source.Load(mapping.TypeDesc!.Type!); + argTypes.Add(mapping.TypeDesc.Type!); MethodInfo XmlSerializationWriter_WriteXXX = typeof(XmlSerializationWriter).GetMethod( nullable ? ("WriteNullableQualifiedNameLiteral") : "WriteElementQualifiedName", CodeGenerator.InstanceBindingFlags, argTypes.ToArray() - ); + )!; ilg.Call(XmlSerializationWriter_WriteXXX); if (hasDefault) @@ -122,22 +124,22 @@ private void WriteQualifiedNameElement(string name, string ns, object defaultVal private void WriteEnumValue(EnumMapping mapping, SourceInfo source, out Type returnType) { - string methodName = ReferenceMapping(mapping); + string? methodName = ReferenceMapping(mapping); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe - if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc.Name)); + if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc!.Name)); #endif // For enum, its write method (eg. Write1_Gender) could be called multiple times // prior to its declaration. MethodBuilder methodBuilder = EnsureMethodBuilder(typeBuilder, - methodName, + methodName!, CodeGenerator.PrivateMethodAttributes, typeof(string), - new Type[] { mapping.TypeDesc.Type }); + new Type[] { mapping.TypeDesc!.Type! }); ilg.Ldarg(0); - source.Load(mapping.TypeDesc.Type); + source.Load(mapping.TypeDesc.Type!); ilg.Call(methodBuilder); returnType = typeof(string); } @@ -146,14 +148,14 @@ private void WritePrimitiveValue(TypeDesc typeDesc, SourceInfo source, out Type { if (typeDesc == StringTypeDesc || typeDesc.FormatterName == "String") { - source.Load(typeDesc.Type); - returnType = typeDesc.Type; + source.Load(typeDesc.Type!); + returnType = typeDesc.Type!; } else { if (!typeDesc.HasCustomFormatter) { - Type argType = typeDesc.Type; + Type argType = typeDesc.Type!; // No ToString(Byte), compiler used ToString(Int16) instead. if (argType == typeof(byte)) argType = typeof(short); @@ -164,8 +166,8 @@ private void WritePrimitiveValue(TypeDesc typeDesc, SourceInfo source, out Type "ToString", CodeGenerator.StaticBindingFlags, new Type[] { argType } - ); - source.Load(typeDesc.Type); + )!; + source.Load(typeDesc.Type!); ilg.Call(XmlConvert_ToString); returnType = XmlConvert_ToString.ReturnType; } @@ -181,33 +183,33 @@ private void WritePrimitiveValue(TypeDesc typeDesc, SourceInfo source, out Type MethodInfo FromXXX = typeof(XmlSerializationWriter).GetMethod( "From" + typeDesc.FormatterName, bindingFlags, - new Type[] { typeDesc.Type } - ); - source.Load(typeDesc.Type); + new Type[] { typeDesc.Type! } + )!; + source.Load(typeDesc.Type!); ilg.Call(FromXXX); returnType = FromXXX.ReturnType; } } } - private void WritePrimitive(string method, string name, string ns, object defaultValue, SourceInfo source, TypeMapping mapping, bool writeXsiType, bool isElement, bool isNullable) + private void WritePrimitive(string method, string name, string? ns, object? defaultValue, SourceInfo source, TypeMapping mapping, bool writeXsiType, bool isElement, bool isNullable) { - TypeDesc typeDesc = mapping.TypeDesc; - bool hasDefault = defaultValue != null && defaultValue != DBNull.Value && mapping.TypeDesc.HasDefaultSupport; + TypeDesc typeDesc = mapping.TypeDesc!; + bool hasDefault = defaultValue != null && defaultValue != DBNull.Value && mapping.TypeDesc!.HasDefaultSupport; if (hasDefault) { if (mapping is EnumMapping) { #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe - if (defaultValue.GetType() != typeof(string)) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, name + " has invalid default type " + defaultValue.GetType().Name)); + if (defaultValue!.GetType() != typeof(string)) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, name + " has invalid default type " + defaultValue.GetType().Name)); #endif - source.Load(mapping.TypeDesc.Type); - string enumDefaultValue = null; + source.Load(mapping.TypeDesc!.Type!); + string? enumDefaultValue = null; if (((EnumMapping)mapping).IsFlags) { - string[] values = ((string)defaultValue).Split(null); + string[] values = ((string)defaultValue!).Split(null); for (int i = 0; i < values.Length; i++) { if (values[i] == null || values[i].Length == 0) @@ -219,14 +221,14 @@ private void WritePrimitive(string method, string name, string ns, object defaul } else { - enumDefaultValue = (string)defaultValue; + enumDefaultValue = (string)defaultValue!; } - ilg.Ldc(Enum.Parse(mapping.TypeDesc.Type, enumDefaultValue, false)); + ilg.Ldc(Enum.Parse(mapping.TypeDesc.Type!, enumDefaultValue!, false)); ilg.If(Cmp.NotEqualTo); // " != " } else { - WriteCheckDefault(source, defaultValue, isNullable); + WriteCheckDefault(source, defaultValue!, isNullable); } } List argTypes = new List(); @@ -257,7 +259,7 @@ private void WritePrimitive(string method, string name, string ns, object defaul ConstructorInfo XmlQualifiedName_ctor = typeof(XmlQualifiedName).GetConstructor( CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string) } - ); + )!; ilg.Ldstr(GetCSharpString(mapping.TypeName)); ilg.Ldstr(GetCSharpString(mapping.Namespace)); ilg.New(XmlQualifiedName_ctor); @@ -267,7 +269,7 @@ private void WritePrimitive(string method, string name, string ns, object defaul method, CodeGenerator.InstanceBindingFlags, argTypes.ToArray() - ); + )!; ilg.Call(XmlSerializationWriter_method); if (hasDefault) @@ -276,26 +278,26 @@ private void WritePrimitive(string method, string name, string ns, object defaul } } - private void WriteTag(string methodName, string name, string ns) + private void WriteTag(string methodName, string name, string? ns) { MethodInfo XmlSerializationWriter_Method = typeof(XmlSerializationWriter).GetMethod( methodName, CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Ldstr(GetCSharpString(name)); ilg.Ldstr(GetCSharpString(ns)); ilg.Call(XmlSerializationWriter_Method); } - private void WriteTag(string methodName, string name, string ns, bool writePrefixed) + private void WriteTag(string methodName, string name, string? ns, bool writePrefixed) { MethodInfo XmlSerializationWriter_Method = typeof(XmlSerializationWriter).GetMethod( methodName, CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string), typeof(object), typeof(bool) } - ); + )!; ilg.Ldarg(0); ilg.Ldstr(GetCSharpString(name)); ilg.Ldstr(GetCSharpString(ns)); @@ -304,7 +306,7 @@ private void WriteTag(string methodName, string name, string ns, bool writePrefi ilg.Call(XmlSerializationWriter_Method); } - private void WriteStartElement(string name, string ns, bool writePrefixed) + private void WriteStartElement(string name, string? ns, bool writePrefixed) { WriteTag("WriteStartElement", name, ns, writePrefixed); } @@ -315,7 +317,7 @@ private void WriteEndElement() "WriteEndElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationWriter_WriteEndElement); } @@ -325,7 +327,7 @@ private void WriteEndElement(string source) "WriteEndElement", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(object) } - ); + )!; object oVar = ilg.GetVariable(source); ilg.Ldarg(0); ilg.Load(oVar); @@ -333,12 +335,12 @@ private void WriteEndElement(string source) ilg.Call(XmlSerializationWriter_WriteEndElement); } - private void WriteLiteralNullTag(string name, string ns) + private void WriteLiteralNullTag(string name, string? ns) { WriteTag("WriteNullTagLiteral", name, ns); } - private void WriteEmptyTag(string name, string ns) + private void WriteEmptyTag(string name, string? ns) { WriteTag("WriteEmptyTag", name, ns); } @@ -346,7 +348,7 @@ private void WriteEmptyTag(string name, string ns) private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) { ElementAccessor element = xmlMembersMapping.Accessor; - MembersMapping mapping = (MembersMapping)element.Mapping; + MembersMapping mapping = (MembersMapping)element.Mapping!; bool hasWrapperElement = mapping.HasWrapperElement; bool writeAccessors = mapping.WriteAccessors; string methodName = NextMethodName(element.Name); @@ -363,7 +365,7 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) "WriteStartDocument", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationWriter_WriteStartDocument); @@ -371,7 +373,7 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) "TopLevelElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationWriter_TopLevelElement); @@ -387,10 +389,10 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) { WriteStartElement(element.Name, (element.Form == XmlSchemaForm.Qualified ? element.Namespace : ""), false); - int xmlnsMember = FindXmlnsIndex(mapping.Members); + int xmlnsMember = FindXmlnsIndex(mapping.Members!); if (xmlnsMember >= 0) { - MemberMapping member = mapping.Members[xmlnsMember]; + MemberMapping member = mapping.Members![xmlnsMember]; string source = "((" + typeof(XmlSerializerNamespaces).FullName + ")p[" + xmlnsMember.ToString(CultureInfo.InvariantCulture) + "])"; ilg.Ldloc(pLengthLoc); @@ -400,15 +402,15 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) ilg.EndIf(); } - for (int i = 0; i < mapping.Members.Length; i++) + for (int i = 0; i < mapping.Members!.Length; i++) { MemberMapping member = mapping.Members[i]; if (member.Attribute != null && !member.Ignore) { - SourceInfo source = new SourceInfo("p[" + i.ToString(CultureInfo.InvariantCulture) + "]", null, null, pLengthLoc.LocalType.GetElementType(), ilg); + SourceInfo source = new SourceInfo("p[" + i.ToString(CultureInfo.InvariantCulture) + "]", null, null, pLengthLoc.LocalType.GetElementType()!, ilg); - SourceInfo specifiedSource = null; + SourceInfo? specifiedSource = null; int specifiedPosition = 0; if (member.CheckSpecified != SpecifiedAccessor.None) { @@ -443,7 +445,7 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) ilg.If(); } - WriteMember(source, member.Attribute, member.TypeDesc, "p"); + WriteMember(source, member.Attribute, member.TypeDesc!, "p"); if (specifiedSource != null) { @@ -455,7 +457,7 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) } } - for (int i = 0; i < mapping.Members.Length; i++) + for (int i = 0; i < mapping.Members!.Length; i++) { MemberMapping member = mapping.Members[i]; if (member.Xmlns != null) @@ -463,7 +465,7 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) if (member.Ignore) continue; - SourceInfo specifiedSource = null; + SourceInfo? specifiedSource = null; int specifiedPosition = 0; if (member.CheckSpecified != SpecifiedAccessor.None) { @@ -500,14 +502,14 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) } string source = "p[" + i.ToString(CultureInfo.InvariantCulture) + "]"; - string enumSource = null; + string? enumSource = null; if (member.ChoiceIdentifier != null) { for (int j = 0; j < mapping.Members.Length; j++) { if (mapping.Members[j].Name == member.ChoiceIdentifier.MemberName) { - enumSource = "((" + mapping.Members[j].TypeDesc.CSharpName + ")p[" + j.ToString(CultureInfo.InvariantCulture) + "]" + ")"; + enumSource = "((" + mapping.Members[j].TypeDesc!.CSharpName + ")p[" + j.ToString(CultureInfo.InvariantCulture) + "]" + ")"; break; } } @@ -519,7 +521,7 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) } // override writeAccessors choice when we've written a wrapper element - WriteMember(new SourceInfo(source, source, null, null, ilg), enumSource, member.ElementsSortedByDerivation, member.Text, member.ChoiceIdentifier, member.TypeDesc, writeAccessors || hasWrapperElement); + WriteMember(new SourceInfo(source, source, null, null, ilg), enumSource, member.ElementsSortedByDerivation!, member.Text, member.ChoiceIdentifier, member.TypeDesc!, writeAccessors || hasWrapperElement); if (specifiedSource != null) { @@ -540,7 +542,7 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) private string GenerateTypeElement(XmlTypeMapping xmlTypeMapping) { ElementAccessor element = xmlTypeMapping.Accessor; - TypeMapping mapping = element.Mapping; + TypeMapping mapping = element.Mapping!; string methodName = NextMethodName(element.Name); ilg = new CodeGenerator(this.typeBuilder); ilg.BeginMethod( @@ -555,7 +557,7 @@ private string GenerateTypeElement(XmlTypeMapping xmlTypeMapping) "WriteStartDocument", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationWriter_WriteStartDocument); @@ -569,13 +571,13 @@ private string GenerateTypeElement(XmlTypeMapping xmlTypeMapping) ilg.GotoMethodEnd(); ilg.EndIf(); - if (!mapping.TypeDesc.IsValueType && !mapping.TypeDesc.Type.IsPrimitive) + if (!mapping.TypeDesc!.IsValueType && !mapping.TypeDesc.Type!.IsPrimitive) { MethodInfo XmlSerializationWriter_TopLevelElement = typeof(XmlSerializationWriter).GetMethod( "TopLevelElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationWriter_TopLevelElement); } @@ -593,23 +595,23 @@ private string NextMethodName(string name) private void WriteEnumMethod(EnumMapping mapping) { - string methodName; + string? methodName; MethodNames.TryGetValue(mapping, out methodName); List argTypes = new List(); List argNames = new List(); - argTypes.Add(mapping.TypeDesc.Type); + argTypes.Add(mapping.TypeDesc!.Type!); argNames.Add("v"); ilg = new CodeGenerator(this.typeBuilder); ilg.BeginMethod( typeof(string), - GetMethodBuilder(methodName), + GetMethodBuilder(methodName!), argTypes.ToArray(), argNames.ToArray(), CodeGenerator.PrivateMethodAttributes); LocalBuilder sLoc = ilg.DeclareLocal(typeof(string), "s"); ilg.Load(null); ilg.Stloc(sLoc); - ConstantMapping[] constants = mapping.Constants; + ConstantMapping[] constants = mapping.Constants!; if (constants.Length > 0) { @@ -619,7 +621,7 @@ private void WriteEnumMethod(EnumMapping mapping) Label defaultLabel = ilg.DefineLabel(); Label endSwitchLabel = ilg.DefineLabel(); // This local is necessary; otherwise, it becomes if/else - LocalBuilder localTmp = ilg.DeclareLocal(mapping.TypeDesc.Type, "localTmp"); + LocalBuilder localTmp = ilg.DeclareLocal(mapping.TypeDesc.Type!, "localTmp"); ilg.Ldarg("v"); ilg.Stloc(localTmp); for (int i = 0; i < constants.Length; i++) @@ -629,7 +631,7 @@ private void WriteEnumMethod(EnumMapping mapping) { Label caseLabel = ilg.DefineLabel(); ilg.Ldloc(localTmp); - ilg.Ldc(Enum.ToObject(mapping.TypeDesc.Type, c.Value)); + ilg.Ldc(Enum.ToObject(mapping.TypeDesc.Type!, c.Value)); ilg.Beq(caseLabel); caseLabels.Add(caseLabel); retValues.Add(GetCSharpString(c.XmlName)); @@ -679,7 +681,7 @@ private void WriteEnumMethod(EnumMapping mapping) "FromEnum", CodeGenerator.StaticBindingFlags, new Type[] { typeof(long), typeof(string[]), typeof(long[]), typeof(string) } - ); + )!; ilg.Call(XmlSerializationWriter_FromEnum); ilg.Stloc(sLoc); ilg.Br(endSwitchLabel); @@ -699,22 +701,22 @@ private void WriteEnumMethod(EnumMapping mapping) "get_InvariantCulture", CodeGenerator.StaticBindingFlags, Array.Empty() - ); + )!; MethodInfo Int64_ToString = typeof(long).GetMethod( "ToString", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(IFormatProvider) } - ); + )!; MethodInfo XmlSerializationWriter_CreateInvalidEnumValueException = typeof(XmlSerializationWriter).GetMethod( "CreateInvalidEnumValueException", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(object), typeof(string) } - ); + )!; // Default body ilg.MarkLabel(defaultLabel); ilg.Ldarg(0); ilg.Ldarg("v"); - ilg.ConvertValue(mapping.TypeDesc.Type, typeof(long)); + ilg.ConvertValue(mapping.TypeDesc.Type!, typeof(long)); LocalBuilder numLoc = ilg.DeclareLocal(typeof(long), "num"); ilg.Stloc(numLoc); // Invoke method on Value type need address @@ -733,17 +735,17 @@ private void WriteEnumMethod(EnumMapping mapping) private void WriteDerivedTypes(StructMapping mapping) { - for (StructMapping derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) + for (StructMapping? derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) { ilg.InitElseIf(); - WriteTypeCompare("t", derived.TypeDesc.Type); + WriteTypeCompare("t", derived.TypeDesc!.Type!); ilg.AndIf(); - string methodName = ReferenceMapping(derived); + string? methodName = ReferenceMapping(derived); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe - if (methodName == null) throw new InvalidOperationException("derived from " + mapping.TypeDesc.FullName + ", " + SR.Format(SR.XmlInternalErrorMethod, derived.TypeDesc.Name)); + if (methodName == null) throw new InvalidOperationException("derived from " + mapping.TypeDesc!.FullName + ", " + SR.Format(SR.XmlInternalErrorMethod, derived.TypeDesc.Name)); #endif List argTypes = new List(); @@ -755,8 +757,8 @@ private void WriteDerivedTypes(StructMapping mapping) object oVar = ilg.GetVariable("o"); Type oType = ilg.GetVariableType(oVar); ilg.Load(oVar); - ilg.ConvertValue(oType, derived.TypeDesc.Type); - argTypes.Add(derived.TypeDesc.Type); + ilg.ConvertValue(oType, derived.TypeDesc.Type!); + argTypes.Add(derived.TypeDesc.Type!); if (derived.TypeDesc.IsNullable) { argTypes.Add(typeof(bool)); @@ -765,7 +767,7 @@ private void WriteDerivedTypes(StructMapping mapping) argTypes.Add(typeof(bool)); ilg.Ldc(true); MethodInfo methodBuilder = EnsureMethodBuilder(typeBuilder, - methodName, + methodName!, CodeGenerator.PrivateMethodAttributes, typeof(void), argTypes.ToArray()); @@ -786,11 +788,11 @@ private void WriteEnumAndArrayTypes() { EnumMapping mapping = (EnumMapping)m; ilg.InitElseIf(); - WriteTypeCompare("t", mapping.TypeDesc.Type); + WriteTypeCompare("t", mapping.TypeDesc!.Type!); // WriteXXXTypeCompare leave bool on the stack ilg.AndIf(); - string methodName = ReferenceMapping(mapping); + string? methodName = ReferenceMapping(mapping); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe @@ -800,12 +802,12 @@ private void WriteEnumAndArrayTypes() "get_Writer", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlWriter_WriteStartElement = typeof(XmlWriter).GetMethod( "WriteStartElement", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationWriter_get_Writer); ilg.Ldarg("n"); @@ -815,35 +817,35 @@ private void WriteEnumAndArrayTypes() "WriteXsiType", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Ldstr(GetCSharpString(mapping.TypeName)); ilg.Ldstr(GetCSharpString(mapping.Namespace)); ilg.Call(XmlSerializationWriter_WriteXsiType); MethodBuilder methodBuilder = EnsureMethodBuilder(typeBuilder, - methodName, + methodName!, CodeGenerator.PrivateMethodAttributes, typeof(string), - new Type[] { mapping.TypeDesc.Type } + new Type[] { mapping.TypeDesc.Type! } ); MethodInfo XmlWriter_WriteString = typeof(XmlWriter).GetMethod( "WriteString", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationWriter_get_Writer); object oVar = ilg.GetVariable("o"); ilg.Ldarg(0); ilg.Load(oVar); - ilg.ConvertValue(ilg.GetVariableType(oVar), mapping.TypeDesc.Type); + ilg.ConvertValue(ilg.GetVariableType(oVar), mapping.TypeDesc.Type!); ilg.Call(methodBuilder); ilg.Call(XmlWriter_WriteString); MethodInfo XmlWriter_WriteEndElement = typeof(XmlWriter).GetMethod( "WriteEndElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationWriter_get_Writer); ilg.Call(XmlWriter_WriteEndElement); @@ -851,13 +853,13 @@ private void WriteEnumAndArrayTypes() } else if (m is ArrayMapping) { - ArrayMapping mapping = m as ArrayMapping; + ArrayMapping? mapping = m as ArrayMapping; if (mapping == null) continue; ilg.InitElseIf(); - if (mapping.TypeDesc.IsArray) - WriteArrayTypeCompare("t", mapping.TypeDesc.Type); + if (mapping.TypeDesc!.IsArray) + WriteArrayTypeCompare("t", mapping.TypeDesc.Type!); else - WriteTypeCompare("t", mapping.TypeDesc.Type); + WriteTypeCompare("t", mapping.TypeDesc.Type!); // WriteXXXTypeCompare leave bool on the stack ilg.AndIf(); ilg.EnterScope(); @@ -866,12 +868,12 @@ private void WriteEnumAndArrayTypes() "get_Writer", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlWriter_WriteStartElement = typeof(XmlWriter).GetMethod( "WriteStartElement", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationWriter_get_Writer); ilg.Ldarg("n"); @@ -881,19 +883,19 @@ private void WriteEnumAndArrayTypes() "WriteXsiType", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Ldstr(GetCSharpString(mapping.TypeName)); ilg.Ldstr(GetCSharpString(mapping.Namespace)); ilg.Call(XmlSerializationWriter_WriteXsiType); - WriteMember(new SourceInfo("o", "o", null, null, ilg), null, mapping.ElementsSortedByDerivation, null, null, mapping.TypeDesc, true); + WriteMember(new SourceInfo("o", "o", null, null, ilg), null, mapping.ElementsSortedByDerivation!, null, null, mapping.TypeDesc, true); MethodInfo XmlWriter_WriteEndElement = typeof(XmlWriter).GetMethod( "WriteEndElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationWriter_get_Writer); ilg.Call(XmlWriter_WriteEndElement); @@ -906,7 +908,7 @@ private void WriteEnumAndArrayTypes() private void WriteStructMethod(StructMapping mapping) { - string methodName; + string? methodName; MethodNames.TryGetValue(mapping, out methodName); ilg = new CodeGenerator(this.typeBuilder); @@ -916,7 +918,7 @@ private void WriteStructMethod(StructMapping mapping) argNames.Add("n"); argTypes.Add(typeof(string)); argNames.Add("ns"); - argTypes.Add(mapping.TypeDesc.Type); + argTypes.Add(mapping.TypeDesc!.Type!); argNames.Add("o"); if (mapping.TypeDesc.IsNullable) { @@ -926,7 +928,7 @@ private void WriteStructMethod(StructMapping mapping) argTypes.Add(typeof(bool)); argNames.Add("needType"); ilg.BeginMethod(typeof(void), - GetMethodBuilder(methodName), + GetMethodBuilder(methodName!), argTypes.ToArray(), argNames.ToArray(), CodeGenerator.PrivateMethodAttributes); @@ -940,7 +942,7 @@ private void WriteStructMethod(StructMapping mapping) "WriteNullTagLiteral", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Ldarg("n"); ilg.Ldarg("ns"); @@ -958,13 +960,13 @@ private void WriteStructMethod(StructMapping mapping) "GetType", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ArgBuilder oArg = ilg.GetArg("o"); ilg.LdargAddress(oArg); ilg.ConvertAddress(oArg.ArgType, typeof(object)); ilg.Call(Object_GetType); ilg.Stloc(tLoc); - WriteTypeCompare("t", mapping.TypeDesc.Type); + WriteTypeCompare("t", mapping.TypeDesc.Type!); // Bool on the stack from WriteTypeCompare. ilg.If(); // if (t == typeof(...)) WriteDerivedTypes(mapping); @@ -977,7 +979,7 @@ private void WriteStructMethod(StructMapping mapping) "WriteTypedPrimitive", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string), typeof(object), typeof(bool) } - ); + )!; ilg.Ldarg(0); ilg.Ldarg("n"); ilg.Ldarg("ns"); @@ -992,7 +994,7 @@ private void WriteStructMethod(StructMapping mapping) "CreateUnknownTypeException", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(object) } - ); + )!; ilg.Ldarg(0); ilg.Ldarg(oArg); ilg.ConvertValue(oArg.ArgType, typeof(object)); @@ -1010,13 +1012,13 @@ private void WriteStructMethod(StructMapping mapping) "set_EscapeName", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(bool) } - ); + )!; ilg.Ldarg(0); ilg.Ldc(false); ilg.Call(XmlSerializationWriter_set_EscapeName); } - string xmlnsSource = null; + string? xmlnsSource = null; MemberMapping[] members = TypeScope.GetAllMembers(mapping, memberInfos); int xmlnsMember = FindXmlnsIndex(members); if (xmlnsMember >= 0) @@ -1045,7 +1047,7 @@ private void WriteStructMethod(StructMapping mapping) "WriteStartElement", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string), typeof(object), typeof(bool), typeof(XmlSerializerNamespaces) } - ); + )!; ilg.Call(XmlSerializationWriter_WriteStartElement); if (!mapping.TypeDesc.IsRoot) { @@ -1055,7 +1057,7 @@ private void WriteStructMethod(StructMapping mapping) "WriteXsiType", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Ldstr(GetCSharpString(mapping.TypeName)); ilg.Ldstr(GetCSharpString(mapping.Namespace)); @@ -1072,7 +1074,7 @@ private void WriteStructMethod(StructMapping mapping) if (m.CheckShouldPersist) { ilg.LdargAddress(oArg); - ilg.Call(m.CheckShouldPersistMethodInfo); + ilg.Call(m.CheckShouldPersistMethodInfo!); ilg.If(); } if (m.CheckSpecified != SpecifiedAccessor.None) @@ -1081,7 +1083,7 @@ private void WriteStructMethod(StructMapping mapping) ILGenLoad(memberGet); ilg.If(); } - WriteMember(RaCodeGen.GetSourceForMember("o", m, mapping.TypeDesc, ilg), m.Attribute, m.TypeDesc, "o"); + WriteMember(RaCodeGen.GetSourceForMember("o", m, mapping.TypeDesc, ilg), m.Attribute, m.TypeDesc!, "o"); if (m.CheckSpecified != SpecifiedAccessor.None) { @@ -1100,12 +1102,12 @@ private void WriteStructMethod(StructMapping mapping) if (m.Xmlns != null) continue; CodeIdentifier.CheckValidIdentifier(m.Name); - bool checkShouldPersist = m.CheckShouldPersist && (m.Elements.Length > 0 || m.Text != null); + bool checkShouldPersist = m.CheckShouldPersist && (m.Elements!.Length > 0 || m.Text != null); if (checkShouldPersist) { ilg.LdargAddress(oArg); - ilg.Call(m.CheckShouldPersistMethodInfo); + ilg.Call(m.CheckShouldPersistMethodInfo!); ilg.If(); } if (m.CheckSpecified != SpecifiedAccessor.None) @@ -1115,14 +1117,14 @@ private void WriteStructMethod(StructMapping mapping) ilg.If(); } - string choiceSource = null; + string? choiceSource = null; if (m.ChoiceIdentifier != null) { CodeIdentifier.CheckValidIdentifier(m.ChoiceIdentifier.MemberName); choiceSource = RaCodeGen.GetStringForMember("o", m.ChoiceIdentifier.MemberName, mapping.TypeDesc); } - WriteMember(RaCodeGen.GetSourceForMember("o", m, m.MemberInfo, mapping.TypeDesc, ilg), choiceSource, m.ElementsSortedByDerivation, m.Text, m.ChoiceIdentifier, m.TypeDesc, true); + WriteMember(RaCodeGen.GetSourceForMember("o", m, m.MemberInfo, mapping.TypeDesc, ilg), choiceSource, m.ElementsSortedByDerivation!, m.Text, m.ChoiceIdentifier, m.TypeDesc!, true); if (m.CheckSpecified != SpecifiedAccessor.None) { @@ -1138,7 +1140,7 @@ private void WriteStructMethod(StructMapping mapping) ilg.EndMethod(); } - private bool CanOptimizeWriteListSequence(TypeDesc listElementTypeDesc) + private bool CanOptimizeWriteListSequence(TypeDesc? listElementTypeDesc) { // check to see if we can write values of the attribute sequentially // currently we have only one data type (XmlQualifiedName) that we can not write "inline", @@ -1159,7 +1161,7 @@ private void WriteMember(SourceInfo source, AttributeAccessor attribute, TypeDes WriteArrayLocalDecl(fullTypeName, aVar, source, memberTypeDesc); if (memberTypeDesc.IsNullable) { - ilg.Ldloc(memberTypeDesc.Type, aVar); + ilg.Ldloc(memberTypeDesc.Type!, aVar); ilg.Load(null); ilg.If(Cmp.NotEqualTo); } @@ -1167,17 +1169,17 @@ private void WriteMember(SourceInfo source, AttributeAccessor attribute, TypeDes { if (CanOptimizeWriteListSequence(memberTypeDesc.ArrayElementTypeDesc)) { - string ns = attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : string.Empty; + string? ns = attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : string.Empty; MethodInfo XmlSerializationWriter_get_Writer = typeof(XmlSerializationWriter).GetMethod( "get_Writer", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlWriter_WriteStartAttribute = typeof(XmlWriter).GetMethod( "WriteStartAttribute", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string), typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationWriter_get_Writer); ilg.Load(null); @@ -1191,12 +1193,12 @@ private void WriteMember(SourceInfo source, AttributeAccessor attribute, TypeDes ConstructorInfo StringBuilder_ctor = typeof(StringBuilder).GetConstructor( CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.New(StringBuilder_ctor); ilg.Stloc(sbLoc); } } - TypeDesc arrayElementTypeDesc = memberTypeDesc.ArrayElementTypeDesc; + TypeDesc arrayElementTypeDesc = memberTypeDesc.ArrayElementTypeDesc!; if (memberTypeDesc.IsEnumerable) { @@ -1206,7 +1208,7 @@ private void WriteMember(SourceInfo source, AttributeAccessor attribute, TypeDes { LocalBuilder localI = ilg.DeclareOrGetLocal(typeof(int), iVar); ilg.For(localI, 0, ilg.GetLocal(aVar)); - WriteLocalDecl(aiVar, RaCodeGen.GetStringForArrayMember(aVar, iVar, memberTypeDesc), arrayElementTypeDesc.Type); + WriteLocalDecl(aiVar, RaCodeGen.GetStringForArrayMember(aVar, iVar, memberTypeDesc), arrayElementTypeDesc.Type!); } if (attribute.IsList) { @@ -1223,12 +1225,12 @@ private void WriteMember(SourceInfo source, AttributeAccessor attribute, TypeDes "get_Writer", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlWriter_WriteString = typeof(XmlWriter).GetMethod( "WriteString", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationWriter_get_Writer); ilg.Ldstr(" "); @@ -1244,7 +1246,7 @@ private void WriteMember(SourceInfo source, AttributeAccessor attribute, TypeDes "Append", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } - ); + )!; ilg.Ldloc(iVar); ilg.Ldc(0); ilg.If(Cmp.NotEqualTo); @@ -1265,7 +1267,7 @@ private void WriteMember(SourceInfo source, AttributeAccessor attribute, TypeDes methodName, CodeGenerator.InstanceBindingFlags, new Type[] { argType } - ); + )!; ilg.Call(method); if (method.ReturnType != typeof(void)) ilg.Pop(); @@ -1287,12 +1289,12 @@ private void WriteMember(SourceInfo source, AttributeAccessor attribute, TypeDes "get_Writer", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlWriter_WriteEndAttribute = typeof(XmlWriter).GetMethod( "WriteEndAttribute", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationWriter_get_Writer); ilg.Call(XmlWriter_WriteEndAttribute); @@ -1303,7 +1305,7 @@ private void WriteMember(SourceInfo source, AttributeAccessor attribute, TypeDes "get_Length", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldloc("sb"); ilg.Call(StringBuilder_get_Length); ilg.Ldc(0); @@ -1313,7 +1315,7 @@ private void WriteMember(SourceInfo source, AttributeAccessor attribute, TypeDes ilg.Ldarg(0); ilg.Ldstr(GetCSharpString(attribute.Name)); argTypes.Add(typeof(string)); - string ns = attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : string.Empty; + string? ns = attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : string.Empty; if (ns != null) { ilg.Ldstr(GetCSharpString(ns)); @@ -1323,7 +1325,7 @@ private void WriteMember(SourceInfo source, AttributeAccessor attribute, TypeDes "ToString", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldloc("sb"); ilg.Call(Object_ToString); argTypes.Add(typeof(string)); @@ -1331,7 +1333,7 @@ private void WriteMember(SourceInfo source, AttributeAccessor attribute, TypeDes "WriteAttribute", CodeGenerator.InstanceBindingFlags, argTypes.ToArray() - ); + )!; ilg.Call(XmlSerializationWriter_WriteAttribute); ilg.EndIf(); } @@ -1353,14 +1355,14 @@ private void WriteAttribute(SourceInfo source, AttributeAccessor attribute, stri if (attribute.Mapping is SpecialMapping) { SpecialMapping special = (SpecialMapping)attribute.Mapping; - if (special.TypeDesc.Kind == TypeKind.Attribute || special.TypeDesc.CanBeAttributeValue) + if (special.TypeDesc!.Kind == TypeKind.Attribute || special.TypeDesc.CanBeAttributeValue) { System.Diagnostics.Debug.Assert(parent == "o" || parent == "p"); MethodInfo XmlSerializationWriter_WriteXmlAttribute = typeof(XmlSerializationWriter).GetMethod( "WriteXmlAttribute", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(XmlNode), typeof(object) } - ); + )!; ilg.Ldarg(0); ilg.Ldloc(source.Source); ilg.Ldarg(parent); @@ -1372,20 +1374,20 @@ private void WriteAttribute(SourceInfo source, AttributeAccessor attribute, stri } else { - TypeDesc typeDesc = attribute.Mapping.TypeDesc; + TypeDesc typeDesc = attribute.Mapping!.TypeDesc!; source = source.CastTo(typeDesc); WritePrimitive("WriteAttribute", attribute.Name, attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : "", GetConvertedDefaultValue(source.Type, attribute.Default), source, attribute.Mapping, false, false, false); } } - private static object GetConvertedDefaultValue(Type targetType, object rawDefaultValue) + private static object? GetConvertedDefaultValue(Type? targetType, object? rawDefaultValue) { if (targetType == null) { return rawDefaultValue; } - object convertedDefaultValue; + object? convertedDefaultValue; if (!targetType.TryConvertTo(rawDefaultValue, out convertedDefaultValue)) { return rawDefaultValue; @@ -1394,7 +1396,7 @@ private static object GetConvertedDefaultValue(Type targetType, object rawDefaul return convertedDefaultValue; } - private void WriteMember(SourceInfo source, string choiceSource, ElementAccessor[] elements, TextAccessor text, ChoiceIdentifierAccessor choice, TypeDesc memberTypeDesc, bool writeAccessors) + private void WriteMember(SourceInfo source, string? choiceSource, ElementAccessor[] elements, TextAccessor? text, ChoiceIdentifierAccessor? choice, TypeDesc memberTypeDesc, bool writeAccessors) { if (memberTypeDesc.IsArrayLike && !(elements.Length == 1 && elements[0].Mapping is ArrayMapping)) @@ -1405,7 +1407,7 @@ private void WriteMember(SourceInfo source, string choiceSource, ElementAccessor } - private void WriteArray(SourceInfo source, string choiceSource, ElementAccessor[] elements, TextAccessor text, ChoiceIdentifierAccessor choice, TypeDesc arrayTypeDesc) + private void WriteArray(SourceInfo source, string? choiceSource, ElementAccessor[] elements, TextAccessor? text, ChoiceIdentifierAccessor? choice, TypeDesc arrayTypeDesc) { if (elements.Length == 0 && text == null) return; string arrayTypeName = arrayTypeDesc.CSharpName; @@ -1419,11 +1421,11 @@ private void WriteArray(SourceInfo source, string choiceSource, ElementAccessor[ ilg.If(Cmp.NotEqualTo); } - string cName = null; + string? cName = null; if (choice != null) { - string choiceFullName = choice.Mapping.TypeDesc.CSharpName; - SourceInfo choiceSourceInfo = new SourceInfo(choiceSource, null, choice.MemberInfo, null, ilg); + string choiceFullName = choice.Mapping!.TypeDesc!.CSharpName; + SourceInfo choiceSourceInfo = new SourceInfo(choiceSource!, null, choice.MemberInfo, null, ilg); cName = "c" + choice.Mapping.TypeDesc.Name; WriteArrayLocalDecl(choiceFullName + "[]", cName, choiceSourceInfo, choice.Mapping.TypeDesc); // write check for the choice identifier array @@ -1447,7 +1449,7 @@ private void WriteArray(SourceInfo source, string choiceSource, ElementAccessor[ "CreateInvalidChoiceIdentifierValueException", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Ldstr(GetCSharpString(choice.Mapping.TypeDesc.FullName)); ilg.Ldstr(GetCSharpString(choice.MemberName)); @@ -1456,16 +1458,16 @@ private void WriteArray(SourceInfo source, string choiceSource, ElementAccessor[ ilg.EndIf(); } - WriteArrayItems(elements, text, choice, arrayTypeDesc, aName, cName); + WriteArrayItems(elements, text, choice, arrayTypeDesc, aName, cName!); if (arrayTypeDesc.IsNullable) { ilg.EndIf(); } } - private void WriteArrayItems(ElementAccessor[] elements, TextAccessor text, ChoiceIdentifierAccessor choice, TypeDesc arrayTypeDesc, string arrayName, string choiceName) + private void WriteArrayItems(ElementAccessor[] elements, TextAccessor? text, ChoiceIdentifierAccessor? choice, TypeDesc arrayTypeDesc, string arrayName, string? choiceName) { - TypeDesc arrayElementTypeDesc = arrayTypeDesc.ArrayElementTypeDesc; + TypeDesc arrayElementTypeDesc = arrayTypeDesc.ArrayElementTypeDesc!; if (arrayTypeDesc.IsEnumerable) { @@ -1480,26 +1482,26 @@ private void WriteArrayItems(ElementAccessor[] elements, TextAccessor text, Choi getEnumeratorMethod = typeIEnumerable.GetMethod( "GetEnumerator", CodeGenerator.InstanceBindingFlags, - Array.Empty()); + Array.Empty())!; - ilg.ConvertValue(arrayTypeDesc.Type, typeIEnumerable); + ilg.ConvertValue(arrayTypeDesc.Type!, typeIEnumerable); } else if (arrayTypeDesc.IsGenericInterface) { - Type typeIEnumerable = typeof(IEnumerable<>).MakeGenericType(arrayElementTypeDesc.Type); + Type typeIEnumerable = typeof(IEnumerable<>).MakeGenericType(arrayElementTypeDesc.Type!); getEnumeratorMethod = typeIEnumerable.GetMethod( "GetEnumerator", CodeGenerator.InstanceBindingFlags, - Array.Empty()); + Array.Empty())!; - ilg.ConvertValue(arrayTypeDesc.Type, typeIEnumerable); + ilg.ConvertValue(arrayTypeDesc.Type!, typeIEnumerable); } else { - getEnumeratorMethod = arrayTypeDesc.Type.GetMethod( + getEnumeratorMethod = arrayTypeDesc.Type!.GetMethod( "GetEnumerator", - Array.Empty()); + Array.Empty())!; } ilg.Call(getEnumeratorMethod); ilg.ConvertValue(getEnumeratorMethod.ReturnType, typeof(IEnumerator)); @@ -1511,14 +1513,14 @@ private void WriteArrayItems(ElementAccessor[] elements, TextAccessor text, Choi ilg.WhileBegin(); string arrayNamePlusA = (arrayName).Replace(arrayTypeDesc.Name, "") + "a" + arrayElementTypeDesc.Name; string arrayNamePlusI = (arrayName).Replace(arrayTypeDesc.Name, "") + "i" + arrayElementTypeDesc.Name; - WriteLocalDecl(arrayNamePlusI, "e.Current", arrayElementTypeDesc.Type); + WriteLocalDecl(arrayNamePlusI, "e.Current", arrayElementTypeDesc.Type!); WriteElements(new SourceInfo(arrayNamePlusI, null, null, arrayElementTypeDesc.Type, ilg), choiceName + "i", elements, text, choice, arrayNamePlusA, true, true); ilg.WhileBeginCondition(); // while (e.MoveNext()) MethodInfo IEnumerator_MoveNext = typeof(IEnumerator).GetMethod( "MoveNext", CodeGenerator.InstanceBindingFlags, - Array.Empty()); + Array.Empty())!; ilg.Ldloc(eLoc); ilg.Call(IEnumerator_MoveNext); ilg.WhileEndCondition(); @@ -1537,10 +1539,10 @@ private void WriteArrayItems(ElementAccessor[] elements, TextAccessor text, Choi int count = elements.Length + (text == null ? 0 : 1); if (count > 1) { - WriteLocalDecl(arrayNamePlusI, RaCodeGen.GetStringForArrayMember(arrayName, iPlusArrayName, arrayTypeDesc), arrayElementTypeDesc.Type); + WriteLocalDecl(arrayNamePlusI, RaCodeGen.GetStringForArrayMember(arrayName, iPlusArrayName, arrayTypeDesc), arrayElementTypeDesc.Type!); if (choice != null) { - WriteLocalDecl(choiceName + "i", RaCodeGen.GetStringForArrayMember(choiceName, iPlusArrayName, choice.Mapping.TypeDesc), choice.Mapping.TypeDesc.Type); + WriteLocalDecl(choiceName + "i", RaCodeGen.GetStringForArrayMember(choiceName, iPlusArrayName, choice.Mapping!.TypeDesc!), choice.Mapping.TypeDesc!.Type!); } WriteElements(new SourceInfo(arrayNamePlusI, null, null, arrayElementTypeDesc.Type, ilg), choiceName + "i", elements, text, choice, arrayNamePlusA, true, arrayElementTypeDesc.IsNullable); } @@ -1552,13 +1554,13 @@ private void WriteArrayItems(ElementAccessor[] elements, TextAccessor text, Choi } } - private void WriteElements(SourceInfo source, string enumSource, ElementAccessor[] elements, TextAccessor text, ChoiceIdentifierAccessor choice, string arrayName, bool writeAccessors, bool isNullable) + private void WriteElements(SourceInfo source, string? enumSource, ElementAccessor[] elements, TextAccessor? text, ChoiceIdentifierAccessor? choice, string arrayName, bool writeAccessors, bool isNullable) { if (elements.Length == 0 && text == null) return; if (elements.Length == 1 && text == null) { - TypeDesc td = elements[0].IsUnbounded ? elements[0].Mapping.TypeDesc.CreateArrayTypeDesc() : elements[0].Mapping.TypeDesc; - if (!elements[0].Any && !elements[0].Mapping.TypeDesc.IsOptionalValue) + TypeDesc td = elements[0].IsUnbounded ? elements[0].Mapping!.TypeDesc!.CreateArrayTypeDesc() : elements[0].Mapping!.TypeDesc!; + if (!elements[0].Any && !elements[0].Mapping!.TypeDesc!.IsOptionalValue) source = source.CastTo(td); WriteElement(source, elements[0], arrayName, writeAccessors); } @@ -1574,9 +1576,9 @@ private void WriteElements(SourceInfo source, string enumSource, ElementAccessor } int anyCount = 0; var namedAnys = new List(); - ElementAccessor unnamedAny = null; // can only have one + ElementAccessor? unnamedAny = null; // can only have one bool wroteFirstIf = false; - string enumTypeName = choice == null ? null : choice.Mapping.TypeDesc.FullName; + string? enumTypeName = choice == null ? null : choice.Mapping!.TypeDesc!.FullName; for (int i = 0; i < elements.Length; i++) { @@ -1592,13 +1594,13 @@ private void WriteElements(SourceInfo source, string enumSource, ElementAccessor } else if (choice != null) { - string fullTypeName = element.Mapping.TypeDesc.CSharpName; - object enumValue; - string enumFullName = enumTypeName + ".@" + FindChoiceEnumValue(element, (EnumMapping)choice.Mapping, out enumValue); + string fullTypeName = element.Mapping!.TypeDesc!.CSharpName; + object? enumValue; + string enumFullName = enumTypeName + ".@" + FindChoiceEnumValue(element, (EnumMapping)choice.Mapping!, out enumValue); if (wroteFirstIf) ilg.InitElseIf(); else { wroteFirstIf = true; ilg.InitIf(); } - ILGenLoad(enumSource, choice == null ? null : choice.Mapping.TypeDesc.Type); + ILGenLoad(enumSource!, choice == null ? null : choice.Mapping!.TypeDesc!.Type); ilg.Load(enumValue); ilg.Ceq(); if (isNullable && !element.IsNullable) @@ -1616,7 +1618,7 @@ private void WriteElements(SourceInfo source, string enumSource, ElementAccessor } ilg.AndIf(); - WriteChoiceTypeCheck(source, fullTypeName, choice, enumFullName, element.Mapping.TypeDesc); + WriteChoiceTypeCheck(source, fullTypeName, choice!, enumFullName, element.Mapping.TypeDesc); SourceInfo castedSource = source; castedSource = source.CastTo(element.Mapping.TypeDesc); @@ -1624,11 +1626,11 @@ private void WriteElements(SourceInfo source, string enumSource, ElementAccessor } else { - TypeDesc td = element.IsUnbounded ? element.Mapping.TypeDesc.CreateArrayTypeDesc() : element.Mapping.TypeDesc; + TypeDesc td = element.IsUnbounded ? element.Mapping!.TypeDesc!.CreateArrayTypeDesc() : element.Mapping!.TypeDesc!; string fullTypeName = td.CSharpName; if (wroteFirstIf) ilg.InitElseIf(); else { wroteFirstIf = true; ilg.InitIf(); } - WriteInstanceOf(source, td.Type); + WriteInstanceOf(source, td.Type!); // WriteInstanceOf leave bool on the stack ilg.AndIf(); SourceInfo castedSource = source; @@ -1652,7 +1654,7 @@ private void WriteElements(SourceInfo source, string enumSource, ElementAccessor if (elements.Length - anyCount > 0) ilg.InitElseIf(); else ilg.InitIf(); - string fullTypeName = typeof(XmlElement).FullName; + string fullTypeName = typeof(XmlElement).FullName!; source.Load(typeof(object)); ilg.IsInst(typeof(XmlElement)); @@ -1671,16 +1673,16 @@ private void WriteElements(SourceInfo source, string enumSource, ElementAccessor if (c++ > 0) ilg.InitElseIf(); else ilg.InitIf(); - string enumFullName = null; + string? enumFullName = null; Label labelEnd, labelFalse; if (choice != null) { - object enumValue; - enumFullName = enumTypeName + ".@" + FindChoiceEnumValue(element, (EnumMapping)choice.Mapping, out enumValue); + object? enumValue; + enumFullName = enumTypeName + ".@" + FindChoiceEnumValue(element, (EnumMapping)choice.Mapping!, out enumValue); labelFalse = ilg.DefineLabel(); labelEnd = ilg.DefineLabel(); - ILGenLoad(enumSource, choice == null ? null : choice.Mapping.TypeDesc.Type); + ILGenLoad(enumSource!, choice == null ? null : choice.Mapping!.TypeDesc!.Type); ilg.Load(enumValue); ilg.Bne(labelFalse); if (isNullable && !element.IsNullable) @@ -1705,12 +1707,12 @@ private void WriteElements(SourceInfo source, string enumSource, ElementAccessor "get_Name", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlNode_get_NamespaceURI = typeof(XmlNode).GetMethod( "get_NamespaceURI", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldloc(elemLoc); ilg.Call(XmlNode_get_Name); ilg.Ldstr(GetCSharpString(element.Name)); @@ -1718,7 +1720,7 @@ private void WriteElements(SourceInfo source, string enumSource, ElementAccessor "op_Equality", CodeGenerator.StaticBindingFlags, new Type[] { typeof(string), typeof(string) } - ); + )!; ilg.Call(String_op_Equality); ilg.Brfalse(labelFalse); ilg.Ldloc(elemLoc); @@ -1741,7 +1743,7 @@ private void WriteElements(SourceInfo source, string enumSource, ElementAccessor "CreateChoiceIdentifierValueException", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string), typeof(string), typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Ldstr(GetCSharpString(enumFullName)); ilg.Ldstr(GetCSharpString(choice.MemberName)); @@ -1768,19 +1770,19 @@ private void WriteElements(SourceInfo source, string enumSource, ElementAccessor "CreateUnknownAnyElementException", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Ldloc(elemLoc); MethodInfo XmlNode_get_Name = typeof(XmlNode).GetMethod( "get_Name", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlNode_get_NamespaceURI = typeof(XmlNode).GetMethod( "get_NamespaceURI", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Call(XmlNode_get_Name); ilg.Ldloc(elemLoc); ilg.Call(XmlNode_get_NamespaceURI); @@ -1794,11 +1796,11 @@ private void WriteElements(SourceInfo source, string enumSource, ElementAccessor } if (text != null) { - string fullTypeName = text.Mapping.TypeDesc.CSharpName; + string fullTypeName = text.Mapping!.TypeDesc!.CSharpName; if (elements.Length > 0) { ilg.InitElseIf(); - WriteInstanceOf(source, text.Mapping.TypeDesc.Type); + WriteInstanceOf(source, text.Mapping.TypeDesc.Type!); ilg.AndIf(); SourceInfo castedSource = source.CastTo(text.Mapping.TypeDesc); WriteText(castedSource, text); @@ -1826,7 +1828,7 @@ private void WriteElements(SourceInfo source, string enumSource, ElementAccessor MethodInfo XmlSerializationWriter_CreateUnknownTypeException = typeof(XmlSerializationWriter).GetMethod( "CreateUnknownTypeException", CodeGenerator.InstanceBindingFlags, - new Type[] { typeof(object) }); + new Type[] { typeof(object) })!; ilg.Ldarg(0); source.Load(typeof(object)); ilg.Call(XmlSerializationWriter_CreateUnknownTypeException); @@ -1853,31 +1855,31 @@ private void WriteText(SourceInfo source, TextAccessor text) } else { - WritePrimitiveValue(mapping.TypeDesc, source, out argType); + WritePrimitiveValue(mapping.TypeDesc!, source, out argType); } MethodInfo XmlSerializationWriter_WriteValue = typeof(XmlSerializationWriter).GetMethod( "WriteValue", CodeGenerator.InstanceBindingFlags, new Type[] { argType } - ); + )!; ilg.Call(XmlSerializationWriter_WriteValue); } else if (text.Mapping is SpecialMapping) { SpecialMapping mapping = (SpecialMapping)text.Mapping; - switch (mapping.TypeDesc.Kind) + switch (mapping.TypeDesc!.Kind) { case TypeKind.Node: - MethodInfo WriteTo = source.Type.GetMethod( + MethodInfo WriteTo = source.Type!.GetMethod( "WriteTo", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(XmlWriter) } - ); + )!; MethodInfo XmlSerializationWriter_get_Writer = typeof(XmlSerializationWriter).GetMethod( "get_Writer", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; source.Load(source.Type); ilg.Ldarg(0); ilg.Call(XmlSerializationWriter_get_Writer); @@ -1891,17 +1893,17 @@ private void WriteText(SourceInfo source, TextAccessor text) private void WriteElement(SourceInfo source, ElementAccessor element, string arrayName, bool writeAccessor) { - string name = writeAccessor ? element.Name : element.Mapping.TypeName; - string ns = element.Any && element.Name.Length == 0 ? null : (element.Form == XmlSchemaForm.Qualified ? (writeAccessor ? element.Namespace : element.Mapping.Namespace) : ""); + string name = writeAccessor ? element.Name : element.Mapping!.TypeName!; + string? ns = element.Any && element.Name.Length == 0 ? null : (element.Form == XmlSchemaForm.Qualified ? (writeAccessor ? element.Namespace : element.Mapping!.Namespace) : ""); if (element.Mapping is NullableMapping) { - if (source.Type == element.Mapping.TypeDesc.Type) + if (source.Type == element.Mapping.TypeDesc!.Type) { - MethodInfo Nullable_get_HasValue = element.Mapping.TypeDesc.Type.GetMethod( + MethodInfo Nullable_get_HasValue = element.Mapping.TypeDesc.Type!.GetMethod( "get_HasValue", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; source.LoadAddress(element.Mapping.TypeDesc.Type); ilg.Call(Nullable_get_HasValue); } @@ -1912,7 +1914,7 @@ private void WriteElement(SourceInfo source, ElementAccessor element, string arr ilg.Cne(); } ilg.If(); - string fullTypeName = element.Mapping.TypeDesc.BaseTypeDesc.CSharpName; + string fullTypeName = element.Mapping.TypeDesc.BaseTypeDesc!.CSharpName; SourceInfo castedSource = source.CastTo(element.Mapping.TypeDesc.BaseTypeDesc); ElementAccessor e = element.Clone(); e.Mapping = ((NullableMapping)element.Mapping).BaseMapping; @@ -1934,7 +1936,7 @@ private void WriteElement(SourceInfo source, ElementAccessor element, string arr else { ilg.EnterScope(); - string fullTypeName = mapping.TypeDesc.CSharpName; + string fullTypeName = mapping.TypeDesc!.CSharpName; WriteArrayLocalDecl(fullTypeName, arrayName, source, mapping.TypeDesc); if (element.IsNullable) { @@ -1950,7 +1952,7 @@ private void WriteElement(SourceInfo source, ElementAccessor element, string arr } } WriteStartElement(name, ns, false); - WriteArrayItems(mapping.ElementsSortedByDerivation, null, null, mapping.TypeDesc, arrayName, null); + WriteArrayItems(mapping.ElementsSortedByDerivation!, null, null, mapping.TypeDesc, arrayName, null); WriteEndElement(); if (element.IsNullable) { @@ -1977,7 +1979,7 @@ private void WriteElement(SourceInfo source, ElementAccessor element, string arr WriteQualifiedNameElement(name, ns, GetConvertedDefaultValue(source.Type, element.Default), source, element.IsNullable, mapping); else { - string suffixRaw = mapping.TypeDesc.XmlEncodingNotRequired ? "Raw" : ""; + string suffixRaw = mapping.TypeDesc!.XmlEncodingNotRequired ? "Raw" : ""; WritePrimitive(element.IsNullable ? ("WriteNullableStringLiteral" + suffixRaw) : ("WriteElementString" + suffixRaw), name, ns, GetConvertedDefaultValue(source.Type, element.Default), source, mapping, false, true, element.IsNullable); } @@ -1986,11 +1988,11 @@ private void WriteElement(SourceInfo source, ElementAccessor element, string arr { StructMapping mapping = (StructMapping)element.Mapping; - string methodName = ReferenceMapping(mapping); + string? methodName = ReferenceMapping(mapping); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe - if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc.Name)); + if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc!.Name)); #endif List argTypes = new List(); ilg.Ldarg(0); @@ -1998,8 +2000,8 @@ private void WriteElement(SourceInfo source, ElementAccessor element, string arr argTypes.Add(typeof(string)); ilg.Ldstr(GetCSharpString(ns)); argTypes.Add(typeof(string)); - source.Load(mapping.TypeDesc.Type); - argTypes.Add(mapping.TypeDesc.Type); + source.Load(mapping.TypeDesc!.Type); + argTypes.Add(mapping.TypeDesc.Type!); if (mapping.TypeDesc.IsNullable) { ilg.Ldc(element.IsNullable); @@ -2008,7 +2010,7 @@ private void WriteElement(SourceInfo source, ElementAccessor element, string arr ilg.Ldc(false); argTypes.Add(typeof(bool)); MethodBuilder methodBuilder = EnsureMethodBuilder(typeBuilder, - methodName, + methodName!, CodeGenerator.PrivateMethodAttributes, typeof(void), argTypes.ToArray()); @@ -2017,7 +2019,7 @@ private void WriteElement(SourceInfo source, ElementAccessor element, string arr else if (element.Mapping is SpecialMapping) { SpecialMapping mapping = (SpecialMapping)element.Mapping; - TypeDesc td = mapping.TypeDesc; + TypeDesc td = mapping.TypeDesc!; string fullTypeName = td.CSharpName; @@ -2050,7 +2052,7 @@ private void WriteElement(SourceInfo source, ElementAccessor element, string arr "CreateInvalidAnyTypeException", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(object) } - ); + )!; ilg.Ldarg(0); source.Load(null); ilg.Call(XmlSerializationWriter_CreateInvalidAnyTypeException); @@ -2065,13 +2067,13 @@ private void WriteElement(SourceInfo source, ElementAccessor element, string arr } } - private void WriteElementCall(string func, Type cast, SourceInfo source, string name, string ns, bool isNullable, bool isAny) + private void WriteElementCall(string func, Type cast, SourceInfo source, string? name, string? ns, bool isNullable, bool isAny) { MethodInfo XmlSerializationWriter_func = typeof(XmlSerializationWriter).GetMethod( func, CodeGenerator.InstanceBindingFlags, new Type[] { cast, typeof(string), typeof(string), typeof(bool), typeof(bool) } - ); + )!; ilg.Ldarg(0); source.Load(cast); ilg.Ldstr(GetCSharpString(name)); @@ -2100,7 +2102,7 @@ private void WriteCheckDefault(SourceInfo source, object value, bool isNullable) "get_Length", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; source.Load(typeof(string)); ilg.Call(String_get_Length); ilg.Ldc(0); @@ -2130,7 +2132,7 @@ private void WriteCheckDefault(SourceInfo source, object value, bool isNullable) else if (value.GetType().IsPrimitive) { source.Load(null); - ilg.Ldc(Convert.ChangeType(value, source.Type, CultureInfo.InvariantCulture)); + ilg.Ldc(Convert.ChangeType(value, source.Type!, CultureInfo.InvariantCulture)); ilg.Cne(); } else @@ -2142,7 +2144,7 @@ private void WriteCheckDefault(SourceInfo source, object value, bool isNullable) "op_Inequality", CodeGenerator.StaticBindingFlags, new Type[] { valueType, valueType } - ); + )!; if (op_Inequality != null) ilg.Call(op_Inequality); else @@ -2159,7 +2161,7 @@ private void WriteChoiceTypeCheck(SourceInfo source, string fullTypeName, Choice source.Load(typeof(object)); ilg.Load(null); ilg.Beq(labelFalse); - WriteInstanceOf(source, typeDesc.Type); + WriteInstanceOf(source, typeDesc.Type!); // Negative ilg.Ldc(false); ilg.Ceq(); @@ -2172,7 +2174,7 @@ private void WriteChoiceTypeCheck(SourceInfo source, string fullTypeName, Choice "CreateMismatchChoiceException", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string), typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Ldstr(GetCSharpString(typeDesc.FullName)); ilg.Ldstr(GetCSharpString(choice.MemberName)); @@ -2200,7 +2202,7 @@ private void WriteNamespaces(string source) "WriteNamespaceDeclarations", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(XmlSerializerNamespaces) } - ); + )!; ilg.Ldarg(0); ILGenLoad(source, typeof(XmlSerializerNamespaces)); ilg.Call(XmlSerializationWriter_WriteNamespaceDeclarations); @@ -2241,12 +2243,12 @@ private void WriteArrayTypeCompare(string variable, Type arrayType) } - private string FindChoiceEnumValue(ElementAccessor element, EnumMapping choiceMapping, out object eValue) + private string FindChoiceEnumValue(ElementAccessor element, EnumMapping choiceMapping, out object? eValue) { - string enumValue = null; + string? enumValue = null; eValue = null; - for (int i = 0; i < choiceMapping.Constants.Length; i++) + for (int i = 0; i < choiceMapping.Constants!.Length; i++) { string xmlName = choiceMapping.Constants[i].XmlName; @@ -2255,13 +2257,13 @@ private string FindChoiceEnumValue(ElementAccessor element, EnumMapping choiceMa if (xmlName == "##any:") { enumValue = choiceMapping.Constants[i].Name; - eValue = Enum.ToObject(choiceMapping.TypeDesc.Type, choiceMapping.Constants[i].Value); + eValue = Enum.ToObject(choiceMapping.TypeDesc!.Type!, choiceMapping.Constants[i].Value); break; } continue; } int colon = xmlName.LastIndexOf(':'); - string choiceNs = colon < 0 ? choiceMapping.Namespace : xmlName.Substring(0, colon); + string? choiceNs = colon < 0 ? choiceMapping.Namespace : xmlName.Substring(0, colon); string choiceName = colon < 0 ? xmlName : xmlName.Substring(colon + 1); if (element.Name == choiceName) @@ -2269,7 +2271,7 @@ private string FindChoiceEnumValue(ElementAccessor element, EnumMapping choiceMa if ((element.Form == XmlSchemaForm.Unqualified && string.IsNullOrEmpty(choiceNs)) || element.Namespace == choiceNs) { enumValue = choiceMapping.Constants[i].Name; - eValue = Enum.ToObject(choiceMapping.TypeDesc.Type, choiceMapping.Constants[i].Value); + eValue = Enum.ToObject(choiceMapping.TypeDesc!.Type!, choiceMapping.Constants[i].Value); break; } } @@ -2279,10 +2281,10 @@ private string FindChoiceEnumValue(ElementAccessor element, EnumMapping choiceMa if (element.Any && element.Name.Length == 0) { // Type {0} is missing enumeration value '##any' for XmlAnyElementAttribute. - throw new InvalidOperationException(SR.Format(SR.XmlChoiceMissingAnyValue, choiceMapping.TypeDesc.FullName)); + throw new InvalidOperationException(SR.Format(SR.XmlChoiceMissingAnyValue, choiceMapping.TypeDesc!.FullName)); } // Type {0} is missing value for '{1}'. - throw new InvalidOperationException(SR.Format(SR.XmlChoiceMissingValue, choiceMapping.TypeDesc.FullName, element.Namespace + ":" + element.Name, element.Name, element.Namespace)); + throw new InvalidOperationException(SR.Format(SR.XmlChoiceMissingValue, choiceMapping.TypeDesc!.FullName, element.Namespace + ":" + element.Name, element.Name, element.Namespace)); } CodeIdentifier.CheckValidIdentifier(enumValue); return enumValue; @@ -2338,16 +2340,16 @@ internal SourceInfo GetSourceForMember(string obj, MemberMapping member, TypeDes { return GetSourceForMember(obj, member, member.MemberInfo, typeDesc, ilg); } - internal SourceInfo GetSourceForMember(string obj, MemberMapping member, MemberInfo memberInfo, TypeDesc typeDesc, CodeGenerator ilg) + internal SourceInfo GetSourceForMember(string obj, MemberMapping member, MemberInfo? memberInfo, TypeDesc typeDesc, CodeGenerator ilg) { - return new SourceInfo(GetStringForMember(obj, member.Name, typeDesc), obj, memberInfo, member.TypeDesc.Type, ilg); + return new SourceInfo(GetStringForMember(obj, member.Name, typeDesc), obj, memberInfo, member.TypeDesc!.Type, ilg); } internal void ILGenForEnumMember(CodeGenerator ilg, Type type, string memberName) { ilg.Ldc(Enum.Parse(type, memberName, false)); } - internal string GetStringForArrayMember(string arrayName, string subscript, TypeDesc arrayTypeDesc) + internal string GetStringForArrayMember(string? arrayName, string subscript, TypeDesc arrayTypeDesc) { { return arrayName + "[" + subscript + "]"; @@ -2364,7 +2366,7 @@ internal void ILGenForCreateInstance(CodeGenerator ilg, Type type, bool ctorInac ConstructorInfo ctor = type.GetConstructor( CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; if (ctor != null) ilg.New(ctor); else @@ -2380,12 +2382,12 @@ internal void ILGenForCreateInstance(CodeGenerator ilg, Type type, bool ctorInac ILGenForCreateInstance(ilg, type, cast ? type : null, ctorInaccessible); } - internal void ILGenForCreateInstance(CodeGenerator ilg, Type type, Type cast, bool nonPublic) + internal void ILGenForCreateInstance(CodeGenerator ilg, Type type, Type? cast, bool nonPublic) { // Special case DBNull if (type == typeof(DBNull)) { - FieldInfo DBNull_Value = type.GetField("Value", CodeGenerator.StaticBindingFlags); + FieldInfo DBNull_Value = type.GetField("Value", CodeGenerator.StaticBindingFlags)!; ilg.LoadMember(DBNull_Value); return; } @@ -2394,18 +2396,18 @@ internal void ILGenForCreateInstance(CodeGenerator ilg, Type type, Type cast, bo // codegen the same as 'internal XElement : this("default") { }' if (type.FullName == "System.Xml.Linq.XElement") { - Type xName = type.Assembly.GetType("System.Xml.Linq.XName"); + Type? xName = type.Assembly.GetType("System.Xml.Linq.XName"); if (xName != null) { MethodInfo XName_op_Implicit = xName.GetMethod( "op_Implicit", CodeGenerator.StaticBindingFlags, new Type[] { typeof(string) } - ); + )!; ConstructorInfo XElement_ctor = type.GetConstructor( CodeGenerator.InstanceBindingFlags, new Type[] { xName } - ); + )!; if (XName_op_Implicit != null && XElement_ctor != null) { ilg.Ldstr("default"); @@ -2426,20 +2428,20 @@ internal void ILGenForCreateInstance(CodeGenerator ilg, Type type, Type cast, bo "GetTypeInfo", CodeGenerator.StaticBindingFlags, new[] { typeof(Type) } - ); + )!; ilg.Call(getTypeInfoMehod); // IEnumerator e = typeInfo.DeclaredConstructors.GetEnumerator(); LocalBuilder enumerator = ilg.DeclareLocal(typeof(IEnumerator<>).MakeGenericType(typeof(ConstructorInfo)), "e"); - MethodInfo getDeclaredConstructors = typeof(TypeInfo).GetMethod("get_DeclaredConstructors"); - MethodInfo getEnumerator = typeof(IEnumerable<>).MakeGenericType(typeof(ConstructorInfo)).GetMethod("GetEnumerator"); + MethodInfo getDeclaredConstructors = typeof(TypeInfo).GetMethod("get_DeclaredConstructors")!; + MethodInfo getEnumerator = typeof(IEnumerable<>).MakeGenericType(typeof(ConstructorInfo)).GetMethod("GetEnumerator")!; ilg.Call(getDeclaredConstructors); ilg.Call(getEnumerator); ilg.Stloc(enumerator); ilg.WhileBegin(); // ConstructorInfo constructorInfo = e.Current(); - MethodInfo enumeratorCurrent = typeof(IEnumerator).GetMethod("get_Current"); + MethodInfo enumeratorCurrent = typeof(IEnumerator).GetMethod("get_Current")!; ilg.Ldloc(enumerator); ilg.Call(enumeratorCurrent); LocalBuilder constructorInfo = ilg.DeclareLocal(typeof(ConstructorInfo), "constructorInfo"); @@ -2447,11 +2449,11 @@ internal void ILGenForCreateInstance(CodeGenerator ilg, Type type, Type cast, bo // if (!constructorInfo.IsStatic && constructorInfo.GetParameters.Length() == 0) ilg.Ldloc(constructorInfo); - MethodInfo constructorIsStatic = typeof(ConstructorInfo).GetMethod("get_IsStatic"); + MethodInfo constructorIsStatic = typeof(ConstructorInfo).GetMethod("get_IsStatic")!; ilg.Call(constructorIsStatic); ilg.Brtrue(labelEndIf); ilg.Ldloc(constructorInfo); - MethodInfo constructorGetParameters = typeof(ConstructorInfo).GetMethod("GetParameters"); + MethodInfo constructorGetParameters = typeof(ConstructorInfo).GetMethod("GetParameters")!; ilg.Call(constructorGetParameters); ilg.Ldlen(); ilg.Ldc(0); @@ -2459,7 +2461,7 @@ internal void ILGenForCreateInstance(CodeGenerator ilg, Type type, Type cast, bo ilg.Brtrue(labelEndIf); // constructorInfo.Invoke(null); - MethodInfo constructorInvoke = typeof(ConstructorInfo).GetMethod("Invoke", new Type[] { typeof(object[]) }); + MethodInfo constructorInvoke = typeof(ConstructorInfo).GetMethod("Invoke", new Type[] { typeof(object[]) })!; ilg.Ldloc(constructorInfo); ilg.Load(null); ilg.Call(constructorInvoke); @@ -2470,7 +2472,7 @@ internal void ILGenForCreateInstance(CodeGenerator ilg, Type type, Type cast, bo MethodInfo IEnumeratorMoveNext = typeof(IEnumerator).GetMethod( "MoveNext", CodeGenerator.InstanceBindingFlags, - Array.Empty()); + Array.Empty())!; ilg.Ldloc(enumerator); ilg.Call(IEnumeratorMoveNext); ilg.WhileEndCondition(); @@ -2480,7 +2482,7 @@ internal void ILGenForCreateInstance(CodeGenerator ilg, Type type, Type cast, bo "CreateInstance", CodeGenerator.StaticBindingFlags, new Type[] { typeof(Type) } - ); + )!; ilg.Ldc(type); ilg.Call(Activator_CreateInstance); ilg.MarkLabel(labelReturn); @@ -2490,7 +2492,7 @@ internal void ILGenForCreateInstance(CodeGenerator ilg, Type type, Type cast, bo internal void WriteLocalDecl(string variableName, SourceInfo initValue) { - Type localType = initValue.Type; + Type localType = initValue.Type!; LocalBuilder localA = initValue.ILG.DeclareOrGetLocal(localType, variableName); if (initValue.Source != null) { @@ -2514,7 +2516,7 @@ internal void WriteLocalDecl(string variableName, SourceInfo initValue) { string[] vars = initValue.Source.Split('.'); object fixup = initValue.ILG.GetVariable(vars[0]); - PropertyInfo propInfo = initValue.ILG.GetVariableType(fixup).GetProperty(vars[1]); + PropertyInfo propInfo = initValue.ILG.GetVariableType(fixup).GetProperty(vars[1])!; initValue.ILG.LoadMember(fixup, propInfo); initValue.ILG.ConvertValue(propInfo.PropertyType, localA.LocalType); } @@ -2549,7 +2551,7 @@ internal void WriteInstanceOf(SourceInfo source, Type type, CodeGenerator ilg) internal void WriteArrayLocalDecl(string typeName, string variableName, SourceInfo initValue, TypeDesc arrayTypeDesc) { Debug.Assert(typeName == arrayTypeDesc.CSharpName || typeName == arrayTypeDesc.CSharpName + "[]"); - Type localType = (typeName == arrayTypeDesc.CSharpName) ? arrayTypeDesc.Type : arrayTypeDesc.Type.MakeArrayType(); + Type localType = (typeName == arrayTypeDesc.CSharpName) ? arrayTypeDesc.Type! : arrayTypeDesc.Type!.MakeArrayType(); // This may need reused variable to get code compat? LocalBuilder local = initValue.ILG.DeclareOrGetLocal(localType, variableName); if (initValue != null) @@ -2578,7 +2580,8 @@ internal void WriteArrayTypeCompare(string variable, Type arrayType, CodeGenerat } } - internal static string GetQuotedCSharpString(string value) + [return: NotNullIfNotNull("value")] + internal static string? GetQuotedCSharpString(string? value) { if (value == null) { @@ -2591,7 +2594,8 @@ internal static string GetQuotedCSharpString(string value) return writer.ToString(); } - internal static string GetCSharpString(string value) + [return: NotNullIfNotNull("value")] + internal static string? GetCSharpString(string? value) { if (value == null) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs index 32e7571198a148..a017863bef8983 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System.Reflection; @@ -21,13 +22,13 @@ namespace System.Xml.Serialization public struct XmlDeserializationEvents { - private XmlNodeEventHandler _onUnknownNode; - private XmlAttributeEventHandler _onUnknownAttribute; - private XmlElementEventHandler _onUnknownElement; - private UnreferencedObjectEventHandler _onUnreferencedObject; - internal object sender; + private XmlNodeEventHandler? _onUnknownNode; + private XmlAttributeEventHandler? _onUnknownAttribute; + private XmlElementEventHandler? _onUnknownElement; + private UnreferencedObjectEventHandler? _onUnreferencedObject; + internal object? sender; - public XmlNodeEventHandler OnUnknownNode + public XmlNodeEventHandler? OnUnknownNode { get { @@ -40,7 +41,7 @@ public XmlNodeEventHandler OnUnknownNode } } - public XmlAttributeEventHandler OnUnknownAttribute + public XmlAttributeEventHandler? OnUnknownAttribute { get { @@ -52,7 +53,7 @@ public XmlAttributeEventHandler OnUnknownAttribute } } - public XmlElementEventHandler OnUnknownElement + public XmlElementEventHandler? OnUnknownElement { get { @@ -64,7 +65,7 @@ public XmlElementEventHandler OnUnknownElement } } - public UnreferencedObjectEventHandler OnUnreferencedObject + public UnreferencedObjectEventHandler? OnUnreferencedObject { get { @@ -118,19 +119,19 @@ private static bool ReflectionMethodEnabled } } - private TempAssembly _tempAssembly; + private TempAssembly? _tempAssembly; #pragma warning disable 0414 private bool _typedSerializer; #pragma warning restore 0414 - private readonly Type _primitiveType; - private XmlMapping _mapping; + private readonly Type? _primitiveType; + private XmlMapping _mapping = null!; private XmlDeserializationEvents _events; - internal string DefaultNamespace; - private Type _rootType; + internal string? DefaultNamespace; + private Type? _rootType; private bool _isReflectionBasedSerializer; private static readonly TempAssemblyCache s_cache = new TempAssemblyCache(); - private static volatile XmlSerializerNamespaces s_defaultNamespaces; + private static volatile XmlSerializerNamespaces? s_defaultNamespaces; private static XmlSerializerNamespaces DefaultNamespaces { get @@ -155,20 +156,20 @@ protected XmlSerializer() { } - public XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace) : + public XmlSerializer(Type type, XmlAttributeOverrides? overrides, Type[]? extraTypes, XmlRootAttribute? root, string? defaultNamespace) : this(type, overrides, extraTypes, root, defaultNamespace, null) { } - public XmlSerializer(Type type, XmlRootAttribute root) : this(type, null, Array.Empty(), root, null, null) + public XmlSerializer(Type type, XmlRootAttribute? root) : this(type, null, Array.Empty(), root, null, null) { } - public XmlSerializer(Type type, Type[] extraTypes) : this(type, null, extraTypes, null, null, null) + public XmlSerializer(Type type, Type[]? extraTypes) : this(type, null, extraTypes, null, null, null) { } - public XmlSerializer(Type type, XmlAttributeOverrides overrides) : this(type, overrides, Array.Empty(), null, null, null) + public XmlSerializer(Type type, XmlAttributeOverrides? overrides) : this(type, overrides, Array.Empty(), null, null, null) { } @@ -181,11 +182,11 @@ public XmlSerializer(XmlTypeMapping xmlTypeMapping) _mapping = xmlTypeMapping; } - public XmlSerializer(Type type) : this(type, (string)null) + public XmlSerializer(Type type) : this(type, (string?)null) { } - public XmlSerializer(Type type, string defaultNamespace) + public XmlSerializer(Type type, string? defaultNamespace) { if (type == null) throw new ArgumentNullException(nameof(type)); @@ -193,7 +194,7 @@ public XmlSerializer(Type type, string defaultNamespace) DefaultNamespace = defaultNamespace; _rootType = type; - _mapping = GetKnownMapping(type, defaultNamespace); + _mapping = GetKnownMapping(type, defaultNamespace)!; if (_mapping != null) { _primitiveType = type; @@ -208,8 +209,8 @@ public XmlSerializer(Type type, string defaultNamespace) if (_tempAssembly == null) { { - XmlSerializerImplementation contract = null; - Assembly assembly = TempAssembly.LoadGeneratedAssembly(type, defaultNamespace, out contract); + XmlSerializerImplementation? contract = null; + Assembly? assembly = TempAssembly.LoadGeneratedAssembly(type, defaultNamespace, out contract); if (assembly == null) { if (Mode == SerializationMode.PreGenOnly) @@ -222,7 +223,7 @@ public XmlSerializer(Type type, string defaultNamespace) // need to reflect and generate new serialization assembly XmlReflectionImporter importer = new XmlReflectionImporter(defaultNamespace); _mapping = importer.ImportTypeMapping(type, null, defaultNamespace); - _tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace); + _tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace)!; } else { @@ -242,7 +243,7 @@ public XmlSerializer(Type type, string defaultNamespace) } } - public XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace, string location) + public XmlSerializer(Type type, XmlAttributeOverrides? overrides, Type[]? extraTypes, XmlRootAttribute? root, string? defaultNamespace, string? location) { if (type == null) throw new ArgumentNullException(nameof(type)); @@ -253,7 +254,7 @@ public XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTyp _tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace, location); } - private XmlTypeMapping GenerateXmlTypeMapping(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace) + private XmlTypeMapping GenerateXmlTypeMapping(Type type, XmlAttributeOverrides? overrides, Type[]? extraTypes, XmlRootAttribute? root, string? defaultNamespace) { XmlReflectionImporter importer = new XmlReflectionImporter(overrides, defaultNamespace); if (extraTypes != null) @@ -265,17 +266,17 @@ private XmlTypeMapping GenerateXmlTypeMapping(Type type, XmlAttributeOverrides o return importer.ImportTypeMapping(type, root, defaultNamespace); } - internal static TempAssembly GenerateTempAssembly(XmlMapping xmlMapping) + internal static TempAssembly? GenerateTempAssembly(XmlMapping xmlMapping) { return GenerateTempAssembly(xmlMapping, null, null); } - internal static TempAssembly GenerateTempAssembly(XmlMapping xmlMapping, Type type, string defaultNamespace) + internal static TempAssembly? GenerateTempAssembly(XmlMapping xmlMapping, Type? type, string? defaultNamespace) { return GenerateTempAssembly(xmlMapping, type, defaultNamespace, null); } - internal static TempAssembly GenerateTempAssembly(XmlMapping xmlMapping, Type type, string defaultNamespace, string location) + internal static TempAssembly? GenerateTempAssembly(XmlMapping xmlMapping, Type? type, string? defaultNamespace, string? location) { if (xmlMapping == null) { @@ -288,15 +289,15 @@ internal static TempAssembly GenerateTempAssembly(XmlMapping xmlMapping, Type ty return null; } - return new TempAssembly(new XmlMapping[] { xmlMapping }, new Type[] { type }, defaultNamespace, location); + return new TempAssembly(new XmlMapping[] { xmlMapping }, new Type?[] { type }, defaultNamespace, location); } - public void Serialize(TextWriter textWriter, object o) + public void Serialize(TextWriter textWriter, object? o) { Serialize(textWriter, o, null); } - public void Serialize(TextWriter textWriter, object o, XmlSerializerNamespaces namespaces) + public void Serialize(TextWriter textWriter, object? o, XmlSerializerNamespaces? namespaces) { XmlTextWriter xmlWriter = new XmlTextWriter(textWriter); xmlWriter.Formatting = Formatting.Indented; @@ -304,12 +305,12 @@ public void Serialize(TextWriter textWriter, object o, XmlSerializerNamespaces n Serialize(xmlWriter, o, namespaces); } - public void Serialize(Stream stream, object o) + public void Serialize(Stream stream, object? o) { Serialize(stream, o, null); } - public void Serialize(Stream stream, object o, XmlSerializerNamespaces namespaces) + public void Serialize(Stream stream, object? o, XmlSerializerNamespaces? namespaces) { XmlTextWriter xmlWriter = new XmlTextWriter(stream, null); xmlWriter.Formatting = Formatting.Indented; @@ -317,22 +318,22 @@ public void Serialize(Stream stream, object o, XmlSerializerNamespaces namespace Serialize(xmlWriter, o, namespaces); } - public void Serialize(XmlWriter xmlWriter, object o) + public void Serialize(XmlWriter xmlWriter, object? o) { Serialize(xmlWriter, o, null); } - public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces) + public void Serialize(XmlWriter xmlWriter, object? o, XmlSerializerNamespaces? namespaces) { Serialize(xmlWriter, o, namespaces, null); } - public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle) + public void Serialize(XmlWriter xmlWriter, object? o, XmlSerializerNamespaces? namespaces, string? encodingStyle) { Serialize(xmlWriter, o, namespaces, encodingStyle, null); } - public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle, string id) + public void Serialize(XmlWriter xmlWriter, object? o, XmlSerializerNamespaces? namespaces, string? encodingStyle, string? id) { try { @@ -365,7 +366,7 @@ public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces nam else _tempAssembly.InvokeWriter(_mapping, xmlWriter, o, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id); } - catch (Exception e) + catch (Exception? e) { if (e is TargetInvocationException) e = e.InnerException; @@ -374,7 +375,7 @@ public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces nam xmlWriter.Flush(); } - private void SerializeUsingReflection(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle, string id) + private void SerializeUsingReflection(XmlWriter xmlWriter, object? o, XmlSerializerNamespaces? namespaces, string? encodingStyle, string? id) { XmlMapping mapping = GetMapping(); var writer = new ReflectionXmlSerializationWriter(mapping, xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id); @@ -385,13 +386,13 @@ private XmlMapping GetMapping() { if (_mapping == null || !_mapping.GenerateSerializer) { - _mapping = GenerateXmlTypeMapping(_rootType, null, null, null, DefaultNamespace); + _mapping = GenerateXmlTypeMapping(_rootType!, null, null, null, DefaultNamespace); } return _mapping; } - public object Deserialize(Stream stream) + public object? Deserialize(Stream stream) { XmlTextReader xmlReader = new XmlTextReader(stream); xmlReader.WhitespaceHandling = WhitespaceHandling.Significant; @@ -400,7 +401,7 @@ public object Deserialize(Stream stream) return Deserialize(xmlReader, null); } - public object Deserialize(TextReader textReader) + public object? Deserialize(TextReader textReader) { XmlTextReader xmlReader = new XmlTextReader(textReader); xmlReader.WhitespaceHandling = WhitespaceHandling.Significant; @@ -409,22 +410,22 @@ public object Deserialize(TextReader textReader) return Deserialize(xmlReader, null); } - public object Deserialize(XmlReader xmlReader) + public object? Deserialize(XmlReader xmlReader) { return Deserialize(xmlReader, null); } - public object Deserialize(XmlReader xmlReader, XmlDeserializationEvents events) + public object? Deserialize(XmlReader xmlReader, XmlDeserializationEvents events) { return Deserialize(xmlReader, null, events); } - public object Deserialize(XmlReader xmlReader, string encodingStyle) + public object? Deserialize(XmlReader xmlReader, string? encodingStyle) { return Deserialize(xmlReader, encodingStyle, _events); } - public object Deserialize(XmlReader xmlReader, string encodingStyle, XmlDeserializationEvents events) + public object? Deserialize(XmlReader xmlReader, string? encodingStyle, XmlDeserializationEvents events) { events.sender = this; try @@ -459,7 +460,7 @@ public object Deserialize(XmlReader xmlReader, string encodingStyle, XmlDeserial return _tempAssembly.InvokeReader(_mapping, xmlReader, events, encodingStyle); } } - catch (Exception e) + catch (Exception? e) { if (e is TargetInvocationException) e = e.InnerException; @@ -476,7 +477,7 @@ public object Deserialize(XmlReader xmlReader, string encodingStyle, XmlDeserial } } - private object DeserializeUsingReflection(XmlReader xmlReader, string encodingStyle, XmlDeserializationEvents events) + private object? DeserializeUsingReflection(XmlReader xmlReader, string? encodingStyle, XmlDeserializationEvents events) { XmlMapping mapping = GetMapping(); var reader = new ReflectionXmlSerializationReader(mapping, xmlReader, events, encodingStyle); @@ -493,8 +494,8 @@ public virtual bool CanDeserialize(XmlReader xmlReader) { if (_primitiveType != null) { - TypeDesc typeDesc = (TypeDesc)TypeScope.PrimtiveTypes[_primitiveType]; - return xmlReader.IsStartElement(typeDesc.DataType.Name, string.Empty); + TypeDesc typeDesc = (TypeDesc)TypeScope.PrimtiveTypes[_primitiveType]!; + return xmlReader.IsStartElement(typeDesc.DataType!.Name!, string.Empty); } else if (_tempAssembly != null) { @@ -506,12 +507,12 @@ public virtual bool CanDeserialize(XmlReader xmlReader) } } - public static XmlSerializer[] FromMappings(XmlMapping[] mappings) + public static XmlSerializer[] FromMappings(XmlMapping[]? mappings) { - return FromMappings(mappings, (Type)null); + return FromMappings(mappings, (Type?)null); } - public static XmlSerializer[] FromMappings(XmlMapping[] mappings, Type type) + public static XmlSerializer[] FromMappings(XmlMapping[]? mappings, Type? type) { if (mappings == null || mappings.Length == 0) return Array.Empty(); bool anySoapMapping = false; @@ -529,14 +530,14 @@ public static XmlSerializer[] FromMappings(XmlMapping[] mappings, Type type) return serializers; } - XmlSerializerImplementation contract = null; - Assembly assembly = type == null ? null : TempAssembly.LoadGeneratedAssembly(type, null, out contract); - TempAssembly tempAssembly = null; + XmlSerializerImplementation? contract = null; + Assembly? assembly = type == null ? null : TempAssembly.LoadGeneratedAssembly(type, null, out contract); + TempAssembly? tempAssembly = null; if (assembly == null) { if (Mode == SerializationMode.PreGenOnly) { - AssemblyName name = type.Assembly.GetName(); + AssemblyName name = type!.Assembly.GetName(); string serializerName = Compiler.GetTempAssemblyName(name, null); throw new FileLoadException(SR.Format(SR.FailLoadAssemblyUnderPregenMode, serializerName)); } @@ -549,14 +550,14 @@ public static XmlSerializer[] FromMappings(XmlMapping[] mappings, Type type) { if (type == null) { - tempAssembly = new TempAssembly(mappings, new Type[] { type }, null, null); + tempAssembly = new TempAssembly(mappings, new Type?[] { type }, null, null); XmlSerializer[] serializers = new XmlSerializer[mappings.Length]; contract = tempAssembly.Contract; for (int i = 0; i < serializers.Length; i++) { - serializers[i] = (XmlSerializer)contract.TypedSerializers[mappings[i].Key]; + serializers[i] = (XmlSerializer)contract.TypedSerializers[mappings[i].Key!]!; serializers[i].SetTempAssembly(tempAssembly, mappings[i]); } @@ -573,12 +574,12 @@ public static XmlSerializer[] FromMappings(XmlMapping[] mappings, Type type) { XmlSerializer[] serializers = new XmlSerializer[mappings.Length]; for (int i = 0; i < serializers.Length; i++) - serializers[i] = (XmlSerializer)contract.TypedSerializers[mappings[i].Key]; + serializers[i] = (XmlSerializer)contract!.TypedSerializers[mappings[i].Key!]!; return serializers; } } - private static XmlSerializer[] GetReflectionBasedSerializers(XmlMapping[] mappings, Type type) + private static XmlSerializer[] GetReflectionBasedSerializers(XmlMapping[] mappings, Type? type) { var serializers = new XmlSerializer[mappings.Length]; for (int i = 0; i < serializers.Length; i++) @@ -592,7 +593,7 @@ private static XmlSerializer[] GetReflectionBasedSerializers(XmlMapping[] mappin return serializers; } - internal static bool GenerateSerializer(Type[] types, XmlMapping[] mappings, Stream stream) + internal static bool GenerateSerializer(Type[]? types, XmlMapping[] mappings, Stream stream) { if (types == null || types.Length == 0) return false; @@ -608,7 +609,7 @@ internal static bool GenerateSerializer(Type[] types, XmlMapping[] mappings, Str throw new InvalidOperationException(SR.XmlMelformMapping); } - Assembly assembly = null; + Assembly? assembly = null; for (int i = 0; i < types.Length; i++) { Type type = types[i]; @@ -632,9 +633,9 @@ internal static bool GenerateSerializer(Type[] types, XmlMapping[] mappings, Str private static XmlSerializer[] GetSerializersFromCache(XmlMapping[] mappings, Type type) { - XmlSerializer[] serializers = new XmlSerializer[mappings.Length]; + XmlSerializer?[] serializers = new XmlSerializer?[mappings.Length]; - Dictionary typedMappingTable = null; + Dictionary? typedMappingTable = null; lock (s_xmlSerializerTable) { if (!s_xmlSerializerTable.TryGetValue(type, out typedMappingTable)) @@ -671,18 +672,18 @@ private static XmlSerializer[] GetSerializersFromCache(XmlMapping[] mappings, Ty foreach (XmlSerializerMappingKey mappingKey in pendingKeys.Keys) { index = pendingKeys[mappingKey]; - serializers[index] = (XmlSerializer)contract.TypedSerializers[mappingKey.Mapping.Key]; - serializers[index].SetTempAssembly(tempAssembly, mappingKey.Mapping); + serializers[index] = (XmlSerializer)contract.TypedSerializers[mappingKey.Mapping.Key!]!; + serializers[index]!.SetTempAssembly(tempAssembly, mappingKey.Mapping); - typedMappingTable[mappingKey] = serializers[index]; + typedMappingTable[mappingKey] = serializers[index]!; } } } - return serializers; + return serializers!; } - public static XmlSerializer[] FromTypes(Type[] types) + public static XmlSerializer[] FromTypes(Type[]? types) { if (types == null) return Array.Empty(); @@ -701,7 +702,7 @@ public static string GetXmlSerializerAssemblyName(Type type) return GetXmlSerializerAssemblyName(type, null); } - public static string GetXmlSerializerAssemblyName(Type type, string defaultNamespace) + public static string GetXmlSerializerAssemblyName(Type type, string? defaultNamespace) { if (type == null) { @@ -764,7 +765,7 @@ public event UnreferencedObjectEventHandler UnreferencedObject protected virtual XmlSerializationWriter CreateWriter() { throw new NotImplementedException(); } - protected virtual void Serialize(object o, XmlSerializationWriter writer) { throw new NotImplementedException(); } + protected virtual void Serialize(object? o, XmlSerializationWriter writer) { throw new NotImplementedException(); } internal void SetTempAssembly(TempAssembly tempAssembly, XmlMapping mapping) { @@ -773,25 +774,25 @@ internal void SetTempAssembly(TempAssembly tempAssembly, XmlMapping mapping) _typedSerializer = true; } - private static XmlTypeMapping GetKnownMapping(Type type, string ns) + private static XmlTypeMapping? GetKnownMapping(Type type, string? ns) { if (ns != null && ns != string.Empty) return null; - TypeDesc typeDesc = (TypeDesc)TypeScope.PrimtiveTypes[type]; + TypeDesc? typeDesc = (TypeDesc?)TypeScope.PrimtiveTypes[type]; if (typeDesc == null) return null; ElementAccessor element = new ElementAccessor(); - element.Name = typeDesc.DataType.Name; + element.Name = typeDesc.DataType!.Name; XmlTypeMapping mapping = new XmlTypeMapping(null, element); mapping.SetKeyInternal(XmlMapping.GenerateKey(type, null, null)); return mapping; } - private void SerializePrimitive(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces) + private void SerializePrimitive(XmlWriter xmlWriter, object? o, XmlSerializerNamespaces? namespaces) { XmlSerializationPrimitiveWriter writer = new XmlSerializationPrimitiveWriter(); writer.Init(xmlWriter, namespaces, null, null, null); - switch (_primitiveType.GetTypeCode()) + switch (_primitiveType!.GetTypeCode()) { case TypeCode.String: writer.Write_string(o); @@ -858,18 +859,18 @@ private void SerializePrimitive(XmlWriter xmlWriter, object o, XmlSerializerName } else { - throw new InvalidOperationException(SR.Format(SR.XmlUnxpectedType, _primitiveType.FullName)); + throw new InvalidOperationException(SR.Format(SR.XmlUnxpectedType, _primitiveType!.FullName)); } break; } } - private object DeserializePrimitive(XmlReader xmlReader, XmlDeserializationEvents events) + private object? DeserializePrimitive(XmlReader xmlReader, XmlDeserializationEvents events) { XmlSerializationPrimitiveReader reader = new XmlSerializationPrimitiveReader(); reader.Init(xmlReader, events, null, null); - object o; - switch (_primitiveType.GetTypeCode()) + object? o; + switch (_primitiveType!.GetTypeCode()) { case TypeCode.String: o = reader.Read_string(); @@ -936,7 +937,7 @@ private object DeserializePrimitive(XmlReader xmlReader, XmlDeserializationEvent } else { - throw new InvalidOperationException(SR.Format(SR.XmlUnxpectedType, _primitiveType.FullName)); + throw new InvalidOperationException(SR.Format(SR.XmlUnxpectedType, _primitiveType!.FullName)); } break; } @@ -951,9 +952,9 @@ public XmlSerializerMappingKey(XmlMapping mapping) this.Mapping = mapping; } - public override bool Equals(object obj) + public override bool Equals(object? obj) { - XmlSerializerMappingKey other = obj as XmlSerializerMappingKey; + XmlSerializerMappingKey? other = obj as XmlSerializerMappingKey; if (other == null) return false; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerAssemblyAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerAssemblyAttribute.cs index e194dbfd5fd3ec..77490dfff29484 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerAssemblyAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerAssemblyAttribute.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; @@ -8,26 +9,26 @@ namespace System.Xml.Serialization [AttributeUsage(AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Struct, AllowMultiple = false)] public sealed class XmlSerializerAssemblyAttribute : System.Attribute { - private string _assemblyName; - private string _codeBase; + private string? _assemblyName; + private string? _codeBase; public XmlSerializerAssemblyAttribute() : this(null, null) { } - public XmlSerializerAssemblyAttribute(string assemblyName) : this(assemblyName, null) { } + public XmlSerializerAssemblyAttribute(string? assemblyName) : this(assemblyName, null) { } - public XmlSerializerAssemblyAttribute(string assemblyName, string codeBase) + public XmlSerializerAssemblyAttribute(string? assemblyName, string? codeBase) { _assemblyName = assemblyName; _codeBase = codeBase; } - public string CodeBase + public string? CodeBase { get { return _codeBase; } set { _codeBase = value; } } - public string AssemblyName + public string? AssemblyName { get { return _assemblyName; } set { _assemblyName = value; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerFactory.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerFactory.cs index 76eae175d35a1d..35cf451e09cae6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerFactory.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerFactory.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System.Reflection; @@ -17,22 +18,22 @@ namespace System.Xml.Serialization public class XmlSerializerFactory { - public XmlSerializer CreateSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace) + public XmlSerializer CreateSerializer(Type type, XmlAttributeOverrides? overrides, Type[]? extraTypes, XmlRootAttribute? root, string? defaultNamespace) { return CreateSerializer(type, overrides, extraTypes, root, defaultNamespace, null); } - public XmlSerializer CreateSerializer(Type type, XmlRootAttribute root) + public XmlSerializer CreateSerializer(Type type, XmlRootAttribute? root) { return CreateSerializer(type, null, Array.Empty(), root, null, null); } - public XmlSerializer CreateSerializer(Type type, Type[] extraTypes) + public XmlSerializer CreateSerializer(Type type, Type[]? extraTypes) { return CreateSerializer(type, null, extraTypes, null, null, null); } - public XmlSerializer CreateSerializer(Type type, XmlAttributeOverrides overrides) + public XmlSerializer CreateSerializer(Type type, XmlAttributeOverrides? overrides) { return CreateSerializer(type, overrides, Array.Empty(), null, null, null); } @@ -44,15 +45,15 @@ public XmlSerializer CreateSerializer(XmlTypeMapping xmlTypeMapping) public XmlSerializer CreateSerializer(Type type) { - return CreateSerializer(type, (string)null); + return CreateSerializer(type, (string?)null); } - public XmlSerializer CreateSerializer(Type type, string defaultNamespace) + public XmlSerializer CreateSerializer(Type type, string? defaultNamespace) { return new XmlSerializer(type, defaultNamespace); } - public XmlSerializer CreateSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace, string location) + public XmlSerializer CreateSerializer(Type type, XmlAttributeOverrides? overrides, Type[]? extraTypes, XmlRootAttribute? root, string? defaultNamespace, string? location) { return new XmlSerializer(type, overrides, extraTypes, root, defaultNamespace, location); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerNamespaces.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerNamespaces.cs index bd4c75d9807b03..567018494bc5da 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerNamespaces.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerNamespaces.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System.Reflection; @@ -11,13 +12,14 @@ namespace System.Xml.Serialization using System.Collections.Generic; using System.Xml.Extensions; using System.Xml; + using System.Diagnostics.CodeAnalysis; /// /// [To be supplied.] /// public class XmlSerializerNamespaces { - private Dictionary _namespaces; + private Dictionary? _namespaces; /// /// [To be supplied.] @@ -33,7 +35,7 @@ public XmlSerializerNamespaces() /// public XmlSerializerNamespaces(XmlSerializerNamespaces namespaces) { - _namespaces = new Dictionary(namespaces.Namespaces); + _namespaces = new Dictionary(namespaces.Namespaces); } /// @@ -51,7 +53,7 @@ public XmlSerializerNamespaces(XmlQualifiedName[] namespaces) /// /// [To be supplied.] /// - public void Add(string prefix, string ns) + public void Add(string prefix, string? ns) { // parameter value check if (prefix != null && prefix.Length > 0) @@ -59,10 +61,10 @@ public void Add(string prefix, string ns) if (ns != null && ns.Length > 0) ExtensionMethods.ToUri(ns); - AddInternal(prefix, ns); + AddInternal(prefix!, ns); } - internal void AddInternal(string prefix, string ns) + internal void AddInternal(string prefix, string? ns) { Namespaces[prefix] = ns; } @@ -85,7 +87,7 @@ public int Count get { return Namespaces.Count; } } - internal ArrayList NamespaceList + internal ArrayList? NamespaceList { get { @@ -94,24 +96,25 @@ internal ArrayList NamespaceList ArrayList namespaceList = new ArrayList(); foreach (string key in Namespaces.Keys) { - namespaceList.Add(new XmlQualifiedName(key, (string)Namespaces[key])); + namespaceList.Add(new XmlQualifiedName(key, (string?)Namespaces[key])); } return namespaceList; } } - internal Dictionary Namespaces + [AllowNull] + internal Dictionary Namespaces { get { if (_namespaces == null) - _namespaces = new Dictionary(); + _namespaces = new Dictionary(); return _namespaces; } set { _namespaces = value; } } - internal string LookupPrefix(string ns) + internal string? LookupPrefix(string? ns) { if (string.IsNullOrEmpty(ns)) return null; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerVersionAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerVersionAttribute.cs index 747559aa9d3735..5a7c6716930342 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerVersionAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerVersionAttribute.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; @@ -8,40 +9,40 @@ namespace System.Xml.Serialization [AttributeUsage(AttributeTargets.Assembly)] public sealed class XmlSerializerVersionAttribute : System.Attribute { - private string _mvid; - private string _serializerVersion; - private string _ns; - private Type _type; + private string? _mvid; + private string? _serializerVersion; + private string? _ns; + private Type? _type; public XmlSerializerVersionAttribute() { } - public XmlSerializerVersionAttribute(Type type) + public XmlSerializerVersionAttribute(Type? type) { _type = type; } - public string ParentAssemblyId + public string? ParentAssemblyId { get { return _mvid; } set { _mvid = value; } } - public string Version + public string? Version { get { return _serializerVersion; } set { _serializerVersion = value; } } - public string Namespace + public string? Namespace { get { return _ns; } set { _ns = value; } } - public Type Type + public Type? Type { get { return _type; } set { _type = value; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlTextAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlTextAttribute.cs index 32a117a7d1ff7d..aad49a49b260e9 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlTextAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlTextAttribute.cs @@ -1,8 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; - +using System.Diagnostics.CodeAnalysis; namespace System.Xml.Serialization { @@ -12,8 +13,8 @@ namespace System.Xml.Serialization [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue)] public class XmlTextAttribute : System.Attribute { - private Type _type; - private string _dataType; + private Type? _type; + private string? _dataType; /// /// [To be supplied.] @@ -25,7 +26,7 @@ public XmlTextAttribute() /// /// [To be supplied.] /// - public XmlTextAttribute(Type type) + public XmlTextAttribute(Type? type) { _type = type; } @@ -33,7 +34,7 @@ public XmlTextAttribute(Type type) /// /// [To be supplied.] /// - public Type Type + public Type? Type { get { return _type; } set { _type = value; } @@ -42,6 +43,7 @@ public Type Type /// /// [To be supplied.] /// + [AllowNull] public string DataType { get { return _dataType == null ? string.Empty : _dataType; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlTypeAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlTypeAttribute.cs index 880615dfdeab79..de408389ce4a8c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlTypeAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlTypeAttribute.cs @@ -1,8 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; - +using System.Diagnostics.CodeAnalysis; namespace System.Xml.Serialization { @@ -14,8 +15,8 @@ public class XmlTypeAttribute : System.Attribute { private bool _includeInSchema = true; private bool _anonymousType; - private string _ns; - private string _typeName; + private string? _ns; + private string? _typeName; /// /// [To be supplied.] @@ -27,7 +28,7 @@ public XmlTypeAttribute() /// /// [To be supplied.] /// - public XmlTypeAttribute(string typeName) + public XmlTypeAttribute(string? typeName) { _typeName = typeName; } @@ -53,6 +54,7 @@ public bool IncludeInSchema /// /// [To be supplied.] /// + [AllowNull] public string TypeName { get { return _typeName == null ? string.Empty : _typeName; } @@ -62,7 +64,7 @@ public string TypeName /// /// [To be supplied.] /// - public string Namespace + public string? Namespace { get { return _ns; } set { _ns = value; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlTypeMapping.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlTypeMapping.cs index 4d96050a8a5c74..fbc74d40862979 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlTypeMapping.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlTypeMapping.cs @@ -1,10 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System.Reflection; using System; - namespace System.Xml.Serialization { /// @@ -12,11 +12,11 @@ namespace System.Xml.Serialization /// public class XmlTypeMapping : XmlMapping { - internal XmlTypeMapping(TypeScope scope, ElementAccessor accessor) : base(scope, accessor) + internal XmlTypeMapping(TypeScope? scope, ElementAccessor accessor) : base(scope, accessor) { } - internal TypeMapping Mapping + internal TypeMapping? Mapping { get { return Accessor.Mapping; } } @@ -28,7 +28,7 @@ public string TypeName { get { - return Mapping.TypeDesc.Name; + return Mapping!.TypeDesc!.Name; } } @@ -39,29 +39,29 @@ public string TypeFullName { get { - return Mapping.TypeDesc.FullName; + return Mapping!.TypeDesc!.FullName; } } /// /// [To be supplied.] /// - public string XsdTypeName + public string? XsdTypeName { get { - return Mapping.TypeName; + return Mapping!.TypeName; } } /// /// [To be supplied.] /// - public string XsdTypeNamespace + public string? XsdTypeNamespace { get { - return Mapping.Namespace; + return Mapping!.Namespace; } } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Xmlcustomformatter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Xmlcustomformatter.cs index 2450890af55692..719eab1c0df102 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Xmlcustomformatter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Xmlcustomformatter.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; @@ -33,7 +34,9 @@ private static DateTimeSerializationSection.DateTimeSerializationMode Mode } } private XmlCustomFormatter() { } - internal static string FromDefaultValue(object value, string formatter) + + [return: NotNullIfNotNull("value")] + internal static string? FromDefaultValue(object? value, string formatter) { if (value == null) return null; Type type = value.GetType(); @@ -109,22 +112,26 @@ internal static string FromChar(char value) return XmlConvert.ToString((ushort)value); } - internal static string FromXmlName(string name) + [return: NotNullIfNotNull("name")] + internal static string? FromXmlName(string? name) { return XmlConvert.EncodeName(name); } - internal static string FromXmlNCName(string ncName) + [return: NotNullIfNotNull("ncName")] + internal static string? FromXmlNCName(string? ncName) { return XmlConvert.EncodeLocalName(ncName); } - internal static string FromXmlNmToken(string nmToken) + [return: NotNullIfNotNull("nmToken")] + internal static string? FromXmlNmToken(string? nmToken) { return XmlConvert.EncodeNmToken(nmToken); } - internal static string FromXmlNmTokens(string nmTokens) + [return: NotNullIfNotNull("nmTokens")] + internal static string? FromXmlNmTokens(string? nmTokens) { if (nmTokens == null) return null; @@ -152,7 +159,8 @@ internal static void WriteArrayBase64(XmlWriter writer, byte[] inData, int start writer.WriteBase64(inData, start, count); } - internal static string FromByteArrayHex(byte[] value) + [return: NotNullIfNotNull("value")] + internal static string? FromByteArrayHex(byte[]? value) { if (value == null) return null; @@ -162,7 +170,7 @@ internal static string FromByteArrayHex(byte[] value) return XmlConvert.ToBinHexString(value); } - internal static string FromEnum(long val, string[] vals, long[] ids, string typeName) + internal static string FromEnum(long val, string[] vals, long[] ids, string? typeName) { #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe @@ -393,27 +401,32 @@ internal static char ToChar(string value) return (char)XmlConvert.ToUInt16(value); } - internal static string ToXmlName(string value) + [return: NotNullIfNotNull("value")] + internal static string? ToXmlName(string? value) { return XmlConvert.DecodeName(CollapseWhitespace(value)); } - internal static string ToXmlNCName(string value) + [return: NotNullIfNotNull("value")] + internal static string? ToXmlNCName(string? value) { return XmlConvert.DecodeName(CollapseWhitespace(value)); } - internal static string ToXmlNmToken(string value) + [return: NotNullIfNotNull("value")] + internal static string? ToXmlNmToken(string? value) { return XmlConvert.DecodeName(CollapseWhitespace(value)); } - internal static string ToXmlNmTokens(string value) + [return: NotNullIfNotNull("value")] + internal static string? ToXmlNmTokens(string? value) { return XmlConvert.DecodeName(CollapseWhitespace(value)); } - internal static byte[] ToByteArrayBase64(string value) + [return: NotNullIfNotNull("value")] + internal static byte[]? ToByteArrayBase64(string? value) { if (value == null) return null; value = value.Trim(); @@ -421,20 +434,22 @@ internal static byte[] ToByteArrayBase64(string value) return Array.Empty(); return Convert.FromBase64String(value); } - internal static byte[] ToByteArrayHex(string value) + + [return: NotNullIfNotNull("value")] + internal static byte[]? ToByteArrayHex(string? value) { if (value == null) return null; value = value.Trim(); return XmlConvert.FromBinHexString(value); } - internal static long ToEnum(string val, Hashtable vals, string typeName, bool validate) + internal static long ToEnum(string val, Hashtable vals, string? typeName, bool validate) { long value = 0; string[] parts = val.Split(null); for (int i = 0; i < parts.Length; i++) { - object id = vals[parts[i]]; + object? id = vals[parts[i]]; if (id != null) value |= (long)id; else if (validate && parts[i].Length > 0) @@ -443,7 +458,8 @@ internal static long ToEnum(string val, Hashtable vals, string typeName, bool va return value; } - private static string CollapseWhitespace(string value) + [return: NotNullIfNotNull("value")] + private static string? CollapseWhitespace(string? value) { if (value == null) return null; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/_Events.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/_Events.cs index 0dbffd395f16f4..2ec21b84552ebb 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/_Events.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/_Events.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System.IO; @@ -9,18 +10,18 @@ namespace System.Xml.Serialization using System.ComponentModel; using System.Xml; - public delegate void XmlAttributeEventHandler(object sender, XmlAttributeEventArgs e); + public delegate void XmlAttributeEventHandler(object? sender, XmlAttributeEventArgs e); public class XmlAttributeEventArgs : EventArgs { - private readonly object _o; + private readonly object? _o; private readonly XmlAttribute _attr; - private readonly string _qnames; + private readonly string? _qnames; private readonly int _lineNumber; private readonly int _linePosition; - internal XmlAttributeEventArgs(XmlAttribute attr, int lineNumber, int linePosition, object o, string qnames) + internal XmlAttributeEventArgs(XmlAttribute attr, int lineNumber, int linePosition, object? o, string? qnames) { _attr = attr; _o = o; @@ -29,7 +30,7 @@ internal XmlAttributeEventArgs(XmlAttribute attr, int lineNumber, int linePositi _linePosition = linePosition; } - public object ObjectBeingDeserialized + public object? ObjectBeingDeserialized { get { return _o; } } @@ -64,17 +65,17 @@ public string ExpectedAttributes } } - public delegate void XmlElementEventHandler(object sender, XmlElementEventArgs e); + public delegate void XmlElementEventHandler(object? sender, XmlElementEventArgs e); public class XmlElementEventArgs : EventArgs { - private readonly object _o; + private readonly object? _o; private readonly XmlElement _elem; - private readonly string _qnames; + private readonly string? _qnames; private readonly int _lineNumber; private readonly int _linePosition; - internal XmlElementEventArgs(XmlElement elem, int lineNumber, int linePosition, object o, string qnames) + internal XmlElementEventArgs(XmlElement elem, int lineNumber, int linePosition, object? o, string? qnames) { _elem = elem; _o = o; @@ -83,7 +84,7 @@ internal XmlElementEventArgs(XmlElement elem, int lineNumber, int linePosition, _linePosition = linePosition; } - public object ObjectBeingDeserialized + public object? ObjectBeingDeserialized { get { return _o; } } @@ -112,18 +113,18 @@ public string ExpectedElements } } - public delegate void XmlNodeEventHandler(object sender, XmlNodeEventArgs e); + public delegate void XmlNodeEventHandler(object? sender, XmlNodeEventArgs e); public class XmlNodeEventArgs : EventArgs { - private readonly object _o; + private readonly object? _o; private readonly XmlNode _xmlNode; private readonly int _lineNumber; private readonly int _linePosition; - internal XmlNodeEventArgs(XmlNode xmlNode, int lineNumber, int linePosition, object o) + internal XmlNodeEventArgs(XmlNode xmlNode, int lineNumber, int linePosition, object? o) { _o = o; _xmlNode = xmlNode; @@ -131,7 +132,7 @@ internal XmlNodeEventArgs(XmlNode xmlNode, int lineNumber, int linePosition, obj _linePosition = linePosition; } - public object ObjectBeingDeserialized + public object? ObjectBeingDeserialized { get { return _o; } } @@ -156,7 +157,7 @@ public string NamespaceURI get { return _xmlNode.NamespaceURI; } } - public string Text + public string? Text { get { return _xmlNode.Value; } } @@ -178,25 +179,25 @@ public int LinePosition } } - public delegate void UnreferencedObjectEventHandler(object sender, UnreferencedObjectEventArgs e); + public delegate void UnreferencedObjectEventHandler(object? sender, UnreferencedObjectEventArgs e); public class UnreferencedObjectEventArgs : EventArgs { - private readonly object _o; - private readonly string _id; + private readonly object? _o; + private readonly string? _id; - public UnreferencedObjectEventArgs(object o, string id) + public UnreferencedObjectEventArgs(object? o, string? id) { _o = o; _id = id; } - public object UnreferencedObject + public object? UnreferencedObject { get { return _o; } } - public string UnreferencedId + public string? UnreferencedId { get { return _id; } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/indentedWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/indentedWriter.cs index 1711118e8bd543..c45f0b74e3d257 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/indentedWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/indentedWriter.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System.IO; @@ -33,7 +34,7 @@ internal int Indent } } - internal void Write(string s) + internal void Write(string? s) { if (_needIndent) WriteIndent(); _writer.Write(s); @@ -45,7 +46,7 @@ internal void Write(char c) _writer.Write(c); } - internal void WriteLine(string s) + internal void WriteLine(string? s) { if (_needIndent) WriteIndent(); _writer.WriteLine(s); From a4c673e8a5f296cfa88e8a7809970264699a6b19 Mon Sep 17 00:00:00 2001 From: Krzysztof Wicher Date: Thu, 27 Aug 2020 14:57:29 +0200 Subject: [PATCH 07/14] Globally enable nullability in XML (#41438) * Globally enable nullability in XML * remove double #nullable enable in the file --- src/libraries/Common/src/SkipLocalsInit.cs | 1 + .../Common/src/System/CSharpHelpers.cs | 1 + .../Common/src/System/HexConverter.cs | 1 + src/libraries/Common/src/System/Marvin.cs | 1 + .../System.Private.Xml/src/Misc/HResults.cs | 1 - .../src/System.Private.Xml.csproj | 1 + .../src/System/Xml/AsyncHelper.cs | 1 - .../src/System/Xml/Base64Decoder.cs | 1 - .../src/System/Xml/Base64Encoder.cs | 1 - .../src/System/Xml/Base64EncoderAsync.cs | 1 - .../src/System/Xml/BinHexDecoder.cs | 1 - .../src/System/Xml/BinHexEncoder.cs | 1 - .../src/System/Xml/BinHexEncoderAsync.cs | 1 - .../src/System/Xml/BinaryXml/BinXmlToken.cs | 1 - .../src/System/Xml/BinaryXml/SqlUtils.cs | 1 - .../System/Xml/BinaryXml/XmlBinaryReader.cs | 1 - .../src/System/Xml/BitStack.cs | 1 - .../System.Private.Xml/src/System/Xml/Bits.cs | 1 - .../src/System/Xml/ByteStack.cs | 1 - .../src/System/Xml/Cache/Shape.cs | 1 - .../src/System/Xml/Cache/ShapeGenerator.cs | 1 - .../System/Xml/Cache/XPathDocumentBuilder.cs | 1 - .../System/Xml/Cache/XPathDocumentIterator.cs | 1 - .../Xml/Cache/XPathDocumentNavigator.cs | 1 - .../src/System/Xml/Cache/XPathDocumentView.cs | 1 - .../src/System/Xml/Cache/XPathNode.cs | 1 - .../src/System/Xml/Cache/XPathNodeHelper.cs | 1 - .../src/System/Xml/Cache/XPathNodeInfoAtom.cs | 1 - .../src/System/Xml/Cache/XPathNodeView.cs | 1 - .../Cache/XPathNodeViewPropertyDescriptor.cs | 1 - .../Xml/Core/CharEntityEncoderFallback.cs | 1 - .../src/System/Xml/Core/ConformanceLevel.cs | 1 - .../src/System/Xml/Core/DtdProcessing.cs | 1 - .../src/System/Xml/Core/EntityHandling.cs | 1 - .../Xml/Core/HtmlEncodedRawTextWriter.cs | 2 +- .../Core/HtmlRawTextWriterGenerator.ttinclude | 10 +- .../src/System/Xml/Core/HtmlTernaryTree.cs | 1 - .../System/Xml/Core/HtmlUtf8RawTextWriter.cs | 2 +- .../src/System/Xml/Core/IDtdInfo.cs | 1 - .../src/System/Xml/Core/IDtdParser.cs | 1 - .../src/System/Xml/Core/IDtdParserAdapter.cs | 1 - .../System/Xml/Core/IDtdParserAdapterAsync.cs | 1 - .../src/System/Xml/Core/IDtdParserAsync.cs | 1 - .../src/System/Xml/Core/IRemovableWriter.cs | 1 - .../Xml/Core/IValidationEventHandling.cs | 1 - .../Xml/Core/IncrementalReadDecoders.cs | 1 - .../Xml/Core/LocalAppContextSwitches.cs | 1 - .../src/System/Xml/Core/NamespaceHandling.cs | 1 - .../src/System/Xml/Core/NewLineHandling.cs | 1 - .../src/System/Xml/Core/QueryOutputWriter.cs | 1 - .../System/Xml/Core/QueryOutputWriterV1.cs | 1 - .../Xml/Core/ReadContentAsBinaryHelper.cs | 1 - .../Core/ReadContentAsBinaryHelperAsync.cs | 5 +- .../System/Xml/Core/ReadOnlyTernaryTree.cs | 1 - .../src/System/Xml/Core/ReadState.cs | 1 - .../Xml/Core/TextEncodedRawTextWriter.cs | 1 + .../Core/TextRawTextWriterGenerator.ttinclude | 6 +- .../System/Xml/Core/TextUtf8RawTextWriter.cs | 1 + .../Xml/Core/ValidatingReaderNodeData.cs | 1 - .../src/System/Xml/Core/ValidationType.cs | 1 - .../src/System/Xml/Core/WhitespaceHandling.cs | 1 - .../System/Xml/Core/XmlAsyncCheckReader.cs | 1 - .../System/Xml/Core/XmlAsyncCheckWriter.cs | 1 - .../System/Xml/Core/XmlAutoDetectWriter.cs | 1 - .../System/Xml/Core/XmlCharCheckingReader.cs | 1 - .../Xml/Core/XmlCharCheckingReaderAsync.cs | 1 - .../System/Xml/Core/XmlCharCheckingWriter.cs | 1 - .../Xml/Core/XmlCharCheckingWriterAsync.cs | 1 - .../Xml/Core/XmlEncodedRawTextWriter.cs | 3 +- .../Xml/Core/XmlEncodedRawTextWriterAsync.cs | 2 +- .../src/System/Xml/Core/XmlEventCache.cs | 1 - .../src/System/Xml/Core/XmlParserContext.cs | 1 - .../Core/XmlRawTextWriterGenerator.ttinclude | 107 +++++++++++------- .../XmlRawTextWriterGeneratorAsync.ttinclude | 68 ++++++----- .../src/System/Xml/Core/XmlRawWriter.cs | 1 - .../src/System/Xml/Core/XmlRawWriterAsync.cs | 1 - .../src/System/Xml/Core/XmlReader.cs | 1 - .../src/System/Xml/Core/XmlReaderAsync.cs | 1 - .../src/System/Xml/Core/XmlReaderSettings.cs | 1 - .../src/System/Xml/Core/XmlSpace.cs | 1 - .../src/System/Xml/Core/XmlSubtreeReader.cs | 1 - .../System/Xml/Core/XmlSubtreeReaderAsync.cs | 1 - .../src/System/Xml/Core/XmlTextEncoder.cs | 1 - .../src/System/Xml/Core/XmlTextReader.cs | 1 - .../System/Xml/Core/XmlTextReaderImpl.Unix.cs | 1 - .../src/System/Xml/Core/XmlTextReaderImpl.cs | 1 - .../System/Xml/Core/XmlTextReaderImplAsync.cs | 1 - .../Xml/Core/XmlTextReaderImplHelpers.cs | 1 - .../Xml/Core/XmlTextReaderImplHelpersAsync.cs | 1 - .../src/System/Xml/Core/XmlTextWriter.cs | 1 - .../System/Xml/Core/XmlUtf8RawTextWriter.cs | 1 + .../Xml/Core/XmlUtf8RawTextWriterAsync.cs | 1 + .../System/Xml/Core/XmlValidatingReader.cs | 1 - .../Xml/Core/XmlValidatingReaderImpl.cs | 1 - .../Xml/Core/XmlValidatingReaderImplAsync.cs | 1 - .../System/Xml/Core/XmlWellFormedWriter.cs | 1 - .../Xml/Core/XmlWellFormedWriterAsync.cs | 1 - .../Xml/Core/XmlWellFormedWriterHelpers.cs | 1 - .../Core/XmlWellFormedWriterHelpersAsync.cs | 1 - .../src/System/Xml/Core/XmlWrappingReader.cs | 1 - .../System/Xml/Core/XmlWrappingReaderAsync.cs | 1 - .../src/System/Xml/Core/XmlWrappingWriter.cs | 1 - .../System/Xml/Core/XmlWrappingWriterAsync.cs | 1 - .../src/System/Xml/Core/XmlWriter.cs | 1 - .../src/System/Xml/Core/XmlWriterAsync.cs | 1 - .../src/System/Xml/Core/XmlWriterSettings.cs | 1 - .../src/System/Xml/Core/XsdCachingReader.cs | 1 - .../System/Xml/Core/XsdCachingReaderAsync.cs | 1 - .../System/Xml/Core/XsdValidatingReader.cs | 1 - .../Xml/Core/XsdValidatingReaderAsync.cs | 1 - .../src/System/Xml/DiagnosticsSwitches.cs | 1 - .../System/Xml/Dom/DocumentSchemaValidator.cs | 1 - .../System/Xml/Dom/DocumentXPathNavigator.cs | 1 - .../src/System/Xml/Dom/DocumentXmlWriter.cs | 1 - .../src/System/Xml/Dom/DomNameTable.cs | 1 - .../src/System/Xml/Dom/XPathNodeList.cs | 1 - .../src/System/Xml/Dom/XmlAttribute.cs | 1 - .../System/Xml/Dom/XmlAttributeCollection.cs | 1 - .../src/System/Xml/Dom/XmlCDataSection.cs | 1 - .../src/System/Xml/Dom/XmlCharacterData.cs | 1 - .../src/System/Xml/Dom/XmlChildEnumerator.cs | 1 - .../src/System/Xml/Dom/XmlChildNodes.cs | 1 - .../src/System/Xml/Dom/XmlComment.cs | 1 - .../src/System/Xml/Dom/XmlDeclaration.cs | 1 - .../src/System/Xml/Dom/XmlDocument.cs | 1 - .../src/System/Xml/Dom/XmlDocumentFragment.cs | 1 - .../src/System/Xml/Dom/XmlDocumentType.cs | 1 - .../src/System/Xml/Dom/XmlDomTextWriter.cs | 1 - .../src/System/Xml/Dom/XmlElement.cs | 1 - .../src/System/Xml/Dom/XmlElementList.cs | 1 - .../src/System/Xml/Dom/XmlEntity.cs | 1 - .../src/System/Xml/Dom/XmlEntityReference.cs | 1 - .../System/Xml/Dom/XmlEventChangedAction.cs | 1 - .../src/System/Xml/Dom/XmlImplementation.cs | 1 - .../src/System/Xml/Dom/XmlLinkedNode.cs | 1 - .../src/System/Xml/Dom/XmlLoader.cs | 1 - .../src/System/Xml/Dom/XmlName.cs | 1 - .../Dom/XmlNamedNodeMap.SmallXmlNodeList.cs | 1 - .../src/System/Xml/Dom/XmlNamedNodemap.cs | 1 - .../src/System/Xml/Dom/XmlNode.cs | 1 - .../System/Xml/Dom/XmlNodeChangedEventArgs.cs | 1 - .../Xml/Dom/XmlNodeChangedEventHandler.cs | 1 - .../src/System/Xml/Dom/XmlNodeList.cs | 1 - .../src/System/Xml/Dom/XmlNodeReader.cs | 1 - .../src/System/Xml/Dom/XmlNotation.cs | 1 - .../Xml/Dom/XmlProcessingInstruction.cs | 1 - .../Xml/Dom/XmlSignificantWhiteSpace.cs | 1 - .../src/System/Xml/Dom/XmlText.cs | 1 - .../System/Xml/Dom/XmlUnspecifiedAttribute.cs | 1 - .../src/System/Xml/Dom/XmlWhitespace.cs | 1 - .../src/System/Xml/EmptyEnumerator.cs | 1 - .../System/Xml/Extensions/ExtensionMethods.cs | 1 - .../src/System/Xml/HWStack.cs | 1 - .../Xml/IApplicationResourceStreamResolver.cs | 1 - .../src/System/Xml/IHasXmlNode.cs | 1 - .../src/System/Xml/IXmlLineInfo.cs | 1 - .../src/System/Xml/IXmlNamespaceResolver.cs | 1 - .../src/System/Xml/LineInfo.cs | 1 - .../src/System/Xml/MTNameTable.cs | 1 - .../src/System/Xml/NameTable.cs | 1 - .../System.Private.Xml/src/System/Xml/Ref.cs | 1 - .../src/System/Xml/Resolvers/XmlKnownDtds.cs | 1 - .../Xml/Resolvers/XmlPreloadedResolver.cs | 1 - .../Resolvers/XmlPreloadedResolverAsync.cs | 1 - .../src/System/Xml/Schema/Asttree.cs | 1 - .../src/System/Xml/Schema/AutoValidator.cs | 1 - .../src/System/Xml/Schema/BaseProcessor.cs | 1 - .../src/System/Xml/Schema/BaseValidator.cs | 1 - .../src/System/Xml/Schema/BitSet.cs | 1 - .../src/System/Xml/Schema/Chameleonkey.cs | 1 - .../Xml/Schema/CompiledidEntityConstraint.cs | 1 - .../src/System/Xml/Schema/ConstraintStruct.cs | 1 - .../src/System/Xml/Schema/ContentValidator.cs | 1 - .../Xml/Schema/DataTypeImplementation.cs | 1 - .../src/System/Xml/Schema/DtdParser.cs | 1 - .../src/System/Xml/Schema/DtdParserAsync.cs | 1 - .../src/System/Xml/Schema/DtdValidator.cs | 1 - .../src/System/Xml/Schema/FacetChecker.cs | 1 - .../src/System/Xml/Schema/IXmlSchemaInfo.cs | 1 - .../src/System/Xml/Schema/Inference/Infer.cs | 1 - .../Inference/XmlSchemaInferenceException.cs | 1 - .../src/System/Xml/Schema/NamespaceList.cs | 1 - .../src/System/Xml/Schema/Parser.cs | 1 - .../src/System/Xml/Schema/ParserAsync.cs | 1 - .../src/System/Xml/Schema/Preprocessor.cs | 1 - .../src/System/Xml/Schema/SchemaAttDef.cs | 1 - .../src/System/Xml/Schema/SchemaBuilder.cs | 1 - .../Xml/Schema/SchemaCollectionCompiler.cs | 1 - .../Schema/SchemaCollectionpreProcessor.cs | 1 - .../src/System/Xml/Schema/SchemaDeclBase.cs | 1 - .../System/Xml/Schema/SchemaElementDecl.cs | 1 - .../src/System/Xml/Schema/SchemaEntity.cs | 1 - .../src/System/Xml/Schema/SchemaInfo.cs | 1 - .../src/System/Xml/Schema/SchemaNames.cs | 1 - .../Xml/Schema/SchemaNamespacemanager.cs | 1 - .../src/System/Xml/Schema/SchemaNotation.cs | 1 - .../System/Xml/Schema/SchemaSetCompiler.cs | 1 - .../src/System/Xml/Schema/SchemaType.cs | 1 - .../System/Xml/Schema/ValidationEventArgs.cs | 1 - .../Xml/Schema/ValidationEventHandler.cs | 1 - .../src/System/Xml/Schema/ValidationState.cs | 1 - .../src/System/Xml/Schema/XdrBuilder.cs | 1 - .../src/System/Xml/Schema/XdrValidator.cs | 1 - .../src/System/Xml/Schema/XmlAtomicValue.cs | 1 - .../src/System/Xml/Schema/XmlSchema.cs | 1 - .../src/System/Xml/Schema/XmlSchemaAll.cs | 1 - .../System/Xml/Schema/XmlSchemaAnnotated.cs | 1 - .../System/Xml/Schema/XmlSchemaAnnotation.cs | 1 - .../src/System/Xml/Schema/XmlSchemaAny.cs | 1 - .../Xml/Schema/XmlSchemaAnyAttribute.cs | 1 - .../src/System/Xml/Schema/XmlSchemaAppInfo.cs | 1 - .../System/Xml/Schema/XmlSchemaAttribute.cs | 1 - .../Xml/Schema/XmlSchemaAttributeGroup.cs | 1 - .../Xml/Schema/XmlSchemaAttributeGroupref.cs | 1 - .../src/System/Xml/Schema/XmlSchemaChoice.cs | 1 - .../System/Xml/Schema/XmlSchemaCollection.cs | 1 - .../Schema/XmlSchemaCompilationSettings.cs | 1 - .../Xml/Schema/XmlSchemaComplexContent.cs | 1 - .../XmlSchemaComplexContentExtension.cs | 1 - .../XmlSchemaComplexContentRestriction.cs | 1 - .../System/Xml/Schema/XmlSchemaComplexType.cs | 1 - .../src/System/Xml/Schema/XmlSchemaContent.cs | 1 - .../Xml/Schema/XmlSchemaContentModel.cs | 1 - .../Xml/Schema/XmlSchemaContentProcessing.cs | 1 - .../System/Xml/Schema/XmlSchemaContentType.cs | 1 - .../System/Xml/Schema/XmlSchemaDataType.cs | 1 - .../Xml/Schema/XmlSchemaDerivationMethod.cs | 1 - .../Xml/Schema/XmlSchemaDocumentation.cs | 1 - .../src/System/Xml/Schema/XmlSchemaElement.cs | 1 - .../System/Xml/Schema/XmlSchemaException.cs | 1 - .../System/Xml/Schema/XmlSchemaExternal.cs | 1 - .../src/System/Xml/Schema/XmlSchemaFacet.cs | 1 - .../src/System/Xml/Schema/XmlSchemaForm.cs | 1 - .../src/System/Xml/Schema/XmlSchemaGroup.cs | 1 - .../System/Xml/Schema/XmlSchemaGroupBase.cs | 1 - .../System/Xml/Schema/XmlSchemaGroupRef.cs | 1 - .../Xml/Schema/XmlSchemaIdEntityConstraint.cs | 1 - .../src/System/Xml/Schema/XmlSchemaImport.cs | 1 - .../src/System/Xml/Schema/XmlSchemaInclude.cs | 1 - .../src/System/Xml/Schema/XmlSchemaInfo.cs | 1 - .../System/Xml/Schema/XmlSchemaNotation.cs | 1 - .../src/System/Xml/Schema/XmlSchemaObject.cs | 1 - .../Xml/Schema/XmlSchemaObjectCollection.cs | 1 - .../System/Xml/Schema/XmlSchemaObjectTable.cs | 1 - .../System/Xml/Schema/XmlSchemaParticle.cs | 1 - .../System/Xml/Schema/XmlSchemaRedefine.cs | 1 - .../System/Xml/Schema/XmlSchemaSequence.cs | 1 - .../src/System/Xml/Schema/XmlSchemaSet.cs | 1 - .../Xml/Schema/XmlSchemaSimpleContent.cs | 1 - .../Schema/XmlSchemaSimpleContentExtension.cs | 1 - .../XmlSchemaSimpleContentRestriction.cs | 1 - .../System/Xml/Schema/XmlSchemaSimpleType.cs | 1 - .../Xml/Schema/XmlSchemaSimpleTypeContent.cs | 1 - .../Xml/Schema/XmlSchemaSimpleTypeList.cs | 1 - .../Schema/XmlSchemaSimpleTypeRestriction.cs | 1 - .../Xml/Schema/XmlSchemaSimpleTypeUnion.cs | 1 - .../Xml/Schema/XmlSchemaSubstitutionGroup.cs | 1 - .../src/System/Xml/Schema/XmlSchemaType.cs | 1 - .../src/System/Xml/Schema/XmlSchemaUse.cs | 1 - .../Schema/XmlSchemaValidationException.cs | 1 - .../System/Xml/Schema/XmlSchemaValidator.cs | 1 - .../System/Xml/Schema/XmlSchemaValidity.cs | 1 - .../src/System/Xml/Schema/XmlSeverityType.cs | 1 - .../src/System/Xml/Schema/XmlTokenizedType.cs | 1 - .../src/System/Xml/Schema/XmlTypeCode.cs | 1 - .../Xml/Schema/XmlUntypedStringConverter.cs | 1 - .../System/Xml/Schema/XmlValueConverter.cs | 1 - .../src/System/Xml/Schema/XsdBuilder.cs | 1 - .../src/System/Xml/Schema/XsdDateTime.cs | 1 - .../src/System/Xml/Schema/XsdDuration.cs | 1 - .../src/System/Xml/Schema/XsdValidator.cs | 1 - .../Serialization/CodeGenerationoptions.cs | 1 - .../System/Xml/Serialization/CodeGenerator.cs | 1 - .../Xml/Serialization/CodeIdentifier.cs | 1 - .../Xml/Serialization/CodeIdentifiers.cs | 1 - .../System/Xml/Serialization/Compilation.cs | 1 - .../src/System/Xml/Serialization/Compiler.cs | 1 - .../DateTimeSerializationSection.cs | 1 - .../src/System/Xml/Serialization/Globals.cs | 1 - .../Xml/Serialization/IXmlSerializable.cs | 1 - .../Xml/Serialization/IXmlTextParser.cs | 1 - .../System/Xml/Serialization/ImportContext.cs | 1 - .../src/System/Xml/Serialization/Mappings.cs | 1 - .../src/System/Xml/Serialization/Models.cs | 1 - .../src/System/Xml/Serialization/NameTable.cs | 1 - .../Serialization/PrimitiveXmlSerializers.cs | 1 - .../ReflectionXmlSerializationReader.cs | 1 - .../ReflectionXmlSerializationWriter.cs | 1 - .../Xml/Serialization/SchemaImporter.cs | 1 - .../Xml/Serialization/SchemaObjectWriter.cs | 1 - .../Serialization/SoapAttributeAttribute.cs | 1 - .../Serialization/SoapAttributeOverrides.cs | 1 - .../Xml/Serialization/SoapAttributes.cs | 1 - .../Xml/Serialization/SoapElementAttribute.cs | 1 - .../Xml/Serialization/SoapEnumAttribute.cs | 1 - .../Xml/Serialization/SoapIgnoreAttribute.cs | 1 - .../Xml/Serialization/SoapIncludeAttribute.cs | 1 - .../Serialization/SoapReflectionImporter.cs | 1 - .../Xml/Serialization/SoapSchemamember.cs | 1 - .../Xml/Serialization/SoapTypeAttribute.cs | 1 - .../System/Xml/Serialization/SourceInfo.cs | 1 - .../src/System/Xml/Serialization/TypeCode.cs | 1 - .../Xml/Serialization/TypeExtensions.cs | 1 - .../src/System/Xml/Serialization/Types.cs | 1 - .../Serialization/XmlAnyAttributeAttribute.cs | 1 - .../Serialization/XmlAnyElementAttribute.cs | 1 - .../Serialization/XmlAnyElementAttributes.cs | 1 - .../Xml/Serialization/XmlArrayAttribute.cs | 1 - .../Serialization/XmlArrayItemAttribute.cs | 1 - .../Serialization/XmlArrayItemAttributes.cs | 1 - .../Serialization/XmlAttributeAttribute.cs | 1 - .../Serialization/XmlAttributeOverrides.cs | 1 - .../System/Xml/Serialization/XmlAttributes.cs | 1 - .../XmlChoiceIdentifierAttribute.cs | 1 - .../Xml/Serialization/XmlElementAttribute.cs | 1 - .../Xml/Serialization/XmlElementAttributes.cs | 1 - .../Xml/Serialization/XmlEnumAttribute.cs | 1 - .../Xml/Serialization/XmlIgnoreAttribute.cs | 1 - .../Xml/Serialization/XmlIncludeAttribute.cs | 1 - .../System/Xml/Serialization/XmlMapping.cs | 1 - .../Xml/Serialization/XmlMemberMapping.cs | 1 - .../Xml/Serialization/XmlMembersMapping.cs | 1 - .../XmlNamespaceDeclarationsAttribute.cs | 1 - .../Serialization/XmlReflectionImporter.cs | 1 - .../Xml/Serialization/XmlReflectionMember.cs | 1 - .../Xml/Serialization/XmlRootAttribute.cs | 1 - .../Xml/Serialization/XmlSchemaExporter.cs | 1 - .../Xml/Serialization/XmlSchemaImporter.cs | 1 - .../XmlSchemaProviderAttribute.cs | 1 - .../System/Xml/Serialization/XmlSchemas.cs | 1 - .../XmlSerializationEventSource.cs | 1 - .../XmlSerializationGeneratedCode.cs | 1 - .../Serialization/XmlSerializationILGen.cs | 1 - .../Serialization/XmlSerializationReader.cs | 1 - .../XmlSerializationReaderILGen.cs | 1 - .../Serialization/XmlSerializationWriter.cs | 1 - .../XmlSerializationWriterILGen.cs | 1 - .../System/Xml/Serialization/XmlSerializer.cs | 1 - .../XmlSerializerAssemblyAttribute.cs | 1 - .../Xml/Serialization/XmlSerializerFactory.cs | 1 - .../Serialization/XmlSerializerNamespaces.cs | 1 - .../XmlSerializerVersionAttribute.cs | 1 - .../Xml/Serialization/XmlTextAttribute.cs | 1 - .../Xml/Serialization/XmlTypeAttribute.cs | 1 - .../Xml/Serialization/XmlTypeMapping.cs | 1 - .../Xml/Serialization/Xmlcustomformatter.cs | 1 - .../src/System/Xml/Serialization/_Events.cs | 1 - .../Xml/Serialization/indentedWriter.cs | 1 - .../src/System/Xml/ValidateNames.cs | 1 - .../src/System/Xml/XPath/IXPathNavigable.cs | 1 - .../Xml/XPath/Internal/AbsoluteQuery.cs | 1 - .../src/System/Xml/XPath/Internal/AstNode.cs | 1 - .../Xml/XPath/Internal/AttributeQuery.cs | 1 - .../src/System/Xml/XPath/Internal/Axis.cs | 1 - .../Xml/XPath/Internal/BaseAxisQuery.cs | 1 - .../System/Xml/XPath/Internal/BooleanExpr.cs | 1 - .../Xml/XPath/Internal/BooleanFunctions.cs | 1 - .../Xml/XPath/Internal/CacheAxisQuery.cs | 1 - .../Xml/XPath/Internal/CacheChildrenQuery.cs | 1 - .../Xml/XPath/Internal/CacheOutputQuery.cs | 1 - .../Xml/XPath/Internal/ChildrenQuery.cs | 1 - .../Xml/XPath/Internal/ClonableStack.cs | 1 - .../Xml/XPath/Internal/CompiledXPathExpr.cs | 1 - .../System/Xml/XPath/Internal/ContextQuery.cs | 1 - .../Xml/XPath/Internal/DescendantBaseQuery.cs | 1 - .../Xml/XPath/Internal/DescendantQuery.cs | 1 - .../Internal/DescendantoverDescendantQuery.cs | 1 - .../Xml/XPath/Internal/DocumentorderQuery.cs | 1 - .../System/Xml/XPath/Internal/EmptyQuery.cs | 1 - .../Xml/XPath/Internal/ExtensionQuery.cs | 1 - .../src/System/Xml/XPath/Internal/Filter.cs | 1 - .../System/Xml/XPath/Internal/FilterQuery.cs | 1 - .../Xml/XPath/Internal/FollSiblingQuery.cs | 1 - .../Xml/XPath/Internal/FollowingQuery.cs | 1 - .../XPath/Internal/ForwardPositionQuery.cs | 1 - .../src/System/Xml/XPath/Internal/Function.cs | 1 - .../Xml/XPath/Internal/FunctionQuery.cs | 1 - .../src/System/Xml/XPath/Internal/Group.cs | 1 - .../System/Xml/XPath/Internal/GroupQuery.cs | 1 - .../src/System/Xml/XPath/Internal/IdQuery.cs | 1 - .../Xml/XPath/Internal/IteratorFilter.cs | 1 - .../System/Xml/XPath/Internal/LogicalExpr.cs | 1 - .../Xml/XPath/Internal/MergeFilterQuery.cs | 1 - .../Xml/XPath/Internal/NamespaceQuery.cs | 1 - .../Xml/XPath/Internal/NodeFunctions.cs | 1 - .../Xml/XPath/Internal/NumberFunctions.cs | 1 - .../System/Xml/XPath/Internal/NumericExpr.cs | 1 - .../src/System/Xml/XPath/Internal/Operand.cs | 1 - .../System/Xml/XPath/Internal/OperandQuery.cs | 1 - .../src/System/Xml/XPath/Internal/Operator.cs | 1 - .../System/Xml/XPath/Internal/ParentQuery.cs | 1 - .../Xml/XPath/Internal/PreSiblingQuery.cs | 1 - .../Xml/XPath/Internal/PrecedingQuery.cs | 1 - .../src/System/Xml/XPath/Internal/Query.cs | 1 - .../System/Xml/XPath/Internal/QueryBuilder.cs | 1 - .../Xml/XPath/Internal/ResetableIterator.cs | 1 - .../XPath/Internal/ReversePositionQuery.cs | 1 - .../src/System/Xml/XPath/Internal/Root.cs | 1 - .../System/Xml/XPath/Internal/SortQuery.cs | 1 - .../Xml/XPath/Internal/StringFunctions.cs | 1 - .../System/Xml/XPath/Internal/UnionExpr.cs | 1 - .../System/Xml/XPath/Internal/ValueQuery.cs | 1 - .../src/System/Xml/XPath/Internal/Variable.cs | 1 - .../Xml/XPath/Internal/VariableQuery.cs | 1 - .../XPath/Internal/XPathAncestorIterator.cs | 1 - .../Xml/XPath/Internal/XPathAncestorQuery.cs | 1 - .../Xml/XPath/Internal/XPathArrayIterator.cs | 1 - .../Xml/XPath/Internal/XPathAxisIterator.cs | 1 - .../Xml/XPath/Internal/XPathChildIterator.cs | 1 - .../XPath/Internal/XPathDescendantIterator.cs | 1 - .../Xml/XPath/Internal/XPathEmptyIterator.cs | 1 - .../Xml/XPath/Internal/XPathMultyIterator.cs | 1 - .../System/Xml/XPath/Internal/XPathParser.cs | 1 - .../System/Xml/XPath/Internal/XPathScanner.cs | 1 - .../XPath/Internal/XPathSelectionIterator.cs | 1 - .../Xml/XPath/Internal/XPathSelfQuery.cs | 1 - .../XPath/Internal/XPathSingletonIterator.cs | 1 - .../src/System/Xml/XPath/XPathDocument.cs | 1 - .../src/System/Xml/XPath/XPathException.cs | 1 - .../src/System/Xml/XPath/XPathExpr.cs | 1 - .../src/System/Xml/XPath/XPathItem.cs | 1 - .../System/Xml/XPath/XPathNamespaceScope.cs | 1 - .../src/System/Xml/XPath/XPathNavigator.cs | 1 - .../Xml/XPath/XPathNavigatorKeyComparer.cs | 1 - .../System/Xml/XPath/XPathNavigatorReader.cs | 1 - .../src/System/Xml/XPath/XPathNodeIterator.cs | 1 - .../src/System/Xml/XPath/XPathNodeType.cs | 1 - .../src/System/Xml/XmlCharType.cs | 1 - .../src/System/Xml/XmlComplianceUtil.cs | 1 - .../src/System/Xml/XmlConvert.cs | 1 - .../src/System/Xml/XmlDownloadManager.cs | 1 - .../src/System/Xml/XmlDownloadManagerAsync.cs | 1 - .../src/System/Xml/XmlEncoding.cs | 1 - .../src/System/Xml/XmlException.cs | 1 - .../src/System/Xml/XmlNameTable.cs | 1 - .../src/System/Xml/XmlNamespaceScope.cs | 1 - .../src/System/Xml/XmlNamespacemanager.cs | 1 - .../src/System/Xml/XmlNodeOrder.cs | 1 - .../src/System/Xml/XmlNodeType.cs | 1 - .../src/System/Xml/XmlNullResolver.cs | 1 - .../src/System/Xml/XmlQualifiedName.cs | 1 - .../src/System/Xml/XmlReservedNs.cs | 1 - .../src/System/Xml/XmlResolver.cs | 1 - .../src/System/Xml/XmlResolverAsync.cs | 1 - .../src/System/Xml/XmlSecureResolver.cs | 1 - .../src/System/Xml/XmlSecureResolverAsync.cs | 1 - .../src/System/Xml/XmlUrlResolver.cs | 1 - .../src/System/Xml/XmlUrlResolverAsync.cs | 1 - .../src/System/Xml/Xsl/ISourceLineInfo.cs | 1 - .../System/Xml/Xsl/IlGen/GenerateHelper.cs | 1 - .../Xml/Xsl/IlGen/IteratorDescriptor.cs | 1 - .../System/Xml/Xsl/IlGen/OptimizerPatterns.cs | 1 - .../System/Xml/Xsl/IlGen/StaticDataManager.cs | 1 - .../System/Xml/Xsl/IlGen/TailCallAnalyzer.cs | 1 - .../System/Xml/Xsl/IlGen/XmlILAnnotation.cs | 1 - .../Xml/Xsl/IlGen/XmlILConstructAnalyzer.cs | 1 - .../src/System/Xml/Xsl/IlGen/XmlILModule.cs | 1 - .../System/Xml/Xsl/IlGen/XmlILOptimization.cs | 1 - .../Xml/Xsl/IlGen/XmlILOptimizerVisitor.cs | 1 - .../src/System/Xml/Xsl/IlGen/XmlILTrace.cs | 1 - .../System/Xml/Xsl/IlGen/XmlIlTypeHelper.cs | 1 - .../src/System/Xml/Xsl/IlGen/XmlIlVisitor.cs | 1 - .../src/System/Xml/Xsl/ListBase.cs | 1 - .../src/System/Xml/Xsl/Pair.cs | 1 - .../src/System/Xml/Xsl/QIL/QilBinary.cs | 1 - .../src/System/Xml/Xsl/QIL/QilChoice.cs | 1 - .../src/System/Xml/Xsl/QIL/QilCloneVisitor.cs | 1 - .../src/System/Xml/Xsl/QIL/QilDataSource.cs | 1 - .../src/System/Xml/Xsl/QIL/QilExpression.cs | 1 - .../src/System/Xml/Xsl/QIL/QilFactory.cs | 1 - .../src/System/Xml/Xsl/QIL/QilFunction.cs | 1 - .../src/System/Xml/Xsl/QIL/QilInvoke.cs | 1 - .../System/Xml/Xsl/QIL/QilInvokeEarlyBound.cs | 1 - .../System/Xml/Xsl/QIL/QilInvokeLateBound.cs | 1 - .../src/System/Xml/Xsl/QIL/QilIterator.cs | 1 - .../src/System/Xml/Xsl/QIL/QilList.cs | 1 - .../src/System/Xml/Xsl/QIL/QilLiteral.cs | 1 - .../src/System/Xml/Xsl/QIL/QilLoop.cs | 1 - .../src/System/Xml/Xsl/QIL/QilName.cs | 1 - .../src/System/Xml/Xsl/QIL/QilNode.cs | 1 - .../src/System/Xml/Xsl/QIL/QilNodeType.cs | 1 - .../src/System/Xml/Xsl/QIL/QilParameter.cs | 1 - .../System/Xml/Xsl/QIL/QilPatternFactory.cs | 1 - .../System/Xml/Xsl/QIL/QilPatternVisitor.cs | 1 - .../src/System/Xml/Xsl/QIL/QilReference.cs | 1 - .../System/Xml/Xsl/QIL/QilReplaceVisitor.cs | 1 - .../System/Xml/Xsl/QIL/QilScopedVisitor.cs | 1 - .../src/System/Xml/Xsl/QIL/QilSortKey.cs | 1 - .../src/System/Xml/Xsl/QIL/QilStrConcat.cs | 1 - .../src/System/Xml/Xsl/QIL/QilTargetType.cs | 1 - .../src/System/Xml/Xsl/QIL/QilTernary.cs | 1 - .../src/System/Xml/Xsl/QIL/QilTypeChecker.cs | 1 - .../src/System/Xml/Xsl/QIL/QilUnary.cs | 1 - .../Xml/Xsl/QIL/QilValidationVisitor.cs | 1 - .../src/System/Xml/Xsl/QIL/QilVisitor.cs | 1 - .../src/System/Xml/Xsl/QIL/QilXmlWriter.cs | 1 - .../System/Xml/Xsl/QIL/SerializationHints.cs | 1 - .../System/Xml/Xsl/QIL/SubstitutionList.cs | 1 - .../src/System/Xml/Xsl/QIL/WhitespaceRule.cs | 1 - .../src/System/Xml/Xsl/QueryReaderSettings.cs | 1 - .../Xml/Xsl/Runtime/ContentIterators.cs | 1 + .../Xml/Xsl/Runtime/DecimalFormatter.cs | 1 + .../Xml/Xsl/Runtime/DocumentOrderComparer.cs | 1 + .../Xml/Xsl/Runtime/DodSequenceMerge.cs | 1 + .../System/Xml/Xsl/Runtime/EarlyBoundInfo.cs | 1 + .../System/Xml/Xsl/Runtime/NumberFormatter.cs | 1 + .../System/Xml/Xsl/Runtime/RtfNavigator.cs | 1 + .../System/Xml/Xsl/Runtime/SetIterators.cs | 1 + .../Xml/Xsl/Runtime/SiblingIterators.cs | 1 + .../System/Xml/Xsl/Runtime/StringConcat.cs | 1 - .../System/Xml/Xsl/Runtime/TreeIterators.cs | 1 + .../Xml/Xsl/Runtime/WhitespaceRuleLookup.cs | 1 + .../Xml/Xsl/Runtime/WhitespaceRuleReader.cs | 1 + .../System/Xml/Xsl/Runtime/XmlAggregates.cs | 1 + .../Xml/Xsl/Runtime/XmlAttributeCache.cs | 1 + .../Xml/Xsl/Runtime/XmlCollation.Unix.cs | 1 + .../Xml/Xsl/Runtime/XmlCollation.Windows.cs | 1 + .../System/Xml/Xsl/Runtime/XmlCollation.cs | 1 + .../Xml/Xsl/Runtime/XmlExtensionFunction.cs | 1 + .../src/System/Xml/Xsl/Runtime/XmlILIndex.cs | 1 + .../Xml/Xsl/Runtime/XmlILStorageConverter.cs | 1 + .../System/Xml/Xsl/Runtime/XmlIterators.cs | 1 + .../Xml/Xsl/Runtime/XmlNavigatorFilter.cs | 1 + .../Xml/Xsl/Runtime/XmlNavigatorStack.cs | 1 + .../System/Xml/Xsl/Runtime/XmlQueryContext.cs | 1 + .../System/Xml/Xsl/Runtime/XmlQueryOutput.cs | 1 + .../System/Xml/Xsl/Runtime/XmlQueryRuntime.cs | 1 + .../Xml/Xsl/Runtime/XmlQuerySequence.cs | 1 + .../Xml/Xsl/Runtime/XmlQueryStaticData.cs | 1 + .../Xml/Xsl/Runtime/XmlRawWriterWrapper.cs | 1 + .../Xml/Xsl/Runtime/XmlSequenceWriter.cs | 1 + .../src/System/Xml/Xsl/Runtime/XmlSortKey.cs | 1 + .../Xml/Xsl/Runtime/XmlSortKeyAccumulator.cs | 1 + .../src/System/Xml/Xsl/Runtime/XslNumber.cs | 1 + .../src/System/Xml/Xsl/Runtime/XsltConvert.cs | 1 + .../System/Xml/Xsl/Runtime/XsltFunctions.cs | 1 + .../src/System/Xml/Xsl/Runtime/XsltLibrary.cs | 1 + .../src/System/Xml/Xsl/SourceLineInfo.cs | 1 - .../System/Xml/Xsl/XPath/IXPathEnvironment.cs | 1 - .../src/System/Xml/Xsl/XPath/IXpathBuilder.cs | 1 - .../src/System/Xml/Xsl/XPath/XPathAxis.cs | 1 - .../src/System/Xml/Xsl/XPath/XPathBuilder.cs | 1 - .../Xml/Xsl/XPath/XPathCompileException.cs | 1 - .../src/System/Xml/Xsl/XPath/XPathContext.cs | 1 - .../src/System/Xml/Xsl/XPath/XPathOperator.cs | 1 - .../src/System/Xml/Xsl/XPath/XPathParser.cs | 1 - .../System/Xml/Xsl/XPath/XPathQilFactory.cs | 1 - .../src/System/Xml/Xsl/XPath/XPathScanner.cs | 1 - .../src/System/Xml/Xsl/XPathConvert.cs | 1 - .../src/System/Xml/Xsl/XmlILCommand.cs | 1 - .../src/System/Xml/Xsl/XmlIlGenerator.cs | 1 - .../src/System/Xml/Xsl/XmlNodeKindFlags.cs | 1 - .../System/Xml/Xsl/XmlQualifiedNameTest.cs | 1 - .../src/System/Xml/Xsl/XmlQueryCardinality.cs | 1 - .../src/System/Xml/Xsl/XmlQueryType.cs | 1 - .../src/System/Xml/Xsl/XmlQueryTypeFactory.cs | 1 - .../src/System/Xml/Xsl/XslException.cs | 1 - .../src/System/Xml/Xsl/Xslt/Compiler.cs | 7 +- .../src/System/Xml/Xsl/Xslt/CompilerError.cs | 1 - .../Xml/Xsl/Xslt/CompilerScopeManager.cs | 1 - .../src/System/Xml/Xsl/Xslt/Focus.cs | 1 - .../src/System/Xml/Xsl/Xslt/IErrorHelper.cs | 1 - .../System/Xml/Xsl/Xslt/InvokeGenerator.cs | 1 - .../System/Xml/Xsl/Xslt/KeyMatchBuilder.cs | 1 - .../src/System/Xml/Xsl/Xslt/Keywords.cs | 1 - .../src/System/Xml/Xsl/Xslt/MatcherBuilder.cs | 5 +- .../System/Xml/Xsl/Xslt/OutputScopeManager.cs | 2 - .../src/System/Xml/Xsl/Xslt/QilGenerator.cs | 5 +- .../System/Xml/Xsl/Xslt/QilGeneratorEnv.cs | 1 - .../System/Xml/Xsl/Xslt/QilStrConcatenator.cs | 1 - .../src/System/Xml/Xsl/Xslt/Scripts.cs | 1 - .../src/System/Xml/Xsl/Xslt/Stylesheet.cs | 26 ++--- .../Xml/Xsl/Xslt/XPathPatternBuilder.cs | 1 - .../System/Xml/Xsl/Xslt/XPathPatternParser.cs | 1 - .../src/System/Xml/Xsl/Xslt/XslAst.cs | 1 - .../src/System/Xml/Xsl/Xslt/XslAstAnalyzer.cs | 9 +- .../src/System/Xml/Xsl/Xslt/XslFlags.cs | 1 - .../src/System/Xml/Xsl/Xslt/XslVisitor.cs | 1 - .../src/System/Xml/Xsl/Xslt/XsltInput.cs | 1 - .../src/System/Xml/Xsl/Xslt/XsltLoader.cs | 3 +- .../src/System/Xml/Xsl/Xslt/XsltQilFactory.cs | 1 - .../src/System/Xml/Xsl/XsltOld/Action.cs | 1 - .../src/System/Xml/Xsl/XsltOld/ActionFrame.cs | 1 - .../Xml/Xsl/XsltOld/ApplyImportsAction.cs | 1 - .../Xml/Xsl/XsltOld/ApplyTemplatesAction.cs | 1 - .../System/Xml/Xsl/XsltOld/AttributeAction.cs | 1 - .../Xml/Xsl/XsltOld/AttributeSetAction.cs | 1 - .../src/System/Xml/Xsl/XsltOld/Avt.cs | 1 - .../src/System/Xml/Xsl/XsltOld/AvtEvent.cs | 1 - .../src/System/Xml/Xsl/XsltOld/BeginEvent.cs | 1 - .../src/System/Xml/Xsl/XsltOld/BuilderInfo.cs | 1 - .../Xml/Xsl/XsltOld/CallTemplateAction.cs | 1 - .../System/Xml/Xsl/XsltOld/ChooseAction.cs | 1 - .../System/Xml/Xsl/XsltOld/CommentAction.cs | 1 - .../System/Xml/Xsl/XsltOld/CompiledAction.cs | 1 - .../src/System/Xml/Xsl/XsltOld/Compiler.cs | 1 - .../System/Xml/Xsl/XsltOld/ContainerAction.cs | 1 - .../src/System/Xml/Xsl/XsltOld/CopyAction.cs | 1 - .../Xml/Xsl/XsltOld/CopyAttributesAction.cs | 1 - .../System/Xml/Xsl/XsltOld/CopyCodeAction.cs | 1 - .../Xml/Xsl/XsltOld/CopyNamespacesAction.cs | 1 - .../Xml/Xsl/XsltOld/CopyNodeSetAction.cs | 1 - .../System/Xml/Xsl/XsltOld/CopyOfAction.cs | 1 - .../src/System/Xml/Xsl/XsltOld/DbgCompiler.cs | 1 - .../System/Xml/Xsl/XsltOld/DocumentScope.cs | 1 - .../System/Xml/Xsl/XsltOld/ElementAction.cs | 1 - .../src/System/Xml/Xsl/XsltOld/EndEvent.cs | 1 - .../src/System/Xml/Xsl/XsltOld/Event.cs | 1 - .../System/Xml/Xsl/XsltOld/ForEachAction.cs | 1 - .../src/System/Xml/Xsl/XsltOld/HtmlProps.cs | 1 - .../System/Xml/Xsl/XsltOld/IRecordOutput.cs | 1 - .../src/System/Xml/Xsl/XsltOld/IfAction.cs | 1 - .../src/System/Xml/Xsl/XsltOld/InputScope.cs | 1 - .../Xml/Xsl/XsltOld/InputScopeManager.cs | 1 - .../System/Xml/Xsl/XsltOld/MessageAction.cs | 1 - .../System/Xml/Xsl/XsltOld/NameSpaceEvent.cs | 1 - .../System/Xml/Xsl/XsltOld/NamespaceDecl.cs | 1 - .../System/Xml/Xsl/XsltOld/NavigatorInput.cs | 1 - .../System/Xml/Xsl/XsltOld/NavigatorOutput.cs | 1 - .../System/Xml/Xsl/XsltOld/NumberAction.cs | 1 - .../src/System/Xml/Xsl/XsltOld/OutKeywords.cs | 1 - .../src/System/Xml/Xsl/XsltOld/OutputScope.cs | 1 - .../Xml/Xsl/XsltOld/OutputScopeManager.cs | 1 - .../src/System/Xml/Xsl/XsltOld/PrefixQName.cs | 1 - .../XsltOld/ProcessingInstructionAction.cs | 1 - .../src/System/Xml/Xsl/XsltOld/Processor.cs | 1 - .../System/Xml/Xsl/XsltOld/ReaderOutput.cs | 1 - .../System/Xml/Xsl/XsltOld/RecordBuilder.cs | 1 - .../src/System/Xml/Xsl/XsltOld/RootAction.cs | 1 - .../Xml/Xsl/XsltOld/SequentialOutput.cs | 1 - .../src/System/Xml/Xsl/XsltOld/SortAction.cs | 1 - .../System/Xml/Xsl/XsltOld/StateMachine.cs | 1 - .../System/Xml/Xsl/XsltOld/StringOutput.cs | 1 - .../src/System/Xml/Xsl/XsltOld/Stylesheet.cs | 1 - .../System/Xml/Xsl/XsltOld/TemplateAction.cs | 1 - .../Xml/Xsl/XsltOld/TemplateBaseAction.cs | 1 - .../Xml/Xsl/XsltOld/TemplateLookupAction.cs | 1 - .../System/Xml/Xsl/XsltOld/TemplateManager.cs | 1 - .../src/System/Xml/Xsl/XsltOld/TextAction.cs | 1 - .../src/System/Xml/Xsl/XsltOld/TextEvent.cs | 1 - .../System/Xml/Xsl/XsltOld/TextOnlyOutput.cs | 1 - .../src/System/Xml/Xsl/XsltOld/TextOutput.cs | 1 - .../src/System/Xml/Xsl/XsltOld/TheQuery.cs | 1 - .../Xml/Xsl/XsltOld/UseAttributeSetsAction.cs | 1 - .../System/Xml/Xsl/XsltOld/ValueOfAction.cs | 1 - .../System/Xml/Xsl/XsltOld/VariableAction.cs | 1 - .../System/Xml/Xsl/XsltOld/WithParamAction.cs | 1 - .../System/Xml/Xsl/XsltOld/WriterOutput.cs | 1 - .../Xml/Xsl/XsltOld/XsltCompileContext.cs | 1 - .../System/Xml/Xsl/XsltOld/XsltDebugger.cs | 1 - .../src/System/Xml/Xsl/XsltOld/XsltOutput.cs | 1 - .../Xml/Xsl/XsltOld/newinstructionaction.cs | 1 - .../System/Xml/Xslt/XslCompiledTransform.cs | 1 - .../src/System/Xml/Xslt/XslTransform.cs | 1 - .../src/System/Xml/Xslt/XsltArgumentList.cs | 1 - .../src/System/Xml/Xslt/XsltContext.cs | 1 - .../src/System/Xml/Xslt/XsltException.cs | 1 - .../src/System/Xml/Xslt/XsltSettings.cs | 1 - 658 files changed, 190 insertions(+), 714 deletions(-) diff --git a/src/libraries/Common/src/SkipLocalsInit.cs b/src/libraries/Common/src/SkipLocalsInit.cs index b462975c356d69..cf6403c33892ed 100644 --- a/src/libraries/Common/src/SkipLocalsInit.cs +++ b/src/libraries/Common/src/SkipLocalsInit.cs @@ -1,5 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable disable // Used to indicate to the compiler that the .locals init flag should not be set in method headers. [module: System.Runtime.CompilerServices.SkipLocalsInit] diff --git a/src/libraries/Common/src/System/CSharpHelpers.cs b/src/libraries/Common/src/System/CSharpHelpers.cs index ac1be4170c4e03..decc30b6a0a3ca 100644 --- a/src/libraries/Common/src/System/CSharpHelpers.cs +++ b/src/libraries/Common/src/System/CSharpHelpers.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable disable using System.Collections.Generic; using System.Globalization; diff --git a/src/libraries/Common/src/System/HexConverter.cs b/src/libraries/Common/src/System/HexConverter.cs index d0cd3f074dc008..7f244771ca31a6 100644 --- a/src/libraries/Common/src/System/HexConverter.cs +++ b/src/libraries/Common/src/System/HexConverter.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable disable using System.Diagnostics; using System.Runtime.CompilerServices; diff --git a/src/libraries/Common/src/System/Marvin.cs b/src/libraries/Common/src/System/Marvin.cs index e8a907d2dff6f7..35bd8e2ea045b0 100644 --- a/src/libraries/Common/src/System/Marvin.cs +++ b/src/libraries/Common/src/System/Marvin.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable disable using System.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; diff --git a/src/libraries/System.Private.Xml/src/Misc/HResults.cs b/src/libraries/System.Private.Xml/src/Misc/HResults.cs index 439cb63651a8f0..2cc3c392222ae3 100644 --- a/src/libraries/System.Private.Xml/src/Misc/HResults.cs +++ b/src/libraries/System.Private.Xml/src/Misc/HResults.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable /* These HRESULTs are used for mapping managed exceptions to COM error codes and vice versa through COM Interop. For background on COM error codes see diff --git a/src/libraries/System.Private.Xml/src/System.Private.Xml.csproj b/src/libraries/System.Private.Xml/src/System.Private.Xml.csproj index c3b7f512fce2c4..0d6948e5f38b9f 100644 --- a/src/libraries/System.Private.Xml/src/System.Private.Xml.csproj +++ b/src/libraries/System.Private.Xml/src/System.Private.Xml.csproj @@ -4,6 +4,7 @@ true $(DefineConstants);FEATURE_COMPILED_XSL $(NetCoreAppCurrent)-Windows_NT;$(NetCoreAppCurrent) + enable while (pDst < pDstEnd && (_xmlCharType.IsAttributeValueChar((char)(ch = *pSrc)) && ch <= 0x7F)) <# } else { #> while (pDst < pDstEnd && _xmlCharType.IsAttributeValueChar((char)(ch = *pSrc))) -<# } -#> { +<# } #> + { *pDst++ = (<#= BufferType #>)ch; pSrc++; } @@ -813,8 +815,8 @@ namespace System.Xml { Init(settings); } -<# } -#> + +<# } #> public <#= ClassNameIndent #>(Stream stream, XmlWriterSettings settings) : base(stream, settings) { Init(settings); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/HtmlTernaryTree.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/HtmlTernaryTree.cs index 98de7ca37b87c6..36450f80e4e651 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/HtmlTernaryTree.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/HtmlTernaryTree.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable // This file is generated by TernaryTreeGenerator.cs, // and is used by the TernaryTreeRO class. diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/HtmlUtf8RawTextWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/HtmlUtf8RawTextWriter.cs index 2b71f86d56a9ff..228088b9dc8315 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/HtmlUtf8RawTextWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/HtmlUtf8RawTextWriter.cs @@ -4,6 +4,7 @@ // WARNING: This file is generated and should not be modified directly. // Instead, modify HtmlRawTextWriterGenerator.ttinclude +#nullable disable using System; using System.IO; using System.Text; @@ -779,7 +780,6 @@ internal class HtmlUtf8RawTextWriterIndent : HtmlUtf8RawTextWriter // // Constructors // - public HtmlUtf8RawTextWriterIndent(Stream stream, XmlWriterSettings settings) : base(stream, settings) { Init(settings); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/IDtdInfo.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/IDtdInfo.cs index 400d313cad1b15..66aa795f760355 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/IDtdInfo.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/IDtdInfo.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections.Generic; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/IDtdParser.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/IDtdParser.cs index 3f771d8f91a60e..90def36eed89bf 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/IDtdParser.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/IDtdParser.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Xml; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/IDtdParserAdapter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/IDtdParserAdapter.cs index 29d730cc66dd98..e15c6f5efaf1b8 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/IDtdParserAdapter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/IDtdParserAdapter.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Diagnostics.CodeAnalysis; using System.Text; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/IDtdParserAdapterAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/IDtdParserAdapterAsync.cs index 0299d26f19e02f..6fab0228665ce1 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/IDtdParserAdapterAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/IDtdParserAdapterAsync.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Text; using System.Xml.Schema; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/IDtdParserAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/IDtdParserAsync.cs index 9134424fa76424..261c37daa248c9 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/IDtdParserAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/IDtdParserAsync.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Xml; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/IRemovableWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/IRemovableWriter.cs index c74dc523513304..7399313a41fdc4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/IRemovableWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/IRemovableWriter.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml { /// diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/IValidationEventHandling.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/IValidationEventHandling.cs index 57ce91b8a129a6..7e35927d434d98 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/IValidationEventHandling.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/IValidationEventHandling.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Xml.Schema; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/IncrementalReadDecoders.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/IncrementalReadDecoders.cs index cd61d58b06e215..804790302adddc 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/IncrementalReadDecoders.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/IncrementalReadDecoders.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics; namespace System.Xml diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/LocalAppContextSwitches.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/LocalAppContextSwitches.cs index dd1d002bee7113..1c6a61c43beb3b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/LocalAppContextSwitches.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/LocalAppContextSwitches.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Runtime.CompilerServices; namespace System diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/NamespaceHandling.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/NamespaceHandling.cs index f326b594b4e481..b96189e6aaac71 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/NamespaceHandling.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/NamespaceHandling.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml { // diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/NewLineHandling.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/NewLineHandling.cs index 2020cec7aa6cb0..1e60dd28c72443 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/NewLineHandling.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/NewLineHandling.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml { // NewLineHandling specifies what will XmlWriter do with new line characters. The options are: diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/QueryOutputWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/QueryOutputWriter.cs index 6cced37f2300bf..86e8bd878a6767 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/QueryOutputWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/QueryOutputWriter.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/QueryOutputWriterV1.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/QueryOutputWriterV1.cs index 527c893952fdfa..88cf3c9f91571c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/QueryOutputWriterV1.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/QueryOutputWriterV1.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.IO; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/ReadContentAsBinaryHelper.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/ReadContentAsBinaryHelper.cs index 53a4f6a0e9c6b1..043e9118ec91ba 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/ReadContentAsBinaryHelper.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/ReadContentAsBinaryHelper.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics; namespace System.Xml diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/ReadContentAsBinaryHelperAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/ReadContentAsBinaryHelperAsync.cs index ac94c57cba8a0f..9b2492bebc40bc 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/ReadContentAsBinaryHelperAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/ReadContentAsBinaryHelperAsync.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; - using System.Threading.Tasks; namespace System.Xml @@ -316,7 +315,7 @@ private async Task ReadContentAsBinaryAsync(byte[] buffer, int index, int c { if (_valueOffset < _valueChunkLength) { - int decodedCharsCount = _decoder.Decode(_valueChunk, _valueOffset, _valueChunkLength - _valueOffset); + int decodedCharsCount = _decoder.Decode(_valueChunk!, _valueOffset, _valueChunkLength - _valueOffset); _valueOffset += decodedCharsCount; } if (_decoder.IsFull) @@ -324,7 +323,7 @@ private async Task ReadContentAsBinaryAsync(byte[] buffer, int index, int c return _decoder.DecodedCount; } Debug.Assert(_valueOffset == _valueChunkLength); - if ((_valueChunkLength = await _reader.ReadValueChunkAsync(_valueChunk, 0, ChunkSize).ConfigureAwait(false)) == 0) + if ((_valueChunkLength = await _reader.ReadValueChunkAsync(_valueChunk!, 0, ChunkSize).ConfigureAwait(false)) == 0) { break; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/ReadOnlyTernaryTree.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/ReadOnlyTernaryTree.cs index c33e206bfae930..5b0d0ea23deba5 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/ReadOnlyTernaryTree.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/ReadOnlyTernaryTree.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.IO; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/ReadState.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/ReadState.cs index 63bb693c7135c6..7953441fd3e07d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/ReadState.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/ReadState.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml { // Specifies the state of the XmlReader. diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/TextEncodedRawTextWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/TextEncodedRawTextWriter.cs index 0561b1d19e3506..113c95cec4fa0c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/TextEncodedRawTextWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/TextEncodedRawTextWriter.cs @@ -4,6 +4,7 @@ // WARNING: This file is generated and should not be modified directly. // Instead, modify TextRawTextWriterGenerator.ttinclude +#nullable disable using System; using System.IO; using System.Text; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/TextRawTextWriterGenerator.ttinclude b/src/libraries/System.Private.Xml/src/System/Xml/Core/TextRawTextWriterGenerator.ttinclude index c003190d75e1c3..5147cc74d5190f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/TextRawTextWriterGenerator.ttinclude +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/TextRawTextWriterGenerator.ttinclude @@ -5,6 +5,7 @@ // WARNING: This file is generated and should not be modified directly. // Instead, modify TextRawTextWriterGenerator.ttinclude +#nullable disable using System; using System.IO; using System.Text; @@ -20,12 +21,13 @@ namespace System.Xml // operation with serialization in order to achieve better performance. // internal class <#= ClassName #> : <#= BaseClassName #> - {<# -if (WriterType == RawTextWriterType.Encoded) { #> + { +<# if (WriterType == RawTextWriterType.Encoded) { #> // Construct an instance of this class that outputs text to the TextWriter interface. public <#= ClassName #>(TextWriter writer, XmlWriterSettings settings) : base(writer, settings) { } + <# } #> // Construct an instance of this class that serializes to a Stream interface. public <#= ClassName #>(Stream stream, XmlWriterSettings settings) : base(stream, settings) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/TextUtf8RawTextWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/TextUtf8RawTextWriter.cs index 74858b15aa7aa0..f0b317f3d54b82 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/TextUtf8RawTextWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/TextUtf8RawTextWriter.cs @@ -4,6 +4,7 @@ // WARNING: This file is generated and should not be modified directly. // Instead, modify TextRawTextWriterGenerator.ttinclude +#nullable disable using System; using System.IO; using System.Text; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/ValidatingReaderNodeData.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/ValidatingReaderNodeData.cs index c58e0ec9f40b31..74d47994fbb596 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/ValidatingReaderNodeData.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/ValidatingReaderNodeData.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.IO; using System.Text; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/ValidationType.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/ValidationType.cs index c75b571d05b2aa..e6350a12a6a3f3 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/ValidationType.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/ValidationType.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml { // Specifies the type of validation to perform in XmlValidatingReader or in XmlReaderSettings. diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/WhitespaceHandling.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/WhitespaceHandling.cs index 4e4df434979ca9..1b78f52b0d3803 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/WhitespaceHandling.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/WhitespaceHandling.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml { // Specifies how whitespace is handled in XmlTextReader. diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlAsyncCheckReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlAsyncCheckReader.cs index 97909cf5d95f83..bbb047946b4d85 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlAsyncCheckReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlAsyncCheckReader.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections.Generic; using System.Diagnostics; using System.Threading.Tasks; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlAsyncCheckWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlAsyncCheckWriter.cs index 84990c82955ed0..96829862e6ff38 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlAsyncCheckWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlAsyncCheckWriter.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Threading.Tasks; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlAutoDetectWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlAutoDetectWriter.cs index c3aa8c0d97bd95..39978242bc82d2 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlAutoDetectWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlAutoDetectWriter.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingReader.cs index ca0ce55d013b95..30b088cdc3ffcd 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingReader.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Xml; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingReaderAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingReaderAsync.cs index 68f79ba17a167f..85e0e2a6edace5 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingReaderAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingReaderAsync.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Xml; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriter.cs index 2fa82a671869db..548287eac1629d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriter.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.IO; using System.Text; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriterAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriterAsync.cs index 4b5a0e961fbf3c..1a6395c2ac6a3d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriterAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlCharCheckingWriterAsync.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.IO; using System.Text; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEncodedRawTextWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEncodedRawTextWriter.cs index bc7a3a4daea2a3..4b9796b609e13b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEncodedRawTextWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEncodedRawTextWriter.cs @@ -4,6 +4,7 @@ // WARNING: This file is generated and should not be modified directly. // Instead, modify XmlRawTextWriterGenerator.ttinclude +#nullable disable using System; using System.IO; using System.Xml; @@ -49,7 +50,6 @@ internal partial class XmlEncodedRawTextWriter : XmlRawWriter protected bool _writeToNull; protected bool _hadDoubleBracket; protected bool _inAttributeValue; - protected int _bufBytesUsed; protected char[] _bufChars; @@ -1687,7 +1687,6 @@ internal unsafe void EncodeChar(ref char* pSrc, char* pSrcEnd, ref char* pDst) } } - protected void ChangeTextContentMark(bool value) { Debug.Assert(_inTextContent != value); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEncodedRawTextWriterAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEncodedRawTextWriterAsync.cs index 532039ee830bdd..b48b6051fce649 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEncodedRawTextWriterAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEncodedRawTextWriterAsync.cs @@ -4,6 +4,7 @@ // WARNING: This file is generated and should not be modified directly. // Instead, modify XmlRawTextWriterGeneratorAsync.ttinclude +#nullable disable using System; using System.IO; using System.Xml; @@ -660,7 +661,6 @@ protected virtual async Task FlushBufferAsync() // Move last buffer character to the beginning of the buffer (so that previous character can always be determined) _bufChars[0] = _bufChars[_bufPos - 1]; - // Reset buffer position _textPos = (_textPos == _bufPos) ? 1 : 0; _attrEndPos = (_attrEndPos == _bufPos) ? 1 : 0; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEventCache.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEventCache.cs index 49f4ebc3038888..2f4394cfb2d5f3 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEventCache.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlEventCache.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections.Generic; using System.Diagnostics; using System.Text; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlParserContext.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlParserContext.cs index 77409e7bfd54ec..0ec44b8775e8ae 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlParserContext.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlParserContext.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Xml; using System.Text; using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlRawTextWriterGenerator.ttinclude b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlRawTextWriterGenerator.ttinclude index 05d1c89291b296..1e52c3703cf918 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlRawTextWriterGenerator.ttinclude +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlRawTextWriterGenerator.ttinclude @@ -5,6 +5,7 @@ // WARNING: This file is generated and should not be modified directly. // Instead, modify XmlRawTextWriterGenerator.ttinclude +#nullable disable using System; using System.IO; using System.Xml; @@ -67,8 +68,8 @@ namespace System.Xml private int[] _textContentMarks; // even indices contain text content start positions // odd indices contain markup start positions private readonly CharEntityEncoderFallback _charEntityFallback; -<# } -#> +<# } #> + // writer settings protected NewLineHandling _newLineHandling; protected bool _closeOutput; @@ -88,9 +89,10 @@ namespace System.Xml private const int BUFSIZE = 2048 * 3; // Should be greater than default FileStream size (4096), otherwise the FileStream will try to cache the data private const int ASYNCBUFSIZE = 64 * 1024; // Set async buffer size to 64KB private const int OVERFLOW = 32; // Allow overflow in order to reduce checks when writing out constant size markup -<# if (WriterType != RawTextWriterType.Utf8) { -#> private const int INIT_MARKS_COUNT = 64; +<# if (WriterType != RawTextWriterType.Utf8) { #> + private const int INIT_MARKS_COUNT = 64; <# } #> + // // Constructors // @@ -116,6 +118,7 @@ namespace System.Xml } } <# if (WriterType == RawTextWriterType.Encoded) { #> + // Construct an instance of this class that outputs text to the TextWriter interface. public <#= ClassName #>(TextWriter writer, XmlWriterSettings settings) : this(settings) { @@ -138,6 +141,7 @@ namespace System.Xml } } <# } #> + // Construct an instance of this class that serializes to a Stream interface. public <#= ClassName #>(Stream stream, XmlWriterSettings settings) : this(settings) { @@ -152,8 +156,8 @@ namespace System.Xml _bufLen = ASYNCBUFSIZE; } - <#= BufferName #> = new <#= BufferType #>[_bufLen + OVERFLOW];<# -if (WriterType == RawTextWriterType.Utf8) { #> + <#= BufferName #> = new <#= BufferType #>[_bufLen + OVERFLOW]; +<# if (WriterType == RawTextWriterType.Utf8) { #> // Output UTF-8 byte order mark if Encoding object wants it if (!stream.CanSeek || stream.Position == 0) { @@ -197,6 +201,7 @@ if (WriterType == RawTextWriterType.Utf8) { #> } } <# } #> + // Write the xml declaration if (settings.AutoXmlDeclaration) { @@ -754,8 +759,8 @@ if (WriterType == RawTextWriterType.Utf8) { #> _stream = null; } } - }<# -if (WriterType == RawTextWriterType.Encoded) { #> + } +<# if (WriterType == RawTextWriterType.Encoded) { #> else if (_writer != null) { try @@ -776,8 +781,8 @@ if (WriterType == RawTextWriterType.Encoded) { #> _writer = null; } } - }<# -} #> + } +<# } #> } } @@ -786,12 +791,13 @@ if (WriterType == RawTextWriterType.Encoded) { #> { FlushBuffer(); FlushEncoder(); + <# if (WriterType == RawTextWriterType.Utf8) { #> if (_stream != null) { _stream.Flush(); - }<# -} else { #> + } +<# } else { #> if (_stream != null) { _stream.Flush(); @@ -799,8 +805,8 @@ if (WriterType == RawTextWriterType.Encoded) { #> else if (_writer != null) { _writer.Flush(); - }<# -} #> + } +<# } #> } // @@ -813,14 +819,14 @@ if (WriterType == RawTextWriterType.Encoded) { #> { // Output all characters (except for previous characters stored at beginning of buffer) if (!_writeToNull) - {<# -if (WriterType == RawTextWriterType.Utf8) { #> + { +<# if (WriterType == RawTextWriterType.Utf8) { #> if (_bufPos - 1 > 0) { Debug.Assert(_stream != null); _stream.Write(<#= BufferName #>, 1, _bufPos - 1); - }<# -} else { #> + } +<# } else { #> Debug.Assert(_stream != null || _writer != null); if (_stream != null) @@ -852,8 +858,8 @@ if (WriterType == RawTextWriterType.Utf8) { #> // Write text to TextWriter _writer.Write(<#= BufferName #>, 1, _bufPos - 1); } - }<# -} #> + } +<# } #> } } catch @@ -866,6 +872,7 @@ if (WriterType == RawTextWriterType.Utf8) { #> { // Move last buffer character to the beginning of the buffer (so that previous character can always be determined) <#= BufferName #>[0] = <#= BufferName #>[_bufPos - 1]; + <# if (WriterType == RawTextWriterType.Utf8) { #> if (IsSurrogateByte(<#= BufferName #>[0])) { @@ -875,6 +882,7 @@ if (WriterType == RawTextWriterType.Utf8) { #> <#= BufferName #>[2] = <#= BufferName #>[_bufPos + 1]; <#= BufferName #>[3] = <#= BufferName #>[_bufPos + 2]; } + <# } #> // Reset buffer position _textPos = (_textPos == _bufPos) ? 1 : 0; @@ -885,6 +893,7 @@ if (WriterType == RawTextWriterType.Utf8) { #> // close an empty element or in CDATA section detection of double ]; <#= BufferName #>[0] will always be 0 } } + <# if (WriterType == RawTextWriterType.Utf8) { #> private void FlushEncoder() { @@ -937,6 +946,7 @@ if (WriterType == RawTextWriterType.Utf8) { #> } } <# } #> + // Serialize text that is part of an attribute value. The '&', '<', '>', and '"' characters // are entitized. protected unsafe void WriteAttributeTextBlock(char* pSrc, char* pSrcEnd) @@ -953,12 +963,13 @@ if (WriterType == RawTextWriterType.Utf8) { #> { pDstEnd = pDstBegin + _bufLen; } + <# if (WriterType == RawTextWriterType.Utf8) { #> while (pDst < pDstEnd && (_xmlCharType.IsAttributeValueChar((char)(ch = *pSrc)) && ch <= 0x7F)) <# } else { #> while (pDst < pDstEnd && _xmlCharType.IsAttributeValueChar((char)(ch = *pSrc))) -<# } -#> { +<# } #> + { *pDst = (<#= BufferType #>)ch; pDst++; pSrc++; @@ -1062,12 +1073,13 @@ if (WriterType == RawTextWriterType.Utf8) { #> { pDstEnd = pDstBegin + _bufLen; } + <# if (WriterType == RawTextWriterType.Utf8) { #> while (pDst < pDstEnd && (_xmlCharType.IsAttributeValueChar((char)(ch = *pSrc)) && ch <= 0x7F)) <# } else { #> while (pDst < pDstEnd && _xmlCharType.IsAttributeValueChar((char)(ch = *pSrc))) -<# } -#> { +<# } #> + { *pDst = (<#= BufferType #>)ch; pDst++; pSrc++; @@ -1178,12 +1190,13 @@ if (WriterType == RawTextWriterType.Utf8) { #> { pDstEnd = pDstBegin + _bufLen; } + <# if (WriterType == RawTextWriterType.Utf8) { #> while (pDst < pDstEnd && ((ch = *pSrc) <= 0x7F)) <# } else { #> while (pDst < pDstEnd && ((ch = *pSrc) < XmlCharType.SurHighStart)) -<# } -#> { +<# }#> + { pSrc++; *pDst = (<#= BufferType #>)ch; pDst++; @@ -1227,12 +1240,13 @@ if (WriterType == RawTextWriterType.Utf8) { #> { pDstEnd = pDstBegin + _bufLen; } + <# if (WriterType == RawTextWriterType.Utf8) { #> while (pDst < pDstEnd && (_xmlCharType.IsTextChar((char)(ch = *pSrc)) && ch <= 0x7F)) <# } else { #> while (pDst < pDstEnd && _xmlCharType.IsTextChar((char)(ch = *pSrc))) -<# } -#> { +<# } #> + { *pDst = (<#= BufferType #>)ch; pDst++; pSrc++; @@ -1332,12 +1346,13 @@ if (WriterType == RawTextWriterType.Utf8) { #> { pDstEnd = pDstBegin + _bufLen; } + <# if (WriterType == RawTextWriterType.Utf8) { #> while (pDst < pDstEnd && (_xmlCharType.IsTextChar((char)(ch = *pSrc)) && ch != stopChar && ch <= 0x7F)) <# } else { #> while (pDst < pDstEnd && (_xmlCharType.IsTextChar((char)(ch = *pSrc)) && ch != stopChar)) -<# } -#> { +<# } #> + { *pDst = (<#= BufferType #>)ch; pDst++; pSrc++; @@ -1468,12 +1483,13 @@ if (WriterType == RawTextWriterType.Utf8) { #> { pDstEnd = pDstBegin + _bufLen; } + <# if (WriterType == RawTextWriterType.Utf8) { #> while (pDst < pDstEnd && (_xmlCharType.IsAttributeValueChar((char)(ch = *pSrc)) && ch != ']' && ch <= 0x7F)) <# } else { #> while (pDst < pDstEnd && (_xmlCharType.IsAttributeValueChar((char)(ch = *pSrc)) && ch != ']')) -<# } -#> { +<# } #> + { *pDst = (<#= BufferType #>)ch; pDst++; pSrc++; @@ -1566,6 +1582,7 @@ if (WriterType == RawTextWriterType.Utf8) { #> _bufPos = (int)(pDst - pDstBegin); } } + <# if (WriterType == RawTextWriterType.Utf8) { #> // Returns true if UTF8 encoded byte is first of four bytes that encode a surrogate pair. // To do this, detect the bit pattern 11110xxx. @@ -1573,6 +1590,7 @@ if (WriterType == RawTextWriterType.Utf8) { #> { return (b & 0xF8) == 0xF0; } + <# } #> private static unsafe <#= BufferType #>* EncodeSurrogate(char* pSrc, char* pSrcEnd, <#= BufferType #>* pDst) { @@ -1586,8 +1604,8 @@ if (WriterType == RawTextWriterType.Utf8) { #> int lowChar = pSrc[1]; if (lowChar >= XmlCharType.SurLowStart && (LocalAppContextSwitches.DontThrowOnInvalidSurrogatePairs || lowChar <= XmlCharType.SurLowEnd)) - {<# -if (WriterType == RawTextWriterType.Utf8) { #> + { +<# if (WriterType == RawTextWriterType.Utf8) { #> // Calculate Unicode scalar value for easier manipulations (see section 3.7 in Unicode spec) // The scalar value repositions surrogate values to start at 0x10000. @@ -1603,6 +1621,7 @@ if (WriterType == RawTextWriterType.Utf8) { #> pDst[1] = (<#= BufferType #>)lowChar; pDst += 2; <# } #> + return pDst; } throw XmlConvert.CreateInvalidSurrogatePairException((char)lowChar, (char)ch); @@ -1629,8 +1648,8 @@ if (WriterType == RawTextWriterType.Utf8) { #> return CharEntity(pDst, (char)ch); } else - {<# -if (WriterType == RawTextWriterType.Utf8) { #> + { +<# if (WriterType == RawTextWriterType.Utf8) { #> if (ch < 0x80) { *pDst = (<#= BufferType #>)ch; @@ -1644,6 +1663,7 @@ if (WriterType == RawTextWriterType.Utf8) { #> *pDst = (<#= BufferType #>)ch; pDst++; <# } #> + return pDst; } } @@ -1655,8 +1675,8 @@ if (WriterType == RawTextWriterType.Utf8) { #> <#= EncodeChar(3, false) #> } -<# if (WriterType == RawTextWriterType.Utf8) { -#> internal static unsafe byte* EncodeMultibyteUTF8(int ch, byte* pDst) +<# if (WriterType == RawTextWriterType.Utf8) { #> + internal static unsafe byte* EncodeMultibyteUTF8(int ch, byte* pDst) { Debug.Assert(ch >= 0x80 && !XmlCharType.IsSurrogate(ch)); @@ -1704,8 +1724,9 @@ if (WriterType == RawTextWriterType.Utf8) { #> pSrc++; } } -<# } -if (WriterType == RawTextWriterType.Encoded) { #> + +<# } #> +<# if (WriterType == RawTextWriterType.Encoded) { #> protected void ChangeTextContentMark(bool value) { Debug.Assert(_inTextContent != value); @@ -1725,6 +1746,7 @@ if (WriterType == RawTextWriterType.Encoded) { #> Array.Copy(_textContentMarks, newTextContentMarks, _textContentMarks.Length); _textContentMarks = newTextContentMarks; } + <# } #> // Write NewLineChars to the specified buffer position and return an updated position. protected unsafe <#= BufferType #>* WriteNewLine(<#= BufferType #>* pDst) @@ -1943,12 +1965,13 @@ if (WriterType == RawTextWriterType.Encoded) { #> // // Constructors - //<# -if (WriterType == RawTextWriterType.Encoded) { #> + // +<# if (WriterType == RawTextWriterType.Encoded) { #> public <#= ClassNameIndent #>(TextWriter writer, XmlWriterSettings settings) : base(writer, settings) { Init(settings); } + <# } #> public <#= ClassNameIndent #>(Stream stream, XmlWriterSettings settings) : base(stream, settings) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlRawTextWriterGeneratorAsync.ttinclude b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlRawTextWriterGeneratorAsync.ttinclude index 39e38820540b8b..4c274dca6f35d0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlRawTextWriterGeneratorAsync.ttinclude +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlRawTextWriterGeneratorAsync.ttinclude @@ -5,6 +5,7 @@ // WARNING: This file is generated and should not be modified directly. // Instead, modify XmlRawTextWriterGeneratorAsync.ttinclude +#nullable disable using System; using System.IO; using System.Xml; @@ -590,22 +591,22 @@ namespace System.Xml public override async Task FlushAsync() { CheckAsyncCall(); - await FlushBufferAsync().ConfigureAwait(false);<# -if (WriterType == RawTextWriterType.Encoded) { #> - await FlushEncoderAsync().ConfigureAwait(false);<# -} #> + await FlushBufferAsync().ConfigureAwait(false); +<# if (WriterType == RawTextWriterType.Encoded) { #> + await FlushEncoderAsync().ConfigureAwait(false); +<# } #> if (_stream != null) { await _stream.FlushAsync().ConfigureAwait(false); } -<# if (WriterType == RawTextWriterType.Encoded) { -#> else if (_writer != null) +<# if (WriterType == RawTextWriterType.Encoded) { #> + else if (_writer != null) { await _writer.FlushAsync().ConfigureAwait(false); } -<# } -#> } +<# } #> + } // // Implementation methods @@ -618,14 +619,14 @@ if (WriterType == RawTextWriterType.Encoded) { #> // Output all characters (except for previous characters stored at beginning of buffer) if (!_writeToNull) { -<# if (WriterType == RawTextWriterType.Utf8) { -#> if (_bufPos - 1 > 0) +<# if (WriterType == RawTextWriterType.Utf8) { #> + if (_bufPos - 1 > 0) { Debug.Assert(_stream != null); await _stream.WriteAsync(_bufBytes.AsMemory(1, _bufPos - 1)).ConfigureAwait(false); - }<# -} else { -#> Debug.Assert(_stream != null || _writer != null); + } +<# } else { #> + Debug.Assert(_stream != null || _writer != null); if (_stream != null) { @@ -656,8 +657,8 @@ if (WriterType == RawTextWriterType.Encoded) { #> // Write text to TextWriter await _writer.WriteAsync(<#= BufferName #>.AsMemory(1, _bufPos - 1)).ConfigureAwait(false); } - }<# -} #> + } +<# } #> } } catch @@ -671,8 +672,8 @@ if (WriterType == RawTextWriterType.Encoded) { #> // Move last buffer character to the beginning of the buffer (so that previous character can always be determined) <#= BufferName #>[0] = <#= BufferName #>[_bufPos - 1]; -<# if (WriterType == RawTextWriterType.Utf8) { -#> if (IsSurrogateByte(_bufBytes[0])) +<# if (WriterType == RawTextWriterType.Utf8) { #> + if (IsSurrogateByte(_bufBytes[0])) { // Last character was the first byte in a surrogate encoding, so move last three // bytes of encoding to the beginning of the buffer. @@ -680,6 +681,7 @@ if (WriterType == RawTextWriterType.Encoded) { #> _bufBytes[2] = _bufBytes[_bufPos + 1]; _bufBytes[3] = _bufBytes[_bufPos + 2]; } + <# } #> // Reset buffer position _textPos = (_textPos == _bufPos) ? 1 : 0; @@ -690,6 +692,7 @@ if (WriterType == RawTextWriterType.Encoded) { #> // close an empty element or in CDATA section detection of double ]; _BUFFER[0] will always be 0 } } + <# if (WriterType == RawTextWriterType.Encoded) { #> private async Task EncodeCharsAsync(int startOffset, int endOffset, bool writeAllToStream) { @@ -737,6 +740,7 @@ if (WriterType == RawTextWriterType.Encoded) { #> return Task.CompletedTask; } + <# } #> // Serialize text that is part of an attribute value. The '&', '<', '>', and '"' characters // are entitized. @@ -756,12 +760,13 @@ if (WriterType == RawTextWriterType.Encoded) { #> { pDstEnd = pDstBegin + _bufLen; } + <# if (WriterType == RawTextWriterType.Utf8) { #> while (pDst < pDstEnd && (_xmlCharType.IsAttributeValueChar((char)(ch = *pSrc)) && ch <= 0x7F)) <# } else { #> while (pDst < pDstEnd && _xmlCharType.IsAttributeValueChar((char)(ch = *pSrc))) -<# } -#> { +<# } #> + { *pDst = (<#= BufferType #>)ch; pDst++; pSrc++; @@ -945,12 +950,13 @@ if (WriterType == RawTextWriterType.Encoded) { #> { pDstEnd = pDstBegin + _bufLen; } + <# if (WriterType == RawTextWriterType.Utf8) { #> while (pDst < pDstEnd && (_xmlCharType.IsAttributeValueChar((char)(ch = *pSrc)) && ch <= 0x7F)) <# } else { #> while (pDst < pDstEnd && _xmlCharType.IsAttributeValueChar((char)(ch = *pSrc))) -<# } -#> { +<# } #> + { *pDst = (<#= BufferType #>)ch; pDst++; pSrc++; @@ -1171,12 +1177,13 @@ if (WriterType == RawTextWriterType.Encoded) { #> { pDstEnd = pDstBegin + _bufLen; } + <# if (WriterType == RawTextWriterType.Utf8) { #> while (pDst < pDstEnd && ((ch = *pSrc) <= 0x7F)) <# } else { #> while (pDst < pDstEnd && ((ch = *pSrc) < XmlCharType.SurHighStart)) -<# } -#> { +<# } #> + { pSrc++; *pDst = (<#= BufferType #>)ch; pDst++; @@ -1331,12 +1338,13 @@ if (WriterType == RawTextWriterType.Encoded) { #> { pDstEnd = pDstBegin + _bufLen; } + <# if (WriterType == RawTextWriterType.Utf8) { #> while (pDst < pDstEnd && (_xmlCharType.IsTextChar((char)(ch = *pSrc)) && ch <= 0x7F)) <# } else { #> while (pDst < pDstEnd && _xmlCharType.IsTextChar((char)(ch = *pSrc))) -<# } -#> { +<# } #> + { *pDst = (<#= BufferType #>)ch; pDst++; pSrc++; @@ -1518,12 +1526,13 @@ if (WriterType == RawTextWriterType.Encoded) { #> { pDstEnd = pDstBegin + _bufLen; } + <# if (WriterType == RawTextWriterType.Utf8) { #> while (pDst < pDstEnd && (_xmlCharType.IsTextChar((char)(ch = *pSrc)) && ch != stopChar && ch <= 0x7F)) <# } else { #> while (pDst < pDstEnd && (_xmlCharType.IsTextChar((char)(ch = *pSrc)) && ch != stopChar)) -<# } -#> { +<# } #> + { *pDst = (<#= BufferType #>)ch; pDst++; pSrc++; @@ -1693,12 +1702,13 @@ if (WriterType == RawTextWriterType.Encoded) { #> { pDstEnd = pDstBegin + _bufLen; } + <# if (WriterType == RawTextWriterType.Utf8) { #> while (pDst < pDstEnd && (_xmlCharType.IsAttributeValueChar((char)(ch = *pSrc)) && ch != ']' && ch <= 0x7F)) <# } else { #> while (pDst < pDstEnd && (_xmlCharType.IsAttributeValueChar((char)(ch = *pSrc)) && ch != ']')) -<# } -#> { +<# } #> + { *pDst = (<#= BufferType #>)ch; pDst++; pSrc++; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlRawWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlRawWriter.cs index ab14fcbd05f945..f3c2f1813257a5 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlRawWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlRawWriter.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.IO; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlRawWriterAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlRawWriterAsync.cs index fe8091cc64eb84..5cd1605a25dd71 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlRawWriterAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlRawWriterAsync.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.IO; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlReader.cs index 8c8e8a039bb5fe..310d9de0e64ace 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlReader.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections; using System.Diagnostics; using System.Globalization; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlReaderAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlReaderAsync.cs index e1f7f65b33ab08..0a1868f63cc58a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlReaderAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlReaderAsync.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.IO; using System.Text; using System.Security; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlReaderSettings.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlReaderSettings.cs index 843be88627773e..b0a11c49476723 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlReaderSettings.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlReaderSettings.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.IO; using System.Diagnostics; using System.Globalization; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlSpace.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlSpace.cs index 2ea0a32cc82ec1..9e9bce5efb7d7f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlSpace.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlSpace.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml { // An enumeration for the xml:space scope used in XmlReader and XmlWriter. diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlSubtreeReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlSubtreeReader.cs index 97b9bbb69efd27..3325ddc91ba701 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlSubtreeReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlSubtreeReader.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Xml; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlSubtreeReaderAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlSubtreeReaderAsync.cs index b79b54ef68096e..c10ddc917e61da 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlSubtreeReaderAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlSubtreeReaderAsync.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Xml; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextEncoder.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextEncoder.cs index e0b1b5cf2844e7..a613b1ca9002a6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextEncoder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextEncoder.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.IO; using System.Text; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReader.cs index 48598298580f09..38e8705ba2bd9b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReader.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.IO; using System.Text; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.Unix.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.Unix.cs index bb66e409946516..74836c79217fcd 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.Unix.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.Unix.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml { internal partial class XmlTextReaderImpl diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.cs index 32c82f72dc7e57..7927d28da61745 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImpl.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.IO; using System.Text; using System.Xml.Schema; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImplAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImplAsync.cs index ad012c1c4418b8..d4ef7509a8f7d3 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImplAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImplAsync.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.IO; using System.Text; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImplHelpers.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImplHelpers.cs index 635ec418fc3b71..b44ef135934191 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImplHelpers.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImplHelpers.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.IO; using System.Text; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImplHelpersAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImplHelpersAsync.cs index a9a0b3aaf39b7f..8662b036182a99 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImplHelpersAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextReaderImplHelpersAsync.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.IO; using System.Text; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextWriter.cs index a50f7dafc3dd3b..2438b5910dea03 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlTextWriter.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections; using System.Collections.Generic; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlUtf8RawTextWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlUtf8RawTextWriter.cs index e536c26ffade77..53133d7d857f50 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlUtf8RawTextWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlUtf8RawTextWriter.cs @@ -4,6 +4,7 @@ // WARNING: This file is generated and should not be modified directly. // Instead, modify XmlRawTextWriterGenerator.ttinclude +#nullable disable using System; using System.IO; using System.Xml; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlUtf8RawTextWriterAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlUtf8RawTextWriterAsync.cs index cbc86eae932e75..8d165f7bf22693 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlUtf8RawTextWriterAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlUtf8RawTextWriterAsync.cs @@ -4,6 +4,7 @@ // WARNING: This file is generated and should not be modified directly. // Instead, modify XmlRawTextWriterGeneratorAsync.ttinclude +#nullable disable using System; using System.IO; using System.Xml; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlValidatingReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlValidatingReader.cs index a3911c8e47bae8..1daa6a6c61c1d8 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlValidatingReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlValidatingReader.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.IO; using System.Text; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlValidatingReaderImpl.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlValidatingReaderImpl.cs index 239b854adba7f2..ab27891a9e313b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlValidatingReaderImpl.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlValidatingReaderImpl.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.IO; using System.Text; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlValidatingReaderImplAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlValidatingReaderImplAsync.cs index 3b917610d63e80..9064713526146b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlValidatingReaderImplAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlValidatingReaderImplAsync.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.IO; using System.Text; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriter.cs index 738ff3c7c3a3e6..ea82f5389e87a4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriter.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.IO; using System.Text; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterAsync.cs index 75248f3b473789..3657f951697d5e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterAsync.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Threading.Tasks; using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterHelpers.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterHelpers.cs index 09ab72796797ab..811170725111ff 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterHelpers.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterHelpers.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Text; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterHelpersAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterHelpersAsync.cs index 9b70772408c59c..36b337574fb38f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterHelpersAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterHelpersAsync.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Text; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWrappingReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWrappingReader.cs index 62636bdeef7bc4..4d9060a0b98092 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWrappingReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWrappingReader.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Xml; using System.Xml.Schema; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWrappingReaderAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWrappingReaderAsync.cs index c98404e2e1e457..e2e82670417745 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWrappingReaderAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWrappingReaderAsync.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Xml; using System.Xml.Schema; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWrappingWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWrappingWriter.cs index 3f334dcfdae0bd..60bdc9b446a695 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWrappingWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWrappingWriter.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Xml.Schema; using System.Collections; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWrappingWriterAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWrappingWriterAsync.cs index 46c2d673390d7b..e7270102a55882 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWrappingWriterAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWrappingWriterAsync.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.IO; using System.Xml.Schema; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriter.cs index 90c848747ad40b..6542efb13cba23 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriter.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.IO; using System.Text; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriterAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriterAsync.cs index 703d0e101a680b..2a8b3347f5f042 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriterAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriterAsync.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Threading.Tasks; using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriterSettings.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriterSettings.cs index 5cde9f0b33230c..ec42b416dfbf42 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriterSettings.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlWriterSettings.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections.Generic; using System.Diagnostics; using System.IO; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdCachingReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdCachingReader.cs index 119604e0b84703..72a424a97023a4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdCachingReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdCachingReader.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.IO; using System.Text; using System.Xml.Schema; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdCachingReaderAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdCachingReaderAsync.cs index 9abcb8104bd4cd..50123abbbf0f6f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdCachingReaderAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdCachingReaderAsync.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.IO; using System.Text; using System.Xml.Schema; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdValidatingReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdValidatingReader.cs index 09f0615fdfadcf..10e2003ab8bc10 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdValidatingReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdValidatingReader.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.IO; using System.Text; using System.Xml.Schema; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdValidatingReaderAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdValidatingReaderAsync.cs index 652fdf73cbceb1..24466213621757 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdValidatingReaderAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Core/XsdValidatingReaderAsync.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.IO; using System.Text; using System.Xml.Schema; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/DiagnosticsSwitches.cs b/src/libraries/System.Private.Xml/src/System/Xml/DiagnosticsSwitches.cs index 7a4a89c72f82ff..31a1264a345dae 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/DiagnosticsSwitches.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/DiagnosticsSwitches.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml { using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentSchemaValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentSchemaValidator.cs index a7c1c2d3b462f7..68085baec44656 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentSchemaValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentSchemaValidator.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Text; using System.Collections; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentXPathNavigator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentXPathNavigator.cs index c9c16dda81cd7c..166c50fa0f7934 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentXPathNavigator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentXPathNavigator.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections; using System.Collections.Generic; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentXmlWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentXmlWriter.cs index 5019c9bdf9e93e..3bcd7a3e0069b5 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentXmlWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/DocumentXmlWriter.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections; using System.Collections.Generic; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/DomNameTable.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/DomNameTable.cs index 6e187954537731..748f0c3d0b2788 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/DomNameTable.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/DomNameTable.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Diagnostics; using System.Xml.Schema; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XPathNodeList.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XPathNodeList.cs index 4a0ffa3f53c581..11c01d42464f16 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XPathNodeList.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XPathNodeList.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml { using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlAttribute.cs index 24e11bda6ed953..b29fea07407c14 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlAttribute.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Xml.Schema; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlAttributeCollection.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlAttributeCollection.cs index b2fd07dfb225b2..fa5ab070b21025 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlAttributeCollection.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlAttributeCollection.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlCDataSection.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlCDataSection.cs index 86f65d649bc928..41c1e6d29f4aed 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlCDataSection.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlCDataSection.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlCharacterData.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlCharacterData.cs index f5d7f610c5d386..7cf6740bf4eb52 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlCharacterData.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlCharacterData.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Text; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlChildEnumerator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlChildEnumerator.cs index 463b96689ca321..fc211c121b1614 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlChildEnumerator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlChildEnumerator.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections; namespace System.Xml diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlChildNodes.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlChildNodes.cs index 865f5b13b42075..d696646e9540e8 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlChildNodes.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlChildNodes.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections; namespace System.Xml diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlComment.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlComment.cs index d9ea593dc87b57..ae34a6e9fc3125 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlComment.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlComment.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDeclaration.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDeclaration.cs index 4544ca733cb718..dc21a3fd364b4c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDeclaration.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDeclaration.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocument.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocument.cs index a254bee81f1da3..34b22cce873fed 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocument.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocument.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections; using System.Collections.Generic; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocumentFragment.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocumentFragment.cs index ae0345450628dd..e0a26aa7d1418a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocumentFragment.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocumentFragment.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocumentType.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocumentType.cs index ab166f91a00e70..4d468eb53ba0fd 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocumentType.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDocumentType.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics; using System.Xml.Schema; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDomTextWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDomTextWriter.cs index 9697b4945b30d4..daa41566956739 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDomTextWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlDomTextWriter.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.IO; using System.Text; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlElement.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlElement.cs index 60016007054002..b103dcf44e3b54 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlElement.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlElement.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Xml.Schema; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlElementList.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlElementList.cs index 02211d6d21aa39..6401227842be55 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlElementList.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlElementList.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlEntity.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlEntity.cs index 636bae90881d31..88a405193b0226 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlEntity.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlEntity.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml { // Represents a parsed or unparsed entity in the XML document. diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlEntityReference.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlEntityReference.cs index 59d7c595e88695..150e85f165903f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlEntityReference.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlEntityReference.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics; namespace System.Xml diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlEventChangedAction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlEventChangedAction.cs index 59c2540fce2afc..1cf0a0c7fe00ff 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlEventChangedAction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlEventChangedAction.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml { // Specifies the type of node change diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlImplementation.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlImplementation.cs index 5dfbecc1f156e8..395c4ef29bb879 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlImplementation.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlImplementation.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml { // Provides methods for performing operations that are independent of any diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlLinkedNode.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlLinkedNode.cs index 41ae4635e1d05f..41a7e41401a544 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlLinkedNode.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlLinkedNode.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml { // Gets the node immediately preceding or following this node. diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlLoader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlLoader.cs index 05e28484d44902..75145a14e671d8 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlLoader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlLoader.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.IO; using System.Diagnostics; using System.Globalization; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlName.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlName.cs index 504245a91df73c..0cd270a420d8d2 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlName.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlName.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml { using System.Text; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNamedNodeMap.SmallXmlNodeList.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNamedNodeMap.SmallXmlNodeList.cs index a57403419940a1..cb217eb5b6c22b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNamedNodeMap.SmallXmlNodeList.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNamedNodeMap.SmallXmlNodeList.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections; using System.Collections.Generic; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNamedNodemap.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNamedNodemap.cs index 54b0c64ce4a348..bfaf118ea670b4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNamedNodemap.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNamedNodemap.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections; namespace System.Xml diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNode.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNode.cs index c31e084a6e2e08..8bd2cbe1855ad0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNode.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNode.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.IO; using System.Collections; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeChangedEventArgs.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeChangedEventArgs.cs index d89ed2ffb1e40a..09a6964a5ff423 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeChangedEventArgs.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeChangedEventArgs.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml { public class XmlNodeChangedEventArgs : EventArgs diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeChangedEventHandler.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeChangedEventHandler.cs index d106ceacf243ae..b63ac819cf4f02 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeChangedEventHandler.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeChangedEventHandler.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml { public delegate void XmlNodeChangedEventHandler(object sender, XmlNodeChangedEventArgs e); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeList.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeList.cs index 0565f5203a9279..96cb9096da94ad 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeList.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeList.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections; namespace System.Xml diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeReader.cs index b3a255cd467985..705ad125aafb22 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNodeReader.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNotation.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNotation.cs index 79ed84c14d35c5..9519c9421dcb55 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNotation.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlNotation.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlProcessingInstruction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlProcessingInstruction.cs index 89e36be95503a8..193454132445a7 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlProcessingInstruction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlProcessingInstruction.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlSignificantWhiteSpace.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlSignificantWhiteSpace.cs index dd9995d57f31cd..fb58b8f0537617 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlSignificantWhiteSpace.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlSignificantWhiteSpace.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlText.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlText.cs index db4533514d0a7c..788c2e2e1ea147 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlText.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlText.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlUnspecifiedAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlUnspecifiedAttribute.cs index 205d1d8a427175..a98cd608e0d134 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlUnspecifiedAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlUnspecifiedAttribute.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml { internal class XmlUnspecifiedAttribute : XmlAttribute diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlWhitespace.cs b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlWhitespace.cs index 7f9509cd3d5665..5113a488563f82 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlWhitespace.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Dom/XmlWhitespace.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/EmptyEnumerator.cs b/src/libraries/System.Private.Xml/src/System/Xml/EmptyEnumerator.cs index adcaef0e5b7750..a74974840d9fc0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/EmptyEnumerator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/EmptyEnumerator.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Extensions/ExtensionMethods.cs b/src/libraries/System.Private.Xml/src/System/Xml/Extensions/ExtensionMethods.cs index d216ac13b91da9..d91034169fea66 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Extensions/ExtensionMethods.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Extensions/ExtensionMethods.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Reflection; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/HWStack.cs b/src/libraries/System.Private.Xml/src/System/Xml/HWStack.cs index b9cb6fc25340ed..7ba3e31f4d5145 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/HWStack.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/HWStack.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; namespace System.Xml diff --git a/src/libraries/System.Private.Xml/src/System/Xml/IApplicationResourceStreamResolver.cs b/src/libraries/System.Private.Xml/src/System/Xml/IApplicationResourceStreamResolver.cs index 5469cbcf40b02c..9cf3e9114a2812 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/IApplicationResourceStreamResolver.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/IApplicationResourceStreamResolver.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.IO; using System.ComponentModel; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/IHasXmlNode.cs b/src/libraries/System.Private.Xml/src/System/Xml/IHasXmlNode.cs index b5f449593ec8f9..53e587c10c88e5 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/IHasXmlNode.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/IHasXmlNode.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml { public interface IHasXmlNode diff --git a/src/libraries/System.Private.Xml/src/System/Xml/IXmlLineInfo.cs b/src/libraries/System.Private.Xml/src/System/Xml/IXmlLineInfo.cs index e2345eb7bbd1ab..87246bb3258e6e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/IXmlLineInfo.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/IXmlLineInfo.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml { public interface IXmlLineInfo diff --git a/src/libraries/System.Private.Xml/src/System/Xml/IXmlNamespaceResolver.cs b/src/libraries/System.Private.Xml/src/System/Xml/IXmlNamespaceResolver.cs index 30a394f214c716..960b6a02047f3b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/IXmlNamespaceResolver.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/IXmlNamespaceResolver.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections; using System.Collections.Generic; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/LineInfo.cs b/src/libraries/System.Private.Xml/src/System/Xml/LineInfo.cs index c8cc3218bec923..09018fc7301978 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/LineInfo.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/LineInfo.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml { internal struct LineInfo diff --git a/src/libraries/System.Private.Xml/src/System/Xml/MTNameTable.cs b/src/libraries/System.Private.Xml/src/System/Xml/MTNameTable.cs index 84540652aff8ed..b10c97ca25fceb 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/MTNameTable.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/MTNameTable.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable #if MTNAMETABLE using System; using System.IO; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/NameTable.cs b/src/libraries/System.Private.Xml/src/System/Xml/NameTable.cs index 84773cee3bcd22..14575914d1f20f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/NameTable.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/NameTable.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Runtime.InteropServices; namespace System.Xml diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Ref.cs b/src/libraries/System.Private.Xml/src/System/Xml/Ref.cs index 926704d32b6067..d5064eaab20bec 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Ref.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Ref.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics; namespace System.Xml diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Resolvers/XmlKnownDtds.cs b/src/libraries/System.Private.Xml/src/System/Xml/Resolvers/XmlKnownDtds.cs index 60ff023c6790fe..4023e971574751 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Resolvers/XmlKnownDtds.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Resolvers/XmlKnownDtds.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Resolvers { // diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Resolvers/XmlPreloadedResolver.cs b/src/libraries/System.Private.Xml/src/System/Xml/Resolvers/XmlPreloadedResolver.cs index e09c29c3b236a3..de8e7d4a1d425b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Resolvers/XmlPreloadedResolver.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Resolvers/XmlPreloadedResolver.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.IO; using System.Xml; using System.Net; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Resolvers/XmlPreloadedResolverAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Resolvers/XmlPreloadedResolverAsync.cs index 244d5873363a28..97fc6c3c2ef9a4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Resolvers/XmlPreloadedResolverAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Resolvers/XmlPreloadedResolverAsync.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.IO; using System.Xml; using System.Threading.Tasks; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Asttree.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Asttree.cs index 7fefb7ac0606f4..277e7045124ad4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Asttree.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Asttree.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/AutoValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/AutoValidator.cs index 8004a18fcbb08e..eb87b34495f882 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/AutoValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/AutoValidator.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/BaseProcessor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/BaseProcessor.cs index 13d9e729c07e59..8f27d8d525a69a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/BaseProcessor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/BaseProcessor.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Collections; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/BaseValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/BaseValidator.cs index 17a51af17bbdc5..e70092bf7d2bed 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/BaseValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/BaseValidator.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.IO; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/BitSet.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/BitSet.cs index 96feed5b4f3085..d389ff72a5bc58 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/BitSet.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/BitSet.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Text; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Chameleonkey.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Chameleonkey.cs index 5d26910e7daf75..207a67d9f42802 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Chameleonkey.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Chameleonkey.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Collections; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/CompiledidEntityConstraint.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/CompiledidEntityConstraint.cs index e9fea6800fb464..7370dd125e2a3a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/CompiledidEntityConstraint.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/CompiledidEntityConstraint.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Text; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/ConstraintStruct.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/ConstraintStruct.cs index dcb1e962cf52b8..0ddc7dba2bfba8 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/ConstraintStruct.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/ConstraintStruct.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/ContentValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/ContentValidator.cs index 75afce31d4a88a..e2ce468c6cfe95 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/ContentValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/ContentValidator.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections; using System.Collections.Generic; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/DataTypeImplementation.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/DataTypeImplementation.cs index f757e3d687fc14..29310bc5b62821 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/DataTypeImplementation.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/DataTypeImplementation.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdParser.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdParser.cs index ba8515296c36fd..782e5021b279e1 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdParser.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdParser.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.IO; using System.Text; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdParserAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdParserAsync.cs index 266df4e5667d2b..f9b1eeb359131c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdParserAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdParserAsync.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.IO; using System.Text; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdValidator.cs index a385ee2cb13238..720a7ca83eeb1e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/DtdValidator.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/FacetChecker.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/FacetChecker.cs index d90bd76b359a23..5f53c75bff95d0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/FacetChecker.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/FacetChecker.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/IXmlSchemaInfo.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/IXmlSchemaInfo.cs index 076ebc9733c988..6f4cab48076119 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/IXmlSchemaInfo.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/IXmlSchemaInfo.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Xml; using System.Collections; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Inference/Infer.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Inference/Infer.cs index e31f2557609ce3..ad7d1cc67df350 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Inference/Infer.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Inference/Infer.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.IO; using System.Xml; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Inference/XmlSchemaInferenceException.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Inference/XmlSchemaInferenceException.cs index 27c09dd32d0cec..e9ba54d399b3ac 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Inference/XmlSchemaInferenceException.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Inference/XmlSchemaInferenceException.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.IO; using System.Resources; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/NamespaceList.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/NamespaceList.cs index 5f583979d8f736..2114b9e40248ec 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/NamespaceList.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/NamespaceList.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Collections; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Parser.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Parser.cs index 967afd56e2c4d1..0a43ac6581b6bf 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Parser.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Parser.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/ParserAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/ParserAsync.cs index fc1144c64ecdb5..be4c75527c211b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/ParserAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/ParserAsync.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Preprocessor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Preprocessor.cs index f0294f909dc82d..550495e6aadea7 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/Preprocessor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/Preprocessor.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Collections; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaAttDef.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaAttDef.cs index b469a12a3ca17b..df43302695f781 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaAttDef.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaAttDef.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaBuilder.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaBuilder.cs index b2b846dd99c8cd..7bfdca2a8d9f41 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaBuilder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaBuilder.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { internal abstract class SchemaBuilder diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionCompiler.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionCompiler.cs index 6db2721a3f0a58..26f8fcb7688464 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionCompiler.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionCompiler.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections; using System.Collections.Generic; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionpreProcessor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionpreProcessor.cs index e9b1a0dc4d5774..81a3e9f87432b2 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionpreProcessor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaCollectionpreProcessor.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Collections; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaDeclBase.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaDeclBase.cs index 89aee3e3e8b348..bf96ba0a3c779c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaDeclBase.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaDeclBase.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Collections.Generic; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaElementDecl.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaElementDecl.cs index e749d91729e7ee..b07b2fe2ae245f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaElementDecl.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaElementDecl.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaEntity.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaEntity.cs index 2ad9bb2281edb0..a3810d9189ee36 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaEntity.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaEntity.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaInfo.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaInfo.cs index 0a220ff6b88574..afd5c7840d4eda 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaInfo.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaInfo.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Xml; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaNames.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaNames.cs index 932365fe8fe486..3093c55f645427 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaNames.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaNames.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Collections; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaNamespacemanager.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaNamespacemanager.cs index 2721d21c35d120..9c3b9055f30270 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaNamespacemanager.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaNamespacemanager.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaNotation.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaNotation.cs index acaeeae2ee2f47..bb114f3019220c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaNotation.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaNotation.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaSetCompiler.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaSetCompiler.cs index a95f98b0011dd3..98b63e36e8748e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaSetCompiler.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaSetCompiler.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections; using System.Collections.Generic; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaType.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaType.cs index 84a55a6e57935c..2bd0d132fc664f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaType.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaType.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { internal enum SchemaType diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/ValidationEventArgs.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/ValidationEventArgs.cs index 1f93fff5088ae4..5eb7352ab8678c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/ValidationEventArgs.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/ValidationEventArgs.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { /// diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/ValidationEventHandler.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/ValidationEventHandler.cs index 216a4c5c870536..1e0aca373a7eab 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/ValidationEventHandler.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/ValidationEventHandler.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { public delegate void ValidationEventHandler(object? sender, ValidationEventArgs e); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/ValidationState.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/ValidationState.cs index 181dff8c668d37..c7860253a5858f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/ValidationState.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/ValidationState.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XdrBuilder.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XdrBuilder.cs index a02ed3580b409f..35d41104358c05 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XdrBuilder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XdrBuilder.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.IO; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XdrValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XdrValidator.cs index a5df534b04bc0c..bbbffb483e92cd 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XdrValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XdrValidator.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.IO; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlAtomicValue.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlAtomicValue.cs index 6985881f910d02..0ba7f5af19a217 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlAtomicValue.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlAtomicValue.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections; using System.Collections.Generic; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchema.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchema.cs index 5cb23353c26be7..309fb8ffa402ef 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchema.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchema.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.IO; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAll.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAll.cs index 061fe26c32835d..806764660104bb 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAll.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAll.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Collections; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAnnotated.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAnnotated.cs index f85effb97e4184..54e9676daf7dd7 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAnnotated.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAnnotated.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Collections; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAnnotation.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAnnotation.cs index 0a89c9e67b3bea..d15371f18d4a0d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAnnotation.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAnnotation.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Collections; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAny.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAny.cs index 1996c0720fa9fb..dee86d0ee407e5 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAny.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAny.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.ComponentModel; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAnyAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAnyAttribute.cs index 070351ca940f92..48775d8ca67521 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAnyAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAnyAttribute.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Collections; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAppInfo.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAppInfo.cs index 7e6da556b23162..b886ee7fd253bf 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAppInfo.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAppInfo.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Collections; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAttribute.cs index 0f8fe5f74fd328..d1cc422f95b8fc 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAttribute.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAttributeGroup.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAttributeGroup.cs index 9cbe29e349e868..36c56f39f488a9 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAttributeGroup.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAttributeGroup.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Collections; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAttributeGroupref.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAttributeGroupref.cs index 98a4a883e6bc82..873bcd693204c7 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAttributeGroupref.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaAttributeGroupref.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Collections; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaChoice.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaChoice.cs index b9d5a8b1845ae8..b762baededeb4f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaChoice.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaChoice.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Collections; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaCollection.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaCollection.cs index 707de039376fa5..fd646d96c64ace 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaCollection.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaCollection.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaCompilationSettings.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaCompilationSettings.cs index 6f7aebc0f9d498..f22e0a47438747 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaCompilationSettings.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaCompilationSettings.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { public sealed class XmlSchemaCompilationSettings diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaComplexContent.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaComplexContent.cs index 62af58c4fb0bff..bc9f4a62ecf123 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaComplexContent.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaComplexContent.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Xml.Serialization; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaComplexContentExtension.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaComplexContentExtension.cs index 3e48e3c31e5e0a..efbbc73fe88532 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaComplexContentExtension.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaComplexContentExtension.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Collections; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaComplexContentRestriction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaComplexContentRestriction.cs index 0189a8ed9bac84..0b382791dcf65b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaComplexContentRestriction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaComplexContentRestriction.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Collections; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaComplexType.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaComplexType.cs index 8681f5390b5240..0b82c430a82b32 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaComplexType.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaComplexType.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Xml.Serialization; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaContent.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaContent.cs index 426c639c31f726..2e264d968b56d4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaContent.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaContent.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Collections; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaContentModel.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaContentModel.cs index d0cd16dc26af70..ed13b55e18d9ba 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaContentModel.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaContentModel.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Xml.Serialization; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaContentProcessing.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaContentProcessing.cs index 083b9dc2bae54c..057952db1a6cd2 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaContentProcessing.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaContentProcessing.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Xml.Serialization; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaContentType.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaContentType.cs index 7df3f9b50c889d..17e79cbce742ab 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaContentType.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaContentType.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { public enum XmlSchemaContentType diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaDataType.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaDataType.cs index 277ed588e59c06..31fb39ed805e24 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaDataType.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaDataType.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections; using System.Diagnostics; using System.ComponentModel; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaDerivationMethod.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaDerivationMethod.cs index f0fcb63bc34cc4..a30441ee84c290 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaDerivationMethod.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaDerivationMethod.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Collections; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaDocumentation.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaDocumentation.cs index ff8e25556de55c..c032d78eaf8d54 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaDocumentation.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaDocumentation.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Collections; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaElement.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaElement.cs index 58c68160b5584e..7e88413d4050ae 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaElement.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaElement.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.ComponentModel; using System.Xml.Serialization; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaException.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaException.cs index 22eabefe6fe954..eb6e6dd8c555cf 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaException.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaException.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.IO; using System.Text; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaExternal.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaExternal.cs index e17824fc47bf90..bfeca6efdc250a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaExternal.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaExternal.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Collections; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaFacet.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaFacet.cs index 520d23c937a124..b359ae5e484f02 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaFacet.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaFacet.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.ComponentModel; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaForm.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaForm.cs index 531b8729188699..13dcac06b0f34a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaForm.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaForm.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Xml.Serialization; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaGroup.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaGroup.cs index dcc63f266f6285..823b06342a90af 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaGroup.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaGroup.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Xml.Serialization; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaGroupBase.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaGroupBase.cs index 4d6cd344c664a5..9678c855aa58c1 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaGroupBase.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaGroupBase.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Xml.Serialization; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaGroupRef.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaGroupRef.cs index d85759e92acca8..b69998b260b455 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaGroupRef.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaGroupRef.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Xml.Serialization; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaIdEntityConstraint.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaIdEntityConstraint.cs index 48f95cae818509..9b29480ef8898f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaIdEntityConstraint.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaIdEntityConstraint.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Collections; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaImport.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaImport.cs index 0891fd6bb0e70c..d4d0821c785825 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaImport.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaImport.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Xml.Serialization; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaInclude.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaInclude.cs index 40621c79693a0b..3809e49b72cfff 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaInclude.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaInclude.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Xml.Serialization; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaInfo.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaInfo.cs index 5069a94ff1ef8b..b4f7290a57c8ae 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaInfo.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaInfo.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Xml; using System.Collections; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaNotation.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaNotation.cs index 5573b484e4ab13..6b48aa3f9df536 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaNotation.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaNotation.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Xml.Serialization; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaObject.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaObject.cs index 550ae80d501ad5..74c1cbb611b04d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaObject.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaObject.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaObjectCollection.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaObjectCollection.cs index f953ff9536f137..3db82f2e5c6bbf 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaObjectCollection.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaObjectCollection.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Collections; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaObjectTable.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaObjectTable.cs index 9d81500fb48c4c..21abf9461d549f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaObjectTable.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaObjectTable.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Collections; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaParticle.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaParticle.cs index cb2cf276234838..926b9ee6c92b21 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaParticle.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaParticle.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Xml.Serialization; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaRedefine.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaRedefine.cs index 15de67a0248c07..bb1196f9a06247 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaRedefine.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaRedefine.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Xml.Serialization; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSequence.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSequence.cs index 0b49797930d297..9b989f79f29581 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSequence.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSequence.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Xml.Serialization; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSet.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSet.cs index b6e433a1c489ea..cdbe0178c0c32b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSet.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSet.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics; using System.Collections; using System.Threading; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleContent.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleContent.cs index 6418f6c91742ad..504b82af0bda00 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleContent.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleContent.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Xml.Serialization; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleContentExtension.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleContentExtension.cs index c574586d3f3373..01fb7ade1b21b5 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleContentExtension.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleContentExtension.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Xml.Serialization; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleContentRestriction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleContentRestriction.cs index bf9048c598f355..f4b5ba9dcf25de 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleContentRestriction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleContentRestriction.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Xml.Serialization; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleType.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleType.cs index abae95c709ae1c..62fe61a46dc9c6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleType.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleType.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Xml.Serialization; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleTypeContent.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleTypeContent.cs index 44eb1e43c378d8..6de1aa0fa8e7ab 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleTypeContent.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleTypeContent.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { public abstract class XmlSchemaSimpleTypeContent : XmlSchemaAnnotated diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleTypeList.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleTypeList.cs index a4a4a6438202b2..4ae0dbec2a694a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleTypeList.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleTypeList.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Xml.Serialization; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleTypeRestriction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleTypeRestriction.cs index 908e7c36cdca26..a00192dbb6d1f4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleTypeRestriction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleTypeRestriction.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Collections; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleTypeUnion.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleTypeUnion.cs index 0857ee17a2918a..72ac95ec782e19 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleTypeUnion.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSimpleTypeUnion.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Xml.Serialization; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSubstitutionGroup.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSubstitutionGroup.cs index 16e87a4a5e91d0..645d77e41cc2a9 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSubstitutionGroup.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaSubstitutionGroup.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Collections; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaType.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaType.cs index b3a10c4e1984b3..48a6c3129357dc 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaType.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaType.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaUse.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaUse.cs index ac5eb8b2097e80..94c9d97b66e523 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaUse.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaUse.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Xml.Serialization; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidationException.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidationException.cs index 993aa858936c9f..a3742ab827e123 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidationException.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidationException.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.IO; using System.Text; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidator.cs index 5b993c86b1e578..fc36e865a79cdc 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidator.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections; using System.Collections.Generic; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidity.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidity.cs index b27c7b657b541f..75acccf5bdd966 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidity.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaValidity.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { public enum XmlSchemaValidity diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSeverityType.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSeverityType.cs index a97967f3bb9e6e..6e2bf6369762fc 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSeverityType.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSeverityType.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { //UE Atention diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlTokenizedType.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlTokenizedType.cs index b4c304ada401c3..f438013043ae98 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlTokenizedType.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlTokenizedType.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml { // NOTE: Absolute numbering is utilized in DtdParser. -HelenaK diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlTypeCode.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlTypeCode.cs index b77c2d49b87b77..07d30ea73f74de 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlTypeCode.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlTypeCode.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { public enum XmlTypeCode diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlUntypedStringConverter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlUntypedStringConverter.cs index 8c086115dc120c..e8855cff7431f7 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlUntypedStringConverter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlUntypedStringConverter.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Xml; using System.Text; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlValueConverter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlValueConverter.cs index 930387e6e9f853..08c6d660d189e7 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlValueConverter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlValueConverter.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Xml; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdBuilder.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdBuilder.cs index 74449d98725f0c..fb362b61f800dd 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdBuilder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdBuilder.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.IO; using System.Collections; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdDateTime.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdDateTime.cs index 74ad3bb912cd42..717bc204e58278 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdDateTime.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdDateTime.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdDuration.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdDuration.cs index 6cbb8571924579..454d7f8eb8359b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdDuration.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdDuration.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdValidator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdValidator.cs index 2191857f29a245..ed95d6647417ab 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdValidator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdValidator.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Schema { using System.Collections; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeGenerationoptions.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeGenerationoptions.cs index 42fbe3a3442a83..6f7ad17f4e4a36 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeGenerationoptions.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeGenerationoptions.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeGenerator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeGenerator.cs index 22bbca0e50119a..2ae83d3c2022ce 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeGenerator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeGenerator.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections; using System.Collections.Generic; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeIdentifier.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeIdentifier.cs index 2393f70b554b34..0b4240a1a03e91 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeIdentifier.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeIdentifier.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Text; using System.Collections; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeIdentifiers.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeIdentifiers.cs index 66f28c88e857b3..ebbac5ed2e4e30 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeIdentifiers.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeIdentifiers.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Compilation.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Compilation.cs index 86d3ffaa6f81fb..622d0fd3331d85 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Compilation.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Compilation.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Reflection; using System.Reflection.Emit; using System.Collections; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Compiler.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Compiler.cs index 5de0d1bb434a58..bbf1968fc95308 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Compiler.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Compiler.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System.Reflection; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Configuration/DateTimeSerializationSection.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Configuration/DateTimeSerializationSection.cs index bad80f2ac8ae30..c841409eaea8c1 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Configuration/DateTimeSerializationSection.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Configuration/DateTimeSerializationSection.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization.Configuration { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Globals.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Globals.cs index 868c60cc311262..1a83cd547d992c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Globals.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Globals.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics.CodeAnalysis; using System.Security; using System.Reflection; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/IXmlSerializable.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/IXmlSerializable.cs index e2d444a36bf050..afa8dfe5eaf92d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/IXmlSerializable.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/IXmlSerializable.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System.Xml; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/IXmlTextParser.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/IXmlTextParser.cs index 685485f3da0dfa..4e1acb19e25816 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/IXmlTextParser.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/IXmlTextParser.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System.Xml; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ImportContext.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ImportContext.cs index 6af84291c6edf5..cba6418f6827f7 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ImportContext.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ImportContext.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Mappings.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Mappings.cs index 9a67c0df253350..c5069e4fabb868 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Mappings.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Mappings.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System.Reflection; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Models.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Models.cs index 9d0010e2baaa73..d8ecf30322ff50 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Models.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Models.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/NameTable.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/NameTable.cs index f7f43ad4683a5a..604e61c980e8a2 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/NameTable.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/NameTable.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System.Xml; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/PrimitiveXmlSerializers.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/PrimitiveXmlSerializers.cs index 4eb47af828865d..81fa7b25f0d109 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/PrimitiveXmlSerializers.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/PrimitiveXmlSerializers.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; namespace System.Xml.Serialization diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationReader.cs index e39e7bf796d6e6..3de884102feaef 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationReader.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs index 5258ec2c1cc615..7ad693fdae5760 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections; using System.Collections.Generic; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaImporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaImporter.cs index c3ef906d46f5fa..2df97cbc0e73a1 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaImporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaImporter.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaObjectWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaObjectWriter.cs index f4b469f61e4f99..64681460cbb1a0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaObjectWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaObjectWriter.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapAttributeAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapAttributeAttribute.cs index 5ba74b764905f9..d1922c1d6222ce 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapAttributeAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapAttributeAttribute.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapAttributeOverrides.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapAttributeOverrides.cs index f9fb5d7de763f4..172516362b11ea 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapAttributeOverrides.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapAttributeOverrides.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System.Reflection; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapAttributes.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapAttributes.cs index 0d57c9755fea88..8f7faee01d1c2a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapAttributes.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapAttributes.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapElementAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapElementAttribute.cs index 98975be0429eed..4fc30e76656672 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapElementAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapElementAttribute.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapEnumAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapEnumAttribute.cs index 23c86a4080df5a..018558456b1fce 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapEnumAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapEnumAttribute.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapIgnoreAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapIgnoreAttribute.cs index 2fdd91dc5b2533..23c6971bbdda1d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapIgnoreAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapIgnoreAttribute.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapIncludeAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapIncludeAttribute.cs index 1c41a6bf5b3c32..1b66ac7409e761 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapIncludeAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapIncludeAttribute.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapReflectionImporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapReflectionImporter.cs index bc1ef880ff13ef..2878eeb604c19a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapReflectionImporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapReflectionImporter.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System.Reflection; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapSchemamember.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapSchemamember.cs index afeb107a56ec92..4623bf56bf7dc1 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapSchemamember.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapSchemamember.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapTypeAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapTypeAttribute.cs index b816a34d4db3a0..778fb01ab2b899 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapTypeAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapTypeAttribute.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SourceInfo.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SourceInfo.cs index ff16ce43b56768..967218a452deb5 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SourceInfo.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SourceInfo.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/TypeCode.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/TypeCode.cs index e980e75935be73..ccdd17406242fe 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/TypeCode.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/TypeCode.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/TypeExtensions.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/TypeExtensions.cs index bde6ff093bd432..f84d014c93ae65 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/TypeExtensions.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/TypeExtensions.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Types.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Types.cs index 02739759f465d0..db191768f82bb2 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Types.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Types.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAnyAttributeAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAnyAttributeAttribute.cs index b57cbffc68df7a..a34d6ac0d3ab44 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAnyAttributeAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAnyAttributeAttribute.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Xml.Schema; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAnyElementAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAnyElementAttribute.cs index 8c146c15abd881..d58e05a7298b06 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAnyElementAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAnyElementAttribute.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Diagnostics.CodeAnalysis; using System.Xml.Schema; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAnyElementAttributes.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAnyElementAttributes.cs index ee3796482a3591..bd57b3492bce4f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAnyElementAttributes.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAnyElementAttributes.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlArrayAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlArrayAttribute.cs index dec726faaf3904..ebad8fd02d3466 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlArrayAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlArrayAttribute.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Diagnostics.CodeAnalysis; using System.Xml.Schema; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlArrayItemAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlArrayItemAttribute.cs index b3bd0d98551212..c6f836b736aa83 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlArrayItemAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlArrayItemAttribute.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Diagnostics.CodeAnalysis; using System.Xml.Schema; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlArrayItemAttributes.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlArrayItemAttributes.cs index dceec59f18997a..88ebed304c7e63 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlArrayItemAttributes.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlArrayItemAttributes.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributeAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributeAttribute.cs index a0b8eb7d9ad3ce..37db81c763a1d0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributeAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributeAttribute.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Diagnostics.CodeAnalysis; using System.Xml.Schema; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributeOverrides.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributeOverrides.cs index 115a07e0d2589b..56f0d8bb5e3667 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributeOverrides.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributeOverrides.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System.Reflection; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributes.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributes.cs index 6c1e487b28ba86..f8fbd5e4e246e0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributes.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributes.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlChoiceIdentifierAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlChoiceIdentifierAttribute.cs index 982badde112fad..e29a96cf8579f6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlChoiceIdentifierAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlChoiceIdentifierAttribute.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Xml.Schema; using System.Reflection; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlElementAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlElementAttribute.cs index a809fb7ea6ca83..a5bfbedaee8f82 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlElementAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlElementAttribute.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Diagnostics.CodeAnalysis; using System.Xml.Schema; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlElementAttributes.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlElementAttributes.cs index 92392568b2dee1..ff016f0a09d60c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlElementAttributes.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlElementAttributes.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlEnumAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlEnumAttribute.cs index 340c39353f9e2b..066a0a44f50433 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlEnumAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlEnumAttribute.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; namespace System.Xml.Serialization diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlIgnoreAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlIgnoreAttribute.cs index 6d1fd60586a3ea..690d02b5a2330c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlIgnoreAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlIgnoreAttribute.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; namespace System.Xml.Serialization diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlIncludeAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlIncludeAttribute.cs index 7993b4084ecfba..06d20274c2ee03 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlIncludeAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlIncludeAttribute.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; namespace System.Xml.Serialization diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlMapping.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlMapping.cs index 93d6a0c63a8863..2f28a383dd7c72 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlMapping.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlMapping.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.ComponentModel; using System.Globalization; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlMemberMapping.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlMemberMapping.cs index 6abcd9cc90d507..7445e73f71189f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlMemberMapping.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlMemberMapping.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Reflection; using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlMembersMapping.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlMembersMapping.cs index 21fbe9afa9dffa..c10126b35f6065 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlMembersMapping.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlMembersMapping.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Reflection; using System; using System.Text; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlNamespaceDeclarationsAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlNamespaceDeclarationsAttribute.cs index 8f0bf641bbd986..c4578a06ba4a76 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlNamespaceDeclarationsAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlNamespaceDeclarationsAttribute.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Xml.Schema; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs index 3fd048f33fab3f..30035fe8b4aa25 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System.Reflection; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionMember.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionMember.cs index e7f33264760745..d713fbd38e6afa 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionMember.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionMember.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Xml.Serialization; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlRootAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlRootAttribute.cs index 9caa2008b20d57..039d97f0594aa4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlRootAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlRootAttribute.cs @@ -5,7 +5,6 @@ // //------------------------------------------------------------------------------ -#nullable enable using System; using System.Diagnostics.CodeAnalysis; using System.Xml.Schema; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaExporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaExporter.cs index 20662550ed0082..839ddc19cd805a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaExporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaExporter.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaImporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaImporter.cs index a4b64f5bf587cc..c8bdea531056e5 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaImporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaImporter.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaProviderAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaProviderAttribute.cs index 36095d9a673300..2874c44b8dfa73 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaProviderAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaProviderAttribute.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemas.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemas.cs index e0e3f2cb5810a6..78ea35dc32cbbb 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemas.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemas.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System.Collections; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationEventSource.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationEventSource.cs index 3e8d6f20db9e5d..605cc23c4d1712 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationEventSource.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationEventSource.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections.Generic; using System.Linq; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationGeneratedCode.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationGeneratedCode.cs index 8cd499f58ddf77..48744786703479 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationGeneratedCode.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationGeneratedCode.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationILGen.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationILGen.cs index fe017660a9a700..933a04563bd955 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationILGen.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationILGen.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs index 828104e74a1048..0935a40eb48610 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs index 872dcbfc47570d..31c149ad8c5d37 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs index 50a1632df0678d..ba8ad5e5a6b748 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriterILGen.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriterILGen.cs index e907ffc6471e24..605656dfa7d1ee 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriterILGen.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriterILGen.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections; using System.Collections.Generic; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs index a017863bef8983..678cdc26c3444d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System.Reflection; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerAssemblyAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerAssemblyAttribute.cs index 77490dfff29484..c85a8e890c7a3f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerAssemblyAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerAssemblyAttribute.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerFactory.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerFactory.cs index 35cf451e09cae6..e2dba5894b618d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerFactory.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerFactory.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System.Reflection; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerNamespaces.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerNamespaces.cs index 567018494bc5da..864f3d80f6c237 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerNamespaces.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerNamespaces.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System.Reflection; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerVersionAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerVersionAttribute.cs index 5a7c6716930342..4a24276bc63dbd 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerVersionAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerVersionAttribute.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlTextAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlTextAttribute.cs index aad49a49b260e9..c76ce95e8346a4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlTextAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlTextAttribute.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Diagnostics.CodeAnalysis; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlTypeAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlTypeAttribute.cs index de408389ce4a8c..5843c35d2f8122 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlTypeAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlTypeAttribute.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Diagnostics.CodeAnalysis; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlTypeMapping.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlTypeMapping.cs index fbc74d40862979..87c003d729f320 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlTypeMapping.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlTypeMapping.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Reflection; using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Xmlcustomformatter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Xmlcustomformatter.cs index 719eab1c0df102..e60231d22144a4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Xmlcustomformatter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Xmlcustomformatter.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/_Events.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/_Events.cs index 2ec21b84552ebb..2a7cbbc3c2d28e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/_Events.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/_Events.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System.IO; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/indentedWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/indentedWriter.cs index c45f0b74e3d257..365707c2619c00 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/indentedWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/indentedWriter.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Serialization { using System.IO; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/ValidateNames.cs b/src/libraries/System.Private.Xml/src/System/Xml/ValidateNames.cs index d95186a185cca4..ef896bef9bd11e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/ValidateNames.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/ValidateNames.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Xml.XPath; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/IXPathNavigable.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/IXPathNavigable.cs index 30154d43cfde07..c751b02dd50232 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/IXPathNavigable.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/IXPathNavigable.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.XPath { public interface IXPathNavigable diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/AbsoluteQuery.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/AbsoluteQuery.cs index e50788851e5cd8..6e449d4671b78a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/AbsoluteQuery.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/AbsoluteQuery.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/AstNode.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/AstNode.cs index 0ffc5380a22e79..77990da06fed62 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/AstNode.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/AstNode.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Xml.XPath; namespace MS.Internal.Xml.XPath diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/AttributeQuery.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/AttributeQuery.cs index eea9f6fb04cb22..867083308b9679 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/AttributeQuery.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/AttributeQuery.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics; using System.Xml; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/Axis.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/Axis.cs index d29b580aab1482..36c0bcb421c6ef 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/Axis.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/Axis.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/BaseAxisQuery.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/BaseAxisQuery.cs index bdc4cc22459ce1..132d90242d04b1 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/BaseAxisQuery.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/BaseAxisQuery.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics; using System.Xml; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/BooleanExpr.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/BooleanExpr.cs index 2174615d51d7ff..4cf058b90289f6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/BooleanExpr.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/BooleanExpr.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics; using System.Xml; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/BooleanFunctions.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/BooleanFunctions.cs index 2fab357bfc26fc..2ae24d53792e8b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/BooleanFunctions.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/BooleanFunctions.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Diagnostics; using System.Xml; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/CacheAxisQuery.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/CacheAxisQuery.cs index a01d88dd7c3665..82bbf2c0c54d56 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/CacheAxisQuery.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/CacheAxisQuery.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections.Generic; using System.Diagnostics; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/CacheChildrenQuery.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/CacheChildrenQuery.cs index 6dcaae29d95ec1..c84daf9946c801 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/CacheChildrenQuery.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/CacheChildrenQuery.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics; using System.Xml; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/CacheOutputQuery.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/CacheOutputQuery.cs index c200c466015a2f..04a8b91066e71a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/CacheOutputQuery.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/CacheOutputQuery.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections.Generic; using System.Diagnostics; using System.Xml; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ChildrenQuery.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ChildrenQuery.cs index 3a9d201f083741..d3f59aa883475c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ChildrenQuery.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ChildrenQuery.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Xml.XPath; namespace MS.Internal.Xml.XPath diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ClonableStack.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ClonableStack.cs index 4637938a15322a..08af2101b2e043 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ClonableStack.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ClonableStack.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace MS.Internal.Xml.XPath { internal sealed class ClonableStack : System.Collections.Generic.List diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/CompiledXPathExpr.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/CompiledXPathExpr.cs index 736a8159f21940..fb5390ef2de4bf 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/CompiledXPathExpr.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/CompiledXPathExpr.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ContextQuery.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ContextQuery.cs index 1f463a451de245..2fd0cac5e2c015 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ContextQuery.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ContextQuery.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Xml.XPath; namespace MS.Internal.Xml.XPath diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/DescendantBaseQuery.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/DescendantBaseQuery.cs index 2c289612b82acb..451e9eabbf6b5e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/DescendantBaseQuery.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/DescendantBaseQuery.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Xml; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/DescendantQuery.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/DescendantQuery.cs index 413da810a407e2..3f2ee1b3fa78b8 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/DescendantQuery.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/DescendantQuery.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Xml.XPath; namespace MS.Internal.Xml.XPath diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/DescendantoverDescendantQuery.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/DescendantoverDescendantQuery.cs index 1b0d657a406fea..f0d58f673bc311 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/DescendantoverDescendantQuery.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/DescendantoverDescendantQuery.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/DocumentorderQuery.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/DocumentorderQuery.cs index f2f56f6a72e77a..72416ec7f63233 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/DocumentorderQuery.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/DocumentorderQuery.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Xml.XPath; namespace MS.Internal.Xml.XPath diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/EmptyQuery.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/EmptyQuery.cs index ebfd1a7229d1b9..c222d54f39de5d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/EmptyQuery.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/EmptyQuery.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Xml.XPath; namespace MS.Internal.Xml.XPath diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ExtensionQuery.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ExtensionQuery.cs index 4645ba2bc93b0a..b829ef3c9345b4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ExtensionQuery.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ExtensionQuery.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Xml; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/Filter.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/Filter.cs index e0840ef3499613..11ecec19c49c7e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/Filter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/Filter.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Xml.XPath; namespace MS.Internal.Xml.XPath diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/FilterQuery.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/FilterQuery.cs index 53eaf5a23a1045..ee3256af0ab273 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/FilterQuery.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/FilterQuery.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics; using System.Xml; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/FollSiblingQuery.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/FollSiblingQuery.cs index a579d60cc75e14..e66266c9a80010 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/FollSiblingQuery.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/FollSiblingQuery.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections.Generic; using System.Xml.XPath; using StackNav = MS.Internal.Xml.XPath.ClonableStack; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/FollowingQuery.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/FollowingQuery.cs index 48a998caa030c7..db94d2ff64674b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/FollowingQuery.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/FollowingQuery.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ForwardPositionQuery.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ForwardPositionQuery.cs index f70c9a50fbbf24..241911c977028f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ForwardPositionQuery.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ForwardPositionQuery.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/Function.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/Function.cs index c1c0e0d2d7154a..4b8157850ea2e4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/Function.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/Function.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections.Generic; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/FunctionQuery.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/FunctionQuery.cs index 405319df5b63be..e6269202f624da 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/FunctionQuery.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/FunctionQuery.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections.Generic; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/Group.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/Group.cs index de71354d8133ad..de0171981253f7 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/Group.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/Group.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Xml.XPath; namespace MS.Internal.Xml.XPath diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/GroupQuery.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/GroupQuery.cs index f5b43b98a88bc1..e2079494ca7d5d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/GroupQuery.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/GroupQuery.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Xml.XPath; namespace MS.Internal.Xml.XPath diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/IdQuery.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/IdQuery.cs index 1bf9010d8cab47..00056a740b2cdd 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/IdQuery.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/IdQuery.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics; using System.Xml; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/IteratorFilter.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/IteratorFilter.cs index adb9d0bb256a53..9123f14e327967 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/IteratorFilter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/IteratorFilter.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/LogicalExpr.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/LogicalExpr.cs index 53f556d5a95219..1e1b0d95984eb6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/LogicalExpr.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/LogicalExpr.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics; using System.Xml; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/MergeFilterQuery.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/MergeFilterQuery.cs index 81c661d1517844..a629749a202a62 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/MergeFilterQuery.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/MergeFilterQuery.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics; using System.Xml; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/NamespaceQuery.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/NamespaceQuery.cs index 0d44a9b25376de..bb27ccad1121aa 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/NamespaceQuery.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/NamespaceQuery.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/NodeFunctions.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/NodeFunctions.cs index 8cd1bd738019ea..07a96cf22dfbd3 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/NodeFunctions.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/NodeFunctions.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Xml; using System.Xml.XPath; using System.Xml.Xsl; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/NumberFunctions.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/NumberFunctions.cs index 3cf4ae14fe122e..ca970b84f8749c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/NumberFunctions.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/NumberFunctions.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Diagnostics; using System.Xml; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/NumericExpr.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/NumericExpr.cs index eeb5775e7e218f..854232dc96b80d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/NumericExpr.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/NumericExpr.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics; using System.Xml; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/Operand.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/Operand.cs index edde39245f64a6..ae309945f41588 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/Operand.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/Operand.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Xml.XPath; namespace MS.Internal.Xml.XPath diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/OperandQuery.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/OperandQuery.cs index ff8172d18a8fc8..851944910e9b26 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/OperandQuery.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/OperandQuery.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Globalization; using System.Xml; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/Operator.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/Operator.cs index 2a79a96f7ce17e..6dd69c8e611ca1 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/Operator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/Operator.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ParentQuery.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ParentQuery.cs index 7661973f0594e3..80fc288674cf02 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ParentQuery.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ParentQuery.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Xml.XPath; namespace MS.Internal.Xml.XPath diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/PreSiblingQuery.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/PreSiblingQuery.cs index 17762b4e66179c..6db2488019be59 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/PreSiblingQuery.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/PreSiblingQuery.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections.Generic; using System.Diagnostics; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/PrecedingQuery.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/PrecedingQuery.cs index 818ab4085d6ffe..83f449e8cdf444 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/PrecedingQuery.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/PrecedingQuery.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics; using System.Xml.XPath; using StackNav = MS.Internal.Xml.XPath.ClonableStack; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/Query.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/Query.cs index cfb402c3a11cc3..3d08b72aee913f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/Query.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/Query.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections.Generic; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/QueryBuilder.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/QueryBuilder.cs index efda195b62e8ab..d45bae233b8cfe 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/QueryBuilder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/QueryBuilder.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections.Generic; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ResetableIterator.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ResetableIterator.cs index ed06c29494e7f8..d88410000e3991 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ResetableIterator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ResetableIterator.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Xml.XPath; namespace MS.Internal.Xml.XPath diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ReversePositionQuery.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ReversePositionQuery.cs index 116b29568a958c..7d65497e248562 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ReversePositionQuery.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ReversePositionQuery.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Xml.XPath; namespace MS.Internal.Xml.XPath diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/Root.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/Root.cs index 5e9303fa81dd56..505bc9e2bb3a43 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/Root.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/Root.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Xml.XPath; namespace MS.Internal.Xml.XPath diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/SortQuery.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/SortQuery.cs index 96eeb329426fb6..51dff75b027fba 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/SortQuery.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/SortQuery.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections; using System.Collections.Generic; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/StringFunctions.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/StringFunctions.cs index 3ea556f6d736d9..5394bd67e93438 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/StringFunctions.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/StringFunctions.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections.Generic; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/UnionExpr.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/UnionExpr.cs index d7684f6ac1e435..c3f18463a6306a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/UnionExpr.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/UnionExpr.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Xml; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ValueQuery.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ValueQuery.cs index 8cb5615d062833..654e86db2ca733 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ValueQuery.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/ValueQuery.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Xml; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/Variable.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/Variable.cs index 89150323978dc4..45eb4bcf71548a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/Variable.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/Variable.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Xml.XPath; namespace MS.Internal.Xml.XPath diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/VariableQuery.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/VariableQuery.cs index 74678d2404de93..cce5d1301add6b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/VariableQuery.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/VariableQuery.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Diagnostics; using System.Xml; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathAncestorIterator.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathAncestorIterator.cs index 621b4e0304adb5..d5b07d571e986f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathAncestorIterator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathAncestorIterator.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Xml.XPath; namespace MS.Internal.Xml.XPath diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathAncestorQuery.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathAncestorQuery.cs index 0487aa79f7e398..8f8255b8bf2d1c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathAncestorQuery.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathAncestorQuery.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Xml; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathArrayIterator.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathArrayIterator.cs index 2bb0944ebee53a..f7d35ddfc40d13 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathArrayIterator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathArrayIterator.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections; using System.Collections.Generic; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathAxisIterator.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathAxisIterator.cs index cf15bfd5f445f9..996b35e8b7e69a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathAxisIterator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathAxisIterator.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathChildIterator.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathChildIterator.cs index 3fdeb2ea79dd4d..1db05129cec2f7 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathChildIterator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathChildIterator.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Xml.XPath; namespace MS.Internal.Xml.XPath diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathDescendantIterator.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathDescendantIterator.cs index f0e1542b67ab4a..65a0e9b17972b4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathDescendantIterator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathDescendantIterator.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Xml.XPath; namespace MS.Internal.Xml.XPath diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathEmptyIterator.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathEmptyIterator.cs index bd6b5a0964f46d..c58f7447519d34 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathEmptyIterator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathEmptyIterator.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Xml.XPath; namespace MS.Internal.Xml.XPath diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathMultyIterator.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathMultyIterator.cs index 437cd195390594..22f24f688ed321 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathMultyIterator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathMultyIterator.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace MS.Internal.Xml.XPath { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathParser.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathParser.cs index 8c75360e61cdbe..5c08a2b078d430 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathParser.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathParser.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections.Generic; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathScanner.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathScanner.cs index 5477ab18321dd6..f5482e94b8029c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathScanner.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathScanner.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Diagnostics; using System.Globalization; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathSelectionIterator.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathSelectionIterator.cs index 1431765888b707..e710cf3556fef7 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathSelectionIterator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathSelectionIterator.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Xml.XPath; namespace MS.Internal.Xml.XPath diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathSelfQuery.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathSelfQuery.cs index 8fa0b677eb7532..dd83e8b5423c5c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathSelfQuery.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathSelfQuery.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Xml.XPath; namespace MS.Internal.Xml.XPath diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathSingletonIterator.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathSingletonIterator.cs index 7311ec45018d3f..67cdd880360381 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathSingletonIterator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/Internal/XPathSingletonIterator.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathDocument.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathDocument.cs index e54f875101c3be..82b173a82adf6e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathDocument.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathDocument.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using MS.Internal.Xml.Cache; using System.Collections.Generic; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathException.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathException.cs index af0c9d0bf35e42..3b1a9fe8df4a32 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathException.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathException.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Resources; using System.Runtime.Serialization; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathExpr.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathExpr.cs index f9b5e4c644914b..447610c51f7dda 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathExpr.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathExpr.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using MS.Internal.Xml.XPath; using System.Collections; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathItem.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathItem.cs index abe7141ce9a480..6af68b0b7c3070 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathItem.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathItem.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Xml.Schema; namespace System.Xml.XPath diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNamespaceScope.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNamespaceScope.cs index 48399c0fb8bcb6..82fcb44330f68a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNamespaceScope.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNamespaceScope.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.XPath { public enum XPathNamespaceScope diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigator.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigator.cs index 288f8d5212386b..f7c86f7f9b7232 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigator.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.ComponentModel; using System.IO; using System.Collections; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigatorKeyComparer.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigatorKeyComparer.cs index b79cc674d533b0..2e4a259a8d415d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigatorKeyComparer.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigatorKeyComparer.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using MS.Internal.Xml.Cache; using System.Collections; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigatorReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigatorReader.cs index 1b8a06a8dcfd57..94c1dce35728a8 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigatorReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNavigatorReader.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.IO; using System.Xml.Schema; using System.Collections; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNodeIterator.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNodeIterator.cs index d9573be04b37ea..b8750782c6207d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNodeIterator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNodeIterator.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNodeType.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNodeType.cs index e23fcd921afeaf..a7008883b65b70 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNodeType.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathNodeType.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.XPath { public enum XPathNodeType diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlCharType.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlCharType.cs index 82cfb9dce6805b..8d26ecd8630d26 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlCharType.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlCharType.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics; using System.IO; using System.Threading; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlComplianceUtil.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlComplianceUtil.cs index 1252d6ad85aedf..eb74150941ad13 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlComplianceUtil.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlComplianceUtil.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.IO; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlConvert.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlConvert.cs index e04ebb6969afaa..ff81f2161551c0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlConvert.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlConvert.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Text; using System.Globalization; using System.Xml.Schema; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlDownloadManager.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlDownloadManager.cs index 226d0bc71dae6e..2e35677cf389a6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlDownloadManager.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlDownloadManager.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.IO; using System.Net; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlDownloadManagerAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlDownloadManagerAsync.cs index 8d320d5c604f7f..87b3da75f3b590 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlDownloadManagerAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlDownloadManagerAsync.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.IO; using System.Net; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlEncoding.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlEncoding.cs index 3361da0e0c46da..e65a2807134e2d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlEncoding.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlEncoding.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Text; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlException.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlException.cs index 7339ba0df057fa..dde7f76f54a5fb 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlException.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlException.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Resources; using System.Text; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlNameTable.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlNameTable.cs index 03e2b5c129cdd9..e566ff2704c48e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlNameTable.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlNameTable.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml { /// diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlNamespaceScope.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlNamespaceScope.cs index e742f6ee5b8484..062b581143ead4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlNamespaceScope.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlNamespaceScope.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml { /// diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlNamespacemanager.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlNamespacemanager.cs index 9529ee963cf83c..9e209bd16b61a9 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlNamespacemanager.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlNamespacemanager.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlNodeOrder.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlNodeOrder.cs index e353e1b1ba6f7f..5b1bbbd3c896d0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlNodeOrder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlNodeOrder.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml { public enum XmlNodeOrder diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlNodeType.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlNodeType.cs index 74bd699d7566dc..5fb688d9bf6acf 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlNodeType.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlNodeType.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml { /// diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlNullResolver.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlNullResolver.cs index 62a34ffe6594b4..ea93f83dfffbb3 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlNullResolver.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlNullResolver.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Net; namespace System.Xml diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlQualifiedName.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlQualifiedName.cs index d74ee28f826dae..6ff8642c2d5c40 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlQualifiedName.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlQualifiedName.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlReservedNs.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlReservedNs.cs index e4ef0a1116457e..a3922562aa7519 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlReservedNs.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlReservedNs.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml { /// diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlResolver.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlResolver.cs index c9c6ff75e7c650..357cf3c69b162d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlResolver.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlResolver.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlResolverAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlResolverAsync.cs index a21b4b639045ed..21504ff5e06ddb 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlResolverAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlResolverAsync.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Threading.Tasks; namespace System.Xml diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlSecureResolver.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlSecureResolver.cs index 05398fa3c35f1b..330feb5378a19b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlSecureResolver.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlSecureResolver.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml { using System.Net; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlSecureResolverAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlSecureResolverAsync.cs index 61a06da7a19f35..59ffe4bcb36254 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlSecureResolverAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlSecureResolverAsync.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Threading.Tasks; namespace System.Xml diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlUrlResolver.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlUrlResolver.cs index 7f1fcbf55f1b32..641e5842c58f2a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlUrlResolver.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlUrlResolver.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Threading; using System.Net; using System.Net.Cache; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/XmlUrlResolverAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/XmlUrlResolverAsync.cs index f054e23ffb912c..62125f9d8042b0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlUrlResolverAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlUrlResolverAsync.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Runtime.Versioning; using System.Threading.Tasks; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/ISourceLineInfo.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/ISourceLineInfo.cs index 8a45cc4da4e461..705e01d5244772 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/ISourceLineInfo.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/ISourceLineInfo.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Xsl { internal interface ISourceLineInfo diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/GenerateHelper.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/GenerateHelper.cs index 1b770d4d5b1e0e..8130d26d8f2a2b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/GenerateHelper.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/GenerateHelper.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Globalization; using System.Xml; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/IteratorDescriptor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/IteratorDescriptor.cs index d69b9853c28d4a..5e6ef24dfe2dd7 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/IteratorDescriptor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/IteratorDescriptor.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections; using System.Collections.Generic; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/OptimizerPatterns.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/OptimizerPatterns.cs index 93904a435363a3..4c3965fac095f9 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/OptimizerPatterns.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/OptimizerPatterns.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Diagnostics; using System.Xml.Xsl.Qil; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/StaticDataManager.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/StaticDataManager.cs index e0d47c7007d7ba..c9e25cdad922bd 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/StaticDataManager.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/StaticDataManager.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections; using System.Collections.Generic; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/TailCallAnalyzer.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/TailCallAnalyzer.cs index 99cdf8f6a48987..600070bec9cf9a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/TailCallAnalyzer.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/TailCallAnalyzer.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Diagnostics; using System.Xml.Xsl.Qil; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILAnnotation.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILAnnotation.cs index b691af96ffbdb6..e1580e23a70f9b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILAnnotation.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILAnnotation.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Reflection; using System.Xml.Xsl.Qil; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILConstructAnalyzer.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILConstructAnalyzer.cs index 98ac3aea46d5e2..730054b9eb521a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILConstructAnalyzer.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILConstructAnalyzer.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Xml; using System.Xml.Schema; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILModule.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILModule.cs index f6b43070e81bc8..9d193487a007d1 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILModule.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILModule.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections; using System.Diagnostics; using System.Reflection; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILOptimization.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILOptimization.cs index d7c7c6df808eae..c00eb27ab8011f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILOptimization.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILOptimization.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Xsl.IlGen { /// diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILOptimizerVisitor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILOptimizerVisitor.cs index fbdcd37eb20009..e02dc3d989261a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILOptimizerVisitor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILOptimizerVisitor.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILTrace.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILTrace.cs index 7a8e9819bf40af..c93e81f753a178 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILTrace.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlILTrace.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.IO; using System.Security; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlIlTypeHelper.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlIlTypeHelper.cs index a3cbb3e37b4541..a7ead3818658e3 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlIlTypeHelper.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlIlTypeHelper.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections.Generic; using System.IO; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlIlVisitor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlIlVisitor.cs index ce44e31df7c893..75f097381d794f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlIlVisitor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/IlGen/XmlIlVisitor.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Xml; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/ListBase.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/ListBase.cs index e9e85c1d8e6a10..d2996cf63f3df4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/ListBase.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/ListBase.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Xml; using System.Xml.Schema; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Pair.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Pair.cs index 893ec61b7b9e5d..626bd17bae913c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Pair.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Pair.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilBinary.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilBinary.cs index a71c32a6e8dd97..47765658b99ff1 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilBinary.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilBinary.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections.Generic; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilChoice.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilChoice.cs index 2a3a6ec1dfddbe..daff0690f6d2b5 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilChoice.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilChoice.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilCloneVisitor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilCloneVisitor.cs index 2865ecc906b314..e379522b931206 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilCloneVisitor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilCloneVisitor.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections.Generic; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilDataSource.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilDataSource.cs index cca511141a6743..99ad88b9a45a2f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilDataSource.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilDataSource.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections.Generic; using System.Xml.Schema; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilExpression.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilExpression.cs index 74378ec7f64353..5b743985b8b0e6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilExpression.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilExpression.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections.Generic; using System.Xml.Xsl.Runtime; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilFactory.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilFactory.cs index 695fc459e78b9c..4c6fe3fa700e89 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilFactory.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilFactory.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections.Generic; namespace System.Xml.Xsl.Qil diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilFunction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilFunction.cs index d00e2262c141e4..b6dd25a1c8da83 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilFunction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilFunction.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections.Generic; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilInvoke.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilInvoke.cs index 48326db762dc98..0530d062e2c9ae 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilInvoke.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilInvoke.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Diagnostics; using System.Xml.Schema; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilInvokeEarlyBound.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilInvokeEarlyBound.cs index b8e07b16e937db..dcc36df218df20 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilInvokeEarlyBound.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilInvokeEarlyBound.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Diagnostics; using System.Reflection; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilInvokeLateBound.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilInvokeLateBound.cs index a558cc2f65f2fb..dfa095333190ec 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilInvokeLateBound.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilInvokeLateBound.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilIterator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilIterator.cs index 3a9247e91347c7..2a1475bf2a9ccb 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilIterator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilIterator.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilList.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilList.cs index 171fde25f79ec9..d105ee90bf45d2 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilList.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilList.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections.Generic; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilLiteral.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilLiteral.cs index c86dbb2712ff96..b418c83ca5f3c4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilLiteral.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilLiteral.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilLoop.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilLoop.cs index cfe90c421faffe..b3f2f29898563d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilLoop.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilLoop.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilName.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilName.cs index a51f7597c50d6c..413c51abab9362 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilName.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilName.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilNode.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilNode.cs index cd2cca2f7a0c52..9551e911d82fec 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilNode.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilNode.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections; using System.Collections.Generic; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilNodeType.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilNodeType.cs index 387544491a6cb6..c9973ae9a24431 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilNodeType.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilNodeType.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Xsl.Qil { /// An enumeration of all the possible QilExpression node types. diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilParameter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilParameter.cs index 085962bbbbbd39..258dcb1067545b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilParameter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilParameter.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilPatternFactory.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilPatternFactory.cs index 5d655c188d0236..c5862ec77f0942 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilPatternFactory.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilPatternFactory.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections.Generic; using System.Diagnostics; using System.Reflection; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilPatternVisitor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilPatternVisitor.cs index 8e82891582d0b5..5701f5bba48c0e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilPatternVisitor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilPatternVisitor.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections; using System.Diagnostics.CodeAnalysis; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilReference.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilReference.cs index 107a645db29c39..dd269f7d31362a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilReference.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilReference.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilReplaceVisitor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilReplaceVisitor.cs index a7799c4e2a1df1..087a0352834790 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilReplaceVisitor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilReplaceVisitor.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections; using System.Collections.Generic; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilScopedVisitor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilScopedVisitor.cs index 01519661151b89..84b4cba5168263 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilScopedVisitor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilScopedVisitor.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections.Generic; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilSortKey.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilSortKey.cs index cab41ac94651f9..073e8a291fd676 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilSortKey.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilSortKey.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilStrConcat.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilStrConcat.cs index 49761767eed577..8dafd52113c449 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilStrConcat.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilStrConcat.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilTargetType.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilTargetType.cs index e5c77760b5385e..adcc09db04b7de 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilTargetType.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilTargetType.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections.Generic; using System.Xml.Schema; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilTernary.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilTernary.cs index 86ddd1fe85a34e..787937751c4147 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilTernary.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilTernary.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections.Generic; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilTypeChecker.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilTypeChecker.cs index ac947b5a9ed9f6..2b187a375aa06f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilTypeChecker.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilTypeChecker.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections; using System.Collections.Generic; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilUnary.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilUnary.cs index 151ab3fa5cb92c..112cf609714870 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilUnary.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilUnary.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections.Generic; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilValidationVisitor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilValidationVisitor.cs index 8134de7f5ca400..41c3a5765b1ba2 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilValidationVisitor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilValidationVisitor.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilVisitor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilVisitor.cs index 88ac380bd6f504..561d83704219a4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilVisitor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilVisitor.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilXmlWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilXmlWriter.cs index 9188c3e8866fe7..7e2b54f7ced507 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilXmlWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/QilXmlWriter.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections; using System.Collections.Generic; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/SerializationHints.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/SerializationHints.cs index 952080b25513f6..fc9635c2033b5e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/SerializationHints.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/SerializationHints.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; namespace System.Xml.Xsl.Qil diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/SubstitutionList.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/SubstitutionList.cs index 54c03eae52cb57..35f4d7d2bd4294 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/SubstitutionList.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/SubstitutionList.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/WhitespaceRule.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/WhitespaceRule.cs index 18bf7065770eeb..a1f129bc2a5e64 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/WhitespaceRule.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QIL/WhitespaceRule.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QueryReaderSettings.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QueryReaderSettings.cs index d95ef698a6f22b..9bd4a85ac9023a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QueryReaderSettings.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/QueryReaderSettings.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections; using System.Collections.Generic; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/ContentIterators.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/ContentIterators.cs index 215ebd78c61804..44ec8492d2224f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/ContentIterators.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/ContentIterators.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable disable using System; using System.Xml; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/DecimalFormatter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/DecimalFormatter.cs index 7d2e72e6db1f3e..ee3d21356c627c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/DecimalFormatter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/DecimalFormatter.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable disable using System.Diagnostics; using System.Globalization; using System.Text; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/DocumentOrderComparer.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/DocumentOrderComparer.cs index e4928bbe511b60..f595922ebcb62d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/DocumentOrderComparer.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/DocumentOrderComparer.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable disable using System; using System.Collections; using System.Collections.Generic; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/DodSequenceMerge.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/DodSequenceMerge.cs index e6fc6e3c845f08..bb82c33a8d63fd 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/DodSequenceMerge.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/DodSequenceMerge.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable disable using System; using System.Collections.Generic; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/EarlyBoundInfo.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/EarlyBoundInfo.cs index 773f2295bd7969..9b44a9fe557d9e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/EarlyBoundInfo.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/EarlyBoundInfo.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable disable using System.Diagnostics; using System.Reflection; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/NumberFormatter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/NumberFormatter.cs index dd6d4cac8a9478..ffe223ead73025 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/NumberFormatter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/NumberFormatter.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable disable using System.Diagnostics; using System.Text; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/RtfNavigator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/RtfNavigator.cs index ef7039fdf41050..8ca6025bc44e70 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/RtfNavigator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/RtfNavigator.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable disable using System; using System.Threading; using System.IO; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/SetIterators.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/SetIterators.cs index 7e92b43627a22f..7001187ecbc35f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/SetIterators.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/SetIterators.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable disable using System; using System.Xml; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/SiblingIterators.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/SiblingIterators.cs index 16f0e8c68b2d69..15eab78c27b963 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/SiblingIterators.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/SiblingIterators.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable disable using System; using System.Xml; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/StringConcat.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/StringConcat.cs index 1a5395a52beff4..f2f61ca05081e8 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/StringConcat.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/StringConcat.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections.Generic; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/TreeIterators.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/TreeIterators.cs index 15ae373cfb5148..07a9798589437b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/TreeIterators.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/TreeIterators.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable disable using System.ComponentModel; using System.Diagnostics; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/WhitespaceRuleLookup.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/WhitespaceRuleLookup.cs index 81aee6351e41b7..20cccb874ffb00 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/WhitespaceRuleLookup.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/WhitespaceRuleLookup.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable disable using System; using System.Xml; using System.Collections; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/WhitespaceRuleReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/WhitespaceRuleReader.cs index 8fbee96c8dd899..358ef4385601c4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/WhitespaceRuleReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/WhitespaceRuleReader.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable disable using System.Diagnostics; namespace System.Xml.Xsl.Runtime diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlAggregates.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlAggregates.cs index 6fb4a836fbcb43..65dabdf77e5ef6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlAggregates.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlAggregates.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable disable using System; using System.Xml; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlAttributeCache.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlAttributeCache.cs index 68ebc461f28806..0a4560db11d681 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlAttributeCache.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlAttributeCache.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable disable namespace System.Xml.Xsl.Runtime { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlCollation.Unix.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlCollation.Unix.cs index c01679e628a5e5..419d570707d7d6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlCollation.Unix.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlCollation.Unix.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable disable using System.Globalization; namespace System.Xml.Xsl.Runtime diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlCollation.Windows.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlCollation.Windows.cs index 40e0e7e7ad5083..577beae5bf35ec 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlCollation.Windows.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlCollation.Windows.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable disable using System.Globalization; namespace System.Xml.Xsl.Runtime diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlCollation.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlCollation.cs index 21bd19a14f5ff2..224747d64468e1 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlCollation.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlCollation.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable disable using System.Collections; using System.ComponentModel; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlExtensionFunction.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlExtensionFunction.cs index 2f73e3434b2d8d..1707aa9d560999 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlExtensionFunction.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlExtensionFunction.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable disable using System; using System.Collections.Generic; using System.Xml; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlILIndex.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlILIndex.cs index 7fd7f342e1afc6..86fcbb33150b82 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlILIndex.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlILIndex.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable disable using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlILStorageConverter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlILStorageConverter.cs index 92c355f8296440..840a8bf7cbcf0f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlILStorageConverter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlILStorageConverter.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable disable using System; using System.Collections.Generic; using System.IO; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlIterators.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlIterators.cs index 8c01f8f4f65c40..4964e538b3c30b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlIterators.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlIterators.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable disable using System; using System.Xml; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlNavigatorFilter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlNavigatorFilter.cs index 9de706c3ad2136..ee3756d2e7afe4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlNavigatorFilter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlNavigatorFilter.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable disable using System.Xml; using System.Xml.XPath; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlNavigatorStack.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlNavigatorStack.cs index 477f626c873491..08b530c4aba3c4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlNavigatorStack.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlNavigatorStack.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable disable using System; using System.Xml; using System.Xml.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryContext.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryContext.cs index 62386394bcb057..c2d3b2e3781d1d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryContext.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryContext.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable disable using System; using System.Collections; using System.Collections.Generic; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryOutput.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryOutput.cs index 5c786ce640bdf2..83387e02926fcc 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryOutput.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryOutput.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable disable using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryRuntime.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryRuntime.cs index 6efecc81d3ba3d..0575e803f3ddf7 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryRuntime.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryRuntime.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable disable using System; using System.IO; using System.Xml; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQuerySequence.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQuerySequence.cs index a7d417f5b6440c..b43ecb531ad8d8 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQuerySequence.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQuerySequence.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable disable using System; using System.Collections; using System.Collections.Generic; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryStaticData.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryStaticData.cs index b01534e60b624f..0cd1738310d883 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryStaticData.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlQueryStaticData.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable disable using System.Collections.Generic; using System.Diagnostics; using System.IO; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlRawWriterWrapper.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlRawWriterWrapper.cs index 7d76fb59a604e2..df64624cadaa15 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlRawWriterWrapper.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlRawWriterWrapper.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable disable using System; using System.IO; using System.Xml; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlSequenceWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlSequenceWriter.cs index 04ea89ff779440..873f52b8b6eec7 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlSequenceWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlSequenceWriter.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable disable using System; using System.Collections.Generic; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlSortKey.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlSortKey.cs index a4828b480d248d..fe94d265fb8855 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlSortKey.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlSortKey.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable disable using System; using System.Diagnostics; using System.Globalization; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlSortKeyAccumulator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlSortKeyAccumulator.cs index 4ccdbc040be04d..29fc8c76b2dff6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlSortKeyAccumulator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XmlSortKeyAccumulator.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable disable using System; using System.Diagnostics; using System.Globalization; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XslNumber.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XslNumber.cs index c028f23bddb0dd..4673961e6b7b20 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XslNumber.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XslNumber.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable disable using System.Collections; using System.Collections.Generic; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltConvert.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltConvert.cs index e8bfa389628e67..26b902273ee77e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltConvert.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltConvert.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable disable using System; using System.Collections; using System.Collections.Generic; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltFunctions.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltFunctions.cs index cf5118ccd76658..309cd5c1d2dc46 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltFunctions.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltFunctions.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable disable using System.IO; using System.Text; using System.Reflection; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltLibrary.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltLibrary.cs index 6fe94786064bc8..ccf04eb9d09b5a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltLibrary.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Runtime/XsltLibrary.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable disable using System.Collections.Specialized; using System.Collections.Generic; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/SourceLineInfo.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/SourceLineInfo.cs index d979a4c12a8f9d..d0b14c713385a6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/SourceLineInfo.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/SourceLineInfo.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics; namespace System.Xml.Xsl diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/IXPathEnvironment.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/IXPathEnvironment.cs index 201217f13c92b7..c079cbab68f580 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/IXPathEnvironment.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/IXPathEnvironment.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections.Generic; using System.Xml.Xsl.Qil; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/IXpathBuilder.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/IXpathBuilder.cs index a8c33e48f1cb83..e44b4ddbe004b5 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/IXpathBuilder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/IXpathBuilder.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathAxis.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathAxis.cs index 18977c9a45b6e1..ee3a212595bce0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathAxis.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathAxis.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Xsl.XPath { // Order is important - we use them as an index in QilAxis & AxisMask arrays diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathBuilder.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathBuilder.cs index dff13ae08889d7..0be02ffcb2f7bd 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathBuilder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathBuilder.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathCompileException.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathCompileException.cs index 42470c834f8a50..6b2e67550a4c13 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathCompileException.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathCompileException.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Runtime.Serialization; using System.Text; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathContext.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathContext.cs index f863ef75540a3b..f1b073d2e95aff 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathContext.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathContext.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable #if DontUse // XPathContext is not used any more but comments in it and Replacer visitor may be used to // optimize code XSLT generates on last(). diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathOperator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathOperator.cs index adc8c37e681e45..58765d248f85b4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathOperator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathOperator.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Xsl.XPath { // order is importent. We are using them as an index in OperatorGroup & QilOperator & XPathOperatorToQilNodeType arrays diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathParser.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathParser.cs index d707ad52d5dd2b..5208144246306e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathParser.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathParser.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections.Generic; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathQilFactory.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathQilFactory.cs index 09e635a6d30a9d..879e8d997c7c2e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathQilFactory.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathQilFactory.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics; using System.Xml.Schema; using System.Xml.Xsl.Qil; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathScanner.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathScanner.cs index e6509bf1580132..12dc8384cfcd8d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathScanner.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPath/XPathScanner.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable // http://www.w3.org/TR/xpath#exprlex //------------------------------------------------------------------------------ diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPathConvert.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPathConvert.cs index c31f265cbb9f36..b23f0a37223a74 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPathConvert.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XPathConvert.cs @@ -8,7 +8,6 @@ * */ -#nullable enable using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlILCommand.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlILCommand.cs index 6649cbbe55446f..bb0adf57e3d907 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlILCommand.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlILCommand.cs @@ -4,7 +4,6 @@ // http://webdata/xml/specs/querylowlevel.xml //------------------------------------------------------------------------------ -#nullable enable using System.Collections; using System.Diagnostics; using System.IO; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlIlGenerator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlIlGenerator.cs index e20f724312c92f..16d19e0e1a84cb 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlIlGenerator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlIlGenerator.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections; using System.Collections.Generic; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlNodeKindFlags.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlNodeKindFlags.cs index 882264228e95b3..4101c0fb4459b1 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlNodeKindFlags.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlNodeKindFlags.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; namespace System.Xml.Xsl diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlQualifiedNameTest.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlQualifiedNameTest.cs index 66363cf8683dab..b140fc567eac50 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlQualifiedNameTest.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlQualifiedNameTest.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Xml; using System.Xml.Schema; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlQueryCardinality.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlQueryCardinality.cs index 012b94fa9d4215..bf46143f278a85 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlQueryCardinality.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlQueryCardinality.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics; using System.IO; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlQueryType.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlQueryType.cs index 3005c4d7bb8cc6..b8a9c6c51d2ea8 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlQueryType.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlQueryType.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections.Generic; using System.Diagnostics; using System.IO; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlQueryTypeFactory.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlQueryTypeFactory.cs index b844184dd7f4f6..ce571c9932ec52 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlQueryTypeFactory.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XmlQueryTypeFactory.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections.Generic; using System.Diagnostics; using System.Globalization; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XslException.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XslException.cs index a239d96c103dfd..37dbe195e52632 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XslException.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/XslException.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics; using System.Globalization; using System.Resources; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/Compiler.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/Compiler.cs index dcf14189c20500..1105a03cae9ced 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/Compiler.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/Compiler.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; @@ -140,7 +139,7 @@ private void MergeWhitespaceRules(Stylesheet sheet) { for (int idx = 0; idx <= 2; idx++) { - sheet.WhitespaceRules[idx].Reverse(); + sheet.WhitespaceRules![idx].Reverse(); this.WhitespaceRules.AddRange(sheet.WhitespaceRules[idx]); } sheet.WhitespaceRules = null; @@ -148,7 +147,7 @@ private void MergeWhitespaceRules(Stylesheet sheet) private void MergeAttributeSets(Stylesheet sheet) { - foreach (QilName attSetName in sheet.AttributeSets.Keys) + foreach (QilName attSetName in sheet.AttributeSets!.Keys) { AttributeSet? attSet; if (!this.AttributeSets.TryGetValue(attSetName, out attSet)) @@ -166,7 +165,7 @@ private void MergeAttributeSets(Stylesheet sheet) private void MergeGlobalVarPars(Stylesheet sheet) { - foreach (VarPar var in sheet.GlobalVarPars) + foreach (VarPar var in sheet.GlobalVarPars!) { Debug.Assert(var.NodeType == XslNodeType.Variable || var.NodeType == XslNodeType.Param); if (!AllGlobalVarPars.ContainsKey(var.Name!)) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/CompilerError.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/CompilerError.cs index 4a313c993844b9..fa10fd9a2480f3 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/CompilerError.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/CompilerError.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections; namespace System.Xml.Xsl.Xslt diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/CompilerScopeManager.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/CompilerScopeManager.cs index 315f81ad639963..b32692c26d062f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/CompilerScopeManager.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/CompilerScopeManager.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics; using System.Diagnostics.CodeAnalysis; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/Focus.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/Focus.cs index 632349da5c319d..cce691ba93b540 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/Focus.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/Focus.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections.Generic; using System.Diagnostics; using System.Xml.Xsl.XPath; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/IErrorHelper.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/IErrorHelper.cs index 4565dfa83b00da..19d2fb80dd01a1 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/IErrorHelper.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/IErrorHelper.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable namespace System.Xml.Xsl { internal interface IErrorHelper diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/InvokeGenerator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/InvokeGenerator.cs index d7d4c0234dd156..6e15fc5605a9da 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/InvokeGenerator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/InvokeGenerator.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections.Generic; using System.Diagnostics; using System.Xml.Xsl.Qil; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/KeyMatchBuilder.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/KeyMatchBuilder.cs index 81cd01cc051cca..b7a110a2e6023e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/KeyMatchBuilder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/KeyMatchBuilder.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Diagnostics; using System.Collections; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/Keywords.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/Keywords.cs index 9bcc76bda2f231..7574183e0ca17e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/Keywords.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/Keywords.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Xml; namespace System.Xml.Xsl.Xslt diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/MatcherBuilder.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/MatcherBuilder.cs index ca2cde344eb7f1..3e16e60d002d8b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/MatcherBuilder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/MatcherBuilder.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; @@ -358,7 +357,7 @@ private void AddPatterns(List matches) private void CollectPatternsInternal(Stylesheet sheet, QilName mode) { // Process imported stylesheets in the straight order, since their order will be reverted in the result tree - foreach (Stylesheet import in sheet.Imports) + foreach (Stylesheet import in sheet.Imports!) { CollectPatternsInternal(import, mode); } @@ -374,7 +373,7 @@ private void CollectPatternsInternal(Stylesheet sheet, QilName mode) public void CollectPatterns(StylesheetLevel sheet, QilName mode) { Clear(); - foreach (Stylesheet import in sheet.Imports) + foreach (Stylesheet import in sheet.Imports!) { CollectPatternsInternal(import, mode); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/OutputScopeManager.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/OutputScopeManager.cs index 9dde09dbc401a9..ffcbe6d8e387c7 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/OutputScopeManager.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/OutputScopeManager.cs @@ -1,13 +1,11 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System; using System.Diagnostics; using System.Xml; using System.Collections; -#nullable enable namespace System.Xml.Xsl.Xslt { internal class OutputScopeManager diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilGenerator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilGenerator.cs index a799185c158764..410a8f75e46968 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilGenerator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilGenerator.cs @@ -5,7 +5,6 @@ // http://www.w3.org/TR/xslt20/ //------------------------------------------------------------------------------ -#nullable enable using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; @@ -157,7 +156,7 @@ private QilExpression Compile(Compiler compiler) try { CompileKeys(); - CompileAndSortMatches(compiler.Root!.Imports[0]); + CompileAndSortMatches(compiler.Root!.Imports![0]); PrecompileProtoTemplatesHeaders(); CompileGlobalVariables(); @@ -2164,7 +2163,7 @@ private void CompileAndSortMatches(Stylesheet sheet) sheet.SortTemplateMatches(); - foreach (Stylesheet import in sheet.Imports) + foreach (Stylesheet import in sheet.Imports!) { CompileAndSortMatches(import); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilGeneratorEnv.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilGeneratorEnv.cs index 8181f99a4a97ce..38d543b5138415 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilGeneratorEnv.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilGeneratorEnv.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Collections.Generic; using System.Diagnostics; using System.Xml.Schema; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilStrConcatenator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilStrConcatenator.cs index 80ded330780a3d..32c71b7e352211 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilStrConcatenator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/QilStrConcatenator.cs @@ -1,7 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -#nullable enable using System.Diagnostics; using System.Xml; using System.Text; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/Scripts.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/Scripts.cs index 479af7a79a119e..1b09d4150b62e9 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/Scripts.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/Scripts.cs @@ -4,7 +4,6 @@ // http://devdiv/Documents/Whidbey/CLR/CurrentSpecs/BCL/CodeDom%20Activation.doc //------------------------------------------------------------------------------ -#nullable enable using System.Collections.Generic; using System.Collections.Specialized; using System.Configuration; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/Stylesheet.cs b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/Stylesheet.cs index 26ecb7c6e148f7..011862c1ff00af 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/Stylesheet.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Xsl/Xslt/Stylesheet.cs @@ -10,7 +10,7 @@ namespace System.Xml.Xsl.Xslt { internal class StylesheetLevel { - public Stylesheet[] Imports; + public Stylesheet[]? Imports; // If (this is Stylesheet) { // ModeFlags and ApplyFunctions are abblout apply-imports @@ -27,10 +27,10 @@ internal class Stylesheet : StylesheetLevel { private readonly Compiler _compiler; public List ImportHrefs = new List(); - public List GlobalVarPars = new List(); + public List? GlobalVarPars = new List(); // xsl:attribute-set/@name -> AttributeSet - public Dictionary AttributeSets = new Dictionary(); + public Dictionary? AttributeSets = new Dictionary(); private readonly int _importPrecedence; private int _orderNumber; @@ -40,7 +40,7 @@ internal class Stylesheet : StylesheetLevel WhitespaceRules[1] - rules with default priority -0.25 WhitespaceRules[2] - rules with default priority -0.5 */ - public List[] WhitespaceRules = new List[3]; + public List[]? WhitespaceRules = new List[3]; public List