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/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/CodeDom/CodeObject.cs b/src/libraries/Common/src/System/CodeDom/CodeObject.cs index c20871af3d6f68..74aa7a9ebf11fc 100644 --- a/src/libraries/Common/src/System/CodeDom/CodeObject.cs +++ b/src/libraries/Common/src/System/CodeDom/CodeObject.cs @@ -16,7 +16,7 @@ public class CodeObject internal class CodeObject #endif { - private IDictionary _userData; + private IDictionary? _userData; public CodeObject() { } diff --git a/src/libraries/Common/src/System/CodeDom/CodeTypeReference.cs b/src/libraries/Common/src/System/CodeDom/CodeTypeReference.cs index 7a5f3e7790ad53..5144111b7652d8 100644 --- a/src/libraries/Common/src/System/CodeDom/CodeTypeReference.cs +++ b/src/libraries/Common/src/System/CodeDom/CodeTypeReference.cs @@ -28,9 +28,9 @@ public class CodeTypeReference : CodeObject internal class CodeTypeReference : CodeObject #endif { - private string _baseType; + private string? _baseType; private readonly bool _isInterface; - private CodeTypeReferenceCollection _typeArguments; + private CodeTypeReferenceCollection? _typeArguments; private bool _needsFixup; public CodeTypeReference() @@ -50,7 +50,7 @@ public CodeTypeReference(Type type) if (type.IsArray) { ArrayRank = type.GetArrayRank(); - ArrayElementType = new CodeTypeReference(type.GetElementType()); + ArrayElementType = new CodeTypeReference(type.GetElementType()!); _baseType = null; } else @@ -86,7 +86,7 @@ private void InitializeFromType(Type type) Type currentType = type; while (currentType.IsNested) { - currentType = currentType.DeclaringType; + currentType = currentType.DeclaringType!; _baseType = currentType.Name + "+" + _baseType; } @@ -116,17 +116,17 @@ private void InitializeFromType(Type type) } } - private void Initialize(string typeName) + private void Initialize(string? typeName) { Initialize(typeName, Options); } - private void Initialize(string typeName, CodeTypeReferenceOptions options) + private void Initialize(string? typeName, CodeTypeReferenceOptions options) { Options = options; if (string.IsNullOrEmpty(typeName)) { - typeName = typeof(void).FullName; + typeName = typeof(void).FullName!; _baseType = typeName; ArrayRank = 0; ArrayElementType = null; @@ -303,7 +303,7 @@ public CodeTypeReference(CodeTypeReference arrayType, int rank) ArrayElementType = arrayType; } - public CodeTypeReference ArrayElementType { get; set; } + public CodeTypeReference? ArrayElementType { get; set; } public int ArrayRank { get; set; } diff --git a/src/libraries/Common/src/System/CodeDom/CodeTypeReferenceCollection.cs b/src/libraries/Common/src/System/CodeDom/CodeTypeReferenceCollection.cs index 819fa06b26ae46..7705d998afc88b 100644 --- a/src/libraries/Common/src/System/CodeDom/CodeTypeReferenceCollection.cs +++ b/src/libraries/Common/src/System/CodeDom/CodeTypeReferenceCollection.cs @@ -29,7 +29,7 @@ public CodeTypeReferenceCollection(CodeTypeReference[] value) public CodeTypeReference this[int index] { - get { return ((CodeTypeReference)(List[index])); } + get { return ((CodeTypeReference)(List[index]!)); } set { List[index] = value; } } 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/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.Data.Common/ref/System.Data.Common.cs b/src/libraries/System.Data.Common/ref/System.Data.Common.cs index 763f079568b2a2..537b12b62e46c9 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); @@ -3536,7 +3536,6 @@ public enum StorageState UnmanagedBuffer = 2, } } -#nullable disable namespace System.Xml { [System.ObsoleteAttribute("XmlDataDocument class will be removed in a future release.")] @@ -3546,17 +3545,16 @@ public XmlDataDocument() { } public XmlDataDocument(System.Data.DataSet dataset) { } public System.Data.DataSet DataSet { get { throw null; } } public override System.Xml.XmlNode CloneNode(bool deep) { throw null; } - public override System.Xml.XmlElement CreateElement(string prefix, string localName, string namespaceURI) { throw null; } + public override System.Xml.XmlElement CreateElement(string? prefix, string localName, string? namespaceURI) { throw null; } public override System.Xml.XmlEntityReference CreateEntityReference(string name) { throw null; } - protected override System.Xml.XPath.XPathNavigator CreateNavigator(System.Xml.XmlNode node) { throw null; } - public override System.Xml.XmlElement GetElementById(string elemId) { throw null; } + protected override System.Xml.XPath.XPathNavigator? CreateNavigator(System.Xml.XmlNode node) { throw null; } + public override System.Xml.XmlElement? GetElementById(string elemId) { throw null; } public System.Xml.XmlElement GetElementFromRow(System.Data.DataRow r) { throw null; } public override System.Xml.XmlNodeList GetElementsByTagName(string name) { throw null; } - public System.Data.DataRow GetRowFromElement(System.Xml.XmlElement e) { throw null; } + public System.Data.DataRow? GetRowFromElement(System.Xml.XmlElement? e) { throw null; } public override void Load(System.IO.Stream inStream) { } public override void Load(System.IO.TextReader txtReader) { } public override void Load(string filename) { } public override void Load(System.Xml.XmlReader reader) { } } } -#nullable enable 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/Common/ObjectStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/ObjectStorage.cs index 6e16308edca499..6c2c947aa0156d 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/ObjectStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/ObjectStorage.cs @@ -341,7 +341,7 @@ public override object ConvertXmlToObject(string s) StringReader strreader = new StringReader(s); XmlSerializer deserializerWithOutRootAttribute = ObjectStorage.GetXmlSerializer(type); - return (deserializerWithOutRootAttribute.Deserialize(strreader)); + return (deserializerWithOutRootAttribute.Deserialize(strreader))!; } // Prevent inlining so that reflection calls are not moved to caller that may be in a different assembly that may have a different grant set. @@ -355,10 +355,10 @@ public override object ConvertXmlToObject(XmlReader xmlReader, XmlRootAttribute if (null == xmlAttrib) { // this means type implements IXmlSerializable Type? type = null; - string typeName = xmlReader.GetAttribute(Keywords.MSD_INSTANCETYPE, Keywords.MSDNS); + string? typeName = xmlReader.GetAttribute(Keywords.MSD_INSTANCETYPE, Keywords.MSDNS); if (typeName == null || typeName.Length == 0) { // No CDT polumorphism - string xsdTypeName = xmlReader.GetAttribute(Keywords.TYPE, Keywords.XSINS); // this xsd type: Base type polymorphism + string? xsdTypeName = xmlReader.GetAttribute(Keywords.TYPE, Keywords.XSINS); // this xsd type: Base type polymorphism if (null != xsdTypeName && xsdTypeName.Length > 0) { string[] _typename = xsdTypeName.Split(':'); diff --git a/src/libraries/System.Data.Common/src/System/Data/Common/SqlUDTStorage.cs b/src/libraries/System.Data.Common/src/System/Data/Common/SqlUDTStorage.cs index 2681daf1ddf872..1743d3f667a0ea 100644 --- a/src/libraries/System.Data.Common/src/System/Data/Common/SqlUDTStorage.cs +++ b/src/libraries/System.Data.Common/src/System/Data/Common/SqlUDTStorage.cs @@ -161,7 +161,7 @@ public override object ConvertXmlToObject(string s) StringReader strreader = new StringReader(s); XmlSerializer deserializerWithOutRootAttribute = ObjectStorage.GetXmlSerializer(_dataType); - return (deserializerWithOutRootAttribute.Deserialize(strreader)); + return (deserializerWithOutRootAttribute.Deserialize(strreader))!; } // Prevent inlining so that reflection calls are not moved to caller that may be in a different assembly that may have a different grant set. @@ -170,10 +170,10 @@ public override object ConvertXmlToObject(XmlReader xmlReader, XmlRootAttribute { if (null == xmlAttrib) { - string typeName = xmlReader.GetAttribute(Keywords.MSD_INSTANCETYPE, Keywords.MSDNS); + string? typeName = xmlReader.GetAttribute(Keywords.MSD_INSTANCETYPE, Keywords.MSDNS); if (typeName == null) { - string xsdTypeName = xmlReader.GetAttribute(Keywords.MSD_INSTANCETYPE, Keywords.XSINS); // this xsd type + string? xsdTypeName = xmlReader.GetAttribute(Keywords.MSD_INSTANCETYPE, Keywords.XSINS); // this xsd type if (null != xsdTypeName) { typeName = XSDSchema.XsdtoClr(xsdTypeName).FullName!; @@ -188,7 +188,7 @@ public override object ConvertXmlToObject(XmlReader xmlReader, XmlRootAttribute else { XmlSerializer deserializerWithRootAttribute = ObjectStorage.GetXmlSerializer(_dataType, xmlAttrib); - return (deserializerWithRootAttribute.Deserialize(xmlReader)); + return (deserializerWithRootAttribute.Deserialize(xmlReader))!; } } diff --git a/src/libraries/System.Data.Common/src/System/Data/DataSet.cs b/src/libraries/System.Data.Common/src/System/Data/DataSet.cs index e5c7e2a70159b4..8089963349f12e 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataSet.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataSet.cs @@ -181,7 +181,7 @@ protected SchemaSerializationMode DetermineSchemaSerializationMode(XmlReader rea { if (reader.HasAttributes) { - string attribValue = reader.GetAttribute(Keywords.MSD_SCHEMASERIALIZATIONMODE, Keywords.MSDNS); + string? attribValue = reader.GetAttribute(Keywords.MSD_SCHEMASERIALIZATIONMODE, Keywords.MSDNS); if (string.Equals(attribValue, Keywords.MSD_EXCLUDESCHEMA, StringComparison.OrdinalIgnoreCase)) { schemaSerializationMode = SchemaSerializationMode.ExcludeSchema; @@ -1533,7 +1533,7 @@ public void InferXmlSchema(XmlReader? reader, string[]? nsArray) XmlDocument xdoc = new XmlDocument(); if (reader.NodeType == XmlNodeType.Element) { - XmlNode node = xdoc.ReadNode(reader); + XmlNode node = xdoc.ReadNode(reader)!; xdoc.AppendChild(node); } else @@ -1693,7 +1693,7 @@ internal void ReadXmlSchema(XmlReader? reader, bool denyResolving) throw ExceptionBuilder.DataSetUnsupportedSchema(Keywords.XSDNS); } - XmlNode node = xdoc.ReadNode(reader); + XmlNode node = xdoc.ReadNode(reader)!; topNode.AppendChild(node); } @@ -1755,7 +1755,7 @@ internal void ReadXSDSchema(XmlReader reader, bool denyResolving) { if (reader.HasAttributes) { - string attribValue = reader.GetAttribute(Keywords.MSD_FRAGMENTCOUNT, Keywords.MSDNS); // this must not move the position + string? attribValue = reader.GetAttribute(Keywords.MSD_FRAGMENTCOUNT, Keywords.MSDNS); // this must not move the position if (!string.IsNullOrEmpty(attribValue)) { schemaFragmentCount = int.Parse(attribValue, null); @@ -1765,7 +1765,7 @@ internal void ReadXSDSchema(XmlReader reader, bool denyResolving) while (reader.LocalName == Keywords.XSD_SCHEMA && reader.NamespaceURI == Keywords.XSDNS) { - XmlSchema s = XmlSchema.Read(reader, null); + XmlSchema s = XmlSchema.Read(reader, null)!; sSet.Add(s); //read the end tag ReadEndElement(reader); @@ -1787,10 +1787,10 @@ internal void ReadXSDSchema(XmlReader reader, bool denyResolving) internal void ReadXDRSchema(XmlReader reader) { XmlDocument xdoc = new XmlDocument(); // we may need this to infer the schema - XmlNode schNode = xdoc.ReadNode(reader); + XmlNode schNode = xdoc.ReadNode(reader)!; xdoc.AppendChild(schNode); XDRSchema schema = new XDRSchema(this, false); - DataSetName = xdoc.DocumentElement.LocalName; + DataSetName = xdoc.DocumentElement!.LocalName; schema.LoadSchema((XmlElement)schNode, this); } @@ -2121,7 +2121,7 @@ internal XmlReadMode ReadXml(XmlReader reader, bool denyResolving) if (!fSchemaFound && Tables.Count == 0) { - XmlNode node = xdoc.ReadNode(reader); + XmlNode node = xdoc.ReadNode(reader)!; topNode.AppendChild(node); } else @@ -2177,12 +2177,12 @@ internal XmlReadMode ReadXml(XmlReader reader, bool denyResolving) if (!isEmptyDataSet && !topNodeIsProcessed) { - XmlElement root = xdoc.DocumentElement; + XmlElement root = xdoc.DocumentElement!; Debug.Assert(root.NamespaceURI != null, "root.NamespaceURI should not ne null, it should be empty string"); // just recognize that below given Xml represents datatable in toplevel //text
// only allow root element with simple content, if any - if (root.ChildNodes.Count == 0 || ((root.ChildNodes.Count == 1) && root.FirstChild.GetType() == typeof(System.Xml.XmlText))) + if (root.ChildNodes.Count == 0 || ((root.ChildNodes.Count == 1) && root.FirstChild!.GetType() == typeof(System.Xml.XmlText))) { bool initfTopLevelTable = _fTopLevelTable; // if root element maps to a datatable @@ -2525,7 +2525,7 @@ internal XmlReadMode ReadXml(XmlReader? reader, XmlReadMode mode, bool denyResol if (mode == XmlReadMode.Fragment) { xdoc.AppendChild(xdoc.CreateElement("ds_sqlXmlWraPPeR")); - topNode = xdoc.DocumentElement; + topNode = xdoc.DocumentElement!; } else { @@ -2666,7 +2666,7 @@ internal XmlReadMode ReadXml(XmlReader? reader, XmlReadMode mode, bool denyResol if (mode == XmlReadMode.InferSchema || mode == XmlReadMode.InferTypedSchema) { //save the node in DOM until the end; - XmlNode node = xdoc.ReadNode(reader); + XmlNode node = xdoc.ReadNode(reader)!; topNode.AppendChild(node); } else @@ -3309,7 +3309,7 @@ protected virtual void ReadXmlSerializable(XmlReader reader) const string xsinill = Keywords.XSI + ":" + Keywords.XSI_NIL; if (reader.MoveToAttribute(xsinill)) { - string nilAttrib = reader.GetAttribute(xsinill); + string? nilAttrib = reader.GetAttribute(xsinill); if (string.Equals(nilAttrib, "true", StringComparison.Ordinal)) { // case sensitive true comparison @@ -3321,7 +3321,7 @@ protected virtual void ReadXmlSerializable(XmlReader reader) const string UseDataSetSchemaOnlyString = Keywords.MSD + ":" + Keywords.USEDATASETSCHEMAONLY; if (reader.MoveToAttribute(UseDataSetSchemaOnlyString)) { - string useDataSetSchemaOnly = reader.GetAttribute(UseDataSetSchemaOnlyString); + string? useDataSetSchemaOnly = reader.GetAttribute(UseDataSetSchemaOnlyString); if (string.Equals(useDataSetSchemaOnly, "true", StringComparison.Ordinal) || string.Equals(useDataSetSchemaOnly, "1", StringComparison.Ordinal)) { @@ -3330,14 +3330,14 @@ protected virtual void ReadXmlSerializable(XmlReader reader) else if (!string.Equals(useDataSetSchemaOnly, "false", StringComparison.Ordinal) && !string.Equals(useDataSetSchemaOnly, "0", StringComparison.Ordinal)) { - throw ExceptionBuilder.InvalidAttributeValue(Keywords.USEDATASETSCHEMAONLY, useDataSetSchemaOnly); + throw ExceptionBuilder.InvalidAttributeValue(Keywords.USEDATASETSCHEMAONLY, useDataSetSchemaOnly!); } } const string udtIsWrappedString = Keywords.MSD + ":" + Keywords.UDTCOLUMNVALUEWRAPPED; if (reader.MoveToAttribute(udtIsWrappedString)) { - string _udtIsWrappedString = reader.GetAttribute(udtIsWrappedString); + string? _udtIsWrappedString = reader.GetAttribute(udtIsWrappedString); if (string.Equals(_udtIsWrappedString, "true", StringComparison.Ordinal) || string.Equals(_udtIsWrappedString, "1", StringComparison.Ordinal)) { @@ -3346,7 +3346,7 @@ protected virtual void ReadXmlSerializable(XmlReader reader) else if (!string.Equals(_udtIsWrappedString, "false", StringComparison.Ordinal) && !string.Equals(_udtIsWrappedString, "0", StringComparison.Ordinal)) { - throw ExceptionBuilder.InvalidAttributeValue(Keywords.UDTCOLUMNVALUEWRAPPED, _udtIsWrappedString); + throw ExceptionBuilder.InvalidAttributeValue(Keywords.UDTCOLUMNVALUEWRAPPED, _udtIsWrappedString!); } } } diff --git a/src/libraries/System.Data.Common/src/System/Data/DataTable.cs b/src/libraries/System.Data.Common/src/System/Data/DataTable.cs index ad0a64e64ec419..8b4c1083b60882 100644 --- a/src/libraries/System.Data.Common/src/System/Data/DataTable.cs +++ b/src/libraries/System.Data.Common/src/System/Data/DataTable.cs @@ -5851,7 +5851,7 @@ internal XmlReadMode ReadXml(XmlReader? reader, bool denyResolving) if (!fSchemaFound && Columns.Count == 0) { - XmlNode node = xdoc.ReadNode(reader); + XmlNode node = xdoc.ReadNode(reader)!; topNode.AppendChild(node); } else @@ -5966,7 +5966,7 @@ internal XmlReadMode ReadXml(XmlReader? reader, XmlReadMode mode, bool denyResol if (mode == XmlReadMode.Fragment) { xdoc.AppendChild(xdoc.CreateElement("ds_sqlXmlWraPPeR")); - topNode = xdoc.DocumentElement; + topNode = xdoc.DocumentElement!; } else { @@ -6147,7 +6147,7 @@ internal XmlReadMode ReadXml(XmlReader? reader, XmlReadMode mode, bool denyResol if (mode == XmlReadMode.InferSchema) { //save the node in DOM until the end; - XmlNode node = xdoc.ReadNode(reader); + XmlNode node = xdoc.ReadNode(reader)!; topNode.AppendChild(node); } else @@ -6347,7 +6347,7 @@ internal void ReadXSDSchema(XmlReader reader, bool denyResolving) XmlSchemaSet sSet = new XmlSchemaSet(); while (reader.LocalName == Keywords.XSD_SCHEMA && reader.NamespaceURI == Keywords.XSDNS) { - XmlSchema s = XmlSchema.Read(reader, null); + XmlSchema s = XmlSchema.Read(reader, null)!; sSet.Add(s); //read the end tag ReadEndElement(reader); 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/src/System/Data/SQLTypes/SQLBinary.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBinary.cs index 9d771f0699c4f5..ab176703b4657b 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBinary.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBinary.cs @@ -424,7 +424,7 @@ public override int GetHashCode() void IXmlSerializable.ReadXml(XmlReader reader) { - string isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); + string? isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); if (isNull != null && XmlConvert.ToBoolean(isNull)) { // Read the next value. diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBoolean.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBoolean.cs index 932d7c18457caf..b76f3d16c7d2d2 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBoolean.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBoolean.cs @@ -489,7 +489,7 @@ public override int GetHashCode() void IXmlSerializable.ReadXml(XmlReader reader) { - string isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); + string? isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); if (isNull != null && XmlConvert.ToBoolean(isNull)) { // Read the next value. diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLByte.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLByte.cs index 060ae2b4483c0a..fd353138851358 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLByte.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLByte.cs @@ -498,7 +498,7 @@ public override int GetHashCode() void IXmlSerializable.ReadXml(XmlReader reader) { - string isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); + string? isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); if (isNull != null && XmlConvert.ToBoolean(isNull)) { // Read the next value. diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBytes.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBytes.cs index 14d1fa1e53dfec..caeff12be45661 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBytes.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLBytes.cs @@ -498,7 +498,7 @@ void IXmlSerializable.ReadXml(XmlReader r) { byte[]? value = null; - string isNull = r.GetAttribute("nil", XmlSchema.InstanceNamespace); + string? isNull = r.GetAttribute("nil", XmlSchema.InstanceNamespace); if (isNull != null && XmlConvert.ToBoolean(isNull)) { diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLChars.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLChars.cs index b7ae23b5f3b42c..dfb18b73ab6529 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLChars.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLChars.cs @@ -496,7 +496,7 @@ void IXmlSerializable.ReadXml(XmlReader r) { char[]? value = null; - string isNull = r.GetAttribute("nil", XmlSchema.InstanceNamespace); + string? isNull = r.GetAttribute("nil", XmlSchema.InstanceNamespace); if (isNull != null && XmlConvert.ToBoolean(isNull)) { diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDateTime.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDateTime.cs index 6126c74a8eb788..2e08f0eb4d20e5 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDateTime.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDateTime.cs @@ -645,7 +645,7 @@ public override int GetHashCode() void IXmlSerializable.ReadXml(XmlReader reader) { - string isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); + string? isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); if (isNull != null && XmlConvert.ToBoolean(isNull)) { // Read the next value. diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDecimal.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDecimal.cs index 2fd011c00afec3..0297adacd4f57c 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDecimal.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDecimal.cs @@ -3334,7 +3334,7 @@ public override int GetHashCode() void IXmlSerializable.ReadXml(XmlReader reader) { - string isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); + string? isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); if (isNull != null && XmlConvert.ToBoolean(isNull)) { // Read the next value. diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDouble.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDouble.cs index 968f5cb25199b8..aa8ea8cb9dd257 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDouble.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLDouble.cs @@ -414,7 +414,7 @@ public override int GetHashCode() void IXmlSerializable.ReadXml(XmlReader reader) { - string isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); + string? isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); if (isNull != null && XmlConvert.ToBoolean(isNull)) { // Read the next value. diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLGuid.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLGuid.cs index 0a8770867c97a9..263cf292444095 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLGuid.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLGuid.cs @@ -305,7 +305,7 @@ public override int GetHashCode() void IXmlSerializable.ReadXml(XmlReader reader) { - string isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); + string? isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); if (isNull != null && XmlConvert.ToBoolean(isNull)) { // Read the next value. diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt16.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt16.cs index 3444f1723d16c9..7da5e90509aa0d 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt16.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt16.cs @@ -499,7 +499,7 @@ public override int GetHashCode() void IXmlSerializable.ReadXml(XmlReader reader) { - string isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); + string? isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); if (isNull != null && XmlConvert.ToBoolean(isNull)) { // Read the next value. diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt32.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt32.cs index c9c06b23e34f42..c02908e39f7505 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt32.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt32.cs @@ -514,7 +514,7 @@ public override int GetHashCode() void IXmlSerializable.ReadXml(XmlReader reader) { - string isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); + string? isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); if (isNull != null && XmlConvert.ToBoolean(isNull)) { // Read the next value. diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt64.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt64.cs index c4508d6a5b8034..d65fcd73f6c009 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt64.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLInt64.cs @@ -573,7 +573,7 @@ public override int GetHashCode() void IXmlSerializable.ReadXml(XmlReader reader) { - string isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); + string? isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); if (isNull != null && XmlConvert.ToBoolean(isNull)) { // Read the next value. diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLMoney.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLMoney.cs index 5e722dee6d7322..83ecd1c80166e3 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLMoney.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLMoney.cs @@ -564,7 +564,7 @@ public override int GetHashCode() void IXmlSerializable.ReadXml(XmlReader reader) { - string isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); + string? isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); if (isNull != null && XmlConvert.ToBoolean(isNull)) { // Read the next value. diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLSingle.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLSingle.cs index 8798deb096385b..9e61441618cc46 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLSingle.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLSingle.cs @@ -424,7 +424,7 @@ public override int GetHashCode() void IXmlSerializable.ReadXml(XmlReader reader) { - string isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); + string? isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); if (isNull != null && XmlConvert.ToBoolean(isNull)) { // Read the next value. diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLString.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLString.cs index b85a9137f7591f..e16012f11647bb 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLString.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SQLString.cs @@ -922,7 +922,7 @@ public override int GetHashCode() void IXmlSerializable.ReadXml(XmlReader reader) { - string isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); + string? isNull = reader.GetAttribute("nil", XmlSchema.InstanceNamespace); if (isNull != null && XmlConvert.ToBoolean(isNull)) { // Read the next value. diff --git a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SqlXml.cs b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SqlXml.cs index 7af1333bc70c24..8c6726a6dbe24b 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SqlXml.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SQLTypes/SqlXml.cs @@ -220,7 +220,7 @@ private Stream CreateMemoryStreamFromXmlReader(XmlReader reader) void IXmlSerializable.ReadXml(XmlReader r) { - string isNull = r.GetAttribute("nil", XmlSchema.InstanceNamespace); + string? isNull = r.GetAttribute("nil", XmlSchema.InstanceNamespace); if (isNull != null && XmlConvert.ToBoolean(isNull)) { diff --git a/src/libraries/System.Data.Common/src/System/Data/SimpleType.cs b/src/libraries/System.Data.Common/src/System/Data/SimpleType.cs index c2393282fafffb..63dbd993fea709 100644 --- a/src/libraries/System.Data.Common/src/System/Data/SimpleType.cs +++ b/src/libraries/System.Data.Common/src/System/Data/SimpleType.cs @@ -19,15 +19,15 @@ internal sealed class SimpleType : ISerializable private int _length = -1; private int _minLength = -1; private int _maxLength = -1; - private string _pattern = string.Empty; + private string? _pattern = string.Empty; private string _ns = string.Empty; // my ns - private string _maxExclusive = string.Empty; - private string _maxInclusive = string.Empty; - private string _minExclusive = string.Empty; - private string _minInclusive = string.Empty; + private string? _maxExclusive = string.Empty; + private string? _maxInclusive = string.Empty; + private string? _minExclusive = string.Empty; + private string? _minInclusive = string.Empty; - internal string _enumeration = string.Empty; + internal string? _enumeration = string.Empty; internal SimpleType(string baseType) { @@ -82,7 +82,7 @@ internal void LoadTypeValues(XmlSchemaSimpleType node) if (_baseType == null || _baseType.Length == 0) { - _baseType = content.BaseType.Name; + _baseType = content.BaseType!.Name; _xmlBaseType = null; } diff --git a/src/libraries/System.Data.Common/src/System/Data/xmlsaver.cs b/src/libraries/System.Data.Common/src/System/Data/xmlsaver.cs index 0d5f4952a27713..7307670eceb503 100644 --- a/src/libraries/System.Data.Common/src/System/Data/xmlsaver.cs +++ b/src/libraries/System.Data.Common/src/System/Data/xmlsaver.cs @@ -1189,7 +1189,7 @@ internal XmlElement HandleRelation(DataRelation rel, XmlDocument dc) private static XmlElement? FindSimpleType(XmlElement schema, string name) { - for (XmlNode n = schema.FirstChild; n != null; n = n.NextSibling) + for (XmlNode? n = schema.FirstChild; n != null; n = n.NextSibling) { if (n is XmlElement) { @@ -1558,7 +1558,7 @@ internal void AppendChildWithoutRef(XmlElement node, string Namespace, XmlElemen if (node == null) return null; - for (XmlNode n = node.FirstChild; n != null; n = n.NextSibling) + for (XmlNode? n = node.FirstChild; n != null; n = n.NextSibling) { if (!(n is XmlElement)) continue; @@ -3134,12 +3134,12 @@ public override void WriteEndDocument() _xmltextWriter.WriteEndDocument(); } - public override void WriteDocType(string name, string pubid, string sysid, string subset) + public override void WriteDocType(string name, string? pubid, string? sysid, string? subset) { _xmltextWriter.WriteDocType(name, pubid, sysid, subset); } - public override void WriteStartElement(string prefix, string localName, string ns) + public override void WriteStartElement(string? prefix, string localName, string? ns) { _xmltextWriter.WriteStartElement(prefix, localName, ns); } @@ -3154,7 +3154,7 @@ public override void WriteFullEndElement() _xmltextWriter.WriteFullEndElement(); } - public override void WriteStartAttribute(string prefix, string localName, string ns) + public override void WriteStartAttribute(string? prefix, string localName, string? ns) { _xmltextWriter.WriteStartAttribute(prefix, localName, ns); } @@ -3164,17 +3164,17 @@ public override void WriteEndAttribute() _xmltextWriter.WriteEndAttribute(); } - public override void WriteCData(string text) + public override void WriteCData(string? text) { _xmltextWriter.WriteCData(text); } - public override void WriteComment(string text) + public override void WriteComment(string? text) { _xmltextWriter.WriteComment(text); } - public override void WriteProcessingInstruction(string name, string text) + public override void WriteProcessingInstruction(string name, string? text) { _xmltextWriter.WriteProcessingInstruction(name, text); } @@ -3189,12 +3189,12 @@ public override void WriteCharEntity(char ch) _xmltextWriter.WriteCharEntity(ch); } - public override void WriteWhitespace(string ws) + public override void WriteWhitespace(string? ws) { _xmltextWriter.WriteWhitespace(ws); } - public override void WriteString(string text) + public override void WriteString(string? text) { _xmltextWriter.WriteString(text); } @@ -3252,12 +3252,12 @@ public override void WriteName(string name) _xmltextWriter.WriteName(name); } - public override void WriteQualifiedName(string localName, string ns) + public override void WriteQualifiedName(string localName, string? ns) { _xmltextWriter.WriteQualifiedName(localName, ns); } - public override string LookupPrefix(string ns) + public override string? LookupPrefix(string ns) { return _xmltextWriter.LookupPrefix(ns); } @@ -3270,7 +3270,7 @@ public override XmlSpace XmlSpace } } - public override string XmlLang + public override string? XmlLang { get { @@ -3300,7 +3300,7 @@ private DataTextReader(XmlReader input) _xmlreader = input; } - public override XmlReaderSettings Settings + public override XmlReaderSettings? Settings { get { @@ -3360,7 +3360,7 @@ public override int Depth get { return _xmlreader.Depth; } } - public override string BaseURI + public override string? BaseURI { get { return _xmlreader.BaseURI; } } @@ -3392,12 +3392,12 @@ public override string XmlLang public override int AttributeCount { get { return _xmlreader.AttributeCount; } } - public override string GetAttribute(string name) + public override string? GetAttribute(string name) { return _xmlreader.GetAttribute(name); } - public override string GetAttribute(string localName, string namespaceURI) + public override string? GetAttribute(string localName, string? namespaceURI) { return _xmlreader.GetAttribute(localName, namespaceURI); } @@ -3412,7 +3412,7 @@ public override bool MoveToAttribute(string name) return _xmlreader.MoveToAttribute(name); } - public override bool MoveToAttribute(string localName, string namespaceURI) + public override bool MoveToAttribute(string localName, string? namespaceURI) { return _xmlreader.MoveToAttribute(localName, namespaceURI); } @@ -3472,7 +3472,7 @@ public override XmlNameTable NameTable get { return _xmlreader.NameTable; } } - public override string LookupNamespace(string prefix) + public override string? LookupNamespace(string prefix) { return _xmlreader.LookupNamespace(prefix); } diff --git a/src/libraries/System.Data.Common/src/System/Xml/BaseTreeIterator.cs b/src/libraries/System.Data.Common/src/System/Xml/BaseTreeIterator.cs index 74a17212360660..ed8b41d8a8be7b 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/BaseTreeIterator.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/BaseTreeIterator.cs @@ -1,8 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -// TODO: Enable after System.Private.Xml is annotated -#nullable disable +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; namespace System.Xml { @@ -16,11 +16,15 @@ internal BaseTreeIterator(DataSetMapper mapper) this.mapper = mapper; } - internal abstract XmlNode CurrentNode { get; } + internal abstract XmlNode? CurrentNode { get; } + [MemberNotNullWhen(true, nameof(CurrentNode))] internal abstract bool Next(); + + [MemberNotNullWhen(true, nameof(CurrentNode))] internal abstract bool NextRight(); + [MemberNotNullWhen(true, nameof(CurrentNode))] internal bool NextRowElement() { while (Next()) @@ -33,6 +37,7 @@ internal bool NextRowElement() return false; } + [MemberNotNullWhen(true, nameof(CurrentNode))] internal bool NextRightRowElement() { if (NextRight()) @@ -47,10 +52,10 @@ internal bool NextRightRowElement() } // Returns true if the current node is on a row element (head of a region) + [MemberNotNullWhen(true, nameof(CurrentNode))] internal bool OnRowElement() { - XmlBoundElement be = CurrentNode as XmlBoundElement; - return (be != null) && (be.Row != null); + return CurrentNode is XmlBoundElement be && be.Row != null; } } } diff --git a/src/libraries/System.Data.Common/src/System/Xml/DataDocumentXPathNavigator.cs b/src/libraries/System.Data.Common/src/System/Xml/DataDocumentXPathNavigator.cs index ec88cf99e8cd39..1fc9394dd1253c 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/DataDocumentXPathNavigator.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/DataDocumentXPathNavigator.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -// TODO: Enable after System.Private.Xml is annotated -#nullable disable - using System.Xml.XPath; #pragma warning disable 0618 // ignore obsolete warning about XmlDataDocument @@ -50,7 +47,7 @@ public override string Value get { XPathNodeType xnt = _curNode.NodeType; - return xnt == XPathNodeType.Element || xnt == XPathNodeType.Root ? _curNode.InnerText : _curNode.Value; + return xnt == XPathNodeType.Element || xnt == XPathNodeType.Root ? _curNode.InnerText : _curNode.Value!; } } @@ -73,7 +70,7 @@ public override string GetAttribute(string localName, string namespaceURI) } _temp.MoveTo(_curNode); - return _temp.MoveToAttribute(localName, namespaceURI) ? _temp.Value : string.Empty; + return _temp.MoveToAttribute(localName, namespaceURI) ? _temp.Value! : string.Empty; } public override string GetNamespace(string name) => _curNode.GetNamespace(name); @@ -129,7 +126,7 @@ public override bool MoveTo(XPathNavigator other) { if (other != null) { - DataDocumentXPathNavigator otherDataDocXPathNav = other as DataDocumentXPathNavigator; + DataDocumentXPathNavigator? otherDataDocXPathNav = other as DataDocumentXPathNavigator; if (otherDataDocXPathNav != null && _curNode.MoveTo(otherDataDocXPathNav.CurNode)) { _doc = _curNode.Document; @@ -146,7 +143,7 @@ public override bool IsSamePosition(XPathNavigator other) { if (other != null) { - DataDocumentXPathNavigator otherDataDocXPathNav = other as DataDocumentXPathNavigator; + DataDocumentXPathNavigator? otherDataDocXPathNav = other as DataDocumentXPathNavigator; if (otherDataDocXPathNav != null && _doc == otherDataDocXPathNav.Document && _curNode.IsSamePosition(otherDataDocXPathNav.CurNode)) { @@ -158,16 +155,16 @@ public override bool IsSamePosition(XPathNavigator other) //the function is only called for XPathNodeList enumerate nodes and // shouldn't be promoted to frequently use because it will cause foliation - XmlNode IHasXmlNode.GetNode() => _curNode.Node; + XmlNode IHasXmlNode.GetNode() => _curNode.Node!; - public override XmlNodeOrder ComparePosition(XPathNavigator other) + public override XmlNodeOrder ComparePosition(XPathNavigator? other) { if (other == null) { return XmlNodeOrder.Unknown; // this is what XPathDocument does. } - DataDocumentXPathNavigator otherDataDocXPathNav = other as DataDocumentXPathNavigator; + DataDocumentXPathNavigator? otherDataDocXPathNav = other as DataDocumentXPathNavigator; return otherDataDocXPathNav == null || otherDataDocXPathNav.Document != _doc ? XmlNodeOrder.Unknown : diff --git a/src/libraries/System.Data.Common/src/System/Xml/DataPointer.cs b/src/libraries/System.Data.Common/src/System/Xml/DataPointer.cs index 768834a9cc3d32..d04cd7d46fed03 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/DataPointer.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/DataPointer.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -// TODO: Enable after System.Private.Xml is annotated -#nullable disable - using System.Data; using System.Diagnostics; @@ -15,7 +12,7 @@ internal sealed class DataPointer : IXmlDataVirtualNode { private XmlDataDocument _doc; private XmlNode _node; - private DataColumn _column; + private DataColumn? _column; private bool _fOnValue; private bool _bNeedFoliate; private bool _isInUse; @@ -45,9 +42,9 @@ internal DataPointer(DataPointer pointer) internal void AddPointer() => _doc.AddPointer(this); // Returns the row element of the region that the pointer points into - private XmlBoundElement GetRowElement() + private XmlBoundElement? GetRowElement() { - XmlBoundElement rowElem; + XmlBoundElement? rowElem; if (_column != null) { rowElem = _node as XmlBoundElement; @@ -60,11 +57,11 @@ private XmlBoundElement GetRowElement() return rowElem; } - private DataRow Row + private DataRow? Row { get { - XmlBoundElement rowElem = GetRowElement(); + XmlBoundElement? rowElem = GetRowElement(); if (rowElem == null) { return null; @@ -103,7 +100,7 @@ private void MoveTo(XmlNode node) AssertValid(); } - private void MoveTo(XmlNode node, DataColumn column, bool fOnValue) + private void MoveTo(XmlNode node, DataColumn? column, bool fOnValue) { // You should not move outside of this document Debug.Assert(node == _doc || node.OwnerDocument == _doc); @@ -114,7 +111,7 @@ private void MoveTo(XmlNode node, DataColumn column, bool fOnValue) AssertValid(); } - private DataColumn NextColumn(DataRow row, DataColumn col, bool fAttribute, bool fNulls) + private DataColumn? NextColumn(DataRow row, DataColumn? col, bool fAttribute, bool fNulls) { if (row.RowState == DataRowState.Deleted) { @@ -139,9 +136,9 @@ private DataColumn NextColumn(DataRow row, DataColumn col, bool fAttribute, bool return null; } - private DataColumn NthColumn(DataRow row, bool fAttribute, int iColumn, bool fNulls) + private DataColumn? NthColumn(DataRow row, bool fAttribute, int iColumn, bool fNulls) { - DataColumn c = null; + DataColumn? c = null; while ((c = NextColumn(row, c, fAttribute, fNulls)) != null) { if (iColumn == 0) @@ -156,7 +153,7 @@ private DataColumn NthColumn(DataRow row, bool fAttribute, int iColumn, bool fNu private int ColumnCount(DataRow row, bool fAttribute, bool fNulls) { - DataColumn c = null; + DataColumn? c = null; int count = 0; while ((c = NextColumn(row, c, fAttribute, fNulls)) != null) { @@ -187,7 +184,7 @@ internal bool MoveToFirstChild() else if (!IsFoliated(_node)) { // find virtual column elements first - DataColumn c = NextColumn(Row, null, false, false); + DataColumn? c = NextColumn(Row!, null, false, false); if (c != null) { MoveTo(_node, c, _doc.IsTextOnly(c)); @@ -196,7 +193,7 @@ internal bool MoveToFirstChild() } // look for anything - XmlNode n = _doc.SafeFirstChild(_node); + XmlNode? n = _doc.SafeFirstChild(_node); if (n != null) { MoveTo(n); @@ -219,14 +216,14 @@ internal bool MoveToNextSibling() return false; } - DataColumn c = NextColumn(Row, _column, false, false); + DataColumn? c = NextColumn(Row!, _column, false, false); if (c != null) { MoveTo(_node, c, false); return true; } - XmlNode n = _doc.SafeFirstChild(_node); + XmlNode? n = _doc.SafeFirstChild(_node); if (n != null) { MoveTo(n); @@ -235,7 +232,7 @@ internal bool MoveToNextSibling() } else { - XmlNode n = _doc.SafeNextSibling(_node); + XmlNode? n = _doc.SafeNextSibling(_node); if (n != null) { MoveTo(n); @@ -269,7 +266,7 @@ internal bool MoveToParent() } else { - XmlNode n = _node.ParentNode; + XmlNode? n = _node.ParentNode; if (n != null) { MoveTo(n); @@ -298,7 +295,7 @@ internal bool MoveToOwnerElement() } else if (_node.NodeType == XmlNodeType.Attribute) { - XmlNode n = ((XmlAttribute)_node).OwnerElement; + XmlNode? n = ((XmlAttribute)_node).OwnerElement; if (n != null) { MoveTo(n, null, false); @@ -323,11 +320,11 @@ internal int AttributeCount { if (!IsFoliated(_node)) { - return ColumnCount(Row, true, false); + return ColumnCount(Row!, true, false); } else { - return _node.Attributes.Count; + return _node.Attributes!.Count; } } } @@ -350,7 +347,7 @@ internal bool MoveToAttribute(int i) { if (!IsFoliated(_node)) { - DataColumn c = NthColumn(Row, true, i, false); + DataColumn? c = NthColumn(Row!, true, i, false); if (c != null) { MoveTo(_node, c, false); @@ -359,7 +356,7 @@ internal bool MoveToAttribute(int i) } else { - XmlNode n = _node.Attributes.Item(i); + XmlNode? n = _node.Attributes!.Item(i); if (n != null) { MoveTo(n, null, false); @@ -551,7 +548,7 @@ internal string Prefix } } - internal string Value + internal string? Value { get { @@ -567,7 +564,7 @@ internal string Value } else if (_column.ColumnMapping == MappingType.Attribute || _fOnValue) { - DataRow row = Row; + DataRow row = Row!; DataRowVersion rowVersion = (row.RowState == DataRowState.Detached) ? DataRowVersion.Proposed : DataRowVersion.Current; object value = row[_column, rowVersion]; if (!Convert.IsDBNull(value)) @@ -590,7 +587,7 @@ bool IXmlDataVirtualNode.IsOnNode(XmlNode nodeToCheck) return nodeToCheck == _node; } - bool IXmlDataVirtualNode.IsOnColumn(DataColumn col) + bool IXmlDataVirtualNode.IsOnColumn(DataColumn? col) { RealFoliate(); return col == _column; @@ -651,17 +648,17 @@ internal void RealFoliate() return; } - XmlNode n = null; + XmlNode? n = null; - if (_doc.IsTextOnly(_column)) + if (_doc.IsTextOnly(_column!)) { n = _node.FirstChild; } else { - if (_column.ColumnMapping == MappingType.Attribute) + if (_column!.ColumnMapping == MappingType.Attribute) { - n = _node.Attributes.GetNamedItem(_column.EncodedColumnName, _column.Namespace); + n = _node.Attributes!.GetNamedItem(_column.EncodedColumnName, _column.Namespace); } else { @@ -693,7 +690,7 @@ internal void RealFoliate() } //for the 6 properties below, only when the this.column == null that the nodetype could be XmlDeclaration node - internal string PublicId + internal string? PublicId { get { @@ -720,7 +717,7 @@ internal string PublicId } } - internal string SystemId + internal string? SystemId { get { @@ -747,7 +744,7 @@ internal string SystemId } } - internal string InternalSubset + internal string? InternalSubset { get { @@ -760,18 +757,18 @@ internal string InternalSubset } } - internal XmlDeclaration Declaration + internal XmlDeclaration? Declaration { get { - XmlNode child = _doc.SafeFirstChild(_doc); + XmlNode? child = _doc.SafeFirstChild(_doc); if (child != null && child.NodeType == XmlNodeType.XmlDeclaration) return (XmlDeclaration)child; return null; } } - internal string Encoding + internal string? Encoding { get { @@ -782,7 +779,7 @@ internal string Encoding } else if (NodeType == XmlNodeType.Document) { - XmlDeclaration dec = Declaration; + XmlDeclaration? dec = Declaration; if (dec != null) { return dec.Encoding; @@ -792,7 +789,7 @@ internal string Encoding } } - internal string Standalone + internal string? Standalone { get { @@ -803,7 +800,7 @@ internal string Standalone } else if (NodeType == XmlNodeType.Document) { - XmlDeclaration dec = Declaration; + XmlDeclaration? dec = Declaration; if (dec != null) { return dec.Standalone; @@ -813,7 +810,7 @@ internal string Standalone } } - internal string Version + internal string? Version { get { @@ -824,7 +821,7 @@ internal string Version } else if (NodeType == XmlNodeType.Document) { - XmlDeclaration dec = Declaration; + XmlDeclaration? dec = Declaration; if (dec != null) return dec.Version; } @@ -839,10 +836,10 @@ private void AssertValid() if (_column != null) { // We must be on a de-foliated region - XmlBoundElement rowElem = _node as XmlBoundElement; + XmlBoundElement? rowElem = _node as XmlBoundElement; Debug.Assert(rowElem != null); - DataRow row = rowElem.Row; + DataRow? row = rowElem.Row; Debug.Assert(row != null); ElementState state = rowElem.ElementState; @@ -861,7 +858,7 @@ private void AssertValid() internal void SetNoLongerUse() { - _node = null; + _node = null!; _column = null; _fOnValue = false; _bNeedFoliate = false; diff --git a/src/libraries/System.Data.Common/src/System/Xml/DataSetMappper.cs b/src/libraries/System.Data.Common/src/System/Xml/DataSetMappper.cs index 95a2e5014b281b..55480193f85f2d 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/DataSetMappper.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/DataSetMappper.cs @@ -1,12 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -// TODO: Enable after System.Private.Xml is annotated -#nullable disable - using System.Collections; using System.Data; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; #pragma warning disable 0618 // ignore obsolete warning about XmlDataDocument @@ -25,8 +23,8 @@ internal sealed class DataSetMapper private Hashtable _tableSchemaMap; // maps an string (currently this is localName:nsURI) to a DataTable. Used to quickly find if a bound-elem matches any data-table metadata.. private Hashtable _columnSchemaMap; // maps a string (table localName:nsURI) to a Hashtable. The 2nd hastable (the one that is stored as data in columnSchemaMap, maps a string to a DataColumn. - private XmlDataDocument _doc; // The document this mapper is related to - private DataSet _dataSet; // The dataset this mapper is related to + private XmlDataDocument? _doc; // The document this mapper is related to + private DataSet? _dataSet; // The dataset this mapper is related to internal const string strReservedXmlns = "http://www.w3.org/2000/xmlns/"; internal DataSetMapper() @@ -66,7 +64,7 @@ internal void SetupMapping(XmlDataDocument xd, DataSet ds) internal DataTable SearchMatchingTableSchema(string localName, string namespaceURI) { object tid = GetIdentity(localName, namespaceURI); - return (DataTable)(_tableSchemaMap[tid]); + return (DataTable)(_tableSchemaMap[tid]!); } // SearchMatchingTableSchema function works only when the elem has not been bound to a DataRow. If you want to get the table associated w/ an element after @@ -86,7 +84,7 @@ internal DataTable SearchMatchingTableSchema(string localName, string namespaceU // a column from the parent region table, then the node is NOT associated w/ a DataTable (it is a potential DataColumn in the parent region) // 3.3.2 Else the node is a row-element (and associated w/ a DataTable / DataRow ) // - internal DataTable SearchMatchingTableSchema(XmlBoundElement rowElem, XmlBoundElement elem) + internal DataTable? SearchMatchingTableSchema(XmlBoundElement? rowElem, XmlBoundElement elem) { Debug.Assert(elem != null); @@ -104,7 +102,7 @@ internal DataTable SearchMatchingTableSchema(XmlBoundElement rowElem, XmlBoundEl // Currently we expect we map things from top of the tree to the bottom Debug.Assert(rowElem.Row != null); - DataColumn col = GetColumnSchemaForNode(rowElem, elem); + DataColumn? col = GetColumnSchemaForNode(rowElem, elem); if (col == null) { return t; @@ -135,7 +133,7 @@ internal DataTable SearchMatchingTableSchema(XmlBoundElement rowElem, XmlBoundEl } } - for (XmlNode n = elem.FirstChild; n != null; n = n.NextSibling) + for (XmlNode? n = elem.FirstChild; n != null; n = n.NextSibling) { if (n.NodeType == XmlNodeType.Element) { @@ -148,7 +146,7 @@ internal DataTable SearchMatchingTableSchema(XmlBoundElement rowElem, XmlBoundEl return null; } - internal DataColumn GetColumnSchemaForNode(XmlBoundElement rowElem, XmlNode node) + internal DataColumn? GetColumnSchemaForNode(XmlBoundElement rowElem, XmlNode node) { Debug.Assert(rowElem != null); // The caller must make sure that node is not a row-element @@ -157,10 +155,10 @@ internal DataColumn GetColumnSchemaForNode(XmlBoundElement rowElem, XmlNode node object tid = GetIdentity(rowElem.LocalName, rowElem.NamespaceURI); object cid = GetIdentity(node.LocalName, node.NamespaceURI); - Hashtable columns = (Hashtable)_columnSchemaMap[tid]; + Hashtable? columns = (Hashtable?)_columnSchemaMap[tid]; if (columns != null) { - DataColumn col = (DataColumn)(columns[cid]); + DataColumn? col = (DataColumn?)(columns[cid]); if (col == null) { return null; @@ -183,9 +181,9 @@ internal DataColumn GetColumnSchemaForNode(XmlBoundElement rowElem, XmlNode node } return null; } - internal DataTable GetTableSchemaForElement(XmlElement elem) + internal DataTable? GetTableSchemaForElement(XmlElement elem) { - XmlBoundElement be = elem as XmlBoundElement; + XmlBoundElement? be = elem as XmlBoundElement; if (be == null) { return null; @@ -194,7 +192,7 @@ internal DataTable GetTableSchemaForElement(XmlElement elem) return GetTableSchemaForElement(be); } - internal DataTable GetTableSchemaForElement(XmlBoundElement be) => be.Row?.Table; + internal DataTable? GetTableSchemaForElement(XmlBoundElement be) => be.Row?.Table; internal static bool IsNotMapped(DataColumn c) => c.ColumnMapping == MappingType.Hidden; @@ -204,18 +202,18 @@ internal DataTable GetTableSchemaForElement(XmlElement elem) // XmlElement e = be; // GetRowFromElement( be ); // Calls GetRowFromElement( XmlBoundElement ) // GetRowFromElement( e ); // Calls GetRowFromElement( XmlElement ), in spite of e beeing an instance of XmlBoundElement - internal DataRow GetRowFromElement(XmlElement e) => (e as XmlBoundElement)?.Row; + internal DataRow? GetRowFromElement(XmlElement? e) => (e as XmlBoundElement)?.Row; - internal DataRow GetRowFromElement(XmlBoundElement be) => be.Row; + internal DataRow? GetRowFromElement(XmlBoundElement be) => be.Row; // Get the row-elem associatd w/ the region node is in. // If node is in a region not mapped (like document element node) the function returns false and sets elem to null) // This function does not work if the region is not associated w/ a DataRow (it uses DataRow association to know what is the row element associated w/ the region) - internal bool GetRegion(XmlNode node, out XmlBoundElement rowElem) + internal bool GetRegion(XmlNode? node, [NotNullWhen(true)] out XmlBoundElement? rowElem) { while (node != null) { - XmlBoundElement be = node as XmlBoundElement; + XmlBoundElement? be = node as XmlBoundElement; // Break if found a region if (be != null && GetRowFromElement(be) != null) { @@ -247,7 +245,7 @@ internal bool IsRegionRadical(XmlBoundElement rowElem) return true; } - DataTable table = GetTableSchemaForElement(rowElem); + DataTable table = GetTableSchemaForElement(rowElem)!; DataColumnCollection columns = table.Columns; int iColumn = 0; @@ -264,7 +262,7 @@ internal bool IsRegionRadical(XmlBoundElement rowElem) } // only mapped attrs are valid - DataColumn schema = GetColumnSchemaForNode(rowElem, attr); + DataColumn? schema = GetColumnSchemaForNode(rowElem, attr); if (schema == null) { return false; @@ -277,7 +275,7 @@ internal bool IsRegionRadical(XmlBoundElement rowElem) } // must have exactly one text node (XmlNodeType.Text) child - XmlNode fc = attr.FirstChild; + XmlNode? fc = attr.FirstChild; if (fc == null || fc.NodeType != XmlNodeType.Text || fc.NextSibling != null) { return false; @@ -286,7 +284,7 @@ internal bool IsRegionRadical(XmlBoundElement rowElem) // check column elements iColumn = 0; - XmlNode n = rowElem.FirstChild; + XmlNode? n = rowElem.FirstChild; for (; n != null; n = n.NextSibling) { // only elements can exist in radically structured data @@ -294,7 +292,7 @@ internal bool IsRegionRadical(XmlBoundElement rowElem) { return false; } - XmlElement e = n as XmlElement; + XmlElement? e = n as XmlElement; // only checking for column mappings in this loop if (GetRowFromElement(e) != null) @@ -303,7 +301,7 @@ internal bool IsRegionRadical(XmlBoundElement rowElem) } // element's must have schema to be radically structured - DataColumn schema = GetColumnSchemaForNode(rowElem, e); + DataColumn? schema = GetColumnSchemaForNode(rowElem, e!); if (schema == null) { return false; @@ -322,7 +320,7 @@ internal bool IsRegionRadical(XmlBoundElement rowElem) } // must have exactly one text node child - XmlNode fc = e.FirstChild; + XmlNode? fc = e.FirstChild; if (fc == null || fc.NodeType != XmlNodeType.Text || fc.NextSibling != null) { return false; @@ -339,7 +337,7 @@ internal bool IsRegionRadical(XmlBoundElement rowElem) } // element's must be regions in order to be radially structured - DataRow row = GetRowFromElement((XmlElement)n); + DataRow? row = GetRowFromElement((XmlElement?)n); if (row == null) { return false; @@ -356,11 +354,11 @@ private void AddTableSchema(DataTable table) } private void AddColumnSchema(DataColumn col) { - DataTable table = col.Table; + DataTable table = col.Table!; object idTable = GetIdentity(table.EncodedTableName, table.Namespace); object idColumn = GetIdentity(col.EncodedColumnName, col.Namespace); - Hashtable columns = (Hashtable)_columnSchemaMap[idTable]; + Hashtable? columns = (Hashtable?)_columnSchemaMap[idTable]; if (columns == null) { columns = new Hashtable(); diff --git a/src/libraries/System.Data.Common/src/System/Xml/IXmlDataVirtualNode.cs b/src/libraries/System.Data.Common/src/System/Xml/IXmlDataVirtualNode.cs index 18dbd1ef9f3dbe..81052d77149a89 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/IXmlDataVirtualNode.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/IXmlDataVirtualNode.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -// TODO: Enable after System.Private.Xml is annotated -#nullable disable - using System.Data; namespace System.Xml @@ -11,7 +8,7 @@ namespace System.Xml internal interface IXmlDataVirtualNode { bool IsOnNode(XmlNode nodeToCheck); - bool IsOnColumn(DataColumn col); + bool IsOnColumn(DataColumn? col); bool IsInUse(); void OnFoliated(XmlNode foliatedNode); } diff --git a/src/libraries/System.Data.Common/src/System/Xml/RegionIterator.cs b/src/libraries/System.Data.Common/src/System/Xml/RegionIterator.cs index 5be84261bcd1de..1a6545e1ea6913 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/RegionIterator.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/RegionIterator.cs @@ -1,10 +1,8 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -// TODO: Enable after System.Private.Xml is annotated -#nullable disable - using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Text; #pragma warning disable 618 // ignore obsolete warning about XmlDataDocument @@ -29,11 +27,12 @@ internal RegionIterator(XmlBoundElement rowElement) : base(((XmlDataDocument)(ro _currentNode = rowElement; } - internal override XmlNode CurrentNode => _currentNode; + internal override XmlNode? CurrentNode => _currentNode; + [MemberNotNullWhen(true, nameof(CurrentNode))] internal override bool Next() { - XmlNode nextNode; + XmlNode? nextNode; ElementState oldState = _rowElement.ElementState; // We do not want to cause any foliation w/ this iterator or use this iterator once the region was defoliated @@ -46,6 +45,7 @@ internal override bool Next() if (nextNode != null) { _currentNode = nextNode; + Debug.Assert(CurrentNode != null); // If we have been defoliated, we should have stayed that way Debug.Assert((oldState == ElementState.Defoliated) ? (_rowElement.ElementState == ElementState.Defoliated) : true); // Rollback foliation @@ -56,12 +56,13 @@ internal override bool Next() return NextRight(); } + [MemberNotNullWhen(true, nameof(CurrentNode))] internal override bool NextRight() { // Make sure we do not get past the rowElement if we call NextRight on a just initialized iterator and rowElement has no children if (_currentNode == _rowElement) { - _currentNode = null; + _currentNode = null!; return false; } @@ -70,7 +71,7 @@ internal override bool NextRight() // We do not want to cause any foliation w/ this iterator or use this iterator once the region was defoliated Debug.Assert(oldState != ElementState.None); - XmlNode nextNode = _currentNode.NextSibling; + XmlNode? nextNode = _currentNode.NextSibling; if (nextNode != null) { @@ -79,19 +80,20 @@ internal override bool NextRight() Debug.Assert((oldState == ElementState.Defoliated) ? (_rowElement.ElementState == ElementState.Defoliated) : true); // Rollback foliation _rowElement.ElementState = oldState; + Debug.Assert(CurrentNode != null); return true; } // No next sibling, try the first sibling of from the parent chain nextNode = _currentNode; - while (nextNode != _rowElement && nextNode.NextSibling == null) + while (nextNode != _rowElement && nextNode!.NextSibling == null) { nextNode = nextNode.ParentNode; } if (nextNode == _rowElement) { - _currentNode = null; + _currentNode = null!; // If we have been defoliated, we should have stayed that way Debug.Assert((oldState == ElementState.Defoliated) ? (_rowElement.ElementState == ElementState.Defoliated) : true); @@ -100,19 +102,21 @@ internal override bool NextRight() return false; } + Debug.Assert(nextNode.NextSibling != null); _currentNode = nextNode.NextSibling; - Debug.Assert(_currentNode != null); // If we have been defoliated, we should have stayed that way Debug.Assert((oldState == ElementState.Defoliated) ? (_rowElement.ElementState == ElementState.Defoliated) : true); // Rollback foliation _rowElement.ElementState = oldState; + Debug.Assert(CurrentNode != null); return true; } // Get the initial text value for the current node. You should be positioned on the node (element) for // which to get the initial text value, not on the text node. + [MemberNotNullWhen(true, nameof(CurrentNode))] internal bool NextInitialTextLikeNodes(out string value) { Debug.Assert(CurrentNode != null); @@ -133,7 +137,7 @@ internal bool NextInitialTextLikeNodes(out string value) // We do not want to cause any foliation w/ this iterator or use this iterator once the region was defoliated Debug.Assert(oldState != ElementState.None); - XmlNode n = CurrentNode.FirstChild; + XmlNode? n = CurrentNode.FirstChild; value = GetInitialTextFromNodes(ref n); if (n == null) { @@ -155,9 +159,9 @@ internal bool NextInitialTextLikeNodes(out string value) return true; } - private static string GetInitialTextFromNodes(ref XmlNode n) + private static string GetInitialTextFromNodes(ref XmlNode? n) { - string value = null; + string? value = null; if (n != null) { diff --git a/src/libraries/System.Data.Common/src/System/Xml/TreeIterator.cs b/src/libraries/System.Data.Common/src/System/Xml/TreeIterator.cs index 26bc84f700bf7e..2361b77d884400 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/TreeIterator.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/TreeIterator.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -// TODO: Enable after System.Private.Xml is annotated -#nullable disable - using System.Diagnostics; #pragma warning disable 0618 // ignore obsolete warning about XmlDataDocument @@ -16,18 +13,18 @@ internal sealed class TreeIterator : BaseTreeIterator private readonly XmlNode _nodeTop; private XmlNode _currentNode; - internal TreeIterator(XmlNode nodeTop) : base(((XmlDataDocument)(nodeTop.OwnerDocument)).Mapper) + internal TreeIterator(XmlNode nodeTop) : base(((XmlDataDocument)(nodeTop.OwnerDocument!)).Mapper) { Debug.Assert(nodeTop != null); _nodeTop = nodeTop; _currentNode = nodeTop; } - internal override XmlNode CurrentNode => _currentNode; + internal override XmlNode? CurrentNode => _currentNode; internal override bool Next() { - XmlNode nextNode; + XmlNode? nextNode; // Try to move to the first child nextNode = _currentNode.FirstChild; @@ -47,11 +44,11 @@ internal override bool NextRight() // Make sure we do not get past the nodeTop if we call NextRight on a just initialized iterator and nodeTop has no children if (_currentNode == _nodeTop) { - _currentNode = null; + _currentNode = null!; return false; } - XmlNode nextNode = _currentNode.NextSibling; + XmlNode? nextNode = _currentNode.NextSibling; if (nextNode != null) { @@ -61,19 +58,19 @@ internal override bool NextRight() // No next sibling, try the first sibling of from the parent chain nextNode = _currentNode; - while (nextNode != _nodeTop && nextNode.NextSibling == null) + while (nextNode != _nodeTop && nextNode!.NextSibling == null) { nextNode = nextNode.ParentNode; } if (nextNode == _nodeTop) { - _currentNode = null; + _currentNode = null!; return false; } + Debug.Assert(nextNode.NextSibling != null); _currentNode = nextNode.NextSibling; - Debug.Assert(_currentNode != null); return true; } } diff --git a/src/libraries/System.Data.Common/src/System/Xml/XPathNodePointer.cs b/src/libraries/System.Data.Common/src/System/Xml/XPathNodePointer.cs index d3132302263a20..f7095827dfcd20 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/XPathNodePointer.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/XPathNodePointer.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -// TODO: Enable after System.Private.Xml is annotated -#nullable disable - using System.Data; using System.Diagnostics; using System.Xml.XPath; @@ -17,9 +14,9 @@ internal sealed class XPathNodePointer : IXmlDataVirtualNode private readonly WeakReference _owner; // Owner of this pointer (an DataDocumentXPathNavigator). When the associated DataDocumentXPathNavigator (the owner) goes away, this XPathNodePointer can go away as well. private readonly XmlDataDocument _doc; private XmlNode _node; - private DataColumn _column; + private DataColumn? _column; private bool _fOnValue; - internal XmlBoundElement _parentOfNS; + internal XmlBoundElement? _parentOfNS; internal static readonly int[] s_xmlNodeType_To_XpathNodeType_Map = CreateXmlNodeTypeToXpathNodeTypeMap(); internal const string StrReservedXmlns = "http://www.w3.org/2000/xmlns/"; internal const string StrReservedXml = "http://www.w3.org/XML/1998/namespace"; @@ -33,7 +30,7 @@ private static int[] CreateXmlNodeTypeToXpathNodeTypeMap() Array enumValues = Enum.GetValues(typeof(XmlNodeType)); for (int i = 0; i < enumValues.Length; i++) { - tempVal = (int)enumValues.GetValue(i); + tempVal = (int)enumValues.GetValue(i)!; if (tempVal > max) max = tempVal; } @@ -67,9 +64,10 @@ private XPathNodeType DecideXPNodeTypeForTextNodes(XmlNode node) //the function can only be called on text like nodes. Debug.Assert(XmlDataDocument.IsTextNode(node.NodeType)); XPathNodeType xnt = XPathNodeType.Whitespace; - while (node != null) + XmlNode? n = node; + while (n != null) { - switch (node.NodeType) + switch (n.NodeType) { case XmlNodeType.Whitespace: break; @@ -82,7 +80,7 @@ private XPathNodeType DecideXPNodeTypeForTextNodes(XmlNode node) default: return xnt; } - node = _doc.SafeNextSibling(node); + n = _doc.SafeNextSibling(n); } return xnt; } @@ -118,7 +116,7 @@ internal XPathNodePointer(DataDocumentXPathNavigator owner, XPathNodePointer poi { } - private XPathNodePointer(DataDocumentXPathNavigator owner, XmlDataDocument doc, XmlNode node, DataColumn c, bool bOnValue, XmlBoundElement parentOfNS) + private XPathNodePointer(DataDocumentXPathNavigator owner, XmlDataDocument doc, XmlNode node, DataColumn? c, bool bOnValue, XmlBoundElement? parentOfNS) { Debug.Assert(owner != null); _owner = new WeakReference(owner); @@ -311,7 +309,7 @@ internal string Prefix } } - internal string Value + internal string? Value { get { @@ -321,14 +319,14 @@ internal string Value return null; else if (_column == null) { - string strRet = _node.Value; + string? strRet = _node.Value; if (XmlDataDocument.IsTextNode(_node.NodeType)) { //concatenate adjacent textlike nodes - XmlNode parent = _node.ParentNode; + XmlNode? parent = _node.ParentNode; if (parent == null) return strRet; - XmlNode n = _doc.SafeNextSibling(_node); + XmlNode? n = _doc.SafeNextSibling(_node); while (n != null && XmlDataDocument.IsTextNode(n.NodeType)) { strRet += n.Value; @@ -339,7 +337,7 @@ internal string Value } else if (_column.ColumnMapping == MappingType.Attribute || _fOnValue) { - DataRow row = Row; + DataRow row = Row!; DataRowVersion rowVersion = (row.RowState == DataRowState.Detached) ? DataRowVersion.Proposed : DataRowVersion.Current; object value = row[_column, rowVersion]; if (!Convert.IsDBNull(value)) @@ -366,7 +364,7 @@ internal string InnerText if (_node.NodeType == XmlNodeType.Document) { //document node's region should always be uncompressed - XmlElement rootElem = ((XmlDocument)_node).DocumentElement; + XmlElement? rootElem = ((XmlDocument)_node).DocumentElement; if (rootElem != null) return rootElem.InnerText; return string.Empty; @@ -376,7 +374,7 @@ internal string InnerText } else { - DataRow row = Row; + DataRow row = Row!; DataRowVersion rowVersion = (row.RowState == DataRowState.Detached) ? DataRowVersion.Proposed : DataRowVersion.Current; object value = row[_column, rowVersion]; if (!Convert.IsDBNull(value)) @@ -403,8 +401,8 @@ internal string XmlLang { RealFoliate(); XmlNode curNode = _node; - XmlBoundElement curBoundElem = null; - object colVal = null; + XmlBoundElement? curBoundElem = null; + object? colVal = null; while (curNode != null) { curBoundElem = curNode as XmlBoundElement; @@ -413,7 +411,7 @@ internal string XmlLang if (curBoundElem.ElementState == ElementState.Defoliated) { //if not foliated, going through the columns to get the xml:lang - DataRow row = curBoundElem.Row; + DataRow row = curBoundElem.Row!; foreach (DataColumn col in row.Table.Columns) { if (col.Prefix == "xml" && col.EncodedColumnName == "lang") @@ -433,20 +431,20 @@ internal string XmlLang } } if (curNode.NodeType == XmlNodeType.Attribute) - curNode = ((XmlAttribute)curNode).OwnerElement; + curNode = ((XmlAttribute)curNode).OwnerElement!; else - curNode = curNode.ParentNode; + curNode = curNode.ParentNode!; } return string.Empty; } } - private XmlBoundElement GetRowElement() + private XmlBoundElement? GetRowElement() { - XmlBoundElement rowElem; + XmlBoundElement? rowElem; if (_column != null) { - rowElem = _node as XmlBoundElement; + rowElem = (XmlBoundElement)_node; Debug.Assert(rowElem != null); Debug.Assert(rowElem.Row != null); return rowElem; @@ -456,11 +454,11 @@ private XmlBoundElement GetRowElement() return rowElem; } - private DataRow Row + private DataRow? Row { get { - XmlBoundElement rowElem = GetRowElement(); + XmlBoundElement? rowElem = GetRowElement(); if (rowElem == null) return null; @@ -494,7 +492,7 @@ private void MoveTo(XmlNode node) _fOnValue = false; } - private void MoveTo(XmlNode node, DataColumn column, bool fOnValue) + private void MoveTo(XmlNode node, DataColumn? column, bool fOnValue) { // Should not move outside of this document Debug.Assert(node == _doc || node.OwnerDocument == _doc); @@ -512,7 +510,7 @@ private bool IsFoliated(XmlNode node) private int ColumnCount(DataRow row, bool fAttribute) { - DataColumn c = null; + DataColumn? c = null; int count = 0; while ((c = NextColumn(row, c, fAttribute)) != null) { @@ -533,11 +531,11 @@ internal int AttributeCount if (_column == null && _node.NodeType == XmlNodeType.Element) { if (!IsFoliated(_node)) - return ColumnCount(Row, true); + return ColumnCount(Row!, true); else { int nc = 0; - foreach (XmlAttribute attr in _node.Attributes) + foreach (XmlAttribute attr in _node.Attributes!) { if (attr.NamespaceURI != StrReservedXmlns) nc++; @@ -550,7 +548,7 @@ internal int AttributeCount } } - internal DataColumn NextColumn(DataRow row, DataColumn col, bool fAttribute) + internal DataColumn? NextColumn(DataRow row, DataColumn? col, bool fAttribute) { if (row.RowState == DataRowState.Deleted) return null; @@ -571,7 +569,7 @@ internal DataColumn NextColumn(DataRow row, DataColumn col, bool fAttribute) return null; } - internal DataColumn PreviousColumn(DataRow row, DataColumn col, bool fAttribute) + internal DataColumn? PreviousColumn(DataRow row, DataColumn? col, bool fAttribute) { if (row.RowState == DataRowState.Deleted) return null; @@ -605,8 +603,8 @@ internal bool MoveToAttribute(string localName, string namespaceURI) { if (!IsFoliated(_node)) { - DataColumn c = null; - while ((c = NextColumn(Row, c, true)) != null) + DataColumn? c = null; + while ((c = NextColumn(Row!, c, true)) != null) { if (c.EncodedColumnName == localName && c.Namespace == namespaceURI) { @@ -618,7 +616,7 @@ internal bool MoveToAttribute(string localName, string namespaceURI) else { Debug.Assert(_node.Attributes != null); - XmlNode n = _node.Attributes.GetNamedItem(localName, namespaceURI); + XmlNode? n = _node.Attributes.GetNamedItem(localName, namespaceURI); if (n != null) { MoveTo(n, null, false); @@ -647,8 +645,8 @@ internal bool MoveToNextAttribute(bool bFirst) } if (!IsFoliated(_node)) { - DataColumn c = _column; - while ((c = NextColumn(Row, c, true)) != null) + DataColumn? c = _column; + while ((c = NextColumn(Row!, c, true)) != null) { if (c.Namespace != StrReservedXmlns) { @@ -662,7 +660,7 @@ internal bool MoveToNextAttribute(bool bFirst) { if (bFirst) { - XmlAttributeCollection attrs = _node.Attributes; + XmlAttributeCollection attrs = _node.Attributes!; foreach (XmlAttribute attr in attrs) { if (attr.NamespaceURI != StrReservedXmlns) @@ -674,7 +672,7 @@ internal bool MoveToNextAttribute(bool bFirst) } else { - XmlAttributeCollection attrs = ((XmlAttribute)_node).OwnerElement.Attributes; + XmlAttributeCollection attrs = ((XmlAttribute)_node).OwnerElement!.Attributes; bool bFound = false; foreach (XmlAttribute attr in attrs) { @@ -744,8 +742,8 @@ internal bool MoveToNextSibling() Debug.Assert(_column.ColumnMapping != MappingType.Attribute && _column.ColumnMapping != MappingType.Hidden); return false; } - DataRow curRow = Row; - DataColumn c = NextColumn(curRow, _column, false); + DataRow curRow = Row!; + DataColumn? c = NextColumn(curRow, _column, false); while (c != null) { if (IsValidChild(_node, c)) @@ -755,7 +753,7 @@ internal bool MoveToNextSibling() } c = NextColumn(curRow, c, false); } - XmlNode n = _doc.SafeFirstChild(_node); + XmlNode? n = _doc.SafeFirstChild(_node); if (n != null) { MoveTo(n); @@ -764,8 +762,8 @@ internal bool MoveToNextSibling() } else { - XmlNode n = _node; - XmlNode parent = _node.ParentNode; + XmlNode? n = _node; + XmlNode? parent = _node.ParentNode; if (parent == null) return false; bool bTextLike = XmlDataDocument.IsTextNode(_node.NodeType); @@ -796,8 +794,8 @@ internal bool MoveToPreviousSibling() { if (_fOnValue) return false; - DataRow curRow = Row; - DataColumn c = PreviousColumn(curRow, _column, false); + DataRow curRow = Row!; + DataColumn? c = PreviousColumn(curRow, _column, false); while (c != null) { if (IsValidChild(_node, c)) @@ -810,8 +808,8 @@ internal bool MoveToPreviousSibling() } else { - XmlNode n = _node; - XmlNode parent = _node.ParentNode; + XmlNode? n = _node; + XmlNode? parent = _node.ParentNode; if (parent == null) return false; bool bTextLike = XmlDataDocument.IsTextNode(_node.NodeType); @@ -829,10 +827,10 @@ internal bool MoveToPreviousSibling() } if (!IsFoliated(parent) && (parent is XmlBoundElement)) { - DataRow row = ((XmlBoundElement)parent).Row; + DataRow? row = ((XmlBoundElement)parent).Row; if (row != null) { - DataColumn c = PreviousColumn(row, null, false); + DataColumn? c = PreviousColumn(row, null, false); if (c != null) { MoveTo(parent, c, _doc.IsTextOnly(c)); @@ -851,8 +849,8 @@ internal bool MoveToFirst() AssertValid(); if (_node != null) { - DataRow curRow = null; - XmlNode parent = null; + DataRow? curRow = null; + XmlNode? parent = null; if (_column != null) { curRow = Row; @@ -869,7 +867,7 @@ internal bool MoveToFirst() //first check with the columns in the row if (curRow != null) { - DataColumn c = NextColumn(curRow, null, false); + DataColumn? c = NextColumn(curRow, null, false); while (c != null) { if (IsValidChild(_node, c)) @@ -881,7 +879,7 @@ internal bool MoveToFirst() } } //didn't find a valid column or maybe already Foliated, go through its children nodes - XmlNode n = _doc.SafeFirstChild(parent); + XmlNode? n = _doc.SafeFirstChild(parent); while (n != null) { if (IsValidChild(parent, n)) @@ -913,8 +911,8 @@ internal bool HasChildren if (!IsFoliated(_node)) { // find virtual column elements first - DataRow curRow = Row; - DataColumn c = NextColumn(curRow, null, false); + DataRow curRow = Row!; + DataColumn? c = NextColumn(curRow, null, false); while (c != null) { if (IsValidChild(_node, c)) @@ -923,7 +921,7 @@ internal bool HasChildren } } // look for anything - XmlNode n = _doc.SafeFirstChild(_node); + XmlNode? n = _doc.SafeFirstChild(_node); while (n != null) { if (IsValidChild(_node, n)) @@ -954,8 +952,8 @@ internal bool MoveToFirstChild() if (!IsFoliated(_node)) { // find virtual column elements first - DataRow curRow = Row; - DataColumn c = NextColumn(curRow, null, false); + DataRow curRow = Row!; + DataColumn? c = NextColumn(curRow, null, false); while (c != null) { if (IsValidChild(_node, c)) @@ -967,7 +965,7 @@ internal bool MoveToFirstChild() } } // look for anything - XmlNode n = _doc.SafeFirstChild(_node); + XmlNode? n = _doc.SafeFirstChild(_node); while (n != null) { if (IsValidChild(_node, n)) @@ -988,7 +986,7 @@ internal bool MoveToParent() AssertValid(); if (NodeType == XPathNodeType.Namespace) { - MoveTo(_parentOfNS); + MoveTo(_parentOfNS!); return true; } if (_node != null) @@ -1005,7 +1003,7 @@ internal bool MoveToParent() } else { - XmlNode n = null; + XmlNode? n = null; if (_node.NodeType == XmlNodeType.Attribute) n = ((XmlAttribute)_node).OwnerElement; else @@ -1020,7 +1018,7 @@ internal bool MoveToParent() return false; } - private XmlNode GetParent(XmlNode node) + private XmlNode? GetParent(XmlNode node) { XPathNodeType xnt = ConvertNodeType(node); if (xnt == XPathNodeType.Namespace) @@ -1036,7 +1034,7 @@ private XmlNode GetParent(XmlNode node) internal void MoveToRoot() { XmlNode node = _node; - XmlNode parent = _node; + XmlNode? parent = _node; while (parent != null) { node = parent; @@ -1066,8 +1064,8 @@ internal bool IsSamePosition(XPathNodePointer pointer) private XmlNodeOrder CompareNamespacePosition(XPathNodePointer other) { - XPathNodePointer xp1 = Clone((DataDocumentXPathNavigator)(_owner.Target)); - XPathNodePointer xp2 = other.Clone((DataDocumentXPathNavigator)(other._owner.Target)); + XPathNodePointer xp1 = Clone((DataDocumentXPathNavigator)(_owner.Target!)); + XPathNodePointer xp2 = other.Clone((DataDocumentXPathNavigator)(other._owner.Target!)); while (xp1.MoveToNextNamespace(XPathNamespaceScope.All)) { if (xp1.IsSamePosition(xp2)) @@ -1080,7 +1078,7 @@ private static XmlNode GetRoot(XmlNode node, ref int depth) { depth = 0; XmlNode curNode = node; - XmlNode parent = ((curNode.NodeType == XmlNodeType.Attribute) ? (((XmlAttribute)curNode).OwnerElement) : (curNode.ParentNode)); + XmlNode? parent = ((curNode.NodeType == XmlNodeType.Attribute) ? (((XmlAttribute)curNode).OwnerElement) : (curNode.ParentNode)); for (; parent != null; depth++) { curNode = parent; @@ -1096,7 +1094,7 @@ internal XmlNodeOrder ComparePosition(XPathNodePointer other) if (IsSamePosition(other)) return XmlNodeOrder.Same; - XmlNode curNode1 = null, curNode2 = null; + XmlNode? curNode1 = null, curNode2 = null; //deal with namespace node first if (NodeType == XPathNodeType.Namespace && other.NodeType == XPathNodeType.Namespace) @@ -1204,9 +1202,9 @@ internal XmlNodeOrder ComparePosition(XPathNodePointer other) return XmlNodeOrder.Before; } - XmlNode parent1 = GetParent(curNode1); - XmlNode parent2 = GetParent(curNode2); - XmlNode nextNode = null; + XmlNode? parent1 = GetParent(curNode1!); + XmlNode? parent2 = GetParent(curNode2!); + XmlNode? nextNode = null; while (parent1 != null && parent2 != null) { if (parent1 == parent2) @@ -1230,7 +1228,7 @@ internal XmlNodeOrder ComparePosition(XPathNodePointer other) return XmlNodeOrder.Unknown; } - internal XmlNode Node + internal XmlNode? Node { get { @@ -1240,7 +1238,7 @@ internal XmlNode Node if (_node == null) return null; - XmlBoundElement rowElem = GetRowElement(); + XmlBoundElement? rowElem = GetRowElement(); if (rowElem != null) { bool wasFoliationEnabled = _doc.IsFoliationEnabled; @@ -1260,7 +1258,7 @@ bool IXmlDataVirtualNode.IsOnNode(XmlNode nodeToCheck) return nodeToCheck == _node; } - bool IXmlDataVirtualNode.IsOnColumn(DataColumn col) + bool IXmlDataVirtualNode.IsOnColumn(DataColumn? col) { RealFoliate(); return col == _column; @@ -1287,7 +1285,7 @@ private void RealFoliate() Debug.Assert(_column != null); - XmlNode n = null; + XmlNode? n = null; if (_doc.IsTextOnly(_column)) n = _node.FirstChild; @@ -1295,7 +1293,7 @@ private void RealFoliate() { if (_column.ColumnMapping == MappingType.Attribute) { - n = _node.Attributes.GetNamedItem(_column.EncodedColumnName, _column.Namespace); + n = _node.Attributes!.GetNamedItem(_column.EncodedColumnName, _column.Namespace); } else { @@ -1324,11 +1322,11 @@ private void RealFoliate() //The function only helps to find out if there is a namespace declaration of given name is defined on the given node //It will not check the ancestor of the given node. - private string GetNamespace(XmlBoundElement be, string name) + private string? GetNamespace(XmlBoundElement be, string name) { if (be == null) return null; - XmlAttribute attr = null; + XmlAttribute? attr = null; if (be.IsFoliated) { attr = be.GetAttributeNode(name, StrReservedXmlns); @@ -1339,11 +1337,11 @@ private string GetNamespace(XmlBoundElement be, string name) } else { //defoliated so that we need to search through its column - DataRow curRow = be.Row; + DataRow? curRow = be.Row; if (curRow == null) return null; //going through its attribute columns - DataColumn curCol = PreviousColumn(curRow, null, true); + DataColumn? curCol = PreviousColumn(curRow, null, true); while (curCol != null) { if (curCol.Namespace == StrReservedXmlns) @@ -1367,9 +1365,9 @@ internal string GetNamespace(string name) if (name != null && name.Length == 0) name = "xmlns"; RealFoliate(); - XmlNode node = _node; + XmlNode? node = _node; XmlNodeType nt = node.NodeType; - string retVal = null; + string? retVal = null; while (node != null) { //first identify an element node in the ancestor + itself @@ -1384,7 +1382,7 @@ internal string GetNamespace(string name) if (node != null) { //must be element node - retVal = GetNamespace((XmlBoundElement)node, name); + retVal = GetNamespace((XmlBoundElement)node, name!); if (retVal != null) return retVal; //didn't find it, try the next parentnode @@ -1407,9 +1405,9 @@ internal bool MoveToNamespace(string name) if (attrName != null && attrName.Length == 0) attrName = "xmlns"; RealFoliate(); - XmlNode node = _node; - XmlAttribute attr = null; - XmlBoundElement be = null; + XmlNode? node = _node; + XmlAttribute? attr = null; + XmlBoundElement? be = null; while (node != null) { //check current element node @@ -1427,11 +1425,11 @@ internal bool MoveToNamespace(string name) } else {//defoliated so that we need to search through its column - DataRow curRow = be.Row; + DataRow? curRow = be.Row; if (curRow == null) return false; //going through its attribute columns - DataColumn curCol = PreviousColumn(curRow, null, true); + DataColumn? curCol = PreviousColumn(curRow, null, true); while (curCol != null) { if (curCol.Namespace == StrReservedXmlns && curCol.ColumnName == name) @@ -1456,14 +1454,14 @@ internal bool MoveToNamespace(string name) //the function will find the next namespace node on the given bound element starting with the given column or attribute // whether to use column or attribute depends on if the bound element is foliated or not. - private bool MoveToNextNamespace(XmlBoundElement be, DataColumn col, XmlAttribute curAttr) + private bool MoveToNextNamespace(XmlBoundElement? be, DataColumn? col, XmlAttribute? curAttr) { if (be != null) { if (be.IsFoliated) { XmlAttributeCollection attrs = be.Attributes; - XmlAttribute attr = null; + XmlAttribute? attr = null; bool bFound = false; if (curAttr == null) bFound = true; //the first namespace will be the one @@ -1488,11 +1486,11 @@ private bool MoveToNextNamespace(XmlBoundElement be, DataColumn col, XmlAttribut } else {//defoliated so that we need to search through its column - DataRow curRow = be.Row; + DataRow? curRow = be.Row; if (curRow == null) return false; //going through its attribute columns - DataColumn curCol = PreviousColumn(curRow, col, true); + DataColumn? curCol = PreviousColumn(curRow, col, true); while (curCol != null) { if (curCol.Namespace == StrReservedXmlns && !DuplicateNS(be, curCol.ColumnName)) @@ -1515,8 +1513,8 @@ internal bool MoveToFirstNamespace(XPathNamespaceScope namespaceScope) //only need to check with _node, even if _column is not null and its mapping type is element, it can't have attributes if (_parentOfNS == null) return false; - XmlNode node = _node; - XmlBoundElement be = null; + XmlNode? node = _node; + XmlBoundElement? be = null; while (node != null) { be = node as XmlBoundElement; @@ -1547,8 +1545,8 @@ private bool DuplicateNS(XmlBoundElement endElem, string lname) { if (_parentOfNS == null || endElem == null) return false; - XmlBoundElement be = _parentOfNS; - XmlNode node = null; + XmlBoundElement? be = _parentOfNS; + XmlNode? node = null; while (be != null && be != endElem) { if (GetNamespace(be, lname) != null) @@ -1568,18 +1566,18 @@ internal bool MoveToNextNamespace(XPathNamespaceScope namespaceScope) { RealFoliate(); Debug.Assert(_parentOfNS != null); - XmlNode node = _node; + XmlNode? node = _node; //first check within the same boundelement if (_column != null) { Debug.Assert(_column.Namespace == StrReservedXmlns); if (namespaceScope == XPathNamespaceScope.Local && _parentOfNS != _node) //already outside scope return false; - XmlBoundElement be = _node as XmlBoundElement; + XmlBoundElement? be = _node as XmlBoundElement; Debug.Assert(be != null); - DataRow curRow = be.Row; + DataRow? curRow = be.Row; Debug.Assert(curRow != null); - DataColumn curCol = PreviousColumn(curRow, _column, true); + DataColumn? curCol = PreviousColumn(curRow, _column, true); while (curCol != null) { if (curCol.Namespace == StrReservedXmlns) @@ -1621,7 +1619,7 @@ internal bool MoveToNextNamespace(XPathNamespaceScope namespaceScope) while (node != null) { //try the namespace attributes from the same element - XmlBoundElement be = node as XmlBoundElement; + XmlBoundElement? be = node as XmlBoundElement; if (MoveToNextNamespace(be, null, null)) return true; //no more namespace attribute under the same element @@ -1648,10 +1646,10 @@ private void AssertValid() if (_column != null) { // We must be on a de-foliated region - XmlBoundElement rowElem = _node as XmlBoundElement; + XmlBoundElement? rowElem = _node as XmlBoundElement; Debug.Assert(rowElem != null); - DataRow row = rowElem.Row; + DataRow? row = rowElem.Row; Debug.Assert(row != null); // We cannot be on a column for which the value is DBNull diff --git a/src/libraries/System.Data.Common/src/System/Xml/XmlBoundElement.cs b/src/libraries/System.Data.Common/src/System/Xml/XmlBoundElement.cs index 77ed74c8b94c58..ae57ad3186ea90 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/XmlBoundElement.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/XmlBoundElement.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -// TODO: Enable after System.Private.Xml is annotated -#nullable disable - using System.Data; using System.Diagnostics; using System.Threading; @@ -24,7 +21,7 @@ internal enum ElementState internal sealed class XmlBoundElement : XmlElement { - private DataRow _row; + private DataRow? _row; private ElementState _state; internal XmlBoundElement(string prefix, string localName, string namespaceURI, XmlDocument doc) : base(prefix, localName, namespaceURI, doc) @@ -43,7 +40,7 @@ public override XmlAttributeCollection Attributes public override bool HasAttributes => Attributes.Count > 0; - public override XmlNode FirstChild + public override XmlNode? FirstChild { get { @@ -52,9 +49,9 @@ public override XmlNode FirstChild } } - internal XmlNode SafeFirstChild => base.FirstChild; + internal XmlNode? SafeFirstChild => base.FirstChild; - public override XmlNode LastChild + public override XmlNode? LastChild { get { @@ -63,14 +60,14 @@ public override XmlNode LastChild } } - public override XmlNode PreviousSibling + public override XmlNode? PreviousSibling { get { - XmlNode prev = base.PreviousSibling; + XmlNode? prev = base.PreviousSibling; if (prev == null) { - XmlBoundElement parent = ParentNode as XmlBoundElement; + XmlBoundElement? parent = ParentNode as XmlBoundElement; if (parent != null) { parent.AutoFoliate(); @@ -81,16 +78,16 @@ public override XmlNode PreviousSibling } } - internal XmlNode SafePreviousSibling => base.PreviousSibling; + internal XmlNode? SafePreviousSibling => base.PreviousSibling; - public override XmlNode NextSibling + public override XmlNode? NextSibling { get { - XmlNode next = base.NextSibling; + XmlNode? next = base.NextSibling; if (next == null) { - XmlBoundElement parent = ParentNode as XmlBoundElement; + XmlBoundElement? parent = ParentNode as XmlBoundElement; if (parent != null) { parent.AutoFoliate(); @@ -101,7 +98,7 @@ public override XmlNode NextSibling } } - internal XmlNode SafeNextSibling => base.NextSibling; + internal XmlNode? SafeNextSibling => base.NextSibling; public override bool HasChildNodes { @@ -112,13 +109,13 @@ public override bool HasChildNodes } } - public override XmlNode InsertBefore(XmlNode newChild, XmlNode refChild) + public override XmlNode? InsertBefore(XmlNode newChild, XmlNode? refChild) { AutoFoliate(); return base.InsertBefore(newChild, refChild); } - public override XmlNode InsertAfter(XmlNode newChild, XmlNode refChild) + public override XmlNode? InsertAfter(XmlNode newChild, XmlNode? refChild) { AutoFoliate(); return base.InsertAfter(newChild, refChild); @@ -130,7 +127,7 @@ public override XmlNode ReplaceChild(XmlNode newChild, XmlNode oldChild) return base.ReplaceChild(newChild, oldChild); } - public override XmlNode AppendChild(XmlNode newChild) + public override XmlNode? AppendChild(XmlNode newChild) { AutoFoliate(); return base.AppendChild(newChild); @@ -138,8 +135,8 @@ public override XmlNode AppendChild(XmlNode newChild) internal void RemoveAllChildren() { - XmlNode child = FirstChild; - XmlNode sibling = null; + XmlNode? child = FirstChild; + XmlNode? sibling = null; while (child != null) { @@ -173,7 +170,7 @@ public override string InnerXml } } - internal DataRow Row + internal DataRow? Row { get { return _row; } set { _row = value; } diff --git a/src/libraries/System.Data.Common/src/System/Xml/XmlDataDocument.cs b/src/libraries/System.Data.Common/src/System/Xml/XmlDataDocument.cs index 7c8ce6d6117aaa..09d6ee751b9b3c 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/XmlDataDocument.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/XmlDataDocument.cs @@ -1,14 +1,12 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -// TODO: Enable after System.Private.Xml is annotated -#nullable disable - using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Xml.XPath; @@ -62,14 +60,14 @@ internal void AddPointer(IXmlDataVirtualNode pointer) ArrayList al = new ArrayList(); foreach (DictionaryEntry entry in _pointers) { - IXmlDataVirtualNode temp = (IXmlDataVirtualNode)(entry.Value); + IXmlDataVirtualNode? temp = (IXmlDataVirtualNode?)(entry.Value); Debug.Assert(temp != null); if (!temp.IsInUse()) al.Add(temp); } for (int i = 0; i < al.Count; i++) { - _pointers.Remove(al[i]); + _pointers.Remove(al[i]!); } _countAddPointer = 0; } @@ -81,7 +79,7 @@ internal void AddPointer(IXmlDataVirtualNode pointer) internal void AssertPointerPresent(IXmlDataVirtualNode pointer) { #if DEBUG - object val = _pointers[pointer]; + object? val = _pointers[pointer]; if (val != (object)pointer) Debug.Fail("Pointer not present"); #endif @@ -95,6 +93,7 @@ internal void AssertPointerPresent(IXmlDataVirtualNode pointer) // - ds.ReadXmlData(); // ds is now filled, however doc has no content (since there were no listeners for the new created DataRow's) // We can set-up listeners and track each change in schema, but it is more perf-friendly to do it laizily, all at once, when the first DataRow is created // (we rely on the fact that DataRowCreated is a DataSet wide event, rather than a DataTable event) + [MemberNotNull(nameof(_dataSet))] private void AttachDataSet(DataSet ds) { // You should not have already an associated dataset @@ -110,12 +109,12 @@ private void AttachDataSet(DataSet ds) // after loading, all detached DataRows are synchronized with the xml tree and inserted to their tables // or after setting the innerxml, synchronize the rows and if created new and detached, will be inserted. - internal void SyncRows(DataRow parentRow, XmlNode node, bool fAddRowsToTable) + internal void SyncRows(DataRow? parentRow, XmlNode node, bool fAddRowsToTable) { - XmlBoundElement be = node as XmlBoundElement; + XmlBoundElement? be = node as XmlBoundElement; if (be != null) { - DataRow r = be.Row; + DataRow? r = be.Row; if (r != null && be.ElementState == ElementState.Defoliated) return; //no need of syncRow @@ -137,7 +136,7 @@ internal void SyncRows(DataRow parentRow, XmlNode node, bool fAddRowsToTable) } // Attach all rows from children nodes - for (XmlNode child = node.FirstChild; child != null; child = child.NextSibling) + for (XmlNode? child = node.FirstChild; child != null; child = child.NextSibling) SyncRows(parentRow, child, fAddRowsToTable); } @@ -145,14 +144,14 @@ internal void SyncRows(DataRow parentRow, XmlNode node, bool fAddRowsToTable) // Synchronize the rows and if created new and detached, will be inserted. internal void SyncTree(XmlNode node) { - XmlBoundElement be = null; + XmlBoundElement? be = null; _mapper.GetRegion(node, out be); - DataRow parentRow = null; + DataRow? parentRow = null; bool fAddRowsToTable = IsConnected(node); if (be != null) { - DataRow r = be.Row; + DataRow? r = be.Row; if (r != null && be.ElementState == ElementState.Defoliated) return; //no need of syncRow @@ -177,7 +176,7 @@ internal void SyncTree(XmlNode node) } // Attach all rows from children nodes - for (XmlNode child = node.FirstChild; child != null; child = child.NextSibling) + for (XmlNode? child = node.FirstChild; child != null; child = child.NextSibling) SyncRows(parentRow, child, fAddRowsToTable); } @@ -328,7 +327,7 @@ private void BindToTable(DataTable t) /// Creates an element with the specified Prefix, LocalName, and /// NamespaceURI. /// - public override XmlElement CreateElement(string prefix, string localName, string namespaceURI) + public override XmlElement CreateElement(string? prefix, string localName, string? namespaceURI) { // There are three states for the document: // - special listeners ON, no permananent listeners: this is when the data doc was created w/o any dataset, and the 1st time a new row/element @@ -370,7 +369,7 @@ public override XmlElement CreateElement(string prefix, string localName, string if (col.ColumnMapping != MappingType.Hidden) SetRowValueToNull(row, col); } - XmlBoundElement be = row.Element; + XmlBoundElement? be = row.Element; Debug.Assert(be != null); be.Prefix = prefix; return be; @@ -422,12 +421,12 @@ private void DefoliateRegion(XmlBoundElement rowElem) // drop all attributes rowElem.RemoveAllAttributes(); - XmlNode node = rowElem.FirstChild; + XmlNode? node = rowElem.FirstChild; while (node != null) { - XmlNode next = node.NextSibling; + XmlNode? next = node.NextSibling; - XmlBoundElement be = node as XmlBoundElement; + XmlBoundElement? be = node as XmlBoundElement; if (be != null && be.Row != null) break; @@ -455,7 +454,7 @@ private void DefoliateRegion(XmlBoundElement rowElem) private XmlElement EnsureDocumentElement() { - XmlElement docelem = DocumentElement; + XmlElement? docelem = DocumentElement; if (docelem == null) { string docElemName = XmlConvert.EncodeLocalName(DataSet.DataSetName); @@ -472,11 +471,11 @@ private XmlElement EnsureDocumentElement() } private XmlElement EnsureNonRowDocumentElement() { - XmlElement docElem = DocumentElement; + XmlElement? docElem = DocumentElement; if (docElem == null) return EnsureDocumentElement(); - DataRow rowDocElem = GetRowFromElement(docElem); + DataRow? rowDocElem = GetRowFromElement(docElem); if (rowDocElem == null) return docElem; @@ -490,7 +489,7 @@ private XmlElement DemoteDocumentElement() Debug.Assert(GetRowFromElement(DocumentElement) != null); // Remove the DocumentElement and create a new one - XmlElement oldDocElem = DocumentElement; + XmlElement oldDocElem = DocumentElement!; RemoveChild(oldDocElem); XmlElement docElem = EnsureDocumentElement(); docElem.AppendChild(oldDocElem); @@ -544,7 +543,7 @@ private void FixNestedChildren(DataRow row, XmlElement rowElement) { foreach (DataRow r in row.GetChildRows(dr)) { - XmlElement childElem = r.Element; + XmlElement? childElem = r.Element; // childElem can be null when we create XML from DataSet (XmlDataDocument( DataSet ) is called) and we insert rowElem of the parentRow before // we insert the rowElem of children rows. if (childElem != null) @@ -554,7 +553,7 @@ private void FixNestedChildren(DataRow row, XmlElement rowElement) #endif if (childElem.ParentNode != rowElement) { - childElem.ParentNode.RemoveChild(childElem); + childElem.ParentNode!.RemoveChild(childElem); rowElement.AppendChild(childElem); } #if DEBUG @@ -578,7 +577,7 @@ internal void Foliate(XmlBoundElement node, ElementState newState) { if (newState == ElementState.StrongFoliation && node.Row == null) { - XmlBoundElement rowElem; + XmlBoundElement? rowElem; ElementState rowElemState = ElementState.None; if (_mapper.GetRegion(node, out rowElem)) { @@ -659,7 +658,7 @@ private void ForceFoliation(XmlBoundElement node, ElementState newState) try { - XmlNode priorNode = null; + XmlNode? priorNode = null; DataRow row = node.Row; // create new attrs & elements for row @@ -681,7 +680,7 @@ private void ForceFoliation(XmlBoundElement node, ElementState newState) } else { - XmlNode newNode = null; + XmlNode? newNode = null; if (col.ColumnMapping == MappingType.Element) { newNode = new XmlBoundElement(string.Empty, col.EncodedColumnName, col.Namespace, this); @@ -737,10 +736,10 @@ private void ForceFoliation(XmlBoundElement node, ElementState newState) } //Determine best radical insert position for inserting column elements - private XmlNode GetColumnInsertAfterLocation(DataRow row, DataColumn col, XmlBoundElement rowElement) + private XmlNode? GetColumnInsertAfterLocation(DataRow row, DataColumn col, XmlBoundElement rowElement) { - XmlNode prev = null; - XmlNode node = null; + XmlNode? prev = null; + XmlNode? node = null; // text only columns appear first if (IsTextOnly(col)) @@ -758,13 +757,13 @@ private XmlNode GetColumnInsertAfterLocation(DataRow row, DataColumn col, XmlBou // insert location must be before any non-element nodes if (node.NodeType != XmlNodeType.Element) break; - XmlElement e = node as XmlElement; + XmlElement? e = node as XmlElement; // insert location must be before any non-mapped elements or separate regions if (_mapper.GetRowFromElement(e) != null) break; - object schema = _mapper.GetColumnSchemaForNode(rowElement, node); + object? schema = _mapper.GetColumnSchemaForNode(rowElement, node); if (schema == null || !(schema is DataColumn)) break; @@ -789,15 +788,15 @@ private ArrayList GetNestedChildRelations(DataRow row) return list; } - private DataRow GetNestedParent(DataRow row) + private DataRow? GetNestedParent(DataRow row) { - DataRelation relation = GetNestedParentRelation(row); + DataRelation? relation = GetNestedParentRelation(row); if (relation != null) return row.GetParentRow(relation); return null; } - private static DataRelation GetNestedParentRelation(DataRow row) + private static DataRelation? GetNestedParentRelation(DataRow row) { DataRelation[] relations = row.Table.NestedParentRelations; if (relations.Length == 0) @@ -805,7 +804,7 @@ private static DataRelation GetNestedParentRelation(DataRow row) return relations[0]; } - private DataColumn GetTextOnlyColumn(DataRow row) + private DataColumn? GetTextOnlyColumn(DataRow row) { #if DEBUG { @@ -833,12 +832,12 @@ private DataColumn GetTextOnlyColumn(DataRow row) /// /// Retrieves the DataRow associated with the specified XmlElement. /// - public DataRow GetRowFromElement(XmlElement e) + public DataRow? GetRowFromElement(XmlElement? e) { return _mapper.GetRowFromElement(e); } - private XmlNode GetRowInsertBeforeLocation(DataRow row, XmlElement rowElement, XmlNode parentElement) + private XmlNode? GetRowInsertBeforeLocation(DataRow row, XmlElement rowElement, XmlNode parentElement) { DataRow refRow = row; int i = 0; @@ -851,7 +850,7 @@ private XmlNode GetRowInsertBeforeLocation(DataRow row, XmlElement rowElement, X break; pos = i; - DataRow parentRow = GetNestedParent(row); + DataRow? parentRow = GetNestedParent(row); for (i = pos + 1; i < row.Table.Rows.Count; i++) { refRow = row.Table.Rows[i]; @@ -871,7 +870,7 @@ private XmlNode GetRowInsertBeforeLocation(DataRow row, XmlElement rowElement, X /// public XmlElement GetElementFromRow(DataRow r) { - XmlBoundElement be = r.Element; + XmlBoundElement? be = r.Element; Debug.Assert(be != null); return be; } @@ -884,7 +883,7 @@ internal bool HasPointers(XmlNode node) { if (_pointers.Count > 0) { - object pointer = null; + object? pointer = null; foreach (DictionaryEntry entry in _pointers) { pointer = entry.Value; @@ -997,7 +996,7 @@ private XmlNode CloneTreeInternal(DataPointer other) dp.MoveToOwnerElement(); if (dp.MoveToAttribute(i)) { - newNode.Attributes.Append((XmlAttribute)CloneTreeInternal(dp)); + newNode.Attributes!.Append((XmlAttribute)CloneTreeInternal(dp)); } } @@ -1053,12 +1052,12 @@ private XmlNode CloneNode(DataPointer dp) => //for the nodes without value and have no children XmlNodeType.DocumentFragment => CreateDocumentFragment(), XmlNodeType.DocumentType => CreateDocumentType(dp.Name, dp.PublicId, dp.SystemId, dp.InternalSubset), - XmlNodeType.XmlDeclaration => CreateXmlDeclaration(dp.Version, dp.Encoding, dp.Standalone), + XmlNodeType.XmlDeclaration => CreateXmlDeclaration(dp.Version!, dp.Encoding, dp.Standalone), //for the nodes with value but no children XmlNodeType.Text => CreateTextNode(dp.Value), XmlNodeType.CDATA => CreateCDataSection(dp.Value), - XmlNodeType.ProcessingInstruction => CreateProcessingInstruction(dp.Name, dp.Value), + XmlNodeType.ProcessingInstruction => CreateProcessingInstruction(dp.Name, dp.Value!), XmlNodeType.Comment => CreateComment(dp.Value), XmlNodeType.Whitespace => CreateWhitespace(dp.Value), XmlNodeType.SignificantWhitespace => CreateSignificantWhitespace(dp.Value), @@ -1259,18 +1258,18 @@ private void LoadTreeFromDataSet(DataSet ds) } // load all data from tree structre into datarows - private void LoadRows(XmlBoundElement rowElem, XmlNode node) + private void LoadRows(XmlBoundElement? rowElem, XmlNode node) { Debug.Assert(node != null); - XmlBoundElement be = node as XmlBoundElement; + XmlBoundElement? be = node as XmlBoundElement; if (be != null) { - DataTable dt = _mapper.SearchMatchingTableSchema(rowElem, be); + DataTable? dt = _mapper.SearchMatchingTableSchema(rowElem, be); if (dt != null) { - DataRow r = GetRowFromElement(be); + DataRow? r = GetRowFromElement(be); Debug.Assert(r == null); // If the rowElement was just created and has an un-initialized if (be.ElementState == ElementState.None) @@ -1284,7 +1283,7 @@ private void LoadRows(XmlBoundElement rowElem, XmlNode node) } } // recurse down for children - for (XmlNode child = node.FirstChild; child != null; child = child.NextSibling) + for (XmlNode? child = node.FirstChild; child != null; child = child.NextSibling) LoadRows(rowElem, child); } @@ -1302,7 +1301,7 @@ internal void OnDataRowCreated(object oDataSet, DataRow row) OnNewRow(row); } - internal void OnClearCalled(object oDataSet, DataTable table) + internal void OnClearCalled(object oDataSet, DataTable? table) { throw new NotSupportedException(SR.DataDom_NotSupport_Clear); } @@ -1361,10 +1360,10 @@ private void OnAddRow(DataRow row) ForceFoliation(rowElement, AutoFoliationState); Debug.Assert(rowElement != null); - DataRow rowDocElem = GetRowFromElement(DocumentElement); + DataRow? rowDocElem = GetRowFromElement(DocumentElement); if (rowDocElem != null) { - DataRow parentRow = GetNestedParent(row); + DataRow? parentRow = GetNestedParent(row); if (parentRow == null) DemoteDocumentElement(); } @@ -1402,7 +1401,7 @@ private void OnColumnValueChanged(DataRow row, DataColumn col, XmlBoundElement r { if (_pointers.Count > 0) { - object pointer = null; + object? pointer = null; foreach (DictionaryEntry entry in _pointers) { pointer = entry.Value; @@ -1426,7 +1425,7 @@ private void OnColumnValueChanged(DataRow row, DataColumn col, XmlBoundElement r { value = string.Empty; //make sure that rowElement has Attribute xsi:nil and its value is true - XmlAttribute attr = rowElement.GetAttributeNode(XSI_NIL); + XmlAttribute? attr = rowElement.GetAttributeNode(XSI_NIL); if (attr == null) { attr = CreateAttribute(XSI, Keywords.XSI_NIL, Keywords.XSINS); @@ -1440,7 +1439,7 @@ private void OnColumnValueChanged(DataRow row, DataColumn col, XmlBoundElement r else { //make sure that if rowElement has Attribute xsi:nil, its value is false - XmlAttribute attr = rowElement.GetAttributeNode(XSI_NIL); + XmlAttribute? attr = rowElement.GetAttributeNode(XSI_NIL); if (attr != null) attr.Value = Keywords.FALSE; } @@ -1460,7 +1459,7 @@ private void OnColumnValueChanged(DataRow row, DataColumn col, XmlBoundElement r { if (Convert.IsDBNull(value)) { - attr.OwnerElement.Attributes.Remove(attr); + attr.OwnerElement!.Attributes.Remove(attr); } else { @@ -1484,12 +1483,12 @@ private void OnColumnValueChanged(DataRow row, DataColumn col, XmlBoundElement r bool fMore = iter.Next(); while (fMore) { - if (iter.CurrentNode.NodeType == XmlNodeType.Element) + if (iter.CurrentNode!.NodeType == XmlNodeType.Element) { XmlElement e = (XmlElement)iter.CurrentNode; Debug.Assert(e != null); //we should skip the subregion - XmlBoundElement be = e as XmlBoundElement; + XmlBoundElement? be = e as XmlBoundElement; if (be != null && be.Row != null) { fMore = iter.NextRight(); //skip over the sub-region @@ -1502,7 +1501,7 @@ private void OnColumnValueChanged(DataRow row, DataColumn col, XmlBoundElement r { PromoteNonValueChildren(e); fMore = iter.NextRight(); - e.ParentNode.RemoveChild(e); + e.ParentNode!.RemoveChild(e); // keep looking for more matching elements continue; } @@ -1510,7 +1509,7 @@ private void OnColumnValueChanged(DataRow row, DataColumn col, XmlBoundElement r { ReplaceInitialChildText(e, col.ConvertObjectToXml(value)); //make sure that if the Element has Attribute xsi:nil, its value is false - XmlAttribute attr = e.GetAttributeNode(XSI_NIL); + XmlAttribute? attr = e.GetAttributeNode(XSI_NIL); if (attr != null) attr.Value = Keywords.FALSE; // no need to look any further. @@ -1527,7 +1526,7 @@ private void OnColumnValueChanged(DataRow row, DataColumn col, XmlBoundElement r XmlElement newElem = new XmlBoundElement(string.Empty, col.EncodedColumnName, col.Namespace, this); newElem.AppendChild(CreateTextNode(col.ConvertObjectToXml(value))); - XmlNode elemBefore = GetColumnInsertAfterLocation(row, col, rowElement); + XmlNode? elemBefore = GetColumnInsertAfterLocation(row, col, rowElement); if (elemBefore != null) { rowElement.InsertAfter(newElem, elemBefore); @@ -1544,7 +1543,7 @@ private void OnColumnValueChanged(DataRow row, DataColumn col, XmlBoundElement r } lblDoNestedRelationSync: // Change the XML to conform to the (potentially) change in parent nested relation - DataRelation relation = GetNestedParentRelation(row); + DataRelation? relation = GetNestedParentRelation(row); if (relation != null) { Debug.Assert(relation.ChildTable == row.Table); @@ -1569,16 +1568,16 @@ private void OnColumnChanged(object sender, DataColumnChangeEventArgs args) try { DataRow row = args.Row; - DataColumn col = args.Column; + DataColumn? col = args.Column; if (row.RowState == DataRowState.Detached) { - XmlBoundElement be = row.Element; + XmlBoundElement? be = row.Element; Debug.Assert(be != null); if (be.IsFoliated) { // Need to sync changes from ROM to DOM - OnColumnValueChanged(row, col, be); + OnColumnValueChanged(row, col!, be); } } } @@ -1598,7 +1597,7 @@ private void OnColumnValuesChanged(DataRow row, XmlBoundElement rowElement) // but there will be multiple ROM events if (_columnChangeList.Count > 0) { - if (((DataColumn)(_columnChangeList[0])).Table == row.Table) + if (((DataColumn)(_columnChangeList[0]!)).Table == row.Table) { foreach (DataColumn c in _columnChangeList) OnColumnValueChanged(row, c, rowElement); @@ -1627,7 +1626,7 @@ private void OnDeleteRow(DataRow row, XmlBoundElement rowElement) DemoteDocumentElement(); PromoteInnerRegions(rowElement); - rowElement.ParentNode.RemoveChild(rowElement); + rowElement.ParentNode!.RemoveChild(rowElement); } private void OnDeletingRow(DataRow row, XmlBoundElement rowElement) @@ -1663,7 +1662,7 @@ private void OnFoliated(XmlNode node) { foreach (DictionaryEntry entry in _pointers) { - object pointer = entry.Value; + object? pointer = entry.Value; Debug.Assert(pointer != null); ((IXmlDataVirtualNode)pointer).OnFoliated(node); } @@ -1679,7 +1678,7 @@ private void OnFoliated(XmlNode node) // You should never get here in regular cases } - private DataColumn FindAssociatedParentColumn(DataRelation relation, DataColumn childCol) + private DataColumn? FindAssociatedParentColumn(DataRelation relation, DataColumn childCol) { DataColumn[] columns = relation.ChildKey.ColumnsReference; for (int i = 0; i < columns.Length; i++) @@ -1691,7 +1690,7 @@ private DataColumn FindAssociatedParentColumn(DataRelation relation, DataColumn } // Change the childElement position in the tree to conform to the parent nested relationship in ROM - private void OnNestedParentChange(DataRow child, XmlBoundElement childElement, DataColumn childCol) + private void OnNestedParentChange(DataRow child, XmlBoundElement childElement, DataColumn? childCol) { Debug.Assert(child.Element == childElement && childElement.Row == child); // This function is (and s/b) called as a result of ROM changes, therefore XML changes done here should not be sync-ed to ROM @@ -1700,12 +1699,12 @@ private void OnNestedParentChange(DataRow child, XmlBoundElement childElement, D // In order to check that this move does not change the connected/disconnected state of the node bool fChildElementConnected = IsConnected(childElement); #endif - DataRow parentRowInTree; + DataRow? parentRowInTree; if (childElement == DocumentElement || childElement.ParentNode == null) parentRowInTree = null; else parentRowInTree = GetRowFromElement((XmlElement)childElement.ParentNode); - DataRow parentRowInRelation = GetNestedParent(child); + DataRow? parentRowInRelation = GetNestedParent(child!); if (parentRowInTree != parentRowInRelation) { @@ -1717,17 +1716,17 @@ private void OnNestedParentChange(DataRow child, XmlBoundElement childElement, D else { // no parent? Maybe the parentRow is during changing or childCol is the ID is set to null ( detached from the parent row ). - DataRelation relation = GetNestedParentRelation(child); + DataRelation? relation = GetNestedParentRelation(child!); if (childCol == null || relation == null || Convert.IsDBNull(child[childCol])) { EnsureNonRowDocumentElement().AppendChild(childElement); } else { - DataColumn colInParent = FindAssociatedParentColumn(relation, childCol); + DataColumn? colInParent = FindAssociatedParentColumn(relation, childCol); Debug.Assert(colInParent != null); - object comparedValue = colInParent.ConvertValue(child[childCol]); - if (parentRowInTree._tempRecord != -1 && colInParent.CompareValueTo(parentRowInTree._tempRecord, comparedValue) != 0) + object? comparedValue = colInParent.ConvertValue(child[childCol]); + if (parentRowInTree!._tempRecord != -1 && colInParent.CompareValueTo(parentRowInTree._tempRecord, comparedValue) != 0) { EnsureNonRowDocumentElement().AppendChild(childElement); } @@ -1761,7 +1760,7 @@ private void OnNodeChanged(object sender, XmlNodeChangedEventArgs args) try { // okay to allow text node value changes when bound. - XmlBoundElement rowElement = null; + XmlBoundElement? rowElement = null; Debug.Assert(DataSet.EnforceConstraints == false); @@ -1808,9 +1807,9 @@ private void OnNodeInserted(object sender, XmlNodeChangedEventArgs args) try { // Handle both new node inserted and 2nd part of a move operation. - XmlNode node = args.Node; - XmlNode oldParent = args.OldParent; - XmlNode newParent = args.NewParent; + XmlNode node = args.Node!; + XmlNode? oldParent = args.OldParent; + XmlNode? newParent = args.NewParent; // The code bellow assumes a move operation is fired by DOM in 2 steps: a Remvoe followed by an Insert - this is the 2nd part, the Insert. Debug.Assert(oldParent == null); @@ -1862,8 +1861,8 @@ private void OnNodeRemoved(object sender, XmlNodeChangedEventArgs args) try { - XmlNode node = args.Node; - XmlNode oldParent = args.OldParent; + XmlNode node = args.Node!; + XmlNode? oldParent = args.OldParent; Debug.Assert(args.NewParent == null); if (IsConnected(oldParent)) @@ -1895,22 +1894,22 @@ private void OnNodeRemoving(object sender, XmlNodeChangedEventArgs args) } // Node was removed from connected tree to disconnected tree - private void OnNodeRemovedFromTree(XmlNode node, XmlNode oldParent) + private void OnNodeRemovedFromTree(XmlNode node, XmlNode? oldParent) { - XmlBoundElement oldRowElem; + XmlBoundElement? oldRowElem; // Synchronize values from old region if (_mapper.GetRegion(oldParent, out oldRowElem)) SynchronizeRowFromRowElement(oldRowElem); // Disconnect all regions, starting w/ node (if it is a row-elem) - XmlBoundElement rowElem = node as XmlBoundElement; + XmlBoundElement? rowElem = node as XmlBoundElement; if (rowElem != null && rowElem.Row != null) EnsureDisconnectedDataRow(rowElem); TreeIterator iter = new TreeIterator(node); for (bool fMore = iter.NextRowElement(); fMore; fMore = iter.NextRowElement()) { - rowElem = (XmlBoundElement)(iter.CurrentNode); + rowElem = (XmlBoundElement)(iter.CurrentNode!); EnsureDisconnectedDataRow(rowElem); } @@ -1918,22 +1917,22 @@ private void OnNodeRemovedFromTree(XmlNode node, XmlNode oldParent) AssertNonLiveRows(node); } // Node was removed from the disconnected tree to disconnected tree - private void OnNodeRemovedFromFragment(XmlNode node, XmlNode oldParent) + private void OnNodeRemovedFromFragment(XmlNode node, XmlNode? oldParent) { - XmlBoundElement oldRowElem; + XmlBoundElement? oldRowElem; if (_mapper.GetRegion(oldParent, out oldRowElem)) { // Sync the old region if it is not deleted - DataRow row = oldRowElem.Row; + DataRow row = oldRowElem.Row!; // Since the old region was disconnected, then the row can be only Deleted or Detached Debug.Assert(!IsRowLive(row)); - if (oldRowElem.Row.RowState == DataRowState.Detached) + if (oldRowElem.Row!.RowState == DataRowState.Detached) SynchronizeRowFromRowElement(oldRowElem); } // Need to set nested for the sub-regions (if node is a row-elem, we need to set it just for itself) - XmlBoundElement be = node as XmlBoundElement; + XmlBoundElement? be = node as XmlBoundElement; if (be != null && be.Row != null) { Debug.Assert(!IsRowLive(be.Row)); @@ -1945,7 +1944,7 @@ private void OnNodeRemovedFromFragment(XmlNode node, XmlNode oldParent) TreeIterator iter = new TreeIterator(node); for (bool fMore = iter.NextRowElement(); fMore; fMore = iter.NextRightRowElement()) { - XmlBoundElement rowElemChild = (XmlBoundElement)(iter.CurrentNode); + XmlBoundElement rowElemChild = (XmlBoundElement)(iter.CurrentNode!); SetNestedParentRegion(rowElemChild, null); } } @@ -1967,7 +1966,7 @@ private void OnRowChanged(object sender, DataRowChangeEventArgs args) try { DataRow row = args.Row; - XmlBoundElement rowElement = row.Element; + XmlBoundElement? rowElement = row.Element; // We should have an associated row-elem created when the DataRow was created (or at the load time) Debug.Assert(rowElement != null); @@ -1990,7 +1989,7 @@ private void OnRowChanged(object sender, DataRowChangeEventArgs args) break; case DataRowState.Added: - rowElement.ParentNode.RemoveChild(rowElement); + rowElement.ParentNode!.RemoveChild(rowElement); break; case DataRowState.Modified: @@ -2130,12 +2129,12 @@ private void OnRowChanging(object sender, DataRowChangeEventArgs args) } } - private void OnDataSetPropertyChanging(object oDataSet, PropertyChangedEventArgs args) + private void OnDataSetPropertyChanging(object? oDataSet, PropertyChangedEventArgs args) { if (args.PropertyName == "DataSetName") throw new InvalidOperationException(SR.DataDom_DataSetNameChange); } - private void OnColumnPropertyChanging(object oColumn, PropertyChangedEventArgs args) + private void OnColumnPropertyChanging(object? oColumn, PropertyChangedEventArgs args) { if (args.PropertyName == "ColumnName") throw new InvalidOperationException(SR.DataDom_ColumnNameChange); @@ -2144,7 +2143,7 @@ private void OnColumnPropertyChanging(object oColumn, PropertyChangedEventArgs a if (args.PropertyName == "ColumnMapping") throw new InvalidOperationException(SR.DataDom_ColumnMappingChange); } - private void OnTablePropertyChanging(object oTable, PropertyChangedEventArgs args) + private void OnTablePropertyChanging(object? oTable, PropertyChangedEventArgs args) { if (args.PropertyName == "TableName") throw new InvalidOperationException(SR.DataDom_TableNameChange); @@ -2180,7 +2179,7 @@ private void OnDataSetRelationsChanging(object oRelationsCollection, CollectionC throw new InvalidOperationException(SR.DataDom_DataSetNestedRelationsChange); // If Add and Remove, we should already been throwing if .Nested == false - Debug.Assert(!(args.Action == CollectionChangeAction.Add || args.Action == CollectionChangeAction.Remove) || rel.Nested == false); + Debug.Assert(!(args.Action == CollectionChangeAction.Add || args.Action == CollectionChangeAction.Remove) || rel!.Nested == false); if (args.Action == CollectionChangeAction.Refresh) { foreach (DataRelation relTemp in (DataRelationCollection)oRelationsCollection) @@ -2193,7 +2192,7 @@ private void OnDataSetRelationsChanging(object oRelationsCollection, CollectionC } } - private void OnRelationPropertyChanging(object oRelationsCollection, PropertyChangedEventArgs args) + private void OnRelationPropertyChanging(object? oRelationsCollection, PropertyChangedEventArgs args) { if (args.PropertyName == "Nested") throw new InvalidOperationException(SR.DataDom_DataSetNestedRelationsChange); @@ -2201,7 +2200,7 @@ private void OnRelationPropertyChanging(object oRelationsCollection, PropertyCha private void OnUndeleteRow(DataRow row, XmlElement rowElement) { - XmlNode refRow; + XmlNode? refRow; XmlElement parent; // make certain we weren't place somewhere else. @@ -2209,7 +2208,7 @@ private void OnUndeleteRow(DataRow row, XmlElement rowElement) rowElement.ParentNode.RemoveChild(rowElement); // Find the parent of RowNode to be inserted - DataRow parentRowInRelation = GetNestedParent(row); + DataRow? parentRowInRelation = GetNestedParent(row); if (parentRowInRelation == null) { parent = EnsureNonRowDocumentElement(); @@ -2252,7 +2251,7 @@ private void PromoteInnerRegions(XmlNode parent) Debug.Assert(parent != DocumentElement); // We cannot promote children of the DocumentElement XmlNode prevSibling = parent; - XmlBoundElement parentRegionRowElem; + XmlBoundElement? parentRegionRowElem; _mapper.GetRegion(parent.ParentNode, out parentRegionRowElem); TreeIterator iter = new TreeIterator(parent); @@ -2271,9 +2270,9 @@ private void PromoteNonValueChildren(XmlNode parent) { Debug.Assert(parent != null); XmlNode prevSibling = parent; - XmlNode child = parent.FirstChild; + XmlNode? child = parent.FirstChild; bool bTextLikeNode = true; - XmlNode nextSibling = null; + XmlNode? nextSibling = null; while (child != null) { nextSibling = child.NextSibling; @@ -2288,19 +2287,19 @@ private void PromoteNonValueChildren(XmlNode parent) } } - private void RemoveInitialTextNodes(XmlNode node) + private void RemoveInitialTextNodes(XmlNode? node) { while (node != null && IsTextLikeNode(node)) { - XmlNode sibling = node.NextSibling; - node.ParentNode.RemoveChild(node); + XmlNode? sibling = node.NextSibling; + node.ParentNode!.RemoveChild(node); node = sibling; } } private void ReplaceInitialChildText(XmlNode parent, string value) { - XmlNode n = parent.FirstChild; + XmlNode? n = parent.FirstChild; // don't consider whitespace when replacing initial text while (n != null && n.NodeType == XmlNodeType.Whitespace) @@ -2312,7 +2311,7 @@ private void ReplaceInitialChildText(XmlNode parent, string value) n.Value = value; else n = parent.InsertBefore(CreateTextNode(value), n); - RemoveInitialTextNodes(n.NextSibling); + RemoveInitialTextNodes(n!.NextSibling); } else { @@ -2320,9 +2319,9 @@ private void ReplaceInitialChildText(XmlNode parent, string value) } } - internal XmlNode SafeFirstChild(XmlNode n) + internal XmlNode? SafeFirstChild(XmlNode n) { - XmlBoundElement be = n as XmlBoundElement; + XmlBoundElement? be = n as XmlBoundElement; if (be != null) return be.SafeFirstChild; else @@ -2330,9 +2329,9 @@ internal XmlNode SafeFirstChild(XmlNode n) return n.FirstChild; } - internal XmlNode SafeNextSibling(XmlNode n) + internal XmlNode? SafeNextSibling(XmlNode n) { - XmlBoundElement be = n as XmlBoundElement; + XmlBoundElement? be = n as XmlBoundElement; if (be != null) return be.SafeNextSibling; else @@ -2340,9 +2339,9 @@ internal XmlNode SafeNextSibling(XmlNode n) return n.NextSibling; } - internal XmlNode SafePreviousSibling(XmlNode n) + internal XmlNode? SafePreviousSibling(XmlNode n) { - XmlBoundElement be = n as XmlBoundElement; + XmlBoundElement? be = n as XmlBoundElement; if (be != null) return be.SafePreviousSibling; else @@ -2363,7 +2362,7 @@ internal static void SetRowValueToNull(DataRow row, DataColumn col) internal static void SetRowValueFromXmlText(DataRow row, DataColumn col, string xmlText) { Debug.Assert(xmlText != null); - Debug.Assert(row.Table.DataSet.EnforceConstraints == false); + Debug.Assert(row.Table.DataSet!.EnforceConstraints == false); object oVal; try { @@ -2388,9 +2387,9 @@ private void SynchronizeRowFromRowElement(XmlBoundElement rowElement) } // Sync row fields w/ values from rowElem region. // If rowElemList is != null, all subregions of rowElem are appended to it. - private void SynchronizeRowFromRowElement(XmlBoundElement rowElement, ArrayList rowElemList) + private void SynchronizeRowFromRowElement(XmlBoundElement rowElement, ArrayList? rowElemList) { - DataRow row = rowElement.Row; + DataRow? row = rowElement.Row; Debug.Assert(row != null); // No synchronization needed for deleted rows @@ -2425,7 +2424,7 @@ private void SynchronizeRowFromRowElement(XmlBoundElement rowElement, ArrayList } #endif } - private void SynchronizeRowFromRowElementEx(XmlBoundElement rowElement, ArrayList rowElemList) + private void SynchronizeRowFromRowElementEx(XmlBoundElement rowElement, ArrayList? rowElemList) { Debug.Assert(rowElement != null); Debug.Assert(rowElement.Row != null); @@ -2440,7 +2439,7 @@ private void SynchronizeRowFromRowElementEx(XmlBoundElement rowElement, ArrayLis RegionIterator iter = new RegionIterator(rowElement); bool fMore; // If present, fill up the TextOnly column - DataColumn column = GetTextOnlyColumn(row); + DataColumn? column = GetTextOnlyColumn(row); if (column != null) { foundColumns[column] = column; @@ -2457,14 +2456,14 @@ private void SynchronizeRowFromRowElementEx(XmlBoundElement rowElement, ArrayLis // Fill up the columns mapped to an element while (fMore) { - XmlElement e = iter.CurrentNode as XmlElement; + XmlElement? e = iter.CurrentNode as XmlElement; if (e == null) { fMore = iter.Next(); continue; } - XmlBoundElement be = e as XmlBoundElement; + XmlBoundElement? be = e as XmlBoundElement; if (be != null && be.Row != null) { if (rowElemList != null) @@ -2474,7 +2473,7 @@ private void SynchronizeRowFromRowElementEx(XmlBoundElement rowElement, ArrayLis continue; } - DataColumn c = _mapper.GetColumnSchemaForNode(rowElement, e); + DataColumn? c = _mapper.GetColumnSchemaForNode(rowElement, e); if (c != null) { Debug.Assert(c.Table == row.Table); @@ -2499,7 +2498,7 @@ private void SynchronizeRowFromRowElementEx(XmlBoundElement rowElement, ArrayLis // foreach (XmlAttribute attr in rowElement.Attributes) { - DataColumn c = _mapper.GetColumnSchemaForNode(rowElement, attr); + DataColumn? c = _mapper.GetColumnSchemaForNode(rowElement, attr); if (c != null) { @@ -2553,8 +2552,21 @@ public XmlDataDocument(DataSet dataset) : base(new XmlDataImplementation()) internal XmlDataDocument(XmlImplementation imp) : base(imp) { - } - + // This constructor is used by XmlDataImplementation.CreateDocument(), which + // exposes it as XmlDocument. The methods using these fields are never called. + _dataSet = null!; + _pointers = null!; + _columnChangeList = null!; + _mapper = null!; + _foliationLock = null!; + _attrXml = null!; + } + + [MemberNotNull(nameof(_pointers))] + [MemberNotNull(nameof(_columnChangeList))] + [MemberNotNull(nameof(_mapper))] + [MemberNotNull(nameof(_foliationLock))] + [MemberNotNull(nameof(_attrXml))] private void Init() { _pointers = new Hashtable(); @@ -2574,6 +2586,12 @@ private void Init() _ignoreXmlEvents = false; } + [MemberNotNull(nameof(_pointers))] + [MemberNotNull(nameof(_columnChangeList))] + [MemberNotNull(nameof(_mapper))] + [MemberNotNull(nameof(_foliationLock))] + [MemberNotNull(nameof(_attrXml))] + [MemberNotNull(nameof(_dataSet))] private void Init(DataSet ds) { if (ds == null) @@ -2586,7 +2604,7 @@ private void Init(DataSet ds) Bind(true); } - private bool IsConnected(XmlNode node) + private bool IsConnected(XmlNode? node) { while (true) { @@ -2595,7 +2613,7 @@ private bool IsConnected(XmlNode node) if (node == this) return true; - XmlAttribute attr = node as XmlAttribute; + XmlAttribute? attr = node as XmlAttribute; if (attr != null) node = attr.OwnerElement; else @@ -2606,9 +2624,9 @@ private bool IsRowLive(DataRow row) { return (row.RowState & (DataRowState.Added | DataRowState.Unchanged | DataRowState.Modified)) != 0; } - private static void SetNestedParentRow(DataRow childRow, DataRow parentRow) + private static void SetNestedParentRow(DataRow childRow, DataRow? parentRow) { - DataRelation rel = GetNestedParentRelation(childRow); + DataRelation? rel = GetNestedParentRelation(childRow); //we should not set this row's parentRow if the table doesn't match. if (rel != null) { @@ -2622,7 +2640,7 @@ private static void SetNestedParentRow(DataRow childRow, DataRow parentRow) // A node (node) was inserted into the main tree (connected) from oldParent==null state private void OnNodeInsertedInTree(XmlNode node) { - XmlBoundElement be; + XmlBoundElement? be; ArrayList rowElemList = new ArrayList(); if (_mapper.GetRegion(node, out be)) { @@ -2647,7 +2665,7 @@ private void OnNodeInsertedInTree(XmlNode node) while (rowElemList.Count > 0) { Debug.Assert(rowElemList[0] != null && rowElemList[0] is XmlBoundElement); - XmlBoundElement subRowElem = (XmlBoundElement)(rowElemList[0]); + XmlBoundElement? subRowElem = (XmlBoundElement?)(rowElemList[0]); rowElemList.RemoveAt(0); // Expect rowElem to have a DataTable schema, since it is a sub-region Debug.Assert(subRowElem != null); @@ -2660,12 +2678,12 @@ private void OnNodeInsertedInTree(XmlNode node) // "node" was inserting into a disconnected tree from oldParent==null state private void OnNodeInsertedInFragment(XmlNode node) { - XmlBoundElement be; + XmlBoundElement? be; if (_mapper.GetRegion(node, out be)) { if (be == node) { - Debug.Assert(!IsRowLive(be.Row)); + Debug.Assert(!IsRowLive(be.Row!)); SetNestedParentRegion(be); } else @@ -2676,7 +2694,7 @@ private void OnNodeInsertedInFragment(XmlNode node) while (rowElemList.Count > 0) { Debug.Assert(rowElemList[0] != null && rowElemList[0] is XmlBoundElement); - XmlBoundElement subRowElem = (XmlBoundElement)(rowElemList[0]); + XmlBoundElement subRowElem = (XmlBoundElement)(rowElemList[0]!); rowElemList.RemoveAt(0); SetNestedParentRegion(subRowElem, be); } @@ -2708,7 +2726,7 @@ private void OnRowElementInsertedInTree(XmlBoundElement rowElem, ArrayList rowEl #if DEBUG try { - Debug.Assert(row.Table.DataSet.EnforceConstraints == false); + Debug.Assert(row.Table.DataSet!.EnforceConstraints == false); #endif row.Table.Rows.Add(row); SetNestedParentRegion(rowElem); @@ -2732,7 +2750,7 @@ private void OnRowElementInsertedInTree(XmlBoundElement rowElem, ArrayList rowEl #if DEBUG try { - Debug.Assert(row.Table.DataSet.EnforceConstraints == false); + Debug.Assert(row.Table.DataSet!.EnforceConstraints == false); #endif // Change the row status to be alive (unchanged) row.RejectChanges(); @@ -2770,7 +2788,7 @@ private void EnsureDisconnectedDataRow(XmlBoundElement rowElem) #if DEBUG try { - Debug.Assert(row.Table.DataSet.EnforceConstraints == false); + Debug.Assert(row.Table.DataSet!.EnforceConstraints == false); #endif SetNestedParentRegion(rowElem); #if DEBUG @@ -2812,7 +2830,7 @@ private void EnsureDisconnectedDataRow(XmlBoundElement rowElem) private void OnNonRowElementInsertedInTree(XmlNode node, XmlBoundElement rowElement, ArrayList rowElemList) { // non-row-elem is beeing inserted - DataRow row = rowElement.Row; + DataRow? row = rowElement.Row; // Region should already have an associated data row (otherwise how was the original row-elem inserted ?) Debug.Assert(row != null); SynchronizeRowFromRowElement(rowElement); @@ -2828,7 +2846,7 @@ private void OnNonRowElementInsertedInTree(XmlNode node, XmlBoundElement rowElem private void OnNonRowElementInsertedInFragment(XmlNode node, XmlBoundElement rowElement, ArrayList rowElemList) { // non-row-elem is beeing inserted - DataRow row = rowElement.Row; + DataRow? row = rowElement.Row; // Region should already have an associated data row (otherwise how was the original row-elem inserted ?) Debug.Assert(row != null); // Since oldParent == null, the only 2 row states should have been Detached or Deleted @@ -2843,21 +2861,21 @@ private void SetNestedParentRegion(XmlBoundElement childRowElem) { Debug.Assert(childRowElem.Row != null); - XmlBoundElement parentRowElem; + XmlBoundElement? parentRowElem; _mapper.GetRegion(childRowElem.ParentNode, out parentRowElem); SetNestedParentRegion(childRowElem, parentRowElem); } - private void SetNestedParentRegion(XmlBoundElement childRowElem, XmlBoundElement parentRowElem) + private void SetNestedParentRegion(XmlBoundElement childRowElem, XmlBoundElement? parentRowElem) { - DataRow childRow = childRowElem.Row; + DataRow childRow = childRowElem.Row!; if (parentRowElem == null) { SetNestedParentRow(childRow, null); return; } + Debug.Assert(parentRowElem.Row != null); DataRow parentRow = parentRowElem.Row; - Debug.Assert(parentRow != null); // We should set it only if there is a nested relationship between this child and parent regions DataRelation[] relations = childRow.Table.NestedParentRelations; if (relations.Length != 0 && relations[0].ParentTable == parentRow.Table) // just backward compatable @@ -2908,25 +2926,25 @@ internal static bool IsOnlyWhitespace( string str ) { } */ - protected override XPathNavigator CreateNavigator(XmlNode node) + protected override XPathNavigator? CreateNavigator(XmlNode node) { Debug.Assert(node.OwnerDocument == this || node == this); if (XPathNodePointer.s_xmlNodeType_To_XpathNodeType_Map[(int)(node.NodeType)] == -1) return null; if (IsTextNode(node.NodeType)) { - XmlNode parent = node.ParentNode; + XmlNode? parent = node.ParentNode; if (parent != null && parent.NodeType == XmlNodeType.Attribute) return null; else { #if DEBUG //if current node is a text node, its parent node has to be foliated - XmlBoundElement be = node.ParentNode as XmlBoundElement; + XmlBoundElement? be = node.ParentNode as XmlBoundElement; if (be != null) Debug.Assert(be.IsFoliated); #endif - XmlNode prevSib = node.PreviousSibling; + XmlNode? prevSib = node.PreviousSibling; while (prevSib != null && IsTextNode(prevSib.NodeType)) { node = prevSib; @@ -2944,14 +2962,14 @@ private void AssertLiveRows(XmlNode node) IsFoliationEnabled = false; try { - XmlBoundElement rowElement = node as XmlBoundElement; + XmlBoundElement? rowElement = node as XmlBoundElement; if (rowElement != null && rowElement.Row != null) Debug.Assert(IsRowLive(rowElement.Row)); TreeIterator iter = new TreeIterator(node); for (bool fMore = iter.NextRowElement(); fMore; fMore = iter.NextRowElement()) { rowElement = iter.CurrentNode as XmlBoundElement; - Debug.Assert(rowElement.Row != null); + Debug.Assert(rowElement!.Row != null); Debug.Assert(IsRowLive(rowElement.Row)); } } @@ -2967,14 +2985,14 @@ private void AssertNonLiveRows(XmlNode node) IsFoliationEnabled = false; try { - XmlBoundElement rowElement = node as XmlBoundElement; + XmlBoundElement? rowElement = node as XmlBoundElement; if (rowElement != null && rowElement.Row != null) Debug.Assert(!IsRowLive(rowElement.Row)); TreeIterator iter = new TreeIterator(node); for (bool fMore = iter.NextRowElement(); fMore; fMore = iter.NextRowElement()) { rowElement = iter.CurrentNode as XmlBoundElement; - Debug.Assert(rowElement.Row != null); + Debug.Assert(rowElement!.Row != null); Debug.Assert(!IsRowLive(rowElement.Row)); } } @@ -2984,7 +3002,7 @@ private void AssertNonLiveRows(XmlNode node) } } - public override XmlElement GetElementById(string elemId) + public override XmlElement? GetElementById(string elemId) { throw new NotSupportedException(SR.DataDom_NotSupport_GetElementById); } @@ -3002,9 +3020,9 @@ public override XmlNodeList GetElementsByTagName(string name) // after adding Namespace support foir datatable, DataSet does not guarantee that infered tabels would be in the same sequence as they rae in XML, because // of Namespace. if a table is in different namespace than its children and DataSet, that table would efinetely be added to DataSet after its children. Its By Design // so in order to maintain backward compatability, we reorder the copy of the datatable collection and use it - private DataTable[] OrderTables(DataSet ds) + private DataTable[] OrderTables(DataSet? ds) { - DataTable[] retValue = null; + DataTable[]? retValue = null; if (ds == null || ds.Tables.Count == 0) { retValue = Array.Empty(); @@ -3019,7 +3037,7 @@ private DataTable[] OrderTables(DataSet ds) if (null == retValue) { - retValue = new DataTable[ds.Tables.Count]; + retValue = new DataTable[ds!.Tables.Count]; List tableList = new List(); // first take the root tables that have no parent foreach (DataTable dt in ds.Tables) diff --git a/src/libraries/System.Data.Common/src/System/Xml/XmlDataImplementation.cs b/src/libraries/System.Data.Common/src/System/Xml/XmlDataImplementation.cs index 957c0c65a55da8..a161154f3152fe 100644 --- a/src/libraries/System.Data.Common/src/System/Xml/XmlDataImplementation.cs +++ b/src/libraries/System.Data.Common/src/System/Xml/XmlDataImplementation.cs @@ -1,9 +1,6 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. -// TODO: Enable after System.Private.Xml is annotated -#nullable disable - #pragma warning disable 618 // ignore obsolete warning about XmlDataDocument namespace System.Xml 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() 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, diff --git a/src/libraries/System.Private.DataContractSerialization/src/System.Private.DataContractSerialization.csproj b/src/libraries/System.Private.DataContractSerialization/src/System.Private.DataContractSerialization.csproj index 7ab4ab7cd8d07f..0eec0d2fdb81bf 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System.Private.DataContractSerialization.csproj +++ b/src/libraries/System.Private.DataContractSerialization/src/System.Private.DataContractSerialization.csproj @@ -1,4 +1,4 @@ - + $(NoWarn);1634;1691;649 true @@ -7,6 +7,7 @@ $(NetCoreAppCurrent) false + enable System\Runtime\Serialization diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/AccessorBuilder.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/AccessorBuilder.cs index 47d02fbf303b4d..5cbe9354655b5a 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/AccessorBuilder.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/AccessorBuilder.cs @@ -13,15 +13,15 @@ namespace System.Runtime.Serialization { internal static class FastInvokerBuilder { - public delegate void Setter(ref object obj, object value); - public delegate object Getter(object obj); + public delegate void Setter(ref object obj, object? value); + public delegate object? Getter(object obj); private delegate void StructSetDelegate(ref T obj, TArg value); private delegate TResult StructGetDelegate(ref T obj); - private static readonly MethodInfo s_createGetterInternal = typeof(FastInvokerBuilder).GetMethod(nameof(CreateGetterInternal), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static); - private static readonly MethodInfo s_createSetterInternal = typeof(FastInvokerBuilder).GetMethod(nameof(CreateSetterInternal), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static); - private static readonly MethodInfo s_make = typeof(FastInvokerBuilder).GetMethod(nameof(Make), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static); + private static readonly MethodInfo s_createGetterInternal = typeof(FastInvokerBuilder).GetMethod(nameof(CreateGetterInternal), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)!; + private static readonly MethodInfo s_createSetterInternal = typeof(FastInvokerBuilder).GetMethod(nameof(CreateSetterInternal), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)!; + private static readonly MethodInfo s_make = typeof(FastInvokerBuilder).GetMethod(nameof(Make), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)!; public static Func GetMakeNewInstanceFunc(Type type) { @@ -31,25 +31,23 @@ public static Func GetMakeNewInstanceFunc(Type type) public static Getter CreateGetter(MemberInfo memberInfo) { - if (memberInfo is PropertyInfo) + if (memberInfo is PropertyInfo propInfo) { - var propInfo = (PropertyInfo)memberInfo; - var createGetterGeneric = s_createGetterInternal.MakeGenericMethod(propInfo.DeclaringType, propInfo.PropertyType).CreateDelegate>(); + var createGetterGeneric = s_createGetterInternal.MakeGenericMethod(propInfo.DeclaringType!, propInfo.PropertyType).CreateDelegate>(); Getter accessor = createGetterGeneric(propInfo); return accessor; } - else if (memberInfo is FieldInfo) + else if (memberInfo is FieldInfo fieldInfo) { return (obj) => { - FieldInfo fieldInfo = (FieldInfo)memberInfo; var value = fieldInfo.GetValue(obj); return value; }; } else { - throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.InvalidMember, DataContract.GetClrTypeFullName(memberInfo.DeclaringType), memberInfo.Name))); + throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.InvalidMember, DataContract.GetClrTypeFullName(memberInfo.DeclaringType!), memberInfo.Name))); } } @@ -60,7 +58,7 @@ public static Setter CreateSetter(MemberInfo memberInfo) PropertyInfo propInfo = (PropertyInfo)memberInfo; if (propInfo.CanWrite) { - var buildSetAccessorGeneric = s_createSetterInternal.MakeGenericMethod(propInfo.DeclaringType, propInfo.PropertyType).CreateDelegate>(); + var buildSetAccessorGeneric = s_createSetterInternal.MakeGenericMethod(propInfo.DeclaringType!, propInfo.PropertyType).CreateDelegate>(); Setter accessor = buildSetAccessorGeneric(propInfo); return accessor; } @@ -72,14 +70,14 @@ public static Setter CreateSetter(MemberInfo memberInfo) else if (memberInfo is FieldInfo) { FieldInfo fieldInfo = (FieldInfo)memberInfo; - return (ref object obj, object val) => + return (ref object obj, object? val) => { fieldInfo.SetValue(obj, val); }; } else { - throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.InvalidMember, DataContract.GetClrTypeFullName(memberInfo.DeclaringType), memberInfo.Name))); + throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.InvalidMember, DataContract.GetClrTypeFullName(memberInfo.DeclaringType!), memberInfo.Name))); } } @@ -111,7 +109,7 @@ private static Getter CreateGetterInternal(Property if (typeof(DeclaringType).IsValueType) { - var getMethod = propInfo.GetMethod.CreateDelegate>(); + var getMethod = propInfo.GetMethod!.CreateDelegate>(); return (obj) => { @@ -121,7 +119,7 @@ private static Getter CreateGetterInternal(Property } else { - var getMethod = propInfo.GetMethod.CreateDelegate>(); + var getMethod = propInfo.GetMethod!.CreateDelegate>(); return (obj) => { @@ -136,14 +134,14 @@ private static Setter CreateSetterInternal(Property { if (propInfo.Name == "Key") { - return (ref object obj, object val) => + return (ref object obj, object? val) => { ((IKeyValue)obj).Key = val; }; } else { - return (ref object obj, object val) => + return (ref object obj, object? val) => { ((IKeyValue)obj).Value = val; }; @@ -152,22 +150,22 @@ private static Setter CreateSetterInternal(Property if (typeof(DeclaringType).IsValueType) { - var setMethod = propInfo.SetMethod.CreateDelegate>(); + var setMethod = propInfo.SetMethod!.CreateDelegate>(); - return (ref object obj, object val) => + return (ref object obj, object? val) => { var unboxed = (DeclaringType)obj; - setMethod(ref unboxed, (PropertyType)val); - obj = unboxed; + setMethod(ref unboxed, (PropertyType)val!); + obj = unboxed!; }; } else { - var setMethod = propInfo.SetMethod.CreateDelegate>(); + var setMethod = propInfo.SetMethod!.CreateDelegate>(); - return (ref object obj, object val) => + return (ref object obj, object? val) => { - setMethod((DeclaringType)obj, (PropertyType)val); + setMethod((DeclaringType)obj, (PropertyType)val!); }; } } @@ -180,11 +178,11 @@ public static T CreateDelegate(this MethodInfo method) where T : class { try { - return method.CreateDelegate(typeof(T)) as T; + return (method.CreateDelegate(typeof(T)) as T)!; } catch (Exception e) { - throw new InvalidOperationException(SR.Format(SR.FailedToCreateMethodDelegate, method.Name, method.DeclaringType.FullName), e); + throw new InvalidOperationException(SR.Format(SR.FailedToCreateMethodDelegate, method.Name, method.DeclaringType!.FullName), e); } } } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Attributes.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Attributes.cs index df50b3908c1126..9da06545c254d2 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Attributes.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Attributes.cs @@ -23,18 +23,18 @@ internal class Attributes DictionaryGlobals.XsiTypeLocalName }; - internal string Id; - internal string Ref; - internal string XsiTypeName; - internal string XsiTypeNamespace; - internal string XsiTypePrefix; + internal string Id = null!; // initialized in Reset + internal string Ref = null!; // initialized in Reset + internal string? XsiTypeName; + internal string? XsiTypeNamespace; + internal string? XsiTypePrefix; internal bool XsiNil; - internal string ClrAssembly; - internal string ClrType; + internal string? ClrAssembly; + internal string? ClrType; internal int ArraySZSize; - internal string FactoryTypeName; - internal string FactoryTypeNamespace; - internal string FactoryTypePrefix; + internal string? FactoryTypeName; + internal string? FactoryTypeNamespace; + internal string? FactoryTypePrefix; internal bool UnrecognizedAttributesFound; internal void Read(XmlReaderDelegator reader) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ClassDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ClassDataContract.cs index cf1f749731e357..fd5e9ac4349008 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ClassDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ClassDataContract.cs @@ -17,6 +17,7 @@ namespace System.Runtime.Serialization using System.Xml; using DataContractDictionary = System.Collections.Generic.Dictionary; using System.Linq; + using System.Diagnostics.CodeAnalysis; #if USE_REFEMIT public sealed class ClassDataContract : DataContract @@ -24,13 +25,13 @@ public sealed class ClassDataContract : DataContract internal sealed class ClassDataContract : DataContract #endif { - public XmlDictionaryString[] ContractNamespaces; + public XmlDictionaryString[]? ContractNamespaces; - public XmlDictionaryString[] MemberNames; + public XmlDictionaryString[]? MemberNames; - public XmlDictionaryString[] MemberNamespaces; + public XmlDictionaryString[]? MemberNamespaces; - private XmlDictionaryString[] _childElementNamespaces; + private XmlDictionaryString?[]? _childElementNamespaces; private ClassDataContractCriticalHelper _helper; @@ -46,26 +47,27 @@ private ClassDataContract(Type type, XmlDictionaryString ns, string[] memberName InitClassDataContract(); } + [MemberNotNull(nameof(_helper))] private void InitClassDataContract() { - _helper = base.Helper as ClassDataContractCriticalHelper; + _helper = (base.Helper as ClassDataContractCriticalHelper)!; this.ContractNamespaces = _helper.ContractNamespaces; this.MemberNames = _helper.MemberNames; this.MemberNamespaces = _helper.MemberNamespaces; _isScriptObject = _helper.IsScriptObject; } - internal ClassDataContract BaseContract + internal ClassDataContract? BaseContract { get { return _helper.BaseContract; } } - internal List Members + internal List? Members { get { return _helper.Members; } } - public XmlDictionaryString[] ChildElementNamespaces + public XmlDictionaryString?[]? ChildElementNamespaces { get { @@ -77,7 +79,7 @@ public XmlDictionaryString[] ChildElementNamespaces { if (_helper.ChildElementNamespaces == null) { - XmlDictionaryString[] tempChildElementamespaces = CreateChildElementNamespaces(); + XmlDictionaryString?[]? tempChildElementamespaces = CreateChildElementNamespaces(); Interlocked.MemoryBarrier(); _helper.ChildElementNamespaces = tempChildElementamespaces; } @@ -93,36 +95,36 @@ public XmlDictionaryString[] ChildElementNamespaces } } - internal MethodInfo OnSerializing + internal MethodInfo? OnSerializing { get { return _helper.OnSerializing; } } - internal MethodInfo OnSerialized + internal MethodInfo? OnSerialized { get { return _helper.OnSerialized; } } - internal MethodInfo OnDeserializing + internal MethodInfo? OnDeserializing { get { return _helper.OnDeserializing; } } - internal MethodInfo OnDeserialized + internal MethodInfo? OnDeserialized { get { return _helper.OnDeserialized; } } - internal MethodInfo ExtensionDataSetMethod + internal MethodInfo? ExtensionDataSetMethod { get { return _helper.ExtensionDataSetMethod; } } - public override DataContractDictionary KnownDataContracts + public override DataContractDictionary? KnownDataContracts { get { return _helper.KnownDataContracts; } @@ -147,38 +149,43 @@ public bool HasExtensionData set { _helper.HasExtensionData = value; } } + [MemberNotNullWhen(true, nameof(KeyValuePairGenericArguments))] + [MemberNotNullWhen(true, nameof(KeyValuePairAdapterConstructorInfo))] + [MemberNotNullWhen(true, nameof(GetKeyValuePairMethodInfo))] internal bool IsKeyValuePairAdapter { get +#pragma warning disable CS8775 // Member must have a non-null value when exiting in some condition. { return _helper.IsKeyValuePairAdapter; } +#pragma warning restore CS8775 // Member must have a non-null value when exiting in some condition. } - internal Type[] KeyValuePairGenericArguments + internal Type[]? KeyValuePairGenericArguments { get { return _helper.KeyValuePairGenericArguments; } } - internal ConstructorInfo KeyValuePairAdapterConstructorInfo + internal ConstructorInfo? KeyValuePairAdapterConstructorInfo { get { return _helper.KeyValuePairAdapterConstructorInfo; } } - internal MethodInfo GetKeyValuePairMethodInfo + internal MethodInfo? GetKeyValuePairMethodInfo { get { return _helper.GetKeyValuePairMethodInfo; } } - internal ConstructorInfo GetISerializableConstructor() + internal ConstructorInfo? GetISerializableConstructor() { return _helper.GetISerializableConstructor(); } - private ConstructorInfo _nonAttributedTypeConstructor; + private ConstructorInfo? _nonAttributedTypeConstructor; - internal ConstructorInfo GetNonAttributedTypeConstructor() + internal ConstructorInfo? GetNonAttributedTypeConstructor() { if (_nonAttributedTypeConstructor == null) { @@ -189,7 +196,7 @@ internal ConstructorInfo GetNonAttributedTypeConstructor() return _nonAttributedTypeConstructor; } - private Func _makeNewInstance; + private Func? _makeNewInstance; private Func MakeNewInstance { get @@ -203,9 +210,9 @@ private Func MakeNewInstance } } - internal bool CreateNewInstanceViaDefaultConstructor(out object obj) + internal bool CreateNewInstanceViaDefaultConstructor([NotNullWhen(true)] out object? obj) { - ConstructorInfo ci = GetNonAttributedTypeConstructor(); + ConstructorInfo? ci = GetNonAttributedTypeConstructor(); if (ci == null) { obj = null; @@ -283,7 +290,7 @@ internal XmlFormatClassReaderDelegate XmlFormatReaderDelegate internal static ClassDataContract CreateClassDataContractForKeyValue(Type type, XmlDictionaryString ns, string[] memberNames) { - ClassDataContract cdc = (ClassDataContract)DataContract.GetDataContractFromGeneratedAssembly(type); + ClassDataContract? cdc = (ClassDataContract?)DataContract.GetDataContractFromGeneratedAssembly(type); if (cdc == null) { return new ClassDataContract(type, ns, memberNames); @@ -298,10 +305,10 @@ internal static ClassDataContract CreateClassDataContractForKeyValue(Type type, internal static void CheckAndAddMember(List members, DataMember memberContract, Dictionary memberNamesTable) { - DataMember existingMemberContract; + DataMember? existingMemberContract; if (memberNamesTable.TryGetValue(memberContract.Name, out existingMemberContract)) { - Type declaringType = memberContract.MemberInfo.DeclaringType; + Type declaringType = memberContract.MemberInfo.DeclaringType!; DataContract.ThrowInvalidDataContractException( SR.Format((declaringType.IsEnum ? SR.DupEnumMemberValue : SR.DupMemberName), existingMemberContract.MemberInfo.Name, @@ -314,7 +321,7 @@ internal static void CheckAndAddMember(List members, DataMember memb members.Add(memberContract); } - internal static XmlDictionaryString GetChildNamespaceToDeclare(DataContract dataContract, Type childType, XmlDictionary dictionary) + internal static XmlDictionaryString? GetChildNamespaceToDeclare(DataContract dataContract, Type childType, XmlDictionary dictionary) { childType = DataContract.UnwrapNullableType(childType); if (!childType.IsEnum && !Globals.TypeOfIXmlSerializable.IsAssignableFrom(childType) @@ -412,8 +419,8 @@ internal static bool IsNonAttributedTypeValidForSerialization(Type type) private static string GetGeneralTypeName(Type type) { return type.IsGenericType && !type.IsGenericParameter - ? type.GetGenericTypeDefinition().FullName - : type.FullName; + ? type.GetGenericTypeDefinition().FullName! + : type.FullName!; } internal static bool IsKnownSerializableType(Type type) @@ -429,23 +436,23 @@ internal static bool IsNonSerializedMember(Type type, string memberName) { string typeFullName = GetGeneralTypeName(type); - string[] members; + string[]? members; return s_knownSerializableTypeInfos.TryGetValue(typeFullName, out members) && members.Contains(memberName); } - private XmlDictionaryString[] CreateChildElementNamespaces() + private XmlDictionaryString?[]? CreateChildElementNamespaces() { if (Members == null) return null; - XmlDictionaryString[] baseChildElementNamespaces = null; + XmlDictionaryString?[]? baseChildElementNamespaces = null; if (this.BaseContract != null) baseChildElementNamespaces = this.BaseContract.ChildElementNamespaces; int baseChildElementNamespaceCount = (baseChildElementNamespaces != null) ? baseChildElementNamespaces.Length : 0; - XmlDictionaryString[] childElementNamespaces = new XmlDictionaryString[Members.Count + baseChildElementNamespaceCount]; + XmlDictionaryString?[] childElementNamespaces = new XmlDictionaryString?[Members.Count + baseChildElementNamespaceCount]; if (baseChildElementNamespaceCount > 0) - Array.Copy(baseChildElementNamespaces, childElementNamespaces, baseChildElementNamespaces.Length); + Array.Copy(baseChildElementNamespaces!, childElementNamespaces, baseChildElementNamespaces!.Length); XmlDictionary dictionary = new XmlDictionary(); for (int i = 0; i < this.Members.Count; i++) @@ -461,8 +468,10 @@ private void EnsureMethodsImported() _helper.EnsureMethodsImported(); } - public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) + public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext? context) { + Debug.Assert(context != null); + if (_isScriptObject) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.UnexpectedContractType, DataContract.GetClrTypeFullName(this.GetType()), DataContract.GetClrTypeFullName(UnderlyingType)))); @@ -470,14 +479,14 @@ public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, Xml XmlFormatWriterDelegate(xmlWriter, obj, context, this); } - public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context) + public override object? ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext? context) { if (_isScriptObject) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.UnexpectedContractType, DataContract.GetClrTypeFullName(this.GetType()), DataContract.GetClrTypeFullName(UnderlyingType)))); } xmlReader.Read(); - object o = XmlFormatReaderDelegate(xmlReader, context, MemberNames, MemberNamespaces); + object? o = XmlFormatReaderDelegate(xmlReader, context, MemberNames, MemberNamespaces); xmlReader.ReadEndElement(); return o; } @@ -487,7 +496,7 @@ public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSeria /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// - internal bool RequiresMemberAccessForRead(SecurityException securityException) + internal bool RequiresMemberAccessForRead(SecurityException? securityException) { EnsureMethodsImported(); if (!IsTypeVisible(UnderlyingType)) @@ -530,7 +539,7 @@ internal bool RequiresMemberAccessForRead(SecurityException securityException) new SecurityException(SR.Format( SR.PartialTrustDataContractOnDeserializingNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), - this.OnDeserializing.Name), + this.OnDeserializing!.Name), securityException)); } return true; @@ -544,7 +553,7 @@ internal bool RequiresMemberAccessForRead(SecurityException securityException) new SecurityException(SR.Format( SR.PartialTrustDataContractOnDeserializedNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), - this.OnDeserialized.Name), + this.OnDeserialized!.Name), securityException)); } return true; @@ -590,7 +599,7 @@ internal bool RequiresMemberAccessForRead(SecurityException securityException) /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// - internal bool RequiresMemberAccessForWrite(SecurityException securityException) + internal bool RequiresMemberAccessForWrite(SecurityException? securityException) { EnsureMethodsImported(); @@ -618,7 +627,7 @@ internal bool RequiresMemberAccessForWrite(SecurityException securityException) new SecurityException(SR.Format( SR.PartialTrustDataContractOnSerializingNotPublic, DataContract.GetClrTypeFullName(this.UnderlyingType), - this.OnSerializing.Name), + this.OnSerializing!.Name), securityException)); } return true; @@ -632,7 +641,7 @@ internal bool RequiresMemberAccessForWrite(SecurityException securityException) new SecurityException(SR.Format( SR.PartialTrustDataContractOnSerializedNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), - this.OnSerialized.Name), + this.OnSerialized!.Name), securityException)); } return true; @@ -675,14 +684,14 @@ internal bool RequiresMemberAccessForWrite(SecurityException securityException) private class ClassDataContractCriticalHelper : DataContract.DataContractCriticalHelper { - private static Type[] s_serInfoCtorArgs; - - private ClassDataContract _baseContract; - private List _members; - private MethodInfo _onSerializing, _onSerialized; - private MethodInfo _onDeserializing, _onDeserialized; - private MethodInfo _extensionDataSetMethod; - private DataContractDictionary _knownDataContracts; + private static Type[]? s_serInfoCtorArgs; + + private ClassDataContract? _baseContract; + private List? _members; + private MethodInfo? _onSerializing, _onSerialized; + private MethodInfo? _onDeserializing, _onDeserialized; + private MethodInfo? _extensionDataSetMethod; + private DataContractDictionary? _knownDataContracts; private bool _isISerializable; private bool _isKnownTypeAttributeChecked; private bool _isMethodChecked; @@ -698,17 +707,13 @@ private class ClassDataContractCriticalHelper : DataContract.DataContractCritica private bool _hasExtensionData; private readonly bool _isScriptObject; - private XmlDictionaryString[] _childElementNamespaces; - private XmlFormatClassReaderDelegate _xmlFormatReaderDelegate; - private XmlFormatClassWriterDelegate _xmlFormatWriterDelegate; - - public XmlDictionaryString[] ContractNamespaces; - public XmlDictionaryString[] MemberNames; - public XmlDictionaryString[] MemberNamespaces; + private XmlDictionaryString?[]? _childElementNamespaces; + private XmlFormatClassReaderDelegate? _xmlFormatReaderDelegate; + private XmlFormatClassWriterDelegate? _xmlFormatWriterDelegate; - internal ClassDataContractCriticalHelper() : base() - { - } + public XmlDictionaryString[]? ContractNamespaces; + public XmlDictionaryString[]? MemberNames; + public XmlDictionaryString[]? MemberNamespaces; internal ClassDataContractCriticalHelper(Type type) : base(type) { @@ -724,7 +729,7 @@ internal ClassDataContractCriticalHelper(Type type) : base(type) EnsureMethodsImported(); return; } - Type baseType = type.BaseType; + Type? baseType = type.BaseType; _isISerializable = (Globals.TypeOfISerializable.IsAssignableFrom(type)); SetIsNonAttributedType(type); if (_isISerializable) @@ -800,12 +805,12 @@ internal ClassDataContractCriticalHelper(Type type) : base(type) } else { - baseMemberCount = BaseContract.MemberNames.Length; + baseMemberCount = BaseContract.MemberNames!.Length; MemberNames = new XmlDictionaryString[Members.Count + baseMemberCount]; Array.Copy(BaseContract.MemberNames, MemberNames, baseMemberCount); MemberNamespaces = new XmlDictionaryString[Members.Count + baseMemberCount]; - Array.Copy(BaseContract.MemberNamespaces, MemberNamespaces, baseMemberCount); - baseContractCount = BaseContract.ContractNamespaces.Length; + Array.Copy(BaseContract.MemberNamespaces!, MemberNamespaces, baseMemberCount); + baseContractCount = BaseContract.ContractNamespaces!.Length; ContractNamespaces = new XmlDictionaryString[1 + baseContractCount]; Array.Copy(BaseContract.ContractNamespaces, ContractNamespaces, baseContractCount); } @@ -843,13 +848,13 @@ internal ClassDataContractCriticalHelper(Type type, XmlDictionaryString ns, stri private void EnsureIsReferenceImported(Type type) { - DataContractAttribute dataContractAttribute; + DataContractAttribute? dataContractAttribute; bool isReference = false; bool hasDataContractAttribute = TryGetDCAttribute(type, out dataContractAttribute); if (BaseContract != null) { - if (hasDataContractAttribute && dataContractAttribute.IsReferenceSetExplicitly) + if (hasDataContractAttribute && dataContractAttribute!.IsReferenceSetExplicitly) { bool baseIsReference = this.BaseContract.IsReference; if ((baseIsReference && !dataContractAttribute.IsReference) || @@ -875,7 +880,7 @@ private void EnsureIsReferenceImported(Type type) } else if (hasDataContractAttribute) { - if (dataContractAttribute.IsReference) + if (dataContractAttribute!.IsReference) isReference = dataContractAttribute.IsReference; } @@ -893,6 +898,8 @@ private void EnsureIsReferenceImported(Type type) this.IsReference = isReference; } + [MemberNotNull(nameof(_members))] + [MemberNotNull(nameof(Members))] private void ImportDataMembers() { Type type = this.UnderlyingType; @@ -922,7 +929,7 @@ private void ImportDataMembers() if (memberAttributes != null && memberAttributes.Length > 0) { if (memberAttributes.Length > 1) - ThrowInvalidDataContractException(SR.Format(SR.TooManyDataMembers, DataContract.GetClrTypeFullName(member.DeclaringType), member.Name)); + ThrowInvalidDataContractException(SR.Format(SR.TooManyDataMembers, DataContract.GetClrTypeFullName(member.DeclaringType!), member.Name)); DataMember memberContract = new DataMember(member); @@ -930,10 +937,10 @@ private void ImportDataMembers() { PropertyInfo property = (PropertyInfo)member; - MethodInfo getMethod = property.GetMethod; + MethodInfo? getMethod = property.GetMethod; if (getMethod != null && IsMethodOverriding(getMethod)) continue; - MethodInfo setMethod = property.SetMethod; + MethodInfo? setMethod = property.SetMethod; if (setMethod != null && IsMethodOverriding(setMethod)) continue; if (getMethod == null) @@ -968,7 +975,7 @@ private void ImportDataMembers() { ThrowInvalidDataContractException( SR.Format(SR.IsRequiredDataMemberOnIsReferenceDataContractType, - DataContract.GetClrTypeFullName(member.DeclaringType), + DataContract.GetClrTypeFullName(member.DeclaringType!), member.Name, true), type); } memberContract.EmitDefaultValue = memberAttribute.EmitDefaultValue; @@ -978,8 +985,8 @@ private void ImportDataMembers() } else if (!isPodSerializable) { - FieldInfo field = member as FieldInfo; - PropertyInfo property = member as PropertyInfo; + FieldInfo? field = member as FieldInfo; + PropertyInfo? property = member as PropertyInfo; if ((field == null && property == null) || (field != null && field.IsInitOnly)) continue; @@ -987,18 +994,18 @@ private void ImportDataMembers() if (memberAttributes != null && memberAttributes.Length > 0) { if (memberAttributes.Length > 1) - ThrowInvalidDataContractException(SR.Format(SR.TooManyIgnoreDataMemberAttributes, DataContract.GetClrTypeFullName(member.DeclaringType), member.Name)); + ThrowInvalidDataContractException(SR.Format(SR.TooManyIgnoreDataMemberAttributes, DataContract.GetClrTypeFullName(member.DeclaringType!), member.Name)); else continue; } DataMember memberContract = new DataMember(member); if (property != null) { - MethodInfo getMethod = property.GetGetMethod(); + MethodInfo? getMethod = property.GetGetMethod(); if (getMethod == null || IsMethodOverriding(getMethod) || getMethod.GetParameters().Length > 0) continue; - MethodInfo setMethod = property.SetMethod; + MethodInfo? setMethod = property.SetMethod; if (setMethod == null) { if (!SetIfGetOnlyCollection(memberContract)) @@ -1017,7 +1024,7 @@ private void ImportDataMembers() } else { - FieldInfo field = member as FieldInfo; + FieldInfo? field = member as FieldInfo; bool canSerializeMember; @@ -1040,14 +1047,14 @@ private void ImportDataMembers() DataMember memberContract = new DataMember(member); memberContract.Name = DataContract.EncodeLocalName(member.Name); - object[] optionalFields = field.GetCustomAttributes(Globals.TypeOfOptionalFieldAttribute, false); + object[] optionalFields = field!.GetCustomAttributes(Globals.TypeOfOptionalFieldAttribute, false); if (optionalFields == null || optionalFields.Length == 0) { if (this.IsReference) { ThrowInvalidDataContractException( SR.Format(SR.NonOptionalFieldMemberOnIsReferenceSerializableType, - DataContract.GetClrTypeFullName(member.DeclaringType), + DataContract.GetClrTypeFullName(member.DeclaringType!), member.Name, true), type); } memberContract.IsRequired = true; @@ -1064,11 +1071,12 @@ private void ImportDataMembers() Interlocked.MemoryBarrier(); _members = tempMembers; + Debug.Assert(Members != null); } - private static bool CanSerializeMember(FieldInfo field) + private static bool CanSerializeMember(FieldInfo? field) { - return field != null && !ClassDataContract.IsNonSerializedMember(field.DeclaringType, field.Name); + return field != null && !ClassDataContract.IsNonSerializedMember(field.DeclaringType!, field.Name); } private bool SetIfGetOnlyCollection(DataMember memberContract) @@ -1091,16 +1099,16 @@ private void SetIfMembersHaveConflict(List members) List membersInHierarchy = new List(); foreach (DataMember member in members) { - membersInHierarchy.Add(new Member(member, this.StableName.Namespace, baseTypeIndex)); + membersInHierarchy.Add(new Member(member, this.StableName!.Namespace, baseTypeIndex)); } - ClassDataContract currContract = BaseContract; + ClassDataContract? currContract = BaseContract; while (currContract != null) { baseTypeIndex++; - foreach (DataMember member in currContract.Members) + foreach (DataMember member in currContract.Members!) { - membersInHierarchy.Add(new Member(member, currContract.StableName.Namespace, baseTypeIndex)); + membersInHierarchy.Add(new Member(member, currContract.StableName!.Namespace, baseTypeIndex)); } currContract = currContract.BaseContract; } @@ -1179,7 +1187,7 @@ internal void EnsureMethodsImported() for (int i = 0; i < methods.Length; i++) { MethodInfo method = methods[i]; - Type prevAttributeType = null; + Type? prevAttributeType = null; ParameterInfo[] parameters = method.GetParameters(); if (HasExtensionData && IsValidExtensionDataSetMethod(method, parameters)) { @@ -1208,6 +1216,8 @@ private bool IsValidExtensionDataSetMethod(MethodInfo method, ParameterInfo[] pa { if (method.Name == Globals.ExtensionDataSetExplicitMethod || method.Name == Globals.ExtensionDataSetMethod) { + Debug.Assert(method.DeclaringType != null); + if (_extensionDataSetMethod != null) ThrowInvalidDataContractException(SR.Format(SR.DuplicateExtensionDataSetMethod, method, _extensionDataSetMethod, DataContract.GetClrTypeFullName(method.DeclaringType))); if (method.ReturnType != Globals.TypeOfVoid) @@ -1219,10 +1229,12 @@ private bool IsValidExtensionDataSetMethod(MethodInfo method, ParameterInfo[] pa return false; } - private static bool IsValidCallback(MethodInfo method, ParameterInfo[] parameters, Type attributeType, MethodInfo currentCallback, ref Type prevAttributeType) + private static bool IsValidCallback(MethodInfo method, ParameterInfo[] parameters, Type attributeType, MethodInfo? currentCallback, ref Type? prevAttributeType) { if (method.IsDefined(attributeType, false)) { + Debug.Assert(method.DeclaringType != null); + if (currentCallback != null) DataContract.ThrowInvalidDataContractException(SR.Format(SR.DuplicateCallback, method, currentCallback, DataContract.GetClrTypeFullName(method.DeclaringType), attributeType), method.DeclaringType); else if (prevAttributeType != null) @@ -1243,23 +1255,23 @@ private static bool IsValidCallback(MethodInfo method, ParameterInfo[] parameter return false; } - internal ClassDataContract BaseContract + internal ClassDataContract? BaseContract { get { return _baseContract; } set { _baseContract = value; if (_baseContract != null && IsValueType) - ThrowInvalidDataContractException(SR.Format(SR.ValueTypeCannotHaveBaseType, StableName.Name, StableName.Namespace, _baseContract.StableName.Name, _baseContract.StableName.Namespace)); + ThrowInvalidDataContractException(SR.Format(SR.ValueTypeCannotHaveBaseType, StableName!.Name, StableName.Namespace, _baseContract.StableName!.Name, _baseContract.StableName.Namespace)); } } - internal List Members + internal List? Members { get { return _members; } } - internal MethodInfo OnSerializing + internal MethodInfo? OnSerializing { get { @@ -1268,7 +1280,7 @@ internal MethodInfo OnSerializing } } - internal MethodInfo OnSerialized + internal MethodInfo? OnSerialized { get { @@ -1277,7 +1289,7 @@ internal MethodInfo OnSerialized } } - internal MethodInfo OnDeserializing + internal MethodInfo? OnDeserializing { get { @@ -1286,7 +1298,7 @@ internal MethodInfo OnDeserializing } } - internal MethodInfo OnDeserialized + internal MethodInfo? OnDeserialized { get { @@ -1295,7 +1307,7 @@ internal MethodInfo OnDeserialized } } - internal MethodInfo ExtensionDataSetMethod + internal MethodInfo? ExtensionDataSetMethod { get { @@ -1304,7 +1316,7 @@ internal MethodInfo ExtensionDataSetMethod } } - internal override DataContractDictionary KnownDataContracts + internal override DataContractDictionary? KnownDataContracts { get { @@ -1361,14 +1373,14 @@ private void SetKeyValuePairAdapterFlags(Type type) _isKeyValuePairAdapter = true; _keyValuePairGenericArguments = type.GetGenericArguments(); _keyValuePairCtorInfo = type.GetConstructor(Globals.ScanAllMembers, new Type[] { Globals.TypeOfKeyValuePair.MakeGenericType(_keyValuePairGenericArguments) }); - _getKeyValuePairMethodInfo = type.GetMethod("GetKeyValuePair", Globals.ScanAllMembers); + _getKeyValuePairMethodInfo = type.GetMethod("GetKeyValuePair", Globals.ScanAllMembers)!; } } private bool _isKeyValuePairAdapter; - private Type[] _keyValuePairGenericArguments; - private ConstructorInfo _keyValuePairCtorInfo; - private MethodInfo _getKeyValuePairMethodInfo; + private Type[]? _keyValuePairGenericArguments; + private ConstructorInfo? _keyValuePairCtorInfo; + private MethodInfo? _getKeyValuePairMethodInfo; internal bool IsKeyValuePairAdapter { @@ -1380,34 +1392,34 @@ internal bool IsScriptObject get { return _isScriptObject; } } - internal Type[] KeyValuePairGenericArguments + internal Type[]? KeyValuePairGenericArguments { get { return _keyValuePairGenericArguments; } } - internal ConstructorInfo KeyValuePairAdapterConstructorInfo + internal ConstructorInfo? KeyValuePairAdapterConstructorInfo { get { return _keyValuePairCtorInfo; } } - internal MethodInfo GetKeyValuePairMethodInfo + internal MethodInfo? GetKeyValuePairMethodInfo { get { return _getKeyValuePairMethodInfo; } } - internal ConstructorInfo GetISerializableConstructor() + internal ConstructorInfo? GetISerializableConstructor() { if (!IsISerializable) return null; - ConstructorInfo ctor = UnderlyingType.GetConstructor(Globals.ScanAllMembers, null, SerInfoCtorArgs, null); + ConstructorInfo? ctor = UnderlyingType.GetConstructor(Globals.ScanAllMembers, null, SerInfoCtorArgs, null); if (ctor == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.SerializationInfo_ConstructorNotFound, DataContract.GetClrTypeFullName(UnderlyingType)))); return ctor; } - internal ConstructorInfo GetNonAttributedTypeConstructor() + internal ConstructorInfo? GetNonAttributedTypeConstructor() { if (!this.IsNonAttributedType) return null; @@ -1417,26 +1429,26 @@ internal ConstructorInfo GetNonAttributedTypeConstructor() if (type.IsValueType) return null; - ConstructorInfo ctor = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, Array.Empty()); + ConstructorInfo? ctor = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, Array.Empty()); if (ctor == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.NonAttributedSerializableTypesMustHaveDefaultConstructor, DataContract.GetClrTypeFullName(type)))); return ctor; } - internal XmlFormatClassWriterDelegate XmlFormatWriterDelegate + internal XmlFormatClassWriterDelegate? XmlFormatWriterDelegate { get { return _xmlFormatWriterDelegate; } set { _xmlFormatWriterDelegate = value; } } - internal XmlFormatClassReaderDelegate XmlFormatReaderDelegate + internal XmlFormatClassReaderDelegate? XmlFormatReaderDelegate { get { return _xmlFormatReaderDelegate; } set { _xmlFormatReaderDelegate = value; } } - public XmlDictionaryString[] ChildElementNamespaces + public XmlDictionaryString?[]? ChildElementNamespaces { get { return _childElementNamespaces; } set { _childElementNamespaces = value; } @@ -1516,9 +1528,9 @@ internal ClassDataContractCriticalHelper Clone() internal class DataMemberComparer : IComparer { - public int Compare(DataMember x, DataMember y) + public int Compare(DataMember? x, DataMember? y) { - int orderCompare = x.Order - y.Order; + int orderCompare = x!.Order - y!.Order; if (orderCompare != 0) return orderCompare; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CodeGenerator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CodeGenerator.cs index 9cbf641618386e..42bee7c8e89c94 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CodeGenerator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CodeGenerator.cs @@ -11,12 +11,13 @@ using System.IO; using System.Security; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; namespace System.Runtime.Serialization { internal class CodeGenerator { - private static MethodInfo s_getTypeFromHandle; + private static MethodInfo? s_getTypeFromHandle; private static MethodInfo GetTypeFromHandle { get @@ -30,7 +31,7 @@ private static MethodInfo GetTypeFromHandle } } - private static MethodInfo s_objectEquals; + private static MethodInfo? s_objectEquals; private static MethodInfo ObjectEquals { get @@ -44,7 +45,7 @@ private static MethodInfo ObjectEquals } } - private static MethodInfo s_arraySetValue; + private static MethodInfo? s_arraySetValue; private static MethodInfo ArraySetValue { get @@ -58,7 +59,7 @@ private static MethodInfo ArraySetValue } } - private static MethodInfo s_objectToString; + private static MethodInfo? s_objectToString; private static MethodInfo ObjectToString { get @@ -72,7 +73,7 @@ private static MethodInfo ObjectToString } } - private static MethodInfo s_stringFormat; + private static MethodInfo? s_stringFormat; private static MethodInfo StringFormat { get @@ -86,7 +87,7 @@ private static MethodInfo StringFormat } } - private Type _delegateType; + private Type _delegateType = null!; // initialized in BeginMethod #if USE_REFEMIT AssemblyBuilder assemblyBuilder; @@ -95,7 +96,7 @@ private static MethodInfo StringFormat static int typeCounter; MethodBuilder methodBuilder; #else - private static Module s_serializationModule; + private static Module? s_serializationModule; private static Module SerializationModule { get @@ -107,19 +108,19 @@ private static Module SerializationModule return s_serializationModule; } } - private DynamicMethod _dynamicMethod; + private DynamicMethod _dynamicMethod = null!; // initialized in BeginMethod #endif - private ILGenerator _ilGen; - private List _argList; - private Stack _blockStack; + private ILGenerator _ilGen = null!; // initialized in BeginMethod + private List _argList = null!; // initialized in BeginMethod + private Stack _blockStack = null!; // initialized in BeginMethod private Label _methodEndLabel; private readonly Dictionary _localNames = new Dictionary(); private enum CodeGenTrace { None, Save, Tron }; private readonly CodeGenTrace _codeGenTrace; - private LocalBuilder _stringFormatArray; + private LocalBuilder? _stringFormatArray; internal CodeGenerator() { @@ -140,7 +141,7 @@ internal void BeginMethod(DynamicMethod dynamicMethod, Type delegateType, string internal void BeginMethod(string methodName, Type delegateType, bool allowPrivateMemberAccess) { - MethodInfo signature = delegateType.GetMethod("Invoke"); + MethodInfo signature = delegateType.GetMethod("Invoke")!; ParameterInfo[] parameters = signature.GetParameters(); Type[] paramTypes = new Type[parameters.Length]; for (int i = 0; i < parameters.Length; i++) @@ -184,7 +185,7 @@ internal Delegate EndMethod() EmitSourceLabel("} End method"); Ret(); - Delegate retVal = null; + Delegate? retVal = null; #if USE_REFEMIT Type type = typeBuilder.CreateType(); MethodInfo method = type.GetMethod(methodBuilder.Name); @@ -192,13 +193,13 @@ internal Delegate EndMethod() methodBuilder = null; #else retVal = _dynamicMethod.CreateDelegate(_delegateType); - _dynamicMethod = null; + _dynamicMethod = null!; #endif - _delegateType = null; + _delegateType = null!; - _ilGen = null; - _blockStack = null; - _argList = null; + _ilGen = null!; + _blockStack = null!; + _argList = null!; return retVal; } @@ -259,7 +260,7 @@ internal void Set(LocalBuilder local, object value) Store(local); } - internal object For(LocalBuilder local, object start, object end) + internal object For(LocalBuilder? local, object? start, object? end) { ForState forState = new ForState(local, DefineLabel(), DefineLabel(), end); if (forState.Index != null) @@ -276,7 +277,7 @@ internal object For(LocalBuilder local, object start, object end) internal void EndFor() { object stackTop = _blockStack.Pop(); - ForState forState = stackTop as ForState; + ForState? forState = stackTop as ForState; if (forState == null) ThrowMismatchException(stackTop); @@ -289,7 +290,7 @@ internal void EndFor() MarkLabel(forState.TestLabel); Ldloc(forState.Index); Load(forState.End); - if (GetVariableType(forState.End).IsArray) + if (GetVariableType(forState.End!).IsArray) Ldlen(); Blt(forState.BeginLabel); } @@ -313,7 +314,7 @@ internal void InternalBreakFor(object userForState, OpCode branchInstruction) { foreach (object block in _blockStack) { - ForState forState = block as ForState; + ForState? forState = block as ForState; if (forState != null && (object)forState == userForState) { if (!forState.RequiresEndLabel) @@ -347,13 +348,13 @@ internal void ForEach(LocalBuilder local, Type elementType, Type enumeratorType, internal void EndForEach(MethodInfo moveNextMethod) { object stackTop = _blockStack.Pop(); - ForState forState = stackTop as ForState; + ForState? forState = stackTop as ForState; if (forState == null) ThrowMismatchException(stackTop); MarkLabel(forState.TestLabel); - object enumerator = forState.End; + object? enumerator = forState.End; Call(enumerator, moveNextMethod); @@ -424,7 +425,7 @@ internal void If(Cmp cmpOp) } - internal void If(object value1, Cmp cmpOp, object value2) + internal void If(object value1, Cmp cmpOp, object? value2) { Load(value1); Load(value2); @@ -469,14 +470,14 @@ internal void VerifyParameterCount(MethodInfo methodInfo, int expectedCount) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ParameterCountMismatch, methodInfo.Name, methodInfo.GetParameters().Length, expectedCount))); } - internal void Call(object thisObj, MethodInfo methodInfo) + internal void Call(object? thisObj, MethodInfo methodInfo) { VerifyParameterCount(methodInfo, 0); LoadThis(thisObj, methodInfo); Call(methodInfo); } - internal void Call(object thisObj, MethodInfo methodInfo, object param1) + internal void Call(object? thisObj, MethodInfo methodInfo, object? param1) { VerifyParameterCount(methodInfo, 1); LoadThis(thisObj, methodInfo); @@ -484,7 +485,7 @@ internal void Call(object thisObj, MethodInfo methodInfo, object param1) Call(methodInfo); } - internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2) + internal void Call(object? thisObj, MethodInfo methodInfo, object? param1, object? param2) { VerifyParameterCount(methodInfo, 2); LoadThis(thisObj, methodInfo); @@ -493,7 +494,7 @@ internal void Call(object thisObj, MethodInfo methodInfo, object param1, object Call(methodInfo); } - internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2, object param3) + internal void Call(object? thisObj, MethodInfo methodInfo, object? param1, object? param2, object? param3) { VerifyParameterCount(methodInfo, 3); LoadThis(thisObj, methodInfo); @@ -503,7 +504,7 @@ internal void Call(object thisObj, MethodInfo methodInfo, object param1, object Call(methodInfo); } - internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2, object param3, object param4) + internal void Call(object? thisObj, MethodInfo methodInfo, object? param1, object? param2, object? param3, object? param4) { VerifyParameterCount(methodInfo, 4); LoadThis(thisObj, methodInfo); @@ -514,7 +515,7 @@ internal void Call(object thisObj, MethodInfo methodInfo, object param1, object Call(methodInfo); } - internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2, object param3, object param4, object param5) + internal void Call(object? thisObj, MethodInfo methodInfo, object? param1, object? param2, object? param3, object? param4, object? param5) { VerifyParameterCount(methodInfo, 5); LoadThis(thisObj, methodInfo); @@ -526,7 +527,7 @@ internal void Call(object thisObj, MethodInfo methodInfo, object param1, object Call(methodInfo); } - internal void Call(object thisObj, MethodInfo methodInfo, object param1, object param2, object param3, object param4, object param5, object param6) + internal void Call(object? thisObj, MethodInfo methodInfo, object? param1, object? param2, object? param3, object? param4, object? param5, object? param6) { VerifyParameterCount(methodInfo, 6); LoadThis(thisObj, methodInfo); @@ -541,7 +542,7 @@ internal void Call(object thisObj, MethodInfo methodInfo, object param1, object internal void Call(MethodInfo methodInfo) { - if (methodInfo.IsVirtual && !methodInfo.DeclaringType.IsValueType) + if (methodInfo.IsVirtual && !methodInfo.DeclaringType!.IsValueType) { if (_codeGenTrace != CodeGenTrace.None) EmitSourceInstruction("Callvirt " + methodInfo.ToString() + " on type " + methodInfo.DeclaringType.ToString()); @@ -550,13 +551,13 @@ internal void Call(MethodInfo methodInfo) else if (methodInfo.IsStatic) { if (_codeGenTrace != CodeGenTrace.None) - EmitSourceInstruction("Static Call " + methodInfo.ToString() + " on type " + methodInfo.DeclaringType.ToString()); + EmitSourceInstruction("Static Call " + methodInfo.ToString() + " on type " + methodInfo.DeclaringType!.ToString()); _ilGen.Emit(OpCodes.Call, methodInfo); } else { if (_codeGenTrace != CodeGenTrace.None) - EmitSourceInstruction("Call " + methodInfo.ToString() + " on type " + methodInfo.DeclaringType.ToString()); + EmitSourceInstruction("Call " + methodInfo.ToString() + " on type " + methodInfo.DeclaringType!.ToString()); _ilGen.Emit(OpCodes.Call, methodInfo); } } @@ -564,14 +565,14 @@ internal void Call(MethodInfo methodInfo) internal void Call(ConstructorInfo ctor) { if (_codeGenTrace != CodeGenTrace.None) - EmitSourceInstruction("Call " + ctor.ToString() + " on type " + ctor.DeclaringType.ToString()); + EmitSourceInstruction("Call " + ctor.ToString() + " on type " + ctor.DeclaringType!.ToString()); _ilGen.Emit(OpCodes.Call, ctor); } internal void New(ConstructorInfo constructorInfo) { if (_codeGenTrace != CodeGenTrace.None) - EmitSourceInstruction("Newobj " + constructorInfo.ToString() + " on type " + constructorInfo.DeclaringType.ToString()); + EmitSourceInstruction("Newobj " + constructorInfo.ToString() + " on type " + constructorInfo.DeclaringType!.ToString()); _ilGen.Emit(OpCodes.Newobj, constructorInfo); } @@ -591,9 +592,9 @@ internal void NewArray(Type elementType, object len) _ilGen.Emit(OpCodes.Newarr, elementType); } - internal void LoadArrayElement(object obj, object arrayIndex) + internal void LoadArrayElement(object obj, object? arrayIndex) { - Type objType = GetVariableType(obj).GetElementType(); + Type objType = GetVariableType(obj).GetElementType()!; Load(obj); Load(arrayIndex); if (IsStruct(objType)) @@ -614,7 +615,7 @@ internal void StoreArrayElement(object obj, object arrayIndex, object value) } else { - Type objType = arrayType.GetElementType(); + Type objType = arrayType.GetElementType()!; Load(obj); Load(arrayIndex); if (IsStruct(objType)) @@ -635,7 +636,7 @@ private static bool IsStruct(Type objType) internal Type LoadMember(MemberInfo memberInfo) { - Type memberType = null; + Type? memberType = null; if (memberInfo is FieldInfo) { FieldInfo fieldInfo = (FieldInfo)memberInfo; @@ -653,13 +654,12 @@ internal Type LoadMember(MemberInfo memberInfo) _ilGen.Emit(OpCodes.Ldfld, fieldInfo); } } - else if (memberInfo is PropertyInfo) + else if (memberInfo is PropertyInfo property) { - PropertyInfo property = memberInfo as PropertyInfo; memberType = property.PropertyType; if (property != null) { - MethodInfo getMethod = property.GetMethod; + MethodInfo? getMethod = property.GetMethod; if (getMethod == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.NoGetMethodForProperty, property.DeclaringType, property))); Call(getMethod); @@ -698,10 +698,10 @@ internal void StoreMember(MemberInfo memberInfo) } else if (memberInfo is PropertyInfo) { - PropertyInfo property = memberInfo as PropertyInfo; + PropertyInfo? property = memberInfo as PropertyInfo; if (property != null) { - MethodInfo setMethod = property.SetMethod; + MethodInfo? setMethod = property.SetMethod; if (setMethod == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.NoSetMethodForProperty, property.DeclaringType, property))); Call(setMethod); @@ -755,7 +755,7 @@ internal void LoadDefaultValue(Type type) Load(null); } - internal void Load(object obj) + internal void Load(object? obj) { if (obj == null) { @@ -860,7 +860,7 @@ internal void Ldobj(Type type) if (!opCode.Equals(OpCodes.Nop)) { if (_codeGenTrace != CodeGenTrace.None) - EmitSourceInstruction(opCode.ToString()); + EmitSourceInstruction(opCode.ToString()!); _ilGen.Emit(opCode); } else @@ -1134,7 +1134,7 @@ internal void Ldelem(Type arrayElementType) if (opCode.Equals(OpCodes.Nop)) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ArrayTypeIsNotSupported_GeneratingCode, DataContract.GetClrTypeFullName(arrayElementType)))); if (_codeGenTrace != CodeGenTrace.None) - EmitSourceInstruction(opCode.ToString()); + EmitSourceInstruction(opCode.ToString()!); _ilGen.Emit(opCode); EmitStackTop(arrayElementType); } @@ -1143,7 +1143,7 @@ internal void Ldelema(Type arrayElementType) { OpCode opCode = OpCodes.Ldelema; if (_codeGenTrace != CodeGenTrace.None) - EmitSourceInstruction(opCode.ToString()); + EmitSourceInstruction(opCode.ToString()!); _ilGen.Emit(opCode, arrayElementType); EmitStackTop(arrayElementType); @@ -1179,7 +1179,7 @@ internal void Stelem(Type arrayElementType) if (opCode.Equals(OpCodes.Nop)) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ArrayTypeIsNotSupported_GeneratingCode, DataContract.GetClrTypeFullName(arrayElementType)))); if (_codeGenTrace != CodeGenTrace.None) - EmitSourceInstruction(opCode.ToString()); + EmitSourceInstruction(opCode.ToString()!); EmitStackTop(arrayElementType); _ilGen.Emit(opCode); } @@ -1282,16 +1282,16 @@ internal void Dup() _ilGen.Emit(OpCodes.Dup); } - private void LoadThis(object thisObj, MethodInfo methodInfo) + private void LoadThis(object? thisObj, MethodInfo methodInfo) { if (thisObj != null && !methodInfo.IsStatic) { LoadAddress(thisObj); - ConvertAddress(GetVariableType(thisObj), methodInfo.DeclaringType); + ConvertAddress(GetVariableType(thisObj), methodInfo.DeclaringType!); } } - private void LoadParam(object arg, int oneBasedArgIndex, MethodBase methodInfo) + private void LoadParam(object? arg, int oneBasedArgIndex, MethodBase methodInfo) { Load(arg); if (arg != null) @@ -1342,7 +1342,7 @@ private void InternalConvert(Type source, Type target, bool isAddress) else { if (_codeGenTrace != CodeGenTrace.None) - EmitSourceInstruction(opCode.ToString()); + EmitSourceInstruction(opCode.ToString()!); _ilGen.Emit(opCode); } } @@ -1379,7 +1379,7 @@ private void InternalConvert(Type source, Type target, bool isAddress) private IfState PopIfState() { object stackTop = _blockStack.Pop(); - IfState ifState = stackTop as IfState; + IfState? ifState = stackTop as IfState; if (ifState == null) ThrowMismatchException(stackTop); return ifState; @@ -1396,6 +1396,7 @@ void InitAssemblyBuilder(string methodName) } #endif + [DoesNotReturn] private void ThrowMismatchException(object expected) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ExpectingEnd, expected.ToString()))); @@ -1443,7 +1444,7 @@ internal void Case(Label caseLabel1, string caseLabelName) internal void EndCase() { object stackTop = _blockStack.Peek(); - SwitchState switchState = stackTop as SwitchState; + SwitchState? switchState = stackTop as SwitchState; if (switchState == null) ThrowMismatchException(stackTop); Br(switchState.EndOfSwitchLabel); @@ -1454,7 +1455,7 @@ internal void EndCase() internal void EndSwitch() { object stackTop = _blockStack.Pop(); - SwitchState switchState = stackTop as SwitchState; + SwitchState? switchState = stackTop as SwitchState; if (switchState == null) ThrowMismatchException(stackTop); if (_codeGenTrace != CodeGenTrace.None) @@ -1464,7 +1465,7 @@ internal void EndSwitch() MarkLabel(switchState.EndOfSwitchLabel); } - private static readonly MethodInfo s_stringLength = typeof(string).GetProperty("Length").GetMethod; + private static readonly MethodInfo s_stringLength = typeof(string).GetProperty("Length")!.GetMethod!; internal void ElseIfIsEmptyString(LocalBuilder strLocal) { IfState ifState = (IfState)_blockStack.Pop(); @@ -1548,14 +1549,14 @@ internal ArgBuilder(int index, Type argType) internal class ForState { - private readonly LocalBuilder _indexVar; + private readonly LocalBuilder? _indexVar; private readonly Label _beginLabel; private readonly Label _testLabel; private Label _endLabel; private bool _requiresEndLabel; - private readonly object _end; + private readonly object? _end; - internal ForState(LocalBuilder indexVar, Label beginLabel, Label testLabel, object end) + internal ForState(LocalBuilder? indexVar, Label beginLabel, Label testLabel, object? end) { _indexVar = indexVar; _beginLabel = beginLabel; @@ -1563,7 +1564,7 @@ internal ForState(LocalBuilder indexVar, Label beginLabel, Label testLabel, obje _end = end; } - internal LocalBuilder Index + internal LocalBuilder? Index { get { @@ -1611,7 +1612,7 @@ internal bool RequiresEndLabel } } - internal object End + internal object? End { get { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CollectionDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CollectionDataContract.cs index c62688c6162612..7c23c21df3d36a 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CollectionDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/CollectionDataContract.cs @@ -15,6 +15,7 @@ namespace System.Runtime.Serialization using System.Linq; using DataContractDictionary = System.Collections.Generic.Dictionary; using System.Security; + using System.Diagnostics.CodeAnalysis; // The interface is a perf optimization. // Only KeyValuePairAdapter should implement the interface. @@ -70,8 +71,8 @@ public interface IKeyValue internal interface IKeyValue #endif { - object Key { get; set; } - object Value { get; set; } + object? Key { get; set; } + object? Value { get; set; } } [DataContract(Namespace = "http://schemas.microsoft.com/2003/10/Serialization/Arrays")] @@ -104,16 +105,16 @@ public V Value set { _value = value; } } - object IKeyValue.Key + object? IKeyValue.Key { get { return _key; } - set { _key = (K)value; } + set { _key = (K)value!; } } - object IKeyValue.Value + object? IKeyValue.Value { get { return _value; } - set { _value = (V)value; } + set { _value = (V)value!; } } } @@ -139,35 +140,30 @@ internal sealed class CollectionDataContract : DataContract { private XmlDictionaryString _collectionItemName; - private XmlDictionaryString _childElementNamespace; + private XmlDictionaryString? _childElementNamespace; - private DataContract _itemContract; + private DataContract? _itemContract; private CollectionDataContractCriticalHelper _helper; - public CollectionDataContract(CollectionKind kind) : base(new CollectionDataContractCriticalHelper(kind)) - { - InitCollectionDataContract(this); - } - internal CollectionDataContract(Type type) : base(new CollectionDataContractCriticalHelper(type)) { InitCollectionDataContract(this); } - private CollectionDataContract(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, string deserializationExceptionMessage) + private CollectionDataContract(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, string? deserializationExceptionMessage) : base(new CollectionDataContractCriticalHelper(type, kind, itemType, getEnumeratorMethod, deserializationExceptionMessage)) { InitCollectionDataContract(GetSharedTypeContract(type)); } - private CollectionDataContract(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor) + private CollectionDataContract(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo? addMethod, ConstructorInfo? constructor) : base(new CollectionDataContractCriticalHelper(type, kind, itemType, getEnumeratorMethod, addMethod, constructor)) { InitCollectionDataContract(GetSharedTypeContract(type)); } - private CollectionDataContract(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor, bool isConstructorCheckRequired) + private CollectionDataContract(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo? addMethod, ConstructorInfo? constructor, bool isConstructorCheckRequired) : base(new CollectionDataContractCriticalHelper(type, kind, itemType, getEnumeratorMethod, addMethod, constructor, isConstructorCheckRequired)) { InitCollectionDataContract(GetSharedTypeContract(type)); @@ -178,9 +174,11 @@ private CollectionDataContract(Type type, string invalidCollectionInSharedContra InitCollectionDataContract(GetSharedTypeContract(type)); } - private void InitCollectionDataContract(DataContract sharedTypeContract) + [MemberNotNull(nameof(_helper))] + [MemberNotNull(nameof(_collectionItemName))] + private void InitCollectionDataContract(DataContract? sharedTypeContract) { - _helper = base.Helper as CollectionDataContractCriticalHelper; + _helper = (base.Helper as CollectionDataContractCriticalHelper)!; _collectionItemName = _helper.CollectionItemName; if (_helper.Kind == CollectionKind.Dictionary || _helper.Kind == CollectionKind.GenericDictionary) { @@ -222,7 +220,7 @@ public DataContract ItemContract } } - internal DataContract SharedTypeContract + internal DataContract? SharedTypeContract { get { return _helper.SharedTypeContract; } @@ -243,7 +241,7 @@ public XmlDictionaryString CollectionItemName set { _collectionItemName = value; } } - public string KeyName + public string? KeyName { get { return _helper.KeyName; } @@ -252,7 +250,7 @@ public string KeyName { _helper.KeyName = value; } } - public string ValueName + public string? ValueName { get { return _helper.ValueName; } @@ -266,7 +264,7 @@ internal bool IsDictionary get { return KeyName != null; } } - public XmlDictionaryString ChildElementNamespace + public XmlDictionaryString? ChildElementNamespace { get { @@ -278,7 +276,7 @@ public XmlDictionaryString ChildElementNamespace { if (_helper.ChildElementNamespace == null && !IsDictionary) { - XmlDictionaryString tempChildElementNamespace = ClassDataContract.GetChildNamespaceToDeclare(this, ItemType, new XmlDictionary()); + XmlDictionaryString? tempChildElementNamespace = ClassDataContract.GetChildNamespaceToDeclare(this, ItemType, new XmlDictionary()); Interlocked.MemoryBarrier(); _helper.ChildElementNamespace = tempChildElementNamespace; } @@ -305,25 +303,25 @@ internal bool IsConstructorCheckRequired { _helper.IsConstructorCheckRequired = value; } } - internal MethodInfo GetEnumeratorMethod + internal MethodInfo? GetEnumeratorMethod { get { return _helper.GetEnumeratorMethod; } } - internal MethodInfo AddMethod + internal MethodInfo? AddMethod { get { return _helper.AddMethod; } } - internal ConstructorInfo Constructor + internal ConstructorInfo? Constructor { get { return _helper.Constructor; } } - public override DataContractDictionary KnownDataContracts + public override DataContractDictionary? KnownDataContracts { get { return _helper.KnownDataContracts; } @@ -332,13 +330,13 @@ public override DataContractDictionary KnownDataContracts { _helper.KnownDataContracts = value; } } - internal string InvalidCollectionInSharedContractMessage + internal string? InvalidCollectionInSharedContractMessage { get { return _helper.InvalidCollectionInSharedContractMessage; } } - internal string DeserializationExceptionMessage + internal string? DeserializationExceptionMessage { get { return _helper.DeserializationExceptionMessage; } } @@ -470,28 +468,29 @@ internal Type GetCollectionElementType() private class CollectionDataContractCriticalHelper : DataContract.DataContractCriticalHelper { - private static Type[] s_knownInterfaces; + private static Type[]? s_knownInterfaces; - private Type _itemType; + private Type _itemType = null!; // _itemType is always set except for the "invalid" CollectionDataContract private bool _isItemTypeNullable; private CollectionKind _kind; - private readonly MethodInfo _getEnumeratorMethod, _addMethod; - private readonly ConstructorInfo _constructor; - private readonly string _deserializationExceptionMessage; - private DataContract _itemContract; - private DataContract _sharedTypeContract; - private DataContractDictionary _knownDataContracts; + private readonly MethodInfo? _getEnumeratorMethod; + private readonly MethodInfo? _addMethod; + private readonly ConstructorInfo? _constructor; + private readonly string? _deserializationExceptionMessage; + private DataContract? _itemContract; + private DataContract? _sharedTypeContract; + private DataContractDictionary? _knownDataContracts; private bool _isKnownTypeAttributeChecked; - private string _itemName; + private string _itemName = null!; // _itemName is always set except for the "invalid" CollectionDataContract private bool _itemNameSetExplicit; - private XmlDictionaryString _collectionItemName; - private string _keyName; - private string _valueName; - private XmlDictionaryString _childElementNamespace; - private readonly string _invalidCollectionInSharedContractMessage; - private XmlFormatCollectionReaderDelegate _xmlFormatReaderDelegate; - private XmlFormatGetOnlyCollectionReaderDelegate _xmlFormatGetOnlyCollectionReaderDelegate; - private XmlFormatCollectionWriterDelegate _xmlFormatWriterDelegate; + private XmlDictionaryString _collectionItemName = null!; // _itemName is always set except for the "invalid" CollectionDataContract + private string? _keyName; + private string? _valueName; + private XmlDictionaryString? _childElementNamespace; + private readonly string? _invalidCollectionInSharedContractMessage; + private XmlFormatCollectionReaderDelegate? _xmlFormatReaderDelegate; + private XmlFormatGetOnlyCollectionReaderDelegate? _xmlFormatGetOnlyCollectionReaderDelegate; + private XmlFormatCollectionWriterDelegate? _xmlFormatWriterDelegate; private bool _isConstructorCheckRequired; internal static Type[] KnownInterfaces @@ -517,7 +516,7 @@ internal static Type[] KnownInterfaces } } - private void Init(CollectionKind kind, Type itemType, CollectionDataContractAttribute collectionContractAttribute) + private void Init(CollectionKind kind, Type? itemType, CollectionDataContractAttribute? collectionContractAttribute) { _kind = kind; if (itemType != null) @@ -526,7 +525,7 @@ private void Init(CollectionKind kind, Type itemType, CollectionDataContractAttr _isItemTypeNullable = DataContract.IsTypeNullable(itemType); bool isDictionary = (kind == CollectionKind.Dictionary || kind == CollectionKind.GenericDictionary); - string itemName = null, keyName = null, valueName = null; + string? itemName = null, keyName = null, valueName = null; if (collectionContractAttribute != null) { if (collectionContractAttribute.IsItemNameSetExplicitly) @@ -571,12 +570,6 @@ private void Init(CollectionKind kind, Type itemType, CollectionDataContractAttr } } - internal CollectionDataContractCriticalHelper(CollectionKind kind) - : base() - { - Init(kind, null, null); - } - // array internal CollectionDataContractCriticalHelper(Type type) : base(type) { @@ -589,7 +582,7 @@ internal CollectionDataContractCriticalHelper(Type type) : base(type) } // read-only collection - internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, string deserializationExceptionMessage) + internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, string? deserializationExceptionMessage) : base(type) { if (getEnumeratorMethod == null) @@ -597,7 +590,7 @@ internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Ty if (itemType == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveItemType, GetClrTypeFullName(type)))); - CollectionDataContractAttribute collectionContractAttribute; + CollectionDataContractAttribute? collectionContractAttribute; this.StableName = DataContract.GetCollectionStableName(type, itemType, out collectionContractAttribute); Init(kind, itemType, collectionContractAttribute); @@ -606,7 +599,7 @@ internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Ty } // collection - internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor) : base(type) + internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo? addMethod, ConstructorInfo? constructor) : base(type) { if (getEnumeratorMethod == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveGetEnumeratorMethod, DataContract.GetClrTypeFullName(type)))); @@ -615,7 +608,7 @@ internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Ty if (itemType == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveItemType, DataContract.GetClrTypeFullName(type)))); - CollectionDataContractAttribute collectionContractAttribute; + CollectionDataContractAttribute? collectionContractAttribute; this.StableName = DataContract.GetCollectionStableName(type, itemType, out collectionContractAttribute); Init(kind, itemType, collectionContractAttribute); @@ -625,7 +618,7 @@ internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Ty } // collection - internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo addMethod, ConstructorInfo constructor, bool isConstructorCheckRequired) + internal CollectionDataContractCriticalHelper(Type type, CollectionKind kind, Type itemType, MethodInfo getEnumeratorMethod, MethodInfo? addMethod, ConstructorInfo? constructor, bool isConstructorCheckRequired) : this(type, kind, itemType, getEnumeratorMethod, addMethod, constructor) { _isConstructorCheckRequired = isConstructorCheckRequired; @@ -652,7 +645,7 @@ internal DataContract ItemContract { get { - if (_itemContract == null && UnderlyingType != null) + if (_itemContract == null) { if (IsDictionary) { @@ -662,6 +655,8 @@ internal DataContract ItemContract SR.Format(SR.DupKeyValueName, DataContract.GetClrTypeFullName(UnderlyingType), KeyName), UnderlyingType); } + Debug.Assert(KeyName != null); + Debug.Assert(ValueName != null); _itemContract = ClassDataContract.CreateClassDataContractForKeyValue(ItemType, Namespace, new string[] { KeyName, ValueName }); // Ensure that DataContract gets added to the static DataContract cache for dictionary items DataContract.GetDataContract(ItemType); @@ -683,7 +678,7 @@ internal DataContract ItemContract } } - internal DataContract SharedTypeContract + internal DataContract? SharedTypeContract { get { return _sharedTypeContract; } set { _sharedTypeContract = value; } @@ -706,13 +701,13 @@ public XmlDictionaryString CollectionItemName get { return _collectionItemName; } } - internal string KeyName + internal string? KeyName { get { return _keyName; } set { _keyName = value; } } - internal string ValueName + internal string? ValueName { get { return _valueName; } set { _valueName = value; } @@ -720,9 +715,9 @@ internal string ValueName internal bool IsDictionary => KeyName != null; - public string DeserializationExceptionMessage => _deserializationExceptionMessage; + public string? DeserializationExceptionMessage => _deserializationExceptionMessage; - public XmlDictionaryString ChildElementNamespace + public XmlDictionaryString? ChildElementNamespace { get { return _childElementNamespace; } set { _childElementNamespace = value; } @@ -734,13 +729,13 @@ internal bool IsItemTypeNullable set { _isItemTypeNullable = value; } } - internal MethodInfo GetEnumeratorMethod => _getEnumeratorMethod; + internal MethodInfo? GetEnumeratorMethod => _getEnumeratorMethod; - internal MethodInfo AddMethod => _addMethod; + internal MethodInfo? AddMethod => _addMethod; - internal ConstructorInfo Constructor => _constructor; + internal ConstructorInfo? Constructor => _constructor; - internal override DataContractDictionary KnownDataContracts + internal override DataContractDictionary? KnownDataContracts { get { @@ -763,23 +758,23 @@ internal override DataContractDictionary KnownDataContracts { _knownDataContracts = value; } } - internal string InvalidCollectionInSharedContractMessage => _invalidCollectionInSharedContractMessage; + internal string? InvalidCollectionInSharedContractMessage => _invalidCollectionInSharedContractMessage; internal bool ItemNameSetExplicit => _itemNameSetExplicit; - internal XmlFormatCollectionWriterDelegate XmlFormatWriterDelegate + internal XmlFormatCollectionWriterDelegate? XmlFormatWriterDelegate { get { return _xmlFormatWriterDelegate; } set { _xmlFormatWriterDelegate = value; } } - internal XmlFormatCollectionReaderDelegate XmlFormatReaderDelegate + internal XmlFormatCollectionReaderDelegate? XmlFormatReaderDelegate { get { return _xmlFormatReaderDelegate; } set { _xmlFormatReaderDelegate = value; } } - internal XmlFormatGetOnlyCollectionReaderDelegate XmlFormatGetOnlyCollectionReaderDelegate + internal XmlFormatGetOnlyCollectionReaderDelegate? XmlFormatGetOnlyCollectionReaderDelegate { get { return _xmlFormatGetOnlyCollectionReaderDelegate; } set { _xmlFormatGetOnlyCollectionReaderDelegate = value; } @@ -787,7 +782,7 @@ internal XmlFormatGetOnlyCollectionReaderDelegate XmlFormatGetOnlyCollectionRead private delegate void IncrementCollectionCountDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context); - private IncrementCollectionCountDelegate _incrementCollectionCountDelegate; + private IncrementCollectionCountDelegate? _incrementCollectionCountDelegate; private static void DummyIncrementCollectionCount(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) { } @@ -811,13 +806,13 @@ internal void IncrementCollectionCount(XmlWriterDelegator xmlWriter, object obj, case CollectionKind.GenericList: { var buildIncrementCollectionCountDelegate = BuildIncrementCollectionCountDelegateMethod.MakeGenericMethod(ItemType); - _incrementCollectionCountDelegate = (IncrementCollectionCountDelegate)buildIncrementCollectionCountDelegate.Invoke(null, Array.Empty()); + _incrementCollectionCountDelegate = (IncrementCollectionCountDelegate)buildIncrementCollectionCountDelegate.Invoke(null, Array.Empty())!; } break; case CollectionKind.GenericDictionary: { var buildIncrementCollectionCountDelegate = BuildIncrementCollectionCountDelegateMethod.MakeGenericMethod(Globals.TypeOfKeyValuePair.MakeGenericType(ItemType.GetGenericArguments())); - _incrementCollectionCountDelegate = (IncrementCollectionCountDelegate)buildIncrementCollectionCountDelegate.Invoke(null, Array.Empty()); + _incrementCollectionCountDelegate = (IncrementCollectionCountDelegate)buildIncrementCollectionCountDelegate.Invoke(null, Array.Empty())!; } break; default: @@ -830,7 +825,7 @@ internal void IncrementCollectionCount(XmlWriterDelegator xmlWriter, object obj, _incrementCollectionCountDelegate(xmlWriter, obj, context); } - private static MethodInfo s_buildIncrementCollectionCountDelegateMethod; + private static MethodInfo? s_buildIncrementCollectionCountDelegateMethod; private static MethodInfo BuildIncrementCollectionCountDelegateMethod { @@ -838,7 +833,7 @@ private static MethodInfo BuildIncrementCollectionCountDelegateMethod { if (s_buildIncrementCollectionCountDelegateMethod == null) { - s_buildIncrementCollectionCountDelegateMethod = typeof(CollectionDataContractCriticalHelper).GetMethod(nameof(BuildIncrementCollectionCountDelegate), Globals.ScanAllMembers); + s_buildIncrementCollectionCountDelegateMethod = typeof(CollectionDataContractCriticalHelper).GetMethod(nameof(BuildIncrementCollectionCountDelegate), Globals.ScanAllMembers)!; } return s_buildIncrementCollectionCountDelegateMethod; @@ -856,7 +851,7 @@ private static IncrementCollectionCountDelegate BuildIncrementCollectionCountDel private delegate IEnumerator CreateGenericDictionaryEnumeratorDelegate(IEnumerator enumerator); - private CreateGenericDictionaryEnumeratorDelegate _createGenericDictionaryEnumeratorDelegate; + private CreateGenericDictionaryEnumeratorDelegate? _createGenericDictionaryEnumeratorDelegate; internal IEnumerator GetEnumeratorForCollection(object obj) { @@ -866,8 +861,8 @@ internal IEnumerator GetEnumeratorForCollection(object obj) if (_createGenericDictionaryEnumeratorDelegate == null) { var keyValueTypes = ItemType.GetGenericArguments(); - var buildCreateGenericDictionaryEnumerator = BuildCreateGenericDictionaryEnumerato.MakeGenericMethod(keyValueTypes[0], keyValueTypes[1]); - _createGenericDictionaryEnumeratorDelegate = (CreateGenericDictionaryEnumeratorDelegate)buildCreateGenericDictionaryEnumerator.Invoke(null, Array.Empty()); + MethodInfo buildCreateGenericDictionaryEnumerator = BuildCreateGenericDictionaryEnumerato.MakeGenericMethod(keyValueTypes[0], keyValueTypes[1]); + _createGenericDictionaryEnumeratorDelegate = (CreateGenericDictionaryEnumeratorDelegate)buildCreateGenericDictionaryEnumerator.Invoke(null, Array.Empty())!; } enumerator = _createGenericDictionaryEnumeratorDelegate(enumerator); @@ -882,7 +877,10 @@ internal IEnumerator GetEnumeratorForCollection(object obj) internal Type GetCollectionElementType() { - Type enumeratorType = null; + Debug.Assert(Kind != CollectionKind.Array, "GetCollectionElementType should not be called on Arrays"); + Debug.Assert(GetEnumeratorMethod != null, "GetEnumeratorMethod should be non-null for non-Arrays"); + + Type? enumeratorType = null; if (Kind == CollectionKind.GenericDictionary) { Type[] keyValueTypes = ItemType.GetGenericArguments(); @@ -897,7 +895,7 @@ internal Type GetCollectionElementType() enumeratorType = GetEnumeratorMethod.ReturnType; } - MethodInfo getCurrentMethod = enumeratorType.GetMethod(Globals.GetCurrentMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty()); + MethodInfo? getCurrentMethod = enumeratorType.GetMethod(Globals.GetCurrentMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty()); if (getCurrentMethod == null) { if (enumeratorType.IsInterface) @@ -922,7 +920,7 @@ internal Type GetCollectionElementType() } } - getCurrentMethod = GetTargetMethodWithName(Globals.GetCurrentMethodName, enumeratorType, ienumeratorInterface); + getCurrentMethod = GetTargetMethodWithName(Globals.GetCurrentMethodName, enumeratorType, ienumeratorInterface)!; } } @@ -930,7 +928,7 @@ internal Type GetCollectionElementType() return elementType; } - private static MethodInfo s_buildCreateGenericDictionaryEnumerator; + private static MethodInfo? s_buildCreateGenericDictionaryEnumerator; private static MethodInfo BuildCreateGenericDictionaryEnumerato { @@ -938,7 +936,7 @@ private static MethodInfo BuildCreateGenericDictionaryEnumerato { if (s_buildCreateGenericDictionaryEnumerator == null) { - s_buildCreateGenericDictionaryEnumerator = typeof(CollectionDataContractCriticalHelper).GetMethod(nameof(BuildCreateGenericDictionaryEnumerator), Globals.ScanAllMembers); + s_buildCreateGenericDictionaryEnumerator = typeof(CollectionDataContractCriticalHelper).GetMethod(nameof(BuildCreateGenericDictionaryEnumerator), Globals.ScanAllMembers)!; } return s_buildCreateGenericDictionaryEnumerator; @@ -954,7 +952,7 @@ private static CreateGenericDictionaryEnumeratorDelegate BuildCreateGenericDicti } } - private DataContract GetSharedTypeContract(Type type) + private DataContract? GetSharedTypeContract(Type type) { if (type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, false)) { @@ -976,39 +974,39 @@ internal static bool IsCollectionInterface(Type type) internal static bool IsCollection(Type type) { - Type itemType; + Type? itemType; return IsCollection(type, out itemType); } - internal static bool IsCollection(Type type, out Type itemType) + internal static bool IsCollection(Type type, [NotNullWhen(true)] out Type? itemType) { return IsCollectionHelper(type, out itemType, true /*constructorRequired*/); } internal static bool IsCollection(Type type, bool constructorRequired) { - Type itemType; + Type? itemType; return IsCollectionHelper(type, out itemType, constructorRequired); } - private static bool IsCollectionHelper(Type type, out Type itemType, bool constructorRequired) + private static bool IsCollectionHelper(Type type, [NotNullWhen(true)] out Type? itemType, bool constructorRequired) { if (type.IsArray && DataContract.GetBuiltInDataContract(type) == null) { - itemType = type.GetElementType(); + itemType = type.GetElementType()!; return true; } - DataContract dataContract; + DataContract? dataContract; return IsCollectionOrTryCreate(type, false /*tryCreate*/, out dataContract, out itemType, constructorRequired); } - internal static bool TryCreate(Type type, out DataContract dataContract) + internal static bool TryCreate(Type type, [NotNullWhen(true)] out DataContract? dataContract) { Type itemType; - return IsCollectionOrTryCreate(type, true /*tryCreate*/, out dataContract, out itemType, true /*constructorRequired*/); + return IsCollectionOrTryCreate(type, true /*tryCreate*/, out dataContract!, out itemType, true /*constructorRequired*/); } - internal static bool CreateGetOnlyCollectionDataContract(Type type, out DataContract dataContract) + internal static bool CreateGetOnlyCollectionDataContract(Type type, [NotNullWhen(true)] out DataContract? dataContract) { Type itemType; if (type.IsArray) @@ -1018,11 +1016,11 @@ internal static bool CreateGetOnlyCollectionDataContract(Type type, out DataCont } else { - return IsCollectionOrTryCreate(type, true /*tryCreate*/, out dataContract, out itemType, false /*constructorRequired*/); + return IsCollectionOrTryCreate(type, true /*tryCreate*/, out dataContract!, out itemType, false /*constructorRequired*/); } } - internal static bool TryCreateGetOnlyCollectionDataContract(Type type, out DataContract dataContract) + internal static bool TryCreateGetOnlyCollectionDataContract(Type type, [NotNullWhen(true)] out DataContract? dataContract) { dataContract = DataContract.GetDataContractFromGeneratedAssembly(type); if (dataContract == null) @@ -1035,7 +1033,7 @@ internal static bool TryCreateGetOnlyCollectionDataContract(Type type, out DataC } else { - return IsCollectionOrTryCreate(type, true /*tryCreate*/, out dataContract, out itemType, false /*constructorRequired*/); + return IsCollectionOrTryCreate(type, true /*tryCreate*/, out dataContract!, out itemType, false /*constructorRequired*/); } } else @@ -1052,9 +1050,9 @@ internal static bool TryCreateGetOnlyCollectionDataContract(Type type, out DataC } } - internal static MethodInfo GetTargetMethodWithName(string name, Type type, Type interfaceType) + internal static MethodInfo? GetTargetMethodWithName(string name, Type type, Type interfaceType) { - Type t = type.GetInterfaces().Where(it => it.Equals(interfaceType)).FirstOrDefault(); + Type? t = type.GetInterfaces().Where(it => it.Equals(interfaceType)).FirstOrDefault(); return t?.GetMethod(name); } @@ -1063,7 +1061,7 @@ private static bool IsArraySegment(Type t) return t.IsGenericType && (t.GetGenericTypeDefinition() == typeof(ArraySegment<>)); } - private static bool IsCollectionOrTryCreate(Type type, bool tryCreate, out DataContract dataContract, out Type itemType, bool constructorRequired) + private static bool IsCollectionOrTryCreate(Type type, bool tryCreate, out DataContract? dataContract, out Type itemType, bool constructorRequired) { dataContract = null; itemType = Globals.TypeOfObject; @@ -1074,11 +1072,11 @@ private static bool IsCollectionOrTryCreate(Type type, bool tryCreate, out DataC SR.CollectionTypeCannotBeBuiltIn, null, ref dataContract); } - MethodInfo addMethod, getEnumeratorMethod; + MethodInfo? addMethod, getEnumeratorMethod; bool hasCollectionDataContract = IsCollectionDataContract(type); bool isReadOnlyContract = false; - string deserializationExceptionMessage = null; - Type baseType = type.BaseType; + string? deserializationExceptionMessage = null; + Type? baseType = type.BaseType; bool isBaseTypeCollection = (baseType != null && baseType != Globals.TypeOfObject && baseType != Globals.TypeOfValueType && baseType != Globals.TypeOfUri) ? IsCollection(baseType) : false; @@ -1118,7 +1116,7 @@ private static bool IsCollectionOrTryCreate(Type type, bool tryCreate, out DataC { itemType = Globals.TypeOfKeyValue.MakeGenericType(genericArgs); addMethod = type.GetMethod(Globals.AddMethodName); - getEnumeratorMethod = Globals.TypeOfIEnumerableGeneric.MakeGenericType(Globals.TypeOfKeyValuePair.MakeGenericType(genericArgs)).GetMethod(Globals.GetEnumeratorMethodName); + getEnumeratorMethod = Globals.TypeOfIEnumerableGeneric.MakeGenericType(Globals.TypeOfKeyValuePair.MakeGenericType(genericArgs)).GetMethod(Globals.GetEnumeratorMethodName)!; } else { @@ -1127,7 +1125,7 @@ private static bool IsCollectionOrTryCreate(Type type, bool tryCreate, out DataC { addMethod = Globals.TypeOfICollectionGeneric.MakeGenericType(itemType).GetMethod(Globals.AddMethodName); } - getEnumeratorMethod = Globals.TypeOfIEnumerableGeneric.MakeGenericType(itemType).GetMethod(Globals.GetEnumeratorMethodName); + getEnumeratorMethod = Globals.TypeOfIEnumerableGeneric.MakeGenericType(itemType).GetMethod(Globals.GetEnumeratorMethodName)!; } } else @@ -1148,7 +1146,7 @@ private static bool IsCollectionOrTryCreate(Type type, bool tryCreate, out DataC } } - getEnumeratorMethod = Globals.TypeOfIEnumerable.GetMethod(Globals.GetEnumeratorMethodName); + getEnumeratorMethod = Globals.TypeOfIEnumerable.GetMethod(Globals.GetEnumeratorMethodName)!; } if (tryCreate) dataContract = new CollectionDataContract(type, (CollectionKind)(i + 1), itemType, getEnumeratorMethod, addMethod, null/*defaultCtor*/); @@ -1156,7 +1154,7 @@ private static bool IsCollectionOrTryCreate(Type type, bool tryCreate, out DataC } } } - ConstructorInfo defaultCtor = null; + ConstructorInfo? defaultCtor = null; if (!type.IsValueType) { defaultCtor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Array.Empty(), null); @@ -1178,7 +1176,7 @@ private static bool IsCollectionOrTryCreate(Type type, bool tryCreate, out DataC } } - Type knownInterfaceType = null; + Type? knownInterfaceType = null; CollectionKind kind = CollectionKind.None; bool multipleDefinitions = false; Type[] interfaceTypes = type.GetInterfaces(); @@ -1210,6 +1208,7 @@ private static bool IsCollectionOrTryCreate(Type type, bool tryCreate, out DataC SR.CollectionTypeIsNotIEnumerable, null, ref dataContract); } + Debug.Assert(knownInterfaceType != null); if (kind == CollectionKind.Enumerable || kind == CollectionKind.Collection || kind == CollectionKind.GenericEnumerable) { if (multipleDefinitions) @@ -1218,6 +1217,9 @@ private static bool IsCollectionOrTryCreate(Type type, bool tryCreate, out DataC GetCollectionMethods(type, knownInterfaceType, new Type[] { itemType }, false /*addMethodOnInterface*/, out getEnumeratorMethod, out addMethod); + + Debug.Assert(getEnumeratorMethod != null); + if (addMethod == null) { // All collection types could be considered read-only collections except collection types that are marked [Serializable]. @@ -1249,7 +1251,7 @@ private static bool IsCollectionOrTryCreate(Type type, bool tryCreate, out DataC return HandleIfInvalidCollection(type, tryCreate, hasCollectionDataContract, createContractWithException, SR.CollectionTypeHasMultipleDefinitionsOfInterface, KnownInterfaces[(int)kind - 1].Name, ref dataContract); } - Type[] addMethodTypeArray = null; + Type[]? addMethodTypeArray = null; switch (kind) { case CollectionKind.GenericDictionary: @@ -1275,10 +1277,13 @@ private static bool IsCollectionOrTryCreate(Type type, bool tryCreate, out DataC if (tryCreate) { + Debug.Assert(addMethodTypeArray != null); GetCollectionMethods(type, knownInterfaceType, addMethodTypeArray, true /*addMethodOnInterface*/, out getEnumeratorMethod, out addMethod); + Debug.Assert(getEnumeratorMethod != null); + dataContract = isReadOnlyContract ? new CollectionDataContract(type, kind, itemType, getEnumeratorMethod, deserializationExceptionMessage) : new CollectionDataContract(type, kind, itemType, getEnumeratorMethod, addMethod, defaultCtor, !constructorRequired); @@ -1293,7 +1298,7 @@ internal static bool IsCollectionDataContract(Type type) return type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, false); } - private static bool HandleIfInvalidCollection(Type type, bool tryCreate, bool hasCollectionDataContract, bool createContractWithException, string message, string param, ref DataContract dataContract) + private static bool HandleIfInvalidCollection(Type type, bool tryCreate, bool hasCollectionDataContract, bool createContractWithException, string message, string? param, ref DataContract? dataContract) { if (hasCollectionDataContract) { @@ -1312,19 +1317,19 @@ private static bool HandleIfInvalidCollection(Type type, bool tryCreate, bool ha return false; } - private static void GetReadOnlyCollectionExceptionMessages(Type type, string message, string param, out string deserializationExceptionMessage) + private static void GetReadOnlyCollectionExceptionMessages(Type type, string message, string? param, out string deserializationExceptionMessage) { deserializationExceptionMessage = GetInvalidCollectionMessage(message, SR.Format(SR.ReadOnlyCollectionDeserialization, GetClrTypeFullName(type)), param); } - private static string GetInvalidCollectionMessage(string message, string nestedMessage, string param) + private static string GetInvalidCollectionMessage(string message, string nestedMessage, string? param) { return (param == null) ? SR.Format(message, nestedMessage) : SR.Format(message, nestedMessage, param); } - private static void FindCollectionMethodsOnInterface(Type type, Type interfaceType, ref MethodInfo addMethod, ref MethodInfo getEnumeratorMethod) + private static void FindCollectionMethodsOnInterface(Type type, Type interfaceType, ref MethodInfo? addMethod, ref MethodInfo? getEnumeratorMethod) { - Type t = type.GetInterfaces().Where(it => it.Equals(interfaceType)).FirstOrDefault(); + Type? t = type.GetInterfaces().Where(it => it.Equals(interfaceType)).FirstOrDefault(); if (t != null) { addMethod = t.GetMethod(Globals.AddMethodName) ?? addMethod; @@ -1332,7 +1337,7 @@ private static void FindCollectionMethodsOnInterface(Type type, Type interfaceTy } } - private static void GetCollectionMethods(Type type, Type interfaceType, Type[] addMethodTypeArray, bool addMethodOnInterface, out MethodInfo getEnumeratorMethod, out MethodInfo addMethod) + private static void GetCollectionMethods(Type type, Type interfaceType, Type[] addMethodTypeArray, bool addMethodOnInterface, out MethodInfo? getEnumeratorMethod, out MethodInfo? addMethod) { addMethod = getEnumeratorMethod = null; @@ -1374,7 +1379,7 @@ private static void GetCollectionMethods(Type type, Type interfaceType, Type[] a getEnumeratorMethod = type.GetMethod(Globals.GetEnumeratorMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty()); if (getEnumeratorMethod == null || !Globals.TypeOfIEnumerator.IsAssignableFrom(getEnumeratorMethod.ReturnType)) { - Type ienumerableInterface = interfaceType.GetInterfaces().Where(t => t.FullName.StartsWith("System.Collections.Generic.IEnumerable")).FirstOrDefault(); + Type? ienumerableInterface = interfaceType.GetInterfaces().Where(t => t.FullName!.StartsWith("System.Collections.Generic.IEnumerable")).FirstOrDefault(); if (ienumerableInterface == null) ienumerableInterface = Globals.TypeOfIEnumerable; getEnumeratorMethod = GetTargetMethodWithName(Globals.GetEnumeratorMethodName, type, ienumerableInterface); @@ -1434,7 +1439,7 @@ internal override bool IsValidContract(SerializationMode mode) /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// - internal bool RequiresMemberAccessForRead(SecurityException securityException) + internal bool RequiresMemberAccessForRead(SecurityException? securityException) { if (!IsTypeVisible(UnderlyingType)) { @@ -1480,7 +1485,7 @@ internal bool RequiresMemberAccessForRead(SecurityException securityException) new SecurityException(SR.Format( SR.PartialTrustCollectionContractAddMethodNotPublic, DataContract.GetClrTypeFullName(UnderlyingType), - this.AddMethod.Name), + this.AddMethod!.Name), securityException)); } return true; @@ -1494,7 +1499,7 @@ internal bool RequiresMemberAccessForRead(SecurityException securityException) /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// - internal bool RequiresMemberAccessForWrite(SecurityException securityException) + internal bool RequiresMemberAccessForWrite(SecurityException? securityException) { if (!IsTypeVisible(UnderlyingType)) { @@ -1524,17 +1529,21 @@ internal bool RequiresMemberAccessForWrite(SecurityException securityException) return false; } - public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) + public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext? context) { + Debug.Assert(context != null); + // IsGetOnlyCollection value has already been used to create current collectiondatacontract, value can now be reset. context.IsGetOnlyCollection = false; XmlFormatWriterDelegate(xmlWriter, obj, context, this); } - public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context) + public override object? ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext? context) { + Debug.Assert(context != null); + xmlReader.Read(); - object o = null; + object? o = null; if (context.IsGetOnlyCollection) { // IsGetOnlyCollection value has already been used to create current collectiondatacontract, value can now be reset. @@ -1549,7 +1558,7 @@ public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSeria return o; } - internal class DictionaryEnumerator : IEnumerator> + internal class DictionaryEnumerator : IEnumerator> { private readonly IDictionaryEnumerator _enumerator; @@ -1568,9 +1577,9 @@ public bool MoveNext() return _enumerator.MoveNext(); } - public KeyValue Current + public KeyValue Current { - get { return new KeyValue(_enumerator.Key, _enumerator.Value); } + get { return new KeyValue(_enumerator.Key, _enumerator.Value); } } object System.Collections.IEnumerator.Current diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs index 935223ffaadcfc..93c069a62bd765 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs @@ -15,6 +15,8 @@ namespace System.Runtime.Serialization using System.Linq; using Xml.Schema; using System.Collections.Concurrent; + using System.Diagnostics.CodeAnalysis; + using System.Diagnostics; #if USE_REFEMIT public abstract class DataContract @@ -43,26 +45,26 @@ internal DataContract(DataContractCriticalHelper helper) _ns = helper.Namespace; } - private static DataContract GetGeneratedDataContract(Type type) + private static DataContract? GetGeneratedDataContract(Type type) { // this method used to be rewritten by an IL transform // with the restructuring for multi-file, it has become a regular method - DataContract result; + DataContract? result; return s_dataContracts.TryGetValue(type, out result) ? result : null; } - internal static bool TryGetDataContractFromGeneratedAssembly(Type type, out DataContract dataContract) + internal static bool TryGetDataContractFromGeneratedAssembly(Type type, out DataContract? dataContract) { dataContract = GetGeneratedDataContract(type); return dataContract != null; } - internal static DataContract GetDataContractFromGeneratedAssembly(Type type) + internal static DataContract? GetDataContractFromGeneratedAssembly(Type? type) { return null; } - internal MethodInfo ParseMethod + internal MethodInfo? ParseMethod { get { return _helper.ParseMethod; } } @@ -77,7 +79,7 @@ internal static DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type return GetDataContract(typeHandle, type, SerializationMode.SharedContract); } - internal static DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type type, SerializationMode mode) + internal static DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type? type, SerializationMode mode) { int id = GetId(typeHandle); DataContract dataContract = GetDataContractSkipValidation(id, typeHandle, null); @@ -90,12 +92,12 @@ internal static DataContract GetDataContract(int id, RuntimeTypeHandle typeHandl return dataContract.GetValidContract(mode); } - internal static DataContract GetDataContractSkipValidation(int id, RuntimeTypeHandle typeHandle, Type type) + internal static DataContract GetDataContractSkipValidation(int id, RuntimeTypeHandle typeHandle, Type? type) { return DataContractCriticalHelper.GetDataContractSkipValidation(id, typeHandle, type); } - internal static DataContract GetGetOnlyCollectionDataContract(int id, RuntimeTypeHandle typeHandle, Type type, SerializationMode mode) + internal static DataContract GetGetOnlyCollectionDataContract(int id, RuntimeTypeHandle typeHandle, Type? type, SerializationMode mode) { DataContract dataContract = GetGetOnlyCollectionDataContractSkipValidation(id, typeHandle, type); dataContract = dataContract.GetValidContract(mode); @@ -106,7 +108,7 @@ internal static DataContract GetGetOnlyCollectionDataContract(int id, RuntimeTyp return dataContract; } - internal static DataContract GetGetOnlyCollectionDataContractSkipValidation(int id, RuntimeTypeHandle typeHandle, Type type) + internal static DataContract GetGetOnlyCollectionDataContractSkipValidation(int id, RuntimeTypeHandle typeHandle, Type? type) { return DataContractCriticalHelper.GetGetOnlyCollectionDataContractSkipValidation(id, typeHandle, type); } @@ -126,17 +128,17 @@ internal static int GetId(RuntimeTypeHandle typeHandle) return DataContractCriticalHelper.GetId(typeHandle); } - public static DataContract GetBuiltInDataContract(Type type) + public static DataContract? GetBuiltInDataContract(Type type) { return DataContractCriticalHelper.GetBuiltInDataContract(type); } - public static DataContract GetBuiltInDataContract(string name, string ns) + public static DataContract? GetBuiltInDataContract(string name, string ns) { return DataContractCriticalHelper.GetBuiltInDataContract(name, ns); } - public static DataContract GetBuiltInDataContract(string typeName) + public static DataContract? GetBuiltInDataContract(string typeName) { return DataContractCriticalHelper.GetBuiltInDataContract(typeName); } @@ -151,7 +153,8 @@ internal static XmlDictionaryString GetClrTypeString(string key) return DataContractCriticalHelper.GetClrTypeString(key); } - internal static void ThrowInvalidDataContractException(string message, Type type) + [DoesNotReturn] + internal static void ThrowInvalidDataContractException(string? message, Type? type) { DataContractCriticalHelper.ThrowInvalidDataContractException(message, type); } @@ -192,17 +195,17 @@ internal Type TypeForInitialization { return _helper.TypeForInitialization; } } - public virtual void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) + public virtual void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext? context) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.UnexpectedContractType, DataContract.GetClrTypeFullName(this.GetType()), DataContract.GetClrTypeFullName(UnderlyingType)))); } - public virtual object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context) + public virtual object? ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext? context) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.UnexpectedContractType, DataContract.GetClrTypeFullName(this.GetType()), DataContract.GetClrTypeFullName(UnderlyingType)))); } - public virtual void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) + public virtual void WriteXmlElement(XmlWriterDelegator xmlWriter, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.UnexpectedContractType, DataContract.GetClrTypeFullName(this.GetType()), DataContract.GetClrTypeFullName(UnderlyingType)))); } @@ -239,7 +242,7 @@ public XmlQualifiedName StableName { _helper.StableName = value; } } - public virtual DataContractDictionary KnownDataContracts + public virtual DataContractDictionary? KnownDataContracts { get { return _helper.KnownDataContracts; } @@ -278,7 +281,7 @@ public virtual bool HasRoot { } } - public virtual XmlDictionaryString TopLevelElementName + public virtual XmlDictionaryString? TopLevelElementName { get { return _helper.TopLevelElementName; } @@ -287,7 +290,7 @@ public virtual XmlDictionaryString TopLevelElementName { _helper.TopLevelElementName = value; } } - public virtual XmlDictionaryString TopLevelElementNamespace + public virtual XmlDictionaryString? TopLevelElementNamespace { get { return _helper.TopLevelElementNamespace; } @@ -306,7 +309,7 @@ internal virtual bool IsPrimitive get { return false; } } - internal virtual void WriteRootElement(XmlWriterDelegator writer, XmlDictionaryString name, XmlDictionaryString ns) + internal virtual void WriteRootElement(XmlWriterDelegator writer, XmlDictionaryString name, XmlDictionaryString? ns) { if (object.ReferenceEquals(ns, DictionaryGlobals.SerializationNamespace) && !IsPrimitive) writer.WriteStartElement(Globals.SerPrefix, name, ns); @@ -334,11 +337,11 @@ internal class DataContractCriticalHelper private static readonly Dictionary s_typeToIDCache = new Dictionary(new TypeHandleRefEqualityComparer()); private static DataContract[] s_dataContractCache = new DataContract[32]; private static int s_dataContractID; - private static Dictionary s_typeToBuiltInContract; - private static Dictionary s_nameToBuiltInContract; - private static Dictionary s_namespaces; - private static Dictionary s_clrTypeStrings; - private static XmlDictionary s_clrTypeStringsDictionary; + private static Dictionary? s_typeToBuiltInContract; + private static Dictionary? s_nameToBuiltInContract; + private static Dictionary? s_namespaces; + private static Dictionary? s_clrTypeStrings; + private static XmlDictionary? s_clrTypeStringsDictionary; private static readonly TypeHandleRef s_typeHandleRef = new TypeHandleRef(); private static readonly object s_cacheLock = new object(); @@ -348,14 +351,14 @@ internal class DataContractCriticalHelper private static readonly object s_clrTypeStringsLock = new object(); private Type _underlyingType; - private Type _originalUnderlyingType; + private Type? _originalUnderlyingType; private bool _isReference; private bool _isValueType; - private XmlQualifiedName _stableName; - private XmlDictionaryString _name; - private XmlDictionaryString _ns; + private XmlQualifiedName _stableName = null!; // StableName is always set in concrete ctors set except for the "invalid" CollectionDataContract + private XmlDictionaryString _name = null!; // Name is always set in concrete ctors set except for the "invalid" CollectionDataContract + private XmlDictionaryString _ns = null!; // Namespace is always set in concrete ctors set except for the "invalid" CollectionDataContract - private MethodInfo _parseMethod; + private MethodInfo? _parseMethod; private bool _parseMethodSet; /// @@ -363,7 +366,7 @@ internal class DataContractCriticalHelper /// private Type _typeForInitialization; - internal static DataContract GetDataContractSkipValidation(int id, RuntimeTypeHandle typeHandle, Type type) + internal static DataContract GetDataContractSkipValidation(int id, RuntimeTypeHandle typeHandle, Type? type) { DataContract dataContract = s_dataContractCache[id]; if (dataContract == null) @@ -378,7 +381,7 @@ internal static DataContract GetDataContractSkipValidation(int id, RuntimeTypeHa return dataContract; } - internal static DataContract GetGetOnlyCollectionDataContractSkipValidation(int id, RuntimeTypeHandle typeHandle, Type type) + internal static DataContract GetGetOnlyCollectionDataContractSkipValidation(int id, RuntimeTypeHandle typeHandle, Type? type) { DataContract dataContract = s_dataContractCache[id]; if (dataContract == null) @@ -401,7 +404,7 @@ internal static DataContract GetDataContractForInitialization(int id) internal static int GetIdForInitialization(ClassDataContract classContract) { - int id = DataContract.GetId(classContract.TypeForInitialization.TypeHandle); + int id = DataContract.GetId(classContract.TypeForInitialization!.TypeHandle); if (id < s_dataContractCache.Length && ContractMatches(classContract, s_dataContractCache[id])) { return id; @@ -426,7 +429,7 @@ internal static int GetId(RuntimeTypeHandle typeHandle) { lock (s_cacheLock) { - IntRef id; + IntRef? id; typeHandle = GetDataContractAdapterTypeHandle(typeHandle); s_typeHandleRef.Value = typeHandle; if (!s_typeToIDCache.TryGetValue(s_typeHandleRef, out id)) @@ -461,9 +464,9 @@ internal static int GetId(RuntimeTypeHandle typeHandle) } // check whether a corresponding update is required in ClassDataContract.IsNonAttributedTypeValidForSerialization - private static DataContract CreateDataContract(int id, RuntimeTypeHandle typeHandle, Type type) + private static DataContract CreateDataContract(int id, RuntimeTypeHandle typeHandle, Type? type) { - DataContract dataContract = s_dataContractCache[id]; + DataContract? dataContract = s_dataContractCache[id]; if (dataContract == null) { lock (s_createDataContractLock) @@ -497,7 +500,7 @@ private static DataContract CreateDataContract(Type type) Type originalType = type; type = GetDataContractAdapterType(type); - DataContract dataContract = GetBuiltInDataContract(type); + DataContract? dataContract = GetBuiltInDataContract(type); if (dataContract == null) { if (type.IsArray) @@ -545,9 +548,9 @@ private static void AssignDataContractToId(DataContract dataContract, int id) } } - private static DataContract CreateGetOnlyCollectionDataContract(int id, RuntimeTypeHandle typeHandle, Type type) + private static DataContract CreateGetOnlyCollectionDataContract(int id, RuntimeTypeHandle typeHandle, Type? type) { - DataContract dataContract = null; + DataContract? dataContract = null; lock (s_createDataContractLock) { dataContract = s_dataContractCache[id]; @@ -602,7 +605,7 @@ private static RuntimeTypeHandle GetDataContractAdapterTypeHandle(RuntimeTypeHan return typeHandle; } - public static DataContract GetBuiltInDataContract(Type type) + public static DataContract? GetBuiltInDataContract(Type type) { if (type.IsInterface && !CollectionDataContract.IsCollectionInterface(type)) type = Globals.TypeOfObject; @@ -610,9 +613,9 @@ public static DataContract GetBuiltInDataContract(Type type) lock (s_initBuiltInContractsLock) { if (s_typeToBuiltInContract == null) - s_typeToBuiltInContract = new Dictionary(); + s_typeToBuiltInContract = new Dictionary(); - DataContract dataContract = null; + DataContract? dataContract; if (!s_typeToBuiltInContract.TryGetValue(type, out dataContract)) { TryCreateBuiltInDataContract(type, out dataContract); @@ -622,14 +625,14 @@ public static DataContract GetBuiltInDataContract(Type type) } } - public static DataContract GetBuiltInDataContract(string name, string ns) + public static DataContract? GetBuiltInDataContract(string name, string ns) { lock (s_initBuiltInContractsLock) { if (s_nameToBuiltInContract == null) - s_nameToBuiltInContract = new Dictionary(); + s_nameToBuiltInContract = new Dictionary(); - DataContract dataContract = null; + DataContract? dataContract; XmlQualifiedName qname = new XmlQualifiedName(name, ns); if (!s_nameToBuiltInContract.TryGetValue(qname, out dataContract)) { @@ -640,7 +643,7 @@ public static DataContract GetBuiltInDataContract(string name, string ns) } } - public static DataContract GetBuiltInDataContract(string typeName) + public static DataContract? GetBuiltInDataContract(string typeName) { if (!typeName.StartsWith("System.", StringComparison.Ordinal)) return null; @@ -648,13 +651,13 @@ public static DataContract GetBuiltInDataContract(string typeName) lock (s_initBuiltInContractsLock) { if (s_nameToBuiltInContract == null) - s_nameToBuiltInContract = new Dictionary(); + s_nameToBuiltInContract = new Dictionary(); - DataContract dataContract = null; + DataContract? dataContract; XmlQualifiedName qname = new XmlQualifiedName(typeName); if (!s_nameToBuiltInContract.TryGetValue(qname, out dataContract)) { - Type type = null; + Type? type = null; string name = typeName.Substring(7); if (name == "Char") type = typeof(char); @@ -718,7 +721,7 @@ public static DataContract GetBuiltInDataContract(string typeName) } } - public static bool TryCreateBuiltInDataContract(Type type, out DataContract dataContract) + public static bool TryCreateBuiltInDataContract(Type type, [NotNullWhen(true)] out DataContract? dataContract) { if (type.IsEnum) // Type.GetTypeCode will report Enums as TypeCode.IntXX { @@ -799,7 +802,7 @@ public static bool TryCreateBuiltInDataContract(Type type, out DataContract data return dataContract != null; } - public static bool TryCreateBuiltInDataContract(string name, string ns, out DataContract dataContract) + public static bool TryCreateBuiltInDataContract(string name, string ns, [NotNullWhen(true)] out DataContract? dataContract) { dataContract = null; if (ns == DictionaryGlobals.SchemaNamespace.Value) @@ -927,7 +930,7 @@ internal static string GetNamespace(string key) { if (s_namespaces == null) s_namespaces = new Dictionary(); - string value; + string? value; if (s_namespaces.TryGetValue(key, out value)) return value; try @@ -956,7 +959,7 @@ internal static XmlDictionaryString GetClrTypeString(string key) s_clrTypeStrings = new Dictionary(); try { - s_clrTypeStrings.Add(Globals.TypeOfInt.Assembly.FullName, s_clrTypeStringsDictionary.Add(Globals.MscorlibAssemblyName)); + s_clrTypeStrings.Add(Globals.TypeOfInt.Assembly.FullName!, s_clrTypeStringsDictionary.Add(Globals.MscorlibAssemblyName)); } catch (Exception ex) { @@ -967,10 +970,10 @@ internal static XmlDictionaryString GetClrTypeString(string key) throw DiagnosticUtility.ExceptionUtility.ThrowHelperFatal(ex.Message, ex); } } - XmlDictionaryString value; + XmlDictionaryString? value; if (s_clrTypeStrings.TryGetValue(key, out value)) return value; - value = s_clrTypeStringsDictionary.Add(key); + value = s_clrTypeStringsDictionary!.Add(key); try { s_clrTypeStrings.Add(key, value); @@ -987,7 +990,8 @@ internal static XmlDictionaryString GetClrTypeString(string key) } } - internal static void ThrowInvalidDataContractException(string message, Type type) + [DoesNotReturn] + internal static void ThrowInvalidDataContractException(string? message, Type? type) { if (type != null) { @@ -1012,10 +1016,6 @@ internal static void ThrowInvalidDataContractException(string message, Type type throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(message)); } - internal DataContractCriticalHelper() - { - } - internal DataContractCriticalHelper(Type type) { _underlyingType = type; @@ -1057,6 +1057,7 @@ internal Type TypeForInitialization get { return _typeForInitialization; } } + [MemberNotNull(nameof(_typeForInitialization))] private void SetTypeForInitialization(Type classType) { //if (classType.IsSerializable || classType.IsDefined(Globals.TypeOfDataContractAttribute, false)) @@ -1086,7 +1087,7 @@ internal XmlQualifiedName StableName set { _stableName = value; } } - internal virtual DataContractDictionary KnownDataContracts + internal virtual DataContractDictionary? KnownDataContracts { get { return null; } set { /* do nothing */ } @@ -1116,16 +1117,24 @@ internal virtual bool HasRoot set { } } - internal virtual XmlDictionaryString TopLevelElementName + internal virtual XmlDictionaryString? TopLevelElementName { get { return _name; } - set { _name = value; } + set + { + Debug.Assert(value != null); + _name = value; + } } - internal virtual XmlDictionaryString TopLevelElementNamespace + internal virtual XmlDictionaryString? TopLevelElementNamespace { get { return _ns; } - set { _ns = value; } + set + { + Debug.Assert(value != null); + _ns = value; + } } internal virtual bool CanContainReferences @@ -1138,13 +1147,13 @@ internal virtual bool IsPrimitive get { return false; } } - internal MethodInfo ParseMethod + internal MethodInfo? ParseMethod { get { if (!_parseMethodSet) { - MethodInfo method = UnderlyingType.GetMethod(Globals.ParseMethodName, BindingFlags.Public | BindingFlags.Static, new Type[] { typeof(string) }); + MethodInfo? method = UnderlyingType.GetMethod(Globals.ParseMethodName, BindingFlags.Public | BindingFlags.Static, new Type[] { typeof(string) }); if (method != null && method.ReturnType == UnderlyingType) { @@ -1172,6 +1181,7 @@ internal void SetDataContractName(XmlDictionaryString name, XmlDictionaryString this.StableName = CreateQualifiedName(name.Value, ns.Value); } + [DoesNotReturn] internal void ThrowInvalidDataContractException(string message) { ThrowInvalidDataContractException(message, UnderlyingType); @@ -1185,7 +1195,7 @@ internal static bool IsTypeSerializable(Type type) private static bool IsTypeSerializable(Type type, HashSet previousCollectionTypes) { - Type itemType; + Type? itemType; if (type.IsSerializable || type.IsEnum || @@ -1215,7 +1225,7 @@ private static void ValidatePreviousCollectionTypes(Type collectionType, Type it previousCollectionTypes.Add(collectionType); while (itemType.IsArray) { - itemType = itemType.GetElementType(); + itemType = itemType.GetElementType()!; } if (previousCollectionTypes.Contains(itemType)) { @@ -1307,14 +1317,14 @@ internal static XmlQualifiedName GetStableName(Type type) internal static XmlQualifiedName GetStableName(Type type, out bool hasDataContract) { type = UnwrapRedundantNullableType(type); - XmlQualifiedName stableName; + XmlQualifiedName? stableName; if (TryGetBuiltInXmlAndArrayTypeStableName(type, out stableName)) { hasDataContract = false; } else { - DataContractAttribute dataContractAttribute; + DataContractAttribute? dataContractAttribute; if (TryGetDCAttribute(type, out dataContractAttribute)) { stableName = GetDCTypeStableName(type, dataContractAttribute); @@ -1332,7 +1342,7 @@ internal static XmlQualifiedName GetStableName(Type type, out bool hasDataContra private static XmlQualifiedName GetDCTypeStableName(Type type, DataContractAttribute dataContractAttribute) { - string name = null, ns = null; + string? name = null, ns = null; if (dataContractAttribute.IsNameSetExplicitly) { name = dataContractAttribute.Name; @@ -1360,10 +1370,10 @@ private static XmlQualifiedName GetDCTypeStableName(Type type, DataContractAttri private static XmlQualifiedName GetNonDCTypeStableName(Type type) { - string name = null, ns = null; + string? name = null, ns = null; - Type itemType; - CollectionDataContractAttribute collectionContractAttribute; + Type? itemType; + CollectionDataContractAttribute? collectionContractAttribute; if (CollectionDataContract.IsCollection(type, out itemType)) return GetCollectionStableName(type, itemType, out collectionContractAttribute); name = GetDefaultStableLocalName(type); @@ -1380,11 +1390,11 @@ private static XmlQualifiedName GetNonDCTypeStableName(Type type) return CreateQualifiedName(name, ns); } - private static bool TryGetBuiltInXmlAndArrayTypeStableName(Type type, out XmlQualifiedName stableName) + private static bool TryGetBuiltInXmlAndArrayTypeStableName(Type type, [NotNullWhen(true)] out XmlQualifiedName? stableName) { stableName = null; - DataContract builtInContract = GetBuiltInDataContract(type); + DataContract? builtInContract = GetBuiltInDataContract(type); if (builtInContract != null) { stableName = builtInContract.StableName; @@ -1392,20 +1402,20 @@ private static bool TryGetBuiltInXmlAndArrayTypeStableName(Type type, out XmlQua else if (Globals.TypeOfIXmlSerializable.IsAssignableFrom(type)) { bool hasRoot; - XmlSchemaType xsdType; + XmlSchemaType? xsdType; XmlQualifiedName xmlTypeStableName; SchemaExporter.GetXmlTypeInfo(type, out xmlTypeStableName, out xsdType, out hasRoot); stableName = xmlTypeStableName; } else if (type.IsArray) { - CollectionDataContractAttribute collectionContractAttribute; - stableName = GetCollectionStableName(type, type.GetElementType(), out collectionContractAttribute); + CollectionDataContractAttribute? collectionContractAttribute; + stableName = GetCollectionStableName(type, type.GetElementType()!, out collectionContractAttribute); } return stableName != null; } - internal static bool TryGetDCAttribute(Type type, out DataContractAttribute dataContractAttribute) + internal static bool TryGetDCAttribute(Type type, [NotNullWhen(true)] out DataContractAttribute? dataContractAttribute) { dataContractAttribute = null; @@ -1422,9 +1432,9 @@ internal static bool TryGetDCAttribute(Type type, out DataContractAttribute data return dataContractAttribute != null; } - internal static XmlQualifiedName GetCollectionStableName(Type type, Type itemType, out CollectionDataContractAttribute collectionContractAttribute) + internal static XmlQualifiedName GetCollectionStableName(Type type, Type itemType, out CollectionDataContractAttribute? collectionContractAttribute) { - string name, ns; + string? name, ns; object[] collectionContractAttributes = type.GetCustomAttributes(Globals.TypeOfCollectionDataContractAttribute, false).ToArray(); if (collectionContractAttributes != null && collectionContractAttributes.Length > 0) { @@ -1474,7 +1484,7 @@ private static string GetArrayPrefix(ref Type itemType) if (DataContract.GetBuiltInDataContract(itemType) != null) break; arrayOfPrefix += Globals.ArrayPrefix; - itemType = itemType.GetElementType(); + itemType = itemType.GetElementType()!; } return arrayOfPrefix; } @@ -1494,7 +1504,7 @@ private static string GetDefaultStableLocalName(Type type) if (type.IsGenericParameter) return "{" + type.GenericParameterPosition + "}"; string typeName; - string arrayPrefix = null; + string? arrayPrefix = null; if (type.IsArray) arrayPrefix = GetArrayPrefix(ref type); if (type.DeclaringType == null) @@ -1548,10 +1558,10 @@ private static string GetDefaultStableLocalName(Type type) private static string GetDefaultDataContractNamespace(Type type) { - string clrNs = type.Namespace; + string? clrNs = type.Namespace; if (clrNs == null) clrNs = string.Empty; - string ns = GetGlobalDataContractNamespace(clrNs, type.Module.GetCustomAttributes(typeof(ContractNamespaceAttribute)).ToArray()); + string? ns = GetGlobalDataContractNamespace(clrNs, type.Module.GetCustomAttributes(typeof(ContractNamespaceAttribute)).ToArray()); if (ns == null) ns = GetGlobalDataContractNamespace(clrNs, type.Assembly.GetCustomAttributes(typeof(ContractNamespaceAttribute)).ToArray()); @@ -1562,7 +1572,7 @@ private static string GetDefaultDataContractNamespace(Type type) return ns; } - internal static List GetDataContractNameForGenericName(string typeName, StringBuilder localName) + internal static List GetDataContractNameForGenericName(string typeName, StringBuilder? localName) { List nestedParamCounts = new List(); for (int startIndex = 0, endIndex; ;) @@ -1613,7 +1623,7 @@ internal static XmlQualifiedName CreateQualifiedName(string localName, string ns return new XmlQualifiedName(localName, GetNamespace(ns)); } - internal static string GetDefaultStableNamespace(string clrNs) + internal static string GetDefaultStableNamespace(string? clrNs) { if (clrNs == null) clrNs = string.Empty; return new Uri(Globals.DataContractXsdBaseNamespaceUri, clrNs).AbsoluteUri; @@ -1628,7 +1638,7 @@ internal static void GetDefaultStableName(string fullTypeName, out string localN private static void GetDefaultStableName(CodeTypeReference typeReference, out string localName, out string ns) { string fullTypeName = typeReference.BaseType; - DataContract dataContract = GetBuiltInDataContract(fullTypeName); + DataContract? dataContract = GetBuiltInDataContract(fullTypeName); if (dataContract != null) { localName = dataContract.StableName.Name; @@ -1682,7 +1692,7 @@ private static void CheckExplicitDataContractNamespaceUri(string dataContractNs, ThrowInvalidDataContractException(SR.Format(SR.DataContractNamespaceIsNotValid, dataContractNs), type); dataContractNs = trimmedNs; } - Uri uri; + Uri? uri; if (Uri.TryCreate(dataContractNs, UriKind.RelativeOrAbsolute, out uri)) { if (uri.ToString() == Globals.SerializationNamespace) @@ -1694,7 +1704,7 @@ private static void CheckExplicitDataContractNamespaceUri(string dataContractNs, internal static string GetClrTypeFullName(Type type) { - return !type.IsGenericTypeDefinition && type.ContainsGenericParameters ? type.Namespace + "." + type.Name : type.FullName; + return !type.IsGenericTypeDefinition && type.ContainsGenericParameters ? type.Namespace + "." + type.Name : type.FullName!; } internal static void GetClrNameAndNamespace(string fullTypeName, out string localName, out string ns) @@ -1720,13 +1730,13 @@ internal static string GetDataContractNamespaceFromUri(string uriString) return uriString.StartsWith(Globals.DataContractXsdBaseNamespace, StringComparison.Ordinal) ? uriString.Substring(Globals.DataContractXsdBaseNamespace.Length) : uriString; } - private static string GetGlobalDataContractNamespace(string clrNs, object[] nsAttributes) + private static string? GetGlobalDataContractNamespace(string clrNs, object[] nsAttributes) { - string dataContractNs = null; + string? dataContractNs = null; for (int i = 0; i < nsAttributes.Length; i++) { ContractNamespaceAttribute nsAttribute = (ContractNamespaceAttribute)nsAttributes[i]; - string clrNsInAttribute = nsAttribute.ClrNamespace; + string? clrNsInAttribute = nsAttribute.ClrNamespace; if (clrNsInAttribute == null) clrNsInAttribute = string.Empty; if (clrNsInAttribute == clrNs) @@ -1898,7 +1908,7 @@ private static string ExpandGenericParameters(string format, Type type) internal static string ExpandGenericParameters(string format, IGenericNameProvider genericNameProvider) { - string digest = null; + string? digest = null; StringBuilder typeName = new StringBuilder(); IList nestedParameterCounts = genericNameProvider.GetNestedParameterCounts(); for (int i = 0; i < format.Length; i++) @@ -1950,15 +1960,15 @@ internal static bool IsTypeNullable(Type type) - internal static DataContractDictionary ImportKnownTypeAttributes(Type type) + internal static DataContractDictionary? ImportKnownTypeAttributes(Type type) { - DataContractDictionary knownDataContracts = null; + DataContractDictionary? knownDataContracts = null; Dictionary typesChecked = new Dictionary(); ImportKnownTypeAttributes(type, typesChecked, ref knownDataContracts); return knownDataContracts; } - private static void ImportKnownTypeAttributes(Type type, Dictionary typesChecked, ref DataContractDictionary knownDataContracts) + private static void ImportKnownTypeAttributes(Type? type, Dictionary typesChecked, ref DataContractDictionary? knownDataContracts) { while (type != null && DataContract.IsTypeSerializable(type)) { @@ -1991,7 +2001,7 @@ private static void ImportKnownTypeAttributes(Type type, Dictionary DataContract.ThrowInvalidDataContractException(SR.Format(SR.KnownTypeAttributeOneScheme, DataContract.GetClrTypeFullName(type)), type); } - string methodName = kt.MethodName; + string? methodName = kt.MethodName; if (methodName == null) { DataContract.ThrowInvalidDataContractException(SR.Format(SR.KnownTypeAttributeNoData, DataContract.GetClrTypeFullName(type)), type); @@ -2000,14 +2010,14 @@ private static void ImportKnownTypeAttributes(Type type, Dictionary if (methodName.Length == 0) DataContract.ThrowInvalidDataContractException(SR.Format(SR.KnownTypeAttributeEmptyString, DataContract.GetClrTypeFullName(type)), type); - MethodInfo method = type.GetMethod(methodName, BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public, Array.Empty()); + MethodInfo? method = type.GetMethod(methodName, BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public, Array.Empty()); if (method == null) DataContract.ThrowInvalidDataContractException(SR.Format(SR.KnownTypeAttributeUnknownMethod, methodName, DataContract.GetClrTypeFullName(type)), type); if (!Globals.TypeOfTypeEnumerable.IsAssignableFrom(method.ReturnType)) DataContract.ThrowInvalidDataContractException(SR.Format(SR.KnownTypeAttributeReturnType, DataContract.GetClrTypeFullName(type), methodName), type); - object types = method.Invoke(null, Array.Empty()); + object? types = method.Invoke(null, Array.Empty()); if (types == null) { DataContract.ThrowInvalidDataContractException(SR.Format(SR.KnownTypeAttributeMethodNull, DataContract.GetClrTypeFullName(type)), type); @@ -2029,7 +2039,7 @@ private static void ImportKnownTypeAttributes(Type type, Dictionary //For Json we need to add KeyValuePair to KnownTypes if the UnderLyingType is a Dictionary try { - CollectionDataContract collectionDataContract = DataContract.GetDataContract(type) as CollectionDataContract; + CollectionDataContract? collectionDataContract = DataContract.GetDataContract(type) as CollectionDataContract; if (collectionDataContract != null && collectionDataContract.IsDictionary && collectionDataContract.ItemType.GetGenericTypeDefinition() == Globals.TypeOfKeyValue) { @@ -2054,11 +2064,11 @@ private static void ImportKnownTypeAttributes(Type type, Dictionary } } - internal static void CheckAndAdd(Type type, Dictionary typesChecked, ref DataContractDictionary nameToDataContractTable) + internal static void CheckAndAdd(Type type, Dictionary typesChecked, [NotNullIfNotNull("nameToDataContractTable")] ref DataContractDictionary? nameToDataContractTable) { type = DataContract.UnwrapNullableType(type); DataContract dataContract = DataContract.GetDataContract(type); - DataContract alreadyExistingContract; + DataContract? alreadyExistingContract; if (nameToDataContractTable == null) { nameToDataContractTable = new DataContractDictionary(); @@ -2100,7 +2110,7 @@ internal static bool IsTypeVisible(Type t) /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// - internal static bool ConstructorRequiresMemberAccess(ConstructorInfo ctor) + internal static bool ConstructorRequiresMemberAccess(ConstructorInfo? ctor) { return ctor != null && !ctor.IsPublic && !IsMemberVisibleInSerializationModule(ctor); } @@ -2111,7 +2121,7 @@ internal static bool ConstructorRequiresMemberAccess(ConstructorInfo ctor) /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// - internal static bool MethodRequiresMemberAccess(MethodInfo method) + internal static bool MethodRequiresMemberAccess(MethodInfo? method) { return method != null && !method.IsPublic && !IsMemberVisibleInSerializationModule(method); } @@ -2122,7 +2132,7 @@ internal static bool MethodRequiresMemberAccess(MethodInfo method) /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// - internal static bool FieldRequiresMemberAccess(FieldInfo field) + internal static bool FieldRequiresMemberAccess(FieldInfo? field) { return field != null && !field.IsPublic && !IsMemberVisibleInSerializationModule(field); } @@ -2144,7 +2154,7 @@ private static bool IsTypeVisibleInSerializationModule(Type type) /// private static bool IsMemberVisibleInSerializationModule(MemberInfo member) { - if (!IsTypeVisibleInSerializationModule(member.DeclaringType)) + if (!IsTypeVisibleInSerializationModule(member.DeclaringType!)) return false; if (member is MethodInfo) @@ -2271,10 +2281,10 @@ public bool ParametersFromBuiltInNamespaces private XmlQualifiedName GetStableName(int i) { object o = _genericParams[i]; - XmlQualifiedName qname = o as XmlQualifiedName; + XmlQualifiedName? qname = o as XmlQualifiedName; if (qname == null) { - Type paramType = o as Type; + Type? paramType = o as Type; if (paramType != null) _genericParams[i] = qname = DataContract.GetStableName(paramType); else @@ -2288,9 +2298,9 @@ private XmlQualifiedName GetStableName(int i) internal class TypeHandleRefEqualityComparer : IEqualityComparer { - public bool Equals(TypeHandleRef x, TypeHandleRef y) + public bool Equals(TypeHandleRef? x, TypeHandleRef? y) { - return x.Value.Equals(y.Value); + return x!.Value.Equals(y!.Value); } public int GetHashCode(TypeHandleRef obj) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractResolver.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractResolver.cs index 6cfc5ef44ad99b..ea96105f2195bd 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractResolver.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractResolver.cs @@ -8,7 +8,7 @@ namespace System.Runtime.Serialization { public abstract class DataContractResolver { - public abstract bool TryResolveType(Type type, Type declaredType, DataContractResolver knownTypeResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace); - public abstract Type ResolveName(string typeName, string typeNamespace, Type declaredType, DataContractResolver knownTypeResolver); + public abstract bool TryResolveType(Type type, Type? declaredType, DataContractResolver knownTypeResolver, out XmlDictionaryString? typeName, out XmlDictionaryString? typeNamespace); + public abstract Type? ResolveName(string typeName, string? typeNamespace, Type? declaredType, DataContractResolver knownTypeResolver); } } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSerializer.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSerializer.cs index 61dbc2cb0b8705..53a1840c9cdc13 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSerializer.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSerializer.cs @@ -15,22 +15,23 @@ namespace System.Runtime.Serialization using System.Collections.ObjectModel; using System.Runtime.CompilerServices; using DataContractDictionary = System.Collections.Generic.Dictionary; + using System.Diagnostics.CodeAnalysis; public sealed class DataContractSerializer : XmlObjectSerializer { private Type _rootType; - private DataContract _rootContract; // post-surrogate + private DataContract? _rootContract; // post-surrogate private bool _needsContractNsAtRoot; - private XmlDictionaryString _rootName; - private XmlDictionaryString _rootNamespace; + private XmlDictionaryString? _rootName; + private XmlDictionaryString? _rootNamespace; private int _maxItemsInObjectGraph; private bool _ignoreExtensionDataObject; private bool _preserveObjectReferences; - private ReadOnlyCollection _knownTypeCollection; - internal IList knownTypeList; - internal DataContractDictionary knownDataContracts; - private DataContractResolver _dataContractResolver; - private ISerializationSurrogateProvider _serializationSurrogateProvider; + private ReadOnlyCollection? _knownTypeCollection; + internal IList? knownTypeList; + internal DataContractDictionary? knownDataContracts; + private DataContractResolver? _dataContractResolver; + private ISerializationSurrogateProvider? _serializationSurrogateProvider; private bool _serializeReadOnlyTypes; private static SerializationOption _option = IsReflectionBackupAllowed() ? SerializationOption.ReflectionAsBackup : SerializationOption.CodeGenOnly; @@ -55,11 +56,11 @@ private static bool IsReflectionBackupAllowed() } public DataContractSerializer(Type type) - : this(type, (IEnumerable)null) + : this(type, (IEnumerable?)null) { } - public DataContractSerializer(Type type, IEnumerable knownTypes) + public DataContractSerializer(Type type, IEnumerable? knownTypes) { Initialize(type, knownTypes, int.MaxValue, false, false, null, false); } @@ -70,7 +71,7 @@ public DataContractSerializer(Type type, string rootName, string rootNamespace) { } - public DataContractSerializer(Type type, string rootName, string rootNamespace, IEnumerable knownTypes) + public DataContractSerializer(Type type, string rootName, string rootNamespace, IEnumerable? knownTypes) { XmlDictionary dictionary = new XmlDictionary(2); Initialize(type, dictionary.Add(rootName), dictionary.Add(DataContract.GetNamespace(rootNamespace)), knownTypes, int.MaxValue, false, false, null, false); @@ -82,7 +83,7 @@ public DataContractSerializer(Type type, XmlDictionaryString rootName, XmlDictio { } - public DataContractSerializer(Type type, XmlDictionaryString rootName, XmlDictionaryString rootNamespace, IEnumerable knownTypes) + public DataContractSerializer(Type type, XmlDictionaryString rootName, XmlDictionaryString rootNamespace, IEnumerable? knownTypes) { Initialize(type, rootName, rootNamespace, knownTypes, int.MaxValue, false, false, null, false); } @@ -92,7 +93,7 @@ internal DataContractSerializer(Type type, IEnumerable knownTypes, int max Initialize(type, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, preserveObjectReferences, null, false); } - public DataContractSerializer(Type type, DataContractSerializerSettings settings) + public DataContractSerializer(Type type, DataContractSerializerSettings? settings) { if (settings == null) { @@ -102,12 +103,13 @@ public DataContractSerializer(Type type, DataContractSerializerSettings settings settings.PreserveObjectReferences, settings.DataContractResolver, settings.SerializeReadOnlyTypes); } + [MemberNotNull(nameof(_rootType))] private void Initialize(Type type, - IEnumerable knownTypes, + IEnumerable? knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, bool preserveObjectReferences, - DataContractResolver dataContractResolver, + DataContractResolver? dataContractResolver, bool serializeReadOnlyTypes) { CheckNull(type, nameof(type)); @@ -132,12 +134,13 @@ private void Initialize(Type type, _serializeReadOnlyTypes = serializeReadOnlyTypes; } - private void Initialize(Type type, XmlDictionaryString rootName, XmlDictionaryString rootNamespace, - IEnumerable knownTypes, + [MemberNotNull(nameof(_rootType))] + private void Initialize(Type type, XmlDictionaryString? rootName, XmlDictionaryString? rootNamespace, + IEnumerable? knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, bool preserveObjectReferences, - DataContractResolver dataContractResolver, + DataContractResolver? dataContractResolver, bool serializeReadOnlyTypes) { Initialize(type, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, preserveObjectReferences, dataContractResolver, serializeReadOnlyTypes); @@ -166,7 +169,7 @@ public ReadOnlyCollection KnownTypes } } - internal override DataContractDictionary KnownDataContracts + internal override DataContractDictionary? KnownDataContracts { get { @@ -187,7 +190,7 @@ public int MaxItemsInObjectGraph get { return _maxItemsInObjectGraph; } } - internal ISerializationSurrogateProvider SerializationSurrogateProvider + internal ISerializationSurrogateProvider? SerializationSurrogateProvider { get { return _serializationSurrogateProvider; } set { _serializationSurrogateProvider = value; } @@ -203,7 +206,7 @@ public bool IgnoreExtensionDataObject get { return _ignoreExtensionDataObject; } } - public DataContractResolver DataContractResolver + public DataContractResolver? DataContractResolver { get { return _dataContractResolver; } } @@ -226,29 +229,29 @@ private DataContract RootContract } } - internal override void InternalWriteObject(XmlWriterDelegator writer, object graph) + internal override void InternalWriteObject(XmlWriterDelegator writer, object? graph) { InternalWriteObject(writer, graph, null); } - internal override void InternalWriteObject(XmlWriterDelegator writer, object graph, DataContractResolver dataContractResolver) + internal override void InternalWriteObject(XmlWriterDelegator writer, object? graph, DataContractResolver? dataContractResolver) { InternalWriteStartObject(writer, graph); InternalWriteObjectContent(writer, graph, dataContractResolver); InternalWriteEndObject(writer); } - public override void WriteObject(XmlWriter writer, object graph) + public override void WriteObject(XmlWriter writer, object? graph) { WriteObjectHandleExceptions(new XmlWriterDelegator(writer), graph); } - public override void WriteStartObject(XmlWriter writer, object graph) + public override void WriteStartObject(XmlWriter writer, object? graph) { WriteStartObjectHandleExceptions(new XmlWriterDelegator(writer), graph); } - public override void WriteObjectContent(XmlWriter writer, object graph) + public override void WriteObjectContent(XmlWriter writer, object? graph) { WriteObjectContentHandleExceptions(new XmlWriterDelegator(writer), graph); } @@ -258,12 +261,12 @@ public override void WriteEndObject(XmlWriter writer) WriteEndObjectHandleExceptions(new XmlWriterDelegator(writer)); } - public override void WriteStartObject(XmlDictionaryWriter writer, object graph) + public override void WriteStartObject(XmlDictionaryWriter writer, object? graph) { WriteStartObjectHandleExceptions(new XmlWriterDelegator(writer), graph); } - public override void WriteObjectContent(XmlDictionaryWriter writer, object graph) + public override void WriteObjectContent(XmlDictionaryWriter writer, object? graph) { WriteObjectContentHandleExceptions(new XmlWriterDelegator(writer), graph); } @@ -273,17 +276,17 @@ public override void WriteEndObject(XmlDictionaryWriter writer) WriteEndObjectHandleExceptions(new XmlWriterDelegator(writer)); } - public void WriteObject(XmlDictionaryWriter writer, object graph, DataContractResolver dataContractResolver) + public void WriteObject(XmlDictionaryWriter writer, object? graph, DataContractResolver? dataContractResolver) { WriteObjectHandleExceptions(new XmlWriterDelegator(writer), graph, dataContractResolver); } - public override object ReadObject(XmlReader reader) + public override object? ReadObject(XmlReader reader) { return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), true /*verifyObjectName*/); } - public override object ReadObject(XmlReader reader, bool verifyObjectName) + public override object? ReadObject(XmlReader reader, bool verifyObjectName) { return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), verifyObjectName); } @@ -293,7 +296,7 @@ public override bool IsStartObject(XmlReader reader) return IsStartObjectHandleExceptions(new XmlReaderDelegator(reader)); } - public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName) + public override object? ReadObject(XmlDictionaryReader reader, bool verifyObjectName) { return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), verifyObjectName); } @@ -303,22 +306,22 @@ public override bool IsStartObject(XmlDictionaryReader reader) return IsStartObjectHandleExceptions(new XmlReaderDelegator(reader)); } - public object ReadObject(XmlDictionaryReader reader, bool verifyObjectName, DataContractResolver dataContractResolver) + public object? ReadObject(XmlDictionaryReader reader, bool verifyObjectName, DataContractResolver? dataContractResolver) { return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), verifyObjectName, dataContractResolver); } - internal override void InternalWriteStartObject(XmlWriterDelegator writer, object graph) + internal override void InternalWriteStartObject(XmlWriterDelegator writer, object? graph) { WriteRootElement(writer, RootContract, _rootName, _rootNamespace, _needsContractNsAtRoot); } - internal override void InternalWriteObjectContent(XmlWriterDelegator writer, object graph) + internal override void InternalWriteObjectContent(XmlWriterDelegator writer, object? graph) { InternalWriteObjectContent(writer, graph, null); } - internal void InternalWriteObjectContent(XmlWriterDelegator writer, object graph, DataContractResolver dataContractResolver) + internal void InternalWriteObjectContent(XmlWriterDelegator writer, object? graph, DataContractResolver? dataContractResolver) { if (MaxItemsInObjectGraph == 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ExceededMaxItemsQuota, MaxItemsInObjectGraph))); @@ -358,7 +361,7 @@ internal void InternalWriteObjectContent(XmlWriterDelegator writer, object graph } else { - XmlObjectSerializerWriteContext context = null; + XmlObjectSerializerWriteContext? context = null; if (IsRootXmlAny(_rootName, contract)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.IsAnyCannotBeSerializedAsDerivedType, graphType, contract.UnderlyingType))); @@ -398,12 +401,12 @@ internal override void InternalWriteEndObject(XmlWriterDelegator writer) } } - internal override object InternalReadObject(XmlReaderDelegator xmlReader, bool verifyObjectName) + internal override object? InternalReadObject(XmlReaderDelegator xmlReader, bool verifyObjectName) { return InternalReadObject(xmlReader, verifyObjectName, null); } - internal override object InternalReadObject(XmlReaderDelegator xmlReader, bool verifyObjectName, DataContractResolver dataContractResolver) + internal override object? InternalReadObject(XmlReaderDelegator xmlReader, bool verifyObjectName, DataContractResolver? dataContractResolver) { if (MaxItemsInObjectGraph == 0) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ExceededMaxItemsQuota, MaxItemsInObjectGraph))); @@ -415,8 +418,8 @@ internal override object InternalReadObject(XmlReaderDelegator xmlReader, bool v { if (!InternalIsStartObject(xmlReader)) { - XmlDictionaryString expectedName; - XmlDictionaryString expectedNs; + XmlDictionaryString? expectedName; + XmlDictionaryString? expectedNs; if (_rootName == null) { expectedName = RootContract.TopLevelElementName; @@ -443,7 +446,7 @@ internal override object InternalReadObject(XmlReaderDelegator xmlReader, bool v if (IsRootXmlAny(_rootName, contract)) { - return XmlObjectSerializerReadContext.ReadRootIXmlSerializable(xmlReader, contract as XmlDataContract, false /*isMemberType*/); + return XmlObjectSerializerReadContext.ReadRootIXmlSerializable(xmlReader, (contract as XmlDataContract)!, false /*isMemberType*/); } XmlObjectSerializerReadContext context = XmlObjectSerializerReadContext.CreateContext(this, contract, dataContractResolver); @@ -456,19 +459,20 @@ internal override bool InternalIsStartObject(XmlReaderDelegator reader) return IsRootElement(reader, RootContract, _rootName, _rootNamespace); } - internal override Type GetSerializeType(object graph) + internal override Type? GetSerializeType(object? graph) { return (graph == null) ? _rootType : graph.GetType(); } - internal override Type GetDeserializeType() + internal override Type? GetDeserializeType() { return _rootType; } - internal static object SurrogateToDataContractType(ISerializationSurrogateProvider serializationSurrogateProvider, object oldObj, Type surrogatedDeclaredType, ref Type objType) + [return: NotNullIfNotNull("oldObj")] + internal static object? SurrogateToDataContractType(ISerializationSurrogateProvider serializationSurrogateProvider, object? oldObj, Type surrogatedDeclaredType, ref Type objType) { - object obj = DataContractSurrogateCaller.GetObjectToSerialize(serializationSurrogateProvider, oldObj, objType, surrogatedDeclaredType); + object? obj = DataContractSurrogateCaller.GetObjectToSerialize(serializationSurrogateProvider, oldObj, objType, surrogatedDeclaredType); if (obj != oldObj) { objType = obj != null ? obj.GetType() : Globals.TypeOfObject; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSerializerExtensions.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSerializerExtensions.cs index 33e0ed5309903a..87f2b6083d78fd 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSerializerExtensions.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSerializerExtensions.cs @@ -5,12 +5,12 @@ namespace System.Runtime.Serialization { public static class DataContractSerializerExtensions { - public static ISerializationSurrogateProvider GetSerializationSurrogateProvider(this DataContractSerializer serializer) + public static ISerializationSurrogateProvider? GetSerializationSurrogateProvider(this DataContractSerializer serializer) { return serializer.SerializationSurrogateProvider; } - public static void SetSerializationSurrogateProvider(this DataContractSerializer serializer, ISerializationSurrogateProvider provider) + public static void SetSerializationSurrogateProvider(this DataContractSerializer serializer, ISerializationSurrogateProvider? provider) { serializer.SerializationSurrogateProvider = provider; } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSerializerSettings.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSerializerSettings.cs index a9db9bf59678f4..4adb0399b2a6dd 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSerializerSettings.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSerializerSettings.cs @@ -17,17 +17,17 @@ public class DataContractSerializerSettings /// /// Gets or sets Dummy documentation /// - public XmlDictionaryString RootName { get; set; } + public XmlDictionaryString? RootName { get; set; } /// /// Gets or sets Dummy documentation /// - public XmlDictionaryString RootNamespace { get; set; } + public XmlDictionaryString? RootNamespace { get; set; } /// /// Gets or sets Dummy documentation /// - public IEnumerable KnownTypes { get; set; } + public IEnumerable? KnownTypes { get; set; } /// /// Gets or sets Dummy documentation @@ -52,7 +52,7 @@ public int MaxItemsInObjectGraph /// /// Gets or sets Dummy documentation /// - public DataContractResolver DataContractResolver { get; set; } + public DataContractResolver? DataContractResolver { get; set; } /// /// Gets or sets a value indicating whether Dummy documentation diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSet.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSet.cs index 0fee2c35c71ad7..69f10044954474 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSet.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSet.cs @@ -11,8 +11,8 @@ namespace System.Runtime.Serialization { internal sealed class DataContractSet { - private Dictionary _contracts; - private Dictionary _processedContracts; + private Dictionary? _contracts; + private Dictionary? _processedContracts; private readonly ICollection _referencedTypes; private readonly ICollection _referencedCollectionTypes; @@ -115,7 +115,7 @@ public void Add(XmlQualifiedName name, DataContract dataContract) internal void InternalAdd(XmlQualifiedName name, DataContract dataContract) { - DataContract dataContractInSet = null; + DataContract? dataContractInSet = null; if (Contracts.TryGetValue(name, out dataContractInSet)) { if (!dataContractInSet.Equals(dataContract)) @@ -184,7 +184,7 @@ private void AddCollectionDataContract(CollectionDataContract collectionDataCont { if (collectionDataContract.IsDictionary) { - ClassDataContract keyValueContract = collectionDataContract.ItemContract as ClassDataContract; + ClassDataContract keyValueContract = (collectionDataContract.ItemContract as ClassDataContract)!; AddClassDataContract(keyValueContract); } else @@ -201,7 +201,7 @@ private void AddXmlDataContract(XmlDataContract xmlDataContract) AddKnownDataContracts(xmlDataContract.KnownDataContracts); } - private void AddKnownDataContracts(DataContractDictionary knownDataContracts) + private void AddKnownDataContracts(DataContractDictionary? knownDataContracts) { if (knownDataContracts != null) { @@ -218,7 +218,7 @@ internal DataContract GetDataContract(Type clrType) if (_dataContractSurrogate == null) return DataContract.GetDataContract(clrType); #endif - DataContract dataContract = DataContract.GetBuiltInDataContract(clrType); + DataContract? dataContract = DataContract.GetBuiltInDataContract(clrType); if (dataContract != null) return dataContract; @@ -243,11 +243,9 @@ internal DataContract GetDataContract(Type clrType) internal DataContract GetMemberTypeDataContract(DataMember dataMember) { - if (dataMember.MemberInfo != null) + Type dataMemberType = dataMember.MemberType; + if (dataMember.IsGetOnlyCollection) { - Type dataMemberType = dataMember.MemberType; - if (dataMember.IsGetOnlyCollection) - { #if SUPPORT_SURROGATE if (_dataContractSurrogate != null) { @@ -259,14 +257,12 @@ internal DataContract GetMemberTypeDataContract(DataMember dataMember) } } #endif - return DataContract.GetGetOnlyCollectionDataContract(DataContract.GetId(dataMemberType.TypeHandle), dataMemberType.TypeHandle, dataMemberType, SerializationMode.SharedContract); - } - else - { - return GetDataContract(dataMemberType); - } + return DataContract.GetGetOnlyCollectionDataContract(DataContract.GetId(dataMemberType.TypeHandle), dataMemberType.TypeHandle, dataMemberType, SerializationMode.SharedContract); + } + else + { + return GetDataContract(dataMemberType); } - return dataMember.MemberTypeContract; } internal DataContract GetItemTypeDataContract(CollectionDataContract collectionContract) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSurrogateCaller.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSurrogateCaller.cs index 9e59d3b6ee9d2e..2ef49f1e56ca69 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSurrogateCaller.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContractSurrogateCaller.cs @@ -7,6 +7,7 @@ namespace System.Runtime.Serialization using System.CodeDom; using System.Reflection; using System.Collections.ObjectModel; + using System.Diagnostics.CodeAnalysis; internal static class DataContractSurrogateCaller { @@ -17,7 +18,8 @@ internal static Type GetDataContractType(ISerializationSurrogateProvider surroga return surrogateProvider.GetSurrogateType(type) ?? type; } - internal static object GetObjectToSerialize(ISerializationSurrogateProvider surrogateProvider, object obj, Type objType, Type membertype) + [return: NotNullIfNotNull("obj")] + internal static object? GetObjectToSerialize(ISerializationSurrogateProvider surrogateProvider, object? obj, Type objType, Type membertype) { if (obj == null) return null; @@ -26,7 +28,8 @@ internal static object GetObjectToSerialize(ISerializationSurrogateProvider surr return surrogateProvider.GetObjectToSerialize(obj, membertype); } - internal static object GetDeserializedObject(ISerializationSurrogateProvider surrogateProvider, object obj, Type objType, Type memberType) + [return: NotNullIfNotNull("obj")] + internal static object? GetDeserializedObject(ISerializationSurrogateProvider surrogateProvider, object? obj, Type objType, Type memberType) { if (obj == null) return null; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataMember.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataMember.cs index 6c5f3e68854561..b2ddbd1f220bca 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataMember.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataMember.cs @@ -16,11 +16,6 @@ internal class DataMember { private readonly CriticalHelper _helper; - public DataMember() - { - _helper = new CriticalHelper(); - } - internal DataMember(MemberInfo memberInfo) { _helper = new CriticalHelper(memberInfo); @@ -98,7 +93,7 @@ internal DataContract MemberTypeContract { return _helper.MemberTypeContract; } } - internal PrimitiveDataContract MemberPrimitiveContract + internal PrimitiveDataContract? MemberPrimitiveContract { get { @@ -115,7 +110,7 @@ public bool HasConflictingNameAndType { _helper.HasConflictingNameAndType = value; } } - internal DataMember ConflictingMember + internal DataMember? ConflictingMember { get { return _helper.ConflictingMember; } @@ -124,7 +119,7 @@ internal DataMember ConflictingMember { _helper.ConflictingMember = value; } } - private FastInvokerBuilder.Getter _getter; + private FastInvokerBuilder.Getter? _getter; internal FastInvokerBuilder.Getter Getter { get @@ -138,7 +133,7 @@ internal FastInvokerBuilder.Getter Getter } } - private FastInvokerBuilder.Setter _setter; + private FastInvokerBuilder.Setter? _setter; internal FastInvokerBuilder.Setter Setter { get @@ -154,8 +149,8 @@ internal FastInvokerBuilder.Setter Setter private class CriticalHelper { - private DataContract _memberTypeContract; - private string _name; + private DataContract? _memberTypeContract; + private string _name = null!; // Name is always initialized right after construction private int _order; private bool _isRequired; private bool _emitDefaultValue; @@ -163,12 +158,7 @@ private class CriticalHelper private bool _isGetOnlyCollection; private readonly MemberInfo _memberInfo; private bool _hasConflictingNameAndType; - private DataMember _conflictingMember; - - internal CriticalHelper() - { - _emitDefaultValue = Globals.DefaultEmitDefaultValue; - } + private DataMember? _conflictingMember; internal CriticalHelper(MemberInfo memberInfo) { @@ -217,7 +207,7 @@ internal bool IsGetOnlyCollection set { _isGetOnlyCollection = value; } } - private Type _memberType; + private Type? _memberType; internal Type MemberType { @@ -225,7 +215,7 @@ internal Type MemberType { if (_memberType == null) { - FieldInfo field = MemberInfo as FieldInfo; + FieldInfo? field = MemberInfo as FieldInfo; if (field != null) _memberType = field.FieldType; else @@ -254,7 +244,9 @@ internal DataContract MemberTypeContract } } } - return _memberTypeContract; + + // TODO-NULLABLE - MemberInfo is never null, so this can never return null + return _memberTypeContract!; } set { @@ -268,15 +260,15 @@ internal bool HasConflictingNameAndType set { _hasConflictingNameAndType = value; } } - internal DataMember ConflictingMember + internal DataMember? ConflictingMember { get { return _conflictingMember; } set { _conflictingMember = value; } } - private PrimitiveDataContract _memberPrimitiveContract = PrimitiveDataContract.NullContract; + private PrimitiveDataContract? _memberPrimitiveContract = PrimitiveDataContract.NullContract; - internal PrimitiveDataContract MemberPrimitiveContract + internal PrimitiveDataContract? MemberPrimitiveContract { get { @@ -298,7 +290,7 @@ internal PrimitiveDataContract MemberPrimitiveContract internal bool RequiresMemberAccessForGet() { MemberInfo memberInfo = MemberInfo; - FieldInfo field = memberInfo as FieldInfo; + FieldInfo? field = memberInfo as FieldInfo; if (field != null) { return DataContract.FieldRequiresMemberAccess(field); @@ -306,7 +298,7 @@ internal bool RequiresMemberAccessForGet() else { PropertyInfo property = (PropertyInfo)memberInfo; - MethodInfo getMethod = property.GetMethod; + MethodInfo? getMethod = property.GetMethod; if (getMethod != null) { return DataContract.MethodRequiresMemberAccess(getMethod) || !DataContract.IsTypeVisible(property.PropertyType); @@ -323,7 +315,7 @@ internal bool RequiresMemberAccessForGet() internal bool RequiresMemberAccessForSet() { MemberInfo memberInfo = MemberInfo; - FieldInfo field = memberInfo as FieldInfo; + FieldInfo? field = memberInfo as FieldInfo; if (field != null) { return DataContract.FieldRequiresMemberAccess(field); @@ -331,7 +323,7 @@ internal bool RequiresMemberAccessForSet() else { PropertyInfo property = (PropertyInfo)memberInfo; - MethodInfo setMethod = property.SetMethod; + MethodInfo? setMethod = property.SetMethod; if (setMethod != null) { return DataContract.MethodRequiresMemberAccess(setMethod) || !DataContract.IsTypeVisible(property.PropertyType); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DiagnosticUtility.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DiagnosticUtility.cs index 9ac01064795c47..019614307a14e1 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DiagnosticUtility.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DiagnosticUtility.cs @@ -2,19 +2,20 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics; - +using System.Diagnostics.CodeAnalysis; namespace System.Runtime.Serialization { internal static class Fx { [Conditional("DEBUG")] - public static void Assert(bool condition, string message) + public static void Assert([DoesNotReturnIf(false)] bool condition, string message) { System.Diagnostics.Debug.Assert(condition, message); } [Conditional("DEBUG")] + [DoesNotReturn] public static void Assert(string message) { Assert(false, message); @@ -24,18 +25,19 @@ public static void Assert(string message) internal class DiagnosticUtility { [Conditional("DEBUG")] + [DoesNotReturn] public static void DebugAssert(string message) { DebugAssert(false, message); } [Conditional("DEBUG")] - public static void DebugAssert(bool condition, string message) + public static void DebugAssert([DoesNotReturnIf(false)] bool condition, string message) { Debug.Assert(condition, message); } - internal static bool IsFatal(Exception exception) + internal static bool IsFatal(Exception? exception) { while (exception != null) { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/EnumDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/EnumDataContract.cs index dcbd70cd6770d3..e6d46aac89983d 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/EnumDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/EnumDataContract.cs @@ -11,7 +11,7 @@ using System.Xml; using System.Security; using System.Linq; - +using System.Diagnostics.CodeAnalysis; namespace System.Runtime.Serialization { @@ -19,16 +19,11 @@ internal sealed class EnumDataContract : DataContract { private readonly EnumDataContractCriticalHelper _helper; - public EnumDataContract() : base(new EnumDataContractCriticalHelper()) - { - _helper = base.Helper as EnumDataContractCriticalHelper; - } - - public XmlQualifiedName BaseContractName { get; set; } + public XmlQualifiedName? BaseContractName { get; set; } internal EnumDataContract(Type type) : base(new EnumDataContractCriticalHelper(type)) { - _helper = base.Helper as EnumDataContractCriticalHelper; + _helper = (base.Helper as EnumDataContractCriticalHelper)!; } public List Members { @@ -37,7 +32,7 @@ public List Members set { _helper.Members = value; } } - public List Values + public List? Values { get { return _helper.Values; } @@ -58,7 +53,7 @@ public bool IsULong set { _helper.IsULong = value; } } - public XmlDictionaryString[] ChildElementNames + public XmlDictionaryString[]? ChildElementNames { get { return _helper.ChildElementNames; } @@ -76,11 +71,11 @@ private class EnumDataContractCriticalHelper : DataContract.DataContractCritical private static readonly Dictionary s_nameToType = new Dictionary(); private List _members; - private List _values; + private List? _values; private bool _isULong; private bool _isFlags; private readonly bool _hasDataContract; - private XmlDictionaryString[] _childElementNames; + private XmlDictionaryString[]? _childElementNames; static EnumDataContractCriticalHelper() { @@ -101,11 +96,6 @@ internal static void Add(Type type, string localName) s_nameToType.Add(stableName, type); } - internal EnumDataContractCriticalHelper() - { - IsValueType = true; - } - internal EnumDataContractCriticalHelper(Type type) : base(type) { this.StableName = DataContract.GetStableName(type, out _hasDataContract); @@ -120,7 +110,7 @@ internal EnumDataContractCriticalHelper(Type type) : base(type) _childElementNames = new XmlDictionaryString[Members.Count]; for (int i = 0; i < Members.Count; i++) _childElementNames[i] = dictionary.Add(Members[i].Name); - DataContractAttribute dataContractAttribute; + DataContractAttribute? dataContractAttribute; if (TryGetDCAttribute(type, out dataContractAttribute)) { if (dataContractAttribute.IsReference) @@ -140,7 +130,7 @@ internal List Members set { _members = value; } } - internal List Values + internal List? Values { get { return _values; } set { _values = value; } @@ -158,7 +148,7 @@ internal bool IsULong set { _isULong = value; } } - internal XmlDictionaryString[] ChildElementNames + internal XmlDictionaryString[]? ChildElementNames { get { return _childElementNames; } set { _childElementNames = value; } @@ -169,6 +159,7 @@ private void ImportBaseType(Type baseType) _isULong = (baseType == Globals.TypeOfULong); } + [MemberNotNull(nameof(_members))] private void ImportDataMembers() { Type type = this.UnderlyingType; @@ -187,7 +178,7 @@ private void ImportDataMembers() if (memberAttributes != null && memberAttributes.Length > 0) { if (memberAttributes.Length > 1) - ThrowInvalidDataContractException(SR.Format(SR.TooManyEnumMembers, DataContract.GetClrTypeFullName(field.DeclaringType), field.Name)); + ThrowInvalidDataContractException(SR.Format(SR.TooManyEnumMembers, DataContract.GetClrTypeFullName(field.DeclaringType!), field.Name)); EnumMemberAttribute memberAttribute = (EnumMemberAttribute)memberAttributes[0]; DataMember memberContract = new DataMember(field); @@ -205,7 +196,7 @@ private void ImportDataMembers() object[] dataMemberAttributes = field.GetCustomAttributes(Globals.TypeOfDataMemberAttribute, false).ToArray(); if (dataMemberAttributes != null && dataMemberAttributes.Length > 0) - ThrowInvalidDataContractException(SR.Format(SR.DataMemberOnEnumField, DataContract.GetClrTypeFullName(field.DeclaringType), field.Name)); + ThrowInvalidDataContractException(SR.Format(SR.DataMemberOnEnumField, DataContract.GetClrTypeFullName(field.DeclaringType!), field.Name)); } else { @@ -220,7 +211,7 @@ private void ImportDataMembers() if (enumMemberValid) { - object enumValue = field.GetValue(null); + object? enumValue = field.GetValue(null); if (_isULong) tempValues.Add((long)Convert.ToUInt64(enumValue, null)); else @@ -237,11 +228,11 @@ private void ImportDataMembers() internal void WriteEnumValue(XmlWriterDelegator writer, object value) { long longValue = IsULong ? (long)Convert.ToUInt64(value, null) : Convert.ToInt64(value, null); - for (int i = 0; i < Values.Count; i++) + for (int i = 0; i < Values!.Count; i++) { if (longValue == Values[i]) { - writer.WriteString(ChildElementNames[i].Value); + writer.WriteString(ChildElementNames![i].Value); return; } } @@ -266,7 +257,7 @@ internal void WriteEnumValue(XmlWriterDelegator writer, object value) else writer.WriteString(DictionaryGlobals.Space.Value); - writer.WriteString(ChildElementNames[i].Value); + writer.WriteString(ChildElementNames![i].Value); longValue &= ~current; } } @@ -275,7 +266,7 @@ internal void WriteEnumValue(XmlWriterDelegator writer, object value) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.InvalidEnumValueOnWrite, value, DataContract.GetClrTypeFullName(UnderlyingType)))); if (noneWritten && zeroIndex >= 0) - writer.WriteString(ChildElementNames[zeroIndex].Value); + writer.WriteString(ChildElementNames![zeroIndex].Value); } else throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.InvalidEnumValueOnWrite, value, DataContract.GetClrTypeFullName(UnderlyingType)))); @@ -334,7 +325,7 @@ private long ReadEnumValue(string value, int index, int count) string memberName = Members[i].Name; if (memberName.Length == count && string.CompareOrdinal(value, index, memberName, 0, count) == 0) { - return Values[i]; + return Values![i]; } } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.InvalidEnumValueOnRead, value.Substring(index, count), DataContract.GetClrTypeFullName(UnderlyingType)))); @@ -364,12 +355,12 @@ internal long GetEnumValueFromString(string value) } } - public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) + public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext? context) { WriteEnumValue(xmlWriter, obj); } - public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context) + public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext? context) { object obj = ReadEnumValue(xmlReader); if (context != null) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExportOptions.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExportOptions.cs index dfe3813d72314d..c1c60b53ae75a5 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExportOptions.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExportOptions.cs @@ -7,17 +7,17 @@ namespace System.Runtime.Serialization { public class ExportOptions { - private Collection _knownTypes; + private Collection? _knownTypes; #if SUPPORT_SURROGATE - private IDataContractSurrogate _dataContractSurrogate; + private IDataContractSurrogate? _dataContractSurrogate; - public IDataContractSurrogate DataContractSurrogate + public IDataContractSurrogate? DataContractSurrogate { get { return _dataContractSurrogate; } set { _dataContractSurrogate = value; } } - internal IDataContractSurrogate GetSurrogate() + internal IDataContractSurrogate? GetSurrogate() { return _dataContractSurrogate; } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExtensionDataObject.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExtensionDataObject.cs index 4dc77fb341d17e..1ba1ff2d1b21d7 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExtensionDataObject.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExtensionDataObject.cs @@ -10,7 +10,7 @@ namespace System.Runtime.Serialization { public sealed class ExtensionDataObject { - private IList _members; + private IList? _members; #if USE_REFEMIT public ExtensionDataObject() @@ -21,9 +21,9 @@ internal ExtensionDataObject() } #if USE_REFEMIT - public IList Members + public IList? Members #else - internal IList Members + internal IList? Members #endif { get { return _members; } @@ -37,23 +37,20 @@ public class ExtensionDataMember internal class ExtensionDataMember #endif { - private string _name; - private string _ns; - private IDataNode _value; + private IDataNode? _value; private int _memberIndex; - public string Name - { - get { return _name; } - set { _name = value; } - } - public string Namespace + public ExtensionDataMember(string name, string ns) { - get { return _ns; } - set { _ns = value; } + Name = name; + Namespace = ns; } - public IDataNode Value + public string Name { get; } + + public string? Namespace { get; } + + public IDataNode? Value { get { return _value; } set { _value = value; } @@ -73,11 +70,11 @@ internal interface IDataNode #endif { Type DataType { get; } - object Value { get; set; } // boxes for primitives - string DataContractName { get; set; } - string DataContractNamespace { get; set; } - string ClrTypeName { get; set; } - string ClrAssemblyName { get; set; } + object? Value { get; set; } // boxes for primitives + string? DataContractName { get; set; } + string? DataContractNamespace { get; set; } + string? ClrTypeName { get; set; } + string? ClrAssemblyName { get; set; } string Id { get; set; } bool PreservesReferences { get; } @@ -90,11 +87,11 @@ internal interface IDataNode internal class DataNode : IDataNode { protected Type dataType; - private T _value; - private string _dataContractName; - private string _dataContractNamespace; - private string _clrTypeName; - private string _clrAssemblyName; + private T _value = default!; + private string? _dataContractName; + private string? _dataContractNamespace; + private string? _clrTypeName; + private string? _clrAssemblyName; private string _id = Globals.NewObjectId; private bool _isFinalValue; @@ -115,10 +112,10 @@ public Type DataType get { return dataType; } } - public object Value + public object? Value { get { return _value; } - set { _value = (T)value; } + set { _value = (T)value!; } } bool IDataNode.IsFinalValue @@ -139,25 +136,25 @@ public void SetValue(T value) } #endif - public string DataContractName + public string? DataContractName { get { return _dataContractName; } set { _dataContractName = value; } } - public string DataContractNamespace + public string? DataContractNamespace { get { return _dataContractNamespace; } set { _dataContractNamespace = value; } } - public string ClrTypeName + public string? ClrTypeName { get { return _clrTypeName; } set { _clrTypeName = value; } } - public string ClrAssemblyName + public string? ClrAssemblyName { get { return _clrAssemblyName; } set { _clrAssemblyName = value; } @@ -194,7 +191,7 @@ public virtual void Clear() _clrTypeName = _clrAssemblyName = null; } - internal void AddQualifiedNameAttribute(ElementData element, string elementPrefix, string elementName, string elementNs, string valueName, string valueNs) + internal void AddQualifiedNameAttribute(ElementData element, string elementPrefix, string elementName, string elementNs, string valueName, string? valueNs) { string prefix = ExtensionDataReader.GetPrefix(valueNs); element.AddAttribute(elementPrefix, elementNs, elementName, prefix + ":" + valueName); @@ -219,14 +216,14 @@ internal void AddQualifiedNameAttribute(ElementData element, string elementPrefi internal class ClassDataNode : DataNode { - private IList _members; + private IList? _members; internal ClassDataNode() { dataType = Globals.TypeOfClassDataNode; } - internal IList Members + internal IList? Members { get { return _members; } set { _members = value; } @@ -241,28 +238,28 @@ public override void Clear() internal class XmlDataNode : DataNode { - private IList _xmlAttributes; - private IList _xmlChildNodes; - private XmlDocument _ownerDocument; + private IList? _xmlAttributes; + private IList? _xmlChildNodes; + private XmlDocument? _ownerDocument; internal XmlDataNode() { dataType = Globals.TypeOfXmlDataNode; } - internal IList XmlAttributes + internal IList? XmlAttributes { get { return _xmlAttributes; } set { _xmlAttributes = value; } } - internal IList XmlChildNodes + internal IList? XmlChildNodes { get { return _xmlChildNodes; } set { _xmlChildNodes = value; } } - internal XmlDocument OwnerDocument + internal XmlDocument? OwnerDocument { get { return _ownerDocument; } set { _ownerDocument = value; } @@ -279,9 +276,9 @@ public override void Clear() internal class CollectionDataNode : DataNode { - private IList _items; - private string _itemName; - private string _itemNamespace; + private IList? _items; + private string? _itemName; + private string? _itemNamespace; private int _size = -1; internal CollectionDataNode() @@ -289,19 +286,19 @@ internal CollectionDataNode() dataType = Globals.TypeOfCollectionDataNode; } - internal IList Items + internal IList? Items { get { return _items; } set { _items = value; } } - internal string ItemName + internal string? ItemName { get { return _itemName; } set { _itemName = value; } } - internal string ItemNamespace + internal string? ItemNamespace { get { return _itemNamespace; } set { _itemNamespace = value; } @@ -330,28 +327,28 @@ public override void Clear() internal class ISerializableDataNode : DataNode { - private string _factoryTypeName; - private string _factoryTypeNamespace; - private IList _members; + private string? _factoryTypeName; + private string? _factoryTypeNamespace; + private IList? _members; internal ISerializableDataNode() { dataType = Globals.TypeOfISerializableDataNode; } - internal string FactoryTypeName + internal string? FactoryTypeName { get { return _factoryTypeName; } set { _factoryTypeName = value; } } - internal string FactoryTypeNamespace + internal string? FactoryTypeNamespace { get { return _factoryTypeNamespace; } set { _factoryTypeNamespace = value; } } - internal IList Members + internal IList? Members { get { return _members; } set { _members = value; } @@ -375,16 +372,16 @@ public override void Clear() internal class ISerializableDataMember { - private string _name; - private IDataNode _value; + private IDataNode? _value; - internal string Name + public ISerializableDataMember(string name) { - get { return _name; } - set { _name = value; } + Name = name; } - internal IDataNode Value + internal string Name { get; } + + internal IDataNode? Value { get { return _value; } set { _value = value; } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExtensionDataReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExtensionDataReader.cs index 1ecfbb8d7eb058..4f31147f5440ef 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExtensionDataReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ExtensionDataReader.cs @@ -3,6 +3,7 @@ using System.Xml; using System.Collections; +using System.Diagnostics.CodeAnalysis; namespace System.Runtime.Serialization { @@ -21,25 +22,25 @@ private enum ExtensionDataNodeType NullElement, } - private ElementData[] _elements; - private ElementData _element; - private ElementData _nextElement; + private ElementData?[]? _elements; + private ElementData? _element; + private ElementData? _nextElement; private ReadState _readState = ReadState.Initial; private readonly ExtensionDataNodeType _internalNodeType; private XmlNodeType _nodeType; private int _depth; - private string _localName; - private string _ns; - private string _prefix; - private string _value; + private string? _localName; + private string? _ns; + private string? _prefix; + private string? _value; private int _attributeCount; private int _attributeIndex; private static readonly object s_prefixLock = new object(); #pragma warning disable 0649 - private readonly XmlNodeReader _xmlNodeReader; + private readonly XmlNodeReader? _xmlNodeReader; #pragma warning restore 0649 private readonly XmlObjectSerializerReadContext _context; @@ -61,9 +62,9 @@ internal ExtensionDataReader(XmlObjectSerializerReadContext context) _context = context; } - internal IDataNode GetCurrentNode() + internal IDataNode? GetCurrentNode() { - IDataNode retVal = _element.dataNode; + IDataNode? retVal = _element!.dataNode; Skip(); return retVal; } @@ -82,13 +83,17 @@ internal void Reset() _elements = null; } +#pragma warning disable CS8775 // Member must have a non-null value when exiting in some condition. + [MemberNotNullWhen(true, nameof(_xmlNodeReader))] + [MemberNotNullWhen(false, nameof(_element))] private bool IsXmlDataNode { get { return (_internalNodeType == ExtensionDataNodeType.Xml); } } +#pragma warning restore CS8775 // Member must have a non-null value when exiting in some condition. public override XmlNodeType NodeType { get { return IsXmlDataNode ? _xmlNodeReader.NodeType : _nodeType; } } - public override string LocalName { get { return IsXmlDataNode ? _xmlNodeReader.LocalName : _localName; } } - public override string NamespaceURI { get { return IsXmlDataNode ? _xmlNodeReader.NamespaceURI : _ns; } } - public override string Prefix { get { return IsXmlDataNode ? _xmlNodeReader.Prefix : _prefix; } } - public override string Value { get { return IsXmlDataNode ? _xmlNodeReader.Value : _value; } } + public override string LocalName { get { return IsXmlDataNode ? _xmlNodeReader.LocalName : _localName!; } } + public override string NamespaceURI { get { return IsXmlDataNode ? _xmlNodeReader.NamespaceURI : _ns!; } } + public override string Prefix { get { return IsXmlDataNode ? _xmlNodeReader.Prefix : _prefix!; } } + public override string Value { get { return IsXmlDataNode ? _xmlNodeReader.Value : _value!; } } public override int Depth { get { return IsXmlDataNode ? _xmlNodeReader.Depth : _depth; } } public override int AttributeCount { get { return IsXmlDataNode ? _xmlNodeReader.AttributeCount : _attributeCount; } } public override bool EOF { get { return IsXmlDataNode ? _xmlNodeReader.EOF : (_readState == ReadState.EndOfFile); } } @@ -99,8 +104,9 @@ internal void Reset() public override XmlSpace XmlSpace { get { return IsXmlDataNode ? _xmlNodeReader.XmlSpace : base.XmlSpace; } } public override string XmlLang { get { return IsXmlDataNode ? _xmlNodeReader.XmlLang : base.XmlLang; } } public override string this[int i] { get { return IsXmlDataNode ? _xmlNodeReader[i] : GetAttribute(i); } } - public override string this[string name] { get { return IsXmlDataNode ? _xmlNodeReader[name] : GetAttribute(name); } } - public override string this[string name, string namespaceURI] { get { return IsXmlDataNode ? _xmlNodeReader[name, namespaceURI] : GetAttribute(name, namespaceURI); } } + public override string? this[string name] { get { return IsXmlDataNode ? _xmlNodeReader[name] : GetAttribute(name); } } + // TODO-NULLABLE - unnecessary namespaceURI! - https://github.com/dotnet/roslyn/issues/47221 + public override string? this[string name, string? namespaceURI] { get { return IsXmlDataNode ? _xmlNodeReader[name, namespaceURI!] : GetAttribute(name, namespaceURI); } } public override bool MoveToFirstAttribute() { @@ -134,7 +140,7 @@ public override void MoveToAttribute(int index) throw new XmlException(SR.InvalidXmlDeserializingExtensionData); _nodeType = XmlNodeType.Attribute; - AttributeData attribute = _element.attributes[index]; + AttributeData attribute = _element.attributes![index]; _localName = attribute.localName; _ns = attribute.ns; _prefix = attribute.prefix; @@ -143,14 +149,14 @@ public override void MoveToAttribute(int index) } } - public override string GetAttribute(string name, string namespaceURI) + public override string? GetAttribute(string name, string? namespaceURI) { if (IsXmlDataNode) return _xmlNodeReader.GetAttribute(name, namespaceURI); for (int i = 0; i < _element.attributeCount; i++) { - AttributeData attribute = _element.attributes[i]; + AttributeData attribute = _element.attributes![i]; if (attribute.localName == name && attribute.ns == namespaceURI) return attribute.value; } @@ -158,14 +164,14 @@ public override string GetAttribute(string name, string namespaceURI) return null; } - public override bool MoveToAttribute(string name, string namespaceURI) + public override bool MoveToAttribute(string name, string? namespaceURI) { if (IsXmlDataNode) return _xmlNodeReader.MoveToAttribute(name, _ns); for (int i = 0; i < _element.attributeCount; i++) { - AttributeData attribute = _element.attributes[i]; + AttributeData attribute = _element.attributes![i]; if (attribute.localName == name && attribute.ns == namespaceURI) { MoveToAttribute(i); @@ -191,7 +197,7 @@ public override bool MoveToElement() private void SetElement() { _nodeType = XmlNodeType.Element; - _localName = _element.localName; + _localName = _element!.localName; _ns = _element.ns; _prefix = _element.prefix; _value = string.Empty; @@ -199,12 +205,12 @@ private void SetElement() _attributeIndex = -1; } - public override string LookupNamespace(string prefix) + public override string? LookupNamespace(string prefix) { if (IsXmlDataNode) return _xmlNodeReader.LookupNamespace(prefix); - return (string)s_prefixToNsTable[prefix]; + return (string?)s_prefixToNsTable[prefix]; } public override void Skip() @@ -263,7 +269,7 @@ public override bool Read() if (_nodeType == XmlNodeType.Attribute && MoveToNextAttribute()) return true; - MoveNext(_element.dataNode); + MoveNext(_element!.dataNode); switch (_internalNodeType) { @@ -370,7 +376,7 @@ public override XmlNameTable NameTable } } - public override string GetAttribute(string name) + public override string? GetAttribute(string name) { if (IsXmlDataNode) { @@ -422,7 +428,7 @@ public override bool ReadAttributeValue() return false; } - private void MoveNext(IDataNode dataNode) + private void MoveNext(IDataNode? dataNode) { throw NotImplemented.ByDesign; } @@ -442,7 +448,7 @@ private void PushElement() private void PopElement() { - _prefix = _element.prefix; + _prefix = _element!.prefix; _localName = _element.localName; _ns = _element.ns; @@ -457,6 +463,7 @@ private void PopElement() } } + [MemberNotNull(nameof(_elements))] private void GrowElementsIfNeeded() { if (_elements == null) @@ -469,25 +476,25 @@ private void GrowElementsIfNeeded() } } - private ElementData GetNextElement() + private ElementData? GetNextElement() { int nextDepth = _depth + 1; return (_elements == null || _elements.Length <= nextDepth || _elements[nextDepth] == null) ? new ElementData() : _elements[nextDepth]; } - internal static string GetPrefix(string ns) + internal static string GetPrefix(string? ns) { ns = ns ?? string.Empty; - string prefix = (string)s_nsToPrefixTable[ns]; + string? prefix = (string?)s_nsToPrefixTable[ns]; if (prefix == null) { lock (s_prefixLock) { - prefix = (string)s_nsToPrefixTable[ns]; + prefix = (string?)s_nsToPrefixTable[ns]; if (prefix == null) { - prefix = (ns == null || ns.Length == 0) ? string.Empty : "p" + s_nsToPrefixTable.Count; + prefix = (ns.Length == 0) ? string.Empty : "p" + s_nsToPrefixTable.Count; AddPrefix(prefix, ns); } } @@ -508,10 +515,10 @@ public class AttributeData internal class AttributeData #endif { - public string prefix; - public string ns; - public string localName; - public string value; + public string? prefix; + public string? ns; + public string? localName; + public string? value; } #if USE_REFEMIT @@ -520,15 +527,15 @@ public class ElementData internal class ElementData #endif { - public string localName; - public string ns; - public string prefix; + public string? localName; + public string? ns; + public string? prefix; public int attributeCount; - public AttributeData[] attributes; - public IDataNode dataNode; + public AttributeData[]? attributes; + public IDataNode? dataNode; public int childElementIndex; - public void AddAttribute(string prefix, string ns, string name, string value) + public void AddAttribute(string prefix, string ns, string name, string? value) { GrowAttributesIfNeeded(); AttributeData attribute = attributes[attributeCount]; @@ -541,6 +548,7 @@ public void AddAttribute(string prefix, string ns, string name, string value) attributeCount++; } + [MemberNotNull(nameof(attributes))] private void GrowAttributesIfNeeded() { if (attributes == null) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/GenericParameterDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/GenericParameterDataContract.cs index 39881a5069871b..d1f0ec55771cda 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/GenericParameterDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/GenericParameterDataContract.cs @@ -13,7 +13,7 @@ internal sealed class GenericParameterDataContract : DataContract internal GenericParameterDataContract(Type type) : base(new GenericParameterDataContractCriticalHelper(type)) { - _helper = base.Helper as GenericParameterDataContractCriticalHelper; + _helper = (base.Helper as GenericParameterDataContractCriticalHelper)!; } internal int ParameterPosition diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Globals.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Globals.cs index 06fc98f0caa406..52b08bf3d5d187 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Globals.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Globals.cs @@ -22,7 +22,7 @@ internal static class Globals /// internal const BindingFlags ScanAllMembers = BindingFlags.Static | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public; - private static XmlQualifiedName s_idQualifiedName; + private static XmlQualifiedName? s_idQualifiedName; internal static XmlQualifiedName IdQualifiedName { get @@ -33,7 +33,7 @@ internal static XmlQualifiedName IdQualifiedName } } - private static XmlQualifiedName s_refQualifiedName; + private static XmlQualifiedName? s_refQualifiedName; internal static XmlQualifiedName RefQualifiedName { get @@ -44,7 +44,7 @@ internal static XmlQualifiedName RefQualifiedName } } - private static Type s_typeOfObject; + private static Type? s_typeOfObject; internal static Type TypeOfObject { get @@ -55,7 +55,7 @@ internal static Type TypeOfObject } } - private static Type s_typeOfValueType; + private static Type? s_typeOfValueType; internal static Type TypeOfValueType { get @@ -66,7 +66,7 @@ internal static Type TypeOfValueType } } - private static Type s_typeOfArray; + private static Type? s_typeOfArray; internal static Type TypeOfArray { get @@ -77,7 +77,7 @@ internal static Type TypeOfArray } } - private static Type s_typeOfString; + private static Type? s_typeOfString; internal static Type TypeOfString { get @@ -88,7 +88,7 @@ internal static Type TypeOfString } } - private static Type s_typeOfInt; + private static Type? s_typeOfInt; internal static Type TypeOfInt { get @@ -99,7 +99,7 @@ internal static Type TypeOfInt } } - private static Type s_typeOfULong; + private static Type? s_typeOfULong; internal static Type TypeOfULong { get @@ -110,7 +110,7 @@ internal static Type TypeOfULong } } - private static Type s_typeOfVoid; + private static Type? s_typeOfVoid; internal static Type TypeOfVoid { get @@ -121,7 +121,7 @@ internal static Type TypeOfVoid } } - private static Type s_typeOfByteArray; + private static Type? s_typeOfByteArray; internal static Type TypeOfByteArray { get @@ -132,7 +132,7 @@ internal static Type TypeOfByteArray } } - private static Type s_typeOfTimeSpan; + private static Type? s_typeOfTimeSpan; internal static Type TypeOfTimeSpan { get @@ -143,7 +143,7 @@ internal static Type TypeOfTimeSpan } } - private static Type s_typeOfGuid; + private static Type? s_typeOfGuid; internal static Type TypeOfGuid { get @@ -154,7 +154,7 @@ internal static Type TypeOfGuid } } - private static Type s_typeOfDateTimeOffset; + private static Type? s_typeOfDateTimeOffset; internal static Type TypeOfDateTimeOffset { get @@ -165,7 +165,7 @@ internal static Type TypeOfDateTimeOffset } } - private static Type s_typeOfDateTimeOffsetAdapter; + private static Type? s_typeOfDateTimeOffsetAdapter; internal static Type TypeOfDateTimeOffsetAdapter { get @@ -176,7 +176,7 @@ internal static Type TypeOfDateTimeOffsetAdapter } } - private static Type s_typeOfUri; + private static Type? s_typeOfUri; internal static Type TypeOfUri { get @@ -187,7 +187,7 @@ internal static Type TypeOfUri } } - private static Type s_typeOfTypeEnumerable; + private static Type? s_typeOfTypeEnumerable; internal static Type TypeOfTypeEnumerable { get @@ -198,7 +198,7 @@ internal static Type TypeOfTypeEnumerable } } - private static Type s_typeOfStreamingContext; + private static Type? s_typeOfStreamingContext; internal static Type TypeOfStreamingContext { get @@ -209,7 +209,7 @@ internal static Type TypeOfStreamingContext } } - private static Type s_typeOfISerializable; + private static Type? s_typeOfISerializable; internal static Type TypeOfISerializable { get @@ -220,7 +220,7 @@ internal static Type TypeOfISerializable } } - private static Type s_typeOfIDeserializationCallback; + private static Type? s_typeOfIDeserializationCallback; internal static Type TypeOfIDeserializationCallback { get @@ -231,7 +231,7 @@ internal static Type TypeOfIDeserializationCallback } } - private static Type s_typeOfIObjectReference; + private static Type? s_typeOfIObjectReference; internal static Type TypeOfIObjectReference { get @@ -242,7 +242,7 @@ internal static Type TypeOfIObjectReference } } - private static Type s_typeOfXmlFormatClassWriterDelegate; + private static Type? s_typeOfXmlFormatClassWriterDelegate; internal static Type TypeOfXmlFormatClassWriterDelegate { get @@ -253,7 +253,7 @@ internal static Type TypeOfXmlFormatClassWriterDelegate } } - private static Type s_typeOfXmlFormatCollectionWriterDelegate; + private static Type? s_typeOfXmlFormatCollectionWriterDelegate; internal static Type TypeOfXmlFormatCollectionWriterDelegate { get @@ -264,7 +264,7 @@ internal static Type TypeOfXmlFormatCollectionWriterDelegate } } - private static Type s_typeOfXmlFormatClassReaderDelegate; + private static Type? s_typeOfXmlFormatClassReaderDelegate; internal static Type TypeOfXmlFormatClassReaderDelegate { get @@ -275,7 +275,7 @@ internal static Type TypeOfXmlFormatClassReaderDelegate } } - private static Type s_typeOfXmlFormatCollectionReaderDelegate; + private static Type? s_typeOfXmlFormatCollectionReaderDelegate; internal static Type TypeOfXmlFormatCollectionReaderDelegate { get @@ -286,7 +286,7 @@ internal static Type TypeOfXmlFormatCollectionReaderDelegate } } - private static Type s_typeOfXmlFormatGetOnlyCollectionReaderDelegate; + private static Type? s_typeOfXmlFormatGetOnlyCollectionReaderDelegate; internal static Type TypeOfXmlFormatGetOnlyCollectionReaderDelegate { get @@ -297,7 +297,7 @@ internal static Type TypeOfXmlFormatGetOnlyCollectionReaderDelegate } } - private static Type s_typeOfKnownTypeAttribute; + private static Type? s_typeOfKnownTypeAttribute; internal static Type TypeOfKnownTypeAttribute { get @@ -308,7 +308,7 @@ internal static Type TypeOfKnownTypeAttribute } } - private static Type s_typeOfDataContractAttribute; + private static Type? s_typeOfDataContractAttribute; internal static Type TypeOfDataContractAttribute { get @@ -319,7 +319,7 @@ internal static Type TypeOfDataContractAttribute } } - private static Type s_typeOfDataMemberAttribute; + private static Type? s_typeOfDataMemberAttribute; internal static Type TypeOfDataMemberAttribute { get @@ -330,7 +330,7 @@ internal static Type TypeOfDataMemberAttribute } } - private static Type s_typeOfEnumMemberAttribute; + private static Type? s_typeOfEnumMemberAttribute; internal static Type TypeOfEnumMemberAttribute { get @@ -341,7 +341,7 @@ internal static Type TypeOfEnumMemberAttribute } } - private static Type s_typeOfCollectionDataContractAttribute; + private static Type? s_typeOfCollectionDataContractAttribute; internal static Type TypeOfCollectionDataContractAttribute { get @@ -352,7 +352,7 @@ internal static Type TypeOfCollectionDataContractAttribute } } - private static Type s_typeOfOptionalFieldAttribute; + private static Type? s_typeOfOptionalFieldAttribute; internal static Type TypeOfOptionalFieldAttribute { get @@ -366,7 +366,7 @@ internal static Type TypeOfOptionalFieldAttribute } } - private static Type s_typeOfObjectArray; + private static Type? s_typeOfObjectArray; internal static Type TypeOfObjectArray { get @@ -377,7 +377,7 @@ internal static Type TypeOfObjectArray } } - private static Type s_typeOfOnSerializingAttribute; + private static Type? s_typeOfOnSerializingAttribute; internal static Type TypeOfOnSerializingAttribute { get @@ -388,7 +388,7 @@ internal static Type TypeOfOnSerializingAttribute } } - private static Type s_typeOfOnSerializedAttribute; + private static Type? s_typeOfOnSerializedAttribute; internal static Type TypeOfOnSerializedAttribute { get @@ -399,7 +399,7 @@ internal static Type TypeOfOnSerializedAttribute } } - private static Type s_typeOfOnDeserializingAttribute; + private static Type? s_typeOfOnDeserializingAttribute; internal static Type TypeOfOnDeserializingAttribute { get @@ -410,7 +410,7 @@ internal static Type TypeOfOnDeserializingAttribute } } - private static Type s_typeOfOnDeserializedAttribute; + private static Type? s_typeOfOnDeserializedAttribute; internal static Type TypeOfOnDeserializedAttribute { get @@ -421,7 +421,7 @@ internal static Type TypeOfOnDeserializedAttribute } } - private static Type s_typeOfFlagsAttribute; + private static Type? s_typeOfFlagsAttribute; internal static Type TypeOfFlagsAttribute { get @@ -432,7 +432,7 @@ internal static Type TypeOfFlagsAttribute } } - private static Type s_typeOfIXmlSerializable; + private static Type? s_typeOfIXmlSerializable; internal static Type TypeOfIXmlSerializable { get @@ -443,7 +443,7 @@ internal static Type TypeOfIXmlSerializable } } - private static Type s_typeOfXmlSchemaProviderAttribute; + private static Type? s_typeOfXmlSchemaProviderAttribute; internal static Type TypeOfXmlSchemaProviderAttribute { get @@ -454,7 +454,7 @@ internal static Type TypeOfXmlSchemaProviderAttribute } } - private static Type s_typeOfXmlRootAttribute; + private static Type? s_typeOfXmlRootAttribute; internal static Type TypeOfXmlRootAttribute { get @@ -465,7 +465,7 @@ internal static Type TypeOfXmlRootAttribute } } - private static Type s_typeOfXmlQualifiedName; + private static Type? s_typeOfXmlQualifiedName; internal static Type TypeOfXmlQualifiedName { get @@ -476,7 +476,7 @@ internal static Type TypeOfXmlQualifiedName } } - private static Type s_typeOfXmlSchemaType; + private static Type? s_typeOfXmlSchemaType; internal static Type TypeOfXmlSchemaType { get @@ -490,13 +490,13 @@ internal static Type TypeOfXmlSchemaType } } - private static Type s_typeOfIExtensibleDataObject; + private static Type? s_typeOfIExtensibleDataObject; internal static Type TypeOfIExtensibleDataObject => s_typeOfIExtensibleDataObject ?? (s_typeOfIExtensibleDataObject = typeof(IExtensibleDataObject)); - private static Type s_typeOfExtensionDataObject; + private static Type? s_typeOfExtensionDataObject; internal static Type TypeOfExtensionDataObject => s_typeOfExtensionDataObject ?? (s_typeOfExtensionDataObject = typeof(ExtensionDataObject)); - private static Type s_typeOfISerializableDataNode; + private static Type? s_typeOfISerializableDataNode; internal static Type TypeOfISerializableDataNode { get @@ -507,7 +507,7 @@ internal static Type TypeOfISerializableDataNode } } - private static Type s_typeOfClassDataNode; + private static Type? s_typeOfClassDataNode; internal static Type TypeOfClassDataNode { get @@ -518,7 +518,7 @@ internal static Type TypeOfClassDataNode } } - private static Type s_typeOfCollectionDataNode; + private static Type? s_typeOfCollectionDataNode; internal static Type TypeOfCollectionDataNode { get @@ -529,10 +529,10 @@ internal static Type TypeOfCollectionDataNode } } - private static Type s_typeOfXmlDataNode; + private static Type? s_typeOfXmlDataNode; internal static Type TypeOfXmlDataNode => s_typeOfXmlDataNode ?? (s_typeOfXmlDataNode = typeof(XmlDataNode)); - private static Type s_typeOfNullable; + private static Type? s_typeOfNullable; internal static Type TypeOfNullable { get @@ -543,7 +543,7 @@ internal static Type TypeOfNullable } } - private static Type s_typeOfIDictionaryGeneric; + private static Type? s_typeOfIDictionaryGeneric; internal static Type TypeOfIDictionaryGeneric { get @@ -554,7 +554,7 @@ internal static Type TypeOfIDictionaryGeneric } } - private static Type s_typeOfIDictionary; + private static Type? s_typeOfIDictionary; internal static Type TypeOfIDictionary { get @@ -565,7 +565,7 @@ internal static Type TypeOfIDictionary } } - private static Type s_typeOfIListGeneric; + private static Type? s_typeOfIListGeneric; internal static Type TypeOfIListGeneric { get @@ -576,7 +576,7 @@ internal static Type TypeOfIListGeneric } } - private static Type s_typeOfIList; + private static Type? s_typeOfIList; internal static Type TypeOfIList { get @@ -587,7 +587,7 @@ internal static Type TypeOfIList } } - private static Type s_typeOfICollectionGeneric; + private static Type? s_typeOfICollectionGeneric; internal static Type TypeOfICollectionGeneric { get @@ -598,7 +598,7 @@ internal static Type TypeOfICollectionGeneric } } - private static Type s_typeOfICollection; + private static Type? s_typeOfICollection; internal static Type TypeOfICollection { get @@ -609,7 +609,7 @@ internal static Type TypeOfICollection } } - private static Type s_typeOfIEnumerableGeneric; + private static Type? s_typeOfIEnumerableGeneric; internal static Type TypeOfIEnumerableGeneric { get @@ -620,7 +620,7 @@ internal static Type TypeOfIEnumerableGeneric } } - private static Type s_typeOfIEnumerable; + private static Type? s_typeOfIEnumerable; internal static Type TypeOfIEnumerable { get @@ -631,7 +631,7 @@ internal static Type TypeOfIEnumerable } } - private static Type s_typeOfIEnumeratorGeneric; + private static Type? s_typeOfIEnumeratorGeneric; internal static Type TypeOfIEnumeratorGeneric { get @@ -642,7 +642,7 @@ internal static Type TypeOfIEnumeratorGeneric } } - private static Type s_typeOfIEnumerator; + private static Type? s_typeOfIEnumerator; internal static Type TypeOfIEnumerator { get @@ -653,7 +653,7 @@ internal static Type TypeOfIEnumerator } } - private static Type s_typeOfKeyValuePair; + private static Type? s_typeOfKeyValuePair; internal static Type TypeOfKeyValuePair { get @@ -664,7 +664,7 @@ internal static Type TypeOfKeyValuePair } } - private static Type s_typeOfKeyValuePairAdapter; + private static Type? s_typeOfKeyValuePairAdapter; internal static Type TypeOfKeyValuePairAdapter { get @@ -675,7 +675,7 @@ internal static Type TypeOfKeyValuePairAdapter } } - private static Type s_typeOfKeyValue; + private static Type? s_typeOfKeyValue; internal static Type TypeOfKeyValue { get @@ -686,7 +686,7 @@ internal static Type TypeOfKeyValue } } - private static Type s_typeOfIDictionaryEnumerator; + private static Type? s_typeOfIDictionaryEnumerator; internal static Type TypeOfIDictionaryEnumerator { get @@ -697,7 +697,7 @@ internal static Type TypeOfIDictionaryEnumerator } } - private static Type s_typeOfDictionaryEnumerator; + private static Type? s_typeOfDictionaryEnumerator; internal static Type TypeOfDictionaryEnumerator { get @@ -708,7 +708,7 @@ internal static Type TypeOfDictionaryEnumerator } } - private static Type s_typeOfGenericDictionaryEnumerator; + private static Type? s_typeOfGenericDictionaryEnumerator; internal static Type TypeOfGenericDictionaryEnumerator { get @@ -719,7 +719,7 @@ internal static Type TypeOfGenericDictionaryEnumerator } } - private static Type s_typeOfDictionaryGeneric; + private static Type? s_typeOfDictionaryGeneric; internal static Type TypeOfDictionaryGeneric { get @@ -730,7 +730,7 @@ internal static Type TypeOfDictionaryGeneric } } - private static Type s_typeOfHashtable; + private static Type? s_typeOfHashtable; internal static Type TypeOfHashtable { get @@ -741,7 +741,7 @@ internal static Type TypeOfHashtable } } - private static Type s_typeOfXmlElement; + private static Type? s_typeOfXmlElement; internal static Type TypeOfXmlElement { get @@ -752,7 +752,7 @@ internal static Type TypeOfXmlElement } } - private static Type s_typeOfXmlNodeArray; + private static Type? s_typeOfXmlNodeArray; internal static Type TypeOfXmlNodeArray { get @@ -763,7 +763,7 @@ internal static Type TypeOfXmlNodeArray } } - private static Type s_typeOfDBNull; + private static Type? s_typeOfDBNull; internal static Type TypeOfDBNull { get @@ -774,7 +774,7 @@ internal static Type TypeOfDBNull } } - private static Uri s_dataContractXsdBaseNamespaceUri; + private static Uri? s_dataContractXsdBaseNamespaceUri; internal static Uri DataContractXsdBaseNamespaceUri { get @@ -799,7 +799,7 @@ private static bool TypeSequenceEqual(Type[] seq1, Type[] seq2) return true; } - private static MethodBase FilterMethodBases(MethodBase[] methodBases, Type[] parameterTypes, string methodName) + private static MethodBase? FilterMethodBases(MethodBase[]? methodBases, Type[] parameterTypes, string methodName) { if (methodBases == null || string.IsNullOrEmpty(methodName)) return null; @@ -809,23 +809,23 @@ private static MethodBase FilterMethodBases(MethodBase[] methodBases, Type[] par return matchedMethods.FirstOrDefault(); } - internal static ConstructorInfo GetConstructor(this Type type, BindingFlags bindingFlags, Type[] parameterTypes) + internal static ConstructorInfo? GetConstructor(this Type type, BindingFlags bindingFlags, Type[] parameterTypes) { - var constructorInfos = type.GetConstructors(bindingFlags); - var constructorInfo = FilterMethodBases(constructorInfos.Cast().ToArray(), parameterTypes, ".ctor"); + ConstructorInfo[] constructorInfos = type.GetConstructors(bindingFlags); + var constructorInfo = FilterMethodBases(constructorInfos.Cast().ToArray()!, parameterTypes, ".ctor"); return constructorInfo != null ? (ConstructorInfo)constructorInfo : null; } - internal static MethodInfo GetMethod(this Type type, string methodName, BindingFlags bindingFlags, Type[] parameterTypes) + internal static MethodInfo? GetMethod(this Type type, string methodName, BindingFlags bindingFlags, Type[] parameterTypes) { var methodInfos = type.GetMethods(bindingFlags); - var methodInfo = FilterMethodBases(methodInfos.Cast().ToArray(), parameterTypes, methodName); + var methodInfo = FilterMethodBases(methodInfos.Cast().ToArray()!, parameterTypes, methodName); return methodInfo != null ? (MethodInfo)methodInfo : null; } #endregion - private static readonly Type s_typeOfScriptObject; + private static readonly Type? s_typeOfScriptObject; internal static ClassDataContract CreateScriptObjectClassDataContract() { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/HybridObjectCache.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/HybridObjectCache.cs index 7f07fb22d80ca8..035f1556b67a8b 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/HybridObjectCache.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/HybridObjectCache.cs @@ -10,19 +10,19 @@ namespace System.Runtime.Serialization { internal class HybridObjectCache { - private Dictionary _objectDictionary; - private Dictionary _referencedObjectDictionary; + private Dictionary? _objectDictionary; + private Dictionary? _referencedObjectDictionary; internal HybridObjectCache() { } - internal void Add(string id, object obj) + internal void Add(string id, object? obj) { if (_objectDictionary == null) - _objectDictionary = new Dictionary(); + _objectDictionary = new Dictionary(); - object existingObject; + object? existingObject; if (_objectDictionary.TryGetValue(id, out existingObject)) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.MultipleIdDefinition, id))); _objectDictionary.Add(id, obj); @@ -34,11 +34,11 @@ internal void Remove(string id) _objectDictionary.Remove(id); } - internal object GetObject(string id) + internal object? GetObject(string id) { if (_referencedObjectDictionary == null) { - _referencedObjectDictionary = new Dictionary(); + _referencedObjectDictionary = new Dictionary(); _referencedObjectDictionary.Add(id, null); } else @@ -48,7 +48,7 @@ internal object GetObject(string id) if (_objectDictionary != null) { - object obj; + object? obj; _objectDictionary.TryGetValue(id, out obj); return obj; } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/IExtensibleDataObject.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/IExtensibleDataObject.cs index 701e4ec4813ca6..4cfbc8f114bf0b 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/IExtensibleDataObject.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/IExtensibleDataObject.cs @@ -5,6 +5,6 @@ namespace System.Runtime.Serialization { public interface IExtensibleDataObject { - ExtensionDataObject ExtensionData { get; set; } + ExtensionDataObject? ExtensionData { get; set; } } } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/DataContractJsonSerializer.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/DataContractJsonSerializer.cs index 05cc2a26487d2e..604040e59e8db2 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/DataContractJsonSerializer.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/DataContractJsonSerializer.cs @@ -16,6 +16,7 @@ namespace System.Runtime.Serialization.Json using System.Globalization; using System.Reflection; using System.Security; + using System.Diagnostics.CodeAnalysis; public sealed class DataContractJsonSerializer : XmlObjectSerializer { @@ -27,13 +28,13 @@ public sealed class DataContractJsonSerializer : XmlObjectSerializer private const char WHITESPACE = ' '; - internal IList knownTypeList; - internal DataContractDictionary knownDataContracts; + internal IList? knownTypeList; + internal DataContractDictionary? knownDataContracts; private readonly EmitTypeInformation _emitTypeInformation; - private ReadOnlyCollection _knownTypeCollection; + private ReadOnlyCollection? _knownTypeCollection; private readonly int _maxItemsInObjectGraph; private readonly bool _serializeReadOnlyTypes; - private readonly DateTimeFormat _dateTimeFormat; + private readonly DateTimeFormat? _dateTimeFormat; private readonly bool _useSimpleDictionaryFormat; private readonly DataContractJsonSerializerImpl _serializer; @@ -44,32 +45,32 @@ public DataContractJsonSerializer(Type type) _serializer = new DataContractJsonSerializerImpl(type); } - public DataContractJsonSerializer(Type type, string rootName) + public DataContractJsonSerializer(Type type, string? rootName) : this(type, rootName, null) { } - public DataContractJsonSerializer(Type type, XmlDictionaryString rootName) + public DataContractJsonSerializer(Type type, XmlDictionaryString? rootName) : this(type, rootName, null) { } - public DataContractJsonSerializer(Type type, IEnumerable knownTypes) + public DataContractJsonSerializer(Type type, IEnumerable? knownTypes) { _serializer = new DataContractJsonSerializerImpl(type, knownTypes); } - public DataContractJsonSerializer(Type type, string rootName, IEnumerable knownTypes) + public DataContractJsonSerializer(Type type, string? rootName, IEnumerable? knownTypes) : this(type, new DataContractJsonSerializerSettings() { RootName = rootName, KnownTypes = knownTypes }) { } - public DataContractJsonSerializer(Type type, XmlDictionaryString rootName, IEnumerable knownTypes) + public DataContractJsonSerializer(Type type, XmlDictionaryString? rootName, IEnumerable? knownTypes) { _serializer = new DataContractJsonSerializerImpl(type, rootName, knownTypes); } - public DataContractJsonSerializer(Type type, DataContractJsonSerializerSettings settings) + public DataContractJsonSerializer(Type type, DataContractJsonSerializerSettings? settings) { _serializer = new DataContractJsonSerializerImpl(type, settings); } @@ -98,7 +99,7 @@ public ReadOnlyCollection KnownTypes } } - internal override DataContractDictionary KnownDataContracts + internal override DataContractDictionary? KnownDataContracts { get { @@ -119,7 +120,7 @@ public int MaxItemsInObjectGraph get { return _maxItemsInObjectGraph; } } - public DateTimeFormat DateTimeFormat + public DateTimeFormat? DateTimeFormat { get { @@ -171,42 +172,42 @@ internal static DataContract GetDataContract(DataContract declaredTypeContract, return contract; } - public override void WriteObject(Stream stream, object graph) + public override void WriteObject(Stream stream, object? graph) { _serializer.WriteObject(stream, graph); } - public override void WriteObject(XmlWriter writer, object graph) + public override void WriteObject(XmlWriter writer, object? graph) { _serializer.WriteObject(writer, graph); } - public override void WriteObject(XmlDictionaryWriter writer, object graph) + public override void WriteObject(XmlDictionaryWriter writer, object? graph) { _serializer.WriteObject(writer, graph); } - public override object ReadObject(Stream stream) + public override object? ReadObject(Stream stream) { return _serializer.ReadObject(stream); } - public override object ReadObject(XmlReader reader) + public override object? ReadObject(XmlReader reader) { return _serializer.ReadObject(reader); } - public override object ReadObject(XmlReader reader, bool verifyObjectName) + public override object? ReadObject(XmlReader reader, bool verifyObjectName) { return _serializer.ReadObject(reader, verifyObjectName); } - public override object ReadObject(XmlDictionaryReader reader) + public override object? ReadObject(XmlDictionaryReader reader) { return _serializer.ReadObject(reader); } - private List GetKnownTypesFromContext(XmlObjectSerializerContext context, IList serializerKnownTypeList) + private List GetKnownTypesFromContext(XmlObjectSerializerContext context, IList? serializerKnownTypeList) { List knownTypesList = new List(); if (context != null) @@ -241,10 +242,8 @@ private List GetKnownTypesFromContext(XmlObjectSerializerContext context, internal static void InvokeOnSerializing(object value, DataContract contract, XmlObjectSerializerWriteContextComplexJson context) { - if (contract is ClassDataContract) + if (contract is ClassDataContract classContract) { - ClassDataContract classContract = contract as ClassDataContract; - if (classContract.BaseContract != null) InvokeOnSerializing(value, classContract.BaseContract, context); if (classContract.OnSerializing != null) @@ -279,10 +278,8 @@ internal static void InvokeOnSerializing(object value, DataContract contract, Xm internal static void InvokeOnSerialized(object value, DataContract contract, XmlObjectSerializerWriteContextComplexJson context) { - if (contract is ClassDataContract) + if (contract is ClassDataContract classContract) { - ClassDataContract classContract = contract as ClassDataContract; - if (classContract.BaseContract != null) InvokeOnSerialized(value, classContract.BaseContract, context); if (classContract.OnSerialized != null) @@ -317,10 +314,8 @@ internal static void InvokeOnSerialized(object value, DataContract contract, Xml internal static void InvokeOnDeserializing(object value, DataContract contract, XmlObjectSerializerReadContextComplexJson context) { - if (contract is ClassDataContract) + if (contract is ClassDataContract classContract) { - ClassDataContract classContract = contract as ClassDataContract; - if (classContract.BaseContract != null) InvokeOnDeserializing(value, classContract.BaseContract, context); if (classContract.OnDeserializing != null) @@ -355,10 +350,8 @@ internal static void InvokeOnDeserializing(object value, DataContract contract, internal static void InvokeOnDeserialized(object value, DataContract contract, XmlObjectSerializerReadContextComplexJson context) { - if (contract is ClassDataContract) + if (contract is ClassDataContract classContract) { - ClassDataContract classContract = contract as ClassDataContract; - if (classContract.BaseContract != null) InvokeOnDeserialized(value, classContract.BaseContract, context); if (classContract.OnDeserialized != null) @@ -427,12 +420,12 @@ internal static string ConvertXmlNameToJsonName(string xmlName) return XmlConvert.DecodeName(xmlName); } - internal static XmlDictionaryString ConvertXmlNameToJsonName(XmlDictionaryString xmlName) + internal static XmlDictionaryString? ConvertXmlNameToJsonName(XmlDictionaryString? xmlName) { return (xmlName == null) ? null : new XmlDictionary().Add(ConvertXmlNameToJsonName(xmlName.Value)); } - internal static object ReadJsonValue(DataContract contract, XmlReaderDelegator reader, XmlObjectSerializerReadContextComplexJson context) + internal static object? ReadJsonValue(DataContract contract, XmlReaderDelegator reader, XmlObjectSerializerReadContextComplexJson context) { return JsonDataContract.GetJsonDataContract(contract).ReadJsonValue(reader, context); } @@ -442,22 +435,22 @@ internal static void WriteJsonValue(JsonDataContract contract, XmlWriterDelegato contract.WriteJsonValue(writer, graph, context, declaredTypeHandle); } - public override void WriteStartObject(XmlWriter writer, object graph) + public override void WriteStartObject(XmlWriter writer, object? graph) { _serializer.WriteStartObject(writer, graph); } - public override void WriteStartObject(XmlDictionaryWriter writer, object graph) + public override void WriteStartObject(XmlDictionaryWriter writer, object? graph) { _serializer.WriteStartObject(writer, graph); } - public override void WriteObjectContent(XmlWriter writer, object graph) + public override void WriteObjectContent(XmlWriter writer, object? graph) { _serializer.WriteObjectContent(writer, graph); } - public override void WriteObjectContent(XmlDictionaryWriter writer, object graph) + public override void WriteObjectContent(XmlDictionaryWriter writer, object? graph) { _serializer.WriteObjectContent(writer, graph); } @@ -472,7 +465,7 @@ public override void WriteEndObject(XmlDictionaryWriter writer) _serializer.WriteEndObject(writer); } - public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName) + public override object? ReadObject(XmlDictionaryReader reader, bool verifyObjectName) { return _serializer.ReadObject(reader, verifyObjectName); } @@ -490,38 +483,38 @@ public override bool IsStartObject(XmlDictionaryReader reader) internal sealed class DataContractJsonSerializerImpl : XmlObjectSerializer { - internal IList knownTypeList; - internal DataContractDictionary knownDataContracts; + internal IList? knownTypeList; + internal DataContractDictionary? knownDataContracts; private EmitTypeInformation _emitTypeInformation; private bool _ignoreExtensionDataObject; - private ReadOnlyCollection _knownTypeCollection; + private ReadOnlyCollection? _knownTypeCollection; private int _maxItemsInObjectGraph; - private DataContract _rootContract; // post-surrogate - private XmlDictionaryString _rootName; + private DataContract? _rootContract; // post-surrogate + private XmlDictionaryString? _rootName; private bool _rootNameRequiresMapping; private Type _rootType; private bool _serializeReadOnlyTypes; - private DateTimeFormat _dateTimeFormat; + private DateTimeFormat? _dateTimeFormat; private bool _useSimpleDictionaryFormat; public DataContractJsonSerializerImpl(Type type) - : this(type, (IEnumerable)null) + : this(type, (IEnumerable?)null) { } - public DataContractJsonSerializerImpl(Type type, IEnumerable knownTypes) + public DataContractJsonSerializerImpl(Type type, IEnumerable? knownTypes) : this(type, null, knownTypes, int.MaxValue, false, false) { } - public DataContractJsonSerializerImpl(Type type, XmlDictionaryString rootName, IEnumerable knownTypes) + public DataContractJsonSerializerImpl(Type type, XmlDictionaryString? rootName, IEnumerable? knownTypes) : this(type, rootName, knownTypes, int.MaxValue, false, false) { } internal DataContractJsonSerializerImpl(Type type, - XmlDictionaryString rootName, - IEnumerable knownTypes, + XmlDictionaryString? rootName, + IEnumerable? knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, bool alwaysEmitTypeInformation) @@ -530,14 +523,14 @@ internal DataContractJsonSerializerImpl(Type type, Initialize(type, rootName, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, emitTypeInformation, false, null, false); } - public DataContractJsonSerializerImpl(Type type, DataContractJsonSerializerSettings settings) + public DataContractJsonSerializerImpl(Type type, DataContractJsonSerializerSettings? settings) { if (settings == null) { settings = new DataContractJsonSerializerSettings(); } - XmlDictionaryString rootName = (settings.RootName == null) ? null : new XmlDictionary(1).Add(settings.RootName); + XmlDictionaryString? rootName = (settings.RootName == null) ? null : new XmlDictionary(1).Add(settings.RootName); Initialize(type, rootName, settings.KnownTypes, settings.MaxItemsInObjectGraph, settings.IgnoreExtensionDataObject, settings.EmitTypeInformation, settings.SerializeReadOnlyTypes, settings.DateTimeFormat, settings.UseSimpleDictionaryFormat); } @@ -561,7 +554,7 @@ public ReadOnlyCollection KnownTypes } } - internal override DataContractDictionary KnownDataContracts + internal override DataContractDictionary? KnownDataContracts { get { @@ -606,7 +599,7 @@ public bool SerializeReadOnlyTypes } } - public DateTimeFormat DateTimeFormat + public DateTimeFormat? DateTimeFormat { get { @@ -655,28 +648,28 @@ public override bool IsStartObject(XmlDictionaryReader reader) return IsStartObjectHandleExceptions(new JsonReaderDelegator(reader)); } - public override object ReadObject(Stream stream) + public override object? ReadObject(Stream stream) { CheckNull(stream, nameof(stream)); return ReadObject(JsonReaderWriterFactory.CreateJsonReader(stream, XmlDictionaryReaderQuotas.Max)); } - public override object ReadObject(XmlReader reader) + public override object? ReadObject(XmlReader reader) { return ReadObjectHandleExceptions(new JsonReaderDelegator(reader, this.DateTimeFormat), true); } - public override object ReadObject(XmlReader reader, bool verifyObjectName) + public override object? ReadObject(XmlReader reader, bool verifyObjectName) { return ReadObjectHandleExceptions(new JsonReaderDelegator(reader, this.DateTimeFormat), verifyObjectName); } - public override object ReadObject(XmlDictionaryReader reader) + public override object? ReadObject(XmlDictionaryReader reader) { return ReadObjectHandleExceptions(new JsonReaderDelegator(reader, this.DateTimeFormat), true); // verifyObjectName } - public override object ReadObject(XmlDictionaryReader reader, bool verifyObjectName) + public override object? ReadObject(XmlDictionaryReader reader, bool verifyObjectName) { return ReadObjectHandleExceptions(new JsonReaderDelegator(reader, this.DateTimeFormat), verifyObjectName); } @@ -694,7 +687,7 @@ public override void WriteEndObject(XmlDictionaryWriter writer) } - public override void WriteObject(Stream stream, object graph) + public override void WriteObject(Stream stream, object? graph) { CheckNull(stream, nameof(stream)); XmlDictionaryWriter jsonWriter = JsonReaderWriterFactory.CreateJsonWriter(stream, Encoding.UTF8, false); // ownsStream @@ -702,39 +695,39 @@ public override void WriteObject(Stream stream, object graph) jsonWriter.Flush(); } - public override void WriteObject(XmlWriter writer, object graph) + public override void WriteObject(XmlWriter writer, object? graph) { WriteObjectHandleExceptions(new JsonWriterDelegator(writer, this.DateTimeFormat), graph); } - public override void WriteObject(XmlDictionaryWriter writer, object graph) + public override void WriteObject(XmlDictionaryWriter writer, object? graph) { WriteObjectHandleExceptions(new JsonWriterDelegator(writer, this.DateTimeFormat), graph); } - public override void WriteObjectContent(XmlWriter writer, object graph) + public override void WriteObjectContent(XmlWriter writer, object? graph) { WriteObjectContentHandleExceptions(new JsonWriterDelegator(writer, this.DateTimeFormat), graph); } - public override void WriteObjectContent(XmlDictionaryWriter writer, object graph) + public override void WriteObjectContent(XmlDictionaryWriter writer, object? graph) { WriteObjectContentHandleExceptions(new JsonWriterDelegator(writer, this.DateTimeFormat), graph); } - public override void WriteStartObject(XmlWriter writer, object graph) + public override void WriteStartObject(XmlWriter writer, object? graph) { // No need to pass in DateTimeFormat to JsonWriterDelegator: no DateTimes will be written in start object WriteStartObjectHandleExceptions(new JsonWriterDelegator(writer), graph); } - public override void WriteStartObject(XmlDictionaryWriter writer, object graph) + public override void WriteStartObject(XmlDictionaryWriter writer, object? graph) { // No need to pass in DateTimeFormat to JsonWriterDelegator: no DateTimes will be written in start object WriteStartObjectHandleExceptions(new JsonWriterDelegator(writer), graph); } - internal static bool CheckIfJsonNameRequiresMapping(string jsonName) + internal static bool CheckIfJsonNameRequiresMapping(string? jsonName) { if (jsonName != null) { @@ -754,7 +747,7 @@ internal static bool CheckIfJsonNameRequiresMapping(string jsonName) return false; } - internal static bool CheckIfJsonNameRequiresMapping(XmlDictionaryString jsonName) + internal static bool CheckIfJsonNameRequiresMapping(XmlDictionaryString? jsonName) { return (jsonName == null) ? false : CheckIfJsonNameRequiresMapping(jsonName.Value); } @@ -774,14 +767,15 @@ internal static string ConvertXmlNameToJsonName(string xmlName) return XmlConvert.DecodeName(xmlName); } - internal static XmlDictionaryString ConvertXmlNameToJsonName(XmlDictionaryString xmlName) + [return: NotNullIfNotNull("xmlName")] + internal static XmlDictionaryString? ConvertXmlNameToJsonName(XmlDictionaryString? xmlName) { return (xmlName == null) ? null : new XmlDictionary().Add(ConvertXmlNameToJsonName(xmlName.Value)); } internal static bool IsJsonLocalName(XmlReaderDelegator reader, string elementName) { - string name; + string? name; if (XmlObjectSerializerReadContextComplexJson.TryGetJsonLocalName(reader, out name)) { return (elementName == name); @@ -789,7 +783,7 @@ internal static bool IsJsonLocalName(XmlReaderDelegator reader, string elementNa return false; } - internal static object ReadJsonValue(DataContract contract, XmlReaderDelegator reader, XmlObjectSerializerReadContextComplexJson context) + internal static object? ReadJsonValue(DataContract contract, XmlReaderDelegator reader, XmlObjectSerializerReadContextComplexJson? context) { return JsonDataContract.GetJsonDataContract(contract).ReadJsonValue(reader, context); } @@ -799,17 +793,17 @@ internal static void WriteJsonNull(XmlWriterDelegator writer) writer.WriteAttributeString(null, JsonGlobals.typeString, null, JsonGlobals.nullString); // prefix // namespace } - internal static void WriteJsonValue(JsonDataContract contract, XmlWriterDelegator writer, object graph, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle) + internal static void WriteJsonValue(JsonDataContract contract, XmlWriterDelegator writer, object graph, XmlObjectSerializerWriteContextComplexJson? context, RuntimeTypeHandle declaredTypeHandle) { contract.WriteJsonValue(writer, graph, context, declaredTypeHandle); } - internal override Type GetDeserializeType() + internal override Type? GetDeserializeType() { return _rootType; } - internal override Type GetSerializeType(object graph) + internal override Type? GetSerializeType(object? graph) { return (graph == null) ? _rootType : graph.GetType(); } @@ -824,7 +818,7 @@ internal override bool InternalIsStartObject(XmlReaderDelegator reader) return IsJsonLocalName(reader, RootName.Value); } - internal override object InternalReadObject(XmlReaderDelegator xmlReader, bool verifyObjectName) + internal override object? InternalReadObject(XmlReaderDelegator xmlReader, bool verifyObjectName) { if (MaxItemsInObjectGraph == 0) { @@ -858,14 +852,14 @@ internal override void InternalWriteEndObject(XmlWriterDelegator writer) writer.WriteEndElement(); } - internal override void InternalWriteObject(XmlWriterDelegator writer, object graph) + internal override void InternalWriteObject(XmlWriterDelegator writer, object? graph) { InternalWriteStartObject(writer, graph); InternalWriteObjectContent(writer, graph); InternalWriteEndObject(writer); } - internal override void InternalWriteObjectContent(XmlWriterDelegator writer, object graph) + internal override void InternalWriteObjectContent(XmlWriterDelegator writer, object? graph) { if (MaxItemsInObjectGraph == 0) { @@ -917,7 +911,7 @@ internal override void InternalWriteObjectContent(XmlWriterDelegator writer, obj } } - internal override void InternalWriteStartObject(XmlWriterDelegator writer, object graph) + internal override void InternalWriteStartObject(XmlWriterDelegator writer, object? graph) { if (_rootNameRequiresMapping) { @@ -932,7 +926,7 @@ internal override void InternalWriteStartObject(XmlWriterDelegator writer, objec private void AddCollectionItemTypeToKnownTypes(Type knownType) { - Type itemType; + Type? itemType; Type typeToCheck = knownType; while (CollectionDataContract.IsCollection(typeToCheck, out itemType)) { @@ -940,18 +934,19 @@ private void AddCollectionItemTypeToKnownTypes(Type knownType) { itemType = Globals.TypeOfKeyValuePair.MakeGenericType(itemType.GenericTypeArguments); } - this.knownTypeList.Add(itemType); + this.knownTypeList!.Add(itemType); typeToCheck = itemType; } } + [MemberNotNull(nameof(_rootType))] private void Initialize(Type type, - IEnumerable knownTypes, + IEnumerable? knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, EmitTypeInformation emitTypeInformation, bool serializeReadOnlyTypes, - DateTimeFormat dateTimeFormat, + DateTimeFormat? dateTimeFormat, bool useSimpleDictionaryFormat) { CheckNull(type, nameof(type)); @@ -982,14 +977,15 @@ private void Initialize(Type type, _useSimpleDictionaryFormat = useSimpleDictionaryFormat; } + [MemberNotNull(nameof(_rootType))] private void Initialize(Type type, - XmlDictionaryString rootName, - IEnumerable knownTypes, + XmlDictionaryString? rootName, + IEnumerable? knownTypes, int maxItemsInObjectGraph, bool ignoreExtensionDataObject, EmitTypeInformation emitTypeInformation, bool serializeReadOnlyTypes, - DateTimeFormat dateTimeFormat, + DateTimeFormat? dateTimeFormat, bool useSimpleDictionaryFormat) { Initialize(type, knownTypes, maxItemsInObjectGraph, ignoreExtensionDataObject, emitTypeInformation, serializeReadOnlyTypes, dateTimeFormat, useSimpleDictionaryFormat); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/DataContractJsonSerializerSettings.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/DataContractJsonSerializerSettings.cs index efddc3e0f64d33..e3958d86c230a3 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/DataContractJsonSerializerSettings.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/DataContractJsonSerializerSettings.cs @@ -17,12 +17,12 @@ public class DataContractJsonSerializerSettings /// /// Gets or sets Dummy documentation /// - public string RootName { get; set; } + public string? RootName { get; set; } /// /// Gets or sets Dummy documentation /// - public IEnumerable KnownTypes { get; set; } + public IEnumerable? KnownTypes { get; set; } /// /// Gets or sets Dummy documentation @@ -53,7 +53,7 @@ public int MaxItemsInObjectGraph /// /// Gets or sets Dummy documentation /// - public DateTimeFormat DateTimeFormat { get; set; } + public DateTimeFormat? DateTimeFormat { get; set; } /// /// Gets or sets a value indicating whether Dummy documentation diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/IXmlJsonReaderInitializer.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/IXmlJsonReaderInitializer.cs index 4f5656dee67df9..6986ae6781f237 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/IXmlJsonReaderInitializer.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/IXmlJsonReaderInitializer.cs @@ -10,10 +10,10 @@ namespace System.Runtime.Serialization.Json { public interface IXmlJsonReaderInitializer { - void SetInput(byte[] buffer, int offset, int count, Encoding encoding, XmlDictionaryReaderQuotas quotas, - OnXmlDictionaryReaderClose onClose); + void SetInput(byte[] buffer, int offset, int count, Encoding? encoding, XmlDictionaryReaderQuotas quotas, + OnXmlDictionaryReaderClose? onClose); - void SetInput(Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas, - OnXmlDictionaryReaderClose onClose); + void SetInput(Stream stream, Encoding? encoding, XmlDictionaryReaderQuotas quotas, + OnXmlDictionaryReaderClose? onClose); } } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonByteArrayDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonByteArrayDataContract.cs index 1d763d25bdcb31..19ac60805082e0 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonByteArrayDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonByteArrayDataContract.cs @@ -16,7 +16,7 @@ public JsonByteArrayDataContract(ByteArrayDataContract traditionalByteArrayDataC { } - public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context) + public override object? ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson? context) { if (context == null) { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonClassDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonClassDataContract.cs index 39132901eff7de..13e8a4031810fc 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonClassDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonClassDataContract.cs @@ -16,7 +16,7 @@ internal class JsonClassDataContract : JsonDataContract public JsonClassDataContract(ClassDataContract traditionalDataContract) : base(new JsonClassDataContractCriticalHelper(traditionalDataContract)) { - _helper = base.Helper as JsonClassDataContractCriticalHelper; + _helper = (base.Helper as JsonClassDataContractCriticalHelper)!; } private JsonFormatClassReaderDelegate CreateJsonFormatReaderDelegate() @@ -87,13 +87,13 @@ internal JsonFormatClassWriterDelegate JsonFormatWriterDelegate } } - internal XmlDictionaryString[] MemberNames => _helper.MemberNames; + internal XmlDictionaryString[]? MemberNames => _helper.MemberNames; internal override string TypeName => _helper.TypeName; private ClassDataContract TraditionalClassDataContract => _helper.TraditionalClassDataContract; - public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context) + public override object? ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson? context) { jsonReader.Read(); object o = JsonFormatReaderDelegate(jsonReader, context, XmlDictionaryString.Empty, MemberNames); @@ -101,17 +101,18 @@ public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjec return o; } - public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle) + public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson? context, RuntimeTypeHandle declaredTypeHandle) { + Debug.Assert(context != null); jsonWriter.WriteAttributeString(null, JsonGlobals.typeString, null, JsonGlobals.objectString); JsonFormatWriterDelegate(jsonWriter, obj, context, TraditionalClassDataContract, MemberNames); } private class JsonClassDataContractCriticalHelper : JsonDataContractCriticalHelper { - private JsonFormatClassReaderDelegate _jsonFormatReaderDelegate; - private JsonFormatClassWriterDelegate _jsonFormatWriterDelegate; - private XmlDictionaryString[] _memberNames; + private JsonFormatClassReaderDelegate? _jsonFormatReaderDelegate; + private JsonFormatClassWriterDelegate? _jsonFormatWriterDelegate; + private XmlDictionaryString[]? _memberNames; private readonly ClassDataContract _traditionalClassDataContract; private readonly string _typeName; @@ -123,19 +124,19 @@ public JsonClassDataContractCriticalHelper(ClassDataContract traditionalDataCont CopyMembersAndCheckDuplicateNames(); } - internal JsonFormatClassReaderDelegate JsonFormatReaderDelegate + internal JsonFormatClassReaderDelegate? JsonFormatReaderDelegate { get { return _jsonFormatReaderDelegate; } set { _jsonFormatReaderDelegate = value; } } - internal JsonFormatClassWriterDelegate JsonFormatWriterDelegate + internal JsonFormatClassWriterDelegate? JsonFormatWriterDelegate { get { return _jsonFormatWriterDelegate; } set { _jsonFormatWriterDelegate = value; } } - internal XmlDictionaryString[] MemberNames + internal XmlDictionaryString[]? MemberNames { get { return _memberNames; } } @@ -150,7 +151,7 @@ private void CopyMembersAndCheckDuplicateNames() if (_traditionalClassDataContract.MemberNames != null) { int memberCount = _traditionalClassDataContract.MemberNames.Length; - Dictionary memberTable = new Dictionary(memberCount); + Dictionary memberTable = new Dictionary(memberCount); XmlDictionaryString[] decodedMemberNames = new XmlDictionaryString[memberCount]; for (int i = 0; i < memberCount; i++) { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonCollectionDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonCollectionDataContract.cs index c2dc6304c29007..3374eb79c89eec 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonCollectionDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonCollectionDataContract.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.Reflection; using System.Runtime.CompilerServices; using System.Threading; @@ -15,7 +16,7 @@ internal class JsonCollectionDataContract : JsonDataContract public JsonCollectionDataContract(CollectionDataContract traditionalDataContract) : base(new JsonCollectionDataContractCriticalHelper(traditionalDataContract)) { - _helper = base.Helper as JsonCollectionDataContractCriticalHelper; + _helper = (base.Helper as JsonCollectionDataContractCriticalHelper)!; } private JsonFormatCollectionReaderDelegate CreateJsonFormatReaderDelegate() @@ -129,10 +130,12 @@ internal JsonFormatCollectionWriterDelegate JsonFormatWriterDelegate private CollectionDataContract TraditionalCollectionDataContract => _helper.TraditionalCollectionDataContract; - public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context) + public override object? ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson? context) { + Debug.Assert(context != null); + jsonReader.Read(); - object o = null; + object? o = null; if (context.IsGetOnlyCollection) { // IsGetOnlyCollection value has already been used to create current collectiondatacontract, value can now be reset. @@ -147,8 +150,9 @@ public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjec return o; } - public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle) + public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson? context, RuntimeTypeHandle declaredTypeHandle) { + Debug.Assert(context != null); // IsGetOnlyCollection value has already been used to create current collectiondatacontract, value can now be reset. context.IsGetOnlyCollection = false; JsonFormatWriterDelegate(jsonWriter, obj, context, TraditionalCollectionDataContract); @@ -156,9 +160,9 @@ public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object ob private class JsonCollectionDataContractCriticalHelper : JsonDataContractCriticalHelper { - private JsonFormatCollectionReaderDelegate _jsonFormatReaderDelegate; - private JsonFormatGetOnlyCollectionReaderDelegate _jsonFormatGetOnlyReaderDelegate; - private JsonFormatCollectionWriterDelegate _jsonFormatWriterDelegate; + private JsonFormatCollectionReaderDelegate? _jsonFormatReaderDelegate; + private JsonFormatGetOnlyCollectionReaderDelegate? _jsonFormatGetOnlyReaderDelegate; + private JsonFormatCollectionWriterDelegate? _jsonFormatWriterDelegate; private readonly CollectionDataContract _traditionalCollectionDataContract; public JsonCollectionDataContractCriticalHelper(CollectionDataContract traditionalDataContract) @@ -167,19 +171,19 @@ public JsonCollectionDataContractCriticalHelper(CollectionDataContract tradition _traditionalCollectionDataContract = traditionalDataContract; } - internal JsonFormatCollectionReaderDelegate JsonFormatReaderDelegate + internal JsonFormatCollectionReaderDelegate? JsonFormatReaderDelegate { get { return _jsonFormatReaderDelegate; } set { _jsonFormatReaderDelegate = value; } } - internal JsonFormatGetOnlyCollectionReaderDelegate JsonFormatGetOnlyReaderDelegate + internal JsonFormatGetOnlyCollectionReaderDelegate? JsonFormatGetOnlyReaderDelegate { get { return _jsonFormatGetOnlyReaderDelegate; } set { _jsonFormatGetOnlyReaderDelegate = value; } } - internal JsonFormatCollectionWriterDelegate JsonFormatWriterDelegate + internal JsonFormatCollectionWriterDelegate? JsonFormatWriterDelegate { get { return _jsonFormatWriterDelegate; } set { _jsonFormatWriterDelegate = value; } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonDataContract.cs index a66b7415e686db..be572739ab4f52 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonDataContract.cs @@ -6,6 +6,7 @@ using System.Runtime.Serialization; using System.Reflection; using System.Xml; +using System.Diagnostics; namespace System.Runtime.Serialization.Json { @@ -23,26 +24,26 @@ protected JsonDataContract(JsonDataContractCriticalHelper helper) _helper = helper; } - internal virtual string TypeName => null; + internal virtual string? TypeName => null; protected JsonDataContractCriticalHelper Helper => _helper; protected DataContract TraditionalDataContract => _helper.TraditionalDataContract; - private Dictionary KnownDataContracts => _helper.KnownDataContracts; + private Dictionary? KnownDataContracts => _helper.KnownDataContracts; - public static JsonReadWriteDelegates GetGeneratedReadWriteDelegates(DataContract c) + public static JsonReadWriteDelegates? GetGeneratedReadWriteDelegates(DataContract c) { // this method used to be rewritten by an IL transform // with the restructuring for multi-file, this is no longer true - instead // this has become a normal method - JsonReadWriteDelegates result; + JsonReadWriteDelegates? result; return JsonReadWriteDelegates.GetJsonDelegates().TryGetValue(c, out result) ? result : null; } internal static JsonReadWriteDelegates GetReadWriteDelegatesFromGeneratedAssembly(DataContract c) { - JsonReadWriteDelegates result = GetGeneratedReadWriteDelegates(c); + JsonReadWriteDelegates? result = GetGeneratedReadWriteDelegates(c); if (result == null) { throw new InvalidDataContractException(SR.Format(SR.SerializationCodeIsMissingForType, c.UnderlyingType)); @@ -53,9 +54,9 @@ internal static JsonReadWriteDelegates GetReadWriteDelegatesFromGeneratedAssembl } } - internal static JsonReadWriteDelegates TryGetReadWriteDelegatesFromGeneratedAssembly(DataContract c) + internal static JsonReadWriteDelegates? TryGetReadWriteDelegatesFromGeneratedAssembly(DataContract c) { - JsonReadWriteDelegates result = GetGeneratedReadWriteDelegates(c); + JsonReadWriteDelegates? result = GetGeneratedReadWriteDelegates(c); return result; } @@ -64,27 +65,27 @@ public static JsonDataContract GetJsonDataContract(DataContract traditionalDataC return JsonDataContractCriticalHelper.GetJsonDataContract(traditionalDataContract); } - public object ReadJsonValue(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context) + public object? ReadJsonValue(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson? context) { PushKnownDataContracts(context); - object deserializedObject = ReadJsonValueCore(jsonReader, context); + object? deserializedObject = ReadJsonValueCore(jsonReader, context); PopKnownDataContracts(context); return deserializedObject; } - public virtual object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context) + public virtual object? ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson? context) { return TraditionalDataContract.ReadXmlValue(jsonReader, context); } - public void WriteJsonValue(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle) + public void WriteJsonValue(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson? context, RuntimeTypeHandle declaredTypeHandle) { PushKnownDataContracts(context); WriteJsonValueCore(jsonWriter, obj, context, declaredTypeHandle); PopKnownDataContracts(context); } - public virtual void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle) + public virtual void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson? context, RuntimeTypeHandle declaredTypeHandle) { TraditionalDataContract.WriteXmlValue(jsonWriter, obj, context); } @@ -108,18 +109,20 @@ protected static bool TryReadNullAtTopLevel(XmlReaderDelegator reader) return false; } - protected void PopKnownDataContracts(XmlObjectSerializerContext context) + protected void PopKnownDataContracts(XmlObjectSerializerContext? context) { if (KnownDataContracts != null) { + Debug.Assert(context != null); context.scopedKnownTypes.Pop(); } } - protected void PushKnownDataContracts(XmlObjectSerializerContext context) + protected void PushKnownDataContracts(XmlObjectSerializerContext? context) { if (KnownDataContracts != null) { + Debug.Assert(context != null); context.scopedKnownTypes.Push(KnownDataContracts); } } @@ -134,7 +137,7 @@ internal class JsonDataContractCriticalHelper private static readonly TypeHandleRef s_typeHandleRef = new TypeHandleRef(); private static readonly Dictionary s_typeToIDCache = new Dictionary(new TypeHandleRefEqualityComparer()); - private Dictionary _knownDataContracts; + private Dictionary? _knownDataContracts; private readonly DataContract _traditionalDataContract; private readonly string _typeName; @@ -145,7 +148,7 @@ internal JsonDataContractCriticalHelper(DataContract traditionalDataContract) _typeName = string.IsNullOrEmpty(traditionalDataContract.Namespace.Value) ? traditionalDataContract.Name.Value : string.Concat(traditionalDataContract.Name.Value, JsonGlobals.NameValueSeparatorString, XmlObjectSerializerWriteContextComplexJson.TruncateDefaultDataContractNamespace(traditionalDataContract.Namespace.Value)); } - internal Dictionary KnownDataContracts => _knownDataContracts; + internal Dictionary? KnownDataContracts => _knownDataContracts; internal DataContract TraditionalDataContract => _traditionalDataContract; @@ -167,7 +170,7 @@ internal static int GetId(RuntimeTypeHandle typeHandle) { lock (s_cacheLock) { - IntRef id; + IntRef? id; s_typeHandleRef.Value = typeHandle; if (!s_typeToIDCache.TryGetValue(s_typeHandleRef, out id)) { @@ -269,7 +272,7 @@ private void AddCollectionItemContractsToKnownDataContracts() { foreach (KeyValuePair knownDataContract in _traditionalDataContract.KnownDataContracts) { - CollectionDataContract collectionDataContract = knownDataContract.Value as CollectionDataContract; + CollectionDataContract? collectionDataContract = knownDataContract.Value as CollectionDataContract; while (collectionDataContract != null) { DataContract itemContract = collectionDataContract.ItemContract; @@ -309,10 +312,10 @@ public static Dictionary GetJsonDelegates( return s_jsonDelegates; } - public JsonFormatClassWriterDelegate ClassWriterDelegate { get; set; } - public JsonFormatClassReaderDelegate ClassReaderDelegate { get; set; } - public JsonFormatCollectionWriterDelegate CollectionWriterDelegate { get; set; } - public JsonFormatCollectionReaderDelegate CollectionReaderDelegate { get; set; } - public JsonFormatGetOnlyCollectionReaderDelegate GetOnlyCollectionReaderDelegate { get; set; } + public JsonFormatClassWriterDelegate? ClassWriterDelegate { get; set; } + public JsonFormatClassReaderDelegate? ClassReaderDelegate { get; set; } + public JsonFormatCollectionWriterDelegate? CollectionWriterDelegate { get; set; } + public JsonFormatCollectionReaderDelegate? CollectionReaderDelegate { get; set; } + public JsonFormatGetOnlyCollectionReaderDelegate? GetOnlyCollectionReaderDelegate { get; set; } } } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonEncodingStreamWrapper.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonEncodingStreamWrapper.cs index 3ed7266de37a0a..939f83ba5b23e6 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonEncodingStreamWrapper.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonEncodingStreamWrapper.cs @@ -1,6 +1,8 @@ // 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.Diagnostics.CodeAnalysis; using System.IO; using System.Text; using System.Xml; @@ -22,18 +24,18 @@ internal class JsonEncodingStreamWrapper : Stream private readonly byte[] _byteBuffer = new byte[1]; private int _byteCount; private int _byteOffset; - private byte[] _bytes; - private char[] _chars; - private Decoder _dec; - private Encoder _enc; - private Encoding _encoding; + private byte[]? _bytes; + private char[]? _chars; + private Decoder? _dec; + private Encoder? _enc; + private Encoding? _encoding; private SupportedEncoding _encodingCode; private readonly bool _isReading; - private Stream _stream; + private Stream _stream = null!; // initialized in InitForXXX - public JsonEncodingStreamWrapper(Stream stream, Encoding encoding, bool isReader) + public JsonEncodingStreamWrapper(Stream stream, Encoding? encoding, bool isReader) { _isReading = isReader; if (isReader) @@ -128,7 +130,7 @@ public override int WriteTimeout set { _stream.WriteTimeout = value; } } - public static ArraySegment ProcessBuffer(byte[] buffer, int offset, int count, Encoding encoding) + public static ArraySegment ProcessBuffer(byte[] buffer, int offset, int count, Encoding? encoding) { try { @@ -186,6 +188,8 @@ public override int Read(byte[] buffer, int offset, int count) return _stream.Read(buffer, offset, count); } + Debug.Assert(_bytes != null); + Debug.Assert(_chars != null); // No more bytes than can be turned into characters _byteOffset = 0; _byteCount = _stream.Read(_bytes, _byteCount, (_chars.Length - 1) * 2); @@ -200,7 +204,7 @@ public override int Read(byte[] buffer, int offset, int count) CleanupCharBreak(); // Change encoding - int charCount = _encoding.GetChars(_bytes, 0, _byteCount, _chars, 0); + int charCount = _encoding!.GetChars(_bytes, 0, _byteCount, _chars, 0); _byteCount = Encoding.UTF8.GetBytes(_chars, 0, charCount, _bytes, 0); } @@ -209,7 +213,7 @@ public override int Read(byte[] buffer, int offset, int count) { count = _byteCount; } - Buffer.BlockCopy(_bytes, _byteOffset, buffer, offset, count); + Buffer.BlockCopy(_bytes!, _byteOffset, buffer, offset, count); _byteOffset += count; _byteCount -= count; return count; @@ -253,11 +257,13 @@ public override void Write(byte[] buffer, int offset, int count) return; } + Debug.Assert(_bytes != null); + Debug.Assert(_chars != null); while (count > 0) { int size = _chars.Length < count ? _chars.Length : count; - int charCount = _dec.GetChars(buffer, offset, size, _chars, 0, false); - _byteCount = _enc.GetBytes(_chars, 0, charCount, _bytes, 0, false); + int charCount = _dec!.GetChars(buffer, offset, size, _chars, 0, false); + _byteCount = _enc!.GetBytes(_chars, 0, charCount, _bytes, 0, false); _stream.Write(_bytes, 0, _byteCount); offset += size; count -= size; @@ -293,7 +299,7 @@ private static string GetEncodingName(SupportedEncoding enc) => _ => throw new XmlException(SR.JsonEncodingNotSupported), }; - private static SupportedEncoding GetSupportedEncoding(Encoding encoding) + private static SupportedEncoding GetSupportedEncoding(Encoding? encoding) { if (encoding == null) { @@ -346,6 +352,8 @@ private static void ThrowExpectedEncodingMismatch(SupportedEncoding expEnc, Supp private void CleanupCharBreak() { + Debug.Assert(_bytes != null); + int max = _byteOffset + _byteCount; // Read on 2 byte boundaries @@ -385,6 +393,8 @@ private void CleanupCharBreak() } } + [MemberNotNull(nameof(_chars))] + [MemberNotNull(nameof(_bytes))] private void EnsureBuffers() { EnsureByteBuffer(); @@ -394,6 +404,7 @@ private void EnsureBuffers() } } + [MemberNotNull(nameof(_bytes))] private void EnsureByteBuffer() { if (_bytes != null) @@ -408,6 +419,8 @@ private void EnsureByteBuffer() private void FillBuffer(int count) { + Debug.Assert(_bytes != null); + count -= _byteCount; while (count > 0) { @@ -422,7 +435,7 @@ private void FillBuffer(int count) } } - private void InitForReading(Stream inputStream, Encoding expectedEncoding) + private void InitForReading(Stream inputStream, Encoding? expectedEncoding) { try { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonEnumDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonEnumDataContract.cs index 916e22da5120f9..f169cf1488ba59 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonEnumDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonEnumDataContract.cs @@ -10,12 +10,12 @@ internal class JsonEnumDataContract : JsonDataContract public JsonEnumDataContract(EnumDataContract traditionalDataContract) : base(new JsonEnumDataContractCriticalHelper(traditionalDataContract)) { - _helper = base.Helper as JsonEnumDataContractCriticalHelper; + _helper = (base.Helper as JsonEnumDataContractCriticalHelper)!; } public bool IsULong => _helper.IsULong; - public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context) + public override object? ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson? context) { object enumValue; if (IsULong) @@ -34,7 +34,7 @@ public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjec return enumValue; } - public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle) + public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson? context, RuntimeTypeHandle declaredTypeHandle) { if (IsULong) { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatGeneratorStatics.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatGeneratorStatics.cs index f746185a03c331..85ba87d52c12f0 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatGeneratorStatics.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatGeneratorStatics.cs @@ -12,73 +12,73 @@ namespace System.Runtime.Serialization { public static class JsonFormatGeneratorStatics { - private static PropertyInfo s_collectionItemNameProperty; + private static PropertyInfo? s_collectionItemNameProperty; - private static ConstructorInfo s_extensionDataObjectCtor; + private static ConstructorInfo? s_extensionDataObjectCtor; - private static PropertyInfo s_extensionDataProperty; + private static PropertyInfo? s_extensionDataProperty; - private static MethodInfo s_getItemContractMethod; + private static MethodInfo? s_getItemContractMethod; - private static MethodInfo s_getJsonDataContractMethod; + private static MethodInfo? s_getJsonDataContractMethod; - private static MethodInfo s_getJsonMemberIndexMethod; + private static MethodInfo? s_getJsonMemberIndexMethod; - private static MethodInfo s_getRevisedItemContractMethod; + private static MethodInfo? s_getRevisedItemContractMethod; - private static MethodInfo s_getUninitializedObjectMethod; + private static MethodInfo? s_getUninitializedObjectMethod; - private static MethodInfo s_ienumeratorGetCurrentMethod; + private static MethodInfo? s_ienumeratorGetCurrentMethod; - private static MethodInfo s_ienumeratorMoveNextMethod; + private static MethodInfo? s_ienumeratorMoveNextMethod; - private static MethodInfo s_isStartElementMethod0; + private static MethodInfo? s_isStartElementMethod0; - private static MethodInfo s_isStartElementMethod2; + private static MethodInfo? s_isStartElementMethod2; - private static PropertyInfo s_localNameProperty; + private static PropertyInfo? s_localNameProperty; - private static PropertyInfo s_namespaceProperty; + private static PropertyInfo? s_namespaceProperty; - private static MethodInfo s_moveToContentMethod; + private static MethodInfo? s_moveToContentMethod; - private static PropertyInfo s_nodeTypeProperty; + private static PropertyInfo? s_nodeTypeProperty; - private static MethodInfo s_onDeserializationMethod; + private static MethodInfo? s_onDeserializationMethod; - private static MethodInfo s_readJsonValueMethod; + private static MethodInfo? s_readJsonValueMethod; - private static ConstructorInfo s_serializationExceptionCtor; + private static ConstructorInfo? s_serializationExceptionCtor; - private static Type[] s_serInfoCtorArgs; + private static Type[]? s_serInfoCtorArgs; - private static MethodInfo s_throwDuplicateMemberExceptionMethod; + private static MethodInfo? s_throwDuplicateMemberExceptionMethod; - private static MethodInfo s_throwMissingRequiredMembersMethod; + private static MethodInfo? s_throwMissingRequiredMembersMethod; - private static PropertyInfo s_typeHandleProperty; + private static PropertyInfo? s_typeHandleProperty; - private static PropertyInfo s_useSimpleDictionaryFormatReadProperty; + private static PropertyInfo? s_useSimpleDictionaryFormatReadProperty; - private static PropertyInfo s_useSimpleDictionaryFormatWriteProperty; + private static PropertyInfo? s_useSimpleDictionaryFormatWriteProperty; - private static MethodInfo s_writeAttributeStringMethod; + private static MethodInfo? s_writeAttributeStringMethod; - private static MethodInfo s_writeEndElementMethod; + private static MethodInfo? s_writeEndElementMethod; - private static MethodInfo s_writeJsonISerializableMethod; + private static MethodInfo? s_writeJsonISerializableMethod; - private static MethodInfo s_writeJsonNameWithMappingMethod; + private static MethodInfo? s_writeJsonNameWithMappingMethod; - private static MethodInfo s_writeJsonValueMethod; + private static MethodInfo? s_writeJsonValueMethod; - private static MethodInfo s_writeStartElementMethod; + private static MethodInfo? s_writeStartElementMethod; - private static MethodInfo s_writeStartElementStringMethod; + private static MethodInfo? s_writeStartElementStringMethod; - private static MethodInfo s_parseEnumMethod; + private static MethodInfo? s_parseEnumMethod; - private static MethodInfo s_getJsonMemberNameMethod; + private static MethodInfo? s_getJsonMemberNameMethod; public static PropertyInfo CollectionItemNameProperty { @@ -96,10 +96,10 @@ public static PropertyInfo CollectionItemNameProperty public static ConstructorInfo ExtensionDataObjectCtor => s_extensionDataObjectCtor ?? (s_extensionDataObjectCtor = - typeof(ExtensionDataObject).GetConstructor(Globals.ScanAllMembers, null, Array.Empty(), null)); + typeof(ExtensionDataObject).GetConstructor(Globals.ScanAllMembers, null, Array.Empty(), null))!; public static PropertyInfo ExtensionDataProperty => s_extensionDataProperty ?? - (s_extensionDataProperty = typeof(IExtensibleDataObject).GetProperty("ExtensionData")); + (s_extensionDataProperty = typeof(IExtensibleDataObject).GetProperty("ExtensionData")!); public static MethodInfo GetCurrentMethod { @@ -107,7 +107,7 @@ public static MethodInfo GetCurrentMethod { if (s_ienumeratorGetCurrentMethod == null) { - s_ienumeratorGetCurrentMethod = typeof(IEnumerator).GetProperty("Current").GetGetMethod(); + s_ienumeratorGetCurrentMethod = typeof(IEnumerator).GetProperty("Current")!.GetGetMethod(); Debug.Assert(s_ienumeratorGetCurrentMethod != null); } return s_ienumeratorGetCurrentMethod; @@ -119,7 +119,7 @@ public static MethodInfo GetItemContractMethod { if (s_getItemContractMethod == null) { - s_getItemContractMethod = typeof(CollectionDataContract).GetProperty("ItemContract", Globals.ScanAllMembers).GetGetMethod(true); // nonPublic + s_getItemContractMethod = typeof(CollectionDataContract).GetProperty("ItemContract", Globals.ScanAllMembers)!.GetGetMethod(nonPublic: true); Debug.Assert(s_getItemContractMethod != null); } return s_getItemContractMethod; @@ -265,6 +265,7 @@ public static MethodInfo OnDeserializationMethod if (s_onDeserializationMethod == null) { s_onDeserializationMethod = typeof(IDeserializationCallback).GetMethod("OnDeserialization"); + Debug.Assert(s_onDeserializationMethod != null); } return s_onDeserializationMethod; } @@ -288,6 +289,7 @@ public static ConstructorInfo SerializationExceptionCtor if (s_serializationExceptionCtor == null) { s_serializationExceptionCtor = typeof(SerializationException).GetConstructor(new Type[] { typeof(string) }); + Debug.Assert(s_serializationExceptionCtor != null); } return s_serializationExceptionCtor; } @@ -394,6 +396,7 @@ public static MethodInfo WriteJsonISerializableMethod if (s_writeJsonISerializableMethod == null) { s_writeJsonISerializableMethod = typeof(XmlObjectSerializerWriteContextComplexJson).GetMethod("WriteJsonISerializable", Globals.ScanAllMembers); + Debug.Assert(s_writeJsonISerializableMethod != null); } return s_writeJsonISerializableMethod; } @@ -455,6 +458,7 @@ public static MethodInfo ParseEnumMethod if (s_parseEnumMethod == null) { s_parseEnumMethod = typeof(Enum).GetMethod("Parse", BindingFlags.Static | BindingFlags.Public, new Type[] { typeof(Type), typeof(string) }); + Debug.Assert(s_parseEnumMethod != null); } return s_parseEnumMethod; } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatReaderGenerator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatReaderGenerator.cs index 47d4b81032879f..5f0326769efe63 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatReaderGenerator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatReaderGenerator.cs @@ -8,13 +8,14 @@ namespace System.Runtime.Serialization.Json { using System; using System.Collections.Generic; + using System.Diagnostics; using System.Reflection; using System.Reflection.Emit; using System.Runtime; using System.Security; using System.Xml; - internal delegate object JsonFormatClassReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContextComplexJson context, XmlDictionaryString emptyDictionaryString, XmlDictionaryString[] memberNames); + internal delegate object JsonFormatClassReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContextComplexJson? context, XmlDictionaryString emptyDictionaryString, XmlDictionaryString[]? memberNames); internal delegate object JsonFormatCollectionReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContextComplexJson context, XmlDictionaryString emptyDictionaryString, XmlDictionaryString itemName, CollectionDataContract collectionContract); internal delegate void JsonFormatGetOnlyCollectionReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContextComplexJson context, XmlDictionaryString emptyDictionaryString, XmlDictionaryString itemName, CollectionDataContract collectionContract); @@ -44,14 +45,14 @@ public JsonFormatGetOnlyCollectionReaderDelegate GenerateGetOnlyCollectionReader private class CriticalHelper { - private CodeGenerator _ilg; - private LocalBuilder _objectLocal; - private Type _objectType; - private ArgBuilder _xmlReaderArg; - private ArgBuilder _contextArg; - private ArgBuilder _memberNamesArg; - private ArgBuilder _collectionContractArg; - private ArgBuilder _emptyDictionaryStringArg; + private CodeGenerator _ilg = null!; // initialized in GenerateXXXReader + private LocalBuilder _objectLocal = null!; // initialized in CreateObject and ReadCollection + private Type? _objectType; + private ArgBuilder _xmlReaderArg = null!; // initialized in InitArgs + private ArgBuilder _contextArg = null!; // initialized in InitArgs + private ArgBuilder _memberNamesArg = null!; // initialized in InitArgs + private ArgBuilder? _collectionContractArg; + private ArgBuilder _emptyDictionaryStringArg = null!; // initialized in InitArgs public JsonFormatClassReaderDelegate GenerateClassReader(ClassDataContract classContract) { @@ -59,7 +60,7 @@ public JsonFormatClassReaderDelegate GenerateClassReader(ClassDataContract class bool memberAccessFlag = classContract.RequiresMemberAccessForRead(null); try { - BeginMethod(_ilg, "Read" + DataContract.SanitizeTypeName(classContract.StableName.Name) + "FromJson", typeof(JsonFormatClassReaderDelegate), memberAccessFlag); + BeginMethod(_ilg, "Read" + DataContract.SanitizeTypeName(classContract.StableName!.Name) + "FromJson", typeof(JsonFormatClassReaderDelegate), memberAccessFlag); } catch (SecurityException securityException) { @@ -167,7 +168,7 @@ private void BeginMethod(CodeGenerator ilg, string methodName, Type delegateType ilg.BeginMethod(methodName, delegateType, allowPrivateMemberAccess); #else - MethodInfo signature = delegateType.GetMethod("Invoke"); + MethodInfo signature = delegateType.GetMethod("Invoke")!; ParameterInfo[] parameters = signature.GetParameters(); Type[] paramTypes = new Type[parameters.Length]; for (int i = 0; i < parameters.Length; i++) @@ -195,7 +196,7 @@ private void CreateObject(ClassDataContract classContract) if (classContract.UnderlyingType == Globals.TypeOfDBNull) { - _ilg.LoadMember(Globals.TypeOfDBNull.GetField("Value")); + _ilg.LoadMember(Globals.TypeOfDBNull.GetField("Value")!); _ilg.Stloc(_objectLocal); } else if (classContract.IsNonAttributedType) @@ -207,7 +208,7 @@ private void CreateObject(ClassDataContract classContract) } else { - _ilg.New(classContract.GetNonAttributedTypeConstructor()); + _ilg.New(classContract.GetNonAttributedTypeConstructor()!); _ilg.Stloc(_objectLocal); } } @@ -226,7 +227,7 @@ private void InvokeOnDeserializing(ClassDataContract classContract) if (classContract.OnDeserializing != null) { _ilg.LoadAddress(_objectLocal); - _ilg.ConvertAddress(_objectLocal.LocalType, _objectType); + _ilg.ConvertAddress(_objectLocal.LocalType, _objectType!); _ilg.Load(_contextArg); _ilg.LoadMember(XmlFormatGeneratorStatics.GetStreamingContextMethod); _ilg.Call(classContract.OnDeserializing); @@ -240,7 +241,7 @@ private void InvokeOnDeserialized(ClassDataContract classContract) if (classContract.OnDeserialized != null) { _ilg.LoadAddress(_objectLocal); - _ilg.ConvertAddress(_objectLocal.LocalType, _objectType); + _ilg.ConvertAddress(_objectLocal.LocalType, _objectType!); _ilg.Load(_contextArg); _ilg.LoadMember(XmlFormatGeneratorStatics.GetStreamingContextMethod); _ilg.Call(classContract.OnDeserialized); @@ -277,10 +278,10 @@ private void ReadClass(ClassDataContract classContract) _ilg.Store(extensionDataLocal); ReadMembers(classContract, extensionDataLocal); - ClassDataContract currentContract = classContract; + ClassDataContract? currentContract = classContract; while (currentContract != null) { - MethodInfo extensionDataSetMethod = currentContract.ExtensionDataSetMethod; + MethodInfo? extensionDataSetMethod = currentContract.ExtensionDataSetMethod; if (extensionDataSetMethod != null) _ilg.Call(_objectLocal, extensionDataSetMethod, extensionDataLocal); currentContract = currentContract.BaseContract; @@ -292,9 +293,9 @@ private void ReadClass(ClassDataContract classContract) } } - private void ReadMembers(ClassDataContract classContract, LocalBuilder extensionDataLocal) + private void ReadMembers(ClassDataContract classContract, LocalBuilder? extensionDataLocal) { - int memberCount = classContract.MemberNames.Length; + int memberCount = classContract.MemberNames!.Length; _ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, memberCount); BitFlagsGenerator expectedElements = new BitFlagsGenerator(memberCount, _ilg, classContract.UnderlyingType.Name + "_ExpectedElements"); @@ -345,7 +346,7 @@ private int ReadMembers(ClassDataContract classContract, BitFlagsGenerator expec int memberCount = (classContract.BaseContract == null) ? 0 : ReadMembers(classContract.BaseContract, expectedElements, memberLabels, throwDuplicateMemberLabel, memberIndexLocal); - for (int i = 0; i < classContract.Members.Count; i++, memberCount++) + for (int i = 0; i < classContract.Members!.Count; i++, memberCount++) { DataMember dataMember = classContract.Members[i]; Type memberType = dataMember.MemberType; @@ -353,7 +354,7 @@ private int ReadMembers(ClassDataContract classContract, BitFlagsGenerator expec _ilg.Set(memberIndexLocal, memberCount); expectedElements.Load(memberCount); _ilg.Brfalse(throwDuplicateMemberLabel); - LocalBuilder value = null; + LocalBuilder? value = null; if (dataMember.IsGetOnlyCollection) { _ilg.LoadAddress(_objectLocal); @@ -368,7 +369,7 @@ private int ReadMembers(ClassDataContract classContract, BitFlagsGenerator expec _ilg.Call(_contextArg, XmlFormatGeneratorStatics.ResetCollectionMemberInfoMethod); value = ReadValue(memberType, dataMember.Name); _ilg.LoadAddress(_objectLocal); - _ilg.ConvertAddress(_objectLocal.LocalType, _objectType); + _ilg.ConvertAddress(_objectLocal.LocalType, _objectType!); _ilg.Ldloc(value); _ilg.StoreMember(dataMember.MemberInfo); } @@ -407,7 +408,7 @@ private int SetRequiredElements(ClassDataContract contract, byte[] requiredEleme { int memberCount = (contract.BaseContract == null) ? 0 : SetRequiredElements(contract.BaseContract, requiredElements); - List members = contract.Members; + List members = contract.Members!; for (int i = 0; i < members.Count; i++, memberCount++) { if (members[i].IsRequired) @@ -434,11 +435,11 @@ private void ResetExpectedElements(BitFlagsGenerator expectedElements, int index private void ReadISerializable(ClassDataContract classContract) { - ConstructorInfo ctor = classContract.UnderlyingType.GetConstructor(Globals.ScanAllMembers, null, JsonFormatGeneratorStatics.SerInfoCtorArgs, null); + ConstructorInfo? ctor = classContract.UnderlyingType.GetConstructor(Globals.ScanAllMembers, null, JsonFormatGeneratorStatics.SerInfoCtorArgs, null); if (ctor == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.SerializationInfo_ConstructorNotFound, DataContract.GetClrTypeFullName(classContract.UnderlyingType)))); _ilg.LoadAddress(_objectLocal); - _ilg.ConvertAddress(_objectLocal.LocalType, _objectType); + _ilg.ConvertAddress(_objectLocal.LocalType, _objectType!); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.ReadSerializationInfoMethod, _xmlReaderArg, classContract.UnderlyingType); _ilg.Load(_contextArg); _ilg.LoadMember(XmlFormatGeneratorStatics.GetStreamingContextMethod); @@ -448,7 +449,7 @@ private void ReadISerializable(ClassDataContract classContract) private LocalBuilder ReadValue(Type type, string name) { LocalBuilder value = _ilg.DeclareLocal(type, "valueRead"); - LocalBuilder nullableValue = null; + LocalBuilder? nullableValue = null; int nullables = 0; while (type.IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfNullable) { @@ -456,7 +457,7 @@ private LocalBuilder ReadValue(Type type, string name) type = type.GetGenericArguments()[0]; } - PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type); + PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type); if ((primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject) || nullables != 0 || type.IsValueType) { LocalBuilder objectId = _ilg.DeclareLocal(Globals.TypeOfString, "objectIdRead"); @@ -559,10 +560,10 @@ private void WrapNullableObject(LocalBuilder innerValue, LocalBuilder outerValue for (int i = 1; i < nullables; i++) { Type type = Globals.TypeOfNullable.MakeGenericType(innerType); - _ilg.New(type.GetConstructor(new Type[] { innerType })); + _ilg.New(type.GetConstructor(new Type[] { innerType })!); innerType = type; } - _ilg.Call(outerType.GetConstructor(new Type[] { innerType })); + _ilg.Call(outerType.GetConstructor(new Type[] { innerType })!); } private void ReadCollection(CollectionDataContract collectionContract) @@ -570,18 +571,18 @@ private void ReadCollection(CollectionDataContract collectionContract) Type type = collectionContract.UnderlyingType; Type itemType = collectionContract.ItemType; bool isArray = (collectionContract.Kind == CollectionKind.Array); - ConstructorInfo constructor = collectionContract.Constructor; + ConstructorInfo constructor = collectionContract.Constructor!; if (type.IsInterface) { switch (collectionContract.Kind) { case CollectionKind.GenericDictionary: type = Globals.TypeOfDictionaryGeneric.MakeGenericType(itemType.GetGenericArguments()); - constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, Array.Empty()); + constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, Array.Empty())!; break; case CollectionKind.Dictionary: type = Globals.TypeOfHashtable; - constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, Array.Empty()); + constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, Array.Empty())!; break; case CollectionKind.Collection: case CollectionKind.GenericCollection: @@ -635,7 +636,7 @@ private void ReadCollection(CollectionDataContract collectionContract) _ilg.IfNot(); } - LocalBuilder growingCollection = null; + LocalBuilder? growingCollection = null; if (isArray) { growingCollection = _ilg.DeclareLocal(type, "growingCollection"); @@ -651,6 +652,7 @@ private void ReadCollection(CollectionDataContract collectionContract) LocalBuilder value = ReadCollectionItem(collectionContract, itemType); if (isArray) { + Debug.Assert(growingCollection != null); MethodInfo ensureArraySizeMethod = XmlFormatGeneratorStatics.EnsureArraySizeMethod.MakeGenericMethod(itemType); _ilg.Call(null, ensureArraySizeMethod, growingCollection, i); _ilg.Stloc(growingCollection); @@ -704,7 +706,7 @@ private void ReadSimpleDictionary(CollectionDataContract collectionContract, Typ } ClassDataContract keyValueDataContract = (ClassDataContract)collectionContract.ItemContract; - DataContract keyDataContract = keyValueDataContract.Members[0].MemberTypeContract; + DataContract keyDataContract = keyValueDataContract.Members![0].MemberTypeContract; KeyParseMode keyParseMode = KeyParseMode.Fail; @@ -763,7 +765,7 @@ private void ReadSimpleDictionary(CollectionDataContract collectionContract, Typ } else if (keyParseMode == KeyParseMode.UsingCustomParse) { - _ilg.Call(keyDataContract.ParseMethod); + _ilg.Call(keyDataContract.ParseMethod!); } LocalBuilder pairKey = _ilg.DeclareLocal(keyType, "key"); _ilg.Stloc(pairKey); @@ -871,11 +873,11 @@ private void ReadGetOnlyCollection(CollectionDataContract collectionContract) private bool TryReadPrimitiveArray(Type itemType) { - PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType); + PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType); if (primitiveContract == null) return false; - string readArrayMethod = null; + string? readArrayMethod = null; switch (itemType.GetTypeCode()) { case TypeCode.Boolean: @@ -913,7 +915,7 @@ private bool TryReadPrimitiveArray(Type itemType) // -1 Array Size _ilg.Load(-1); _ilg.Ldloca(_objectLocal); - _ilg.Call(typeof(JsonReaderDelegator).GetMethod(readArrayMethod, Globals.ScanAllMembers)); + _ilg.Call(typeof(JsonReaderDelegator).GetMethod(readArrayMethod, Globals.ScanAllMembers)!); return true; } return false; @@ -945,12 +947,12 @@ private void StoreCollectionValue(LocalBuilder collection, LocalBuilder value, C { if (collectionContract.Kind == CollectionKind.GenericDictionary || collectionContract.Kind == CollectionKind.Dictionary) { - ClassDataContract keyValuePairContract = DataContract.GetDataContract(value.LocalType) as ClassDataContract; + ClassDataContract? keyValuePairContract = DataContract.GetDataContract(value.LocalType) as ClassDataContract; if (keyValuePairContract == null) { Fx.Assert("Failed to create contract for KeyValuePair type"); } - DataMember keyMember = keyValuePairContract.Members[0]; + DataMember keyMember = keyValuePairContract.Members![0]; DataMember valueMember = keyValuePairContract.Members[1]; LocalBuilder pairKey = _ilg.DeclareLocal(keyMember.MemberType, keyMember.Name); LocalBuilder pairValue = _ilg.DeclareLocal(valueMember.MemberType, valueMember.Name); @@ -965,6 +967,8 @@ private void StoreCollectionValue(LocalBuilder collection, LocalBuilder value, C } else { + Debug.Assert(collectionContract.AddMethod != null); + _ilg.Call(collection, collectionContract.AddMethod, value); if (collectionContract.AddMethod.ReturnType != Globals.TypeOfVoid) _ilg.Pop(); @@ -973,6 +977,8 @@ private void StoreCollectionValue(LocalBuilder collection, LocalBuilder value, C private void StoreKeyValuePair(LocalBuilder collection, CollectionDataContract collectionContract, LocalBuilder pairKey, LocalBuilder pairValue) { + Debug.Assert(collectionContract.AddMethod != null); + _ilg.Call(collection, collectionContract.AddMethod, pairKey, pairValue); if (collectionContract.AddMethod.ReturnType != Globals.TypeOfVoid) _ilg.Pop(); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatWriterGenerator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatWriterGenerator.cs index da533661cb1f50..606d464db2ba78 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatWriterGenerator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonFormatWriterGenerator.cs @@ -8,12 +8,13 @@ namespace System.Runtime.Serialization.Json { using System; using System.Collections; + using System.Diagnostics; using System.Reflection; using System.Reflection.Emit; using System.Security; using System.Xml; - internal delegate void JsonFormatClassWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, ClassDataContract dataContract, XmlDictionaryString[] memberNames); + internal delegate void JsonFormatClassWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, ClassDataContract dataContract, XmlDictionaryString[]? memberNames); internal delegate void JsonFormatCollectionWriterDelegate(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, CollectionDataContract dataContract); internal class JsonFormatWriterGenerator @@ -37,14 +38,14 @@ internal JsonFormatCollectionWriterDelegate GenerateCollectionWriter(CollectionD private class CriticalHelper { - private CodeGenerator _ilg; - private ArgBuilder _xmlWriterArg; - private ArgBuilder _contextArg; - private ArgBuilder _dataContractArg; - private LocalBuilder _objectLocal; + private CodeGenerator _ilg = null!; // initialized in GenerateXXXWriter + private ArgBuilder _xmlWriterArg = null!; // initialized in InitArgs + private ArgBuilder _contextArg = null!; // initialized in InitArgs + private ArgBuilder _dataContractArg = null!; // initialized in InitArgs + private LocalBuilder _objectLocal = null!; // initialized in InitArgs // Used for classes - private ArgBuilder _memberNamesArg; + private ArgBuilder? _memberNamesArg; private int _typeIndex = 1; private int _childElementIndex; @@ -102,7 +103,7 @@ private void BeginMethod(CodeGenerator ilg, string methodName, Type delegateType #if USE_REFEMIT ilg.BeginMethod(methodName, delegateType, allowPrivateMemberAccess); #else - MethodInfo signature = delegateType.GetMethod("Invoke"); + MethodInfo signature = delegateType.GetMethod("Invoke")!; ParameterInfo[] parameters = signature.GetParameters(); Type[] paramTypes = new Type[parameters.Length]; for (int i = 0; i < parameters.Length; i++) @@ -136,8 +137,8 @@ private void InitArgs(Type objType) else if (objType.IsGenericType && objType.GetGenericTypeDefinition() == Globals.TypeOfKeyValuePairAdapter) { ClassDataContract dc = (ClassDataContract)DataContract.GetDataContract(objType); - _ilg.ConvertValue(objectArg.ArgType, Globals.TypeOfKeyValuePair.MakeGenericType(dc.KeyValuePairGenericArguments)); - _ilg.New(dc.KeyValuePairAdapterConstructorInfo); + _ilg.ConvertValue(objectArg.ArgType, Globals.TypeOfKeyValuePair.MakeGenericType(dc.KeyValuePairGenericArguments!)); + _ilg.New(dc.KeyValuePairAdapterConstructorInfo!); } else { @@ -200,19 +201,19 @@ private void WriteClass(ClassDataContract classContract) InvokeOnSerialized(classContract); } - private int WriteMembers(ClassDataContract classContract, LocalBuilder extensionDataLocal, ClassDataContract derivedMostClassContract) + private int WriteMembers(ClassDataContract classContract, LocalBuilder? extensionDataLocal, ClassDataContract derivedMostClassContract) { int memberCount = (classContract.BaseContract == null) ? 0 : WriteMembers(classContract.BaseContract, extensionDataLocal, derivedMostClassContract); - int classMemberCount = classContract.Members.Count; + int classMemberCount = classContract.Members!.Count; _ilg.Call(thisObj: _contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, classMemberCount); for (int i = 0; i < classMemberCount; i++, memberCount++) { DataMember member = classContract.Members[i]; Type memberType = member.MemberType; - LocalBuilder memberValue = null; + LocalBuilder? memberValue = null; _ilg.Load(_contextArg); _ilg.Call(methodInfo: member.IsGetOnlyCollection ? @@ -225,7 +226,7 @@ private int WriteMembers(ClassDataContract classContract, LocalBuilder extension _ilg.IfNotDefaultValue(memberValue); } - bool requiresNameAttribute = DataContractJsonSerializerImpl.CheckIfXmlNameRequiresMapping(classContract.MemberNames[i]); + bool requiresNameAttribute = DataContractJsonSerializerImpl.CheckIfXmlNameRequiresMapping(classContract.MemberNames![i]); if (requiresNameAttribute || !TryWritePrimitive(memberType, memberValue, member.MemberInfo, arrayItemIndex: null, name: null, nameIndex: i + _childElementIndex)) { // Note: DataContractSerializer has member-conflict logic here to deal with the schema export @@ -306,7 +307,9 @@ private void WriteCollection(CollectionDataContract collectionContract) } else { - MethodInfo incrementCollectionCountMethod = null; + Debug.Assert(collectionContract.GetEnumeratorMethod != null); + + MethodInfo? incrementCollectionCountMethod = null; switch (collectionContract.Kind) { case CollectionKind.Collection: @@ -328,8 +331,8 @@ private void WriteCollection(CollectionDataContract collectionContract) } bool isDictionary = false, isGenericDictionary = false; - Type enumeratorType = null; - Type[] keyValueTypes = null; + Type? enumeratorType = null; + Type[]? keyValueTypes = null; if (collectionContract.Kind == CollectionKind.GenericDictionary) { isGenericDictionary = true; @@ -346,8 +349,8 @@ private void WriteCollection(CollectionDataContract collectionContract) { enumeratorType = collectionContract.GetEnumeratorMethod.ReturnType; } - MethodInfo moveNextMethod = enumeratorType.GetMethod(Globals.MoveNextMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty()); - MethodInfo getCurrentMethod = enumeratorType.GetMethod(Globals.GetCurrentMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty()); + MethodInfo? moveNextMethod = enumeratorType.GetMethod(Globals.MoveNextMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty()); + MethodInfo? getCurrentMethod = enumeratorType.GetMethod(Globals.GetCurrentMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty()); if (moveNextMethod == null || getCurrentMethod == null) { if (enumeratorType.IsInterface) @@ -376,9 +379,9 @@ private void WriteCollection(CollectionDataContract collectionContract) } } if (moveNextMethod == null) - moveNextMethod = CollectionDataContract.GetTargetMethodWithName(Globals.MoveNextMethodName, enumeratorType, ienumeratorInterface); + moveNextMethod = CollectionDataContract.GetTargetMethodWithName(Globals.MoveNextMethodName, enumeratorType, ienumeratorInterface)!; if (getCurrentMethod == null) - getCurrentMethod = CollectionDataContract.GetTargetMethodWithName(Globals.GetCurrentMethodName, enumeratorType, ienumeratorInterface); + getCurrentMethod = CollectionDataContract.GetTargetMethodWithName(Globals.GetCurrentMethodName, enumeratorType, ienumeratorInterface)!; } } Type elementType = getCurrentMethod.ReturnType; @@ -388,14 +391,15 @@ private void WriteCollection(CollectionDataContract collectionContract) _ilg.Call(_objectLocal, collectionContract.GetEnumeratorMethod); if (isDictionary) { - ConstructorInfo dictEnumCtor = enumeratorType.GetConstructor(Globals.ScanAllMembers, new Type[] { Globals.TypeOfIDictionaryEnumerator }); + ConstructorInfo dictEnumCtor = enumeratorType.GetConstructor(Globals.ScanAllMembers, new Type[] { Globals.TypeOfIDictionaryEnumerator })!; _ilg.ConvertValue(collectionContract.GetEnumeratorMethod.ReturnType, Globals.TypeOfIDictionaryEnumerator); _ilg.New(dictEnumCtor); } else if (isGenericDictionary) { + Debug.Assert(keyValueTypes != null); Type ctorParam = Globals.TypeOfIEnumeratorGeneric.MakeGenericType(Globals.TypeOfKeyValuePair.MakeGenericType(keyValueTypes)); - ConstructorInfo dictEnumCtor = enumeratorType.GetConstructor(Globals.ScanAllMembers, new Type[] { ctorParam }); + ConstructorInfo dictEnumCtor = enumeratorType.GetConstructor(Globals.ScanAllMembers, new Type[] { ctorParam })!; _ilg.ConvertValue(collectionContract.GetEnumeratorMethod.ReturnType, ctorParam); _ilg.New(dictEnumCtor); } @@ -404,9 +408,10 @@ private void WriteCollection(CollectionDataContract collectionContract) bool canWriteSimpleDictionary = isDictionary || isGenericDictionary; if (canWriteSimpleDictionary) { + Debug.Assert(keyValueTypes != null); Type genericDictionaryKeyValueType = Globals.TypeOfKeyValue.MakeGenericType(keyValueTypes); - PropertyInfo genericDictionaryKeyProperty = genericDictionaryKeyValueType.GetProperty(JsonGlobals.KeyString); - PropertyInfo genericDictionaryValueProperty = genericDictionaryKeyValueType.GetProperty(JsonGlobals.ValueString); + PropertyInfo genericDictionaryKeyProperty = genericDictionaryKeyValueType.GetProperty(JsonGlobals.KeyString)!; + PropertyInfo genericDictionaryValueProperty = genericDictionaryKeyValueType.GetProperty(JsonGlobals.ValueString)!; _ilg.Load(_contextArg); _ilg.LoadMember(JsonFormatGeneratorStatics.UseSimpleDictionaryFormatWriteProperty); @@ -472,9 +477,9 @@ private void WriteCollection(CollectionDataContract collectionContract) } } - private bool TryWritePrimitive(Type type, LocalBuilder value, MemberInfo memberInfo, LocalBuilder arrayItemIndex, LocalBuilder name, int nameIndex) + private bool TryWritePrimitive(Type type, LocalBuilder? value, MemberInfo? memberInfo, LocalBuilder? arrayItemIndex, LocalBuilder? name, int nameIndex) { - PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type); + PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type); if (primitiveContract == null || primitiveContract.UnderlyingType == Globals.TypeOfObject) return false; @@ -509,7 +514,7 @@ private bool TryWritePrimitive(Type type, LocalBuilder value, MemberInfo memberI } else { - _ilg.LoadArrayElement(_memberNamesArg, nameIndex); + _ilg.LoadArrayElement(_memberNamesArg!, nameIndex); } // load namespace _ilg.Load(null); @@ -520,11 +525,11 @@ private bool TryWritePrimitive(Type type, LocalBuilder value, MemberInfo memberI private bool TryWritePrimitiveArray(Type type, Type itemType, LocalBuilder value, LocalBuilder itemName) { - PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType); + PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType); if (primitiveContract == null) return false; - string writeArrayMethod = null; + string? writeArrayMethod = null; switch (itemType.GetTypeCode()) { case TypeCode.Boolean: @@ -558,7 +563,7 @@ private bool TryWritePrimitiveArray(Type type, Type itemType, LocalBuilder value MethodInfo writeArrayMethodInfo = typeof(JsonWriterDelegator).GetMethod( writeArrayMethod, Globals.ScanAllMembers, - new Type[] { type, typeof(XmlDictionaryString), typeof(XmlDictionaryString) }); + new Type[] { type, typeof(XmlDictionaryString), typeof(XmlDictionaryString) })!; _ilg.Call(_xmlWriterArg, writeArrayMethodInfo, value, itemName, null); return true; } @@ -590,7 +595,7 @@ private void WriteValue(LocalBuilder memberValue) memberType.GetGenericTypeDefinition() == Globals.TypeOfNullable); if (memberType.IsValueType && !isNullableOfT) { - PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType); + PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType); if (primitiveContract != null) _ilg.Call(_xmlWriterArg, primitiveContract.XmlFormatContentWriterMethod, memberValue); else @@ -612,7 +617,7 @@ private void WriteValue(LocalBuilder memberValue) _ilg.If(); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.WriteNullMethod, _xmlWriterArg, memberType, DataContract.IsTypeSerializable(memberType)); _ilg.Else(); - PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType); + PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType); if (primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject) { if (isNullableOfT) @@ -661,7 +666,7 @@ private void InternalSerialize(MethodInfo methodInfo, LocalBuilder memberValue, _ilg.Stloc(typeHandleValue); _ilg.LoadAddress(typeHandleValue); _ilg.Ldtoken(memberType); - _ilg.Call(typeof(RuntimeTypeHandle).GetMethod("Equals", new Type[] { typeof(RuntimeTypeHandle) })); + _ilg.Call(typeof(RuntimeTypeHandle).GetMethod("Equals", new Type[] { typeof(RuntimeTypeHandle) })!); _ilg.Load(writeXsiType); _ilg.Load(DataContract.GetId(memberType.TypeHandle)); _ilg.Ldtoken(memberType); @@ -678,9 +683,9 @@ private LocalBuilder UnwrapNullableObject(LocalBuilder memberValue)// Leaves !Ha { Type innerType = memberType.GetGenericArguments()[0]; _ilg.Dup(); - _ilg.Call(typeof(Nullable<>).MakeGenericType(innerType).GetMethod("get_HasValue")); + _ilg.Call(typeof(Nullable<>).MakeGenericType(innerType).GetMethod("get_HasValue")!); _ilg.Brfalse(onNull); - _ilg.Call(typeof(Nullable<>).MakeGenericType(innerType).GetMethod("get_Value")); + _ilg.Call(typeof(Nullable<>).MakeGenericType(innerType).GetMethod("get_Value")!); memberType = innerType; } memberValue = _ilg.DeclareLocal(memberType, "nullableUnwrappedMemberValue"); @@ -696,13 +701,13 @@ private LocalBuilder UnwrapNullableObject(LocalBuilder memberValue)// Leaves !Ha return memberValue; } - private void WriteStartElement(LocalBuilder nameLocal, int nameIndex) + private void WriteStartElement(LocalBuilder? nameLocal, int nameIndex) { _ilg.Load(_xmlWriterArg); // localName if (nameLocal == null) - _ilg.LoadArrayElement(_memberNamesArg, nameIndex); + _ilg.LoadArrayElement(_memberNamesArg!, nameIndex); else _ilg.Load(nameLocal); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonObjectDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonObjectDataContract.cs index 544dd2a831e2b4..601ddc1843198b 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonObjectDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonObjectDataContract.cs @@ -14,10 +14,10 @@ public JsonObjectDataContract(DataContract traditionalDataContract) { } - public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context) + public override object? ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson? context) { - object obj; - string contentMode = jsonReader.GetAttribute(JsonGlobals.typeString); + object? obj; + string? contentMode = jsonReader.GetAttribute(JsonGlobals.typeString); switch (contentMode) { @@ -53,7 +53,7 @@ public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjec return obj; } - public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle) + public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson? context, RuntimeTypeHandle declaredTypeHandle) { jsonWriter.WriteAttributeString(null, JsonGlobals.typeString, null, JsonGlobals.objectString); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonQNameDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonQNameDataContract.cs index b3992d003fce91..7a9f805fee2996 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonQNameDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonQNameDataContract.cs @@ -16,7 +16,7 @@ public JsonQNameDataContract(QNameDataContract traditionalQNameDataContract) { } - public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context) + public override object? ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson? context) { if (context == null) { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonReaderDelegator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonReaderDelegator.cs index f567fe82995176..d1ae4d947ae9a1 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonReaderDelegator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonReaderDelegator.cs @@ -4,26 +4,27 @@ using System.Xml; using System.Runtime.Serialization; using System.Globalization; +using System.Diagnostics.CodeAnalysis; namespace System.Runtime.Serialization.Json { internal class JsonReaderDelegator : XmlReaderDelegator { - private readonly DateTimeFormat _dateTimeFormat; - private DateTimeArrayJsonHelperWithString _dateTimeArrayHelper; + private readonly DateTimeFormat? _dateTimeFormat; + private DateTimeArrayJsonHelperWithString? _dateTimeArrayHelper; public JsonReaderDelegator(XmlReader reader) : base(reader) { } - public JsonReaderDelegator(XmlReader reader, DateTimeFormat dateTimeFormat) + public JsonReaderDelegator(XmlReader reader, DateTimeFormat? dateTimeFormat) : this(reader) { _dateTimeFormat = dateTimeFormat; } - internal XmlDictionaryReaderQuotas ReaderQuotas + internal XmlDictionaryReaderQuotas? ReaderQuotas { get { @@ -139,7 +140,7 @@ internal override DateTime ReadContentAsDateTime() return ParseJsonDate(ReadContentAsString(), _dateTimeFormat); } - internal static DateTime ParseJsonDate(string originalDateTimeValue, DateTimeFormat dateTimeFormat) + internal static DateTime ParseJsonDate(string originalDateTimeValue, DateTimeFormat? dateTimeFormat) { if (dateTimeFormat == null) { @@ -241,14 +242,14 @@ public override bool TryReadDateTimeArray(XmlObjectSerializerReadContext context internal override bool TryReadDateTimeArray(XmlObjectSerializerReadContext context, #endif XmlDictionaryString itemName, XmlDictionaryString itemNamespace, - int arrayLength, out DateTime[] array) + int arrayLength, [NotNullWhen(true)] out DateTime[]? array) { return TryReadJsonDateTimeArray(context, itemName, itemNamespace, arrayLength, out array); } internal bool TryReadJsonDateTimeArray(XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, - int arrayLength, out DateTime[] array) + int arrayLength, [NotNullWhen(true)] out DateTime[]? array) { if ((dictionaryReader == null) || (arrayLength != -1)) { @@ -264,9 +265,9 @@ internal bool TryReadJsonDateTimeArray(XmlObjectSerializerReadContext context, private class DateTimeArrayJsonHelperWithString : ArrayHelper { - private readonly DateTimeFormat _dateTimeFormat; + private readonly DateTimeFormat? _dateTimeFormat; - public DateTimeArrayJsonHelperWithString(DateTimeFormat dateTimeFormat) + public DateTimeArrayJsonHelperWithString(DateTimeFormat? dateTimeFormat) { _dateTimeFormat = dateTimeFormat; } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonReaderWriterFactory.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonReaderWriterFactory.cs index fd1a83b874b8d4..888c613a188eed 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonReaderWriterFactory.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonReaderWriterFactory.cs @@ -30,7 +30,7 @@ public static XmlDictionaryReader CreateJsonReader(byte[] buffer, XmlDictionaryR return CreateJsonReader(buffer, 0, buffer.Length, null, quotas, null); } - public static XmlDictionaryReader CreateJsonReader(Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose) + public static XmlDictionaryReader CreateJsonReader(Stream stream, Encoding? encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose? onClose) { XmlJsonReader reader = new XmlJsonReader(); reader.SetInput(stream, encoding, quotas, onClose); @@ -42,7 +42,7 @@ public static XmlDictionaryReader CreateJsonReader(byte[] buffer, int offset, in return CreateJsonReader(buffer, offset, count, null, quotas, null); } - public static XmlDictionaryReader CreateJsonReader(byte[] buffer, int offset, int count, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose) + public static XmlDictionaryReader CreateJsonReader(byte[] buffer, int offset, int count, Encoding? encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose? onClose) { XmlJsonReader reader = new XmlJsonReader(); reader.SetInput(buffer, offset, count, encoding, quotas, onClose); @@ -69,7 +69,7 @@ public static XmlDictionaryWriter CreateJsonWriter(Stream stream, Encoding encod return CreateJsonWriter(stream, encoding, ownsStream, indent, JsonReaderWriterFactory.DefaultIndentChars); } - public static XmlDictionaryWriter CreateJsonWriter(Stream stream, Encoding encoding, bool ownsStream, bool indent, string indentChars) + public static XmlDictionaryWriter CreateJsonWriter(Stream stream, Encoding encoding, bool ownsStream, bool indent, string? indentChars) { XmlJsonWriter writer = new XmlJsonWriter(indent, indentChars); writer.SetOutput(stream, encoding, ownsStream); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonStringDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonStringDataContract.cs index 5e4236c6db98b8..e9e1d3c5d77c45 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonStringDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonStringDataContract.cs @@ -16,7 +16,7 @@ public JsonStringDataContract(StringDataContract traditionalStringDataContract) { } - public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context) + public override object? ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson? context) { if (context == null) { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonUriDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonUriDataContract.cs index ef9f909d0ab2e9..5e5605931c44f9 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonUriDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonUriDataContract.cs @@ -16,7 +16,7 @@ public JsonUriDataContract(UriDataContract traditionalUriDataContract) { } - public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context) + public override object? ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson? context) { if (context == null) { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonWriterDelegator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonWriterDelegator.cs index 834e58b77da945..0ed5f9f7d5a4c5 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonWriterDelegator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonWriterDelegator.cs @@ -8,14 +8,14 @@ namespace System.Runtime.Serialization.Json { internal class JsonWriterDelegator : XmlWriterDelegator { - private readonly DateTimeFormat _dateTimeFormat; + private readonly DateTimeFormat? _dateTimeFormat; public JsonWriterDelegator(XmlWriter writer) : base(writer) { } - public JsonWriterDelegator(XmlWriter writer, DateTimeFormat dateTimeFormat) + public JsonWriterDelegator(XmlWriter writer, DateTimeFormat? dateTimeFormat) : this(writer) { _dateTimeFormat = dateTimeFormat; @@ -26,7 +26,7 @@ internal override void WriteChar(char value) WriteString(XmlConvert.ToString(value)); } - internal override void WriteBase64(byte[] bytes) + internal override void WriteBase64(byte[]? bytes) { if (bytes == null) { @@ -118,7 +118,7 @@ internal override void WriteInt(int value) } - internal void WriteJsonBooleanArray(bool[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) + internal void WriteJsonBooleanArray(bool[] value, XmlDictionaryString itemName, XmlDictionaryString? itemNamespace) { for (int i = 0; i < value.Length; i++) { @@ -126,7 +126,7 @@ internal void WriteJsonBooleanArray(bool[] value, XmlDictionaryString itemName, } } - internal void WriteJsonDateTimeArray(DateTime[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) + internal void WriteJsonDateTimeArray(DateTime[] value, XmlDictionaryString itemName, XmlDictionaryString? itemNamespace) { for (int i = 0; i < value.Length; i++) { @@ -134,7 +134,7 @@ internal void WriteJsonDateTimeArray(DateTime[] value, XmlDictionaryString itemN } } - internal void WriteJsonDecimalArray(decimal[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) + internal void WriteJsonDecimalArray(decimal[] value, XmlDictionaryString itemName, XmlDictionaryString? itemNamespace) { for (int i = 0; i < value.Length; i++) { @@ -142,7 +142,7 @@ internal void WriteJsonDecimalArray(decimal[] value, XmlDictionaryString itemNam } } - internal void WriteJsonInt32Array(int[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) + internal void WriteJsonInt32Array(int[] value, XmlDictionaryString itemName, XmlDictionaryString? itemNamespace) { for (int i = 0; i < value.Length; i++) { @@ -150,7 +150,7 @@ internal void WriteJsonInt32Array(int[] value, XmlDictionaryString itemName, Xml } } - internal void WriteJsonInt64Array(long[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) + internal void WriteJsonInt64Array(long[] value, XmlDictionaryString itemName, XmlDictionaryString? itemNamespace) { for (int i = 0; i < value.Length; i++) { @@ -217,7 +217,7 @@ private void WriteDateTimeInDefaultFormat(DateTime value) writer.WriteString(JsonGlobals.DateTimeEndGuardReader); } - internal void WriteJsonSingleArray(float[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) + internal void WriteJsonSingleArray(float[] value, XmlDictionaryString itemName, XmlDictionaryString? itemNamespace) { for (int i = 0; i < value.Length; i++) { @@ -225,7 +225,7 @@ internal void WriteJsonSingleArray(float[] value, XmlDictionaryString itemName, } } - internal void WriteJsonDoubleArray(double[] value, XmlDictionaryString itemName, XmlDictionaryString itemNamespace) + internal void WriteJsonDoubleArray(double[] value, XmlDictionaryString itemName, XmlDictionaryString? itemNamespace) { for (int i = 0; i < value.Length; i++) { @@ -233,7 +233,7 @@ internal void WriteJsonDoubleArray(double[] value, XmlDictionaryString itemName, } } - internal override void WriteStartElement(string prefix, string localName, string ns) + internal override void WriteStartElement(string? prefix, string localName, string? ns) { if (localName != null && localName.Length == 0) { @@ -242,7 +242,7 @@ internal override void WriteStartElement(string prefix, string localName, string } else { - base.WriteStartElement(prefix, localName, ns); + base.WriteStartElement(prefix, localName!, ns); } } } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonXmlDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonXmlDataContract.cs index dffbb13bc59acd..0dea02feddb5e6 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonXmlDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/JsonXmlDataContract.cs @@ -15,7 +15,7 @@ public JsonXmlDataContract(XmlDataContract traditionalXmlDataContract) { } - public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson context) + public override object? ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjectSerializerReadContextComplexJson? context) { string xmlContent = jsonReader.ReadElementContentAsString(); @@ -23,8 +23,8 @@ public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjec GetKnownTypesFromContext(context, (context == null) ? null : context.SerializerKnownTypeList), 1, false, false); // maxItemsInObjectGraph // ignoreExtensionDataObject // preserveObjectReferences MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(xmlContent)); - object xmlValue; - XmlDictionaryReaderQuotas quotas = ((JsonReaderDelegator)jsonReader).ReaderQuotas; + object? xmlValue; + XmlDictionaryReaderQuotas? quotas = ((JsonReaderDelegator)jsonReader).ReaderQuotas; if (quotas == null) { xmlValue = dataContractSerializer.ReadObject(memoryStream); @@ -40,7 +40,7 @@ public override object ReadJsonValueCore(XmlReaderDelegator jsonReader, XmlObjec return xmlValue; } - public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, RuntimeTypeHandle declaredTypeHandle) + public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object obj, XmlObjectSerializerWriteContextComplexJson? context, RuntimeTypeHandle declaredTypeHandle) { DataContractSerializer dataContractSerializer = new DataContractSerializer(Type.GetTypeFromHandle(declaredTypeHandle), GetKnownTypesFromContext(context, (context == null) ? null : context.SerializerKnownTypeList), 1, false, false); // maxItemsInObjectGraph // ignoreExtensionDataObject // preserveObjectReferences @@ -52,7 +52,7 @@ public override void WriteJsonValueCore(XmlWriterDelegator jsonWriter, object ob jsonWriter.WriteString(serialized); } - private List GetKnownTypesFromContext(XmlObjectSerializerContext context, IList serializerKnownTypeList) + private List GetKnownTypesFromContext(XmlObjectSerializerContext? context, IList? serializerKnownTypeList) { List knownTypesList = new List(); if (context != null) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/ReflectionJsonFormatReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/ReflectionJsonFormatReader.cs index d97393fc789988..dae0e1b19128f8 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/ReflectionJsonFormatReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/ReflectionJsonFormatReader.cs @@ -25,7 +25,7 @@ public ReflectionJsonClassReader(ClassDataContract classDataContract) _reflectionReader = new ReflectionJsonReader(); } - public object ReflectionReadClass(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContextComplexJson context, XmlDictionaryString emptyDictionaryString, XmlDictionaryString[] memberNames) + public object ReflectionReadClass(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContextComplexJson? context, XmlDictionaryString emptyDictionaryString, XmlDictionaryString[]? memberNames) { Debug.Assert(_classContract != null); return _reflectionReader.ReflectionReadClass(xmlReader, context, memberNames, null /*memberNamespaces*/, _classContract); @@ -49,12 +49,12 @@ public void ReflectionReadGetOnlyCollection(XmlReaderDelegator xmlReader, XmlObj internal sealed class ReflectionJsonReader : ReflectionReader { - protected override void ReflectionReadMembers(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, ClassDataContract classContract, ref object obj) + protected override void ReflectionReadMembers(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString[] memberNames, XmlDictionaryString[]? memberNamespaces, ClassDataContract classContract, ref object obj) { var jsonContext = context as XmlObjectSerializerReadContextComplexJson; Debug.Assert(jsonContext != null); - int memberCount = classContract.MemberNames.Length; + int memberCount = classContract.MemberNames!.Length; context.IncrementItemCount(memberCount); DataMember[] members = new DataMember[memberCount]; @@ -62,7 +62,7 @@ protected override void ReflectionReadMembers(XmlReaderDelegator xmlReader, XmlO int memberIndex = -1; - ExtensionDataObject extensionData = null; + ExtensionDataObject? extensionData = null; if (classContract.HasExtensionData) { @@ -102,7 +102,7 @@ protected override string GetCollectionContractNamespace(CollectionDataContract return string.Empty; } - protected override object ReflectionReadDictionaryItem(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, CollectionDataContract collectionContract) + protected override object? ReflectionReadDictionaryItem(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, CollectionDataContract collectionContract) { var jsonContext = context as XmlObjectSerializerReadContextComplexJson; Debug.Assert(jsonContext != null); @@ -113,7 +113,7 @@ protected override object ReflectionReadDictionaryItem(XmlReaderDelegator xmlRea return DataContractJsonSerializer.ReadJsonValue(itemContract, xmlReader, jsonContext); } - protected override bool ReflectionReadSpecialCollection(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, CollectionDataContract collectionContract, object resultCollection) + protected override bool ReflectionReadSpecialCollection(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, CollectionDataContract collectionContract, object? resultCollection) { var jsonContext = context as XmlObjectSerializerReadContextComplexJson; Debug.Assert(jsonContext != null); @@ -128,7 +128,7 @@ protected override bool ReflectionReadSpecialCollection(XmlReaderDelegator xmlRe return false; } - private void ReadSimpleDictionary(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, CollectionDataContract collectionContract, Type keyValueType, object dictionary) + private void ReadSimpleDictionary(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, CollectionDataContract collectionContract, Type keyValueType, object? dictionary) { Type[] keyValueTypes = keyValueType.GetGenericArguments(); Type keyType = keyValueTypes[0]; @@ -142,7 +142,7 @@ private void ReadSimpleDictionary(XmlReaderDelegator xmlReader, XmlObjectSeriali } ClassDataContract keyValueDataContract = (ClassDataContract)collectionContract.ItemContract; - DataContract keyDataContract = keyValueDataContract.Members[0].MemberTypeContract; + DataContract keyDataContract = keyValueDataContract.Members![0].MemberTypeContract; KeyParseMode keyParseMode = KeyParseMode.Fail; @@ -207,7 +207,7 @@ private void ReadSimpleDictionary(XmlReaderDelegator xmlReader, XmlObjectSeriali TypeCode.UInt16 => ushort.Parse(keyString), TypeCode.UInt32 => uint.Parse(keyString), TypeCode.UInt64 => ulong.Parse(keyString), - _ => keyDataContract.ParseMethod.Invoke(null, new object[] { keyString }), + _ => keyDataContract.ParseMethod!.Invoke(null, new object[] { keyString })!, }; } else @@ -220,9 +220,9 @@ private void ReadSimpleDictionary(XmlReaderDelegator xmlReader, XmlObjectSeriali throw new NotImplementedException(SR.Format(SR.MustBeGreaterThanZero, keyTypeNullableDepth)); } - object pairValue = ReflectionReadValue(xmlReader, context, valueType, string.Empty, string.Empty); - + object? pairValue = ReflectionReadValue(xmlReader, context, valueType, string.Empty, string.Empty); + Debug.Assert(dictionary != null); ((IDictionary)dictionary).Add(pairKey, pairValue); } } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/ReflectionJsonFormatWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/ReflectionJsonFormatWriter.cs index 23ec559dc89a78..3fd8d58bd346ef 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/ReflectionJsonFormatWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/ReflectionJsonFormatWriter.cs @@ -4,6 +4,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Diagnostics; using System.Linq; using System.Reflection; using System.Text; @@ -16,14 +17,14 @@ internal class ReflectionJsonFormatWriter { private readonly ReflectionJsonClassWriter _reflectionClassWriter = new ReflectionJsonClassWriter(); - public void ReflectionWriteClass(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, ClassDataContract classContract, XmlDictionaryString[] memberNames) + public void ReflectionWriteClass(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, ClassDataContract classContract, XmlDictionaryString[]? memberNames) { _reflectionClassWriter.ReflectionWriteClass(xmlWriter, obj, context, classContract, memberNames); } public void ReflectionWriteCollection(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContextComplexJson context, CollectionDataContract collectionContract) { - JsonWriterDelegator jsonWriter = xmlWriter as JsonWriterDelegator; + JsonWriterDelegator? jsonWriter = xmlWriter as JsonWriterDelegator; if (jsonWriter == null) { throw new ArgumentException(nameof(xmlWriter)); @@ -40,7 +41,7 @@ public void ReflectionWriteCollection(XmlWriterDelegator xmlWriter, object obj, ReflectionWriteArrayAttribute(jsonWriter); Array array = (Array)obj; - PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType); + PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType); for (int i = 0; i < array.Length; ++i) { _reflectionClassWriter.ReflectionWriteStartElement(jsonWriter, itemName); @@ -64,14 +65,14 @@ public void ReflectionWriteCollection(XmlWriterDelegator xmlWriter, object obj, { ReflectionWriteObjectAttribute(jsonWriter); Type[] itemTypeGenericArguments = collectionContract.ItemType.GetGenericArguments(); - Type dictionaryValueType = itemTypeGenericArguments.Length == 2 ? itemTypeGenericArguments[1] : null; + Type? dictionaryValueType = itemTypeGenericArguments.Length == 2 ? itemTypeGenericArguments[1] : null; while (enumerator.MoveNext()) { object current = enumerator.Current; - object key = ((IKeyValue)current).Key; - object value = ((IKeyValue)current).Value; - _reflectionClassWriter.ReflectionWriteStartElement(jsonWriter, key.ToString()); + object key = ((IKeyValue)current).Key!; + object value = ((IKeyValue)current).Value!; + _reflectionClassWriter.ReflectionWriteStartElement(jsonWriter, key.ToString()!); _reflectionClassWriter.ReflectionWriteValue(jsonWriter, context, dictionaryValueType ?? value.GetType(), value, false, primitiveContractForParamType: null); _reflectionClassWriter.ReflectionWriteEndElement(jsonWriter); } @@ -80,7 +81,7 @@ public void ReflectionWriteCollection(XmlWriterDelegator xmlWriter, object obj, { ReflectionWriteArrayAttribute(jsonWriter); - PrimitiveDataContract primitiveContractForType = PrimitiveDataContract.GetPrimitiveDataContract(collectionContract.UnderlyingType); + PrimitiveDataContract? primitiveContractForType = PrimitiveDataContract.GetPrimitiveDataContract(collectionContract.UnderlyingType); if (primitiveContractForType != null && primitiveContractForType.UnderlyingType != Globals.TypeOfObject) { while (enumerator.MoveNext()) @@ -95,8 +96,8 @@ public void ReflectionWriteCollection(XmlWriterDelegator xmlWriter, object obj, Type elementType = collectionContract.GetCollectionElementType(); bool isDictionary = collectionContract.Kind == CollectionKind.Dictionary || collectionContract.Kind == CollectionKind.GenericDictionary; - DataContract itemContract = null; - JsonDataContract jsonDataContract = null; + DataContract? itemContract = null; + JsonDataContract? jsonDataContract = null; if (isDictionary) { itemContract = XmlObjectSerializerWriteContextComplexJson.GetRevisedItemContract(collectionContract.ItemContract); @@ -110,7 +111,7 @@ public void ReflectionWriteCollection(XmlWriterDelegator xmlWriter, object obj, _reflectionClassWriter.ReflectionWriteStartElement(jsonWriter, itemName); if (isDictionary) { - jsonDataContract.WriteJsonValue(jsonWriter, current, context, collectionContract.ItemType.TypeHandle); + jsonDataContract!.WriteJsonValue(jsonWriter, current, context, collectionContract.ItemType.TypeHandle); } else { @@ -135,11 +136,11 @@ private void ReflectionWriteObjectAttribute(XmlWriterDelegator xmlWriter) private bool ReflectionTryWritePrimitiveArray(JsonWriterDelegator jsonWriter, object obj, Type underlyingType, Type itemType, XmlDictionaryString collectionItemName) { - PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType); + PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType); if (primitiveContract == null) return false; - XmlDictionaryString itemNamespace = null; + XmlDictionaryString? itemNamespace = null; switch (itemType.GetTypeCode()) { @@ -189,14 +190,16 @@ private void ReflectionWriteArrayAttribute(XmlWriterDelegator xmlWriter) internal class ReflectionJsonClassWriter : ReflectionClassWriter { - protected override int ReflectionWriteMembers(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, ClassDataContract classContract, ClassDataContract derivedMostClassContract, int childElementIndex, XmlDictionaryString[] memberNames) + protected override int ReflectionWriteMembers(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, ClassDataContract classContract, ClassDataContract derivedMostClassContract, int childElementIndex, XmlDictionaryString[]? memberNames) { + Debug.Assert(memberNames != null); + int memberCount = (classContract.BaseContract == null) ? 0 : ReflectionWriteMembers(xmlWriter, obj, context, classContract.BaseContract, derivedMostClassContract, childElementIndex, memberNames); childElementIndex += memberCount; - context.IncrementItemCount(classContract.Members.Count); + context.IncrementItemCount(classContract.Members!.Count); for (int i = 0; i < classContract.Members.Count; i++, memberCount++) { DataMember member = classContract.Members[i]; @@ -212,11 +215,11 @@ protected override int ReflectionWriteMembers(XmlWriterDelegator xmlWriter, obje bool shouldWriteValue = true; - object memberValue = null; + object? memberValue = null; if (!member.EmitDefaultValue) { memberValue = ReflectionGetMemberValue(obj, member); - object defaultValue = XmlFormatGeneratorStatics.GetDefaultValue(memberType); + object? defaultValue = XmlFormatGeneratorStatics.GetDefaultValue(memberType); if ((memberValue == null && defaultValue == null) || (memberValue != null && memberValue.Equals(defaultValue))) { @@ -235,8 +238,8 @@ protected override int ReflectionWriteMembers(XmlWriterDelegator xmlWriter, obje { memberValue = ReflectionGetMemberValue(obj, member); } - bool requiresNameAttribute = DataContractJsonSerializerImpl.CheckIfXmlNameRequiresMapping(classContract.MemberNames[i]); - PrimitiveDataContract primitiveContract = member.MemberPrimitiveContract; + bool requiresNameAttribute = DataContractJsonSerializerImpl.CheckIfXmlNameRequiresMapping(classContract.MemberNames![i]); + PrimitiveDataContract? primitiveContract = member.MemberPrimitiveContract; if (requiresNameAttribute || !ReflectionTryWritePrimitive(xmlWriter, context, memberType, memberValue, memberNames[i + childElementIndex] /*name*/, null/*ns*/, primitiveContract)) { // Note: DataContractSerializer has member-conflict logic here to deal with the schema export diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonReader.cs index 4b23e31f6f4d16..b755f9b82c1680 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonReader.cs @@ -7,6 +7,8 @@ using System.Runtime.Serialization; using System.Collections.Generic; using System.Xml; +using System.Diagnostics.CodeAnalysis; +using System.Diagnostics; namespace System.Runtime.Serialization.Json { @@ -274,14 +276,14 @@ internal class XmlJsonReader : XmlBaseReader, IXmlJsonReaderInitializer CharType.None | CharType.FirstName | CharType.Name, // FF (?) }; private bool _buffered; - private byte[] _charactersToSkipOnNextRead; + private byte[]? _charactersToSkipOnNextRead; private JsonComplexTextMode _complexTextMode = JsonComplexTextMode.None; private bool _expectingFirstElementInNonPrimitiveChild; private int _maxBytesPerRead; - private OnXmlDictionaryReaderClose _onReaderClose; + private OnXmlDictionaryReaderClose? _onReaderClose; private bool _readServerTypeElement; private int _scopeDepth; - private JsonNodeType[] _scopes; + private JsonNodeType[]? _scopes; private enum JsonComplexTextMode { @@ -322,7 +324,7 @@ private bool IsReadingCollection { get { - return ((_scopeDepth > 0) && (_scopes[_scopeDepth] == JsonNodeType.Collection)); + return ((_scopeDepth > 0) && (_scopes![_scopeDepth] == JsonNodeType.Collection)); } } @@ -337,7 +339,7 @@ private bool IsReadingComplexText protected override void Dispose(bool disposing) { - OnXmlDictionaryReaderClose onClose = _onReaderClose; + OnXmlDictionaryReaderClose? onClose = _onReaderClose; _onReaderClose = null; ResetState(); if (onClose != null) @@ -369,7 +371,7 @@ public override string GetAttribute(int index) return UnescapeJsonString(base.GetAttribute(index)); } - public override string GetAttribute(string localName, string namespaceUri) + public override string? GetAttribute(string localName, string? namespaceUri) { if (localName != JsonGlobals.typeString) { @@ -377,7 +379,7 @@ public override string GetAttribute(string localName, string namespaceUri) } return base.GetAttribute(localName, namespaceUri); } - public override string GetAttribute(string name) + public override string? GetAttribute(string name) { if (name != JsonGlobals.typeString) { @@ -386,7 +388,7 @@ public override string GetAttribute(string name) return base.GetAttribute(name); } - public override string GetAttribute(XmlDictionaryString localName, XmlDictionaryString namespaceUri) + public override string? GetAttribute(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { if (XmlDictionaryString.GetString(localName) != JsonGlobals.typeString) { @@ -417,6 +419,7 @@ public override bool Read() BufferReader.SetWindow(ElementNode.BufferOffset, _maxBytesPerRead); } + Debug.Assert(_charactersToSkipOnNextRead != null); byte ch; // Skip whitespace before checking EOF @@ -806,8 +809,8 @@ public override int ReadValueChunk(char[] chars, int offset, int count) return base.ReadValueChunk(chars, offset, count); } - public void SetInput(byte[] buffer, int offset, int count, Encoding encoding, XmlDictionaryReaderQuotas quotas, - OnXmlDictionaryReaderClose onClose) + public void SetInput(byte[] buffer, int offset, int count, Encoding? encoding, XmlDictionaryReaderQuotas quotas, + OnXmlDictionaryReaderClose? onClose) { if (buffer == null) { @@ -832,13 +835,13 @@ public void SetInput(byte[] buffer, int offset, int count, Encoding encoding, Xm MoveToInitial(quotas, onClose); ArraySegment seg = JsonEncodingStreamWrapper.ProcessBuffer(buffer, offset, count, encoding); - BufferReader.SetBuffer(seg.Array, seg.Offset, seg.Count, null, null); + BufferReader.SetBuffer(seg.Array!, seg.Offset, seg.Count, null, null); _buffered = true; ResetState(); } - public void SetInput(Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas, - OnXmlDictionaryReaderClose onClose) + public void SetInput(Stream stream, Encoding? encoding, XmlDictionaryReaderQuotas quotas, + OnXmlDictionaryReaderClose? onClose) { if (stream == null) { @@ -853,7 +856,7 @@ public void SetInput(Stream stream, Encoding encoding, XmlDictionaryReaderQuotas ResetState(); } - public override void StartCanonicalization(Stream stream, bool includeComments, string[] inclusivePrefixes) + public override void StartCanonicalization(Stream stream, bool includeComments, string[]? inclusivePrefixes) { throw new NotSupportedException(); } @@ -1080,7 +1083,7 @@ private void EnterJsonScope(JsonNodeType currentNodeType) private JsonNodeType ExitJsonScope() { - JsonNodeType nodeTypeToReturn = _scopes[_scopeDepth]; + JsonNodeType nodeTypeToReturn = _scopes![_scopeDepth]; _scopes[_scopeDepth] = JsonNodeType.None; _scopeDepth--; return nodeTypeToReturn; @@ -1092,7 +1095,7 @@ private JsonNodeType ExitJsonScope() base.MoveToEndElement(); } - private void MoveToInitial(XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose) + private void MoveToInitial(XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose? onClose) { MoveToInitial(quotas); _maxBytesPerRead = quotas.MaxBytesPerRead; @@ -1611,14 +1614,15 @@ private bool TryGetByte(out byte ch) } } - private string UnescapeJsonString(string val) + [return: NotNullIfNotNull("val")] + private string? UnescapeJsonString(string? val) { if (val == null) { return null; } - StringBuilder sb = null; + StringBuilder? sb = null; int startIndex = 0, count = 0; for (int i = 0; i < val.Length; i++) { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonWriter.cs index 3b282919a7a82d..31c8c2ffeaf9b7 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlJsonWriter.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.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; @@ -62,9 +63,9 @@ internal class XmlJsonWriter : XmlDictionaryWriter, IXmlJsonWriterInitializer "\\u001f" }; - private static BinHexEncoding s_binHexEncoding; + private static BinHexEncoding? s_binHexEncoding; - private string _attributeText; + private string? _attributeText; private JsonDataType _dataType; private int _depth; private bool _endElementBuffer; @@ -74,21 +75,21 @@ internal class XmlJsonWriter : XmlDictionaryWriter, IXmlJsonWriterInitializer private bool _isWritingXmlnsAttributeDefaultNs; private NameState _nameState; private JsonNodeType _nodeType; - private JsonNodeWriter _nodeWriter; - private JsonNodeType[] _scopes; - private string _serverTypeValue; + private JsonNodeWriter _nodeWriter = null!; // initialized in SetOutput + private JsonNodeType[]? _scopes; + private string? _serverTypeValue; // Do not use this field's value anywhere other than the WriteState property. // It's OK to set this field's value anywhere and then change the WriteState property appropriately. // If it's necessary to check the WriteState outside WriteState, use the WriteState property. private WriteState _writeState; private bool _wroteServerTypeAttribute; private readonly bool _indent; - private readonly string _indentChars; + private readonly string? _indentChars; private int _indentLevel; public XmlJsonWriter() : this(false, null) { } - public XmlJsonWriter(bool indent, string indentChars) + public XmlJsonWriter(bool indent, string? indentChars) { _indent = indent; if (indent) @@ -122,7 +123,7 @@ private enum NameState WrittenNameWithMapping = 4, } - public override XmlWriterSettings Settings + public override XmlWriterSettings? Settings { // The XmlWriterSettings object used to create this writer instance. // If this writer was not created using the Create method, this property @@ -158,7 +159,7 @@ public override WriteState WriteState } } - public override string XmlLang + public override string? XmlLang { get { return null; } } @@ -184,7 +185,7 @@ private static BinHexEncoding BinHexEncoding private bool IsClosed => (WriteState == WriteState.Closed); - private bool IsWritingCollection => (_depth > 0) && (_scopes[_depth] == JsonNodeType.Collection); + private bool IsWritingCollection => (_depth > 0) && (_scopes![_depth] == JsonNodeType.Collection); private bool IsWritingNameAttribute => (_nameState & NameState.IsWritingNameAttribute) == NameState.IsWritingNameAttribute; @@ -230,7 +231,7 @@ public override void Flush() _nodeWriter.Flush(); } - public override string LookupPrefix(string ns) + public override string? LookupPrefix(string ns) { if (ns == null) { @@ -261,119 +262,120 @@ public void SetOutput(Stream stream, Encoding encoding, bool ownsStream) { throw new ArgumentNullException(nameof(encoding)); } - if (encoding.WebName != Encoding.UTF8.WebName) + Encoding? tempEncoding = encoding; + if (tempEncoding.WebName != Encoding.UTF8.WebName) { - stream = new JsonEncodingStreamWrapper(stream, encoding, false); + stream = new JsonEncodingStreamWrapper(stream, tempEncoding, false); } else { - encoding = null; + tempEncoding = null; } if (_nodeWriter == null) { _nodeWriter = new JsonNodeWriter(); } - _nodeWriter.SetOutput(stream, ownsStream, encoding); + _nodeWriter.SetOutput(stream, ownsStream, tempEncoding); InitializeWriter(); } - public override void WriteArray(string prefix, string localName, string namespaceUri, bool[] array, int offset, int count) + public override void WriteArray(string? prefix, string localName, string? namespaceUri, bool[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } - public override void WriteArray(string prefix, string localName, string namespaceUri, short[] array, int offset, int count) + public override void WriteArray(string? prefix, string localName, string? namespaceUri, short[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } - public override void WriteArray(string prefix, string localName, string namespaceUri, int[] array, int offset, int count) + public override void WriteArray(string? prefix, string localName, string? namespaceUri, int[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } - public override void WriteArray(string prefix, string localName, string namespaceUri, long[] array, int offset, int count) + public override void WriteArray(string? prefix, string localName, string? namespaceUri, long[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } - public override void WriteArray(string prefix, string localName, string namespaceUri, float[] array, int offset, int count) + public override void WriteArray(string? prefix, string localName, string? namespaceUri, float[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } - public override void WriteArray(string prefix, string localName, string namespaceUri, double[] array, int offset, int count) + public override void WriteArray(string? prefix, string localName, string? namespaceUri, double[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } - public override void WriteArray(string prefix, string localName, string namespaceUri, decimal[] array, int offset, int count) + public override void WriteArray(string? prefix, string localName, string? namespaceUri, decimal[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } - public override void WriteArray(string prefix, string localName, string namespaceUri, DateTime[] array, int offset, int count) + public override void WriteArray(string? prefix, string localName, string? namespaceUri, DateTime[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } - public override void WriteArray(string prefix, string localName, string namespaceUri, Guid[] array, int offset, int count) + public override void WriteArray(string? prefix, string localName, string? namespaceUri, Guid[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } - public override void WriteArray(string prefix, string localName, string namespaceUri, TimeSpan[] array, int offset, int count) + public override void WriteArray(string? prefix, string localName, string? namespaceUri, TimeSpan[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } - public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, bool[] array, int offset, int count) + public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, bool[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } - public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, decimal[] array, int offset, int count) + public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, decimal[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } - public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, double[] array, int offset, int count) + public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, double[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } - public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, float[] array, int offset, int count) + public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, float[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } - public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, int[] array, int offset, int count) + public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, int[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } - public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, long[] array, int offset, int count) + public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, long[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } - public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, short[] array, int offset, int count) + public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, short[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } - public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, DateTime[] array, int offset, int count) + public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, DateTime[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } - public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, Guid[] array, int offset, int count) + public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, Guid[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } - public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, TimeSpan[] array, int offset, int count) + public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, TimeSpan[] array, int offset, int count) { throw new NotSupportedException(SR.JsonWriteArrayNotSupported); } @@ -430,7 +432,7 @@ public override void WriteBinHex(byte[] buffer, int index, int count) WriteEscapedJsonString(BinHexEncoding.GetString(buffer, index, count)); } - public override void WriteCData(string text) + public override void WriteCData(string? text) { WriteString(text); } @@ -465,12 +467,12 @@ public override void WriteChars(char[] buffer, int index, int count) WriteString(new string(buffer, index, count)); } - public override void WriteComment(string text) + public override void WriteComment(string? text) { throw new NotSupportedException(SR.Format(SR.JsonMethodNotSupported, "WriteComment")); } - public override void WriteDocType(string name, string pubid, string sysid, string subset) + public override void WriteDocType(string name, string? pubid, string? sysid, string? subset) { throw new NotSupportedException(SR.Format(SR.JsonMethodNotSupported, "WriteDocType")); } @@ -554,7 +556,7 @@ public override void WriteEndAttribute() } else if (IsWritingNameAttribute) { - WriteJsonElementName(_attributeText); + WriteJsonElementName(_attributeText!); _attributeText = null; _nameState = NameState.IsWritingNameWithMapping | NameState.WrittenNameWithMapping; WriteDataTypeServerType(); @@ -680,7 +682,7 @@ public override void WriteEndElement() } } _nodeWriter.WriteText(JsonGlobals.EndObjectChar); - if ((_depth > 0) && _scopes[_depth] == JsonNodeType.Element) + if ((_depth > 0) && _scopes![_depth] == JsonNodeType.Element) { ExitScope(); _endElementBuffer = true; @@ -704,7 +706,7 @@ public override void WriteFullEndElement() WriteEndElement(); } - public override void WriteProcessingInstruction(string name, string text) + public override void WriteProcessingInstruction(string name, string? text) { if (IsClosed) { @@ -722,7 +724,7 @@ public override void WriteProcessingInstruction(string name, string text) } } - public override void WriteQualifiedName(string localName, string ns) + public override void WriteQualifiedName(string localName, string? ns) { if (localName == null) { @@ -770,7 +772,7 @@ public override void WriteRaw(char[] buffer, int index, int count) WriteString(new string(buffer, index, count)); } - public override void WriteStartAttribute(string prefix, string localName, string ns) + public override void WriteStartAttribute(string? prefix, string localName, string? ns) { if (IsClosed) { @@ -898,7 +900,7 @@ public override void WriteStartDocument() } } - public override void WriteStartElement(string prefix, string localName, string ns) + public override void WriteStartElement(string? prefix, string localName, string? ns) { if (localName == null) { @@ -1009,7 +1011,7 @@ public override void WriteStartElement(string prefix, string localName, string n _nodeType = JsonNodeType.Element; } - public override void WriteString(string text) + public override void WriteString(string? text) { if (HasOpenAttribute && (text != null)) { @@ -1084,7 +1086,7 @@ public override void WriteValue(DateTime value) _nodeWriter.WriteDateTimeText(value); } - public override void WriteValue(string value) + public override void WriteValue(string? value) { WriteString(value); } @@ -1132,7 +1134,7 @@ public override void WriteValue(object value) } } - public override void WriteWhitespace(string ws) + public override void WriteWhitespace(string? ws) { if (IsClosed) { @@ -1158,17 +1160,17 @@ public override void WriteWhitespace(string ws) WriteString(ws); } - public override void WriteXmlAttribute(string localName, string value) + public override void WriteXmlAttribute(string localName, string? value) { throw new NotSupportedException(SR.Format(SR.JsonMethodNotSupported, "WriteXmlAttribute")); } - public override void WriteXmlAttribute(XmlDictionaryString localName, XmlDictionaryString value) + public override void WriteXmlAttribute(XmlDictionaryString localName, XmlDictionaryString? value) { throw new NotSupportedException(SR.Format(SR.JsonMethodNotSupported, "WriteXmlAttribute")); } - public override void WriteXmlnsAttribute(string prefix, string namespaceUri) + public override void WriteXmlnsAttribute(string? prefix, string namespaceUri) { if (!IsWritingNameWithMapping) { @@ -1176,7 +1178,7 @@ public override void WriteXmlnsAttribute(string prefix, string namespaceUri) } } - public override void WriteXmlnsAttribute(string prefix, XmlDictionaryString namespaceUri) + public override void WriteXmlnsAttribute(string? prefix, XmlDictionaryString namespaceUri) { if (!IsWritingNameWithMapping) { @@ -1232,7 +1234,7 @@ private void EnterScope(JsonNodeType currentNodeType) private JsonNodeType ExitScope() { - JsonNodeType nodeTypeToReturn = _scopes[_depth]; + JsonNodeType nodeTypeToReturn = _scopes![_depth]; _scopes[_depth] = JsonNodeType.None; _depth--; return nodeTypeToReturn; @@ -1433,7 +1435,7 @@ private void WriteIndent() { for (int i = 0; i < _indentLevel; i++) { - _nodeWriter.WriteText(_indentChars); + _nodeWriter.WriteText(_indentChars!); } } @@ -1536,7 +1538,7 @@ private void WritePrimitiveValue(object value) private void WriteServerTypeAttribute() { - string value = _serverTypeValue; + string? value = _serverTypeValue; JsonDataType oldDataType = _dataType; NameState oldNameState = _nameState; WriteStartElement(JsonGlobals.serverTypeString); @@ -1569,7 +1571,7 @@ private void WriteValue(Array array) { _nodeWriter.WriteText(JsonGlobals.WhitespaceChar); } - WritePrimitiveValue(array.GetValue(i)); + WritePrimitiveValue(array.GetValue(i)!); } _dataType = oldDataType; } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlObjectSerializerReadContextComplexJson.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlObjectSerializerReadContextComplexJson.cs index 0212c484555a2d..39011d6f38b742 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlObjectSerializerReadContextComplexJson.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlObjectSerializerReadContextComplexJson.cs @@ -10,24 +10,16 @@ using System.Runtime.Serialization; using DataContractDictionary = System.Collections.Generic.Dictionary; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; namespace System.Runtime.Serialization.Json { internal class XmlObjectSerializerReadContextComplexJson : XmlObjectSerializerReadContextComplex { - private string _extensionDataValueType; - private readonly DataContractJsonSerializer _jsonSerializer; - private readonly DateTimeFormat _dateTimeFormat; + private string? _extensionDataValueType; + private readonly DateTimeFormat? _dateTimeFormat; private readonly bool _useSimpleDictionaryFormat; - public XmlObjectSerializerReadContextComplexJson(DataContractJsonSerializer serializer, DataContract rootTypeDataContract) - : base(null, int.MaxValue, default(StreamingContext), true) - { - this.rootTypeDataContract = rootTypeDataContract; - this.serializerKnownTypeList = serializer.KnownTypes; - _jsonSerializer = serializer; - } - internal XmlObjectSerializerReadContextComplexJson(DataContractJsonSerializerImpl serializer, DataContract rootTypeDataContract) : base(serializer, serializer.MaxItemsInObjectGraph, default(StreamingContext), false) { @@ -42,12 +34,12 @@ internal static XmlObjectSerializerReadContextComplexJson CreateContext(DataCont return new XmlObjectSerializerReadContextComplexJson(serializer, rootTypeDataContract); } - protected override object ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader) + protected override object? ReadDataContractValue(DataContract dataContract, XmlReaderDelegator reader) { return DataContractJsonSerializerImpl.ReadJsonValue(dataContract, reader, this); } - public int GetJsonMemberIndex(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, int memberIndex, ExtensionDataObject extensionData) + public int GetJsonMemberIndex(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, int memberIndex, ExtensionDataObject? extensionData) { int length = memberNames.Length; if (length != 0) @@ -59,7 +51,7 @@ public int GetJsonMemberIndex(XmlReaderDelegator xmlReader, XmlDictionaryString[ return index; } } - string name; + string? name; if (TryGetJsonLocalName(xmlReader, out name)) { for (int i = 0, index = (memberIndex + 1) % length; i < length; i++, index = (index + 1) % length) @@ -75,7 +67,7 @@ public int GetJsonMemberIndex(XmlReaderDelegator xmlReader, XmlDictionaryString[ return length; } - internal IList SerializerKnownTypeList + internal IList? SerializerKnownTypeList { get { @@ -96,7 +88,7 @@ protected override void StartReadExtensionDataValue(XmlReaderDelegator xmlReader _extensionDataValueType = xmlReader.GetAttribute(JsonGlobals.typeString); } - protected override IDataNode ReadPrimitiveExtensionDataValue(XmlReaderDelegator xmlReader, string dataContractName, string dataContractNamespace) + protected override IDataNode ReadPrimitiveExtensionDataValue(XmlReaderDelegator xmlReader, string? dataContractName, string? dataContractNamespace) { IDataNode dataNode; @@ -244,14 +236,14 @@ internal static XmlQualifiedName ParseQualifiedName(string qname) } return new XmlQualifiedName(name, ns); } - internal override DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type type) + internal override DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type? type) { DataContract dataContract = base.GetDataContract(typeHandle, type); DataContractJsonSerializer.CheckIfTypeIsReference(dataContract); return dataContract; } - internal override DataContract GetDataContractSkipValidation(int typeId, RuntimeTypeHandle typeHandle, Type type) + internal override DataContract GetDataContractSkipValidation(int typeId, RuntimeTypeHandle typeHandle, Type? type) { DataContract dataContract = base.GetDataContractSkipValidation(typeId, typeHandle, type); DataContractJsonSerializer.CheckIfTypeIsReference(dataContract); @@ -265,7 +257,7 @@ internal override DataContract GetDataContract(int id, RuntimeTypeHandle typeHan return dataContract; } - internal static bool TryGetJsonLocalName(XmlReaderDelegator xmlReader, out string name) + internal static bool TryGetJsonLocalName(XmlReaderDelegator xmlReader, [NotNullWhen(true)] out string? name) { if (xmlReader.IsStartElement(JsonGlobals.itemDictionaryString, JsonGlobals.itemDictionaryString)) { @@ -281,7 +273,7 @@ internal static bool TryGetJsonLocalName(XmlReaderDelegator xmlReader, out strin public static string GetJsonMemberName(XmlReaderDelegator xmlReader) { - string name; + string? name; if (!TryGetJsonLocalName(xmlReader, out name)) { name = xmlReader.LocalName; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlObjectSerializerWriteContextComplexJson.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlObjectSerializerWriteContextComplexJson.cs index c3d9d7c4f6c538..15d0335e7dbae6 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlObjectSerializerWriteContextComplexJson.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Json/XmlObjectSerializerWriteContextComplexJson.cs @@ -9,30 +9,16 @@ using System.Collections; using System.IO; using DataContractDictionary = System.Collections.Generic.Dictionary; +using System.Diagnostics.CodeAnalysis; namespace System.Runtime.Serialization.Json { internal class XmlObjectSerializerWriteContextComplexJson : XmlObjectSerializerWriteContextComplex { - private readonly DataContractJsonSerializer _jsonSerializer; private readonly EmitTypeInformation _emitXsiType; private bool _perCallXsiTypeAlreadyEmitted; private readonly bool _useSimpleDictionaryFormat; - public XmlObjectSerializerWriteContextComplexJson(DataContractJsonSerializer serializer, DataContract rootTypeDataContract) - : base(null, int.MaxValue, default(StreamingContext), true) - - { - _jsonSerializer = serializer; - this.rootTypeDataContract = rootTypeDataContract; - this.serializerKnownTypeList = serializer.knownTypeList; - } - - internal static XmlObjectSerializerWriteContextComplexJson CreateContext(DataContractJsonSerializer serializer, DataContract rootTypeDataContract) - { - return new XmlObjectSerializerWriteContextComplexJson(serializer, rootTypeDataContract); - } - internal static XmlObjectSerializerWriteContextComplexJson CreateContext(DataContractJsonSerializerImpl serializer, DataContract rootTypeDataContract) { return new XmlObjectSerializerWriteContextComplexJson(serializer, rootTypeDataContract); @@ -48,7 +34,7 @@ internal XmlObjectSerializerWriteContextComplexJson(DataContractJsonSerializerIm _useSimpleDictionaryFormat = serializer.UseSimpleDictionaryFormat; } - internal IList SerializerKnownTypeList + internal IList? SerializerKnownTypeList { get { @@ -79,7 +65,7 @@ internal override void WriteArraySize(XmlWriterDelegator xmlWriter, int size) //Noop } - protected override void WriteTypeInfo(XmlWriterDelegator writer, string dataContractName, string dataContractNamespace) + protected override void WriteTypeInfo(XmlWriterDelegator writer, string dataContractName, string? dataContractNamespace) { if (_emitXsiType != EmitTypeInformation.Never) { @@ -170,7 +156,7 @@ protected override void WriteDataContractValue(DataContract dataContract, XmlWri JsonDataContract jsonDataContract = JsonDataContract.GetJsonDataContract(dataContract); if (_emitXsiType == EmitTypeInformation.Always && !_perCallXsiTypeAlreadyEmitted && RequiresJsonTypeInfo(dataContract)) { - WriteTypeInfo(xmlWriter, jsonDataContract.TypeName); + WriteTypeInfo(xmlWriter, jsonDataContract.TypeName!); } _perCallXsiTypeAlreadyEmitted = false; DataContractJsonSerializerImpl.WriteJsonValue(jsonDataContract, xmlWriter, obj, this, declaredTypeHandle); @@ -186,7 +172,7 @@ internal XmlDictionaryString CollectionItemName get { return JsonGlobals.itemDictionaryString; } } - protected override void SerializeWithXsiType(XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle objectTypeHandle, Type objectType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle, Type declaredType) + protected override void SerializeWithXsiType(XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle objectTypeHandle, Type? objectType, int declaredTypeID, RuntimeTypeHandle declaredTypeHandle, Type declaredType) { DataContract dataContract; bool verifyKnownType = false; @@ -229,8 +215,8 @@ private void HandleCollectionAssignedToObject(Type declaredType, ref DataContrac if (((CollectionDataContract)dataContract).Kind == CollectionKind.Dictionary) { // Convert non-generic dictionary to generic dictionary - IDictionary dictionaryObj = obj as IDictionary; - Dictionary genericDictionaryObj = new Dictionary(dictionaryObj.Count); + IDictionary dictionaryObj = (obj as IDictionary)!; + Dictionary genericDictionaryObj = new Dictionary(dictionaryObj.Count); // Manual use of IDictionaryEnumerator instead of foreach to avoid DictionaryEntry box allocations. IDictionaryEnumerator e = dictionaryObj.GetEnumerator(); try @@ -254,7 +240,7 @@ private void HandleCollectionAssignedToObject(Type declaredType, ref DataContrac internal override void SerializeWithXsiTypeAtTopLevel(DataContract dataContract, XmlWriterDelegator xmlWriter, object obj, RuntimeTypeHandle originalDeclaredTypeHandle, Type graphType) { bool verifyKnownType = false; - Type declaredType = rootTypeDataContract.UnderlyingType; + Type declaredType = rootTypeDataContract!.UnderlyingType; bool isDeclaredTypeInterface = declaredType.IsInterface; if (!(isDeclaredTypeInterface && CollectionDataContract.IsCollectionInterface(declaredType)) @@ -354,7 +340,8 @@ internal void WriteJsonISerializable(XmlWriterDelegator xmlWriter, ISerializable } } - internal static DataContract GetRevisedItemContract(DataContract oldItemContract) + [return: NotNullIfNotNull("oldItemContract")] + internal static DataContract? GetRevisedItemContract(DataContract oldItemContract) { if ((oldItemContract != null) && oldItemContract.UnderlyingType.IsGenericType && @@ -364,14 +351,14 @@ internal static DataContract GetRevisedItemContract(DataContract oldItemContract } return oldItemContract; } - internal override DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type type) + internal override DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type? type) { DataContract dataContract = base.GetDataContract(typeHandle, type); DataContractJsonSerializer.CheckIfTypeIsReference(dataContract); return dataContract; } - internal override DataContract GetDataContractSkipValidation(int typeId, RuntimeTypeHandle typeHandle, Type type) + internal override DataContract GetDataContractSkipValidation(int typeId, RuntimeTypeHandle typeHandle, Type? type) { DataContract dataContract = base.GetDataContractSkipValidation(typeId, typeHandle, type); DataContractJsonSerializer.CheckIfTypeIsReference(dataContract); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/KnownTypeDataContractResolver.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/KnownTypeDataContractResolver.cs index 9b524bdbfaa8e0..79cd6fb42b9939 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/KnownTypeDataContractResolver.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/KnownTypeDataContractResolver.cs @@ -20,7 +20,7 @@ internal KnownTypeDataContractResolver(XmlObjectSerializerContext context) _context = context; } - public override bool TryResolveType(Type type, Type declaredType, DataContractResolver knownTypeResolver, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace) + public override bool TryResolveType(Type type, Type? declaredType, DataContractResolver knownTypeResolver, out XmlDictionaryString? typeName, out XmlDictionaryString? typeNamespace) { if (type == null) { @@ -50,7 +50,7 @@ public override bool TryResolveType(Type type, Type declaredType, DataContractRe } } - public override Type ResolveName(string typeName, string typeNamespace, Type declaredType, DataContractResolver knownTypeResolver) + public override Type? ResolveName(string typeName, string? typeNamespace, Type? declaredType, DataContractResolver knownTypeResolver) { if (typeName == null || typeNamespace == null) return null; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ObjectReferenceStack.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ObjectReferenceStack.cs index f0236022f75f97..7945a647a124d7 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ObjectReferenceStack.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ObjectReferenceStack.cs @@ -14,9 +14,9 @@ internal struct ObjectReferenceStack private const int InitialArraySize = 4; private int _count; - private object[] _objectArray; - private bool[] _isReferenceArray; - private Dictionary _objectDictionary; + private object[]? _objectArray; + private bool[]? _isReferenceArray; + private Dictionary? _objectDictionary; internal void Push(object obj) { @@ -34,7 +34,7 @@ internal void Push(object obj) else { if (_objectDictionary == null) - _objectDictionary = new Dictionary(); + _objectDictionary = new Dictionary(); _objectDictionary.Add(obj, null); _count++; @@ -95,7 +95,7 @@ internal bool Contains(object obj) } for (int i = (currentCount - 1); i >= 0; i--) { - if (object.ReferenceEquals(obj, _objectArray[i]) && _isReferenceArray != null && !_isReferenceArray[i]) + if (object.ReferenceEquals(obj, _objectArray![i]) && _isReferenceArray != null && !_isReferenceArray[i]) return true; } return false; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ObjectToIdCache.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ObjectToIdCache.cs index 8f8b5b83c67f66..dbe86840f9b9fb 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ObjectToIdCache.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ObjectToIdCache.cs @@ -11,7 +11,7 @@ internal class ObjectToIdCache { internal int m_currentCount; internal int[] m_ids; - internal object[] m_objs; + internal object?[] m_objs; internal bool[] m_isWrapped; public ObjectToIdCache() @@ -131,7 +131,7 @@ private void RemoveAt(int position) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.ObjectTableOverflow)); } - private int ComputeStartPosition(object o) + private int ComputeStartPosition(object? o) { return (RuntimeHelpers.GetHashCode(o) & 0x7FFFFFFF) % m_objs.Length; } @@ -140,14 +140,14 @@ private void Rehash() { int size = GetPrime(m_objs.Length + 1); // The lookup does an inherent doubling int[] oldIds = m_ids; - object[] oldObjs = m_objs; + object?[] oldObjs = m_objs; m_ids = new int[size]; m_objs = new object[size]; m_isWrapped = new bool[size]; for (int j = 0; j < oldObjs.Length; j++) { - object obj = oldObjs[j]; + object? obj = oldObjs[j]; if (obj != null) { bool found, isWrapped; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/PrimitiveDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/PrimitiveDataContract.cs index ed1c0090f41ac7..c094c8d4fed4b1 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/PrimitiveDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/PrimitiveDataContract.cs @@ -18,15 +18,15 @@ internal abstract class PrimitiveDataContract : DataContract protected PrimitiveDataContract(Type type, XmlDictionaryString name, XmlDictionaryString ns) : base(new PrimitiveDataContractCriticalHelper(type, name, ns)) { - _helper = base.Helper as PrimitiveDataContractCriticalHelper; + _helper = (base.Helper as PrimitiveDataContractCriticalHelper)!; } - internal static PrimitiveDataContract GetPrimitiveDataContract(Type type) + internal static PrimitiveDataContract? GetPrimitiveDataContract(Type type) { return DataContract.GetBuiltInDataContract(type) as PrimitiveDataContract; } - internal static PrimitiveDataContract GetPrimitiveDataContract(string name, string ns) + internal static PrimitiveDataContract? GetPrimitiveDataContract(string name, string ns) { return DataContract.GetBuiltInDataContract(name, ns) as PrimitiveDataContract; } @@ -34,7 +34,7 @@ internal static PrimitiveDataContract GetPrimitiveDataContract(string name, stri internal abstract string WriteMethodName { get; } internal abstract string ReadMethodName { get; } - public override XmlDictionaryString TopLevelElementNamespace + public override XmlDictionaryString? TopLevelElementNamespace { get { return DictionaryGlobals.SerializationNamespace; } @@ -56,9 +56,9 @@ internal MethodInfo XmlFormatWriterMethod if (_helper.XmlFormatWriterMethod == null) { if (UnderlyingType.IsValueType) - _helper.XmlFormatWriterMethod = typeof(XmlWriterDelegator).GetMethod(WriteMethodName, Globals.ScanAllMembers, new Type[] { UnderlyingType, typeof(XmlDictionaryString), typeof(XmlDictionaryString) }); + _helper.XmlFormatWriterMethod = typeof(XmlWriterDelegator).GetMethod(WriteMethodName, Globals.ScanAllMembers, new Type[] { UnderlyingType, typeof(XmlDictionaryString), typeof(XmlDictionaryString) })!; else - _helper.XmlFormatWriterMethod = typeof(XmlObjectSerializerWriteContext).GetMethod(WriteMethodName, Globals.ScanAllMembers, new Type[] { typeof(XmlWriterDelegator), UnderlyingType, typeof(XmlDictionaryString), typeof(XmlDictionaryString) }); + _helper.XmlFormatWriterMethod = typeof(XmlObjectSerializerWriteContext).GetMethod(WriteMethodName, Globals.ScanAllMembers, new Type[] { typeof(XmlWriterDelegator), UnderlyingType, typeof(XmlDictionaryString), typeof(XmlDictionaryString) })!; } return _helper.XmlFormatWriterMethod; } @@ -71,9 +71,9 @@ internal MethodInfo XmlFormatContentWriterMethod if (_helper.XmlFormatContentWriterMethod == null) { if (UnderlyingType.IsValueType) - _helper.XmlFormatContentWriterMethod = typeof(XmlWriterDelegator).GetMethod(WriteMethodName, Globals.ScanAllMembers, new Type[] { UnderlyingType }); + _helper.XmlFormatContentWriterMethod = typeof(XmlWriterDelegator).GetMethod(WriteMethodName, Globals.ScanAllMembers, new Type[] { UnderlyingType })!; else - _helper.XmlFormatContentWriterMethod = typeof(XmlObjectSerializerWriteContext).GetMethod(WriteMethodName, Globals.ScanAllMembers, new Type[] { typeof(XmlWriterDelegator), UnderlyingType }); + _helper.XmlFormatContentWriterMethod = typeof(XmlObjectSerializerWriteContext).GetMethod(WriteMethodName, Globals.ScanAllMembers, new Type[] { typeof(XmlWriterDelegator), UnderlyingType })!; } return _helper.XmlFormatContentWriterMethod; } @@ -85,13 +85,13 @@ internal MethodInfo XmlFormatReaderMethod { if (_helper.XmlFormatReaderMethod == null) { - _helper.XmlFormatReaderMethod = typeof(XmlReaderDelegator).GetMethod(ReadMethodName, Globals.ScanAllMembers); + _helper.XmlFormatReaderMethod = typeof(XmlReaderDelegator).GetMethod(ReadMethodName, Globals.ScanAllMembers)!; } return _helper.XmlFormatReaderMethod; } } - public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) + public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext? context) { xmlWriter.WriteAnyType(obj); } @@ -118,28 +118,28 @@ protected bool TryReadNullAtTopLevel(XmlReaderDelegator reader) private class PrimitiveDataContractCriticalHelper : DataContract.DataContractCriticalHelper { - private MethodInfo _xmlFormatWriterMethod; - private MethodInfo _xmlFormatContentWriterMethod; - private MethodInfo _xmlFormatReaderMethod; + private MethodInfo? _xmlFormatWriterMethod; + private MethodInfo? _xmlFormatContentWriterMethod; + private MethodInfo? _xmlFormatReaderMethod; internal PrimitiveDataContractCriticalHelper(Type type, XmlDictionaryString name, XmlDictionaryString ns) : base(type) { SetDataContractName(name, ns); } - internal MethodInfo XmlFormatWriterMethod + internal MethodInfo? XmlFormatWriterMethod { get { return _xmlFormatWriterMethod; } set { _xmlFormatWriterMethod = value; } } - internal MethodInfo XmlFormatContentWriterMethod + internal MethodInfo? XmlFormatContentWriterMethod { get { return _xmlFormatContentWriterMethod; } set { _xmlFormatContentWriterMethod = value; } } - internal MethodInfo XmlFormatReaderMethod + internal MethodInfo? XmlFormatReaderMethod { get { return _xmlFormatReaderMethod; } set { _xmlFormatReaderMethod = value; } @@ -160,20 +160,20 @@ internal CharDataContract(XmlDictionaryString name, XmlDictionaryString ns) : ba internal override string WriteMethodName { get { return "WriteChar"; } } internal override string ReadMethodName { get { return "ReadElementContentAsChar"; } } - public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) + public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context) { writer.WriteChar((char)obj); } - public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) + public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { return (context == null) ? reader.ReadElementContentAsChar() : HandleReadValue(reader.ReadElementContentAsChar(), context); } - public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) + public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns) { - xmlWriter.WriteChar((char)obj, name, ns); + xmlWriter.WriteChar((char)obj!, name, ns); } } @@ -191,20 +191,20 @@ public BooleanDataContract() : base(typeof(bool), DictionaryGlobals.BooleanLocal internal override string WriteMethodName { get { return "WriteBoolean"; } } internal override string ReadMethodName { get { return "ReadElementContentAsBoolean"; } } - public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) + public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context) { writer.WriteBoolean((bool)obj); } - public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) + public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { return (context == null) ? reader.ReadElementContentAsBoolean() : HandleReadValue(reader.ReadElementContentAsBoolean(), context); } - public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) + public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns) { - xmlWriter.WriteBoolean((bool)obj, name, ns); + xmlWriter.WriteBoolean((bool)obj!, name, ns); } } @@ -217,20 +217,20 @@ public SignedByteDataContract() : base(typeof(sbyte), DictionaryGlobals.SignedBy internal override string WriteMethodName { get { return "WriteSignedByte"; } } internal override string ReadMethodName { get { return "ReadElementContentAsSignedByte"; } } - public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) + public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context) { writer.WriteSignedByte((sbyte)obj); } - public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) + public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { return (context == null) ? reader.ReadElementContentAsSignedByte() : HandleReadValue(reader.ReadElementContentAsSignedByte(), context); } - public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) + public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns) { - xmlWriter.WriteSignedByte((sbyte)obj, name, ns); + xmlWriter.WriteSignedByte((sbyte)obj!, name, ns); } } @@ -243,20 +243,20 @@ public UnsignedByteDataContract() : base(typeof(byte), DictionaryGlobals.Unsigne internal override string WriteMethodName { get { return "WriteUnsignedByte"; } } internal override string ReadMethodName { get { return "ReadElementContentAsUnsignedByte"; } } - public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) + public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context) { writer.WriteUnsignedByte((byte)obj); } - public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) + public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { return (context == null) ? reader.ReadElementContentAsUnsignedByte() : HandleReadValue(reader.ReadElementContentAsUnsignedByte(), context); } - public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) + public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns) { - xmlWriter.WriteUnsignedByte((byte)obj, name, ns); + xmlWriter.WriteUnsignedByte((byte)obj!, name, ns); } } @@ -269,20 +269,20 @@ public ShortDataContract() : base(typeof(short), DictionaryGlobals.ShortLocalNam internal override string WriteMethodName { get { return "WriteShort"; } } internal override string ReadMethodName { get { return "ReadElementContentAsShort"; } } - public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) + public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context) { writer.WriteShort((short)obj); } - public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) + public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { return (context == null) ? reader.ReadElementContentAsShort() : HandleReadValue(reader.ReadElementContentAsShort(), context); } - public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) + public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns) { - xmlWriter.WriteShort((short)obj, name, ns); + xmlWriter.WriteShort((short)obj!, name, ns); } } @@ -295,20 +295,20 @@ public UnsignedShortDataContract() : base(typeof(ushort), DictionaryGlobals.Unsi internal override string WriteMethodName { get { return "WriteUnsignedShort"; } } internal override string ReadMethodName { get { return "ReadElementContentAsUnsignedShort"; } } - public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) + public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context) { writer.WriteUnsignedShort((ushort)obj); } - public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) + public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { return (context == null) ? reader.ReadElementContentAsUnsignedShort() : HandleReadValue(reader.ReadElementContentAsUnsignedShort(), context); } - public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) + public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns) { - xmlWriter.WriteUnsignedShort((ushort)obj, name, ns); + xmlWriter.WriteUnsignedShort((ushort)obj!, name, ns); } } @@ -335,17 +335,17 @@ internal override string WriteMethodName } } - public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) + public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context) { throw new NotImplementedException(); } - public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) + public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { throw new NotImplementedException(); } - public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) + public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns) { throw new NotImplementedException(); } @@ -360,20 +360,20 @@ public IntDataContract() : base(typeof(int), DictionaryGlobals.IntLocalName, Dic internal override string WriteMethodName { get { return "WriteInt"; } } internal override string ReadMethodName { get { return "ReadElementContentAsInt"; } } - public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) + public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context) { writer.WriteInt((int)obj); } - public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) + public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { return (context == null) ? reader.ReadElementContentAsInt() : HandleReadValue(reader.ReadElementContentAsInt(), context); } - public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) + public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns) { - xmlWriter.WriteInt((int)obj, name, ns); + xmlWriter.WriteInt((int)obj!, name, ns); } } @@ -386,20 +386,20 @@ public UnsignedIntDataContract() : base(typeof(uint), DictionaryGlobals.Unsigned internal override string WriteMethodName { get { return "WriteUnsignedInt"; } } internal override string ReadMethodName { get { return "ReadElementContentAsUnsignedInt"; } } - public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) + public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context) { writer.WriteUnsignedInt((uint)obj); } - public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) + public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { return (context == null) ? reader.ReadElementContentAsUnsignedInt() : HandleReadValue(reader.ReadElementContentAsUnsignedInt(), context); } - public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) + public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns) { - xmlWriter.WriteUnsignedInt((uint)obj, name, ns); + xmlWriter.WriteUnsignedInt((uint)obj!, name, ns); } } @@ -416,20 +416,20 @@ internal LongDataContract(XmlDictionaryString name, XmlDictionaryString ns) : ba internal override string WriteMethodName { get { return "WriteLong"; } } internal override string ReadMethodName { get { return "ReadElementContentAsLong"; } } - public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) + public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context) { writer.WriteLong((long)obj); } - public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) + public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { return (context == null) ? reader.ReadElementContentAsLong() : HandleReadValue(reader.ReadElementContentAsLong(), context); } - public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) + public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns) { - xmlWriter.WriteLong((long)obj, name, ns); + xmlWriter.WriteLong((long)obj!, name, ns); } } @@ -467,20 +467,20 @@ public UnsignedLongDataContract() : base(typeof(ulong), DictionaryGlobals.Unsign internal override string WriteMethodName { get { return "WriteUnsignedLong"; } } internal override string ReadMethodName { get { return "ReadElementContentAsUnsignedLong"; } } - public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) + public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context) { writer.WriteUnsignedLong((ulong)obj); } - public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) + public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { return (context == null) ? reader.ReadElementContentAsUnsignedLong() : HandleReadValue(reader.ReadElementContentAsUnsignedLong(), context); } - public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) + public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns) { - xmlWriter.WriteUnsignedLong((ulong)obj, name, ns); + xmlWriter.WriteUnsignedLong((ulong)obj!, name, ns); } } @@ -493,20 +493,20 @@ public FloatDataContract() : base(typeof(float), DictionaryGlobals.FloatLocalNam internal override string WriteMethodName { get { return "WriteFloat"; } } internal override string ReadMethodName { get { return "ReadElementContentAsFloat"; } } - public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) + public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context) { writer.WriteFloat((float)obj); } - public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) + public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { return (context == null) ? reader.ReadElementContentAsFloat() : HandleReadValue(reader.ReadElementContentAsFloat(), context); } - public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) + public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns) { - xmlWriter.WriteFloat((float)obj, name, ns); + xmlWriter.WriteFloat((float)obj!, name, ns); } } @@ -519,20 +519,20 @@ public DoubleDataContract() : base(typeof(double), DictionaryGlobals.DoubleLocal internal override string WriteMethodName { get { return "WriteDouble"; } } internal override string ReadMethodName { get { return "ReadElementContentAsDouble"; } } - public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) + public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context) { writer.WriteDouble((double)obj); } - public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) + public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { return (context == null) ? reader.ReadElementContentAsDouble() : HandleReadValue(reader.ReadElementContentAsDouble(), context); } - public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) + public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns) { - xmlWriter.WriteDouble((double)obj, name, ns); + xmlWriter.WriteDouble((double)obj!, name, ns); } } @@ -545,20 +545,20 @@ public DecimalDataContract() : base(typeof(decimal), DictionaryGlobals.DecimalLo internal override string WriteMethodName { get { return "WriteDecimal"; } } internal override string ReadMethodName { get { return "ReadElementContentAsDecimal"; } } - public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) + public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context) { writer.WriteDecimal((decimal)obj); } - public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) + public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { return (context == null) ? reader.ReadElementContentAsDecimal() : HandleReadValue(reader.ReadElementContentAsDecimal(), context); } - public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) + public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns) { - xmlWriter.WriteDecimal((decimal)obj, name, ns); + xmlWriter.WriteDecimal((decimal)obj!, name, ns); } } @@ -571,20 +571,20 @@ public DateTimeDataContract() : base(typeof(DateTime), DictionaryGlobals.DateTim internal override string WriteMethodName { get { return "WriteDateTime"; } } internal override string ReadMethodName { get { return "ReadElementContentAsDateTime"; } } - public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) + public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context) { writer.WriteDateTime((DateTime)obj); } - public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) + public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { return (context == null) ? reader.ReadElementContentAsDateTime() : HandleReadValue(reader.ReadElementContentAsDateTime(), context); } - public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) + public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns) { - xmlWriter.WriteDateTime((DateTime)obj, name, ns); + xmlWriter.WriteDateTime((DateTime)obj!, name, ns); } } @@ -601,12 +601,12 @@ internal StringDataContract(XmlDictionaryString name, XmlDictionaryString ns) : internal override string WriteMethodName { get { return "WriteString"; } } internal override string ReadMethodName { get { return "ReadElementContentAsString"; } } - public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) + public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context) { writer.WriteString((string)obj); } - public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) + public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { if (context == null) { @@ -618,9 +618,9 @@ public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializ } } - public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) + public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns) { - context.WriteString(xmlWriter, (string)obj, name, ns); + context.WriteString(xmlWriter, (string?)obj, name, ns); } } @@ -733,12 +733,12 @@ public ByteArrayDataContract() : base(typeof(byte[]), DictionaryGlobals.ByteArra internal override string WriteMethodName { get { return "WriteBase64"; } } internal override string ReadMethodName { get { return "ReadElementContentAsBase64"; } } - public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) + public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context) { writer.WriteBase64((byte[])obj); } - public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) + public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { if (context == null) { @@ -750,10 +750,10 @@ public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializ } } - public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) + public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns) { xmlWriter.WriteStartElement(name, ns); - xmlWriter.WriteBase64((byte[])obj); + xmlWriter.WriteBase64((byte[]?)obj); xmlWriter.WriteEndElement(); } } @@ -767,12 +767,12 @@ public ObjectDataContract() : base(typeof(object), DictionaryGlobals.ObjectLocal internal override string WriteMethodName { get { return "WriteAnyType"; } } internal override string ReadMethodName { get { return "ReadElementContentAsAnyType"; } } - public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) + public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context) { // write nothing } - public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) + public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { object obj; if (reader.IsEmptyElement) @@ -822,20 +822,20 @@ internal TimeSpanDataContract(XmlDictionaryString name, XmlDictionaryString ns) internal override string WriteMethodName { get { return "WriteTimeSpan"; } } internal override string ReadMethodName { get { return "ReadElementContentAsTimeSpan"; } } - public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) + public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context) { writer.WriteTimeSpan((TimeSpan)obj); } - public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) + public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { return (context == null) ? reader.ReadElementContentAsTimeSpan() : HandleReadValue(reader.ReadElementContentAsTimeSpan(), context); } - public override void WriteXmlElement(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) + public override void WriteXmlElement(XmlWriterDelegator writer, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns) { - writer.WriteTimeSpan((TimeSpan)obj, name, ns); + writer.WriteTimeSpan((TimeSpan)obj!, name, ns); } } @@ -857,20 +857,20 @@ internal GuidDataContract(XmlDictionaryString name, XmlDictionaryString ns) : ba internal override string WriteMethodName { get { return "WriteGuid"; } } internal override string ReadMethodName { get { return "ReadElementContentAsGuid"; } } - public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) + public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context) { writer.WriteGuid((Guid)obj); } - public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) + public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { return (context == null) ? reader.ReadElementContentAsGuid() : HandleReadValue(reader.ReadElementContentAsGuid(), context); } - public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) + public override void WriteXmlElement(XmlWriterDelegator xmlWriter, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns) { - xmlWriter.WriteGuid((Guid)obj, name, ns); + xmlWriter.WriteGuid((Guid)obj!, name, ns); } } @@ -888,12 +888,12 @@ public UriDataContract() : base(typeof(Uri), DictionaryGlobals.UriLocalName, Dic internal override string WriteMethodName { get { return "WriteUri"; } } internal override string ReadMethodName { get { return "ReadElementContentAsUri"; } } - public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) + public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context) { writer.WriteUri((Uri)obj); } - public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) + public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { if (context == null) { @@ -905,9 +905,9 @@ public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializ } } - public override void WriteXmlElement(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) + public override void WriteXmlElement(XmlWriterDelegator writer, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns) { - writer.WriteUri((Uri)obj, name, ns); + writer.WriteUri((Uri?)obj, name, ns); } } @@ -925,12 +925,12 @@ internal override bool IsPrimitive get { return false; } } - public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context) + public override void WriteXmlValue(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext? context) { writer.WriteQName((XmlQualifiedName)obj); } - public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext context) + public override object? ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializerReadContext? context) { if (context == null) { @@ -942,12 +942,12 @@ public override object ReadXmlValue(XmlReaderDelegator reader, XmlObjectSerializ } } - public override void WriteXmlElement(XmlWriterDelegator writer, object obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString ns) + public override void WriteXmlElement(XmlWriterDelegator writer, object? obj, XmlObjectSerializerWriteContext context, XmlDictionaryString name, XmlDictionaryString? ns) { - context.WriteQName(writer, (XmlQualifiedName)obj, name, ns); + context.WriteQName(writer, (XmlQualifiedName?)obj, name, ns); } - internal override void WriteRootElement(XmlWriterDelegator writer, XmlDictionaryString name, XmlDictionaryString ns) + internal override void WriteRootElement(XmlWriterDelegator writer, XmlDictionaryString name, XmlDictionaryString? ns) { if (object.ReferenceEquals(ns, DictionaryGlobals.SerializationNamespace)) writer.WriteStartElement(Globals.SerPrefix, name, ns); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionClassWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionClassWriter.cs index 86801f8835aace..6253555eadd3c5 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionClassWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionClassWriter.cs @@ -16,7 +16,7 @@ namespace System.Runtime.Serialization { internal abstract class ReflectionClassWriter { - public void ReflectionWriteClass(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, ClassDataContract classContract, XmlDictionaryString[] memberNames) + public void ReflectionWriteClass(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, ClassDataContract classContract, XmlDictionaryString[]? memberNames) { InvokeOnSerializing(obj, context, classContract); obj = ResolveAdapterType(obj, classContract); @@ -37,14 +37,16 @@ public void ReflectionWriteClass(XmlWriterDelegator xmlWriter, object obj, XmlOb InvokeOnSerialized(obj, context, classContract); } - public void ReflectionWriteValue(XmlWriterDelegator xmlWriter, XmlObjectSerializerWriteContext context, Type type, object value, bool writeXsiType, PrimitiveDataContract primitiveContractForParamType) + public void ReflectionWriteValue(XmlWriterDelegator xmlWriter, XmlObjectSerializerWriteContext context, Type type, object? value, bool writeXsiType, PrimitiveDataContract? primitiveContractForParamType) { Type memberType = type; - object memberValue = value; + object? memberValue = value; bool originValueIsNullableOfT = (memberType.IsGenericType && memberType.GetGenericTypeDefinition() == Globals.TypeOfNullable); if (memberType.IsValueType && !originValueIsNullableOfT) { - PrimitiveDataContract primitiveContract = primitiveContractForParamType; + Debug.Assert(memberValue != null); + + PrimitiveDataContract? primitiveContract = primitiveContractForParamType; if (primitiveContract != null && !writeXsiType) { primitiveContract.WriteXmlValue(xmlWriter, memberValue, context); @@ -60,12 +62,12 @@ public void ReflectionWriteValue(XmlWriterDelegator xmlWriter, XmlObjectSerializ { if (memberValue == null) { - memberType = Nullable.GetUnderlyingType(memberType); + memberType = Nullable.GetUnderlyingType(memberType)!; } else { - MethodInfo getValue = memberType.GetMethod("get_Value", Array.Empty()); - memberValue = getValue.Invoke(memberValue, Array.Empty()); + MethodInfo getValue = memberType.GetMethod("get_Value", Array.Empty())!; + memberValue = getValue.Invoke(memberValue, Array.Empty())!; memberType = memberValue.GetType(); } } @@ -76,7 +78,7 @@ public void ReflectionWriteValue(XmlWriterDelegator xmlWriter, XmlObjectSerializ } else { - PrimitiveDataContract primitiveContract = originValueIsNullableOfT ? PrimitiveDataContract.GetPrimitiveDataContract(memberType) : primitiveContractForParamType; + PrimitiveDataContract? primitiveContract = originValueIsNullableOfT ? PrimitiveDataContract.GetPrimitiveDataContract(memberType) : primitiveContractForParamType; if (primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject && !writeXsiType) { primitiveContract.WriteXmlValue(xmlWriter, memberValue, context); @@ -91,21 +93,21 @@ public void ReflectionWriteValue(XmlWriterDelegator xmlWriter, XmlObjectSerializ } else { - ReflectionInternalSerialize(xmlWriter, context, memberValue, memberValue.GetType().TypeHandle.Equals(memberType.TypeHandle), writeXsiType, memberType, originValueIsNullableOfT); + ReflectionInternalSerialize(xmlWriter, context, memberValue!, memberValue!.GetType().TypeHandle.Equals(memberType.TypeHandle), writeXsiType, memberType, originValueIsNullableOfT); } } } } } - protected abstract int ReflectionWriteMembers(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, ClassDataContract classContract, ClassDataContract derivedMostClassContract, int childElementIndex, XmlDictionaryString[] memberNames); + protected abstract int ReflectionWriteMembers(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, ClassDataContract classContract, ClassDataContract derivedMostClassContract, int childElementIndex, XmlDictionaryString[]? memberNames); - protected object ReflectionGetMemberValue(object obj, DataMember dataMember) + protected object? ReflectionGetMemberValue(object obj, DataMember dataMember) { return dataMember.Getter(obj); } - protected bool ReflectionTryWritePrimitive(XmlWriterDelegator xmlWriter, XmlObjectSerializerWriteContext context, Type type, object value, XmlDictionaryString name, XmlDictionaryString ns, PrimitiveDataContract primitiveContract) + protected bool ReflectionTryWritePrimitive(XmlWriterDelegator xmlWriter, XmlObjectSerializerWriteContext context, Type type, object? value, XmlDictionaryString name, XmlDictionaryString? ns, PrimitiveDataContract? primitiveContract) { if (primitiveContract == null || primitiveContract.UnderlyingType == Globals.TypeOfObject) return false; @@ -146,7 +148,7 @@ private object ResolveAdapterType(object obj, ClassDataContract classContract) } else if (type.IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfKeyValuePair) { - obj = classContract.KeyValuePairAdapterConstructorInfo.Invoke(new object[] { obj }); + obj = classContract.KeyValuePairAdapterConstructorInfo!.Invoke(new object[] { obj }); } return obj; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionReader.cs index 66730826d1adbb..f1392a84328f5d 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionReader.cs @@ -5,6 +5,7 @@ using System.Collections; using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Reflection; using System.Runtime.Serialization.Json; @@ -16,18 +17,20 @@ namespace System.Runtime.Serialization { internal abstract class ReflectionReader { - private delegate object CollectionReadItemDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, CollectionDataContract collectionContract, Type itemType, string itemName, string itemNs); - private delegate object CollectionSetItemDelegate(object resultCollection, object collectionItem, int itemIndex); + private delegate object? CollectionReadItemDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, CollectionDataContract collectionContract, Type itemType, string itemName, string itemNs); + private delegate object CollectionSetItemDelegate(object resultCollection, object? collectionItem, int itemIndex); - private static readonly MethodInfo s_getCollectionSetItemDelegateMethod = typeof(ReflectionReader).GetMethod(nameof(GetCollectionSetItemDelegate), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); - private static readonly MethodInfo s_objectToKeyValuePairGetKey = typeof(ReflectionReader).GetMethod(nameof(ObjectToKeyValuePairGetKey), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static); - private static readonly MethodInfo s_objectToKeyValuePairGetValue = typeof(ReflectionReader).GetMethod(nameof(ObjectToKeyValuePairGetValue), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static); + private static readonly MethodInfo s_getCollectionSetItemDelegateMethod = typeof(ReflectionReader).GetMethod(nameof(GetCollectionSetItemDelegate), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance)!; + private static readonly MethodInfo s_objectToKeyValuePairGetKey = typeof(ReflectionReader).GetMethod(nameof(ObjectToKeyValuePairGetKey), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)!; + private static readonly MethodInfo s_objectToKeyValuePairGetValue = typeof(ReflectionReader).GetMethod(nameof(ObjectToKeyValuePairGetValue), BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)!; private static readonly Type[] s_arrayConstructorParameters = new Type[] { Globals.TypeOfInt }; private static readonly object[] s_arrayConstructorArguments = new object[] { 32 }; - public object ReflectionReadClass(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, ClassDataContract classContract) + public object ReflectionReadClass(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext? context, XmlDictionaryString[]? memberNames, XmlDictionaryString[]? memberNamespaces, ClassDataContract classContract) { + Debug.Assert(context != null); + object obj = CreateObject(classContract); context.AddNewObject(obj); InvokeOnDeserializing(context, classContract, obj); @@ -38,6 +41,7 @@ public object ReflectionReadClass(XmlReaderDelegator xmlReader, XmlObjectSeriali } else { + Debug.Assert(memberNames != null); ReflectionReadMembers(xmlReader, context, memberNames, memberNamespaces, classContract, ref obj); } @@ -55,7 +59,7 @@ public object ReflectionReadClass(XmlReaderDelegator xmlReader, XmlObjectSeriali public void ReflectionReadGetOnlyCollection(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString collectionItemName, XmlDictionaryString collectionItemNamespace, CollectionDataContract collectionContract) { - object resultCollection = context.GetCollectionMember(); + object? resultCollection = context.GetCollectionMember(); if (ReflectionReadSpecialCollection(xmlReader, context, collectionContract, resultCollection)) { return; @@ -84,7 +88,7 @@ private object ReflectionReadCollectionCore(XmlReaderDelegator xmlReader, XmlObj bool isArray = (collectionContract.Kind == CollectionKind.Array); int arraySize = context.GetArraySize(); - object resultArray = null; + object? resultArray = null; if (isArray && ReflectionTryReadPrimitiveArray(xmlReader, context, collectionItemName, collectionItemNamespace, collectionContract.UnderlyingType, collectionContract.ItemType, arraySize, out resultArray)) { return resultArray; @@ -128,14 +132,14 @@ private object ReadCollectionItems(XmlReaderDelegator xmlReader, XmlObjectSerial Type itemType = collectionContract.ItemType; CollectionReadItemDelegate collectionReadItemDelegate = GetCollectionReadItemDelegate(collectionContract); MethodInfo getCollectionSetItemDelegateMethod = s_getCollectionSetItemDelegateMethod.MakeGenericMethod(itemType); - CollectionSetItemDelegate collectionSetItemDelegate = (CollectionSetItemDelegate)getCollectionSetItemDelegateMethod.Invoke(this, new object[] { collectionContract, resultCollection, isReadOnlyCollection }); + CollectionSetItemDelegate collectionSetItemDelegate = (CollectionSetItemDelegate)getCollectionSetItemDelegateMethod.Invoke(this, new object[] { collectionContract, resultCollection, isReadOnlyCollection })!; int index = 0; while (true) { if (xmlReader.IsStartElement(collectionItemName, collectionItemNamespace)) { - object collectionItem = collectionReadItemDelegate(xmlReader, context, collectionContract, itemType, itemName, itemNs); + object? collectionItem = collectionReadItemDelegate(xmlReader, context, collectionContract, itemType, itemName, itemNs); resultCollection = collectionSetItemDelegate(resultCollection, collectionItem, index); index++; } @@ -160,19 +164,19 @@ private object ReadCollectionItems(XmlReaderDelegator xmlReader, XmlObjectSerial if (!isReadOnlyCollection && IsArrayLikeCollection(collectionContract)) { MethodInfo trimArraySizeMethod = XmlFormatGeneratorStatics.TrimArraySizeMethod.MakeGenericMethod(itemType); - resultCollection = trimArraySizeMethod.Invoke(null, new object[] { resultCollection, index }); + resultCollection = trimArraySizeMethod.Invoke(null, new object[] { resultCollection, index })!; } return resultCollection; } - protected abstract void ReflectionReadMembers(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, ClassDataContract classContract, ref object obj); - protected abstract object ReflectionReadDictionaryItem(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, CollectionDataContract collectionContract); + protected abstract void ReflectionReadMembers(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString[] memberNames, XmlDictionaryString[]? memberNamespaces, ClassDataContract classContract, ref object obj); + protected abstract object? ReflectionReadDictionaryItem(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, CollectionDataContract collectionContract); protected abstract string GetCollectionContractItemName(CollectionDataContract collectionContract); protected abstract string GetCollectionContractNamespace(CollectionDataContract collectionContract); protected abstract string GetClassContractNamespace(ClassDataContract classContract); - protected virtual bool ReflectionReadSpecialCollection(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, CollectionDataContract collectionContract, object resultCollection) + protected virtual bool ReflectionReadSpecialCollection(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, CollectionDataContract collectionContract, object? resultCollection) { return false; } @@ -181,7 +185,7 @@ protected int ReflectionGetMembers(ClassDataContract classContract, DataMember[] { int memberCount = (classContract.BaseContract == null) ? 0 : ReflectionGetMembers(classContract.BaseContract, members); int childElementIndex = memberCount; - for (int i = 0; i < classContract.Members.Count; i++, memberCount++) + for (int i = 0; i < classContract.Members!.Count; i++, memberCount++) { members[childElementIndex + i] = classContract.Members[i]; } @@ -211,9 +215,9 @@ protected void ReflectionReadMember(XmlReaderDelegator xmlReader, XmlObjectSeria } } - protected object ReflectionReadValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, Type type, string name, string ns, PrimitiveDataContract primitiveContractForOriginalType = null) + protected object? ReflectionReadValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, Type type, string name, string ns, PrimitiveDataContract? primitiveContractForOriginalType = null) { - object value = null; + object? value = null; int nullables = 0; while (type.IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfNullable) { @@ -221,7 +225,7 @@ protected object ReflectionReadValue(XmlReaderDelegator xmlReader, XmlObjectSeri type = type.GetGenericArguments()[0]; } - PrimitiveDataContract primitiveContract = nullables != 0 ? + PrimitiveDataContract? primitiveContract = nullables != 0 ? PrimitiveDataContract.GetPrimitiveDataContract(type) : (primitiveContractForOriginalType ?? PrimitiveDataContract.GetPrimitiveDataContract(type)); @@ -237,9 +241,9 @@ protected object ReflectionReadValue(XmlReaderDelegator xmlReader, XmlObjectSeri return value; } - private object ReadItemOfPrimitiveType(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, Type type, string name, string ns, PrimitiveDataContract primitiveContract, int nullables) + private object? ReadItemOfPrimitiveType(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, Type type, string name, string ns, PrimitiveDataContract? primitiveContract, int nullables) { - object value; + object? value; context.ReadAttributes(xmlReader); string objectId = context.ReadIfNullOrRef(xmlReader, type, DataContract.IsTypeSerializable(type)); bool typeIsValueType = type.IsValueType; @@ -295,7 +299,7 @@ private static object ReadISerializable(XmlReaderDelegator xmlReader, XmlObjectS object obj; SerializationInfo serializationInfo = context.ReadSerializationInfo(xmlReader, classContract.UnderlyingType); StreamingContext streamingContext = context.GetStreamingContext(); - ConstructorInfo iSerializableConstructor = classContract.GetISerializableConstructor(); + ConstructorInfo iSerializableConstructor = classContract.GetISerializableConstructor()!; obj = iSerializableConstructor.Invoke(new object[] { serializationInfo, streamingContext }); return obj; } @@ -310,7 +314,7 @@ private CollectionReadItemDelegate GetReflectionReadValueDelegate(Type type) type = type.GetGenericArguments()[0]; } - PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type); + PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type); if ((primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject) || nullables != 0 || type.IsValueType) { return (xmlReaderArg, contextArg, collectionContract, typeArg, nameArg, nsArg) => @@ -324,17 +328,17 @@ private CollectionReadItemDelegate GetReflectionReadValueDelegate(Type type) } } - private object ReflectionGetMemberValue(object obj, DataMember dataMember) + private object? ReflectionGetMemberValue(object obj, DataMember dataMember) { return dataMember.Getter(obj); } - private void ReflectionSetMemberValue(ref object obj, object memberValue, DataMember dataMember) + private void ReflectionSetMemberValue(ref object obj, object? memberValue, DataMember dataMember) { dataMember.Setter(ref obj, memberValue); } - private object ReflectionReadValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, DataMember dataMember, string ns) + private object? ReflectionReadValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, DataMember dataMember, string ns) { Type type = dataMember.MemberType; string name = dataMember.Name; @@ -342,7 +346,7 @@ private object ReflectionReadValue(XmlReaderDelegator xmlReader, XmlObjectSerial return ReflectionReadValue(xmlReader, context, type, name, ns, dataMember.MemberPrimitiveContract); } - private object ReflectionInternalDeserialize(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, CollectionDataContract collectionContract, Type type, string name, string ns) + private object? ReflectionInternalDeserialize(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, CollectionDataContract? collectionContract, Type type, string name, string ns) { return context.InternalDeserialize(xmlReader, DataContract.GetId(type.TypeHandle), type.TypeHandle, name, ns); } @@ -377,7 +381,7 @@ private void InvokeDeserializationCallback(object obj) private static object CreateObject(ClassDataContract classContract) { - object obj; + object? obj; if (!classContract.CreateNewInstanceViaDefaultConstructor(out obj)) { Type classType = classContract.UnderlyingType; @@ -396,7 +400,7 @@ private static object ResolveAdapterObject(object obj, ClassDataContract classCo } else if (obj is IKeyValuePairAdapter) { - obj = classContract.GetKeyValuePairMethodInfo.Invoke(obj, Array.Empty()); + obj = classContract.GetKeyValuePairMethodInfo!.Invoke(obj, Array.Empty())!; } return obj; @@ -430,14 +434,14 @@ private object ReflectionCreateCollection(CollectionDataContract collectionContr if (IsArrayLikeCollection(collectionContract)) { Type arrayType = collectionContract.ItemType.MakeArrayType(); - var ci = arrayType.GetConstructor(s_arrayConstructorParameters); + var ci = arrayType.GetConstructor(s_arrayConstructorParameters)!; var newArray = ci.Invoke(s_arrayConstructorArguments); return newArray; } else if (collectionContract.Kind == CollectionKind.GenericDictionary && collectionContract.UnderlyingType.IsInterface) { Type type = Globals.TypeOfDictionaryGeneric.MakeGenericType(collectionContract.ItemType.GetGenericArguments()); - ConstructorInfo ci = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public, Array.Empty()); + ConstructorInfo ci = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public, Array.Empty())!; object newGenericDict = ci.Invoke(Array.Empty()); return newGenericDict; } @@ -445,7 +449,7 @@ private object ReflectionCreateCollection(CollectionDataContract collectionContr { if (collectionContract.UnderlyingType.IsValueType) { - object newValueObject = Activator.CreateInstance(collectionContract.UnderlyingType); + object newValueObject = Activator.CreateInstance(collectionContract.UnderlyingType)!; return newValueObject; } else if (collectionContract.UnderlyingType == Globals.TypeOfIDictionary) @@ -455,19 +459,19 @@ private object ReflectionCreateCollection(CollectionDataContract collectionContr } else { - ConstructorInfo ci = collectionContract.Constructor; + ConstructorInfo ci = collectionContract.Constructor!; object newCollection = ci.Invoke(Array.Empty()); return newCollection; } } } - private static object ObjectToKeyValuePairGetKey(object o) + private static object? ObjectToKeyValuePairGetKey(object o) { return ((KeyValue)o).Key; } - private static object ObjectToKeyValuePairGetValue(object o) + private static object? ObjectToKeyValuePairGetValue(object o) { return ((KeyValue)o).Value; } @@ -484,7 +488,7 @@ private CollectionSetItemDelegate GetCollectionSetItemDelegate(CollectionData XmlObjectSerializerReadContext.ThrowArrayExceededSizeException(arraySize, collectionContract.UnderlyingType); } - ((T[])resultCollection)[index] = (T)collectionItem; + ((T[])resultCollection)[index] = (T)collectionItem!; return resultCollection; }; } @@ -493,7 +497,7 @@ private CollectionSetItemDelegate GetCollectionSetItemDelegate(CollectionData return (resultCollection, collectionItem, index) => { resultCollection = XmlObjectSerializerReadContext.EnsureArraySize((T[])resultCollection, index); - ((T[])resultCollection)[index] = (T)collectionItem; + ((T[])resultCollection)[index] = (T)collectionItem!; return resultCollection; }; } @@ -501,17 +505,17 @@ private CollectionSetItemDelegate GetCollectionSetItemDelegate(CollectionData { Type keyType = collectionContract.ItemType.GenericTypeArguments[0]; Type valueType = collectionContract.ItemType.GenericTypeArguments[1]; - Func objectToKeyValuePairGetKey = s_objectToKeyValuePairGetKey.MakeGenericMethod(keyType, valueType).CreateDelegate>(); - Func objectToKeyValuePairGetValue = s_objectToKeyValuePairGetValue.MakeGenericMethod(keyType, valueType).CreateDelegate>(); + Func objectToKeyValuePairGetKey = s_objectToKeyValuePairGetKey.MakeGenericMethod(keyType, valueType).CreateDelegate>(); + Func objectToKeyValuePairGetValue = s_objectToKeyValuePairGetValue.MakeGenericMethod(keyType, valueType).CreateDelegate>(); if (collectionContract.Kind == CollectionKind.GenericDictionary) { return (resultCollection, collectionItem, index) => { - object key = objectToKeyValuePairGetKey(collectionItem); - object value = objectToKeyValuePairGetValue(collectionItem); + object? key = objectToKeyValuePairGetKey(collectionItem!); + object? value = objectToKeyValuePairGetValue(collectionItem!); - collectionContract.AddMethod.Invoke(resultCollection, new object[] { key, value }); + collectionContract.AddMethod!.Invoke(resultCollection, new object?[] { key, value }); return resultCollection; }; } @@ -519,11 +523,11 @@ private CollectionSetItemDelegate GetCollectionSetItemDelegate(CollectionData { return (resultCollection, collectionItem, index) => { - object key = objectToKeyValuePairGetKey(collectionItem); - object value = objectToKeyValuePairGetValue(collectionItem); + object? key = objectToKeyValuePairGetKey(collectionItem!); + object? value = objectToKeyValuePairGetValue(collectionItem!); IDictionary dict = (IDictionary)resultCollection; - dict.Add(key, value); + dict.Add(key!, value); return resultCollection; }; } @@ -537,7 +541,7 @@ private CollectionSetItemDelegate GetCollectionSetItemDelegate(CollectionData { return (resultCollection, collectionItem, index) => { - ((ICollection)resultCollection).Add((T)collectionItem); + ((ICollection)resultCollection).Add((T)collectionItem!); return resultCollection; }; } @@ -551,7 +555,7 @@ private CollectionSetItemDelegate GetCollectionSetItemDelegate(CollectionData } else { - MethodInfo addMethod = collectionContract.AddMethod; + MethodInfo? addMethod = collectionContract.AddMethod; if (addMethod == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.CollectionMustHaveAddMethod, DataContract.GetClrTypeFullName(collectionContract.UnderlyingType)))); @@ -559,18 +563,18 @@ private CollectionSetItemDelegate GetCollectionSetItemDelegate(CollectionData return (resultCollection, collectionItem, index) => { - addMethod.Invoke(resultCollection, new object[] { collectionItem }); + addMethod.Invoke(resultCollection, new object?[] { collectionItem }); return resultCollection; }; } } } - private bool ReflectionTryReadPrimitiveArray(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString collectionItemName, XmlDictionaryString collectionItemNamespace, Type type, Type itemType, int arraySize, out object resultArray) + private bool ReflectionTryReadPrimitiveArray(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString collectionItemName, XmlDictionaryString collectionItemNamespace, Type type, Type itemType, int arraySize, [NotNullWhen(true)] out object? resultArray) { resultArray = null; - PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType); + PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType); if (primitiveContract == null) return false; @@ -578,57 +582,71 @@ private bool ReflectionTryReadPrimitiveArray(XmlReaderDelegator xmlReader, XmlOb { case TypeCode.Boolean: { - bool[] boolArray = null; - xmlReader.TryReadBooleanArray(context, collectionItemName, collectionItemNamespace, arraySize, out boolArray); - resultArray = boolArray; + bool[]? boolArray; + if (xmlReader.TryReadBooleanArray(context, collectionItemName, collectionItemNamespace, arraySize, out boolArray)) + { + resultArray = boolArray; + } } break; case TypeCode.DateTime: { - DateTime[] dateTimeArray = null; - xmlReader.TryReadDateTimeArray(context, collectionItemName, collectionItemNamespace, arraySize, out dateTimeArray); - resultArray = dateTimeArray; + DateTime[]? dateTimeArray; + if (xmlReader.TryReadDateTimeArray(context, collectionItemName, collectionItemNamespace, arraySize, out dateTimeArray)) + { + resultArray = dateTimeArray; + } } break; case TypeCode.Decimal: { - decimal[] decimalArray = null; - xmlReader.TryReadDecimalArray(context, collectionItemName, collectionItemNamespace, arraySize, out decimalArray); - resultArray = decimalArray; + decimal[]? decimalArray; + if (xmlReader.TryReadDecimalArray(context, collectionItemName, collectionItemNamespace, arraySize, out decimalArray)) + { + resultArray = decimalArray; + } } break; case TypeCode.Int32: { - int[] intArray = null; - xmlReader.TryReadInt32Array(context, collectionItemName, collectionItemNamespace, arraySize, out intArray); - resultArray = intArray; + int[]? intArray; + if (xmlReader.TryReadInt32Array(context, collectionItemName, collectionItemNamespace, arraySize, out intArray)) + { + resultArray = intArray; + } } break; case TypeCode.Int64: { - long[] longArray = null; - xmlReader.TryReadInt64Array(context, collectionItemName, collectionItemNamespace, arraySize, out longArray); - resultArray = longArray; + long[]? longArray; + if (xmlReader.TryReadInt64Array(context, collectionItemName, collectionItemNamespace, arraySize, out longArray)) + { + resultArray = longArray; + } } break; case TypeCode.Single: { - float[] floatArray = null; - xmlReader.TryReadSingleArray(context, collectionItemName, collectionItemNamespace, arraySize, out floatArray); - resultArray = floatArray; + float[]? floatArray; + if (xmlReader.TryReadSingleArray(context, collectionItemName, collectionItemNamespace, arraySize, out floatArray)) + { + resultArray = floatArray; + } } break; case TypeCode.Double: { - double[] doubleArray = null; - xmlReader.TryReadDoubleArray(context, collectionItemName, collectionItemNamespace, arraySize, out doubleArray); - resultArray = doubleArray; + double[]? doubleArray; + if (xmlReader.TryReadDoubleArray(context, collectionItemName, collectionItemNamespace, arraySize, out doubleArray)) + { + resultArray = doubleArray; + } } break; default: return false; } - return true; + return resultArray != null; } } } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionXmlFormatReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionXmlFormatReader.cs index b21f583e699a1e..9c45733bb2b4ec 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionXmlFormatReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionXmlFormatReader.cs @@ -25,7 +25,7 @@ public ReflectionXmlClassReader(ClassDataContract classDataContract) _reflectionReader = new ReflectionXmlReader(); } - public object ReflectionReadClass(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces) + public object ReflectionReadClass(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext? context, XmlDictionaryString[]? memberNames, XmlDictionaryString[]? memberNamespaces) { return _reflectionReader.ReflectionReadClass(xmlReader, context, memberNames, memberNamespaces, _classContract); } @@ -48,9 +48,11 @@ public void ReflectionReadGetOnlyCollection(XmlReaderDelegator xmlReader, XmlObj internal sealed class ReflectionXmlReader : ReflectionReader { - protected override void ReflectionReadMembers(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, ClassDataContract classContract, ref object obj) + protected override void ReflectionReadMembers(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString[] memberNames, XmlDictionaryString[]? memberNamespaces, ClassDataContract classContract, ref object obj) { - int memberCount = classContract.MemberNames.Length; + Debug.Assert(memberNamespaces != null); + + int memberCount = classContract.MemberNames!.Length; context.IncrementItemCount(memberCount); int memberIndex = -1; int firstRequiredMember; @@ -60,7 +62,7 @@ protected override void ReflectionReadMembers(XmlReaderDelegator xmlReader, XmlO DataMember[] members = new DataMember[memberCount]; int reflectedMemberCount = ReflectionGetMembers(classContract, members); Debug.Assert(reflectedMemberCount == memberCount, "The value returned by ReflectionGetMembers() should equal to memberCount."); - ExtensionDataObject extensionData = null; + ExtensionDataObject? extensionData = null; if (classContract.HasExtensionData) { @@ -94,7 +96,7 @@ protected override void ReflectionReadMembers(XmlReaderDelegator xmlReader, XmlO protected override string GetClassContractNamespace(ClassDataContract classContract) { - return classContract.StableName.Namespace; + return classContract.StableName!.Namespace; } protected override string GetCollectionContractItemName(CollectionDataContract collectionContract) @@ -107,7 +109,7 @@ protected override string GetCollectionContractNamespace(CollectionDataContract return collectionContract.StableName.Namespace; } - protected override object ReflectionReadDictionaryItem(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, CollectionDataContract collectionContract) + protected override object? ReflectionReadDictionaryItem(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, CollectionDataContract collectionContract) { Debug.Assert(collectionContract.Kind == CollectionKind.Dictionary || collectionContract.Kind == CollectionKind.GenericDictionary); context.ReadAttributes(xmlReader); @@ -116,7 +118,7 @@ protected override object ReflectionReadDictionaryItem(XmlReaderDelegator xmlRea private bool[] GetRequiredMembers(ClassDataContract contract, out int firstRequiredMember) { - int memberCount = contract.MemberNames.Length; + int memberCount = contract.MemberNames!.Length; bool[] requiredMembers = new bool[memberCount]; GetRequiredMembers(contract, requiredMembers); for (firstRequiredMember = 0; firstRequiredMember < memberCount; firstRequiredMember++) @@ -128,7 +130,7 @@ private bool[] GetRequiredMembers(ClassDataContract contract, out int firstRequi private int GetRequiredMembers(ClassDataContract contract, bool[] requiredMembers) { int memberCount = (contract.BaseContract == null) ? 0 : GetRequiredMembers(contract.BaseContract, requiredMembers); - List members = contract.Members; + List members = contract.Members!; for (int i = 0; i < members.Count; i++, memberCount++) { requiredMembers[memberCount] = members[i].IsRequired; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionXmlFormatWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionXmlFormatWriter.cs index 638010880728b3..643f3a631001f9 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionXmlFormatWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ReflectionXmlFormatWriter.cs @@ -36,7 +36,7 @@ public void ReflectionWriteCollection(XmlWriterDelegator xmlWriter, object obj, if (!ReflectionTryWritePrimitiveArray(xmlWriter, obj, collectionDataContract.UnderlyingType, itemType, itemName, ns)) { Array array = (Array)obj; - PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType); + PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType); for (int i = 0; i < array.Length; ++i) { _reflectionClassWriter.ReflectionWriteStartElement(xmlWriter, itemType, ns, ns.Value, itemName.Value, 0); @@ -50,7 +50,7 @@ public void ReflectionWriteCollection(XmlWriterDelegator xmlWriter, object obj, collectionDataContract.IncrementCollectionCount(xmlWriter, obj, context); IEnumerator enumerator = collectionDataContract.GetEnumeratorForCollection(obj); - PrimitiveDataContract primitiveContractForType = PrimitiveDataContract.GetPrimitiveDataContract(collectionDataContract.UnderlyingType); + PrimitiveDataContract? primitiveContractForType = PrimitiveDataContract.GetPrimitiveDataContract(collectionDataContract.UnderlyingType); if (primitiveContractForType != null && primitiveContractForType.UnderlyingType != Globals.TypeOfObject) { @@ -87,7 +87,7 @@ public void ReflectionWriteCollection(XmlWriterDelegator xmlWriter, object obj, private bool ReflectionTryWritePrimitiveArray(XmlWriterDelegator xmlWriter, object obj, Type type, Type itemType, XmlDictionaryString collectionItemName, XmlDictionaryString itemNamespace) { - PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType); + PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType); if (primitiveContract == null) return false; @@ -124,16 +124,16 @@ private bool ReflectionTryWritePrimitiveArray(XmlWriterDelegator xmlWriter, obje internal sealed class ReflectionXmlClassWriter : ReflectionClassWriter { - protected override int ReflectionWriteMembers(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, ClassDataContract classContract, ClassDataContract derivedMostClassContract, int childElementIndex, XmlDictionaryString[] emptyStringArray) + protected override int ReflectionWriteMembers(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context, ClassDataContract classContract, ClassDataContract derivedMostClassContract, int childElementIndex, XmlDictionaryString[]? emptyStringArray) { int memberCount = (classContract.BaseContract == null) ? 0 : ReflectionWriteMembers(xmlWriter, obj, context, classContract.BaseContract, derivedMostClassContract, childElementIndex, emptyStringArray); childElementIndex += memberCount; - XmlDictionaryString[] memberNames = classContract.MemberNames; + XmlDictionaryString[] memberNames = classContract.MemberNames!; XmlDictionaryString ns = classContract.Namespace; - context.IncrementItemCount(classContract.Members.Count); + context.IncrementItemCount(classContract.Members!.Count); for (int i = 0; i < classContract.Members.Count; i++, memberCount++) { DataMember member = classContract.Members[i]; @@ -148,11 +148,11 @@ protected override int ReflectionWriteMembers(XmlWriterDelegator xmlWriter, obje } bool shouldWriteValue = true; - object memberValue = null; + object? memberValue = null; if (!member.EmitDefaultValue) { memberValue = ReflectionGetMemberValue(obj, member); - object defaultValue = XmlFormatGeneratorStatics.GetDefaultValue(memberType); + object? defaultValue = XmlFormatGeneratorStatics.GetDefaultValue(memberType); if ((memberValue == null && defaultValue == null) || (memberValue != null && memberValue.Equals(defaultValue))) { @@ -172,14 +172,14 @@ protected override int ReflectionWriteMembers(XmlWriterDelegator xmlWriter, obje { memberValue = ReflectionGetMemberValue(obj, member); } - PrimitiveDataContract primitiveContract = member.MemberPrimitiveContract; + PrimitiveDataContract? primitiveContract = member.MemberPrimitiveContract; if (writeXsiType || !ReflectionTryWritePrimitive(xmlWriter, context, memberType, memberValue, memberNames[i + childElementIndex] /*name*/, ns, primitiveContract)) { ReflectionWriteStartElement(xmlWriter, memberType, ns, ns.Value, member.Name, 0); - if (classContract.ChildElementNamespaces[i + childElementIndex] != null) + if (classContract.ChildElementNamespaces![i + childElementIndex] != null) { - var nsChildElement = classContract.ChildElementNamespaces[i + childElementIndex]; + var nsChildElement = classContract.ChildElementNamespaces[i + childElementIndex]!; xmlWriter.WriteNamespaceDecl(nsChildElement); } ReflectionWriteValue(xmlWriter, context, memberType, memberValue, writeXsiType, primitiveContractForParamType: null); @@ -215,7 +215,7 @@ public void ReflectionWriteEndElement(XmlWriterDelegator xmlWriter) xmlWriter.WriteEndElement(); } - private bool NeedsPrefix(Type type, XmlDictionaryString ns) + private bool NeedsPrefix(Type type, XmlDictionaryString? ns) { return type == Globals.TypeOfXmlQualifiedName && (ns != null && ns.Value != null && ns.Value.Length > 0); } @@ -227,14 +227,14 @@ private bool CheckIfMemberHasConflict(DataMember member, ClassDataContract class return true; // Check for conflict with derived type members - string name = member.Name; - string ns = classContract.StableName.Namespace; - ClassDataContract currentContract = derivedMostClassContract; + string? name = member.Name; + string? ns = classContract.StableName.Namespace; + ClassDataContract? currentContract = derivedMostClassContract; while (currentContract != null && currentContract != classContract) { if (ns == currentContract.StableName.Namespace) { - List members = currentContract.Members; + List members = currentContract.Members!; for (int j = 0; j < members.Count; j++) { if (name == members[j].Name) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaExporter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaExporter.cs index 8c36110d5a57e5..d372854bf11594 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaExporter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaExporter.cs @@ -6,6 +6,7 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Reflection; @@ -18,7 +19,7 @@ namespace System.Runtime.Serialization internal class SchemaExporter { private readonly XmlSchemaSet _schemas; - private XmlDocument _xmlDoc; + private XmlDocument? _xmlDoc; private DataContractSet _dataContractSet; internal SchemaExporter(XmlSchemaSet schemas, DataContractSet dataContractSet) @@ -61,7 +62,7 @@ internal void Export() finally { _xmlDoc = null; - _dataContractSet = null; + _dataContractSet = null!; } } @@ -70,7 +71,7 @@ private void ExportSerializationSchema() if (!Schemas.Contains(Globals.SerializationNamespace)) { StringReader reader = new StringReader(Globals.SerializationSchema); - XmlSchema schema = XmlSchema.Read(new XmlTextReader(reader) { DtdProcessing = DtdProcessing.Prohibit }, null); + XmlSchema? schema = XmlSchema.Read(new XmlTextReader(reader) { DtdProcessing = DtdProcessing.Prohibit }, null); if (schema == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.CouldNotReadSerializationSchema, Globals.SerializationNamespace))); Schemas.Add(schema); @@ -104,13 +105,13 @@ private void ExportDataContract(DataContract dataContract) } } - private XmlSchemaElement ExportTopLevelElement(DataContract dataContract, XmlSchema schema) + private XmlSchemaElement ExportTopLevelElement(DataContract dataContract, XmlSchema? schema) { - if (schema == null || dataContract.StableName.Namespace != dataContract.TopLevelElementNamespace.Value) - schema = GetSchema(dataContract.TopLevelElementNamespace.Value); + if (schema == null || dataContract.StableName.Namespace != dataContract.TopLevelElementNamespace!.Value) + schema = GetSchema(dataContract.TopLevelElementNamespace!.Value); XmlSchemaElement topLevelElement = new XmlSchemaElement(); - topLevelElement.Name = dataContract.TopLevelElementName.Value; + topLevelElement.Name = dataContract.TopLevelElementName!.Value; SetElementType(topLevelElement, dataContract, schema); topLevelElement.IsNillable = true; schema.Items.Add(topLevelElement); @@ -122,18 +123,18 @@ private void ExportClassDataContract(ClassDataContract classDataContract, XmlSch XmlSchemaComplexType type = new XmlSchemaComplexType(); type.Name = classDataContract.StableName.Name; schema.Items.Add(type); - XmlElement genericInfoElement = null; + XmlElement? genericInfoElement = null; if (classDataContract.UnderlyingType.IsGenericType) genericInfoElement = ExportGenericInfo(classDataContract.UnderlyingType, Globals.GenericTypeLocalName, Globals.SerializationNamespace); XmlSchemaSequence rootSequence = new XmlSchemaSequence(); - for (int i = 0; i < classDataContract.Members.Count; i++) + for (int i = 0; i < classDataContract.Members!.Count; i++) { DataMember dataMember = classDataContract.Members[i]; XmlSchemaElement element = new XmlSchemaElement(); element.Name = dataMember.Name; - XmlElement actualTypeElement = null; + XmlElement? actualTypeElement = null; DataContract memberTypeContract = _dataContractSet.GetMemberTypeDataContract(dataMember); if (CheckIfMemberHasConflict(dataMember)) { @@ -153,7 +154,7 @@ private void ExportClassDataContract(ClassDataContract classDataContract, XmlSch rootSequence.Items.Add(element); } - XmlElement isValueTypeElement = null; + XmlElement? isValueTypeElement = null; if (classDataContract.BaseContract != null) { XmlSchemaComplexContentExtension extension = CreateTypeContent(type, classDataContract.BaseContract.StableName, schema); @@ -184,7 +185,7 @@ private void AddReferenceAttributes(XmlSchemaObjectCollection attributes, XmlSch private void SetElementType(XmlSchemaElement element, DataContract dataContract, XmlSchema schema) { - XmlDataContract xmlDataContract = dataContract as XmlDataContract; + XmlDataContract? xmlDataContract = dataContract as XmlDataContract; if (xmlDataContract != null && xmlDataContract.IsAnonymous) { element.SchemaType = xmlDataContract.XsdType; @@ -205,7 +206,7 @@ private bool CheckIfMemberHasConflict(DataMember dataMember) if (dataMember.HasConflictingNameAndType) return true; - DataMember conflictingMember = dataMember.ConflictingMember; + DataMember? conflictingMember = dataMember.ConflictingMember; while (conflictingMember != null) { if (conflictingMember.HasConflictingNameAndType) @@ -216,7 +217,7 @@ private bool CheckIfMemberHasConflict(DataMember dataMember) return false; } - private XmlElement ExportEmitDefaultValue(DataMember dataMember) + private XmlElement? ExportEmitDefaultValue(DataMember dataMember) { if (dataMember.EmitDefaultValue) return null; @@ -249,7 +250,7 @@ private static XmlElement ExportActualType(XmlQualifiedName typeName, XmlDocumen private XmlElement ExportGenericInfo(Type clrType, string elementName, string elementNs) { - Type itemType; + Type? itemType; int nestedCollectionLevel = 0; while (CollectionDataContract.IsCollection(clrType, out itemType)) { @@ -262,8 +263,8 @@ private XmlElement ExportGenericInfo(Type clrType, string elementName, string el nestedCollectionLevel++; } - Type[] genericArguments = null; - IList genericArgumentCounts = null; + Type[]? genericArguments = null; + IList? genericArgumentCounts = null; if (clrType.IsGenericType) { genericArguments = clrType.GetGenericArguments(); @@ -306,6 +307,7 @@ private XmlElement ExportGenericInfo(Type clrType, string elementName, string el { int argIndex = 0; int nestedLevel = 0; + Debug.Assert(genericArgumentCounts != null); foreach (int genericArgumentCount in genericArgumentCounts) { for (int i = 0; i < genericArgumentCount; i++, argIndex++) @@ -332,7 +334,7 @@ private XmlElement ExportGenericInfo(Type clrType, string elementName, string el return typeElement; } - private XmlElement ExportSurrogateData(object key) + private XmlElement? ExportSurrogateData(object key) { // IDataContractSurrogate is not available on NetCore. return null; @@ -343,7 +345,7 @@ private void ExportCollectionDataContract(CollectionDataContract collectionDataC XmlSchemaComplexType type = new XmlSchemaComplexType(); type.Name = collectionDataContract.StableName.Name; schema.Items.Add(type); - XmlElement genericInfoElement = null, isDictionaryElement = null; + XmlElement? genericInfoElement = null, isDictionaryElement = null; if (collectionDataContract.UnderlyingType.IsGenericType && CollectionDataContract.IsCollectionDataContract(collectionDataContract.UnderlyingType)) genericInfoElement = ExportGenericInfo(collectionDataContract.UnderlyingType, Globals.GenericTypeLocalName, Globals.SerializationNamespace); if (collectionDataContract.IsDictionary) @@ -358,10 +360,10 @@ private void ExportCollectionDataContract(CollectionDataContract collectionDataC element.MaxOccursString = Globals.OccursUnbounded; if (collectionDataContract.IsDictionary) { - ClassDataContract keyValueContract = collectionDataContract.ItemContract as ClassDataContract; + ClassDataContract keyValueContract = (collectionDataContract.ItemContract as ClassDataContract)!; XmlSchemaComplexType keyValueType = new XmlSchemaComplexType(); XmlSchemaSequence keyValueSequence = new XmlSchemaSequence(); - foreach (DataMember dataMember in keyValueContract.Members) + foreach (DataMember dataMember in keyValueContract.Members!) { XmlSchemaElement keyValueElement = new XmlSchemaElement(); keyValueElement.Name = dataMember.Name; @@ -402,7 +404,9 @@ private void ExportEnumDataContract(EnumDataContract enumDataContract, XmlSchema { XmlSchemaSimpleType type = new XmlSchemaSimpleType(); type.Name = enumDataContract.StableName.Name; - XmlElement actualTypeElement = (enumDataContract.BaseContractName == DefaultEnumBaseTypeName) ? null : ExportActualType(enumDataContract.BaseContractName); + // https://github.com/dotnet/runtime/issues/41448 - enumDataContract.BaseContractName is always null, but this method is not reachable + Debug.Assert(enumDataContract.BaseContractName != null, "BaseContractName is always null, but this method is not reachable. Suppressing compiler error."); + XmlElement? actualTypeElement = (enumDataContract.BaseContractName == DefaultEnumBaseTypeName) ? null : ExportActualType(enumDataContract.BaseContractName); type.Annotation = GetSchemaAnnotation(actualTypeElement, ExportSurrogateData(enumDataContract)); schema.Items.Add(type); @@ -442,11 +446,11 @@ private void ExportISerializableDataContract(ClassDataContract dataContract, Xml XmlSchemaComplexType type = new XmlSchemaComplexType(); type.Name = dataContract.StableName.Name; schema.Items.Add(type); - XmlElement genericInfoElement = null; + XmlElement? genericInfoElement = null; if (dataContract.UnderlyingType.IsGenericType) genericInfoElement = ExportGenericInfo(dataContract.UnderlyingType, Globals.GenericTypeLocalName, Globals.SerializationNamespace); - XmlElement isValueTypeElement = null; + XmlElement? isValueTypeElement = null; if (dataContract.BaseContract != null) { _ = CreateTypeContent(type, dataContract.BaseContract.StableName, schema); @@ -478,9 +482,9 @@ private XmlSchemaComplexContentExtension CreateTypeContent(XmlSchemaComplexType private void ExportXmlDataContract(XmlDataContract dataContract) { - XmlQualifiedName typeQName; + XmlQualifiedName? typeQName; bool hasRoot; - XmlSchemaType xsdType; + XmlSchemaType? xsdType; Type clrType = dataContract.UnderlyingType; if (!IsSpecialXmlType(clrType, out typeQName, out xsdType, out hasRoot)) @@ -494,9 +498,9 @@ private void ExportXmlDataContract(XmlDataContract dataContract) Fx.Assert("XML data contract type name does not match schema name"); } - XmlSchema schema; + XmlSchema? schema; if (SchemaHelper.GetSchemaElement(Schemas, - new XmlQualifiedName(dataContract.TopLevelElementName.Value, dataContract.TopLevelElementNamespace.Value), + new XmlQualifiedName(dataContract.TopLevelElementName!.Value, dataContract.TopLevelElementNamespace!.Value), out schema) == null) { XmlSchemaElement topLevelElement = ExportTopLevelElement(dataContract, schema); @@ -504,7 +508,7 @@ private void ExportXmlDataContract(XmlDataContract dataContract) ReprocessAll(_schemas); } - XmlSchemaType anonymousType = xsdType; + XmlSchemaType? anonymousType = xsdType; xsdType = SchemaHelper.GetSchemaType(_schemas, typeQName, out schema); if (anonymousType == null && xsdType == null && typeQName.Namespace != XmlSchema.Namespace) { @@ -515,7 +519,7 @@ private void ExportXmlDataContract(XmlDataContract dataContract) xsdType.Annotation = GetSchemaAnnotation( ExportSurrogateData(dataContract), dataContract.IsValueType ? - GetAnnotationMarkup(IsValueTypeName, XmlConvert.ToString(dataContract.IsValueType), schema) : + GetAnnotationMarkup(IsValueTypeName, XmlConvert.ToString(dataContract.IsValueType), schema!) : null ); } @@ -550,7 +554,7 @@ private static void ReprocessAll(XmlSchemaSet schemas)// and remove duplicate it } else continue; - object otherItem = items[qname]; + object? otherItem = items[qname]; if (otherItem != null) { schema.Items.Remove(item); @@ -562,9 +566,9 @@ private static void ReprocessAll(XmlSchemaSet schemas)// and remove duplicate it } } - internal static void GetXmlTypeInfo(Type type, out XmlQualifiedName stableName, out XmlSchemaType xsdType, out bool hasRoot) + internal static void GetXmlTypeInfo(Type type, out XmlQualifiedName stableName, out XmlSchemaType? xsdType, out bool hasRoot) { - if (IsSpecialXmlType(type, out stableName, out xsdType, out hasRoot)) + if (IsSpecialXmlType(type, out stableName!, out xsdType, out hasRoot)) return; XmlSchemaSet schemas = new XmlSchemaSet(); schemas.XmlResolver = null; @@ -573,7 +577,7 @@ internal static void GetXmlTypeInfo(Type type, out XmlQualifiedName stableName, throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidXmlDataContractName, DataContract.GetClrTypeFullName(type)))); } - private static bool InvokeSchemaProviderMethod(Type clrType, XmlSchemaSet schemas, out XmlQualifiedName stableName, out XmlSchemaType xsdType, out bool hasRoot) + private static bool InvokeSchemaProviderMethod(Type clrType, XmlSchemaSet schemas, out XmlQualifiedName stableName, out XmlSchemaType? xsdType, out bool hasRoot) { xsdType = null; hasRoot = true; @@ -590,7 +594,7 @@ private static bool InvokeSchemaProviderMethod(Type clrType, XmlSchemaSet schema xsdType = CreateAnyElementType(); hasRoot = false; } - string methodName = provider.MethodName; + string? methodName = provider.MethodName; if (methodName == null || methodName.Length == 0) { if (!provider.IsAny) @@ -599,14 +603,14 @@ private static bool InvokeSchemaProviderMethod(Type clrType, XmlSchemaSet schema } else { - MethodInfo getMethod = clrType.GetMethod(methodName, /*BindingFlags.DeclaredOnly |*/ BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public, null, new Type[] { typeof(XmlSchemaSet) }, null); + MethodInfo? getMethod = clrType.GetMethod(methodName, /*BindingFlags.DeclaredOnly |*/ BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public, null, new Type[] { typeof(XmlSchemaSet) }, null); if (getMethod == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.MissingGetSchemaMethod, DataContract.GetClrTypeFullName(clrType), methodName))); if (!(Globals.TypeOfXmlQualifiedName.IsAssignableFrom(getMethod.ReturnType)) && !(Globals.TypeOfXmlSchemaType.IsAssignableFrom(getMethod.ReturnType))) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.InvalidReturnTypeOnGetSchemaMethod, DataContract.GetClrTypeFullName(clrType), methodName, DataContract.GetClrTypeFullName(getMethod.ReturnType), DataContract.GetClrTypeFullName(Globals.TypeOfXmlQualifiedName), typeof(XmlSchemaType)))); - object typeInfo = getMethod.Invoke(null, new object[] { schemas }); + object? typeInfo = getMethod.Invoke(null, new object[] { schemas }); if (provider.IsAny) { @@ -622,11 +626,11 @@ private static bool InvokeSchemaProviderMethod(Type clrType, XmlSchemaSet schema } else { - XmlSchemaType providerXsdType = typeInfo as XmlSchemaType; + XmlSchemaType? providerXsdType = typeInfo as XmlSchemaType; if (providerXsdType != null) { - string typeName = providerXsdType.Name; - string typeNs = null; + string? typeName = providerXsdType.Name; + string? typeNs = null; if (typeName == null || typeName.Length == 0) { DataContract.GetDefaultStableName(DataContract.GetClrTypeFullName(clrType), out typeName, out typeNs); @@ -665,8 +669,8 @@ private static bool InvokeSchemaProviderMethod(Type clrType, XmlSchemaSet schema private static void InvokeGetSchemaMethod(Type clrType, XmlSchemaSet schemas, XmlQualifiedName stableName) { - IXmlSerializable ixmlSerializable = (IXmlSerializable)Activator.CreateInstance(clrType); - XmlSchema schema = ixmlSerializable.GetSchema(); + IXmlSerializable ixmlSerializable = (IXmlSerializable)Activator.CreateInstance(clrType)!; + XmlSchema? schema = ixmlSerializable.GetSchema(); if (schema == null) { AddDefaultDatasetType(schemas, stableName.Name, stableName.Namespace); @@ -714,13 +718,13 @@ private static XmlSchemaComplexType CreateAnyElementType() return anyElementType; } - internal static bool IsSpecialXmlType(Type type, out XmlQualifiedName typeName, out XmlSchemaType xsdType, out bool hasRoot) + internal static bool IsSpecialXmlType(Type type, [NotNullWhen(true)] out XmlQualifiedName? typeName, [NotNullWhen(true)] out XmlSchemaType? xsdType, out bool hasRoot) { xsdType = null; hasRoot = true; if (type == Globals.TypeOfXmlElement || type == Globals.TypeOfXmlNodeArray) { - string name = null; + string? name = null; if (type == Globals.TypeOfXmlElement) { xsdType = CreateAnyElementType(); @@ -780,7 +784,7 @@ private XmlSchemaAnnotation GetSchemaAnnotation(XmlQualifiedName annotationQuali return annotation; } - private static XmlSchemaAnnotation GetSchemaAnnotation(params XmlNode[] nodes) + private static XmlSchemaAnnotation? GetSchemaAnnotation(params XmlNode?[]? nodes) { if (nodes == null || nodes.Length == 0) return null; @@ -841,7 +845,7 @@ internal static XmlSchemaAny ISerializableWildcardElement } } - private static XmlQualifiedName s_anytypeQualifiedName; + private static XmlQualifiedName? s_anytypeQualifiedName; internal static XmlQualifiedName AnytypeQualifiedName { get @@ -852,7 +856,7 @@ internal static XmlQualifiedName AnytypeQualifiedName } } - private static XmlQualifiedName s_stringQualifiedName; + private static XmlQualifiedName? s_stringQualifiedName; internal static XmlQualifiedName StringQualifiedName { get @@ -863,7 +867,7 @@ internal static XmlQualifiedName StringQualifiedName } } - private static XmlQualifiedName s_defaultEnumBaseTypeName; + private static XmlQualifiedName? s_defaultEnumBaseTypeName; internal static XmlQualifiedName DefaultEnumBaseTypeName { get @@ -874,7 +878,7 @@ internal static XmlQualifiedName DefaultEnumBaseTypeName } } - private static XmlQualifiedName s_enumerationValueAnnotationName; + private static XmlQualifiedName? s_enumerationValueAnnotationName; internal static XmlQualifiedName EnumerationValueAnnotationName { get @@ -885,7 +889,7 @@ internal static XmlQualifiedName EnumerationValueAnnotationName } } - private static XmlQualifiedName s_surrogateDataAnnotationName; + private static XmlQualifiedName? s_surrogateDataAnnotationName; internal static XmlQualifiedName SurrogateDataAnnotationName { get @@ -896,7 +900,7 @@ internal static XmlQualifiedName SurrogateDataAnnotationName } } - private static XmlQualifiedName s_defaultValueAnnotation; + private static XmlQualifiedName? s_defaultValueAnnotation; internal static XmlQualifiedName DefaultValueAnnotation { get @@ -907,7 +911,7 @@ internal static XmlQualifiedName DefaultValueAnnotation } } - private static XmlQualifiedName s_actualTypeAnnotationName; + private static XmlQualifiedName? s_actualTypeAnnotationName; internal static XmlQualifiedName ActualTypeAnnotationName { get @@ -918,7 +922,7 @@ internal static XmlQualifiedName ActualTypeAnnotationName } } - private static XmlQualifiedName s_isDictionaryAnnotationName; + private static XmlQualifiedName? s_isDictionaryAnnotationName; internal static XmlQualifiedName IsDictionaryAnnotationName { get @@ -929,7 +933,7 @@ internal static XmlQualifiedName IsDictionaryAnnotationName } } - private static XmlQualifiedName s_isValueTypeName; + private static XmlQualifiedName? s_isValueTypeName; internal static XmlQualifiedName IsValueTypeName { get diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaHelper.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaHelper.cs index abc96431fee2c5..8a07b0e2fc9910 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaHelper.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SchemaHelper.cs @@ -12,7 +12,7 @@ namespace System.Runtime.Serialization internal static class SchemaHelper { - internal static bool NamespacesEqual(string ns1, string ns2) + internal static bool NamespacesEqual(string? ns1, string? ns2) { if (ns1 == null || ns1.Length == 0) return (ns2 == null || ns2.Length == 0); @@ -20,7 +20,7 @@ internal static bool NamespacesEqual(string ns1, string ns2) return ns1 == ns2; } - internal static XmlSchemaType GetSchemaType(XmlSchemaSet schemas, XmlQualifiedName typeQName, out XmlSchema outSchema) + internal static XmlSchemaType? GetSchemaType(XmlSchemaSet schemas, XmlQualifiedName typeQName, out XmlSchema? outSchema) { outSchema = null; ICollection currentSchemas = schemas.Schemas(); @@ -32,7 +32,7 @@ internal static XmlSchemaType GetSchemaType(XmlSchemaSet schemas, XmlQualifiedNa outSchema = schema; foreach (XmlSchemaObject schemaObj in schema.Items) { - XmlSchemaType schemaType = schemaObj as XmlSchemaType; + XmlSchemaType? schemaType = schemaObj as XmlSchemaType; if (schemaType != null && schemaType.Name == typeQName.Name) { return schemaType; @@ -43,7 +43,7 @@ internal static XmlSchemaType GetSchemaType(XmlSchemaSet schemas, XmlQualifiedNa return null; } - internal static XmlSchemaElement GetSchemaElement(XmlSchemaSet schemas, XmlQualifiedName elementQName, out XmlSchema outSchema) + internal static XmlSchemaElement? GetSchemaElement(XmlSchemaSet schemas, XmlQualifiedName elementQName, out XmlSchema? outSchema) { outSchema = null; ICollection currentSchemas = schemas.Schemas(); @@ -55,7 +55,7 @@ internal static XmlSchemaElement GetSchemaElement(XmlSchemaSet schemas, XmlQuali outSchema = schema; foreach (XmlSchemaObject schemaObj in schema.Items) { - XmlSchemaElement schemaElement = schemaObj as XmlSchemaElement; + XmlSchemaElement? schemaElement = schemaObj as XmlSchemaElement; if (schemaElement != null && schemaElement.Name == elementQName.Name) { return schemaElement; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ScopedKnownTypes.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ScopedKnownTypes.cs index dee1799625fbfa..e9414b2a899d20 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ScopedKnownTypes.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/ScopedKnownTypes.cs @@ -25,12 +25,12 @@ internal void Pop() _count--; } - internal DataContract GetDataContract(XmlQualifiedName qname) + internal DataContract? GetDataContract(XmlQualifiedName qname) { for (int i = (_count - 1); i >= 0; i--) { DataContractDictionary dataContractDictionary = dataContractDictionaries[i]; - DataContract dataContract; + DataContract? dataContract; if (dataContractDictionary.TryGetValue(qname, out dataContract)) return dataContract; } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SpecialTypeDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SpecialTypeDataContract.cs index 34816e2fad5d4d..2db16229f71fcb 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SpecialTypeDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SpecialTypeDataContract.cs @@ -11,7 +11,7 @@ internal sealed class SpecialTypeDataContract : DataContract public SpecialTypeDataContract(Type type, XmlDictionaryString name, XmlDictionaryString ns) : base(new SpecialTypeDataContractCriticalHelper(type, name, ns)) { - _helper = base.Helper as SpecialTypeDataContractCriticalHelper; + _helper = (base.Helper as SpecialTypeDataContractCriticalHelper)!; } public override bool IsBuiltInDataContract => true; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SurrogateDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SurrogateDataContract.cs index 354a1d0ef7e864..ebf41ee91263c1 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SurrogateDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/SurrogateDataContract.cs @@ -6,6 +6,7 @@ namespace System.Runtime.Serialization using System; using System.Security; using System.Runtime.CompilerServices; + using System.Diagnostics; internal sealed class SurrogateDataContract : DataContract { @@ -14,7 +15,7 @@ internal sealed class SurrogateDataContract : DataContract internal SurrogateDataContract(Type type, ISerializationSurrogate serializationSurrogate) : base(new SurrogateDataContractCriticalHelper(type, serializationSurrogate)) { - _helper = base.Helper as SurrogateDataContractCriticalHelper; + _helper = (base.Helper as SurrogateDataContractCriticalHelper)!; } internal ISerializationSurrogate SerializationSurrogate @@ -22,21 +23,23 @@ internal ISerializationSurrogate SerializationSurrogate get { return _helper.SerializationSurrogate; } } - public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) + public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext? context) { + Debug.Assert(context != null); + SerializationInfo serInfo = new SerializationInfo(UnderlyingType, XmlObjectSerializer.FormatterConverter, !context.UnsafeTypeForwardingEnabled); SerializationSurrogateGetObjectData(obj, serInfo, context.GetStreamingContext()); context.WriteSerializationInfo(xmlWriter, UnderlyingType, serInfo); } [MethodImpl(MethodImplOptions.NoInlining)] - private object SerializationSurrogateSetObjectData(object obj, SerializationInfo serInfo, StreamingContext context) + private object? SerializationSurrogateSetObjectData(object obj, SerializationInfo serInfo, StreamingContext context) { return SerializationSurrogate.SetObjectData(obj, serInfo, context, null); } [MethodImpl(MethodImplOptions.NoInlining)] - internal static object GetRealObject(IObjectReference obj, StreamingContext context) + internal static object? GetRealObject(IObjectReference obj, StreamingContext context) { return obj.GetRealObject(context); } @@ -53,15 +56,17 @@ private void SerializationSurrogateGetObjectData(object obj, SerializationInfo s SerializationSurrogate.GetObjectData(obj, serInfo, context); } - public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context) + public override object? ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext? context) { + Debug.Assert(context != null); + xmlReader.Read(); Type objType = UnderlyingType; - object obj = objType.IsArray ? Array.CreateInstance(objType.GetElementType(), 0) : GetUninitializedObject(objType); + object obj = objType.IsArray ? Array.CreateInstance(objType.GetElementType()!, 0) : GetUninitializedObject(objType); context.AddNewObject(obj); string objectId = context.GetObjectId(); SerializationInfo serInfo = context.ReadSerializationInfo(xmlReader, objType); - object newObj = SerializationSurrogateSetObjectData(obj, serInfo, context.GetStreamingContext()); + object? newObj = SerializationSurrogateSetObjectData(obj, serInfo, context.GetStreamingContext()); if (newObj == null) newObj = obj; if (newObj is IDeserializationCallback) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XPathQueryGenerator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XPathQueryGenerator.cs index 3422aad47e7717..7c0a0a9bb53769 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XPathQueryGenerator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XPathQueryGenerator.cs @@ -23,7 +23,7 @@ public static string CreateFromDataContractSerializer(Type type, MemberInfo[] pa } // Here you can provide your own root element Xpath which will replace the Xpath of the top level element - public static string CreateFromDataContractSerializer(Type type, MemberInfo[] pathToMember, StringBuilder rootElementXpath, out XmlNamespaceManager namespaces) + public static string CreateFromDataContractSerializer(Type type, MemberInfo[] pathToMember, StringBuilder? rootElementXpath, out XmlNamespaceManager namespaces) { if (type == null) { @@ -67,10 +67,10 @@ private static DataContract ProcessDataContract(DataContract contract, ExportCon private static DataContract ProcessClassDataContract(ClassDataContract contract, ExportContext context, MemberInfo memberNode) { - string prefix = context.SetNamespace(contract.Namespace.Value); + string prefix = context.SetNamespace(contract.Namespace!.Value); foreach (DataMember member in GetDataMembers(contract)) { - if (member.MemberInfo.Name == memberNode.Name && member.MemberInfo.DeclaringType.IsAssignableFrom(memberNode.DeclaringType)) + if (member.MemberInfo.Name == memberNode.Name && member.MemberInfo.DeclaringType!.IsAssignableFrom(memberNode.DeclaringType)) { context.WriteChildToContext(member, prefix); return member.MemberTypeContract; @@ -106,8 +106,8 @@ private class ExportContext public ExportContext(DataContract rootContract) { _namespaces = new XmlNamespaceManager(new NameTable()); - string prefix = SetNamespace(rootContract.TopLevelElementNamespace.Value); - _xPathBuilder = new StringBuilder(XPathQueryGenerator.XPathSeparator + prefix + XPathQueryGenerator.NsSeparator + rootContract.TopLevelElementName.Value); + string prefix = SetNamespace(rootContract.TopLevelElementNamespace!.Value); + _xPathBuilder = new StringBuilder(XPathQueryGenerator.XPathSeparator + prefix + XPathQueryGenerator.NsSeparator + rootContract.TopLevelElementName!.Value); } public ExportContext(StringBuilder rootContractXPath) @@ -139,7 +139,7 @@ public string XPath public string SetNamespace(string ns) { - string prefix = _namespaces.LookupPrefix(ns); + string? prefix = _namespaces.LookupPrefix(ns); if (prefix == null || prefix.Length == 0) { prefix = "xg" + (_nextPrefix++).ToString(NumberFormatInfo.InvariantInfo); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlDataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlDataContract.cs index e18a8db3b7d539..62a1b8bc0e513d 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlDataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlDataContract.cs @@ -20,17 +20,12 @@ internal sealed class XmlDataContract : DataContract { private readonly XmlDataContractCriticalHelper _helper; - public XmlDataContract() : base(new XmlDataContractCriticalHelper()) - { - _helper = base.Helper as XmlDataContractCriticalHelper; - } - internal XmlDataContract(Type type) : base(new XmlDataContractCriticalHelper(type)) { - _helper = base.Helper as XmlDataContractCriticalHelper; + _helper = (base.Helper as XmlDataContractCriticalHelper)!; } - public override DataContractDictionary KnownDataContracts + public override DataContractDictionary? KnownDataContracts { get { return _helper.KnownDataContracts; } @@ -39,7 +34,7 @@ public override DataContractDictionary KnownDataContracts { _helper.KnownDataContracts = value; } } - internal XmlSchemaType XsdType + internal XmlSchemaType? XsdType { get { return _helper.XsdType; } set { _helper.XsdType = value; } @@ -61,7 +56,7 @@ public override bool HasRoot { _helper.HasRoot = value; } } - public override XmlDictionaryString TopLevelElementName + public override XmlDictionaryString? TopLevelElementName { get { return _helper.TopLevelElementName; } @@ -70,7 +65,7 @@ public override XmlDictionaryString TopLevelElementName { _helper.TopLevelElementName = value; } } - public override XmlDictionaryString TopLevelElementNamespace + public override XmlDictionaryString? TopLevelElementNamespace { get { return _helper.TopLevelElementNamespace; } @@ -118,18 +113,14 @@ internal CreateXmlSerializableDelegate CreateXmlSerializableDelegate private class XmlDataContractCriticalHelper : DataContract.DataContractCriticalHelper { - private DataContractDictionary _knownDataContracts; + private DataContractDictionary? _knownDataContracts; private bool _isKnownTypeAttributeChecked; - private XmlDictionaryString _topLevelElementName; - private XmlDictionaryString _topLevelElementNamespace; + private XmlDictionaryString? _topLevelElementName; + private XmlDictionaryString? _topLevelElementNamespace; private bool _isTopLevelElementNullable; private bool _hasRoot; - private CreateXmlSerializableDelegate _createXmlSerializable; - private XmlSchemaType _xsdType; - - internal XmlDataContractCriticalHelper() - { - } + private CreateXmlSerializableDelegate? _createXmlSerializable; + private XmlSchemaType? _xsdType; internal XmlDataContractCriticalHelper(Type type) : base(type) { @@ -137,7 +128,7 @@ internal XmlDataContractCriticalHelper(Type type) : base(type) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.IXmlSerializableCannotHaveDataContract, DataContract.GetClrTypeFullName(type)))); if (type.IsDefined(Globals.TypeOfCollectionDataContractAttribute, false)) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.IXmlSerializableCannotHaveCollectionDataContract, DataContract.GetClrTypeFullName(type)))); - XmlSchemaType xsdType; + XmlSchemaType? xsdType; bool hasRoot; XmlQualifiedName stableName; SchemaExporter.GetXmlTypeInfo(type, out stableName, out xsdType, out hasRoot); @@ -146,7 +137,7 @@ internal XmlDataContractCriticalHelper(Type type) : base(type) XmlDictionary dictionary = new XmlDictionary(); this.Name = dictionary.Add(StableName.Name); this.Namespace = dictionary.Add(StableName.Namespace); - object[] xmlRootAttributes = (UnderlyingType == null) ? null : UnderlyingType.GetCustomAttributes(Globals.TypeOfXmlRootAttribute, false).ToArray(); + object[]? xmlRootAttributes = (UnderlyingType == null) ? null : UnderlyingType.GetCustomAttributes(Globals.TypeOfXmlRootAttribute, false).ToArray(); if (xmlRootAttributes == null || xmlRootAttributes.Length == 0) { if (hasRoot) @@ -164,17 +155,17 @@ internal XmlDataContractCriticalHelper(Type type) : base(type) _isTopLevelElementNullable = xmlRootAttribute.IsNullable; string elementName = xmlRootAttribute.ElementName; _topLevelElementName = (elementName == null || elementName.Length == 0) ? Name : dictionary.Add(DataContract.EncodeLocalName(elementName)); - string elementNs = xmlRootAttribute.Namespace; + string? elementNs = xmlRootAttribute.Namespace; _topLevelElementNamespace = (elementNs == null || elementNs.Length == 0) ? DictionaryGlobals.EmptyString : dictionary.Add(elementNs); } else { - throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.IsAnyCannotHaveXmlRoot, DataContract.GetClrTypeFullName(UnderlyingType)))); + throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.IsAnyCannotHaveXmlRoot, DataContract.GetClrTypeFullName(UnderlyingType!)))); } } } - internal override DataContractDictionary KnownDataContracts + internal override DataContractDictionary? KnownDataContracts { get { @@ -197,7 +188,7 @@ internal override DataContractDictionary KnownDataContracts { _knownDataContracts = value; } } - internal XmlSchemaType XsdType + internal XmlSchemaType? XsdType { get { return _xsdType; } set { _xsdType = value; } @@ -214,7 +205,7 @@ internal override bool HasRoot { _hasRoot = value; } } - internal override XmlDictionaryString TopLevelElementName + internal override XmlDictionaryString? TopLevelElementName { get { return _topLevelElementName; } @@ -222,7 +213,7 @@ internal override XmlDictionaryString TopLevelElementName { _topLevelElementName = value; } } - internal override XmlDictionaryString TopLevelElementNamespace + internal override XmlDictionaryString? TopLevelElementNamespace { get { return _topLevelElementNamespace; } @@ -236,21 +227,21 @@ internal bool IsTopLevelElementNullable set { _isTopLevelElementNullable = value; } } - internal CreateXmlSerializableDelegate CreateXmlSerializableDelegate + internal CreateXmlSerializableDelegate? CreateXmlSerializableDelegate { get { return _createXmlSerializable; } set { _createXmlSerializable = value; } } } - private ConstructorInfo GetConstructor() + private ConstructorInfo? GetConstructor() { Type type = UnderlyingType; if (type.IsValueType) return null; - ConstructorInfo ctor = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, Array.Empty()); + ConstructorInfo? ctor = type.GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, Array.Empty()); if (ctor == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.IXmlSerializableMustHaveDefaultConstructor, DataContract.GetClrTypeFullName(type)))); @@ -288,18 +279,18 @@ internal CreateXmlSerializableDelegate GenerateCreateXmlSerializableDelegate() { // Special case XElement // codegen the same as 'internal XElement : this("default") { }' - ConstructorInfo ctor = GetConstructor(); + ConstructorInfo ctor = GetConstructor()!; if (!ctor.IsPublic && 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( + MethodInfo? XName_op_Implicit = xName.GetMethod( "op_Implicit", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public, new Type[] { typeof(string) } ); - ConstructorInfo XElement_ctor = type.GetConstructor( + ConstructorInfo? XElement_ctor = type.GetConstructor( BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, new Type[] { xName } ); @@ -323,7 +314,7 @@ internal CreateXmlSerializableDelegate GenerateCreateXmlSerializableDelegate() /// since this information is used to determine whether to give the generated code access /// permissions to private members, any changes to the logic should be reviewed. /// - private bool RequiresMemberAccessForCreate(SecurityException securityException) + private bool RequiresMemberAccessForCreate(SecurityException? securityException) { if (!IsTypeVisible(UnderlyingType)) { @@ -358,14 +349,14 @@ internal IXmlSerializable ReflectionCreateXmlSerializable(Type type) } else { - object o = null; + object? o = null; if (type == typeof(System.Xml.Linq.XElement)) { - o = new System.Xml.Linq.XElement("default"); + o = new System.Xml.Linq.XElement("default"!); // TODO-NULLABLE - https://github.com/dotnet/roslyn/issues/39802 } else { - ConstructorInfo ctor = GetConstructor(); + ConstructorInfo ctor = GetConstructor()!; o = ctor.Invoke(Array.Empty()); } @@ -373,7 +364,7 @@ internal IXmlSerializable ReflectionCreateXmlSerializable(Type type) } } - public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext context) + public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, XmlObjectSerializerWriteContext? context) { if (context == null) XmlObjectSerializerWriteContext.WriteRootIXmlSerializable(xmlWriter, obj); @@ -381,9 +372,9 @@ public override void WriteXmlValue(XmlWriterDelegator xmlWriter, object obj, Xml context.WriteIXmlSerializable(xmlWriter, obj); } - public override object ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context) + public override object? ReadXmlValue(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext? context) { - object o; + object? o; if (context == null) { o = XmlObjectSerializerReadContext.ReadRootIXmlSerializable(xmlReader, this, true /*isMemberType*/); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatGeneratorStatics.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatGeneratorStatics.cs index ffac56c8628f3c..fa9a69fdf0aa71 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatGeneratorStatics.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatGeneratorStatics.cs @@ -10,7 +10,7 @@ namespace System.Runtime.Serialization { internal static class XmlFormatGeneratorStatics { - private static MethodInfo s_writeStartElementMethod2; + private static MethodInfo? s_writeStartElementMethod2; internal static MethodInfo WriteStartElementMethod2 { get @@ -24,7 +24,7 @@ internal static MethodInfo WriteStartElementMethod2 } } - private static MethodInfo s_writeStartElementMethod3; + private static MethodInfo? s_writeStartElementMethod3; internal static MethodInfo WriteStartElementMethod3 { get @@ -38,7 +38,7 @@ internal static MethodInfo WriteStartElementMethod3 } } - private static MethodInfo s_writeEndElementMethod; + private static MethodInfo? s_writeEndElementMethod; internal static MethodInfo WriteEndElementMethod { get @@ -52,7 +52,7 @@ internal static MethodInfo WriteEndElementMethod } } - private static MethodInfo s_writeNamespaceDeclMethod; + private static MethodInfo? s_writeNamespaceDeclMethod; internal static MethodInfo WriteNamespaceDeclMethod { get @@ -66,22 +66,25 @@ internal static MethodInfo WriteNamespaceDeclMethod } } - private static PropertyInfo s_extensionDataProperty; + private static PropertyInfo? s_extensionDataProperty; internal static PropertyInfo ExtensionDataProperty => s_extensionDataProperty ?? - (s_extensionDataProperty = typeof(IExtensibleDataObject).GetProperty("ExtensionData")); + (s_extensionDataProperty = typeof(IExtensibleDataObject).GetProperty("ExtensionData")!); - private static ConstructorInfo s_dictionaryEnumeratorCtor; + private static ConstructorInfo? s_dictionaryEnumeratorCtor; internal static ConstructorInfo DictionaryEnumeratorCtor { get { if (s_dictionaryEnumeratorCtor == null) + { s_dictionaryEnumeratorCtor = Globals.TypeOfDictionaryEnumerator.GetConstructor(Globals.ScanAllMembers, new Type[] { Globals.TypeOfIDictionaryEnumerator }); + Debug.Assert(s_dictionaryEnumeratorCtor != null); + } return s_dictionaryEnumeratorCtor; } } - private static MethodInfo s_ienumeratorMoveNextMethod; + private static MethodInfo? s_ienumeratorMoveNextMethod; internal static MethodInfo MoveNextMethod { get @@ -95,35 +98,35 @@ internal static MethodInfo MoveNextMethod } } - private static MethodInfo s_ienumeratorGetCurrentMethod; + private static MethodInfo? s_ienumeratorGetCurrentMethod; internal static MethodInfo GetCurrentMethod { get { if (s_ienumeratorGetCurrentMethod == null) { - s_ienumeratorGetCurrentMethod = typeof(IEnumerator).GetProperty("Current").GetGetMethod(); + s_ienumeratorGetCurrentMethod = typeof(IEnumerator).GetProperty("Current")!.GetGetMethod(); Debug.Assert(s_ienumeratorGetCurrentMethod != null); } return s_ienumeratorGetCurrentMethod; } } - private static MethodInfo s_getItemContractMethod; + private static MethodInfo? s_getItemContractMethod; internal static MethodInfo GetItemContractMethod { get { if (s_getItemContractMethod == null) { - s_getItemContractMethod = typeof(CollectionDataContract).GetProperty("ItemContract", Globals.ScanAllMembers).GetMethod; + s_getItemContractMethod = typeof(CollectionDataContract).GetProperty("ItemContract", Globals.ScanAllMembers)!.GetMethod; Debug.Assert(s_getItemContractMethod != null); } return s_getItemContractMethod; } } - private static MethodInfo s_isStartElementMethod2; + private static MethodInfo? s_isStartElementMethod2; internal static MethodInfo IsStartElementMethod2 { get @@ -137,7 +140,7 @@ internal static MethodInfo IsStartElementMethod2 } } - private static MethodInfo s_isStartElementMethod0; + private static MethodInfo? s_isStartElementMethod0; internal static MethodInfo IsStartElementMethod0 { get @@ -151,7 +154,7 @@ internal static MethodInfo IsStartElementMethod0 } } - private static MethodInfo s_getUninitializedObjectMethod; + private static MethodInfo? s_getUninitializedObjectMethod; internal static MethodInfo GetUninitializedObjectMethod { get @@ -165,18 +168,21 @@ internal static MethodInfo GetUninitializedObjectMethod } } - private static MethodInfo s_onDeserializationMethod; + private static MethodInfo? s_onDeserializationMethod; internal static MethodInfo OnDeserializationMethod { get { if (s_onDeserializationMethod == null) + { s_onDeserializationMethod = typeof(IDeserializationCallback).GetMethod("OnDeserialization"); + Debug.Assert(s_onDeserializationMethod != null); + } return s_onDeserializationMethod; } } - private static PropertyInfo s_nodeTypeProperty; + private static PropertyInfo? s_nodeTypeProperty; internal static PropertyInfo NodeTypeProperty { get @@ -190,23 +196,26 @@ internal static PropertyInfo NodeTypeProperty } } - private static ConstructorInfo s_extensionDataObjectCtor; + private static ConstructorInfo? s_extensionDataObjectCtor; internal static ConstructorInfo ExtensionDataObjectCtor => s_extensionDataObjectCtor ?? (s_extensionDataObjectCtor = - typeof(ExtensionDataObject).GetConstructor(Globals.ScanAllMembers, null, Array.Empty(), null)); + typeof(ExtensionDataObject).GetConstructor(Globals.ScanAllMembers, null, Array.Empty(), null)!); - private static ConstructorInfo s_hashtableCtor; + private static ConstructorInfo? s_hashtableCtor; internal static ConstructorInfo HashtableCtor { get { if (s_hashtableCtor == null) + { s_hashtableCtor = Globals.TypeOfHashtable.GetConstructor(Globals.ScanAllMembers, Array.Empty()); + Debug.Assert(s_hashtableCtor != null); + } return s_hashtableCtor; } } - private static MethodInfo s_getStreamingContextMethod; + private static MethodInfo? s_getStreamingContextMethod; internal static MethodInfo GetStreamingContextMethod { get @@ -220,7 +229,7 @@ internal static MethodInfo GetStreamingContextMethod } } - private static MethodInfo s_getCollectionMemberMethod; + private static MethodInfo? s_getCollectionMemberMethod; internal static MethodInfo GetCollectionMemberMethod { get @@ -234,7 +243,7 @@ internal static MethodInfo GetCollectionMemberMethod } } - private static MethodInfo s_storeCollectionMemberInfoMethod; + private static MethodInfo? s_storeCollectionMemberInfoMethod; internal static MethodInfo StoreCollectionMemberInfoMethod { get @@ -248,7 +257,7 @@ internal static MethodInfo StoreCollectionMemberInfoMethod } } - private static MethodInfo s_resetCollectionMemberInfoMethod; + private static MethodInfo? s_resetCollectionMemberInfoMethod; internal static MethodInfo ResetCollectionMemberInfoMethod { get @@ -262,7 +271,7 @@ internal static MethodInfo ResetCollectionMemberInfoMethod } } - private static MethodInfo s_storeIsGetOnlyCollectionMethod; + private static MethodInfo? s_storeIsGetOnlyCollectionMethod; internal static MethodInfo StoreIsGetOnlyCollectionMethod { get @@ -276,7 +285,7 @@ internal static MethodInfo StoreIsGetOnlyCollectionMethod } } - private static MethodInfo s_resetIsGetOnlyCollection; + private static MethodInfo? s_resetIsGetOnlyCollection; internal static MethodInfo ResetIsGetOnlyCollectionMethod { get @@ -290,7 +299,7 @@ internal static MethodInfo ResetIsGetOnlyCollectionMethod } } - private static MethodInfo s_throwNullValueReturnedForGetOnlyCollectionExceptionMethod; + private static MethodInfo? s_throwNullValueReturnedForGetOnlyCollectionExceptionMethod; internal static MethodInfo ThrowNullValueReturnedForGetOnlyCollectionExceptionMethod { get @@ -304,7 +313,7 @@ internal static MethodInfo ThrowNullValueReturnedForGetOnlyCollectionExceptionMe } } - private static MethodInfo s_throwArrayExceededSizeExceptionMethod; + private static MethodInfo? s_throwArrayExceededSizeExceptionMethod; internal static MethodInfo ThrowArrayExceededSizeExceptionMethod { get @@ -318,7 +327,7 @@ internal static MethodInfo ThrowArrayExceededSizeExceptionMethod } } - private static MethodInfo s_incrementItemCountMethod; + private static MethodInfo? s_incrementItemCountMethod; internal static MethodInfo IncrementItemCountMethod { get @@ -332,7 +341,7 @@ internal static MethodInfo IncrementItemCountMethod } } - private static MethodInfo s_internalDeserializeMethod; + private static MethodInfo? s_internalDeserializeMethod; internal static MethodInfo InternalDeserializeMethod { get @@ -346,7 +355,7 @@ internal static MethodInfo InternalDeserializeMethod } } - private static MethodInfo s_moveToNextElementMethod; + private static MethodInfo? s_moveToNextElementMethod; internal static MethodInfo MoveToNextElementMethod { get @@ -360,7 +369,7 @@ internal static MethodInfo MoveToNextElementMethod } } - private static MethodInfo s_getMemberIndexMethod; + private static MethodInfo? s_getMemberIndexMethod; internal static MethodInfo GetMemberIndexMethod { get @@ -374,7 +383,7 @@ internal static MethodInfo GetMemberIndexMethod } } - private static MethodInfo s_getMemberIndexWithRequiredMembersMethod; + private static MethodInfo? s_getMemberIndexWithRequiredMembersMethod; internal static MethodInfo GetMemberIndexWithRequiredMembersMethod { get @@ -388,7 +397,7 @@ internal static MethodInfo GetMemberIndexWithRequiredMembersMethod } } - private static MethodInfo s_throwRequiredMemberMissingExceptionMethod; + private static MethodInfo? s_throwRequiredMemberMissingExceptionMethod; internal static MethodInfo ThrowRequiredMemberMissingExceptionMethod { get @@ -402,7 +411,7 @@ internal static MethodInfo ThrowRequiredMemberMissingExceptionMethod } } - private static MethodInfo s_skipUnknownElementMethod; + private static MethodInfo? s_skipUnknownElementMethod; internal static MethodInfo SkipUnknownElementMethod { get @@ -416,7 +425,7 @@ internal static MethodInfo SkipUnknownElementMethod } } - private static MethodInfo s_readIfNullOrRefMethod; + private static MethodInfo? s_readIfNullOrRefMethod; internal static MethodInfo ReadIfNullOrRefMethod { get @@ -430,7 +439,7 @@ internal static MethodInfo ReadIfNullOrRefMethod } } - private static MethodInfo s_readAttributesMethod; + private static MethodInfo? s_readAttributesMethod; internal static MethodInfo ReadAttributesMethod { get @@ -444,7 +453,7 @@ internal static MethodInfo ReadAttributesMethod } } - private static MethodInfo s_resetAttributesMethod; + private static MethodInfo? s_resetAttributesMethod; internal static MethodInfo ResetAttributesMethod { get @@ -458,7 +467,7 @@ internal static MethodInfo ResetAttributesMethod } } - private static MethodInfo s_getObjectIdMethod; + private static MethodInfo? s_getObjectIdMethod; internal static MethodInfo GetObjectIdMethod { get @@ -472,7 +481,7 @@ internal static MethodInfo GetObjectIdMethod } } - private static MethodInfo s_getArraySizeMethod; + private static MethodInfo? s_getArraySizeMethod; internal static MethodInfo GetArraySizeMethod { get @@ -486,7 +495,7 @@ internal static MethodInfo GetArraySizeMethod } } - private static MethodInfo s_addNewObjectMethod; + private static MethodInfo? s_addNewObjectMethod; internal static MethodInfo AddNewObjectMethod { get @@ -500,7 +509,7 @@ internal static MethodInfo AddNewObjectMethod } } - private static MethodInfo s_addNewObjectWithIdMethod; + private static MethodInfo? s_addNewObjectWithIdMethod; internal static MethodInfo AddNewObjectWithIdMethod { get @@ -514,7 +523,7 @@ internal static MethodInfo AddNewObjectWithIdMethod } } - private static MethodInfo s_getExistingObjectMethod; + private static MethodInfo? s_getExistingObjectMethod; internal static MethodInfo GetExistingObjectMethod { get @@ -528,18 +537,21 @@ internal static MethodInfo GetExistingObjectMethod } } - private static MethodInfo s_getRealObjectMethod; + private static MethodInfo? s_getRealObjectMethod; internal static MethodInfo GetRealObjectMethod { get { if (s_getRealObjectMethod == null) + { s_getRealObjectMethod = typeof(XmlObjectSerializerReadContext).GetMethod("GetRealObject", Globals.ScanAllMembers); + Debug.Assert(s_getRealObjectMethod != null); + } return s_getRealObjectMethod; } } - private static MethodInfo s_ensureArraySizeMethod; + private static MethodInfo? s_ensureArraySizeMethod; internal static MethodInfo EnsureArraySizeMethod { get @@ -553,7 +565,7 @@ internal static MethodInfo EnsureArraySizeMethod } } - private static MethodInfo s_trimArraySizeMethod; + private static MethodInfo? s_trimArraySizeMethod; internal static MethodInfo TrimArraySizeMethod { get @@ -567,7 +579,7 @@ internal static MethodInfo TrimArraySizeMethod } } - private static MethodInfo s_checkEndOfArrayMethod; + private static MethodInfo? s_checkEndOfArrayMethod; internal static MethodInfo CheckEndOfArrayMethod { get @@ -581,21 +593,21 @@ internal static MethodInfo CheckEndOfArrayMethod } } - private static MethodInfo s_getArrayLengthMethod; + private static MethodInfo? s_getArrayLengthMethod; internal static MethodInfo GetArrayLengthMethod { get { if (s_getArrayLengthMethod == null) { - s_getArrayLengthMethod = Globals.TypeOfArray.GetProperty("Length").GetMethod; + s_getArrayLengthMethod = Globals.TypeOfArray.GetProperty("Length")!.GetMethod; Debug.Assert(s_getArrayLengthMethod != null); } return s_getArrayLengthMethod; } } - private static MethodInfo s_createSerializationExceptionMethod; + private static MethodInfo? s_createSerializationExceptionMethod; internal static MethodInfo CreateSerializationExceptionMethod { get @@ -609,18 +621,21 @@ internal static MethodInfo CreateSerializationExceptionMethod } } - private static MethodInfo s_readSerializationInfoMethod; + private static MethodInfo? s_readSerializationInfoMethod; internal static MethodInfo ReadSerializationInfoMethod { get { if (s_readSerializationInfoMethod == null) + { s_readSerializationInfoMethod = typeof(XmlObjectSerializerReadContext).GetMethod("ReadSerializationInfo", Globals.ScanAllMembers); + Debug.Assert(s_readSerializationInfoMethod != null); + } return s_readSerializationInfoMethod; } } - private static MethodInfo s_createUnexpectedStateExceptionMethod; + private static MethodInfo? s_createUnexpectedStateExceptionMethod; internal static MethodInfo CreateUnexpectedStateExceptionMethod { get @@ -634,7 +649,7 @@ internal static MethodInfo CreateUnexpectedStateExceptionMethod } } - private static MethodInfo s_internalSerializeReferenceMethod; + private static MethodInfo? s_internalSerializeReferenceMethod; internal static MethodInfo InternalSerializeReferenceMethod { get @@ -648,7 +663,7 @@ internal static MethodInfo InternalSerializeReferenceMethod } } - private static MethodInfo s_internalSerializeMethod; + private static MethodInfo? s_internalSerializeMethod; internal static MethodInfo InternalSerializeMethod { get @@ -662,7 +677,7 @@ internal static MethodInfo InternalSerializeMethod } } - private static MethodInfo s_writeNullMethod; + private static MethodInfo? s_writeNullMethod; internal static MethodInfo WriteNullMethod { get @@ -676,7 +691,7 @@ internal static MethodInfo WriteNullMethod } } - private static MethodInfo s_incrementArrayCountMethod; + private static MethodInfo? s_incrementArrayCountMethod; internal static MethodInfo IncrementArrayCountMethod { get @@ -690,7 +705,7 @@ internal static MethodInfo IncrementArrayCountMethod } } - private static MethodInfo s_incrementCollectionCountMethod; + private static MethodInfo? s_incrementCollectionCountMethod; internal static MethodInfo IncrementCollectionCountMethod { get @@ -704,7 +719,7 @@ internal static MethodInfo IncrementCollectionCountMethod } } - private static MethodInfo s_incrementCollectionCountGenericMethod; + private static MethodInfo? s_incrementCollectionCountGenericMethod; internal static MethodInfo IncrementCollectionCountGenericMethod { get @@ -718,7 +733,7 @@ internal static MethodInfo IncrementCollectionCountGenericMethod } } - private static MethodInfo s_getDefaultValueMethod; + private static MethodInfo? s_getDefaultValueMethod; internal static MethodInfo GetDefaultValueMethod { get @@ -732,12 +747,12 @@ internal static MethodInfo GetDefaultValueMethod } } - internal static object GetDefaultValue(Type type) + internal static object? GetDefaultValue(Type type) { return GetDefaultValueMethod.MakeGenericMethod(type).Invoke(null, Array.Empty()); } - private static MethodInfo s_getNullableValueMethod; + private static MethodInfo? s_getNullableValueMethod; internal static MethodInfo GetNullableValueMethod { get @@ -751,7 +766,7 @@ internal static MethodInfo GetNullableValueMethod } } - private static MethodInfo s_throwRequiredMemberMustBeEmittedMethod; + private static MethodInfo? s_throwRequiredMemberMustBeEmittedMethod; internal static MethodInfo ThrowRequiredMemberMustBeEmittedMethod { get @@ -765,7 +780,7 @@ internal static MethodInfo ThrowRequiredMemberMustBeEmittedMethod } } - private static MethodInfo s_getHasValueMethod; + private static MethodInfo? s_getHasValueMethod; internal static MethodInfo GetHasValueMethod { get @@ -779,19 +794,22 @@ internal static MethodInfo GetHasValueMethod } } - private static MethodInfo s_writeISerializableMethod; + private static MethodInfo? s_writeISerializableMethod; internal static MethodInfo WriteISerializableMethod { get { if (s_writeISerializableMethod == null) + { s_writeISerializableMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("WriteISerializable", Globals.ScanAllMembers); + Debug.Assert(s_writeISerializableMethod != null); + } return s_writeISerializableMethod; } } - private static MethodInfo s_isMemberTypeSameAsMemberValue; + private static MethodInfo? s_isMemberTypeSameAsMemberValue; internal static MethodInfo IsMemberTypeSameAsMemberValue { get @@ -805,11 +823,11 @@ internal static MethodInfo IsMemberTypeSameAsMemberValue } } - private static MethodInfo s_writeExtensionDataMethod; + private static MethodInfo? s_writeExtensionDataMethod; internal static MethodInfo WriteExtensionDataMethod => s_writeExtensionDataMethod ?? - (s_writeExtensionDataMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("WriteExtensionData", Globals.ScanAllMembers)); + (s_writeExtensionDataMethod = typeof(XmlObjectSerializerWriteContext).GetMethod("WriteExtensionData", Globals.ScanAllMembers)!); - private static MethodInfo s_writeXmlValueMethod; + private static MethodInfo? s_writeXmlValueMethod; internal static MethodInfo WriteXmlValueMethod { get @@ -823,7 +841,7 @@ internal static MethodInfo WriteXmlValueMethod } } - private static MethodInfo s_readXmlValueMethod; + private static MethodInfo? s_readXmlValueMethod; internal static MethodInfo ReadXmlValueMethod { get @@ -837,7 +855,7 @@ internal static MethodInfo ReadXmlValueMethod } } - private static PropertyInfo s_namespaceProperty; + private static PropertyInfo? s_namespaceProperty; internal static PropertyInfo NamespaceProperty { get @@ -851,7 +869,7 @@ internal static PropertyInfo NamespaceProperty } } - private static FieldInfo s_contractNamespacesField; + private static FieldInfo? s_contractNamespacesField; internal static FieldInfo ContractNamespacesField { get @@ -865,7 +883,7 @@ internal static FieldInfo ContractNamespacesField } } - private static FieldInfo s_memberNamesField; + private static FieldInfo? s_memberNamesField; internal static FieldInfo MemberNamesField { get @@ -879,11 +897,11 @@ internal static FieldInfo MemberNamesField } } - private static MethodInfo s_extensionDataSetExplicitMethodInfo; + private static MethodInfo? s_extensionDataSetExplicitMethodInfo; internal static MethodInfo ExtensionDataSetExplicitMethodInfo => s_extensionDataSetExplicitMethodInfo ?? - (s_extensionDataSetExplicitMethodInfo = typeof(IExtensibleDataObject).GetMethod(Globals.ExtensionDataSetMethod)); + (s_extensionDataSetExplicitMethodInfo = typeof(IExtensibleDataObject).GetMethod(Globals.ExtensionDataSetMethod)!); - private static PropertyInfo s_childElementNamespacesProperty; + private static PropertyInfo? s_childElementNamespacesProperty; internal static PropertyInfo ChildElementNamespacesProperty { get @@ -897,7 +915,7 @@ internal static PropertyInfo ChildElementNamespacesProperty } } - private static PropertyInfo s_collectionItemNameProperty; + private static PropertyInfo? s_collectionItemNameProperty; internal static PropertyInfo CollectionItemNameProperty { get @@ -911,7 +929,7 @@ internal static PropertyInfo CollectionItemNameProperty } } - private static PropertyInfo s_childElementNamespaceProperty; + private static PropertyInfo? s_childElementNamespaceProperty; internal static PropertyInfo ChildElementNamespaceProperty { get @@ -925,7 +943,7 @@ internal static PropertyInfo ChildElementNamespaceProperty } } - private static MethodInfo s_getDateTimeOffsetMethod; + private static MethodInfo? s_getDateTimeOffsetMethod; internal static MethodInfo GetDateTimeOffsetMethod { get @@ -939,7 +957,7 @@ internal static MethodInfo GetDateTimeOffsetMethod } } - private static MethodInfo s_getDateTimeOffsetAdapterMethod; + private static MethodInfo? s_getDateTimeOffsetAdapterMethod; internal static MethodInfo GetDateTimeOffsetAdapterMethod { get @@ -953,7 +971,7 @@ internal static MethodInfo GetDateTimeOffsetAdapterMethod } } - private static MethodInfo s_getTypeHandleMethod; + private static MethodInfo? s_getTypeHandleMethod; internal static MethodInfo GetTypeHandleMethod { get @@ -967,7 +985,7 @@ internal static MethodInfo GetTypeHandleMethod } } - private static MethodInfo s_getTypeMethod; + private static MethodInfo? s_getTypeMethod; internal static MethodInfo GetTypeMethod { get @@ -981,7 +999,7 @@ internal static MethodInfo GetTypeMethod } } - private static MethodInfo s_throwInvalidDataContractExceptionMethod; + private static MethodInfo? s_throwInvalidDataContractExceptionMethod; internal static MethodInfo ThrowInvalidDataContractExceptionMethod { get @@ -995,7 +1013,7 @@ internal static MethodInfo ThrowInvalidDataContractExceptionMethod } } - private static PropertyInfo s_serializeReadOnlyTypesProperty; + private static PropertyInfo? s_serializeReadOnlyTypesProperty; internal static PropertyInfo SerializeReadOnlyTypesProperty { get @@ -1009,7 +1027,7 @@ internal static PropertyInfo SerializeReadOnlyTypesProperty } } - private static PropertyInfo s_classSerializationExceptionMessageProperty; + private static PropertyInfo? s_classSerializationExceptionMessageProperty; internal static PropertyInfo ClassSerializationExceptionMessageProperty { get @@ -1023,7 +1041,7 @@ internal static PropertyInfo ClassSerializationExceptionMessageProperty } } - private static PropertyInfo s_collectionSerializationExceptionMessageProperty; + private static PropertyInfo? s_collectionSerializationExceptionMessageProperty; internal static PropertyInfo CollectionSerializationExceptionMessageProperty { get diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatReaderGenerator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatReaderGenerator.cs index 781e3613740381..7452f500fec3cb 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatReaderGenerator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatReaderGenerator.cs @@ -11,6 +11,8 @@ using System.Collections.Generic; using System.Security; using System.Runtime.CompilerServices; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; namespace System.Runtime.Serialization { @@ -21,7 +23,7 @@ namespace System.Runtime.Serialization public sealed class XmlFormatReaderGenerator #else - internal delegate object XmlFormatClassReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces); + internal delegate object? XmlFormatClassReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext? context, XmlDictionaryString[]? memberNames, XmlDictionaryString[]? memberNamespaces); internal delegate object XmlFormatCollectionReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, CollectionDataContract collectionContract); internal delegate void XmlFormatGetOnlyCollectionReaderDelegate(XmlReaderDelegator xmlReader, XmlObjectSerializerReadContext context, XmlDictionaryString itemName, XmlDictionaryString itemNamespace, CollectionDataContract collectionContract); @@ -57,14 +59,14 @@ public XmlFormatGetOnlyCollectionReaderDelegate GenerateGetOnlyCollectionReader( /// private class CriticalHelper { - private CodeGenerator _ilg; - private LocalBuilder _objectLocal; - private Type _objectType; - private ArgBuilder _xmlReaderArg; - private ArgBuilder _contextArg; - private ArgBuilder _memberNamesArg; - private ArgBuilder _memberNamespacesArg; - private ArgBuilder _collectionContractArg; + private CodeGenerator _ilg = null!; // initialized in GenerateXXXReader + private LocalBuilder? _objectLocal; + private Type? _objectType; + private ArgBuilder _xmlReaderArg = null!; // initialized in InitArgs + private ArgBuilder _contextArg = null!; // initialized in InitArgs + private ArgBuilder _memberNamesArg = null!; // initialized in InitArgs + private ArgBuilder _memberNamespacesArg = null!; // initialized in InitArgs + private ArgBuilder? _collectionContractArg; private XmlFormatClassReaderDelegate CreateReflectionXmlClassReader(ClassDataContract classContract) { @@ -101,7 +103,7 @@ public XmlFormatClassReaderDelegate GenerateClassReader(ClassDataContract classC CreateObject(classContract); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.AddNewObjectMethod, _objectLocal); InvokeOnDeserializing(classContract); - LocalBuilder objectId = null; + LocalBuilder? objectId = null; if (HasFactoryMethod(classContract)) { objectId = _ilg.DeclareLocal(Globals.TypeOfString, "objectIdRead"); @@ -233,7 +235,8 @@ private void InitArgs() _memberNamespacesArg = _ilg.GetArg(3); } - + [MemberNotNull(nameof(_objectType))] + [MemberNotNull(nameof(_objectLocal))] private void CreateObject(ClassDataContract classContract) { Type type = _objectType = classContract.UnderlyingType; @@ -244,7 +247,7 @@ private void CreateObject(ClassDataContract classContract) if (classContract.UnderlyingType == Globals.TypeOfDBNull) { - _ilg.LoadMember(Globals.TypeOfDBNull.GetField("Value")); + _ilg.LoadMember(Globals.TypeOfDBNull.GetField("Value")!); _ilg.Stloc(_objectLocal); } else if (classContract.IsNonAttributedType) @@ -256,7 +259,7 @@ private void CreateObject(ClassDataContract classContract) } else { - _ilg.New(classContract.GetNonAttributedTypeConstructor()); + _ilg.New(classContract.GetNonAttributedTypeConstructor()!); _ilg.Stloc(_objectLocal); } } @@ -270,6 +273,9 @@ private void CreateObject(ClassDataContract classContract) private void InvokeOnDeserializing(ClassDataContract classContract) { + Debug.Assert(_objectLocal != null); + Debug.Assert(_objectType != null); + if (classContract.BaseContract != null) InvokeOnDeserializing(classContract.BaseContract); if (classContract.OnDeserializing != null) @@ -284,6 +290,9 @@ private void InvokeOnDeserializing(ClassDataContract classContract) private void InvokeOnDeserialized(ClassDataContract classContract) { + Debug.Assert(_objectLocal != null); + Debug.Assert(_objectType != null); + if (classContract.BaseContract != null) InvokeOnDeserialized(classContract.BaseContract); if (classContract.OnDeserialized != null) @@ -301,8 +310,10 @@ private bool HasFactoryMethod(ClassDataContract classContract) return Globals.TypeOfIObjectReference.IsAssignableFrom(classContract.UnderlyingType); } - private bool InvokeFactoryMethod(ClassDataContract classContract, LocalBuilder objectId) + private bool InvokeFactoryMethod(ClassDataContract classContract, LocalBuilder? objectId) { + Debug.Assert(_objectLocal != null); + if (HasFactoryMethod(classContract)) { _ilg.Load(_contextArg); @@ -326,10 +337,10 @@ private void ReadClass(ClassDataContract classContract) _ilg.Store(extensionDataLocal); ReadMembers(classContract, extensionDataLocal); - ClassDataContract currentContract = classContract; + ClassDataContract? currentContract = classContract; while (currentContract != null) { - MethodInfo extensionDataSetMethod = currentContract.ExtensionDataSetMethod; + MethodInfo? extensionDataSetMethod = currentContract.ExtensionDataSetMethod; if (extensionDataSetMethod != null) _ilg.Call(_objectLocal, extensionDataSetMethod, extensionDataLocal); currentContract = currentContract.BaseContract; @@ -341,9 +352,9 @@ private void ReadClass(ClassDataContract classContract) } } - private void ReadMembers(ClassDataContract classContract, LocalBuilder extensionDataLocal) + private void ReadMembers(ClassDataContract classContract, LocalBuilder? extensionDataLocal) { - int memberCount = classContract.MemberNames.Length; + int memberCount = classContract.MemberNames!.Length; _ilg.Call(_contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, memberCount); LocalBuilder memberIndexLocal = _ilg.DeclareLocal(Globals.TypeOfInt, "memberIndex", -1); @@ -351,7 +362,7 @@ private void ReadMembers(ClassDataContract classContract, LocalBuilder extension int firstRequiredMember; bool[] requiredMembers = GetRequiredMembers(classContract, out firstRequiredMember); bool hasRequiredMembers = (firstRequiredMember < memberCount); - LocalBuilder requiredIndexLocal = hasRequiredMembers ? _ilg.DeclareLocal(Globals.TypeOfInt, "requiredIndex", firstRequiredMember) : null; + LocalBuilder? requiredIndexLocal = hasRequiredMembers ? _ilg.DeclareLocal(Globals.TypeOfInt, "requiredIndex", firstRequiredMember) : null; object forReadElements = _ilg.For(null, null, null); _ilg.Call(null, XmlFormatGeneratorStatics.MoveToNextElementMethod, _xmlReaderArg); @@ -366,18 +377,21 @@ private void ReadMembers(ClassDataContract classContract, LocalBuilder extension _ilg.EndFor(); if (hasRequiredMembers) { - _ilg.If(requiredIndexLocal, Cmp.LessThan, memberCount); + _ilg.If(requiredIndexLocal!, Cmp.LessThan, memberCount); _ilg.Call(null, XmlFormatGeneratorStatics.ThrowRequiredMemberMissingExceptionMethod, _xmlReaderArg, memberIndexLocal, requiredIndexLocal, _memberNamesArg); _ilg.EndIf(); } } - private int ReadMembers(ClassDataContract classContract, bool[] requiredMembers, Label[] memberLabels, LocalBuilder memberIndexLocal, LocalBuilder requiredIndexLocal) + private int ReadMembers(ClassDataContract classContract, bool[] requiredMembers, Label[] memberLabels, LocalBuilder memberIndexLocal, LocalBuilder? requiredIndexLocal) { + Debug.Assert(_objectLocal != null); + Debug.Assert(_objectType != null); + int memberCount = (classContract.BaseContract == null) ? 0 : ReadMembers(classContract.BaseContract, requiredMembers, memberLabels, memberIndexLocal, requiredIndexLocal); - for (int i = 0; i < classContract.Members.Count; i++, memberCount++) + for (int i = 0; i < classContract.Members!.Count; i++, memberCount++) { DataMember dataMember = classContract.Members[i]; Type memberType = dataMember.MemberType; @@ -388,10 +402,10 @@ private int ReadMembers(ClassDataContract classContract, bool[] requiredMembers, for (; nextRequiredIndex < requiredMembers.Length; nextRequiredIndex++) if (requiredMembers[nextRequiredIndex]) break; - _ilg.Set(requiredIndexLocal, nextRequiredIndex); + _ilg.Set(requiredIndexLocal!, nextRequiredIndex); } - LocalBuilder value = null; + LocalBuilder? value = null; if (dataMember.IsGetOnlyCollection) { @@ -421,7 +435,7 @@ private int ReadMembers(ClassDataContract classContract, bool[] requiredMembers, private bool[] GetRequiredMembers(ClassDataContract contract, out int firstRequiredMember) { - int memberCount = contract.MemberNames.Length; + int memberCount = contract.MemberNames!.Length; bool[] requiredMembers = new bool[memberCount]; GetRequiredMembers(contract, requiredMembers); for (firstRequiredMember = 0; firstRequiredMember < memberCount; firstRequiredMember++) @@ -433,7 +447,7 @@ private bool[] GetRequiredMembers(ClassDataContract contract, out int firstRequi private int GetRequiredMembers(ClassDataContract contract, bool[] requiredMembers) { int memberCount = (contract.BaseContract == null) ? 0 : GetRequiredMembers(contract.BaseContract, requiredMembers); - List members = contract.Members; + List members = contract.Members!; for (int i = 0; i < members.Count; i++, memberCount++) { requiredMembers[memberCount] = members[i].IsRequired; @@ -443,7 +457,10 @@ private int GetRequiredMembers(ClassDataContract contract, bool[] requiredMember private void ReadISerializable(ClassDataContract classContract) { - ConstructorInfo ctor = classContract.GetISerializableConstructor(); + Debug.Assert(_objectLocal != null); + Debug.Assert(_objectType != null); + + ConstructorInfo ctor = classContract.GetISerializableConstructor()!; _ilg.LoadAddress(_objectLocal); _ilg.ConvertAddress(_objectLocal.LocalType, _objectType); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.ReadSerializationInfoMethod, _xmlReaderArg, classContract.UnderlyingType); @@ -455,7 +472,7 @@ private void ReadISerializable(ClassDataContract classContract) private LocalBuilder ReadValue(Type type, string name, string ns) { LocalBuilder value = _ilg.DeclareLocal(type, "valueRead"); - LocalBuilder nullableValue = null; + LocalBuilder? nullableValue = null; int nullables = 0; while (type.IsGenericType && type.GetGenericTypeDefinition() == Globals.TypeOfNullable) { @@ -463,7 +480,7 @@ private LocalBuilder ReadValue(Type type, string name, string ns) type = type.GetGenericArguments()[0]; } - PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type); + PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type); if ((primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject) || nullables != 0 || type.IsValueType) { LocalBuilder objectId = _ilg.DeclareLocal(Globals.TypeOfString, "objectIdRead"); @@ -565,19 +582,20 @@ private void WrapNullableObject(LocalBuilder innerValue, LocalBuilder outerValue for (int i = 1; i < nullables; i++) { Type type = Globals.TypeOfNullable.MakeGenericType(innerType); - _ilg.New(type.GetConstructor(new Type[] { innerType })); + _ilg.New(type.GetConstructor(new Type[] { innerType })!); innerType = type; } - _ilg.Call(outerType.GetConstructor(new Type[] { innerType })); + _ilg.Call(outerType.GetConstructor(new Type[] { innerType })!); } + [MemberNotNull(nameof(_objectLocal))] private void ReadCollection(CollectionDataContract collectionContract) { Type type = collectionContract.UnderlyingType; Type itemType = collectionContract.ItemType; bool isArray = (collectionContract.Kind == CollectionKind.Array); - ConstructorInfo constructor = collectionContract.Constructor; + ConstructorInfo constructor = collectionContract.Constructor!; if (type.IsInterface) { @@ -585,7 +603,7 @@ private void ReadCollection(CollectionDataContract collectionContract) { case CollectionKind.GenericDictionary: type = Globals.TypeOfDictionaryGeneric.MakeGenericType(itemType.GetGenericArguments()); - constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public, Array.Empty()); + constructor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public, Array.Empty())!; break; case CollectionKind.Dictionary: type = Globals.TypeOfHashtable; @@ -638,7 +656,7 @@ private void ReadCollection(CollectionDataContract collectionContract) _ilg.If(size, Cmp.EqualTo, -1); - LocalBuilder growingCollection = null; + LocalBuilder? growingCollection = null; if (isArray) { growingCollection = _ilg.DeclareLocal(type, "growingCollection"); @@ -653,6 +671,7 @@ private void ReadCollection(CollectionDataContract collectionContract) LocalBuilder value = ReadCollectionItem(collectionContract, itemType, itemName, itemNs); if (isArray) { + Debug.Assert(growingCollection != null); MethodInfo ensureArraySizeMethod = XmlFormatGeneratorStatics.EnsureArraySizeMethod.MakeGenericMethod(itemType); _ilg.Call(null, ensureArraySizeMethod, growingCollection, i); _ilg.Stloc(growingCollection); @@ -774,11 +793,13 @@ private void ReadGetOnlyCollection(CollectionDataContract collectionContract) private bool TryReadPrimitiveArray(Type type, Type itemType, LocalBuilder size) { - PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType); + Debug.Assert(_objectLocal != null); + + PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType); if (primitiveContract == null) return false; - string readArrayMethod = null; + string? readArrayMethod = null; switch (itemType.GetTypeCode()) { case TypeCode.Boolean: @@ -813,7 +834,7 @@ private bool TryReadPrimitiveArray(Type type, Type itemType, LocalBuilder size) _ilg.Load(_memberNamespacesArg); _ilg.Load(size); _ilg.Ldloca(_objectLocal); - _ilg.Call(typeof(XmlReaderDelegator).GetMethod(readArrayMethod, Globals.ScanAllMembers)); + _ilg.Call(typeof(XmlReaderDelegator).GetMethod(readArrayMethod, Globals.ScanAllMembers)!); return true; } return false; @@ -842,14 +863,16 @@ private LocalBuilder ReadCollectionItem(CollectionDataContract collectionContrac private void StoreCollectionValue(LocalBuilder collection, LocalBuilder value, CollectionDataContract collectionContract) { + Debug.Assert(collectionContract.AddMethod != null); + if (collectionContract.Kind == CollectionKind.GenericDictionary || collectionContract.Kind == CollectionKind.Dictionary) { - ClassDataContract keyValuePairContract = DataContract.GetDataContract(value.LocalType) as ClassDataContract; + ClassDataContract? keyValuePairContract = DataContract.GetDataContract(value.LocalType) as ClassDataContract; if (keyValuePairContract == null) { DiagnosticUtility.DebugAssert("Failed to create contract for KeyValuePair type"); } - DataMember keyMember = keyValuePairContract.Members[0]; + DataMember keyMember = keyValuePairContract.Members![0]; DataMember valueMember = keyValuePairContract.Members[1]; LocalBuilder pairKey = _ilg.DeclareLocal(keyMember.MemberType, keyMember.Name); LocalBuilder pairValue = _ilg.DeclareLocal(valueMember.MemberType, valueMember.Name); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatWriterGenerator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatWriterGenerator.cs index 2d851570889d73..119bf089adc5a7 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatWriterGenerator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlFormatWriterGenerator.cs @@ -11,6 +11,7 @@ using System.Globalization; using System.Security; using System.Runtime.CompilerServices; +using System.Diagnostics; namespace System.Runtime.Serialization { @@ -49,16 +50,16 @@ internal XmlFormatCollectionWriterDelegate GenerateCollectionWriter(CollectionDa private class CriticalHelper { #if !USE_REFEMIT - private CodeGenerator _ilg; - private ArgBuilder _xmlWriterArg; - private ArgBuilder _contextArg; - private ArgBuilder _dataContractArg; - private LocalBuilder _objectLocal; + private CodeGenerator _ilg = null!; // initialized in GenerateXXXWriter + private ArgBuilder _xmlWriterArg = null!; // initialized in InitArgs + private ArgBuilder _contextArg = null!; // initialized in InitArgs + private ArgBuilder _dataContractArg = null!; // initialized in InitArgs + private LocalBuilder _objectLocal = null!; // initialized in InitArgs // Used for classes - private LocalBuilder _contractNamespacesLocal; - private LocalBuilder _memberNamesLocal; - private LocalBuilder _childElementNamespacesLocal; + private LocalBuilder? _contractNamespacesLocal; + private LocalBuilder? _memberNamesLocal; + private LocalBuilder? _childElementNamespacesLocal; private int _typeIndex = 1; private int _childElementIndex; #endif @@ -167,8 +168,8 @@ private void InitArgs(Type objType) else if (objType.IsGenericType && objType.GetGenericTypeDefinition() == Globals.TypeOfKeyValuePairAdapter) { ClassDataContract dc = (ClassDataContract)DataContract.GetDataContract(objType); - _ilg.ConvertValue(objectArg.ArgType, Globals.TypeOfKeyValuePair.MakeGenericType(dc.KeyValuePairGenericArguments)); - _ilg.New(dc.KeyValuePairAdapterConstructorInfo); + _ilg.ConvertValue(objectArg.ArgType, Globals.TypeOfKeyValuePair.MakeGenericType(dc.KeyValuePairGenericArguments!)); + _ilg.New(dc.KeyValuePairAdapterConstructorInfo!); } else { @@ -214,7 +215,7 @@ private void WriteClass(ClassDataContract classContract) } else { - if (classContract.ContractNamespaces.Length > 1) + if (classContract.ContractNamespaces!.Length > 1) { _contractNamespacesLocal = _ilg.DeclareLocal(typeof(XmlDictionaryString[]), "contractNamespaces"); _ilg.Load(_dataContractArg); @@ -227,7 +228,7 @@ private void WriteClass(ClassDataContract classContract) _ilg.LoadMember(XmlFormatGeneratorStatics.MemberNamesField); _ilg.Store(_memberNamesLocal); - for (int i = 0; i < classContract.ChildElementNamespaces.Length; i++) + for (int i = 0; i < classContract.ChildElementNamespaces!.Length; i++) { if (classContract.ChildElementNamespaces[i] != null) { @@ -256,7 +257,7 @@ private void WriteClass(ClassDataContract classContract) InvokeOnSerialized(classContract); } - private int WriteMembers(ClassDataContract classContract, LocalBuilder extensionDataLocal, ClassDataContract derivedMostClassContract) + private int WriteMembers(ClassDataContract classContract, LocalBuilder? extensionDataLocal, ClassDataContract derivedMostClassContract) { int memberCount = (classContract.BaseContract == null) ? 0 : WriteMembers(classContract.BaseContract, extensionDataLocal, derivedMostClassContract); @@ -274,14 +275,14 @@ private int WriteMembers(ClassDataContract classContract, LocalBuilder extension _ilg.Store(namespaceLocal); - int classMemberCount = classContract.Members.Count; + int classMemberCount = classContract.Members!.Count; _ilg.Call(thisObj: _contextArg, XmlFormatGeneratorStatics.IncrementItemCountMethod, classMemberCount); for (int i = 0; i < classMemberCount; i++, memberCount++) { DataMember member = classContract.Members[i]; Type memberType = member.MemberType; - LocalBuilder memberValue = null; + LocalBuilder? memberValue = null; _ilg.Load(_contextArg); _ilg.Call(methodInfo: member.IsGetOnlyCollection ? @@ -297,10 +298,10 @@ private int WriteMembers(ClassDataContract classContract, LocalBuilder extension if (writeXsiType || !TryWritePrimitive(memberType, memberValue, member.MemberInfo, arrayItemIndex: null, ns: namespaceLocal, name: null, nameIndex: i + _childElementIndex)) { WriteStartElement(memberType, classContract.Namespace, namespaceLocal, nameLocal: null, nameIndex: i + _childElementIndex); - if (classContract.ChildElementNamespaces[i + _childElementIndex] != null) + if (classContract.ChildElementNamespaces![i + _childElementIndex] != null) { _ilg.Load(_xmlWriterArg); - _ilg.LoadArrayElement(_childElementNamespacesLocal, i + _childElementIndex); + _ilg.LoadArrayElement(_childElementNamespacesLocal!, i + _childElementIndex); _ilg.Call(methodInfo: XmlFormatGeneratorStatics.WriteNamespaceDeclMethod); } if (memberValue == null) @@ -383,7 +384,9 @@ private void WriteCollection(CollectionDataContract collectionContract) } else { - MethodInfo incrementCollectionCountMethod = null; + Debug.Assert(collectionContract.GetEnumeratorMethod != null); + + MethodInfo? incrementCollectionCountMethod = null; switch (collectionContract.Kind) { case CollectionKind.Collection: @@ -405,8 +408,8 @@ private void WriteCollection(CollectionDataContract collectionContract) } bool isDictionary = false, isGenericDictionary = false; - Type enumeratorType = null; - Type[] keyValueTypes = null; + Type? enumeratorType = null; + Type[]? keyValueTypes = null; if (collectionContract.Kind == CollectionKind.GenericDictionary) { isGenericDictionary = true; @@ -423,8 +426,8 @@ private void WriteCollection(CollectionDataContract collectionContract) { enumeratorType = collectionContract.GetEnumeratorMethod.ReturnType; } - MethodInfo moveNextMethod = enumeratorType.GetMethod(Globals.MoveNextMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty()); - MethodInfo getCurrentMethod = enumeratorType.GetMethod(Globals.GetCurrentMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty()); + MethodInfo? moveNextMethod = enumeratorType.GetMethod(Globals.MoveNextMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty()); + MethodInfo? getCurrentMethod = enumeratorType.GetMethod(Globals.GetCurrentMethodName, BindingFlags.Instance | BindingFlags.Public, Array.Empty()); if (moveNextMethod == null || getCurrentMethod == null) { if (enumeratorType.IsInterface) @@ -453,9 +456,9 @@ private void WriteCollection(CollectionDataContract collectionContract) } } if (moveNextMethod == null) - moveNextMethod = CollectionDataContract.GetTargetMethodWithName(Globals.MoveNextMethodName, enumeratorType, ienumeratorInterface); + moveNextMethod = CollectionDataContract.GetTargetMethodWithName(Globals.MoveNextMethodName, enumeratorType, ienumeratorInterface)!; if (getCurrentMethod == null) - getCurrentMethod = CollectionDataContract.GetTargetMethodWithName(Globals.GetCurrentMethodName, enumeratorType, ienumeratorInterface); + getCurrentMethod = CollectionDataContract.GetTargetMethodWithName(Globals.GetCurrentMethodName, enumeratorType, ienumeratorInterface)!; } } Type elementType = getCurrentMethod.ReturnType; @@ -470,8 +473,8 @@ private void WriteCollection(CollectionDataContract collectionContract) } else if (isGenericDictionary) { - Type ctorParam = Globals.TypeOfIEnumeratorGeneric.MakeGenericType(Globals.TypeOfKeyValuePair.MakeGenericType(keyValueTypes)); - ConstructorInfo dictEnumCtor = enumeratorType.GetConstructor(Globals.ScanAllMembers, new Type[] { ctorParam }); + Type ctorParam = Globals.TypeOfIEnumeratorGeneric.MakeGenericType(Globals.TypeOfKeyValuePair.MakeGenericType(keyValueTypes!)); + ConstructorInfo dictEnumCtor = enumeratorType.GetConstructor(Globals.ScanAllMembers, new Type[] { ctorParam })!; _ilg.ConvertValue(collectionContract.GetEnumeratorMethod.ReturnType, ctorParam); _ilg.New(dictEnumCtor); } @@ -505,9 +508,9 @@ private void WriteCollection(CollectionDataContract collectionContract) } } - private bool TryWritePrimitive(Type type, LocalBuilder value, MemberInfo memberInfo, LocalBuilder arrayItemIndex, LocalBuilder ns, LocalBuilder name, int nameIndex) + private bool TryWritePrimitive(Type type, LocalBuilder? value, MemberInfo? memberInfo, LocalBuilder? arrayItemIndex, LocalBuilder ns, LocalBuilder? name, int nameIndex) { - PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type); + PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(type); if (primitiveContract == null || primitiveContract.UnderlyingType == Globals.TypeOfObject) return false; @@ -542,7 +545,7 @@ private bool TryWritePrimitive(Type type, LocalBuilder value, MemberInfo memberI } else { - _ilg.LoadArrayElement(_memberNamesLocal, nameIndex); + _ilg.LoadArrayElement(_memberNamesLocal!, nameIndex); } // load namespace _ilg.Load(ns); @@ -553,11 +556,11 @@ private bool TryWritePrimitive(Type type, LocalBuilder value, MemberInfo memberI private bool TryWritePrimitiveArray(Type type, Type itemType, LocalBuilder value, LocalBuilder itemName, LocalBuilder itemNamespace) { - PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType); + PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(itemType); if (primitiveContract == null) return false; - string writeArrayMethod = null; + string? writeArrayMethod = null; switch (itemType.GetTypeCode()) { case TypeCode.Boolean: @@ -590,7 +593,7 @@ private bool TryWritePrimitiveArray(Type type, Type itemType, LocalBuilder value _ilg.Load(value); _ilg.Load(itemName); _ilg.Load(itemNamespace); - _ilg.Call(typeof(XmlWriterDelegator).GetMethod(writeArrayMethod, Globals.ScanAllMembers, new Type[] { type, typeof(XmlDictionaryString), typeof(XmlDictionaryString) })); + _ilg.Call(typeof(XmlWriterDelegator).GetMethod(writeArrayMethod, Globals.ScanAllMembers, new Type[] { type, typeof(XmlDictionaryString), typeof(XmlDictionaryString) })!); return true; } return false; @@ -603,7 +606,7 @@ private void WriteValue(LocalBuilder memberValue, bool writeXsiType) memberType.GetGenericTypeDefinition() == Globals.TypeOfNullable); if (memberType.IsValueType && !isNullableOfT) { - PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType); + PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType); if (primitiveContract != null && !writeXsiType) _ilg.Call(_xmlWriterArg, primitiveContract.XmlFormatContentWriterMethod, memberValue); else @@ -625,7 +628,7 @@ private void WriteValue(LocalBuilder memberValue, bool writeXsiType) _ilg.If(); _ilg.Call(_contextArg, XmlFormatGeneratorStatics.WriteNullMethod, _xmlWriterArg, memberType, DataContract.IsTypeSerializable(memberType)); _ilg.Else(); - PrimitiveDataContract primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType); + PrimitiveDataContract? primitiveContract = PrimitiveDataContract.GetPrimitiveDataContract(memberType); if (primitiveContract != null && primitiveContract.UnderlyingType != Globals.TypeOfObject && !writeXsiType) { if (isNullableOfT) @@ -712,7 +715,7 @@ private bool NeedsPrefix(Type type, XmlDictionaryString ns) return type == Globals.TypeOfXmlQualifiedName && (ns != null && ns.Value != null && ns.Value.Length > 0); } - private void WriteStartElement(Type type, XmlDictionaryString ns, LocalBuilder namespaceLocal, LocalBuilder nameLocal, int nameIndex) + private void WriteStartElement(Type type, XmlDictionaryString ns, LocalBuilder namespaceLocal, LocalBuilder? nameLocal, int nameIndex) { bool needsPrefix = NeedsPrefix(type, ns); _ilg.Load(_xmlWriterArg); @@ -722,7 +725,7 @@ private void WriteStartElement(Type type, XmlDictionaryString ns, LocalBuilder n // localName if (nameLocal == null) - _ilg.LoadArrayElement(_memberNamesLocal, nameIndex); + _ilg.LoadArrayElement(_memberNamesLocal!, nameIndex); else _ilg.Load(nameLocal); @@ -746,12 +749,12 @@ private bool CheckIfMemberHasConflict(DataMember member, ClassDataContract class // Check for conflict with derived type members string name = member.Name; string ns = classContract.StableName.Namespace; - ClassDataContract currentContract = derivedMostClassContract; + ClassDataContract? currentContract = derivedMostClassContract; while (currentContract != null && currentContract != classContract) { if (ns == currentContract.StableName.Namespace) { - List members = currentContract.Members; + List members = currentContract.Members!; for (int j = 0; j < members.Count; j++) { if (name == members[j].Name) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializer.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializer.cs index d39117ad1b68c3..4d452bf64dc576 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializer.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializer.cs @@ -15,11 +15,11 @@ namespace System.Runtime.Serialization public abstract class XmlObjectSerializer { - public abstract void WriteStartObject(XmlDictionaryWriter writer, object graph); - public abstract void WriteObjectContent(XmlDictionaryWriter writer, object graph); + public abstract void WriteStartObject(XmlDictionaryWriter writer, object? graph); + public abstract void WriteObjectContent(XmlDictionaryWriter writer, object? graph); public abstract void WriteEndObject(XmlDictionaryWriter writer); - public virtual void WriteObject(Stream stream, object graph) + public virtual void WriteObject(Stream stream, object? graph) { CheckNull(stream, nameof(stream)); XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(stream, Encoding.UTF8, false /*ownsStream*/); @@ -27,19 +27,19 @@ public virtual void WriteObject(Stream stream, object graph) writer.Flush(); } - public virtual void WriteObject(XmlWriter writer, object graph) + public virtual void WriteObject(XmlWriter writer, object? graph) { CheckNull(writer, nameof(writer)); WriteObject(XmlDictionaryWriter.CreateDictionaryWriter(writer), graph); } - public virtual void WriteStartObject(XmlWriter writer, object graph) + public virtual void WriteStartObject(XmlWriter writer, object? graph) { CheckNull(writer, nameof(writer)); WriteStartObject(XmlDictionaryWriter.CreateDictionaryWriter(writer), graph); } - public virtual void WriteObjectContent(XmlWriter writer, object graph) + public virtual void WriteObjectContent(XmlWriter writer, object? graph) { CheckNull(writer, nameof(writer)); WriteObjectContent(XmlDictionaryWriter.CreateDictionaryWriter(writer), graph); @@ -51,17 +51,17 @@ public virtual void WriteEndObject(XmlWriter writer) WriteEndObject(XmlDictionaryWriter.CreateDictionaryWriter(writer)); } - public virtual void WriteObject(XmlDictionaryWriter writer, object graph) + public virtual void WriteObject(XmlDictionaryWriter writer, object? graph) { WriteObjectHandleExceptions(new XmlWriterDelegator(writer), graph); } - internal void WriteObjectHandleExceptions(XmlWriterDelegator writer, object graph) + internal void WriteObjectHandleExceptions(XmlWriterDelegator writer, object? graph) { WriteObjectHandleExceptions(writer, graph, null); } - internal void WriteObjectHandleExceptions(XmlWriterDelegator writer, object graph, DataContractResolver dataContractResolver) + internal void WriteObjectHandleExceptions(XmlWriterDelegator writer, object? graph, DataContractResolver? dataContractResolver) { try { @@ -80,7 +80,7 @@ internal void WriteObjectHandleExceptions(XmlWriterDelegator writer, object grap } } - internal virtual DataContractDictionary KnownDataContracts + internal virtual DataContractDictionary? KnownDataContracts { get { @@ -88,24 +88,24 @@ internal virtual DataContractDictionary KnownDataContracts } } - internal virtual void InternalWriteObject(XmlWriterDelegator writer, object graph) + internal virtual void InternalWriteObject(XmlWriterDelegator writer, object? graph) { WriteStartObject(writer.Writer, graph); WriteObjectContent(writer.Writer, graph); WriteEndObject(writer.Writer); } - internal virtual void InternalWriteObject(XmlWriterDelegator writer, object graph, DataContractResolver dataContractResolver) + internal virtual void InternalWriteObject(XmlWriterDelegator writer, object? graph, DataContractResolver? dataContractResolver) { InternalWriteObject(writer, graph); } - internal virtual void InternalWriteStartObject(XmlWriterDelegator writer, object graph) + internal virtual void InternalWriteStartObject(XmlWriterDelegator writer, object? graph) { DiagnosticUtility.DebugAssert("XmlObjectSerializer.InternalWriteStartObject should never get called"); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } - internal virtual void InternalWriteObjectContent(XmlWriterDelegator writer, object graph) + internal virtual void InternalWriteObjectContent(XmlWriterDelegator writer, object? graph) { DiagnosticUtility.DebugAssert("XmlObjectSerializer.InternalWriteObjectContent should never get called"); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); @@ -116,7 +116,7 @@ internal virtual void InternalWriteEndObject(XmlWriterDelegator writer) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } - internal void WriteStartObjectHandleExceptions(XmlWriterDelegator writer, object graph) + internal void WriteStartObjectHandleExceptions(XmlWriterDelegator writer, object? graph) { try { @@ -133,7 +133,7 @@ internal void WriteStartObjectHandleExceptions(XmlWriterDelegator writer, object } } - internal void WriteObjectContentHandleExceptions(XmlWriterDelegator writer, object graph) + internal void WriteObjectContentHandleExceptions(XmlWriterDelegator writer, object? graph) { try { @@ -171,13 +171,13 @@ internal void WriteEndObjectHandleExceptions(XmlWriterDelegator writer) } } - internal void WriteRootElement(XmlWriterDelegator writer, DataContract contract, XmlDictionaryString name, XmlDictionaryString ns, bool needsContractNsAtRoot) + internal void WriteRootElement(XmlWriterDelegator writer, DataContract contract, XmlDictionaryString? name, XmlDictionaryString? ns, bool needsContractNsAtRoot) { if (name == null) // root name not set explicitly { if (!contract.HasRoot) return; - contract.WriteRootElement(writer, contract.TopLevelElementName, contract.TopLevelElementNamespace); + contract.WriteRootElement(writer, contract.TopLevelElementName!, contract.TopLevelElementNamespace); } else { @@ -189,7 +189,7 @@ internal void WriteRootElement(XmlWriterDelegator writer, DataContract contract, } } - internal bool CheckIfNeedsContractNsAtRoot(XmlDictionaryString name, XmlDictionaryString ns, DataContract contract) + internal bool CheckIfNeedsContractNsAtRoot(XmlDictionaryString? name, XmlDictionaryString? ns, DataContract contract) { if (name == null) return false; @@ -199,7 +199,7 @@ internal bool CheckIfNeedsContractNsAtRoot(XmlDictionaryString name, XmlDictiona return false; } - string contractNs = XmlDictionaryString.GetString(contract.Namespace); + string? contractNs = XmlDictionaryString.GetString(contract.Namespace); if (string.IsNullOrEmpty(contractNs) || contractNs == XmlDictionaryString.GetString(ns)) return false; @@ -217,30 +217,30 @@ internal static bool IsContractDeclared(DataContract contract, DataContract decl || (contract.Name.Value == declaredContract.Name.Value && contract.Namespace.Value == declaredContract.Namespace.Value); } - public virtual object ReadObject(Stream stream) + public virtual object? ReadObject(Stream stream) { CheckNull(stream, nameof(stream)); return ReadObject(XmlDictionaryReader.CreateTextReader(stream, XmlDictionaryReaderQuotas.Max)); } - public virtual object ReadObject(XmlReader reader) + public virtual object? ReadObject(XmlReader reader) { CheckNull(reader, nameof(reader)); return ReadObject(XmlDictionaryReader.CreateDictionaryReader(reader)); } - public virtual object ReadObject(XmlDictionaryReader reader) + public virtual object? ReadObject(XmlDictionaryReader reader) { return ReadObjectHandleExceptions(new XmlReaderDelegator(reader), true /*verifyObjectName*/); } - public virtual object ReadObject(XmlReader reader, bool verifyObjectName) + public virtual object? ReadObject(XmlReader reader, bool verifyObjectName) { CheckNull(reader, nameof(reader)); return ReadObject(XmlDictionaryReader.CreateDictionaryReader(reader), verifyObjectName); } - public abstract object ReadObject(XmlDictionaryReader reader, bool verifyObjectName); + public abstract object? ReadObject(XmlDictionaryReader reader, bool verifyObjectName); public virtual bool IsStartObject(XmlReader reader) { @@ -250,12 +250,12 @@ public virtual bool IsStartObject(XmlReader reader) public abstract bool IsStartObject(XmlDictionaryReader reader); - internal virtual object InternalReadObject(XmlReaderDelegator reader, bool verifyObjectName) + internal virtual object? InternalReadObject(XmlReaderDelegator reader, bool verifyObjectName) { return ReadObject(reader.UnderlyingReader, verifyObjectName); } - internal virtual object InternalReadObject(XmlReaderDelegator reader, bool verifyObjectName, DataContractResolver dataContractResolver) + internal virtual object? InternalReadObject(XmlReaderDelegator reader, bool verifyObjectName, DataContractResolver? dataContractResolver) { return InternalReadObject(reader, verifyObjectName); } @@ -266,12 +266,12 @@ internal virtual bool InternalIsStartObject(XmlReaderDelegator reader) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } - internal object ReadObjectHandleExceptions(XmlReaderDelegator reader, bool verifyObjectName) + internal object? ReadObjectHandleExceptions(XmlReaderDelegator reader, bool verifyObjectName) { return ReadObjectHandleExceptions(reader, verifyObjectName, null); } - internal object ReadObjectHandleExceptions(XmlReaderDelegator reader, bool verifyObjectName, DataContractResolver dataContractResolver) + internal object? ReadObjectHandleExceptions(XmlReaderDelegator reader, bool verifyObjectName, DataContractResolver? dataContractResolver) { try { @@ -305,7 +305,7 @@ internal bool IsStartObjectHandleExceptions(XmlReaderDelegator reader) } } - internal bool IsRootXmlAny(XmlDictionaryString rootName, DataContract contract) + internal bool IsRootXmlAny(XmlDictionaryString? rootName, DataContract contract) { return (rootName == null) && !contract.HasRoot; } @@ -315,34 +315,34 @@ internal bool IsStartElement(XmlReaderDelegator reader) return (reader.MoveToElement() || reader.IsStartElement()); } - internal bool IsRootElement(XmlReaderDelegator reader, DataContract contract, XmlDictionaryString name, XmlDictionaryString ns) + internal bool IsRootElement(XmlReaderDelegator reader, DataContract contract, XmlDictionaryString? name, XmlDictionaryString? ns) { reader.MoveToElement(); if (name != null) // root name set explicitly { - return reader.IsStartElement(name, ns); + return reader.IsStartElement(name, ns!); // https://github.com/dotnet/runtime/issues/41395 } else { if (!contract.HasRoot) return reader.IsStartElement(); - if (reader.IsStartElement(contract.TopLevelElementName, contract.TopLevelElementNamespace)) + if (reader.IsStartElement(contract.TopLevelElementName!, contract.TopLevelElementNamespace!)) return true; - ClassDataContract classContract = contract as ClassDataContract; + ClassDataContract? classContract = contract as ClassDataContract; if (classContract != null) classContract = classContract.BaseContract; while (classContract != null) { - if (reader.IsStartElement(classContract.TopLevelElementName, classContract.TopLevelElementNamespace)) + if (reader.IsStartElement(classContract.TopLevelElementName!, classContract.TopLevelElementNamespace!)) return true; classContract = classContract.BaseContract; } if (classContract == null) { - DataContract objectContract = PrimitiveDataContract.GetPrimitiveDataContract(Globals.TypeOfObject); - if (reader.IsStartElement(objectContract.TopLevelElementName, objectContract.TopLevelElementNamespace)) + DataContract objectContract = PrimitiveDataContract.GetPrimitiveDataContract(Globals.TypeOfObject)!; + if (reader.IsStartElement(objectContract.TopLevelElementName!, objectContract.TopLevelElementNamespace!)) return true; } return false; @@ -373,28 +373,28 @@ internal static SerializationException CreateSerializationException(string error } [MethodImpl(MethodImplOptions.NoInlining)] - internal static SerializationException CreateSerializationException(string errorMessage, Exception innerException) + internal static SerializationException CreateSerializationException(string errorMessage, Exception? innerException) { return new SerializationException(errorMessage, innerException); } - internal static string GetTypeInfoError(string errorMessage, Type type, Exception innerException) + internal static string GetTypeInfoError(string errorMessage, Type? type, Exception innerException) { string typeInfo = (type == null) ? string.Empty : SR.Format(SR.ErrorTypeInfo, DataContract.GetClrTypeFullName(type)); string innerExceptionMessage = (innerException == null) ? string.Empty : innerException.Message; return SR.Format(errorMessage, typeInfo, innerExceptionMessage); } - internal virtual Type GetSerializeType(object graph) + internal virtual Type? GetSerializeType(object? graph) { return (graph == null) ? null : graph.GetType(); } - internal virtual Type GetDeserializeType() + internal virtual Type? GetDeserializeType() { return null; } - private static IFormatterConverter s_formatterConverter; + private static IFormatterConverter? s_formatterConverter; internal static IFormatterConverter FormatterConverter { get diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerContext.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerContext.cs index 1fcb25cd86ed62..7dd8debf5379aa 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerContext.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerContext.cs @@ -18,20 +18,20 @@ internal class XmlObjectSerializerContext #endif { protected XmlObjectSerializer serializer; - protected DataContract rootTypeDataContract; + protected DataContract? rootTypeDataContract; internal ScopedKnownTypes scopedKnownTypes; - protected DataContractDictionary serializerKnownDataContracts; + protected DataContractDictionary? serializerKnownDataContracts; private bool _isSerializerKnownDataContractsSetExplicit; - protected IList serializerKnownTypeList; + protected IList? serializerKnownTypeList; private int _itemCount; private readonly int _maxItemsInObjectGraph; private readonly StreamingContext _streamingContext; private readonly bool _ignoreExtensionDataObject; - private readonly DataContractResolver _dataContractResolver; - private KnownTypeDataContractResolver _knownTypeResolver; + private readonly DataContractResolver? _dataContractResolver; + private KnownTypeDataContractResolver? _knownTypeResolver; internal XmlObjectSerializerContext(XmlObjectSerializer serializer, int maxItemsInObjectGraph, StreamingContext streamingContext, bool ignoreExtensionDataObject, - DataContractResolver dataContractResolver) + DataContractResolver? dataContractResolver) { this.serializer = serializer; _itemCount = 1; @@ -46,7 +46,7 @@ internal XmlObjectSerializerContext(XmlObjectSerializer serializer, int maxItems { } - internal XmlObjectSerializerContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver) + internal XmlObjectSerializerContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver? dataContractResolver) : this(serializer, serializer.MaxItemsInObjectGraph, default(StreamingContext), @@ -102,7 +102,7 @@ internal bool IgnoreExtensionDataObject get { return _ignoreExtensionDataObject; } } - protected DataContractResolver DataContractResolver + protected DataContractResolver? DataContractResolver { get { return _dataContractResolver; } } @@ -124,7 +124,7 @@ internal DataContract GetDataContract(Type type) return GetDataContract(type.TypeHandle, type); } - internal virtual DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type type) + internal virtual DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type? type) { if (IsGetOnlyCollection) { @@ -136,7 +136,7 @@ internal virtual DataContract GetDataContract(RuntimeTypeHandle typeHandle, Type } } - internal virtual DataContract GetDataContractSkipValidation(int typeId, RuntimeTypeHandle typeHandle, Type type) + internal virtual DataContract GetDataContractSkipValidation(int typeId, RuntimeTypeHandle typeHandle, Type? type) { if (IsGetOnlyCollection) { @@ -171,7 +171,7 @@ internal virtual Type GetSurrogatedType(Type type) { return type; } - internal virtual DataContractDictionary SerializerKnownDataContracts + internal virtual DataContractDictionary? SerializerKnownDataContracts { get { @@ -185,16 +185,16 @@ internal virtual DataContractDictionary SerializerKnownDataContracts } } - private DataContract GetDataContractFromSerializerKnownTypes(XmlQualifiedName qname) + private DataContract? GetDataContractFromSerializerKnownTypes(XmlQualifiedName qname) { - DataContractDictionary serializerKnownDataContracts = this.SerializerKnownDataContracts; + DataContractDictionary? serializerKnownDataContracts = this.SerializerKnownDataContracts; if (serializerKnownDataContracts == null) return null; - DataContract outDataContract; + DataContract? outDataContract; return serializerKnownDataContracts.TryGetValue(qname, out outDataContract) ? outDataContract : null; } - internal static DataContractDictionary GetDataContractsForKnownTypes(IList knownTypeList) + internal static DataContractDictionary? GetDataContractsForKnownTypes(IList knownTypeList) { if (knownTypeList == null) return null; DataContractDictionary dataContracts = new DataContractDictionary(); @@ -210,7 +210,7 @@ internal static DataContractDictionary GetDataContractsForKnownTypes(IList return dataContracts; } - internal bool IsKnownType(DataContract dataContract, DataContractDictionary knownDataContracts, Type declaredType) + internal bool IsKnownType(DataContract dataContract, DataContractDictionary? knownDataContracts, Type? declaredType) { bool knownTypesAddedInCurrentScope = false; if (knownDataContracts != null) @@ -228,21 +228,21 @@ internal bool IsKnownType(DataContract dataContract, DataContractDictionary know return isKnownType; } - internal bool IsKnownType(DataContract dataContract, Type declaredType) + internal bool IsKnownType(DataContract dataContract, Type? declaredType) { - DataContract knownContract = ResolveDataContractFromKnownTypes(dataContract.StableName.Name, dataContract.StableName.Namespace, null /*memberTypeContract*/, declaredType); + DataContract? knownContract = ResolveDataContractFromKnownTypes(dataContract.StableName.Name, dataContract.StableName.Namespace, null /*memberTypeContract*/, declaredType); return knownContract != null && knownContract.UnderlyingType == dataContract.UnderlyingType; } - internal Type ResolveNameFromKnownTypes(XmlQualifiedName typeName) + internal Type? ResolveNameFromKnownTypes(XmlQualifiedName typeName) { - DataContract dataContract = ResolveDataContractFromKnownTypes(typeName); + DataContract? dataContract = ResolveDataContractFromKnownTypes(typeName); return dataContract == null ? null : dataContract.UnderlyingType; } - private DataContract ResolveDataContractFromKnownTypes(XmlQualifiedName typeName) + private DataContract? ResolveDataContractFromKnownTypes(XmlQualifiedName typeName) { - DataContract dataContract = PrimitiveDataContract.GetPrimitiveDataContract(typeName.Name, typeName.Namespace); + DataContract? dataContract = PrimitiveDataContract.GetPrimitiveDataContract(typeName.Name, typeName.Namespace); if (dataContract == null) { dataContract = scopedKnownTypes.GetDataContract(typeName); @@ -254,17 +254,17 @@ private DataContract ResolveDataContractFromKnownTypes(XmlQualifiedName typeName return dataContract; } - protected DataContract ResolveDataContractFromKnownTypes(string typeName, string typeNs, DataContract memberTypeContract, Type declaredType) + protected DataContract? ResolveDataContractFromKnownTypes(string typeName, string? typeNs, DataContract? memberTypeContract, Type? declaredType) { XmlQualifiedName qname = new XmlQualifiedName(typeName, typeNs); - DataContract dataContract; + DataContract? dataContract; if (_dataContractResolver == null) { dataContract = ResolveDataContractFromKnownTypes(qname); } else { - Type dataContractType = _dataContractResolver.ResolveName(typeName, typeNs, declaredType, KnownTypeResolver); + Type? dataContractType = _dataContractResolver.ResolveName(typeName, typeNs, declaredType, KnownTypeResolver); dataContract = dataContractType == null ? null : GetDataContract(dataContractType); } if (dataContract == null) @@ -281,7 +281,7 @@ protected DataContract ResolveDataContractFromKnownTypes(string typeName, string dataContract = rootTypeDataContract; else { - CollectionDataContract collectionContract = rootTypeDataContract as CollectionDataContract; + CollectionDataContract? collectionContract = rootTypeDataContract as CollectionDataContract; while (collectionContract != null) { DataContract itemContract = GetDataContract(GetSurrogatedType(collectionContract.ItemType)); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerReadContext.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerReadContext.cs index 927488d48d5621..6a36eb70a65cc8 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerReadContext.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerReadContext.cs @@ -12,6 +12,7 @@ namespace System.Runtime.Serialization using System.Xml.Serialization; using System.Security; using DataContractDictionary = System.Collections.Generic.Dictionary; + using System.Diagnostics.CodeAnalysis; #if USE_REFEMIT public class XmlObjectSerializerReadContext : XmlObjectSerializerContext @@ -19,12 +20,12 @@ public class XmlObjectSerializerReadContext : XmlObjectSerializerContext internal class XmlObjectSerializerReadContext : XmlObjectSerializerContext #endif { - internal Attributes attributes; - private HybridObjectCache _deserializedObjects; - private XmlSerializableReader _xmlSerializableReader; - private XmlDocument _xmlDocument; - private Attributes _attributesInXmlData; - private object _getOnlyCollectionValue; + internal Attributes? attributes; + private HybridObjectCache? _deserializedObjects; + private XmlSerializableReader? _xmlSerializableReader; + private XmlDocument? _xmlDocument; + private Attributes? _attributesInXmlData; + private object? _getOnlyCollectionValue; private bool _isGetOnlyCollection; private HybridObjectCache DeserializedObjects @@ -48,18 +49,18 @@ internal override bool IsGetOnlyCollection #if USE_REFEMIT - public object GetCollectionMember() + public object? GetCollectionMember() #else - internal object GetCollectionMember() + internal object? GetCollectionMember() #endif { return _getOnlyCollectionValue; } #if USE_REFEMIT - public void StoreCollectionMemberInfo(object collectionMember) + public void StoreCollectionMemberInfo(object? collectionMember) #else - internal void StoreCollectionMemberInfo(object collectionMember) + internal void StoreCollectionMemberInfo(object? collectionMember) #endif { _getOnlyCollectionValue = collectionMember; @@ -72,6 +73,7 @@ internal void ResetCollectionMemberInfo() _isGetOnlyCollection = false; } + [DoesNotReturn] #if USE_REFEMIT public static void ThrowNullValueReturnedForGetOnlyCollectionException(Type type) #else @@ -81,6 +83,7 @@ internal static void ThrowNullValueReturnedForGetOnlyCollectionException(Type ty throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.NullValueReturnedForGetOnlyCollection, DataContract.GetClrTypeFullName(type)))); } + [DoesNotReturn] #if USE_REFEMIT public static void ThrowArrayExceededSizeException(int arraySize, Type type) #else @@ -90,7 +93,7 @@ internal static void ThrowArrayExceededSizeException(int arraySize, Type type) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ArrayExceededSize, arraySize, DataContract.GetClrTypeFullName(type)))); } - internal static XmlObjectSerializerReadContext CreateContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver) + internal static XmlObjectSerializerReadContext CreateContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver? dataContractResolver) { return (serializer.PreserveObjectReferences || serializer.SerializationSurrogateProvider != null) ? new XmlObjectSerializerReadContextComplex(serializer, rootTypeDataContract, dataContractResolver) @@ -102,7 +105,7 @@ internal XmlObjectSerializerReadContext(XmlObjectSerializer serializer, int maxI { } - internal XmlObjectSerializerReadContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver) + internal XmlObjectSerializerReadContext(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver? dataContractResolver) : base(serializer, rootTypeDataContract, dataContractResolver) { this.attributes = new Attributes(); @@ -110,29 +113,29 @@ internal XmlObjectSerializerReadContext(DataContractSerializer serializer, DataC #if USE_REFEMIT - public virtual object InternalDeserialize(XmlReaderDelegator xmlReader, int id, RuntimeTypeHandle declaredTypeHandle, string name, string ns) + public virtual object? InternalDeserialize(XmlReaderDelegator xmlReader, int id, RuntimeTypeHandle declaredTypeHandle, string name, string ns) #else - internal virtual object InternalDeserialize(XmlReaderDelegator xmlReader, int id, RuntimeTypeHandle declaredTypeHandle, string name, string ns) + internal virtual object? InternalDeserialize(XmlReaderDelegator xmlReader, int id, RuntimeTypeHandle declaredTypeHandle, string name, string ns) #endif { DataContract dataContract = GetDataContract(id, declaredTypeHandle); return InternalDeserialize(xmlReader, name, ns, Type.GetTypeFromHandle(declaredTypeHandle), ref dataContract); } - internal virtual object InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, string name, string ns) + internal virtual object? InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, string name, string ns) { DataContract dataContract = GetDataContract(declaredType); return InternalDeserialize(xmlReader, name, ns, declaredType, ref dataContract); } - internal virtual object InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, DataContract dataContract, string name, string ns) + internal virtual object? InternalDeserialize(XmlReaderDelegator xmlReader, Type declaredType, DataContract? dataContract, string? name, string? ns) { if (dataContract == null) - GetDataContract(declaredType); + dataContract = GetDataContract(declaredType); return InternalDeserialize(xmlReader, name, ns, declaredType, ref dataContract); } - protected bool TryHandleNullOrRef(XmlReaderDelegator reader, Type declaredType, string name, string ns, ref object retObj) + protected bool TryHandleNullOrRef(XmlReaderDelegator reader, Type declaredType, string? name, string? ns, ref object? retObj) { ReadAttributes(reader); @@ -157,9 +160,9 @@ protected bool TryHandleNullOrRef(XmlReaderDelegator reader, Type declaredType, return false; } - protected object InternalDeserialize(XmlReaderDelegator reader, string name, string ns, Type declaredType, ref DataContract dataContract) + protected object? InternalDeserialize(XmlReaderDelegator reader, string? name, string? ns, Type declaredType, ref DataContract dataContract) { - object retObj = null; + object? retObj = null; if (TryHandleNullOrRef(reader, dataContract.UnderlyingType, name, ns, ref retObj)) return retObj; @@ -170,10 +173,12 @@ protected object InternalDeserialize(XmlReaderDelegator reader, string name, str knownTypesAddedInCurrentScope = true; } + Debug.Assert(attributes != null); + if (attributes.XsiTypeName != null) { - dataContract = ResolveDataContractFromKnownTypes(attributes.XsiTypeName, attributes.XsiTypeNamespace, dataContract, declaredType); - if (dataContract == null) + DataContract? tempDataContract = ResolveDataContractFromKnownTypes(attributes.XsiTypeName, attributes.XsiTypeNamespace, dataContract, declaredType); + if (tempDataContract == null) { if (DataContractResolver == null) { @@ -181,12 +186,13 @@ protected object InternalDeserialize(XmlReaderDelegator reader, string name, str } throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(reader, SR.Format(SR.DcTypeNotResolvedOnDeserialize, attributes.XsiTypeNamespace, attributes.XsiTypeName, reader.NamespaceURI, reader.LocalName)))); } + dataContract = tempDataContract; knownTypesAddedInCurrentScope = ReplaceScopedKnownTypesTop(dataContract.KnownDataContracts, knownTypesAddedInCurrentScope); } if (dataContract.IsISerializable && attributes.FactoryTypeName != null) { - DataContract factoryDataContract = ResolveDataContractFromKnownTypes(attributes.FactoryTypeName, attributes.FactoryTypeNamespace, dataContract, declaredType); + DataContract? factoryDataContract = ResolveDataContractFromKnownTypes(attributes.FactoryTypeName, attributes.FactoryTypeNamespace, dataContract, declaredType); if (factoryDataContract != null) { if (factoryDataContract.IsISerializable) @@ -203,7 +209,7 @@ protected object InternalDeserialize(XmlReaderDelegator reader, string name, str if (knownTypesAddedInCurrentScope) { - object obj = ReadDataContractValue(dataContract, reader); + object? obj = ReadDataContractValue(dataContract, reader); scopedKnownTypes.Pop(); return obj; } @@ -213,7 +219,7 @@ protected object InternalDeserialize(XmlReaderDelegator reader, string name, str } } - private bool ReplaceScopedKnownTypesTop(DataContractDictionary knownDataContracts, bool knownTypesAddedInCurrentScope) + private bool ReplaceScopedKnownTypesTop(DataContractDictionary? knownDataContracts, bool knownTypesAddedInCurrentScope) { if (knownTypesAddedInCurrentScope) { @@ -238,9 +244,9 @@ internal static bool MoveToNextElement(XmlReaderDelegator xmlReader) } #if USE_REFEMIT - public int GetMemberIndex(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, int memberIndex, ExtensionDataObject extensionData) + public int GetMemberIndex(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, int memberIndex, ExtensionDataObject? extensionData) #else - internal int GetMemberIndex(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, int memberIndex, ExtensionDataObject extensionData) + internal int GetMemberIndex(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, int memberIndex, ExtensionDataObject? extensionData) #endif { for (int i = memberIndex + 1; i < memberNames.Length; i++) @@ -253,9 +259,9 @@ internal int GetMemberIndex(XmlReaderDelegator xmlReader, XmlDictionaryString[] } #if USE_REFEMIT - public int GetMemberIndexWithRequiredMembers(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, int memberIndex, int requiredIndex, ExtensionDataObject extensionData) + public int GetMemberIndexWithRequiredMembers(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, int memberIndex, int requiredIndex, ExtensionDataObject? extensionData) #else - internal int GetMemberIndexWithRequiredMembers(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, int memberIndex, int requiredIndex, ExtensionDataObject extensionData) + internal int GetMemberIndexWithRequiredMembers(XmlReaderDelegator xmlReader, XmlDictionaryString[] memberNames, XmlDictionaryString[] memberNamespaces, int memberIndex, int requiredIndex, ExtensionDataObject? extensionData) #endif { for (int i = memberIndex + 1; i < memberNames.Length; i++) @@ -271,6 +277,7 @@ internal int GetMemberIndexWithRequiredMembers(XmlReaderDelegator xmlReader, Xml return memberNames.Length; } + [DoesNotReturn] #if USE_REFEMIT public static void ThrowRequiredMemberMissingException(XmlReaderDelegator xmlReader, int memberIndex, int requiredIndex, XmlDictionaryString[] memberNames) #else @@ -289,7 +296,7 @@ internal static void ThrowRequiredMemberMissingException(XmlReaderDelegator xmlR throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(XmlObjectSerializer.TryAddLineInfo(xmlReader, SR.Format(SR.UnexpectedElementExpectingElements, xmlReader.NodeType, xmlReader.LocalName, xmlReader.NamespaceURI, stringBuilder.ToString())))); } - protected void HandleMemberNotFound(XmlReaderDelegator xmlReader, ExtensionDataObject extensionData, int memberIndex) + protected void HandleMemberNotFound(XmlReaderDelegator xmlReader, ExtensionDataObject? extensionData, int memberIndex) { xmlReader.MoveToContent(); if (xmlReader.NodeType != XmlNodeType.Element) @@ -324,6 +331,8 @@ public string ReadIfNullOrRef(XmlReaderDelegator xmlReader, Type memberType, boo internal string ReadIfNullOrRef(XmlReaderDelegator xmlReader, Type memberType, bool isMemberTypeSerializable) #endif { + Debug.Assert(attributes != null); + if (attributes.Ref != Globals.NewObjectId) { CheckIfTypeSerializable(memberType, isMemberTypeSerializable); @@ -339,6 +348,7 @@ internal string ReadIfNullOrRef(XmlReaderDelegator xmlReader, Type memberType, b return Globals.NewObjectId; } + [MemberNotNull(nameof(attributes))] #if USE_REFEMIT public virtual void ReadAttributes(XmlReaderDelegator xmlReader) #else @@ -366,6 +376,8 @@ public string GetObjectId() internal string GetObjectId() #endif { + Debug.Assert(attributes != null); + return attributes.Id; } @@ -379,25 +391,27 @@ internal virtual int GetArraySize() } #if USE_REFEMIT - public void AddNewObject(object obj) + public void AddNewObject(object? obj) #else - internal void AddNewObject(object obj) + internal void AddNewObject(object? obj) #endif { + Debug.Assert(attributes != null); + AddNewObjectWithId(attributes.Id, obj); } #if USE_REFEMIT - public void AddNewObjectWithId(string id, object obj) + public void AddNewObjectWithId(string id, object? obj) #else - internal void AddNewObjectWithId(string id, object obj) + internal void AddNewObjectWithId(string id, object? obj) #endif { if (id != Globals.NewObjectId) DeserializedObjects.Add(id, obj); } - public void ReplaceDeserializedObject(string id, object oldObj, object newObj) + public void ReplaceDeserializedObject(string id, object? oldObj, object? newObj) { if (object.ReferenceEquals(oldObj, newObj)) return; @@ -411,19 +425,23 @@ public void ReplaceDeserializedObject(string id, object oldObj, object newObj) // These XmlObjectSerializer implementations do not currently support fix-ups. Hence we // throw in such cases to allow us add fix-up support in the future if we need to. if (DeserializedObjects.IsObjectReferenced(id)) + { + // https://github.com/dotnet/runtime/issues/41465 - oldObj or newObj may be null below - suppress compiler error by asserting non-null + Debug.Assert(oldObj != null && newObj != null); throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.FactoryObjectContainsSelfReference, DataContract.GetClrTypeFullName(oldObj.GetType()), DataContract.GetClrTypeFullName(newObj.GetType()), id))); + } DeserializedObjects.Remove(id); DeserializedObjects.Add(id, newObj); } } #if USE_REFEMIT - public object GetExistingObject(string id, Type type, string name, string ns) + public object GetExistingObject(string id, Type? type, string? name, string? ns) #else - internal object GetExistingObject(string id, Type type, string name, string ns) + internal object GetExistingObject(string id, Type? type, string? name, string? ns) #endif { - object retObj = DeserializedObjects.GetObject(id); + object? retObj = DeserializedObjects.GetObject(id); if (retObj == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.DeserializedObjectWithIdNotFound, id))); return retObj; @@ -431,7 +449,7 @@ internal object GetExistingObject(string id, Type type, string name, string ns) private object GetExistingObjectOrExtensionData(string id) { - object retObj = DeserializedObjects.GetObject(id); + object? retObj = DeserializedObjects.GetObject(id); if (retObj == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError( @@ -443,7 +461,7 @@ private object GetExistingObjectOrExtensionData(string id) public object GetRealObject(IObjectReference obj, string id) { - object realObj = SurrogateDataContract.GetRealObject(obj, this.GetStreamingContext()); + object? realObj = SurrogateDataContract.GetRealObject(obj, this.GetStreamingContext()); // If GetRealObject returns null, it indicates that the object could not resolve itself because // it is missing information. This may occur in a case where multiple IObjectReference instances // depend on each other. BinaryFormatter supports this by fixing up the references later. These @@ -466,7 +484,7 @@ internal static void Read(XmlReaderDelegator xmlReader) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.UnexpectedEndOfFile)); } - internal static void ParseQualifiedName(string qname, XmlReaderDelegator xmlReader, out string name, out string ns, out string prefix) + internal static void ParseQualifiedName(string qname, XmlReaderDelegator xmlReader, out string name, out string? ns, out string prefix) { int colon = qname.IndexOf(':'); prefix = ""; @@ -532,21 +550,21 @@ internal void CheckEndOfArray(XmlReaderDelegator xmlReader, int arraySize, XmlDi throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.EndElement, xmlReader)); } - internal object ReadIXmlSerializable(XmlReaderDelegator xmlReader, XmlDataContract xmlDataContract, bool isMemberType) + internal object? ReadIXmlSerializable(XmlReaderDelegator xmlReader, XmlDataContract xmlDataContract, bool isMemberType) { if (_xmlSerializableReader == null) _xmlSerializableReader = new XmlSerializableReader(); return ReadIXmlSerializable(_xmlSerializableReader, xmlReader, xmlDataContract, isMemberType); } - internal static object ReadRootIXmlSerializable(XmlReaderDelegator xmlReader, XmlDataContract xmlDataContract, bool isMemberType) + internal static object? ReadRootIXmlSerializable(XmlReaderDelegator xmlReader, XmlDataContract xmlDataContract, bool isMemberType) { return ReadIXmlSerializable(new XmlSerializableReader(), xmlReader, xmlDataContract, isMemberType); } - internal static object ReadIXmlSerializable(XmlSerializableReader xmlSerializableReader, XmlReaderDelegator xmlReader, XmlDataContract xmlDataContract, bool isMemberType) + internal static object? ReadIXmlSerializable(XmlSerializableReader xmlSerializableReader, XmlReaderDelegator xmlReader, XmlDataContract xmlDataContract, bool isMemberType) { - object obj = null; + object? obj = null; xmlSerializableReader.BeginRead(xmlReader); if (isMemberType && !xmlDataContract.HasRoot) { @@ -558,7 +576,7 @@ internal static object ReadIXmlSerializable(XmlSerializableReader xmlSerializabl if (!xmlReader.IsStartElement()) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateUnexpectedStateException(XmlNodeType.Element, xmlReader)); XmlDocument xmlDoc = new XmlDocument(); - obj = (XmlElement)xmlDoc.ReadNode(xmlSerializableReader); + obj = (XmlElement?)xmlDoc.ReadNode(xmlSerializableReader); } else if (xmlDataContract.UnderlyingType == Globals.TypeOfXmlNodeArray) { @@ -595,7 +613,7 @@ public SerializationInfo ReadSerializationInfo(XmlReaderDelegator xmlReader, Typ IncrementItemCount(1); ReadAttributes(xmlReader); - object value; + object? value; if (attributes.Ref != Globals.NewObjectId) { xmlReader.Skip(); @@ -617,17 +635,17 @@ public SerializationInfo ReadSerializationInfo(XmlReaderDelegator xmlReader, Typ return serInfo; } - protected virtual DataContract ResolveDataContractFromTypeName() + protected virtual DataContract? ResolveDataContractFromTypeName() { + Debug.Assert(attributes != null); + return (attributes.XsiTypeName == null) ? null : ResolveDataContractFromKnownTypes(attributes.XsiTypeName, attributes.XsiTypeNamespace, null /*memberTypeContract*/, null); } private ExtensionDataMember ReadExtensionDataMember(XmlReaderDelegator xmlReader, int memberIndex) { - var member = new ExtensionDataMember + var member = new ExtensionDataMember(xmlReader.LocalName, xmlReader.NamespaceURI) { - Name = xmlReader.LocalName, - Namespace = xmlReader.NamespaceURI, MemberIndex = memberIndex }; @@ -635,11 +653,11 @@ private ExtensionDataMember ReadExtensionDataMember(XmlReaderDelegator xmlReader return member; } - public IDataNode ReadExtensionDataValue(XmlReaderDelegator xmlReader) + public IDataNode? ReadExtensionDataValue(XmlReaderDelegator xmlReader) { ReadAttributes(xmlReader); IncrementItemCount(1); - IDataNode dataNode = null; + IDataNode? dataNode = null; if (attributes.Ref != Globals.NewObjectId) { xmlReader.Skip(); @@ -654,8 +672,8 @@ public IDataNode ReadExtensionDataValue(XmlReaderDelegator xmlReader) } else { - string dataContractName = null; - string dataContractNamespace = null; + string? dataContractName = null; + string? dataContractNamespace = null; if (attributes.XsiTypeName != null) { dataContractName = attributes.XsiTypeName; @@ -679,7 +697,7 @@ public IDataNode ReadExtensionDataValue(XmlReaderDelegator xmlReader) } else { - DataContract dataContract = ResolveDataContractFromTypeName(); + DataContract? dataContract = ResolveDataContractFromTypeName(); if (dataContract == null) dataNode = ReadExtensionDataValue(xmlReader, dataContractName, dataContractNamespace); @@ -732,14 +750,16 @@ protected virtual void StartReadExtensionDataValue(XmlReaderDelegator xmlReader) { } - private IDataNode ReadExtensionDataValue(XmlReaderDelegator xmlReader, string dataContractName, string dataContractNamespace) + private IDataNode ReadExtensionDataValue(XmlReaderDelegator xmlReader, string? dataContractName, string? dataContractNamespace) { + Debug.Assert(attributes != null); + StartReadExtensionDataValue(xmlReader); if (attributes.UnrecognizedAttributesFound) return ReadUnknownXmlData(xmlReader, dataContractName, dataContractNamespace); - IDictionary namespacesInScope = xmlReader.GetNamespacesInScope(XmlNamespaceScope.ExcludeXml); + IDictionary? namespacesInScope = xmlReader.GetNamespacesInScope(XmlNamespaceScope.ExcludeXml); Read(xmlReader); xmlReader.MoveToContent(); @@ -766,7 +786,7 @@ private IDataNode ReadExtensionDataValue(XmlReaderDelegator xmlReader, string da } } - protected virtual IDataNode ReadPrimitiveExtensionDataValue(XmlReaderDelegator xmlReader, string dataContractName, string dataContractNamespace) + protected virtual IDataNode ReadPrimitiveExtensionDataValue(XmlReaderDelegator xmlReader, string? dataContractName, string? dataContractNamespace) { Type valueType = xmlReader.ValueType; if (valueType == Globals.TypeOfString) @@ -784,8 +804,10 @@ protected virtual IDataNode ReadPrimitiveExtensionDataValue(XmlReaderDelegator x return objNode; } - protected void InitializeExtensionDataNode(IDataNode dataNode, string dataContractName, string dataContractNamespace) + protected void InitializeExtensionDataNode(IDataNode dataNode, string? dataContractName, string? dataContractNamespace) { + Debug.Assert(attributes != null); + dataNode.DataContractName = dataContractName; dataNode.DataContractNamespace = dataContractNamespace; dataNode.ClrAssemblyName = attributes.ClrAssembly; @@ -794,14 +816,14 @@ protected void InitializeExtensionDataNode(IDataNode dataNode, string dataContra dataNode.Id = attributes.Id; } - private IDataNode ReadUnknownPrimitiveData(XmlReaderDelegator xmlReader, Type type, string dataContractName, string dataContractNamespace) + private IDataNode ReadUnknownPrimitiveData(XmlReaderDelegator xmlReader, Type type, string? dataContractName, string? dataContractNamespace) { IDataNode dataNode = xmlReader.ReadExtensionData(type); InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace); return dataNode; } - private ClassDataNode ReadUnknownClassData(XmlReaderDelegator xmlReader, string dataContractName, string dataContractNamespace) + private ClassDataNode ReadUnknownClassData(XmlReaderDelegator xmlReader, string? dataContractName, string? dataContractNamespace) { var dataNode = new ClassDataNode(); InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace); @@ -821,8 +843,10 @@ private ClassDataNode ReadUnknownClassData(XmlReaderDelegator xmlReader, string return dataNode; } - private CollectionDataNode ReadUnknownCollectionData(XmlReaderDelegator xmlReader, string dataContractName, string dataContractNamespace) + private CollectionDataNode ReadUnknownCollectionData(XmlReaderDelegator xmlReader, string? dataContractName, string? dataContractNamespace) { + Debug.Assert(attributes != null); + var dataNode = new CollectionDataNode(); InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace); @@ -838,10 +862,10 @@ private CollectionDataNode ReadUnknownCollectionData(XmlReaderDelegator xmlReade dataNode.ItemName = xmlReader.LocalName; dataNode.ItemNamespace = xmlReader.NamespaceURI; } - if (xmlReader.IsStartElement(dataNode.ItemName, dataNode.ItemNamespace)) + if (xmlReader.IsStartElement(dataNode.ItemName, dataNode.ItemNamespace!)) { if (dataNode.Items == null) - dataNode.Items = new List(); + dataNode.Items = new List(); dataNode.Items.Add(ReadExtensionDataValue(xmlReader)); } else @@ -875,8 +899,10 @@ private CollectionDataNode ReadUnknownCollectionData(XmlReaderDelegator xmlReade return dataNode; } - private ISerializableDataNode ReadUnknownISerializableData(XmlReaderDelegator xmlReader, string dataContractName, string dataContractNamespace) + private ISerializableDataNode ReadUnknownISerializableData(XmlReaderDelegator xmlReader, string? dataContractName, string? dataContractNamespace) { + Debug.Assert(attributes != null); + var dataNode = new ISerializableDataNode(); InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace); @@ -895,8 +921,7 @@ private ISerializableDataNode ReadUnknownISerializableData(XmlReaderDelegator xm continue; } - var member = new ISerializableDataMember(); - member.Name = xmlReader.LocalName; + var member = new ISerializableDataMember(xmlReader.LocalName); member.Value = ReadExtensionDataValue(xmlReader); if (dataNode.Members == null) dataNode.Members = new List(); @@ -906,7 +931,7 @@ private ISerializableDataNode ReadUnknownISerializableData(XmlReaderDelegator xm return dataNode; } - private IDataNode ReadUnknownXmlData(XmlReaderDelegator xmlReader, string dataContractName, string dataContractNamespace) + private IDataNode ReadUnknownXmlData(XmlReaderDelegator xmlReader, string? dataContractName, string? dataContractNamespace) { XmlDataNode dataNode = new XmlDataNode(); InitializeExtensionDataNode(dataNode, dataContractName, dataContractNamespace); @@ -915,8 +940,8 @@ private IDataNode ReadUnknownXmlData(XmlReaderDelegator xmlReader, string dataCo if (xmlReader.NodeType == XmlNodeType.EndElement) return dataNode; - IList xmlAttributes = null; - IList xmlChildNodes = null; + IList? xmlAttributes = null; + IList? xmlChildNodes = null; XmlNodeType nodeType = xmlReader.MoveToContent(); if (nodeType != XmlNodeType.Text) @@ -928,7 +953,7 @@ private IDataNode ReadUnknownXmlData(XmlReaderDelegator xmlReader, string dataCo { if (xmlAttributes == null) xmlAttributes = new List(); - xmlAttributes.Add((XmlAttribute)Document.ReadNode(xmlReader.UnderlyingReader)); + xmlAttributes.Add((XmlAttribute)Document.ReadNode(xmlReader.UnderlyingReader)!); } } Read(xmlReader); @@ -941,7 +966,7 @@ private IDataNode ReadUnknownXmlData(XmlReaderDelegator xmlReader, string dataCo if (xmlChildNodes == null) xmlChildNodes = new List(); - xmlChildNodes.Add(Document.ReadNode(xmlReader.UnderlyingReader)); + xmlChildNodes.Add(Document.ReadNode(xmlReader.UnderlyingReader)!); } xmlReader.ReadEndElement(); @@ -954,15 +979,15 @@ private IDataNode ReadUnknownXmlData(XmlReaderDelegator xmlReader, string dataCo // all items have the same name and namespace. To recognize as an ISerializable type, it requires that all // items be unqualified. If the XML only contains elements (no attributes or other nodes) is recognized as a // class/class hierarchy. Otherwise it is deserialized as XML. - private IDataNode ReadAndResolveUnknownXmlData(XmlReaderDelegator xmlReader, IDictionary namespaces, - string dataContractName, string dataContractNamespace) + private IDataNode ReadAndResolveUnknownXmlData(XmlReaderDelegator xmlReader, IDictionary? namespaces, + string? dataContractName, string? dataContractNamespace) { bool couldBeISerializableData = true; bool couldBeCollectionData = true; bool couldBeClassData = true; - string elementNs = null, elementName = null; + string? elementNs = null, elementName = null; var xmlChildNodes = new List(); - IList xmlAttributes = null; + IList? xmlAttributes = null; if (namespaces != null) { xmlAttributes = new List(); @@ -1001,15 +1026,15 @@ private IDataNode ReadAndResolveUnknownXmlData(XmlReaderDelegator xmlReader, IDi if (_attributesInXmlData == null) _attributesInXmlData = new Attributes(); _attributesInXmlData.Read(xmlReader); - XmlNode childNode = Document.ReadNode(xmlReader.UnderlyingReader); + XmlNode childNode = Document.ReadNode(xmlReader.UnderlyingReader)!; xmlChildNodes.Add(childNode); if (namespaces == null) { if (_attributesInXmlData.XsiTypeName != null) - childNode.Attributes.Append(AddNamespaceDeclaration(_attributesInXmlData.XsiTypePrefix, _attributesInXmlData.XsiTypeNamespace)); + childNode.Attributes!.Append(AddNamespaceDeclaration(_attributesInXmlData.XsiTypePrefix, _attributesInXmlData.XsiTypeNamespace)); if (_attributesInXmlData.FactoryTypeName != null) - childNode.Attributes.Append(AddNamespaceDeclaration(_attributesInXmlData.FactoryTypePrefix, _attributesInXmlData.FactoryTypeNamespace)); + childNode.Attributes!.Append(AddNamespaceDeclaration(_attributesInXmlData.FactoryTypePrefix, _attributesInXmlData.FactoryTypeNamespace)); } } xmlReader.ReadEndElement(); @@ -1046,7 +1071,7 @@ private bool IsContentNode(XmlNodeType nodeType) } } - internal XmlReaderDelegator CreateReaderOverChildNodes(IList xmlAttributes, IList xmlChildNodes) + internal XmlReaderDelegator CreateReaderOverChildNodes(IList? xmlAttributes, IList xmlChildNodes) { XmlNode wrapperElement = CreateWrapperXmlElement(Document, xmlAttributes, xmlChildNodes, null, null, null); XmlReaderDelegator nodeReader = CreateReaderDelegatorForReader(new XmlNodeReader(wrapperElement)); @@ -1055,11 +1080,11 @@ internal XmlReaderDelegator CreateReaderOverChildNodes(IList xmlAt return nodeReader; } - internal static XmlNode CreateWrapperXmlElement(XmlDocument document, IList xmlAttributes, IList xmlChildNodes, string prefix, string localName, string ns) + internal static XmlNode CreateWrapperXmlElement(XmlDocument document, IList? xmlAttributes, IList xmlChildNodes, string? prefix, string? localName, string? ns) { localName = localName ?? "wrapper"; ns = ns ?? string.Empty; - XmlNode wrapperElement = document.CreateElement(prefix, localName, ns); + XmlElement wrapperElement = document.CreateElement(prefix, localName, ns); if (xmlAttributes != null) { for (int i = 0; i < xmlAttributes.Count; i++) @@ -1077,7 +1102,7 @@ internal static XmlNode CreateWrapperXmlElement(XmlDocument document, IList() internal static T GetDefaultValue() #endif { - return default(T); + return default(T)!; } #if USE_REFEMIT @@ -516,7 +519,7 @@ internal static T GetNullableValue(Nullable value) where T : struct #endif { // value.Value will throw if hasValue is false - return value.Value; + return value!.Value; } #if USE_REFEMIT @@ -552,17 +555,17 @@ internal static void WriteRootIXmlSerializable(XmlWriterDelegator xmlWriter, obj private static void WriteIXmlSerializable(XmlWriterDelegator xmlWriter, object obj, XmlSerializableWriter xmlSerializableWriter) { xmlSerializableWriter.BeginWrite(xmlWriter.Writer, obj); - IXmlSerializable xmlSerializable = obj as IXmlSerializable; + IXmlSerializable? xmlSerializable = obj as IXmlSerializable; if (xmlSerializable != null) xmlSerializable.WriteXml(xmlSerializableWriter); else { - XmlElement xmlElement = obj as XmlElement; + XmlElement? xmlElement = obj as XmlElement; if (xmlElement != null) xmlElement.WriteTo(xmlSerializableWriter); else { - XmlNode[] xmlNodes = obj as XmlNode[]; + XmlNode[]? xmlNodes = obj as XmlNode[]; if (xmlNodes != null) foreach (XmlNode xmlNode in xmlNodes) xmlNode.WriteTo(xmlSerializableWriter); @@ -600,7 +603,7 @@ internal void WriteSerializationInfo(XmlWriterDelegator xmlWriter, Type objType, { if (DataContractResolver != null) { - XmlDictionaryString typeName, typeNs; + XmlDictionaryString? typeName, typeNs; if (ResolveType(serInfo.ObjectType, objType, out typeName, out typeNs)) { xmlWriter.WriteAttributeQualifiedName(Globals.SerPrefix, DictionaryGlobals.ISerializableFactoryTypeLocalName, DictionaryGlobals.SerializationNamespace, typeName, typeNs); @@ -620,7 +623,7 @@ internal void WriteSerializationInfo(XmlWriterDelegator xmlWriter, Type objType, { XmlDictionaryString name = DataContract.GetClrTypeString(DataContract.EncodeLocalName(serEntry.Name)); xmlWriter.WriteStartElement(name, DictionaryGlobals.EmptyString); - object obj = serEntry.Value; + object? obj = serEntry.Value; if (obj == null) { WriteNull(xmlWriter); @@ -646,15 +649,17 @@ protected virtual void WriteNull(XmlWriterDelegator xmlWriter) private void WriteResolvedTypeInfo(XmlWriterDelegator writer, Type objectType, Type declaredType) { - XmlDictionaryString typeName, typeNamespace; + XmlDictionaryString? typeName, typeNamespace; if (ResolveType(objectType, declaredType, out typeName, out typeNamespace)) { WriteTypeInfo(writer, typeName, typeNamespace); } } - private bool ResolveType(Type objectType, Type declaredType, out XmlDictionaryString typeName, out XmlDictionaryString typeNamespace) + private bool ResolveType(Type objectType, Type declaredType, [NotNullWhen(true)] out XmlDictionaryString? typeName, [NotNullWhen(true)] out XmlDictionaryString? typeNamespace) { + Debug.Assert(DataContractResolver != null); + if (!DataContractResolver.TryResolveType(objectType, declaredType, KnownTypeResolver, out typeName, out typeNamespace)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.Format(SR.ResolveTypeReturnedFalse, DataContract.GetClrTypeFullName(DataContractResolver.GetType()), DataContract.GetClrTypeFullName(objectType)))); @@ -695,7 +700,7 @@ protected virtual bool WriteTypeInfo(XmlWriterDelegator writer, DataContract con return false; } - protected virtual void WriteTypeInfo(XmlWriterDelegator writer, string dataContractName, string dataContractNamespace) + protected virtual void WriteTypeInfo(XmlWriterDelegator writer, string dataContractName, string? dataContractNamespace) { writer.WriteAttributeQualifiedName(Globals.XsiPrefix, DictionaryGlobals.XsiTypeLocalName, DictionaryGlobals.SchemaInstanceNamespace, dataContractName, dataContractNamespace); } @@ -705,17 +710,17 @@ protected virtual void WriteTypeInfo(XmlWriterDelegator writer, XmlDictionaryStr writer.WriteAttributeQualifiedName(Globals.XsiPrefix, DictionaryGlobals.XsiTypeLocalName, DictionaryGlobals.SchemaInstanceNamespace, dataContractName, dataContractNamespace); } - public void WriteExtensionData(XmlWriterDelegator xmlWriter, ExtensionDataObject extensionData, int memberIndex) + public void WriteExtensionData(XmlWriterDelegator xmlWriter, ExtensionDataObject? extensionData, int memberIndex) { if (IgnoreExtensionDataObject || extensionData == null) return; - IList members = extensionData.Members; + IList? members = extensionData.Members; if (members != null) { - for (int i = 0; i < extensionData.Members.Count; i++) + for (int i = 0; i < members.Count; i++) { - ExtensionDataMember member = extensionData.Members[i]; + ExtensionDataMember member = members[i]; if (member.MemberIndex == memberIndex) { WriteExtensionDataMember(xmlWriter, member); @@ -727,7 +732,7 @@ public void WriteExtensionData(XmlWriterDelegator xmlWriter, ExtensionDataObject private void WriteExtensionDataMember(XmlWriterDelegator xmlWriter, ExtensionDataMember member) { xmlWriter.WriteStartElement(member.Name, member.Namespace); - IDataNode dataNode = member.Value; + IDataNode? dataNode = member.Value; WriteExtensionDataValue(xmlWriter, dataNode); xmlWriter.WriteEndElement(); } @@ -740,7 +745,7 @@ internal virtual void WriteExtensionDataTypeInfo(XmlWriterDelegator xmlWriter, I WriteClrTypeInfo(xmlWriter, dataNode.DataType, dataNode.ClrTypeName, dataNode.ClrAssemblyName); } - internal void WriteExtensionDataValue(XmlWriterDelegator xmlWriter, IDataNode dataNode) + internal void WriteExtensionDataValue(XmlWriterDelegator xmlWriter, IDataNode? dataNode) { IncrementItemCount(1); if (dataNode == null) @@ -770,7 +775,7 @@ internal void WriteExtensionDataValue(XmlWriterDelegator xmlWriter, IDataNode da { // NOTE: serialize value in DataNode since it may contain non-primitive // deserialized object (ex. empty class) - object o = dataNode.Value; + object? o = dataNode.Value; if (o != null) InternalSerialize(xmlWriter, o, false /*isDeclaredType*/, false /*writeXsiType*/, -1, o.GetType().TypeHandle); } @@ -783,7 +788,7 @@ internal void WriteExtensionDataValue(XmlWriterDelegator xmlWriter, IDataNode da internal bool TryWriteDeserializedExtensionData(XmlWriterDelegator xmlWriter, IDataNode dataNode) { - object o = dataNode.Value; + object? o = dataNode.Value; if (o == null) return false; @@ -798,7 +803,7 @@ private void WriteExtensionClassData(XmlWriterDelegator xmlWriter, ClassDataNode { WriteExtensionDataTypeInfo(xmlWriter, dataNode); - IList members = dataNode.Members; + IList? members = dataNode.Members; if (members != null) { for (int i = 0; i < members.Count; i++) @@ -817,12 +822,12 @@ private void WriteExtensionCollectionData(XmlWriterDelegator xmlWriter, Collecti WriteArraySize(xmlWriter, dataNode.Size); - IList items = dataNode.Items; + IList? items = dataNode.Items; if (items != null) { for (int i = 0; i < items.Count; i++) { - xmlWriter.WriteStartElement(dataNode.ItemName, dataNode.ItemNamespace); + xmlWriter.WriteStartElement(dataNode.ItemName!, dataNode.ItemNamespace); WriteExtensionDataValue(xmlWriter, items[i]); xmlWriter.WriteEndElement(); } @@ -839,7 +844,7 @@ private void WriteExtensionISerializableData(XmlWriterDelegator xmlWriter, ISeri if (dataNode.FactoryTypeName != null) xmlWriter.WriteAttributeQualifiedName(Globals.SerPrefix, DictionaryGlobals.ISerializableFactoryTypeLocalName, DictionaryGlobals.SerializationNamespace, dataNode.FactoryTypeName, dataNode.FactoryTypeNamespace); - IList members = dataNode.Members; + IList? members = dataNode.Members; if (members != null) { for (int i = 0; i < members.Count; i++) @@ -857,7 +862,7 @@ private void WriteExtensionXmlData(XmlWriterDelegator xmlWriter, XmlDataNode dat { if (!TryWriteDeserializedExtensionData(xmlWriter, dataNode)) { - IList xmlAttributes = dataNode.XmlAttributes; + IList? xmlAttributes = dataNode.XmlAttributes; if (xmlAttributes != null) { foreach (XmlAttribute attribute in xmlAttributes) @@ -865,7 +870,7 @@ private void WriteExtensionXmlData(XmlWriterDelegator xmlWriter, XmlDataNode dat } WriteExtensionDataTypeInfo(xmlWriter, dataNode); - IList xmlChildNodes = dataNode.XmlChildNodes; + IList? xmlChildNodes = dataNode.XmlChildNodes; if (xmlChildNodes != null) { foreach (XmlNode node in xmlChildNodes) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerWriteContextComplex.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerWriteContextComplex.cs index ce64b624b3f3dd..cac1276f47f83e 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerWriteContextComplex.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlObjectSerializerWriteContextComplex.cs @@ -21,10 +21,10 @@ public class XmlObjectSerializerWriteContextComplex : XmlObjectSerializerWriteCo internal class XmlObjectSerializerWriteContextComplex : XmlObjectSerializerWriteContext #endif { - private readonly ISerializationSurrogateProvider _serializationSurrogateProvider; + private readonly ISerializationSurrogateProvider? _serializationSurrogateProvider; private readonly SerializationMode _mode; - internal XmlObjectSerializerWriteContextComplex(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver dataContractResolver) + internal XmlObjectSerializerWriteContextComplex(DataContractSerializer serializer, DataContract rootTypeDataContract, DataContractResolver? dataContractResolver) : base(serializer, rootTypeDataContract, dataContractResolver) { _mode = SerializationMode.SharedContract; @@ -47,7 +47,7 @@ internal override bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, DataContra return false; } - internal override bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, Type dataContractType, string clrTypeName, string clrAssemblyName) + internal override bool WriteClrTypeInfo(XmlWriterDelegator xmlWriter, Type dataContractType, string? clrTypeName, string? clrAssemblyName) { return false; } @@ -64,7 +64,7 @@ internal override void WriteString(XmlWriterDelegator xmlWriter, string value) xmlWriter.WriteString(value); } - internal override void WriteString(XmlWriterDelegator xmlWriter, string value, XmlDictionaryString name, XmlDictionaryString ns) + internal override void WriteString(XmlWriterDelegator xmlWriter, string? value, XmlDictionaryString name, XmlDictionaryString? ns) { if (value == null) WriteNull(xmlWriter, typeof(string), true/*isMemberTypeSerializable*/, name, ns); @@ -121,7 +121,7 @@ internal override void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName xmlWriter.WriteQName(value); } - internal override void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName value, XmlDictionaryString name, XmlDictionaryString ns) + internal override void WriteQName(XmlWriterDelegator xmlWriter, XmlQualifiedName? value, XmlDictionaryString name, XmlDictionaryString? ns) { if (value == null) WriteNull(xmlWriter, typeof(XmlQualifiedName), true/*isMemberTypeSerializable*/, name, ns); @@ -179,7 +179,7 @@ internal override void CheckIfTypeSerializable(Type memberType, bool isMemberTyp if (_serializationSurrogateProvider != null) { while (memberType.IsArray) - memberType = memberType.GetElementType(); + memberType = memberType.GetElementType()!; memberType = DataContractSurrogateCaller.GetDataContractType(_serializationSurrogateProvider, memberType); if (!DataContract.IsTypeSerializable(memberType)) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidDataContractException(SR.Format(SR.TypeNotSerializable, memberType))); @@ -221,7 +221,7 @@ private void InternalSerializeWithSurrogate(XmlWriterDelegator xmlWriter, object declaredTypeHandle = declaredType.TypeHandle; - obj = DataContractSerializer.SurrogateToDataContractType(_serializationSurrogateProvider, obj, declaredType, ref objType); + obj = DataContractSerializer.SurrogateToDataContractType(_serializationSurrogateProvider!, obj, declaredType, ref objType); objTypeHandle = objType.TypeHandle; if (oldObj != obj) objOldId = SerializedObjects.ReassignId(0, oldObj, obj); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlReaderDelegator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlReaderDelegator.cs index 5faa2eea24a307..ca5b54dd6a2e34 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlReaderDelegator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlReaderDelegator.cs @@ -5,7 +5,7 @@ using System.Globalization; using System.Collections.Generic; using System.Xml.Serialization; - +using System.Diagnostics.CodeAnalysis; namespace System.Runtime.Serialization { @@ -16,7 +16,7 @@ internal class XmlReaderDelegator #endif { protected XmlReader reader; - protected XmlDictionaryReader dictionaryReader; + protected XmlDictionaryReader? dictionaryReader; protected bool isEndOfEmptyElement; public XmlReaderDelegator(XmlReader reader) @@ -31,7 +31,7 @@ internal XmlReader UnderlyingReader get { return reader; } } - internal ExtensionDataReader UnderlyingExtensionDataReader + internal ExtensionDataReader? UnderlyingExtensionDataReader { get { return reader as ExtensionDataReader; } } @@ -41,12 +41,12 @@ internal int AttributeCount get { return isEndOfEmptyElement ? 0 : reader.AttributeCount; } } - internal string GetAttribute(string name) + internal string? GetAttribute(string name) { return isEndOfEmptyElement ? null : reader.GetAttribute(name); } - internal string GetAttribute(string name, string namespaceUri) + internal string? GetAttribute(string name, string namespaceUri) { return isEndOfEmptyElement ? null : reader.GetAttribute(name, namespaceUri); } @@ -349,11 +349,13 @@ internal IDataNode ReadExtensionData(Type valueType) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateInvalidPrimitiveTypeException(valueType)); } + [DoesNotReturn] private void ThrowConversionException(string value, string type) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(XmlObjectSerializer.TryAddLineInfo(this, SR.Format(SR.XmlInvalidConversion, value, type)))); } + [DoesNotReturn] private void ThrowNotAtElement() { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(SR.Format(SR.XmlStartElementExpected, "EndElement"))); @@ -513,7 +515,8 @@ public virtual byte[] ReadContentAsBase64() } } - internal byte[] ReadContentAsBase64(string str) + [return: NotNullIfNotNull("str")] + internal byte[]? ReadContentAsBase64(string? str) { if (str == null) return null; @@ -869,7 +872,8 @@ internal virtual XmlQualifiedName ReadContentAsQName() private XmlQualifiedName ParseQualifiedName(string str) { - string name, ns, prefix; + string name, prefix; + string? ns; if (str == null || str.Length == 0) name = ns = string.Empty; else @@ -899,7 +903,7 @@ public bool TryReadBooleanArray(XmlObjectSerializerReadContext context, internal bool TryReadBooleanArray(XmlObjectSerializerReadContext context, #endif XmlDictionaryString itemName, XmlDictionaryString itemNamespace, - int arrayLength, out bool[] array) + int arrayLength, [NotNullWhen(true)] out bool[]? array) { if (dictionaryReader == null) { @@ -933,7 +937,7 @@ public virtual bool TryReadDateTimeArray(XmlObjectSerializerReadContext context, internal virtual bool TryReadDateTimeArray(XmlObjectSerializerReadContext context, #endif XmlDictionaryString itemName, XmlDictionaryString itemNamespace, - int arrayLength, out DateTime[] array) + int arrayLength, [NotNullWhen(true)] out DateTime[]? array) { if (dictionaryReader == null) { @@ -967,7 +971,7 @@ public bool TryReadDecimalArray(XmlObjectSerializerReadContext context, internal bool TryReadDecimalArray(XmlObjectSerializerReadContext context, #endif XmlDictionaryString itemName, XmlDictionaryString itemNamespace, - int arrayLength, out decimal[] array) + int arrayLength, [NotNullWhen(true)] out decimal[]? array) { if (dictionaryReader == null) { @@ -1001,7 +1005,7 @@ public bool TryReadInt32Array(XmlObjectSerializerReadContext context, internal bool TryReadInt32Array(XmlObjectSerializerReadContext context, #endif XmlDictionaryString itemName, XmlDictionaryString itemNamespace, - int arrayLength, out int[] array) + int arrayLength, [NotNullWhen(true)] out int[]? array) { if (dictionaryReader == null) { @@ -1035,7 +1039,7 @@ public bool TryReadInt64Array(XmlObjectSerializerReadContext context, internal bool TryReadInt64Array(XmlObjectSerializerReadContext context, #endif XmlDictionaryString itemName, XmlDictionaryString itemNamespace, - int arrayLength, out long[] array) + int arrayLength, [NotNullWhen(true)] out long[]? array) { if (dictionaryReader == null) { @@ -1069,7 +1073,7 @@ public bool TryReadSingleArray(XmlObjectSerializerReadContext context, internal bool TryReadSingleArray(XmlObjectSerializerReadContext context, #endif XmlDictionaryString itemName, XmlDictionaryString itemNamespace, - int arrayLength, out float[] array) + int arrayLength, [NotNullWhen(true)] out float[]? array) { if (dictionaryReader == null) { @@ -1103,7 +1107,7 @@ public bool TryReadDoubleArray(XmlObjectSerializerReadContext context, internal bool TryReadDoubleArray(XmlObjectSerializerReadContext context, #endif XmlDictionaryString itemName, XmlDictionaryString itemNamespace, - int arrayLength, out double[] array) + int arrayLength, [NotNullWhen(true)] out double[]? array) { if (dictionaryReader == null) { @@ -1131,7 +1135,7 @@ internal bool TryReadDoubleArray(XmlObjectSerializerReadContext context, return true; } - internal IDictionary GetNamespacesInScope(XmlNamespaceScope scope) + internal IDictionary? GetNamespacesInScope(XmlNamespaceScope scope) { return (reader is IXmlNamespaceResolver) ? ((IXmlNamespaceResolver)reader).GetNamespacesInScope(scope) : null; } @@ -1139,7 +1143,7 @@ internal IDictionary GetNamespacesInScope(XmlNamespaceScope scop // IXmlLineInfo members internal bool HasLineInfo() { - IXmlLineInfo iXmlLineInfo = reader as IXmlLineInfo; + IXmlLineInfo? iXmlLineInfo = reader as IXmlLineInfo; return (iXmlLineInfo == null) ? false : iXmlLineInfo.HasLineInfo(); } @@ -1147,7 +1151,7 @@ internal int LineNumber { get { - IXmlLineInfo iXmlLineInfo = reader as IXmlLineInfo; + IXmlLineInfo? iXmlLineInfo = reader as IXmlLineInfo; return (iXmlLineInfo == null) ? 0 : iXmlLineInfo.LineNumber; } } @@ -1156,7 +1160,7 @@ internal int LinePosition { get { - IXmlLineInfo iXmlLineInfo = reader as IXmlLineInfo; + IXmlLineInfo? iXmlLineInfo = reader as IXmlLineInfo; return (iXmlLineInfo == null) ? 0 : iXmlLineInfo.LinePosition; } } @@ -1166,10 +1170,10 @@ internal bool Normalized { get { - XmlTextReader xmlTextReader = reader as XmlTextReader; + XmlTextReader? xmlTextReader = reader as XmlTextReader; if (xmlTextReader == null) { - IXmlTextParser xmlTextParser = reader as IXmlTextParser; + IXmlTextParser? xmlTextParser = reader as IXmlTextParser; return (xmlTextParser == null) ? false : xmlTextParser.Normalized; } else @@ -1177,10 +1181,10 @@ internal bool Normalized } set { - XmlTextReader xmlTextReader = reader as XmlTextReader; + XmlTextReader? xmlTextReader = reader as XmlTextReader; if (xmlTextReader == null) { - IXmlTextParser xmlTextParser = reader as IXmlTextParser; + IXmlTextParser? xmlTextParser = reader as IXmlTextParser; if (xmlTextParser != null) xmlTextParser.Normalized = value; } @@ -1193,10 +1197,10 @@ internal WhitespaceHandling WhitespaceHandling { get { - XmlTextReader xmlTextReader = reader as XmlTextReader; + XmlTextReader? xmlTextReader = reader as XmlTextReader; if (xmlTextReader == null) { - IXmlTextParser xmlTextParser = reader as IXmlTextParser; + IXmlTextParser? xmlTextParser = reader as IXmlTextParser; return (xmlTextParser == null) ? WhitespaceHandling.None : xmlTextParser.WhitespaceHandling; } else @@ -1204,10 +1208,10 @@ internal WhitespaceHandling WhitespaceHandling } set { - XmlTextReader xmlTextReader = reader as XmlTextReader; + XmlTextReader? xmlTextReader = reader as XmlTextReader; if (xmlTextReader == null) { - IXmlTextParser xmlTextParser = reader as IXmlTextParser; + IXmlTextParser? xmlTextParser = reader as IXmlTextParser; if (xmlTextParser != null) xmlTextParser.WhitespaceHandling = value; } @@ -1223,7 +1227,7 @@ internal WhitespaceHandling WhitespaceHandling internal string Value { get { return reader.Value; } } internal Type ValueType { get { return reader.ValueType; } } internal int Depth { get { return reader.Depth; } } - internal string LookupNamespace(string prefix) { return reader.LookupNamespace(prefix); } + internal string? LookupNamespace(string prefix) { return reader.LookupNamespace(prefix); } internal bool EOF { get { return reader.EOF; } } internal void Skip() diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlSerializableReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlSerializableReader.cs index 9356e764099166..a8a259e0b32795 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlSerializableReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlSerializableReader.cs @@ -12,10 +12,10 @@ namespace System.Runtime.Serialization { internal class XmlSerializableReader : XmlReader, IXmlLineInfo { - private XmlReaderDelegator _xmlReader; + private XmlReaderDelegator _xmlReader = null!; // initialized in BeginRead private int _startDepth; private bool _isRootEmptyElement; - private XmlReader _innerReader; + private XmlReader _innerReader = null!; // initialized in BeginRead private XmlReader InnerReader { @@ -67,7 +67,7 @@ public override void Close() throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.IXmlSerializableIllegalOperation)); } - public override XmlReaderSettings Settings { get { return InnerReader.Settings; } } + public override XmlReaderSettings? Settings { get { return InnerReader.Settings; } } public override XmlNodeType NodeType { get { return InnerReader.NodeType; } } public override string Name { get { return InnerReader.Name; } } public override string LocalName { get { return InnerReader.LocalName; } } @@ -76,7 +76,7 @@ public override void Close() public override bool HasValue { get { return InnerReader.HasValue; } } public override string Value { get { return InnerReader.Value; } } public override int Depth { get { return InnerReader.Depth; } } - public override string BaseURI { get { return InnerReader.BaseURI; } } + public override string? BaseURI { get { return InnerReader.BaseURI; } } public override bool IsEmptyElement { get { return InnerReader.IsEmptyElement; } } public override bool IsDefault { get { return InnerReader.IsDefault; } } public override XmlSpace XmlSpace { get { return InnerReader.XmlSpace; } } @@ -84,8 +84,9 @@ public override void Close() public override Type ValueType { get { return InnerReader.ValueType; } } public override int AttributeCount { get { return InnerReader.AttributeCount; } } public override string this[int i] { get { return InnerReader[i]; } } - public override string this[string name] { get { return InnerReader[name]; } } - public override string this[string name, string namespaceURI] { get { return InnerReader[name, namespaceURI]; } } + public override string? this[string name] { get { return InnerReader[name]; } } + // TODO-NULLABLE - unnecessary namespaceURI! - https://github.com/dotnet/roslyn/issues/47221 + public override string? this[string name, string? namespaceURI] { get { return InnerReader[name, namespaceURI!]; } } public override bool EOF { get { return InnerReader.EOF; } } public override ReadState ReadState { get { return InnerReader.ReadState; } } public override XmlNameTable NameTable { get { return InnerReader.NameTable; } } @@ -94,16 +95,16 @@ public override void Close() public override bool CanReadValueChunk { get { return InnerReader.CanReadValueChunk; } } public override bool HasAttributes { get { return InnerReader.HasAttributes; } } - public override string GetAttribute(string name) { return InnerReader.GetAttribute(name); } - public override string GetAttribute(string name, string namespaceURI) { return InnerReader.GetAttribute(name, namespaceURI); } + public override string? GetAttribute(string name) { return InnerReader.GetAttribute(name); } + public override string? GetAttribute(string name, string? namespaceURI) { return InnerReader.GetAttribute(name, namespaceURI); } public override string GetAttribute(int i) { return InnerReader.GetAttribute(i); } public override bool MoveToAttribute(string name) { return InnerReader.MoveToAttribute(name); } - public override bool MoveToAttribute(string name, string ns) { return InnerReader.MoveToAttribute(name, ns); } + public override bool MoveToAttribute(string name, string? ns) { return InnerReader.MoveToAttribute(name, ns); } public override void MoveToAttribute(int i) { InnerReader.MoveToAttribute(i); } public override bool MoveToFirstAttribute() { return InnerReader.MoveToFirstAttribute(); } public override bool MoveToNextAttribute() { return InnerReader.MoveToNextAttribute(); } public override bool MoveToElement() { return InnerReader.MoveToElement(); } - public override string LookupNamespace(string prefix) { return InnerReader.LookupNamespace(prefix); } + public override string? LookupNamespace(string prefix) { return InnerReader.LookupNamespace(prefix); } public override bool ReadAttributeValue() { return InnerReader.ReadAttributeValue(); } public override void ResolveEntity() { InnerReader.ResolveEntity(); } public override bool IsStartElement() { return InnerReader.IsStartElement(); } @@ -118,14 +119,14 @@ public override void Close() public override int ReadContentAsInt() { return InnerReader.ReadContentAsInt(); } public override long ReadContentAsLong() { return InnerReader.ReadContentAsLong(); } public override string ReadContentAsString() { return InnerReader.ReadContentAsString(); } - public override object ReadContentAs(Type returnType, IXmlNamespaceResolver namespaceResolver) { return InnerReader.ReadContentAs(returnType, namespaceResolver); } + public override object ReadContentAs(Type returnType, IXmlNamespaceResolver? namespaceResolver) { return InnerReader.ReadContentAs(returnType, namespaceResolver); } public override int ReadContentAsBase64(byte[] buffer, int index, int count) { return InnerReader.ReadContentAsBase64(buffer, index, count); } public override int ReadContentAsBinHex(byte[] buffer, int index, int count) { return InnerReader.ReadContentAsBinHex(buffer, index, count); } public override int ReadValueChunk(char[] buffer, int index, int count) { return InnerReader.ReadValueChunk(buffer, index, count); } // IXmlLineInfo members bool IXmlLineInfo.HasLineInfo() { - IXmlLineInfo xmlLineInfo = InnerReader as IXmlLineInfo; + IXmlLineInfo? xmlLineInfo = InnerReader as IXmlLineInfo; return (xmlLineInfo == null) ? _xmlReader.HasLineInfo() : xmlLineInfo.HasLineInfo(); } @@ -133,7 +134,7 @@ int IXmlLineInfo.LineNumber { get { - IXmlLineInfo xmlLineInfo = InnerReader as IXmlLineInfo; + IXmlLineInfo? xmlLineInfo = InnerReader as IXmlLineInfo; return (xmlLineInfo == null) ? _xmlReader.LineNumber : xmlLineInfo.LineNumber; } } @@ -142,7 +143,7 @@ int IXmlLineInfo.LinePosition { get { - IXmlLineInfo xmlLineInfo = InnerReader as IXmlLineInfo; + IXmlLineInfo? xmlLineInfo = InnerReader as IXmlLineInfo; return (xmlLineInfo == null) ? _xmlReader.LinePosition : xmlLineInfo.LinePosition; } } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlSerializableServices.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlSerializableServices.cs index 8779b62e235de2..3746d5dafdcbcf 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlSerializableServices.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlSerializableServices.cs @@ -21,7 +21,7 @@ public static XmlNode[] ReadNodes(XmlReader xmlReader) { if (IsValidAttribute(xmlReader)) { - XmlNode node = doc.ReadNode(xmlReader); + XmlNode? node = doc.ReadNode(xmlReader); if (node == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.UnexpectedEndOfFile)); nodeList.Add(node); @@ -35,7 +35,7 @@ public static XmlNode[] ReadNodes(XmlReader xmlReader) xmlReader.Read(); while (xmlReader.Depth > startDepth && xmlReader.NodeType != XmlNodeType.EndElement) { - XmlNode node = doc.ReadNode(xmlReader); + XmlNode? node = doc.ReadNode(xmlReader); if (node == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.UnexpectedEndOfFile)); nodeList.Add(node); @@ -52,14 +52,14 @@ private static bool IsValidAttribute(XmlReader xmlReader) xmlReader.LocalName != "xmlns"; } - public static void WriteNodes(XmlWriter xmlWriter, XmlNode[] nodes) + public static void WriteNodes(XmlWriter xmlWriter, XmlNode?[]? nodes) { if (xmlWriter == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(xmlWriter)); if (nodes != null) for (int i = 0; i < nodes.Length; i++) if (nodes[i] != null) - nodes[i].WriteTo(xmlWriter); + nodes[i]!.WriteTo(xmlWriter); } internal static string AddDefaultSchemaMethodName = "AddDefaultSchema"; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlSerializableWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlSerializableWriter.cs index 15703f8fcbf28d..f127737dfa132f 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlSerializableWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlSerializableWriter.cs @@ -9,9 +9,9 @@ namespace System.Runtime.Serialization { internal class XmlSerializableWriter : XmlWriter { - private XmlWriter _xmlWriter; + private XmlWriter _xmlWriter = null!; // initialized in BeginWrite private int _depth; - private object _obj; + private object? _obj; internal void BeginWrite(XmlWriter xmlWriter, object obj) { @@ -38,12 +38,12 @@ public override void WriteStartDocument(bool standalone) if (WriteState == WriteState.Start) _xmlWriter.WriteStartDocument(standalone); } - public override void WriteDocType(string name, string pubid, string sysid, string subset) + public override void WriteDocType(string name, string? pubid, string? sysid, string? subset) { // XmlSerializer does not write doc type } - public override void WriteStartElement(string prefix, string localName, string ns) + public override void WriteStartElement(string? prefix, string localName, string? ns) { _xmlWriter.WriteStartElement(prefix, localName, ns); _depth++; @@ -70,19 +70,19 @@ public override void Close() throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(XmlObjectSerializer.CreateSerializationException(SR.IXmlSerializableIllegalOperation)); } - public override void WriteStartAttribute(string prefix, string localName, string ns) + public override void WriteStartAttribute(string? prefix, string localName, string? ns) { _xmlWriter.WriteStartAttribute(prefix, localName, ns); } public override void WriteEndAttribute() { _xmlWriter.WriteEndAttribute(); } - public override void WriteCData(string text) { _xmlWriter.WriteCData(text); } - public override void WriteComment(string text) { _xmlWriter.WriteComment(text); } - public override void WriteProcessingInstruction(string name, string text) { _xmlWriter.WriteProcessingInstruction(name, text); } + public override void WriteCData(string? text) { _xmlWriter.WriteCData(text); } + public override void WriteComment(string? text) { _xmlWriter.WriteComment(text); } + public override void WriteProcessingInstruction(string name, string? text) { _xmlWriter.WriteProcessingInstruction(name, text); } public override void WriteEntityRef(string name) { _xmlWriter.WriteEntityRef(name); } public override void WriteCharEntity(char ch) { _xmlWriter.WriteCharEntity(ch); } - public override void WriteWhitespace(string ws) { _xmlWriter.WriteWhitespace(ws); } - public override void WriteString(string text) { _xmlWriter.WriteString(text); } + public override void WriteWhitespace(string? ws) { _xmlWriter.WriteWhitespace(ws); } + public override void WriteString(string? text) { _xmlWriter.WriteString(text); } public override void WriteSurrogateCharEntity(char lowChar, char highChar) { _xmlWriter.WriteSurrogateCharEntity(lowChar, highChar); } public override void WriteChars(char[] buffer, int index, int count) { _xmlWriter.WriteChars(buffer, index, count); } public override void WriteRaw(char[] buffer, int index, int count) { _xmlWriter.WriteRaw(buffer, index, count); } @@ -92,10 +92,10 @@ public override void WriteStartAttribute(string prefix, string localName, string public override WriteState WriteState { get { return _xmlWriter.WriteState; } } public override void Flush() { _xmlWriter.Flush(); } public override void WriteName(string name) { _xmlWriter.WriteName(name); } - public override void WriteQualifiedName(string localName, string ns) { _xmlWriter.WriteQualifiedName(localName, ns); } - public override string LookupPrefix(string ns) { return _xmlWriter.LookupPrefix(ns); } + public override void WriteQualifiedName(string localName, string? ns) { _xmlWriter.WriteQualifiedName(localName, ns); } + public override string? LookupPrefix(string ns) { return _xmlWriter.LookupPrefix(ns); } public override XmlSpace XmlSpace { get { return _xmlWriter.XmlSpace; } } - public override string XmlLang { get { return _xmlWriter.XmlLang; } } + public override string? XmlLang { get { return _xmlWriter.XmlLang; } } public override void WriteNmToken(string name) { _xmlWriter.WriteNmToken(name); } } } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlWriterDelegator.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlWriterDelegator.cs index 94224789d75084..cfe9539c6ccf5b 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlWriterDelegator.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XmlWriterDelegator.cs @@ -14,7 +14,7 @@ internal class XmlWriterDelegator #endif { protected XmlWriter writer; - protected XmlDictionaryWriter dictionaryWriter; + protected XmlDictionaryWriter? dictionaryWriter; internal int depth; private int _prefixes; @@ -35,7 +35,7 @@ internal void Flush() writer.Flush(); } - internal string LookupPrefix(string ns) + internal string? LookupPrefix(string ns) { return writer.LookupPrefix(ns); } @@ -77,7 +77,7 @@ internal void WriteXmlnsAttribute(XmlDictionaryString ns) WriteXmlnsAttribute(ns.Value); } - internal void WriteXmlnsAttribute(string ns) + internal void WriteXmlnsAttribute(string? ns) { if (ns != null) { @@ -89,7 +89,7 @@ internal void WriteXmlnsAttribute(string ns) dictionaryWriter.WriteXmlnsAttribute(null, ns); else { - string prefix = writer.LookupPrefix(ns); + string? prefix = writer.LookupPrefix(ns); if (prefix == null) { prefix = string.Format(CultureInfo.InvariantCulture, "d{0}p{1}", depth, _prefixes); @@ -113,7 +113,7 @@ internal void WriteXmlnsAttribute(string prefix, XmlDictionaryString ns) } } - private void WriteStartAttribute(string prefix, string localName, string ns) + private void WriteStartAttribute(string? prefix, string localName, string? ns) { writer.WriteStartAttribute(prefix, localName, ns); } @@ -124,11 +124,11 @@ private void WriteStartAttribute(string prefix, XmlDictionaryString localName, X dictionaryWriter.WriteStartAttribute(prefix, localName, namespaceUri); else writer.WriteStartAttribute(prefix, - (localName == null ? null : localName.Value), + (localName == null ? null : localName.Value)!, (namespaceUri == null ? null : namespaceUri.Value)); } - internal void WriteAttributeString(string prefix, string localName, string ns, string value) + internal void WriteAttributeString(string? prefix, string localName, string? ns, string value) { WriteStartAttribute(prefix, localName, ns); WriteAttributeStringValue(value); @@ -186,7 +186,7 @@ private void WriteAttributeBoolValue(bool value) writer.WriteValue(value); } - internal void WriteAttributeQualifiedName(string attrPrefix, XmlDictionaryString attrName, XmlDictionaryString attrNs, string name, string ns) + internal void WriteAttributeQualifiedName(string attrPrefix, XmlDictionaryString attrName, XmlDictionaryString attrNs, string name, string? ns) { WriteXmlnsAttribute(ns); WriteStartAttribute(attrPrefix, attrName, attrNs); @@ -194,7 +194,7 @@ internal void WriteAttributeQualifiedName(string attrPrefix, XmlDictionaryString WriteEndAttribute(); } - private void WriteAttributeQualifiedNameValue(string name, string ns) + private void WriteAttributeQualifiedNameValue(string name, string? ns) { writer.WriteQualifiedName(name, ns); } @@ -215,12 +215,12 @@ private void WriteAttributeQualifiedNameValue(XmlDictionaryString name, XmlDicti dictionaryWriter.WriteQualifiedName(name, ns); } - internal void WriteStartElement(string localName, string ns) + internal void WriteStartElement(string localName, string? ns) { WriteStartElement(null, localName, ns); } - internal virtual void WriteStartElement(string prefix, string localName, string ns) + internal virtual void WriteStartElement(string? prefix, string localName, string? ns) { writer.WriteStartElement(prefix, localName, ns); depth++; @@ -230,28 +230,28 @@ internal virtual void WriteStartElement(string prefix, string localName, string #if USE_REFEMIT public void WriteStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri) #else - internal void WriteStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri) + internal void WriteStartElement(XmlDictionaryString localName, XmlDictionaryString? namespaceUri) #endif { WriteStartElement(null, localName, namespaceUri); } - internal void WriteStartElement(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri) + internal void WriteStartElement(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri) { if (dictionaryWriter != null) dictionaryWriter.WriteStartElement(prefix, localName, namespaceUri); else - writer.WriteStartElement(prefix, (localName == null ? null : localName.Value), (namespaceUri == null ? null : namespaceUri.Value)); + writer.WriteStartElement(prefix, (localName == null ? null : localName.Value)!, (namespaceUri == null ? null : namespaceUri.Value)); depth++; _prefixes = 1; } - internal void WriteStartElementPrimitive(XmlDictionaryString localName, XmlDictionaryString namespaceUri) + internal void WriteStartElementPrimitive(XmlDictionaryString localName, XmlDictionaryString? namespaceUri) { if (dictionaryWriter != null) dictionaryWriter.WriteStartElement(null, localName, namespaceUri); else - writer.WriteStartElement(null, (localName == null ? null : localName.Value), (namespaceUri == null ? null : namespaceUri.Value)); + writer.WriteStartElement(null, (localName == null ? null : localName.Value)!, (namespaceUri == null ? null : namespaceUri.Value)); } internal void WriteEndElementPrimitive() @@ -264,7 +264,7 @@ internal WriteState WriteState get { return writer.WriteState; } } - internal string XmlLang + internal string? XmlLang { get { return writer.XmlLang; } } @@ -427,7 +427,7 @@ internal void WriteExtensionData(IDataNode dataNode) WriteBase64(((DataNode)dataNode).GetValue()); else if (valueType == Globals.TypeOfObject) { - object obj = dataNode.Value; + object? obj = dataNode.Value; if (obj != null) WriteAnyType(obj); } @@ -460,9 +460,9 @@ internal virtual void WriteBoolean(bool value) writer.WriteValue(value); } #if USE_REFEMIT - public void WriteBoolean(bool value, XmlDictionaryString name, XmlDictionaryString ns) + public void WriteBoolean(bool value, XmlDictionaryString name, XmlDictionaryString? ns) #else - internal void WriteBoolean(bool value, XmlDictionaryString name, XmlDictionaryString ns) + internal void WriteBoolean(bool value, XmlDictionaryString name, XmlDictionaryString? ns) #endif { WriteStartElementPrimitive(name, ns); @@ -476,9 +476,9 @@ internal virtual void WriteDateTime(DateTime value) } #if USE_REFEMIT - public void WriteDateTime(DateTime value, XmlDictionaryString name, XmlDictionaryString ns) + public void WriteDateTime(DateTime value, XmlDictionaryString name, XmlDictionaryString? ns) #else - internal void WriteDateTime(DateTime value, XmlDictionaryString name, XmlDictionaryString ns) + internal void WriteDateTime(DateTime value, XmlDictionaryString name, XmlDictionaryString? ns) #endif { WriteStartElementPrimitive(name, ns); @@ -491,9 +491,9 @@ internal virtual void WriteDecimal(decimal value) writer.WriteValue(value); } #if USE_REFEMIT - public void WriteDecimal(decimal value, XmlDictionaryString name, XmlDictionaryString ns) + public void WriteDecimal(decimal value, XmlDictionaryString name, XmlDictionaryString? ns) #else - internal void WriteDecimal(decimal value, XmlDictionaryString name, XmlDictionaryString ns) + internal void WriteDecimal(decimal value, XmlDictionaryString name, XmlDictionaryString? ns) #endif { WriteStartElementPrimitive(name, ns); @@ -506,9 +506,9 @@ internal virtual void WriteDouble(double value) writer.WriteValue(value); } #if USE_REFEMIT - public void WriteDouble(double value, XmlDictionaryString name, XmlDictionaryString ns) + public void WriteDouble(double value, XmlDictionaryString name, XmlDictionaryString? ns) #else - internal void WriteDouble(double value, XmlDictionaryString name, XmlDictionaryString ns) + internal void WriteDouble(double value, XmlDictionaryString name, XmlDictionaryString? ns) #endif { WriteStartElementPrimitive(name, ns); @@ -521,9 +521,9 @@ internal virtual void WriteInt(int value) writer.WriteValue(value); } #if USE_REFEMIT - public void WriteInt(int value, XmlDictionaryString name, XmlDictionaryString ns) + public void WriteInt(int value, XmlDictionaryString name, XmlDictionaryString? ns) #else - internal void WriteInt(int value, XmlDictionaryString name, XmlDictionaryString ns) + internal void WriteInt(int value, XmlDictionaryString name, XmlDictionaryString? ns) #endif { WriteStartElementPrimitive(name, ns); @@ -536,9 +536,9 @@ internal virtual void WriteLong(long value) writer.WriteValue(value); } #if USE_REFEMIT - public void WriteLong(long value, XmlDictionaryString name, XmlDictionaryString ns) + public void WriteLong(long value, XmlDictionaryString name, XmlDictionaryString? ns) #else - internal void WriteLong(long value, XmlDictionaryString name, XmlDictionaryString ns) + internal void WriteLong(long value, XmlDictionaryString name, XmlDictionaryString? ns) #endif { WriteStartElementPrimitive(name, ns); @@ -551,9 +551,9 @@ internal virtual void WriteFloat(float value) writer.WriteValue(value); } #if USE_REFEMIT - public void WriteFloat(float value, XmlDictionaryString name, XmlDictionaryString ns) + public void WriteFloat(float value, XmlDictionaryString name, XmlDictionaryString? ns) #else - internal void WriteFloat(float value, XmlDictionaryString name, XmlDictionaryString ns) + internal void WriteFloat(float value, XmlDictionaryString name, XmlDictionaryString? ns) #endif { WriteStartElementPrimitive(name, ns); @@ -561,7 +561,7 @@ internal void WriteFloat(float value, XmlDictionaryString name, XmlDictionaryStr WriteEndElementPrimitive(); } - internal virtual void WriteBase64(byte[] bytes) + internal virtual void WriteBase64(byte[]? bytes) { if (bytes == null) return; @@ -574,9 +574,9 @@ internal virtual void WriteShort(short value) writer.WriteValue(value); } #if USE_REFEMIT - public void WriteShort(short value, XmlDictionaryString name, XmlDictionaryString ns) + public void WriteShort(short value, XmlDictionaryString name, XmlDictionaryString? ns) #else - internal void WriteShort(short value, XmlDictionaryString name, XmlDictionaryString ns) + internal void WriteShort(short value, XmlDictionaryString name, XmlDictionaryString? ns) #endif { WriteStartElementPrimitive(name, ns); @@ -589,9 +589,9 @@ internal virtual void WriteUnsignedByte(byte value) writer.WriteValue(value); } #if USE_REFEMIT - public void WriteUnsignedByte(byte value, XmlDictionaryString name, XmlDictionaryString ns) + public void WriteUnsignedByte(byte value, XmlDictionaryString name, XmlDictionaryString? ns) #else - internal void WriteUnsignedByte(byte value, XmlDictionaryString name, XmlDictionaryString ns) + internal void WriteUnsignedByte(byte value, XmlDictionaryString name, XmlDictionaryString? ns) #endif { WriteStartElementPrimitive(name, ns); @@ -605,9 +605,9 @@ internal virtual void WriteSignedByte(sbyte value) } #if USE_REFEMIT [CLSCompliant(false)] - public void WriteSignedByte(sbyte value, XmlDictionaryString name, XmlDictionaryString ns) + public void WriteSignedByte(sbyte value, XmlDictionaryString name, XmlDictionaryString? ns) #else - internal void WriteSignedByte(sbyte value, XmlDictionaryString name, XmlDictionaryString ns) + internal void WriteSignedByte(sbyte value, XmlDictionaryString name, XmlDictionaryString? ns) #endif { WriteStartElementPrimitive(name, ns); @@ -621,9 +621,9 @@ internal virtual void WriteUnsignedInt(uint value) } #if USE_REFEMIT [CLSCompliant(false)] - public void WriteUnsignedInt(uint value, XmlDictionaryString name, XmlDictionaryString ns) + public void WriteUnsignedInt(uint value, XmlDictionaryString name, XmlDictionaryString? ns) #else - internal void WriteUnsignedInt(uint value, XmlDictionaryString name, XmlDictionaryString ns) + internal void WriteUnsignedInt(uint value, XmlDictionaryString name, XmlDictionaryString? ns) #endif { WriteStartElementPrimitive(name, ns); @@ -637,9 +637,9 @@ internal virtual void WriteUnsignedLong(ulong value) } #if USE_REFEMIT [CLSCompliant(false)] - public void WriteUnsignedLong(ulong value, XmlDictionaryString name, XmlDictionaryString ns) + public void WriteUnsignedLong(ulong value, XmlDictionaryString name, XmlDictionaryString? ns) #else - internal void WriteUnsignedLong(ulong value, XmlDictionaryString name, XmlDictionaryString ns) + internal void WriteUnsignedLong(ulong value, XmlDictionaryString name, XmlDictionaryString? ns) #endif { WriteStartElementPrimitive(name, ns); @@ -653,9 +653,9 @@ internal virtual void WriteUnsignedShort(ushort value) } #if USE_REFEMIT [CLSCompliant(false)] - public void WriteUnsignedShort(ushort value, XmlDictionaryString name, XmlDictionaryString ns) + public void WriteUnsignedShort(ushort value, XmlDictionaryString name, XmlDictionaryString? ns) #else - internal void WriteUnsignedShort(ushort value, XmlDictionaryString name, XmlDictionaryString ns) + internal void WriteUnsignedShort(ushort value, XmlDictionaryString name, XmlDictionaryString? ns) #endif { WriteStartElementPrimitive(name, ns); @@ -668,9 +668,9 @@ internal virtual void WriteChar(char value) writer.WriteValue((int)value); } #if USE_REFEMIT - public void WriteChar(char value, XmlDictionaryString name, XmlDictionaryString ns) + public void WriteChar(char value, XmlDictionaryString name, XmlDictionaryString? ns) #else - internal void WriteChar(char value, XmlDictionaryString name, XmlDictionaryString ns) + internal void WriteChar(char value, XmlDictionaryString name, XmlDictionaryString? ns) #endif { WriteStartElementPrimitive(name, ns); @@ -683,7 +683,7 @@ internal void WriteTimeSpan(TimeSpan value) writer.WriteRaw(XmlConvert.ToString(value)); } - internal void WriteTimeSpan(char value, XmlDictionaryString name, XmlDictionaryString ns) + internal void WriteTimeSpan(char value, XmlDictionaryString name, XmlDictionaryString? ns) { WriteStartElementPrimitive(name, ns); writer.WriteRaw(XmlConvert.ToString(value)); @@ -691,9 +691,9 @@ internal void WriteTimeSpan(char value, XmlDictionaryString name, XmlDictionaryS } #if USE_REFEMIT - public void WriteTimeSpan(TimeSpan value, XmlDictionaryString name, XmlDictionaryString ns) + public void WriteTimeSpan(TimeSpan value, XmlDictionaryString name, XmlDictionaryString? ns) #else - internal void WriteTimeSpan(TimeSpan value, XmlDictionaryString name, XmlDictionaryString ns) + internal void WriteTimeSpan(TimeSpan value, XmlDictionaryString name, XmlDictionaryString? ns) #endif { WriteStartElementPrimitive(name, ns); @@ -706,9 +706,9 @@ internal void WriteGuid(Guid value) writer.WriteRaw(value.ToString()); } #if USE_REFEMIT - public void WriteGuid(Guid value, XmlDictionaryString name, XmlDictionaryString ns) + public void WriteGuid(Guid value, XmlDictionaryString name, XmlDictionaryString? ns) #else - internal void WriteGuid(Guid value, XmlDictionaryString name, XmlDictionaryString ns) + internal void WriteGuid(Guid value, XmlDictionaryString name, XmlDictionaryString? ns) #endif { WriteStartElementPrimitive(name, ns); @@ -716,12 +716,12 @@ internal void WriteGuid(Guid value, XmlDictionaryString name, XmlDictionaryStrin WriteEndElementPrimitive(); } - internal void WriteUri(Uri value) + internal void WriteUri(Uri? value) { - writer.WriteString(value.GetComponents(UriComponents.SerializationInfoString, UriFormat.UriEscaped)); + writer.WriteString(value?.GetComponents(UriComponents.SerializationInfoString, UriFormat.UriEscaped)); } - internal void WriteUri(Uri value, XmlDictionaryString name, XmlDictionaryString ns) + internal void WriteUri(Uri? value, XmlDictionaryString name, XmlDictionaryString? ns) { WriteStartElementPrimitive(name, ns); WriteUri(value); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XsdDataContractExporter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XsdDataContractExporter.cs index 11f84946d50c2a..d240e7885209b8 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XsdDataContractExporter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/XsdDataContractExporter.cs @@ -12,20 +12,20 @@ namespace System.Runtime.Serialization { public class XsdDataContractExporter { - private ExportOptions _options; - private XmlSchemaSet _schemas; - private DataContractSet _dataContractSet; + private ExportOptions? _options; + private XmlSchemaSet? _schemas; + private DataContractSet? _dataContractSet; public XsdDataContractExporter() { } - public XsdDataContractExporter(XmlSchemaSet schemas) + public XsdDataContractExporter(XmlSchemaSet? schemas) { this._schemas = schemas; } - public ExportOptions Options + public ExportOptions? Options { get { return _options; } set { _options = value; } @@ -79,7 +79,7 @@ public void Export(ICollection assemblies) TraceExportBegin(); - DataContractSet oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet); + DataContractSet? oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet); try { foreach (Assembly assembly in assemblies) @@ -114,7 +114,7 @@ public void Export(ICollection types) TraceExportBegin(); - DataContractSet oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet); + DataContractSet? oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet); try { foreach (Type type in types) @@ -146,7 +146,7 @@ public void Export(Type type) TraceExportBegin(); - DataContractSet oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet); + DataContractSet? oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet); try { AddType(type); @@ -172,26 +172,26 @@ public XmlQualifiedName GetSchemaTypeName(Type type) type = GetSurrogatedType(type); DataContract dataContract = DataContract.GetDataContract(type); DataContractSet.EnsureTypeNotGeneric(dataContract.UnderlyingType); - XmlDataContract xmlDataContract = dataContract as XmlDataContract; + XmlDataContract? xmlDataContract = dataContract as XmlDataContract; if (xmlDataContract != null && xmlDataContract.IsAnonymous) return XmlQualifiedName.Empty; return dataContract.StableName; } - public XmlSchemaType GetSchemaType(Type type) + public XmlSchemaType? GetSchemaType(Type type) { if (type == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(type))); type = GetSurrogatedType(type); DataContract dataContract = DataContract.GetDataContract(type); DataContractSet.EnsureTypeNotGeneric(dataContract.UnderlyingType); - XmlDataContract xmlDataContract = dataContract as XmlDataContract; + XmlDataContract? xmlDataContract = dataContract as XmlDataContract; if (xmlDataContract != null && xmlDataContract.IsAnonymous) return xmlDataContract.XsdType; return null; } - public XmlQualifiedName GetRootElementName(Type type) + public XmlQualifiedName? GetRootElementName(Type type) { if (type == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(type))); @@ -200,7 +200,7 @@ public XmlQualifiedName GetRootElementName(Type type) DataContractSet.EnsureTypeNotGeneric(dataContract.UnderlyingType); if (dataContract.HasRoot) { - return new XmlQualifiedName(dataContract.TopLevelElementName.Value, dataContract.TopLevelElementNamespace.Value); + return new XmlQualifiedName(dataContract.TopLevelElementName!.Value, dataContract.TopLevelElementNamespace!.Value); } else { @@ -261,7 +261,7 @@ public bool CanExport(ICollection assemblies) if (assemblies == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(assemblies))); - DataContractSet oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet); + DataContractSet? oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet); try { foreach (Assembly assembly in assemblies) @@ -298,7 +298,7 @@ public bool CanExport(ICollection types) if (types == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(types))); - DataContractSet oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet); + DataContractSet? oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet); try { foreach (Type type in types) @@ -332,7 +332,7 @@ public bool CanExport(Type type) if (type == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(type))); - DataContractSet oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet); + DataContractSet? oldValue = (_dataContractSet == null) ? null : new DataContractSet(_dataContractSet); try { AddType(type); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/ArrayHelper.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/ArrayHelper.cs index b551e26e2dc089..76e7640138cff9 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/ArrayHelper.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/ArrayHelper.cs @@ -10,8 +10,8 @@ internal abstract class ArrayHelper { public TArray[] ReadArray(XmlDictionaryReader reader, TArgument localName, TArgument namespaceUri, int maxArrayLength) { - TArray[][] arrays = null; - TArray[] array = null; + TArray[][]? arrays = null; + TArray[]? array = null; int arrayCount = 0; int totalRead = 0; int count; @@ -49,7 +49,7 @@ public TArray[] ReadArray(XmlDictionaryReader reader, TArgument localName, TArgu int offset = 0; for (int i = 0; i < arrayCount; i++) { - Array.Copy(arrays[i], 0, newArray, offset, arrays[i].Length); + Array.Copy(arrays![i], 0, newArray, offset, arrays[i].Length); offset += arrays[i].Length; } Array.Copy(array, 0, newArray, offset, totalRead - offset); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/EncodingStreamWrapper.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/EncodingStreamWrapper.cs index c5f03aa0a2aea0..08416bf4ef91f6 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/EncodingStreamWrapper.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/EncodingStreamWrapper.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.Serialization; // For SR using System.Text; @@ -36,21 +38,21 @@ private enum SupportedEncoding { UTF8, UTF16LE, UTF16BE, None } private static readonly byte[] s_encodingUnicodeBE = new byte[] { (byte)'u', (byte)'t', (byte)'f', (byte)'-', (byte)'1', (byte)'6', (byte)'b', (byte)'e' }; private SupportedEncoding _encodingCode; - private Encoding _encoding; - private readonly Encoder _enc; - private readonly Decoder _dec; + private Encoding? _encoding; + private readonly Encoder? _enc; + private readonly Decoder? _dec; private readonly bool _isReading; private readonly Stream _stream; - private char[] _chars; - private byte[] _bytes; + private char[]? _chars; + private byte[]? _bytes; private int _byteOffset; private int _byteCount; private readonly byte[] _byteBuffer = new byte[1]; // Reading constructor - public EncodingStreamWrapper(Stream stream, Encoding encoding) + public EncodingStreamWrapper(Stream stream, Encoding? encoding) { try { @@ -111,6 +113,7 @@ public EncodingStreamWrapper(Stream stream, Encoding encoding) } } + [MemberNotNull(nameof(_encoding))] private void SetReadDocumentEncoding(SupportedEncoding e) { EnsureBuffers(); @@ -145,7 +148,7 @@ private static string GetEncodingName(SupportedEncoding enc) => _ => throw new XmlException(SR.XmlEncodingNotSupported), }; - private static SupportedEncoding GetSupportedEncoding(Encoding encoding) + private static SupportedEncoding GetSupportedEncoding(Encoding? encoding) { if (encoding == null) return SupportedEncoding.None; @@ -185,6 +188,7 @@ public EncodingStreamWrapper(Stream stream, Encoding encoding, bool emitBOM) } } + [MemberNotNull(nameof(_bytes))] private SupportedEncoding ReadBOMEncoding(bool notOutOfBand) { int b1 = _stream.ReadByte(); @@ -279,7 +283,7 @@ private void FillBuffer(int count) count -= _byteCount; while (count > 0) { - int read = _stream.Read(_bytes, _byteOffset + _byteCount, count); + int read = _stream.Read(_bytes!, _byteOffset + _byteCount, count); if (read == 0) break; @@ -288,6 +292,8 @@ private void FillBuffer(int count) } } + [MemberNotNull(nameof(_bytes))] + [MemberNotNull(nameof(_chars))] private void EnsureBuffers() { EnsureByteBuffer(); @@ -295,6 +301,7 @@ private void EnsureBuffers() _chars = new char[BufferLength]; } + [MemberNotNull(nameof(_bytes))] private void EnsureByteBuffer() { if (_bytes != null) @@ -439,7 +446,7 @@ private static bool IsWhitespace(byte ch) return ch == (byte)' ' || ch == (byte)'\n' || ch == (byte)'\t' || ch == (byte)'\r'; } - internal static ArraySegment ProcessBuffer(byte[] buffer, int offset, int count, Encoding encoding) + internal static ArraySegment ProcessBuffer(byte[] buffer, int offset, int count, Encoding? encoding) { if (count < 4) throw new XmlException(SR.UnexpectedEndOfFile); @@ -600,6 +607,9 @@ public override int Read(byte[] buffer, int offset, int count) if (_encodingCode == SupportedEncoding.UTF8) return _stream.Read(buffer, offset, count); + Debug.Assert(_bytes != null); + Debug.Assert(_chars != null); + // No more bytes than can be turned into characters _byteOffset = 0; _byteCount = _stream.Read(_bytes, _byteCount, (_chars.Length - 1) * 2); @@ -612,14 +622,14 @@ public override int Read(byte[] buffer, int offset, int count) CleanupCharBreak(); // Change encoding - int charCount = _encoding.GetChars(_bytes, 0, _byteCount, _chars, 0); + int charCount = _encoding!.GetChars(_bytes, 0, _byteCount, _chars, 0); _byteCount = Encoding.UTF8.GetBytes(_chars, 0, charCount, _bytes, 0); } // Give them bytes if (_byteCount < count) count = _byteCount; - Buffer.BlockCopy(_bytes, _byteOffset, buffer, offset, count); + Buffer.BlockCopy(_bytes!, _byteOffset, buffer, offset, count); _byteOffset += count; _byteCount -= count; return count; @@ -632,6 +642,8 @@ public override int Read(byte[] buffer, int offset, int count) private void CleanupCharBreak() { + Debug.Assert(_bytes != null); + int max = _byteOffset + _byteCount; // Read on 2 byte boundaries @@ -692,11 +704,14 @@ public override void Write(byte[] buffer, int offset, int count) return; } + Debug.Assert(_bytes != null); + Debug.Assert(_chars != null); + while (count > 0) { int size = _chars.Length < count ? _chars.Length : count; - int charCount = _dec.GetChars(buffer, offset, size, _chars, 0, false); - _byteCount = _enc.GetBytes(_chars, 0, charCount, _bytes, 0, false); + int charCount = _dec!.GetChars(buffer, offset, size, _chars, 0, false); + _byteCount = _enc!.GetBytes(_chars, 0, charCount, _bytes, 0, false); _stream.Write(_bytes, 0, _byteCount); offset += size; count -= size; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/IXmlDictionary.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/IXmlDictionary.cs index 884f4cba5fe8a2..1f1a5bb404bc8f 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/IXmlDictionary.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/IXmlDictionary.cs @@ -1,12 +1,14 @@ // 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; + namespace System.Xml { public interface IXmlDictionary { - bool TryLookup(string value, out XmlDictionaryString result); - bool TryLookup(int key, out XmlDictionaryString result); - bool TryLookup(XmlDictionaryString value, out XmlDictionaryString result); + bool TryLookup(string value, [NotNullWhen(true)] out XmlDictionaryString? result); + bool TryLookup(int key, [NotNullWhen(true)] out XmlDictionaryString? result); + bool TryLookup(XmlDictionaryString value, [NotNullWhen(true)] out XmlDictionaryString? result); } } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/PrefixHandle.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/PrefixHandle.cs index ef26d719047de6..92d98ab4276f31 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/PrefixHandle.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/PrefixHandle.cs @@ -177,7 +177,7 @@ public int CompareTo(PrefixHandle that) return GetString().CompareTo(that.GetString()); } - public bool Equals(PrefixHandle prefix2) + public bool Equals(PrefixHandle? prefix2) { if (ReferenceEquals(prefix2, null)) return false; @@ -234,7 +234,7 @@ private bool Equals2(XmlDictionaryString prefix2) { return !prefix1.Equals(prefix2); } - public override bool Equals(object obj) + public override bool Equals(object? obj) { return Equals(obj as PrefixHandle); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/StringHandle.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/StringHandle.cs index fa9e0b66a805d1..3f8fa8b1bf3899 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/StringHandle.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/StringHandle.cs @@ -4,7 +4,7 @@ using System; using System.Runtime.Serialization; using System.Diagnostics; - +using System.Diagnostics.CodeAnalysis; namespace System.Xml { @@ -161,7 +161,7 @@ public byte[] GetString(out int offset, out int length) } } - public bool TryGetDictionaryString(out XmlDictionaryString value) + public bool TryGetDictionaryString([NotNullWhen(true)] out XmlDictionaryString? value) { if (_type == StringHandleType.Dictionary) { @@ -226,7 +226,7 @@ private bool Equals2(int offset2, int length2, XmlBufferReader bufferReader2) return GetString() == _bufferReader.GetString(offset2, length2); } - public bool Equals(StringHandle other) + public bool Equals(StringHandle? other) { if (ReferenceEquals(other, null)) return false; @@ -275,7 +275,7 @@ public int CompareTo(StringHandle that) else return string.Compare(this.GetString(), that.GetString(), StringComparison.Ordinal); } - public override bool Equals(object obj) + public override bool Equals(object? obj) { return Equals(obj as StringHandle); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/UniqueId.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/UniqueId.cs index 07ecd304526b6e..95f9aa904ee1ad 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/UniqueId.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/UniqueId.cs @@ -7,7 +7,7 @@ public class UniqueId { private long _idLow; private long _idHigh; - private string _s; + private string? _s; private const int guidLength = 16; private const int uuidLength = 45; @@ -310,7 +310,7 @@ public unsafe override string ToString() return _s; } - public static bool operator ==(UniqueId id1, UniqueId id2) + public static bool operator ==(UniqueId? id1, UniqueId? id2) { if (object.ReferenceEquals(id1, id2)) return true; @@ -327,12 +327,12 @@ public unsafe override string ToString() return id1.ToString() == id2.ToString(); } - public static bool operator !=(UniqueId id1, UniqueId id2) + public static bool operator !=(UniqueId? id1, UniqueId? id2) { return !(id1 == id2); } - public override bool Equals(object obj) + public override bool Equals(object? obj) { return this == (obj as UniqueId); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/ValueHandle.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/ValueHandle.cs index 01861ddb75aff7..94a4908b414ca7 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/ValueHandle.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/ValueHandle.cs @@ -5,7 +5,7 @@ using System.Diagnostics; using System.Globalization; using System.Text; - +using System.Diagnostics.CodeAnalysis; namespace System.Xml { @@ -71,7 +71,7 @@ internal class ValueHandle private ValueHandleType _type; private int _offset; private int _length; - private static Base64Encoding s_base64Encoding; + private static Base64Encoding? s_base64Encoding; private static readonly string[] s_constStrings = { "string", "number", @@ -818,7 +818,7 @@ private bool TryReadUnicodeChars(char[] chars, int offset, int count, out int ac return true; } - public bool TryGetDictionaryString(out XmlDictionaryString value) + public bool TryGetDictionaryString([NotNullWhen(true)] out XmlDictionaryString? value) { if (_type == ValueHandleType.Dictionary) { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseReader.cs index b97d8b373f38b6..bc1dceaad4490e 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseReader.cs @@ -13,7 +13,7 @@ using System.Runtime.Serialization; using System.Collections.Generic; using System.Collections.ObjectModel; - +using System.Diagnostics.CodeAnalysis; namespace System.Xml { @@ -27,43 +27,43 @@ internal abstract class XmlBaseReader : XmlDictionaryReader private readonly XmlBufferReader _bufferReader; private XmlNode _node; private readonly NamespaceManager _nsMgr; - private XmlElementNode[] _elementNodes; - private XmlAttributeNode[] _attributeNodes; + private XmlElementNode[]? _elementNodes; + private XmlAttributeNode[]? _attributeNodes; private readonly XmlAtomicTextNode _atomicTextNode; private int _depth; private int _attributeCount; private int _attributeStart; // Starting index for searching private readonly XmlDictionaryReaderQuotas _quotas; - private XmlNameTable _nameTable; - private XmlDeclarationNode _declarationNode; - private XmlComplexTextNode _complexTextNode; - private XmlWhitespaceTextNode _whitespaceTextNode; - private XmlCDataNode _cdataNode; - private XmlCommentNode _commentNode; + private XmlNameTable? _nameTable; + private XmlDeclarationNode? _declarationNode; + private XmlComplexTextNode? _complexTextNode; + private XmlWhitespaceTextNode? _whitespaceTextNode; + private XmlCDataNode? _cdataNode; + private XmlCommentNode? _commentNode; private readonly XmlElementNode _rootElementNode; private int _attributeIndex; // Index for iteration - private char[] _chars; - private string _prefix; - private string _localName; - private string _ns; - private string _value; + private char[]? _chars; + private string? _prefix; + private string? _localName; + private string? _ns; + private string? _value; private int _trailCharCount; private int _trailByteCount; - private char[] _trailChars; - private byte[] _trailBytes; + private char[]? _trailChars; + private byte[]? _trailBytes; private bool _rootElement; private bool _readingElement; - private AttributeSorter _attributeSorter; + private AttributeSorter? _attributeSorter; private static readonly XmlInitialNode s_initialNode = new XmlInitialNode(XmlBufferReader.Empty); private static readonly XmlEndOfFileNode s_endOfFileNode = new XmlEndOfFileNode(XmlBufferReader.Empty); private static readonly XmlClosedNode s_closedNode = new XmlClosedNode(XmlBufferReader.Empty); - private static Base64Encoding s_base64Encoding; - private static BinHexEncoding s_binHexEncoding; + private static Base64Encoding? s_base64Encoding; + private static BinHexEncoding? s_binHexEncoding; private const string xmlns = "xmlns"; private const string xml = "xml"; private const string xmlnsNamespace = "http://www.w3.org/2000/xmlns/"; private const string xmlNamespace = "http://www.w3.org/XML/1998/namespace"; - private XmlSigningNodeWriter _signingWriter; + private XmlSigningNodeWriter? _signingWriter; private bool _signing; protected XmlBaseReader() @@ -184,7 +184,7 @@ protected XmlDeclarationNode MoveToDeclaration() private bool CheckStandalone(int attr) { - XmlAttributeNode node = _attributeNodes[attr]; + XmlAttributeNode node = _attributeNodes![attr]; if (!node.Prefix.IsEmpty) XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.XmlMalformedDecl)); @@ -197,9 +197,9 @@ private bool CheckStandalone(int attr) return true; } - private bool CheckDeclAttribute(int index, string localName, string value, bool checkLower, string valueSR) + private bool CheckDeclAttribute(int index, string localName, string? value, bool checkLower, string valueSR) { - XmlAttributeNode node = _attributeNodes[index]; + XmlAttributeNode node = _attributeNodes![index]; if (!node.Prefix.IsEmpty) XmlExceptionHelper.ThrowXmlException(this, new XmlException(SR.XmlMalformedDecl)); @@ -268,7 +268,7 @@ protected XmlElementNode ElementNode if (_depth == 0) return _rootElementNode; else - return _elementNodes[_depth]; + return _elementNodes![_depth]; } } @@ -276,7 +276,7 @@ protected void MoveToEndElement() { if (_depth == 0) XmlExceptionHelper.ThrowInvalidBinaryFormat(this); - XmlElementNode elementNode = _elementNodes[_depth]; + XmlElementNode elementNode = _elementNodes![_depth]; XmlEndElementNode endElementNode = elementNode.EndElement; endElementNode.Namespace = elementNode.Namespace; MoveToNode(endElementNode); @@ -353,7 +353,7 @@ private XmlAttributeNode AddAttribute(QNameType qnameType, bool isAtomicValue) } attributeNode.QNameType = qnameType; attributeNode.IsAtomicValue = isAtomicValue; - attributeNode.AttributeText.QNameType = qnameType; + attributeNode.AttributeText!.QNameType = qnameType; attributeNode.AttributeText.IsAtomicValue = isAtomicValue; _attributeCount++; return attributeNode; @@ -391,7 +391,7 @@ protected XmlAttributeNode AddXmlnsAttribute(Namespace ns) _nsMgr.Register(ns); XmlAttributeNode attributeNode = AddAttribute(QNameType.Xmlns, false); attributeNode.Namespace = ns; - attributeNode.AttributeText.Namespace = ns; + attributeNode.AttributeText!.Namespace = ns; return attributeNode; } @@ -466,7 +466,7 @@ public override string this[int index] } } - public override string this[string name] + public override string? this[string name] { get { @@ -474,7 +474,7 @@ public override string this[string name] } } - public override string this[string localName, string namespaceUri] + public override string? this[string localName, string? namespaceUri] { get { @@ -539,10 +539,10 @@ private XmlAttributeNode GetAttributeNode(int index) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(index), SR.ValueMustBeNonNegative)); if (index >= _attributeCount) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(index), SR.Format(SR.OffsetExceedsBufferSize, _attributeCount))); - return _attributeNodes[index]; + return _attributeNodes![index]; } - private XmlAttributeNode GetAttributeNode(string name) + private XmlAttributeNode? GetAttributeNode(string name) { if (name == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(name))); @@ -571,7 +571,7 @@ private XmlAttributeNode GetAttributeNode(string name) prefix = name.Substring(0, index); localName = name.Substring(index + 1); } - XmlAttributeNode[] attributeNodes = _attributeNodes; + XmlAttributeNode[]? attributeNodes = _attributeNodes; int attributeCount = _attributeCount; int attributeIndex = _attributeStart; for (int i = 0; i < attributeCount; i++) @@ -580,7 +580,7 @@ private XmlAttributeNode GetAttributeNode(string name) { attributeIndex = 0; } - XmlAttributeNode attributeNode = attributeNodes[attributeIndex]; + XmlAttributeNode attributeNode = attributeNodes![attributeIndex]; if (attributeNode.IsPrefixAndLocalName(prefix, localName)) { _attributeStart = attributeIndex; @@ -590,7 +590,7 @@ private XmlAttributeNode GetAttributeNode(string name) return null; } - private XmlAttributeNode GetAttributeNode(string localName, string namespaceUri) + private XmlAttributeNode? GetAttributeNode(string localName, string? namespaceUri) { if (localName == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(localName))); @@ -598,7 +598,7 @@ private XmlAttributeNode GetAttributeNode(string localName, string namespaceUri) namespaceUri = string.Empty; if (!_node.CanGetAttribute) return null; - XmlAttributeNode[] attributeNodes = _attributeNodes; + XmlAttributeNode[]? attributeNodes = _attributeNodes; int attributeCount = _attributeCount; int attributeIndex = _attributeStart; for (int i = 0; i < attributeCount; i++) @@ -607,7 +607,7 @@ private XmlAttributeNode GetAttributeNode(string localName, string namespaceUri) { attributeIndex = 0; } - XmlAttributeNode attributeNode = attributeNodes[attributeIndex]; + XmlAttributeNode attributeNode = attributeNodes![attributeIndex]; if (attributeNode.IsLocalNameAndNamespaceUri(localName, namespaceUri)) { _attributeStart = attributeIndex; @@ -617,7 +617,7 @@ private XmlAttributeNode GetAttributeNode(string localName, string namespaceUri) return null; } - private XmlAttributeNode GetAttributeNode(XmlDictionaryString localName, XmlDictionaryString namespaceUri) + private XmlAttributeNode? GetAttributeNode(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { if (localName == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(localName))); @@ -625,7 +625,7 @@ private XmlAttributeNode GetAttributeNode(XmlDictionaryString localName, XmlDict namespaceUri = XmlDictionaryString.Empty; if (!_node.CanGetAttribute) return null; - XmlAttributeNode[] attributeNodes = _attributeNodes; + XmlAttributeNode[]? attributeNodes = _attributeNodes; int attributeCount = _attributeCount; int attributeIndex = _attributeStart; for (int i = 0; i < attributeCount; i++) @@ -634,7 +634,7 @@ private XmlAttributeNode GetAttributeNode(XmlDictionaryString localName, XmlDict { attributeIndex = 0; } - XmlAttributeNode attributeNode = attributeNodes[attributeIndex]; + XmlAttributeNode attributeNode = attributeNodes![attributeIndex]; if (attributeNode.IsLocalNameAndNamespaceUri(localName, namespaceUri)) { _attributeStart = attributeIndex; @@ -650,25 +650,25 @@ public override string GetAttribute(int index) return GetAttributeNode(index).ValueAsString; } - public override string GetAttribute(string name) + public override string? GetAttribute(string name) { - XmlAttributeNode attributeNode = GetAttributeNode(name); + XmlAttributeNode? attributeNode = GetAttributeNode(name); if (attributeNode == null) return null; return attributeNode.ValueAsString; } - public override string GetAttribute(string localName, string namespaceUri) + public override string? GetAttribute(string localName, string? namespaceUri) { - XmlAttributeNode attributeNode = GetAttributeNode(localName, namespaceUri); + XmlAttributeNode? attributeNode = GetAttributeNode(localName, namespaceUri); if (attributeNode == null) return null; return attributeNode.ValueAsString; } - public override string GetAttribute(XmlDictionaryString localName, XmlDictionaryString namespaceUri) + public override string? GetAttribute(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { - XmlAttributeNode attributeNode = GetAttributeNode(localName, namespaceUri); + XmlAttributeNode? attributeNode = GetAttributeNode(localName, namespaceUri); if (attributeNode == null) return null; return attributeNode.ValueAsString; @@ -706,9 +706,9 @@ public override string LocalName } } - public override string LookupNamespace(string prefix) + public override string? LookupNamespace(string prefix) { - Namespace ns = _nsMgr.LookupNamespace(prefix); + Namespace? ns = _nsMgr.LookupNamespace(prefix); if (ns != null) return ns.Uri.GetString(NameTable); if (prefix == xmlns) @@ -718,7 +718,7 @@ public override string LookupNamespace(string prefix) protected Namespace LookupNamespace(PrefixHandleType prefix) { - Namespace ns = _nsMgr.LookupNamespace(prefix); + Namespace? ns = _nsMgr.LookupNamespace(prefix); if (ns == null) XmlExceptionHelper.ThrowUndefinedPrefix(this, PrefixHandle.GetString(prefix)); return ns; @@ -726,7 +726,7 @@ protected Namespace LookupNamespace(PrefixHandleType prefix) protected Namespace LookupNamespace(PrefixHandle prefix) { - Namespace ns = _nsMgr.LookupNamespace(prefix); + Namespace? ns = _nsMgr.LookupNamespace(prefix); if (ns == null) XmlExceptionHelper.ThrowUndefinedPrefix(this, prefix.GetString()); return ns; @@ -736,7 +736,7 @@ protected void ProcessAttributes() { if (_attributeCount > 0) { - ProcessAttributes(_attributeNodes, _attributeCount); + ProcessAttributes(_attributeNodes!, _attributeCount); } } @@ -756,7 +756,7 @@ private void ProcessAttributes(XmlAttributeNode[] attributeNodes, int attributeC { attributeNode.Namespace = NamespaceManager.EmptyNamespace; } - attributeNode.AttributeText.Namespace = attributeNode.Namespace; + attributeNode.AttributeText!.Namespace = attributeNode.Namespace; } } @@ -823,16 +823,16 @@ public override void MoveToAttribute(int index) } public override bool MoveToAttribute(string name) { - XmlNode attributeNode = GetAttributeNode(name); + XmlNode? attributeNode = GetAttributeNode(name); if (attributeNode == null) return false; MoveToNode(attributeNode); return true; } - public override bool MoveToAttribute(string localName, string namespaceUri) + public override bool MoveToAttribute(string localName, string? namespaceUri) { - XmlNode attributeNode = GetAttributeNode(localName, namespaceUri); + XmlNode? attributeNode = GetAttributeNode(localName, namespaceUri); if (attributeNode == null) return false; MoveToNode(attributeNode); @@ -846,7 +846,7 @@ public override bool MoveToElement() if (_depth == 0) MoveToDeclaration(); else - MoveToNode(_elementNodes[_depth]); + MoveToNode(_elementNodes![_depth]); _attributeIndex = -1; return true; } @@ -1257,7 +1257,7 @@ public override void ReadEndElement() if (nodeDepth == 0) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlEndElementNoOpenNodes)); // If depth is non-zero, then the document isn't what was expected - XmlElementNode elementNode = _elementNodes[nodeDepth]; + XmlElementNode elementNode = _elementNodes![nodeDepth]; XmlExceptionHelper.ThrowEndElementExpected(this, elementNode.LocalName.GetString(), elementNode.Namespace.Uri.GetString()); } Read(); @@ -1265,7 +1265,7 @@ public override void ReadEndElement() public override bool ReadAttributeValue() { - XmlAttributeTextNode attributeTextNode = _node.AttributeText; + XmlAttributeTextNode? attributeTextNode = _node.AttributeText; if (attributeTextNode == null) return false; MoveToNode(attributeTextNode); @@ -1428,6 +1428,8 @@ private int ReadBytes(Encoding encoding, int byteBlock, int charBlock, byte[] bu // If there are any trailing buffer return them. if (_trailByteCount > 0) { + Debug.Assert(_trailBytes != null); + int actual = Math.Min(_trailByteCount, byteCount); Buffer.BlockCopy(_trailBytes, 0, buffer, offset, actual); _trailByteCount -= actual; @@ -1455,7 +1457,7 @@ private int ReadBytes(Encoding encoding, int byteBlock, int charBlock, byte[] bu // If we didn't align on the boundary, then we might have some remaining characters if (_trailCharCount > 0) { - Array.Copy(_trailChars, 0, chars, charCount, _trailCharCount); + Array.Copy(_trailChars!, 0, chars, charCount, _trailCharCount); charCount += _trailCharCount; _trailCharCount = 0; } @@ -1687,7 +1689,7 @@ public override object ReadContentAsObject() return ReadContentAsString(); } - public override object ReadContentAs(Type type, IXmlNamespaceResolver namespaceResolver) + public override object ReadContentAs(Type type, IXmlNamespaceResolver? namespaceResolver) { if (type == typeof(ulong)) { @@ -1799,17 +1801,17 @@ public override XmlSpace XmlSpace } } - public override bool TryGetLocalNameAsDictionaryString(out XmlDictionaryString localName) + public override bool TryGetLocalNameAsDictionaryString([NotNullWhen(true)] out XmlDictionaryString? localName) { return _node.TryGetLocalNameAsDictionaryString(out localName); } - public override bool TryGetNamespaceUriAsDictionaryString(out XmlDictionaryString localName) + public override bool TryGetNamespaceUriAsDictionaryString([NotNullWhen(true)] out XmlDictionaryString? localName) { return _node.TryGetNamespaceUriAsDictionaryString(out localName); } - public override bool TryGetValueAsDictionaryString(out XmlDictionaryString value) + public override bool TryGetValueAsDictionaryString([NotNullWhen(true)] out XmlDictionaryString? value) { return _node.TryGetValueAsDictionaryString(out value); } @@ -1909,7 +1911,7 @@ public string GetOpenElements() string s = string.Empty; for (int i = _depth; i > 0; i--) { - string localName = _elementNodes[i].LocalName.GetString(); + string localName = _elementNodes![i].LocalName.GetString(); if (i != _depth) s += ", "; s += localName; @@ -1979,7 +1981,7 @@ private void SignNode(XmlSigningNodeWriter writer) case XmlNodeType.Element: SignStartElement(writer); for (int i = 0; i < _attributeCount; i++) - SignAttribute(writer, _attributeNodes[i]); + SignAttribute(writer, _attributeNodes![i]); writer.WriteEndStartElement(_node.IsEmptyElement); break; case XmlNodeType.Text: @@ -2022,11 +2024,11 @@ protected void SignNode() { if (_signing) { - SignNode(_signingWriter); + SignNode(_signingWriter!); } } - public override void StartCanonicalization(Stream stream, bool includeComments, string[] inclusivePrefixes) + public override void StartCanonicalization(Stream stream, bool includeComments, string[]? inclusivePrefixes) { if (_signing) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlCanonicalizationStarted)); @@ -2044,7 +2046,7 @@ public override void EndCanonicalization() if (!_signing) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlCanonicalizationNotStarted)); - _signingWriter.Flush(); + _signingWriter!.Flush(); _signingWriter.Close(); _signing = false; } @@ -2068,7 +2070,7 @@ protected class XmlNode private readonly bool _canGetAttribute; private readonly bool _canMoveToElement; private readonly ReadState _readState; - private readonly XmlAttributeTextNode _attributeTextNode; + private readonly XmlAttributeTextNode? _attributeTextNode; private bool _exitScope; private readonly int _depthDelta; private bool _isAtomicValue; @@ -2095,7 +2097,7 @@ protected XmlNode(XmlNodeType nodeType, ValueHandle value, XmlNodeFlags nodeFlags, ReadState readState, - XmlAttributeTextNode attributeTextNode, + XmlAttributeTextNode? attributeTextNode, int depthDelta) { _nodeType = nodeType; @@ -2132,7 +2134,7 @@ protected XmlNode(XmlNodeType nodeType, public PrefixHandle Prefix { get { DiagnosticUtility.DebugAssert(_qnameType != QNameType.Xmlns, ""); return _prefix; } } public bool CanGetAttribute { get { return _canGetAttribute; } } public bool CanMoveToElement { get { return _canMoveToElement; } } - public XmlAttributeTextNode AttributeText { get { return _attributeTextNode; } } + public XmlAttributeTextNode? AttributeText { get { return _attributeTextNode; } } public bool SkipValue { get { return _skipValue; } } public ValueHandle Value { get { DiagnosticUtility.DebugAssert(_qnameType != QNameType.Xmlns, ""); return _value; } } public int DepthDelta { get { return _depthDelta; } } @@ -2312,7 +2314,7 @@ public bool IsPrefixAndLocalName(string prefix, string localName) } } - public bool TryGetLocalNameAsDictionaryString(out XmlDictionaryString localName) + public bool TryGetLocalNameAsDictionaryString([NotNullWhen(true)] out XmlDictionaryString? localName) { if (_qnameType == QNameType.Normal) { @@ -2326,7 +2328,7 @@ public bool TryGetLocalNameAsDictionaryString(out XmlDictionaryString localName) } } - public bool TryGetNamespaceUriAsDictionaryString(out XmlDictionaryString ns) + public bool TryGetNamespaceUriAsDictionaryString([NotNullWhen(true)] out XmlDictionaryString? ns) { if (_qnameType == QNameType.Normal) { @@ -2340,7 +2342,7 @@ public bool TryGetNamespaceUriAsDictionaryString(out XmlDictionaryString ns) } } - public bool TryGetValueAsDictionaryString(out XmlDictionaryString value) + public bool TryGetValueAsDictionaryString([NotNullWhen(true)] out XmlDictionaryString? value) { if (_qnameType == QNameType.Normal) { @@ -2462,7 +2464,7 @@ protected XmlTextNode(XmlNodeType nodeType, ValueHandle value, XmlNodeFlags nodeFlags, ReadState readState, - XmlAttributeTextNode attributeTextNode, + XmlAttributeTextNode? attributeTextNode, int depthDelta) : base(nodeType, prefix, localName, value, nodeFlags, readState, attributeTextNode, depthDelta) @@ -2621,8 +2623,8 @@ public XmlClosedNode(XmlBufferReader bufferReader) private class AttributeSorter : IComparer { - private object[] _indeces; - private XmlAttributeNode[] _attributeNodes; + private object[]? _indeces; + private XmlAttributeNode[]? _attributeNodes; private int _attributeCount; private int _attributeIndex1; private int _attributeIndex2; @@ -2670,7 +2672,7 @@ private bool Sort() private bool IsSorted() { - for (int i = 0; i < _indeces.Length - 1; i++) + for (int i = 0; i < _indeces!.Length - 1; i++) { if (Compare(_indeces[i], _indeces[i + 1]) >= 0) { @@ -2682,12 +2684,12 @@ private bool IsSorted() return true; } - public int Compare(object obj1, object obj2) + public int Compare(object? obj1, object? obj2) { - int index1 = (int)obj1; - int index2 = (int)obj2; - XmlAttributeNode attribute1 = _attributeNodes[index1]; - XmlAttributeNode attribute2 = _attributeNodes[index2]; + int index1 = (int)obj1!; + int index2 = (int)obj2!; + XmlAttributeNode attribute1 = _attributeNodes![index1]; + XmlAttributeNode attribute2 = _attributeNodes![index2]; int i = CompareQNameType(attribute1.QNameType, attribute2.QNameType); if (i == 0) @@ -2720,13 +2722,13 @@ public int CompareQNameType(QNameType type1, QNameType type2) private class NamespaceManager { private readonly XmlBufferReader _bufferReader; - private Namespace[] _namespaces; + private Namespace[]? _namespaces; private int _nsCount; private int _depth; - private readonly Namespace[] _shortPrefixUri; + private readonly Namespace?[] _shortPrefixUri; private static readonly Namespace s_emptyNamespace = new Namespace(XmlBufferReader.Empty); - private static Namespace s_xmlNamespace; - private XmlAttribute[] _attributes; + private static Namespace? s_xmlNamespace; + private XmlAttribute[]? _attributes; private int _attributeCount; private XmlSpace _space; private string _lang; @@ -2806,12 +2808,9 @@ public void Clear() { if (_nsCount != 0) { - if (_shortPrefixUri != null) + for (int i = 0; i < _shortPrefixUri.Length; i++) { - for (int i = 0; i < _shortPrefixUri.Length; i++) - { - _shortPrefixUri[i] = null; - } + _shortPrefixUri[i] = null; } _shortPrefixUri[(int)PrefixHandleType.Empty] = s_emptyNamespace; _nsCount = 0; @@ -2831,7 +2830,7 @@ public void ExitScope() { while (_nsCount > 0) { - Namespace nameSpace = _namespaces[_nsCount - 1]; + Namespace nameSpace = _namespaces![_nsCount - 1]; if (nameSpace.Depth != _depth) break; PrefixHandleType shortPrefix; @@ -2843,7 +2842,7 @@ public void ExitScope() } while (_attributeCount > 0) { - XmlAttribute attribute = _attributes[_attributeCount - 1]; + XmlAttribute attribute = _attributes![_attributeCount - 1]; if (attribute.Depth != _depth) break; _space = attribute.XmlSpace; @@ -2857,7 +2856,7 @@ public void Sign(XmlSigningNodeWriter writer) { for (int i = 0; i < _nsCount; i++) { - PrefixHandle prefix = _namespaces[i].Prefix; + PrefixHandle prefix = _namespaces![i].Prefix; bool found = false; for (int j = i + 1; j < _nsCount; j++) { @@ -2952,19 +2951,19 @@ public Namespace AddNamespace() return nameSpace; } - public Namespace LookupNamespace(PrefixHandleType prefix) + public Namespace? LookupNamespace(PrefixHandleType prefix) { return _shortPrefixUri[(int)prefix]; } - public Namespace LookupNamespace(PrefixHandle prefix) + public Namespace? LookupNamespace(PrefixHandle prefix) { PrefixHandleType shortPrefix; if (prefix.TryGetShortPrefix(out shortPrefix)) return LookupNamespace(shortPrefix); for (int i = _nsCount - 1; i >= 0; i--) { - Namespace nameSpace = _namespaces[i]; + Namespace nameSpace = _namespaces![i]; if (nameSpace.Prefix == prefix) return nameSpace; } @@ -2972,14 +2971,14 @@ public Namespace LookupNamespace(PrefixHandle prefix) return XmlNamespace; return null; } - public Namespace LookupNamespace(string prefix) + public Namespace? LookupNamespace(string prefix) { PrefixHandleType shortPrefix; if (TryGetShortPrefix(prefix, out shortPrefix)) return LookupNamespace(shortPrefix); for (int i = _nsCount - 1; i >= 0; i--) { - Namespace nameSpace = _namespaces[i]; + Namespace nameSpace = _namespaces![i]; if (nameSpace.Prefix == prefix) return nameSpace; } @@ -3012,7 +3011,7 @@ private bool TryGetShortPrefix(string s, out PrefixHandleType shortPrefix) private class XmlAttribute { private XmlSpace _space; - private string _lang; + private string _lang = string.Empty; private int _depth; public XmlAttribute() @@ -3061,8 +3060,8 @@ protected class Namespace private readonly PrefixHandle _prefix; private readonly StringHandle _uri; private int _depth; - private Namespace _outerUri; - private string _uriString; + private Namespace? _outerUri; + private string? _uriString; public Namespace(XmlBufferReader bufferReader) { @@ -3129,7 +3128,7 @@ public StringHandle Uri } } - public Namespace OuterUri + public Namespace? OuterUri { get { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseWriter.cs index c99f9f89e22604..a16eade973bf44 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBaseWriter.cs @@ -9,29 +9,30 @@ using System.Runtime.Serialization; using System.Collections.Generic; using System.Threading.Tasks; +using System.Diagnostics.CodeAnalysis; namespace System.Xml { internal abstract class XmlBaseWriter : XmlDictionaryWriter { - private XmlNodeWriter _writer; + private XmlNodeWriter _writer = null!; // initialized in SetOutput private readonly NamespaceManager _nsMgr; - private Element[] _elements; + private Element[]? _elements; private int _depth; - private string _attributeLocalName; - private string _attributeValue; + private string? _attributeLocalName; + private string? _attributeValue; private bool _isXmlAttribute; private bool _isXmlnsAttribute; private WriteState _writeState; private DocumentState _documentState; - private byte[] _trailBytes; + private byte[]? _trailBytes; private int _trailByteCount; - private XmlStreamNodeWriter _nodeWriter; - private XmlSigningNodeWriter _signingWriter; + private XmlStreamNodeWriter _nodeWriter = null!; // initialized in SetOutput + private XmlSigningNodeWriter? _signingWriter; private bool _inList; private const string xmlnsNamespace = "http://www.w3.org/2000/xmlns/"; private const string xmlNamespace = "http://www.w3.org/XML/1998/namespace"; - private static BinHexEncoding _binhexEncoding; + private static BinHexEncoding? _binhexEncoding; private static readonly string[] s_prefixes = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" }; protected XmlBaseWriter() @@ -108,6 +109,7 @@ protected bool IsClosed get { return _writeState == WriteState.Closed; } } + [DoesNotReturn] protected void ThrowClosed() { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlWriterClosed)); @@ -123,7 +125,7 @@ private static BinHexEncoding BinHexEncoding } } - public override string XmlLang + public override string? XmlLang { get { @@ -147,7 +149,7 @@ public override WriteState WriteState } } - public override void WriteXmlnsAttribute(string prefix, string ns) + public override void WriteXmlnsAttribute(string? prefix, string ns) { if (IsClosed) ThrowClosed(); @@ -172,7 +174,7 @@ public override void WriteXmlnsAttribute(string prefix, string ns) } } - public override void WriteXmlnsAttribute(string prefix, XmlDictionaryString ns) + public override void WriteXmlnsAttribute(string? prefix, XmlDictionaryString ns) { if (IsClosed) ThrowClosed(); @@ -197,7 +199,7 @@ public override void WriteXmlnsAttribute(string prefix, XmlDictionaryString ns) } } - private void StartAttribute(ref string prefix, string localName, string ns, XmlDictionaryString xNs) + private void StartAttribute([AllowNull] ref string prefix, string localName, string? ns, XmlDictionaryString? xNs) { if (IsClosed) ThrowClosed(); @@ -271,10 +273,10 @@ private void StartAttribute(ref string prefix, string localName, string ns, XmlD else if (prefix.Length == 0) { // No prefix specified - try to find a prefix corresponding to the given namespace - prefix = _nsMgr.LookupAttributePrefix(ns); + string? tempPrefix = _nsMgr.LookupAttributePrefix(ns); // If we didn't find anything with the right namespace, generate one. - if (prefix == null) + if (tempPrefix == null) { // Watch for special values if (ns.Length == xmlnsNamespace.Length && ns == xmlnsNamespace) @@ -282,8 +284,9 @@ private void StartAttribute(ref string prefix, string localName, string ns, XmlD if (ns.Length == xmlNamespace.Length && ns == xmlNamespace) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlSpecificBindingNamespace, "xml", ns))); - prefix = GeneratePrefix(ns, xNs); + tempPrefix = GeneratePrefix(ns, xNs); } + prefix = tempPrefix; } else { @@ -292,7 +295,7 @@ private void StartAttribute(ref string prefix, string localName, string ns, XmlD _writeState = WriteState.Attribute; } - public override void WriteStartAttribute(string prefix, string localName, string namespaceUri) + public override void WriteStartAttribute(string? prefix, string localName, string? namespaceUri) { StartAttribute(ref prefix, localName, namespaceUri, null); if (!_isXmlnsAttribute) @@ -301,12 +304,12 @@ public override void WriteStartAttribute(string prefix, string localName, string } } - public override void WriteStartAttribute(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri) + public override void WriteStartAttribute(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri) { - StartAttribute(ref prefix, (localName != null ? localName.Value : null), (namespaceUri != null ? namespaceUri.Value : null), namespaceUri); + StartAttribute(ref prefix, (localName != null ? localName.Value : null)!, (namespaceUri != null ? namespaceUri.Value : null), namespaceUri); if (!_isXmlnsAttribute) { - _writer.WriteStartAttribute(prefix, localName); + _writer.WriteStartAttribute(prefix, localName!); } } @@ -325,7 +328,7 @@ public override void WriteEndAttribute() { if (_attributeLocalName == "lang") { - _nsMgr.AddLangAttribute(_attributeValue); + _nsMgr.AddLangAttribute(_attributeValue!); } else if (_attributeLocalName == "space") { @@ -353,7 +356,7 @@ public override void WriteEndAttribute() if (_isXmlnsAttribute) { - _nsMgr.AddNamespaceIfNotDeclared(_attributeLocalName, _attributeValue, null); + _nsMgr.AddNamespaceIfNotDeclared(_attributeLocalName!, _attributeValue!, null); _isXmlnsAttribute = false; _attributeLocalName = null; _attributeValue = null; @@ -389,7 +392,7 @@ private async Task WriteEndAttributeAsyncImpl() { if (_attributeLocalName == "lang") { - _nsMgr.AddLangAttribute(_attributeValue); + _nsMgr.AddLangAttribute(_attributeValue!); } else if (_attributeLocalName == "space") { @@ -417,7 +420,7 @@ private async Task WriteEndAttributeAsyncImpl() if (_isXmlnsAttribute) { - _nsMgr.AddNamespaceIfNotDeclared(_attributeLocalName, _attributeValue, null); + _nsMgr.AddNamespaceIfNotDeclared(_attributeLocalName!, _attributeValue!, null); _isXmlnsAttribute = false; _attributeLocalName = null; _attributeValue = null; @@ -433,7 +436,7 @@ private async Task WriteEndAttributeAsyncImpl() } } - public override void WriteComment(string text) + public override void WriteComment(string? text) { if (IsClosed) ThrowClosed(); @@ -471,7 +474,7 @@ public override void WriteFullEndElement() WriteEndElement(); } - public override void WriteCData(string text) + public override void WriteCData(string? text) { if (IsClosed) ThrowClosed(); @@ -491,12 +494,12 @@ public override void WriteCData(string 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) { throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.XmlMethodNotSupported, "WriteDocType"))); } - private void StartElement(ref string prefix, string localName, string ns, XmlDictionaryString xNs) + private void StartElement(ref string? prefix, string localName, string? ns, XmlDictionaryString? xNs) { if (IsClosed) ThrowClosed(); @@ -541,7 +544,7 @@ private void StartElement(ref string prefix, string localName, string ns, XmlDic element.LocalName = localName; } - private void PreStartElementAsyncCheck(string prefix, string localName, string ns, XmlDictionaryString xNs) + private void PreStartElementAsyncCheck(string? prefix, string localName, string? ns, XmlDictionaryString? xNs) { if (IsClosed) ThrowClosed(); @@ -556,13 +559,13 @@ private void PreStartElementAsyncCheck(string prefix, string localName, string n throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlInvalidWriteState, "WriteStartElement", WriteState.ToString()))); } - private async Task StartElementAndWriteStartElementAsync(string prefix, string localName, string namespaceUri) + private async Task StartElementAndWriteStartElementAsync(string? prefix, string localName, string? namespaceUri) { prefix = await StartElementAsync(prefix, localName, namespaceUri, null).ConfigureAwait(false); await _writer.WriteStartElementAsync(prefix, localName).ConfigureAwait(false); } - private async Task StartElementAsync(string prefix, string localName, string ns, XmlDictionaryString xNs) + private async Task StartElementAsync(string? prefix, string localName, string? ns, XmlDictionaryString? xNs) { await FlushBase64Async().ConfigureAwait(false); await AutoCompleteAsync(WriteState.Element).ConfigureAwait(false); @@ -597,21 +600,21 @@ private async Task StartElementAsync(string prefix, string localName, st return prefix; } - public override void WriteStartElement(string prefix, string localName, string namespaceUri) + public override void WriteStartElement(string? prefix, string localName, string? namespaceUri) { StartElement(ref prefix, localName, namespaceUri, null); _writer.WriteStartElement(prefix, localName); } - public override Task WriteStartElementAsync(string prefix, string localName, string namespaceUri) + public override Task WriteStartElementAsync(string? prefix, string localName, string? namespaceUri) { PreStartElementAsyncCheck(prefix, localName, namespaceUri, null); return StartElementAndWriteStartElementAsync(prefix, localName, namespaceUri); } - public override void WriteStartElement(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri) + public override void WriteStartElement(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri) { - StartElement(ref prefix, (localName != null ? localName.Value : null), (namespaceUri != null ? namespaceUri.Value : null), namespaceUri); + StartElement(ref prefix, localName.Value, (namespaceUri != null ? namespaceUri.Value : null), namespaceUri); _writer.WriteStartElement(prefix, localName); } @@ -634,8 +637,8 @@ public override void WriteEndElement() } else { - Element element = _elements[_depth]; - _writer.WriteEndElement(element.Prefix, element.LocalName); + Element element = _elements![_depth]; + _writer.WriteEndElement(element.Prefix, element.LocalName!); } ExitScope(); @@ -666,8 +669,8 @@ private async Task WriteEndElementAsyncImpl() } else { - Element element = _elements[_depth]; - await _writer.WriteEndElementAsync(element.Prefix, element.LocalName).ConfigureAwait(false); + Element element = _elements![_depth]; + await _writer.WriteEndElementAsync(element.Prefix, element.LocalName!).ConfigureAwait(false); } ExitScope(); @@ -699,7 +702,7 @@ private Element EnterScope() private void ExitScope() { - _elements[_depth].Clear(); + _elements![_depth].Clear(); _depth--; if (_depth == 0 && _documentState == DocumentState.Document) _documentState = DocumentState.Epilog; @@ -822,7 +825,7 @@ private Task EndStartElementAsync() return _writer.WriteEndStartElementAsync(false); } - public override string LookupPrefix(string ns) + public override string? LookupPrefix(string ns) { if (ns == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(ns))); @@ -833,9 +836,9 @@ public override string LookupPrefix(string ns) return _nsMgr.LookupPrefix(ns); } - private string GetQualifiedNamePrefix(string namespaceUri, XmlDictionaryString xNs) + private string GetQualifiedNamePrefix(string namespaceUri, XmlDictionaryString? xNs) { - string prefix = _nsMgr.LookupPrefix(namespaceUri); + string? prefix = _nsMgr.LookupPrefix(namespaceUri); if (prefix == null) { if (_writeState != WriteState.Attribute) @@ -846,7 +849,7 @@ private string GetQualifiedNamePrefix(string namespaceUri, XmlDictionaryString x return prefix; } - public override void WriteQualifiedName(string localName, string namespaceUri) + public override void WriteQualifiedName(string localName, string? namespaceUri) { if (IsClosed) ThrowClosed(); @@ -865,7 +868,7 @@ public override void WriteQualifiedName(string localName, string namespaceUri) WriteString(localName); } - public override void WriteQualifiedName(XmlDictionaryString localName, XmlDictionaryString namespaceUri) + public override void WriteQualifiedName(XmlDictionaryString localName, XmlDictionaryString? namespaceUri) { if (IsClosed) ThrowClosed(); @@ -911,7 +914,7 @@ public override void WriteStartDocument(bool standalone) } - public override void WriteProcessingInstruction(string name, string text) + public override void WriteProcessingInstruction(string name, string? text) { if (IsClosed) ThrowClosed(); @@ -972,7 +975,7 @@ public override void WriteNmToken(string name) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.XmlMethodNotSupported, "WriteNmToken"))); } - public override void WriteWhitespace(string whitespace) + public override void WriteWhitespace(string? whitespace) { if (IsClosed) ThrowClosed(); @@ -993,7 +996,7 @@ public override void WriteWhitespace(string whitespace) WriteString(whitespace); } - public override void WriteString(string value) + public override void WriteString(string? value) { if (IsClosed) ThrowClosed(); @@ -1017,7 +1020,7 @@ public override void WriteString(string value) } } - public override void WriteString(XmlDictionaryString value) + public override void WriteString(XmlDictionaryString? value) { if (IsClosed) ThrowClosed(); @@ -1265,7 +1268,7 @@ protected void WritePrimitiveValue(object value) } } - public override void WriteValue(string value) + public override void WriteValue(string? value) { if (IsClosed) ThrowClosed(); @@ -1392,7 +1395,7 @@ public override void WriteValue(double value) } } - public override void WriteValue(XmlDictionaryString value) + public override void WriteValue(XmlDictionaryString? value) { WriteString(value); } @@ -1499,7 +1502,7 @@ public override void WriteBase64(byte[] buffer, int offset, int count) { while (_trailByteCount < 3 && count > 0) { - _trailBytes[_trailByteCount++] = buffer[offset++]; + _trailBytes![_trailByteCount++] = buffer[offset++]; count--; } } @@ -1569,7 +1572,7 @@ private async Task WriteBase64AsyncImpl(byte[] buffer, int offset, int count) { while (_trailByteCount < 3 && count > 0) { - _trailBytes[_trailByteCount++] = buffer[offset++]; + _trailBytes![_trailByteCount++] = buffer[offset++]; count--; } } @@ -1628,7 +1631,7 @@ protected bool Signing } } - public override void StartCanonicalization(Stream stream, bool includeComments, string[] inclusivePrefixes) + public override void StartCanonicalization(Stream stream, bool includeComments, string[]? inclusivePrefixes) { if (IsClosed) ThrowClosed(); @@ -1648,7 +1651,7 @@ public override void EndCanonicalization() ThrowClosed(); if (!Signing) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlCanonicalizationNotStarted)); - _signingWriter.Flush(); + _signingWriter!.Flush(); _writer = _signingWriter.NodeWriter; } @@ -1669,6 +1672,8 @@ private Task FlushBase64Async() private void FlushTrailBytes() { + Debug.Assert(_trailBytes != null); + if (_attributeValue != null) WriteAttributeText(XmlConverter.Base64Encoding.GetString(_trailBytes, 0, _trailByteCount)); @@ -1683,6 +1688,8 @@ private void FlushTrailBytes() private async Task FlushTrailBytesAsync() { + Debug.Assert(_trailBytes != null); + if (_attributeValue != null) WriteAttributeText(XmlConverter.Base64Encoding.GetString(_trailBytes, 0, _trailByteCount)); @@ -1726,7 +1733,7 @@ private void WriteValue(Array array) { _writer.WriteListSeparator(); } - WritePrimitiveValue(array.GetValue(i)); + WritePrimitiveValue(array.GetValue(i)!); // possible bug to log? } _inList = false; _writer.WriteEndListText(); @@ -1749,19 +1756,19 @@ protected void EndArray() { } - private string GeneratePrefix(string ns, XmlDictionaryString xNs) + private string GeneratePrefix(string ns, XmlDictionaryString? xNs) { if (_writeState != WriteState.Element && _writeState != WriteState.Attribute) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.XmlInvalidPrefixState, WriteState.ToString()))); - string prefix = _nsMgr.AddNamespace(ns, xNs); + string? prefix = _nsMgr.AddNamespace(ns, xNs); if (prefix != null) return prefix; while (true) { - int prefixId = _elements[_depth].PrefixId++; + int prefixId = _elements![_depth].PrefixId++; prefix = string.Concat("d", _depth.ToString(CultureInfo.InvariantCulture), "p", prefixId.ToString(CultureInfo.InvariantCulture)); if (_nsMgr.LookupNamespace(prefix) == null) @@ -1779,7 +1786,7 @@ protected void SignScope(XmlCanonicalWriter signingWriter) private void WriteAttributeText(string value) { - if (_attributeValue.Length == 0) + if (_attributeValue!.Length == 0) _attributeValue = value; else _attributeValue += value; @@ -1787,11 +1794,11 @@ private void WriteAttributeText(string value) private class Element { - private string _prefix; - private string _localName; + private string? _prefix; + private string? _localName; private int _prefixId; - public string Prefix + public string? Prefix { get { @@ -1803,7 +1810,7 @@ public string Prefix } } - public string LocalName + public string? LocalName { get { @@ -1845,14 +1852,14 @@ private enum DocumentState : byte private class NamespaceManager { - private Namespace[] _namespaces; - private Namespace _lastNameSpace; + private Namespace[]? _namespaces; + private Namespace? _lastNameSpace; private int _nsCount; private int _depth; - private XmlAttribute[] _attributes; + private XmlAttribute[]? _attributes; private int _attributeCount; private XmlSpace _space; - private string _lang; + private string? _lang; private int _nsTop; private readonly Namespace _defaultNamespace; @@ -1865,7 +1872,7 @@ public NamespaceManager() _defaultNamespace.UriDictionaryString = null; } - public string XmlLang + public string? XmlLang { get { @@ -1919,18 +1926,18 @@ public void DeclareNamespaces(XmlNodeWriter writer) int i = _nsCount; while (i > 0) { - Namespace nameSpace = _namespaces[i - 1]; + Namespace nameSpace = _namespaces![i - 1]; if (nameSpace.Depth != _depth) break; i--; } while (i < _nsCount) { - Namespace nameSpace = _namespaces[i]; + Namespace nameSpace = _namespaces![i]; if (nameSpace.UriDictionaryString != null) writer.WriteXmlnsAttribute(nameSpace.Prefix, nameSpace.UriDictionaryString); else - writer.WriteXmlnsAttribute(nameSpace.Prefix, nameSpace.Uri); + writer.WriteXmlnsAttribute(nameSpace.Prefix, nameSpace.Uri!); i++; } } @@ -1944,7 +1951,7 @@ public void ExitScope() { while (_nsCount > 0) { - Namespace nameSpace = _namespaces[_nsCount - 1]; + Namespace nameSpace = _namespaces![_nsCount - 1]; if (nameSpace.Depth != _depth) break; if (_lastNameSpace == nameSpace) @@ -1954,7 +1961,7 @@ public void ExitScope() } while (_attributeCount > 0) { - XmlAttribute attribute = _attributes[_attributeCount - 1]; + XmlAttribute attribute = _attributes![_attributeCount - 1]; if (attribute.Depth != _depth) break; _space = attribute.XmlSpace; @@ -2001,7 +2008,7 @@ private void AddAttribute() _attributeCount++; } - public string AddNamespace(string uri, XmlDictionaryString uriDictionaryString) + public string? AddNamespace(string uri, XmlDictionaryString? uriDictionaryString) { if (uri.Length == 0) { @@ -2017,7 +2024,7 @@ public string AddNamespace(string uri, XmlDictionaryString uriDictionaryString) bool declared = false; for (int j = _nsCount - 1; j >= _nsTop; j--) { - Namespace nameSpace = _namespaces[j]; + Namespace nameSpace = _namespaces![j]; if (nameSpace.Prefix == prefix) { declared = true; @@ -2034,7 +2041,7 @@ public string AddNamespace(string uri, XmlDictionaryString uriDictionaryString) return null; } - public void AddNamespaceIfNotDeclared(string prefix, string uri, XmlDictionaryString uriDictionaryString) + public void AddNamespaceIfNotDeclared(string prefix, string uri, XmlDictionaryString? uriDictionaryString) { if (LookupNamespace(prefix) != uri) { @@ -2042,7 +2049,7 @@ public void AddNamespaceIfNotDeclared(string prefix, string uri, XmlDictionarySt } } - public void AddNamespace(string prefix, string uri, XmlDictionaryString uriDictionaryString) + public void AddNamespace(string prefix, string uri, XmlDictionaryString? uriDictionaryString) { if (prefix.Length >= 3) { @@ -2059,7 +2066,7 @@ public void AddNamespace(string prefix, string uri, XmlDictionaryString uriDicti Namespace nameSpace; for (int i = _nsCount - 1; i >= 0; i--) { - nameSpace = _namespaces[i]; + nameSpace = _namespaces![i]; if (nameSpace.Depth != _depth) break; if (nameSpace.Prefix == prefix) @@ -2077,7 +2084,7 @@ public void AddNamespace(string prefix, string uri, XmlDictionaryString uriDicti if (uri.Length == xmlNamespace.Length && uri[18] == 'X' && uri == xmlNamespace) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentException(SR.Format(SR.XmlSpecificBindingNamespace, "xml", uri))); - if (_namespaces.Length == _nsCount) + if (_namespaces!.Length == _nsCount) { Namespace[] newNamespaces = new Namespace[_nsCount * 2]; Array.Copy(_namespaces, newNamespaces, _nsCount); @@ -2097,17 +2104,17 @@ public void AddNamespace(string prefix, string uri, XmlDictionaryString uriDicti _lastNameSpace = null; } - public string LookupPrefix(string ns) + public string? LookupPrefix(string ns) { if (_lastNameSpace != null && _lastNameSpace.Uri == ns) return _lastNameSpace.Prefix; int nsCount = _nsCount; for (int i = nsCount - 1; i >= _nsTop; i--) { - Namespace nameSpace = _namespaces[i]; + Namespace nameSpace = _namespaces![i]; if (object.ReferenceEquals(nameSpace.Uri, ns)) { - string prefix = nameSpace.Prefix; + string? prefix = nameSpace.Prefix; // Make sure that the prefix refers to the namespace in scope bool declared = false; for (int j = i + 1; j < nsCount; j++) @@ -2127,10 +2134,10 @@ public string LookupPrefix(string ns) } for (int i = nsCount - 1; i >= _nsTop; i--) { - Namespace nameSpace = _namespaces[i]; + Namespace nameSpace = _namespaces![i]; if (nameSpace.Uri == ns) { - string prefix = nameSpace.Prefix; + string? prefix = nameSpace.Prefix; // Make sure that the prefix refers to the namespace in scope bool declared = false; for (int j = i + 1; j < nsCount; j++) @@ -2155,7 +2162,7 @@ public string LookupPrefix(string ns) bool emptyPrefixUnassigned = true; for (int i = nsCount - 1; i >= _nsTop; i--) { - if (_namespaces[i].Prefix.Length == 0) + if (_namespaces![i].Prefix!.Length == 0) { emptyPrefixUnassigned = false; break; @@ -2172,19 +2179,19 @@ public string LookupPrefix(string ns) return null; } - public string LookupAttributePrefix(string ns) + public string? LookupAttributePrefix(string ns) { - if (_lastNameSpace != null && _lastNameSpace.Uri == ns && _lastNameSpace.Prefix.Length != 0) + if (_lastNameSpace != null && _lastNameSpace.Uri == ns && _lastNameSpace.Prefix!.Length != 0) return _lastNameSpace.Prefix; int nsCount = _nsCount; for (int i = nsCount - 1; i >= _nsTop; i--) { - Namespace nameSpace = _namespaces[i]; + Namespace nameSpace = _namespaces![i]; if (object.ReferenceEquals(nameSpace.Uri, ns)) { - string prefix = nameSpace.Prefix; + string prefix = nameSpace.Prefix!; if (prefix.Length != 0) { // Make sure that the prefix refers to the namespace in scope @@ -2207,10 +2214,10 @@ public string LookupAttributePrefix(string ns) } for (int i = nsCount - 1; i >= _nsTop; i--) { - Namespace nameSpace = _namespaces[i]; + Namespace nameSpace = _namespaces![i]; if (nameSpace.Uri == ns) { - string prefix = nameSpace.Prefix; + string prefix = nameSpace.Prefix!; if (prefix.Length != 0) { // Make sure that the prefix refers to the namespace in scope @@ -2236,15 +2243,15 @@ public string LookupAttributePrefix(string ns) return null; } - public string LookupNamespace(string prefix) + public string? LookupNamespace(string prefix) { int nsCount = _nsCount; if (prefix.Length == 0) { for (int i = nsCount - 1; i >= _nsTop; i--) { - Namespace nameSpace = _namespaces[i]; - if (nameSpace.Prefix.Length == 0) + Namespace nameSpace = _namespaces![i]; + if (nameSpace.Prefix!.Length == 0) return nameSpace.Uri; } return string.Empty; @@ -2254,7 +2261,7 @@ public string LookupNamespace(string prefix) char prefixChar = prefix[0]; for (int i = nsCount - 1; i >= _nsTop; i--) { - Namespace nameSpace = _namespaces[i]; + Namespace nameSpace = _namespaces![i]; if (nameSpace.PrefixChar == prefixChar) return nameSpace.Uri; } @@ -2262,7 +2269,7 @@ public string LookupNamespace(string prefix) } for (int i = nsCount - 1; i >= _nsTop; i--) { - Namespace nameSpace = _namespaces[i]; + Namespace nameSpace = _namespaces![i]; if (nameSpace.Prefix == prefix) return nameSpace.Uri; } @@ -2276,7 +2283,7 @@ public string LookupNamespace(string prefix) public void Sign(XmlCanonicalWriter signingWriter) { int nsCount = _nsCount; - Fx.Assert(nsCount >= 1 && _namespaces[0].Prefix.Length == 0 && _namespaces[0].Uri.Length == 0, ""); + Fx.Assert(nsCount >= 1 && _namespaces![0].Prefix!.Length == 0 && _namespaces[0].Uri!.Length == 0, ""); for (int i = 1; i < nsCount; i++) { Namespace nameSpace = _namespaces[i]; @@ -2289,7 +2296,7 @@ public void Sign(XmlCanonicalWriter signingWriter) if (!found) { - signingWriter.WriteXmlnsAttribute(nameSpace.Prefix, nameSpace.Uri); + signingWriter.WriteXmlnsAttribute(nameSpace.Prefix!, nameSpace.Uri!); } } } @@ -2297,7 +2304,7 @@ public void Sign(XmlCanonicalWriter signingWriter) private class XmlAttribute { private XmlSpace _space; - private string _lang; + private string? _lang; private int _depth; public XmlAttribute() @@ -2316,7 +2323,7 @@ public int Depth } } - public string XmlLang + public string? XmlLang { get { @@ -2348,9 +2355,9 @@ public void Clear() private class Namespace { - private string _prefix; - private string _ns; - private XmlDictionaryString _xNs; + private string? _prefix; + private string? _ns; + private XmlDictionaryString? _xNs; private int _depth; private char _prefixChar; @@ -2387,7 +2394,8 @@ public char PrefixChar } } - public string Prefix + [DisallowNull] + public string? Prefix { get { @@ -2403,7 +2411,7 @@ public string Prefix } } - public string Uri + public string? Uri { get { @@ -2415,7 +2423,7 @@ public string Uri } } - public XmlDictionaryString UriDictionaryString + public XmlDictionaryString? UriDictionaryString { get { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryReader.cs index cf177b4d546956..7f7e0e38ab3e72 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryReader.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.IO; using System.Runtime.Serialization; @@ -9,15 +10,15 @@ namespace System.Xml public interface IXmlBinaryReaderInitializer { void SetInput(byte[] buffer, int offset, int count, - IXmlDictionary dictionary, + IXmlDictionary? dictionary, XmlDictionaryReaderQuotas quotas, - XmlBinaryReaderSession session, - OnXmlDictionaryReaderClose onClose); + XmlBinaryReaderSession? session, + OnXmlDictionaryReaderClose? onClose); void SetInput(Stream stream, - IXmlDictionary dictionary, + IXmlDictionary? dictionary, XmlDictionaryReaderQuotas quotas, - XmlBinaryReaderSession session, - OnXmlDictionaryReaderClose onClose); + XmlBinaryReaderSession? session, + OnXmlDictionaryReaderClose? onClose); } internal class XmlBinaryReader : XmlBaseReader, IXmlBinaryReaderInitializer @@ -34,10 +35,10 @@ public XmlBinaryReader() } public void SetInput(byte[] buffer, int offset, int count, - IXmlDictionary dictionary, + IXmlDictionary? dictionary, XmlDictionaryReaderQuotas quotas, - XmlBinaryReaderSession session, - OnXmlDictionaryReaderClose onClose) + XmlBinaryReaderSession? session, + OnXmlDictionaryReaderClose? onClose) { if (buffer == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(buffer)); @@ -55,10 +56,10 @@ public void SetInput(byte[] buffer, int offset, int count, } public void SetInput(Stream stream, - IXmlDictionary dictionary, + IXmlDictionary? dictionary, XmlDictionaryReaderQuotas quotas, - XmlBinaryReaderSession session, - OnXmlDictionaryReaderClose onClose) + XmlBinaryReaderSession? session, + OnXmlDictionaryReaderClose? onClose) { if (stream == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(stream)); @@ -67,7 +68,7 @@ public void SetInput(Stream stream, _buffered = false; } - private void MoveToInitial(XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession session, OnXmlDictionaryReaderClose onClose) + private void MoveToInitial(XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession? session, OnXmlDictionaryReaderClose? onClose) { MoveToInitial(quotas); _maxBytesPerRead = quotas.MaxBytesPerRead; @@ -726,14 +727,14 @@ private void ReadAttributes2() attributeNode = AddAttribute(); attributeNode.Prefix.SetValue(PrefixHandleType.Empty); ReadName(attributeNode.LocalName); - ReadAttributeText(attributeNode.AttributeText); + ReadAttributeText(attributeNode.AttributeText!); break; case XmlBinaryNodeType.Attribute: SkipNodeType(); attributeNode = AddAttribute(); ReadName(attributeNode.Prefix); ReadName(attributeNode.LocalName); - ReadAttributeText(attributeNode.AttributeText); + ReadAttributeText(attributeNode.AttributeText!); FixXmlAttribute(attributeNode); break; case XmlBinaryNodeType.ShortDictionaryAttribute: @@ -741,14 +742,14 @@ private void ReadAttributes2() attributeNode = AddAttribute(); attributeNode.Prefix.SetValue(PrefixHandleType.Empty); ReadDictionaryName(attributeNode.LocalName); - ReadAttributeText(attributeNode.AttributeText); + ReadAttributeText(attributeNode.AttributeText!); break; case XmlBinaryNodeType.DictionaryAttribute: SkipNodeType(); attributeNode = AddAttribute(); ReadName(attributeNode.Prefix); ReadDictionaryName(attributeNode.LocalName); - ReadAttributeText(attributeNode.AttributeText); + ReadAttributeText(attributeNode.AttributeText!); break; case XmlBinaryNodeType.XmlnsAttribute: SkipNodeType(); @@ -809,7 +810,7 @@ private void ReadAttributes2() prefix = PrefixHandle.GetAlphaPrefix((int)nodeType - (int)XmlBinaryNodeType.PrefixDictionaryAttributeA); attributeNode.Prefix.SetValue(prefix); ReadDictionaryName(attributeNode.LocalName); - ReadAttributeText(attributeNode.AttributeText); + ReadAttributeText(attributeNode.AttributeText!); break; case XmlBinaryNodeType.PrefixAttributeA: case XmlBinaryNodeType.PrefixAttributeB: @@ -842,7 +843,7 @@ private void ReadAttributes2() prefix = PrefixHandle.GetAlphaPrefix((int)nodeType - (int)XmlBinaryNodeType.PrefixAttributeA); attributeNode.Prefix.SetValue(prefix); ReadName(attributeNode.LocalName); - ReadAttributeText(attributeNode.AttributeText); + ReadAttributeText(attributeNode.AttributeText!); break; default: ProcessAttributes(); @@ -1146,7 +1147,7 @@ private void SkipArrayElements(int count) } } - public override bool IsStartArray(out Type type) + public override bool IsStartArray([NotNullWhen(true)] out Type? type) { type = null; if (_arrayState != ArrayState.Element) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryReaderSession.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryReaderSession.cs index 1d8fddf7ae5c6c..db7c46cd4c5a96 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryReaderSession.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryReaderSession.cs @@ -5,6 +5,7 @@ using System.Xml; using System.Collections.Generic; using System.Runtime.Serialization; +using System.Diagnostics.CodeAnalysis; namespace System.Xml { @@ -12,8 +13,8 @@ public class XmlBinaryReaderSession : IXmlDictionary { private const int MaxArrayEntries = 2048; - private XmlDictionaryString[] _strings; - private Dictionary _stringDict; + private XmlDictionaryString[]? _strings; + private Dictionary? _stringDict; public XmlBinaryReaderSession() { @@ -25,7 +26,7 @@ public XmlDictionaryString Add(int id, string value) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(id), SR.XmlInvalidID)); if (value == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(value)); - XmlDictionaryString xmlString; + XmlDictionaryString? xmlString; if (TryLookup(id, out xmlString)) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.XmlIDDefined)); @@ -54,7 +55,7 @@ public XmlDictionaryString Add(int id, string value) return xmlString; } - public bool TryLookup(int key, out XmlDictionaryString result) + public bool TryLookup(int key, [NotNullWhen(true)] out XmlDictionaryString? result) { if (_strings != null && key >= 0 && key < _strings.Length) { @@ -70,7 +71,7 @@ public bool TryLookup(int key, out XmlDictionaryString result) return false; } - public bool TryLookup(string value, out XmlDictionaryString result) + public bool TryLookup(string value, [NotNullWhen(true)] out XmlDictionaryString? result) { if (value == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(value)); @@ -104,7 +105,7 @@ public bool TryLookup(string value, out XmlDictionaryString result) return false; } - public bool TryLookup(XmlDictionaryString value, out XmlDictionaryString result) + public bool TryLookup(XmlDictionaryString value, [NotNullWhen(true)] out XmlDictionaryString? result) { if (value == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(value))); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriter.cs index 845d948bb8dca5..c353ce30366a87 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriter.cs @@ -17,13 +17,13 @@ namespace System.Xml { public interface IXmlBinaryWriterInitializer { - void SetOutput(Stream stream, IXmlDictionary dictionary, XmlBinaryWriterSession session, bool ownsStream); + void SetOutput(Stream stream, IXmlDictionary? dictionary, XmlBinaryWriterSession? session, bool ownsStream); } internal class XmlBinaryNodeWriter : XmlStreamNodeWriter { - private IXmlDictionary _dictionary; - private XmlBinaryWriterSession _session; + private IXmlDictionary? _dictionary; + private XmlBinaryWriterSession? _session; private bool _inAttribute; private bool _inList; private bool _wroteAttributeValue; @@ -39,7 +39,7 @@ public XmlBinaryNodeWriter() (int)XmlBinaryNodeType.MaxText < 256, "NodeTypes enumeration messed up"); } - public void SetOutput(Stream stream, IXmlDictionary dictionary, XmlBinaryWriterSession session, bool ownsStream) + public void SetOutput(Stream stream, IXmlDictionary? dictionary, XmlBinaryWriterSession? session, bool ownsStream) { _dictionary = dictionary; _session = session; @@ -141,9 +141,9 @@ public override void WriteDeclaration() { } - public override void WriteStartElement(string prefix, string localName) + public override void WriteStartElement(string? prefix, string localName) { - if (prefix.Length == 0) + if (string.IsNullOrEmpty(prefix)) { WriteNode(XmlBinaryNodeType.ShortElement); WriteName(localName); @@ -171,7 +171,7 @@ private void WritePrefixNode(XmlBinaryNodeType nodeType, int ch) WriteNode((XmlBinaryNodeType)((int)nodeType + ch)); } - public override void WriteStartElement(string prefix, XmlDictionaryString localName) + public override void WriteStartElement(string? prefix, XmlDictionaryString localName) { int key; if (!TryGetKey(localName, out key)) @@ -180,7 +180,7 @@ public override void WriteStartElement(string prefix, XmlDictionaryString localN } else { - if (prefix.Length == 0) + if (string.IsNullOrEmpty(prefix)) { WriteNode(XmlBinaryNodeType.ShortDictionaryElement); WriteDictionaryString(localName, key); @@ -212,7 +212,7 @@ public override void WriteEndStartElement(bool isEmpty) } } - public override void WriteEndElement(string prefix, string localName) + public override void WriteEndElement(string? prefix, string localName) { WriteEndElement(); } @@ -303,9 +303,9 @@ public override void WriteEndAttribute() _textNodeOffset = -1; } - public override void WriteXmlnsAttribute(string prefix, string ns) + public override void WriteXmlnsAttribute(string? prefix, string ns) { - if (prefix.Length == 0) + if (string.IsNullOrEmpty(prefix)) { WriteNode(XmlBinaryNodeType.ShortXmlnsAttribute); WriteName(ns); @@ -318,7 +318,7 @@ public override void WriteXmlnsAttribute(string prefix, string ns) } } - public override void WriteXmlnsAttribute(string prefix, XmlDictionaryString ns) + public override void WriteXmlnsAttribute(string? prefix, XmlDictionaryString ns) { int key; if (!TryGetKey(ns, out key)) @@ -327,7 +327,7 @@ public override void WriteXmlnsAttribute(string prefix, XmlDictionaryString ns) } else { - if (prefix.Length == 0) + if (string.IsNullOrEmpty(prefix)) { WriteNode(XmlBinaryNodeType.ShortDictionaryXmlnsAttribute); WriteDictionaryString(ns, key); @@ -349,7 +349,7 @@ private bool TryGetKey(XmlDictionaryString s, out int key) key = s.Key * 2; return true; } - XmlDictionaryString t; + XmlDictionaryString? t; if (_dictionary != null && _dictionary.TryLookup(s, out t)) { DiagnosticUtility.DebugAssert(t.Dictionary == _dictionary, ""); @@ -549,7 +549,7 @@ private void WriteInt64(long value) Advance(8); } - public override void WriteBase64Text(byte[] trailBytes, int trailByteCount, byte[] base64Buffer, int base64Offset, int base64Count) + public override void WriteBase64Text(byte[]? trailBytes, int trailByteCount, byte[] base64Buffer, int base64Offset, int base64Count) { if (_inAttribute) { @@ -566,7 +566,7 @@ public override void WriteBase64Text(byte[] trailBytes, int trailByteCount, byte int offset; byte[] buffer = GetBuffer(trailByteCount, out offset); for (int i = 0; i < trailByteCount; i++) - buffer[offset + i] = trailBytes[i]; + buffer[offset + i] = trailBytes![i]; Advance(trailByteCount); } if (base64Count > 0) @@ -968,9 +968,9 @@ public override void Close() private struct AttributeValue { - private string _captureText; - private XmlDictionaryString _captureXText; - private MemoryStream _captureStream; + private string? _captureText; + private XmlDictionaryString? _captureXText; + private MemoryStream? _captureStream; public void Clear() { @@ -986,7 +986,7 @@ public void WriteText(string s) ArraySegment arraySegment; bool result = _captureStream.TryGetBuffer(out arraySegment); DiagnosticUtility.DebugAssert(result, ""); - _captureText = XmlConverter.Base64Encoding.GetString(arraySegment.Array, arraySegment.Offset, arraySegment.Count); + _captureText = XmlConverter.Base64Encoding.GetString(arraySegment.Array!, arraySegment.Offset, arraySegment.Count); _captureStream = null; } @@ -1018,13 +1018,13 @@ public void WriteText(XmlDictionaryString s) } } - public void WriteBase64Text(byte[] trailBytes, int trailByteCount, byte[] buffer, int offset, int count) + public void WriteBase64Text(byte[]? trailBytes, int trailByteCount, byte[] buffer, int offset, int count) { if (_captureText != null || _captureXText != null) { if (trailByteCount > 0) { - WriteText(XmlConverter.Base64Encoding.GetString(trailBytes, 0, trailByteCount)); + WriteText(XmlConverter.Base64Encoding.GetString(trailBytes!, 0, trailByteCount)); } WriteText(XmlConverter.Base64Encoding.GetString(buffer, offset, count)); } @@ -1034,7 +1034,7 @@ public void WriteBase64Text(byte[] trailBytes, int trailByteCount, byte[] buffer _captureStream = new MemoryStream(); if (trailByteCount > 0) - _captureStream.Write(trailBytes, 0, trailByteCount); + _captureStream.Write(trailBytes!, 0, trailByteCount); _captureStream.Write(buffer, offset, count); } @@ -1057,7 +1057,7 @@ public void WriteTo(XmlBinaryNodeWriter writer) ArraySegment arraySegment; bool result = _captureStream.TryGetBuffer(out arraySegment); DiagnosticUtility.DebugAssert(result, ""); - writer.WriteBase64Text(null, 0, arraySegment.Array, arraySegment.Offset, arraySegment.Count); + writer.WriteBase64Text(null, 0, arraySegment.Array!, arraySegment.Offset, arraySegment.Count); _captureStream = null; } else @@ -1070,12 +1070,12 @@ public void WriteTo(XmlBinaryNodeWriter writer) internal class XmlBinaryWriter : XmlBaseWriter, IXmlBinaryWriterInitializer { - private XmlBinaryNodeWriter _writer; - private char[] _chars; - private byte[] _bytes; + private XmlBinaryNodeWriter _writer = null!; // initialized in SetOutput + private char[]? _chars; + private byte[]? _bytes; - public void SetOutput(Stream stream, IXmlDictionary dictionary, XmlBinaryWriterSession session, bool ownsStream) + public void SetOutput(Stream stream, IXmlDictionary? dictionary, XmlBinaryWriterSession? session, bool ownsStream) { if (stream == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(stream))); @@ -1095,7 +1095,7 @@ protected override void WriteTextNode(XmlDictionaryReader reader, bool attribute Type type = reader.ValueType; if (type == typeof(string)) { - XmlDictionaryString value; + XmlDictionaryString? value; if (reader.TryGetValueAsDictionaryString(out value)) { WriteString(value); @@ -1172,7 +1172,7 @@ protected override void WriteTextNode(XmlDictionaryReader reader, bool attribute WriteValue(reader.ReadContentAsObject()); } - private void WriteStartArray(string prefix, string localName, string namespaceUri, int count) + private void WriteStartArray(string? prefix, string localName, string? namespaceUri, int count) { StartArray(count); _writer.WriteArrayNode(); @@ -1180,7 +1180,7 @@ private void WriteStartArray(string prefix, string localName, string namespaceUr WriteEndElement(); } - private void WriteStartArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, int count) + private void WriteStartArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, int count) { StartArray(count); _writer.WriteArrayNode(); @@ -1193,7 +1193,7 @@ private void WriteEndArray() EndArray(); } - private unsafe void UnsafeWriteArray(string prefix, string localName, string namespaceUri, + private unsafe void UnsafeWriteArray(string? prefix, string localName, string? namespaceUri, XmlBinaryNodeType nodeType, int count, byte* array, byte* arrayMax) { WriteStartArray(prefix, localName, namespaceUri, count); @@ -1201,7 +1201,7 @@ private unsafe void UnsafeWriteArray(string prefix, string localName, string nam WriteEndArray(); } - private unsafe void UnsafeWriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, + private unsafe void UnsafeWriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, XmlBinaryNodeType nodeType, int count, byte* array, byte* arrayMax) { WriteStartArray(prefix, localName, namespaceUri, count); @@ -1223,7 +1223,7 @@ private void CheckArray(Array array, int offset, int count) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, array.Length - offset))); } - public unsafe override void WriteArray(string prefix, string localName, string namespaceUri, bool[] array, int offset, int count) + public unsafe override void WriteArray(string? prefix, string localName, string? namespaceUri, bool[] array, int offset, int count) { { CheckArray(array, offset, count); @@ -1237,7 +1237,7 @@ public unsafe override void WriteArray(string prefix, string localName, string n } } - public unsafe override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, bool[] array, int offset, int count) + public unsafe override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, bool[] array, int offset, int count) { { CheckArray(array, offset, count); @@ -1251,7 +1251,7 @@ public unsafe override void WriteArray(string prefix, XmlDictionaryString localN } } - public unsafe override void WriteArray(string prefix, string localName, string namespaceUri, short[] array, int offset, int count) + public unsafe override void WriteArray(string? prefix, string localName, string? namespaceUri, short[] array, int offset, int count) { { CheckArray(array, offset, count); @@ -1265,7 +1265,7 @@ public unsafe override void WriteArray(string prefix, string localName, string n } } - public unsafe override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, short[] array, int offset, int count) + public unsafe override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, short[] array, int offset, int count) { { CheckArray(array, offset, count); @@ -1279,7 +1279,7 @@ public unsafe override void WriteArray(string prefix, XmlDictionaryString localN } } - public unsafe override void WriteArray(string prefix, string localName, string namespaceUri, int[] array, int offset, int count) + public unsafe override void WriteArray(string? prefix, string localName, string? namespaceUri, int[] array, int offset, int count) { { CheckArray(array, offset, count); @@ -1293,7 +1293,7 @@ public unsafe override void WriteArray(string prefix, string localName, string n } } - public unsafe override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, int[] array, int offset, int count) + public unsafe override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, int[] array, int offset, int count) { { CheckArray(array, offset, count); @@ -1307,7 +1307,7 @@ public unsafe override void WriteArray(string prefix, XmlDictionaryString localN } } - public unsafe override void WriteArray(string prefix, string localName, string namespaceUri, long[] array, int offset, int count) + public unsafe override void WriteArray(string? prefix, string localName, string? namespaceUri, long[] array, int offset, int count) { { CheckArray(array, offset, count); @@ -1321,7 +1321,7 @@ public unsafe override void WriteArray(string prefix, string localName, string n } } - public unsafe override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, long[] array, int offset, int count) + public unsafe override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, long[] array, int offset, int count) { { CheckArray(array, offset, count); @@ -1335,7 +1335,7 @@ public unsafe override void WriteArray(string prefix, XmlDictionaryString localN } } - public unsafe override void WriteArray(string prefix, string localName, string namespaceUri, float[] array, int offset, int count) + public unsafe override void WriteArray(string? prefix, string localName, string? namespaceUri, float[] array, int offset, int count) { { CheckArray(array, offset, count); @@ -1349,7 +1349,7 @@ public unsafe override void WriteArray(string prefix, string localName, string n } } - public unsafe override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, float[] array, int offset, int count) + public unsafe override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, float[] array, int offset, int count) { { CheckArray(array, offset, count); @@ -1363,7 +1363,7 @@ public unsafe override void WriteArray(string prefix, XmlDictionaryString localN } } - public unsafe override void WriteArray(string prefix, string localName, string namespaceUri, double[] array, int offset, int count) + public unsafe override void WriteArray(string? prefix, string localName, string? namespaceUri, double[] array, int offset, int count) { { CheckArray(array, offset, count); @@ -1377,7 +1377,7 @@ public unsafe override void WriteArray(string prefix, string localName, string n } } - public unsafe override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, double[] array, int offset, int count) + public unsafe override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, double[] array, int offset, int count) { { CheckArray(array, offset, count); @@ -1391,7 +1391,7 @@ public unsafe override void WriteArray(string prefix, XmlDictionaryString localN } } - public unsafe override void WriteArray(string prefix, string localName, string namespaceUri, decimal[] array, int offset, int count) + public unsafe override void WriteArray(string? prefix, string localName, string? namespaceUri, decimal[] array, int offset, int count) { { CheckArray(array, offset, count); @@ -1405,7 +1405,7 @@ public unsafe override void WriteArray(string prefix, string localName, string n } } - public unsafe override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, decimal[] array, int offset, int count) + public unsafe override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, decimal[] array, int offset, int count) { { CheckArray(array, offset, count); @@ -1420,7 +1420,7 @@ public unsafe override void WriteArray(string prefix, XmlDictionaryString localN } // DateTime - public override void WriteArray(string prefix, string localName, string namespaceUri, DateTime[] array, int offset, int count) + public override void WriteArray(string? prefix, string localName, string? namespaceUri, DateTime[] array, int offset, int count) { { CheckArray(array, offset, count); @@ -1433,7 +1433,7 @@ public override void WriteArray(string prefix, string localName, string namespac } } - public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, DateTime[] array, int offset, int count) + public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, DateTime[] array, int offset, int count) { { CheckArray(array, offset, count); @@ -1447,7 +1447,7 @@ public override void WriteArray(string prefix, XmlDictionaryString localName, Xm } // Guid - public override void WriteArray(string prefix, string localName, string namespaceUri, Guid[] array, int offset, int count) + public override void WriteArray(string? prefix, string localName, string? namespaceUri, Guid[] array, int offset, int count) { { CheckArray(array, offset, count); @@ -1460,7 +1460,7 @@ public override void WriteArray(string prefix, string localName, string namespac } } - public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, Guid[] array, int offset, int count) + public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, Guid[] array, int offset, int count) { { CheckArray(array, offset, count); @@ -1474,7 +1474,7 @@ public override void WriteArray(string prefix, XmlDictionaryString localName, Xm } // TimeSpan - public override void WriteArray(string prefix, string localName, string namespaceUri, TimeSpan[] array, int offset, int count) + public override void WriteArray(string? prefix, string localName, string? namespaceUri, TimeSpan[] array, int offset, int count) { { CheckArray(array, offset, count); @@ -1487,7 +1487,7 @@ public override void WriteArray(string prefix, string localName, string namespac } } - public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, TimeSpan[] array, int offset, int count) + public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, TimeSpan[] array, int offset, int count) { { CheckArray(array, offset, count); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriterSession.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriterSession.cs index 2bed1f3f06ed1a..1f2078d5bd79e0 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriterSession.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBinaryWriterSession.cs @@ -8,7 +8,7 @@ using System.Runtime.Serialization; using System.Collections.Generic; using System.Collections.ObjectModel; - +using System.Diagnostics.CodeAnalysis; namespace System.Xml { @@ -27,7 +27,7 @@ public XmlBinaryWriterSession() public virtual bool TryAdd(XmlDictionaryString value, out int key) { - IntArray keys; + IntArray? keys; if (value == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(value)); @@ -75,7 +75,7 @@ public void Reset() internal bool TryLookup(XmlDictionaryString s, out int key) { - IntArray keys; + IntArray? keys; if (_maps.TryGetValue(s.Dictionary, out keys)) { key = (keys[s.Key] - 1); @@ -103,7 +103,7 @@ internal bool TryLookup(XmlDictionaryString s, out int key) private class PriorityDictionary where K : class { - private Dictionary _dictionary; + private Dictionary? _dictionary; private readonly Entry[] _list; private int _listCount; private int _now; @@ -122,7 +122,7 @@ public void Clear() _dictionary.Clear(); } - public bool TryGetValue(K key, out V value) + public bool TryGetValue(K key, [MaybeNullWhen(false)] out V value) { for (int i = 0; i < _listCount; i++) { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBufferReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBufferReader.cs index f8357c878503a2..20956f5a1c56d6 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBufferReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlBufferReader.cs @@ -18,20 +18,20 @@ namespace System.Xml internal class XmlBufferReader { private readonly XmlDictionaryReader _reader; - private Stream _stream; - private byte[] _streamBuffer; - private byte[] _buffer; + private Stream? _stream; + private byte[]? _streamBuffer; + private byte[] _buffer = null!; // initialized by SetBuffer private int _offsetMin; private int _offsetMax; - private IXmlDictionary _dictionary; - private XmlBinaryReaderSession _session; - private byte[] _guid; + private IXmlDictionary? _dictionary; + private XmlBinaryReaderSession? _session; + private byte[]? _guid; private int _offset; private const int maxBytesPerChar = 3; - private char[] _chars; + private char[]? _chars; private int _windowOffset; private int _windowOffsetMax; - private ValueHandle _listValue; + private ValueHandle? _listValue; private static readonly XmlBufferReader s_empty = new XmlBufferReader(Array.Empty()); public XmlBufferReader(XmlDictionaryReader reader) @@ -41,7 +41,7 @@ public XmlBufferReader(XmlDictionaryReader reader) public XmlBufferReader(byte[] buffer) { - _reader = null; + _reader = null!; // this ctor is only used in 2 places internally, which will never touch _reader _buffer = buffer; } @@ -70,7 +70,7 @@ public bool IsStreamed } - public void SetBuffer(Stream stream, IXmlDictionary dictionary, XmlBinaryReaderSession session) + public void SetBuffer(Stream stream, IXmlDictionary? dictionary, XmlBinaryReaderSession? session) { if (_streamBuffer == null) { @@ -81,12 +81,12 @@ public void SetBuffer(Stream stream, IXmlDictionary dictionary, XmlBinaryReaderS _windowOffsetMax = _streamBuffer.Length; } - public void SetBuffer(byte[] buffer, int offset, int count, IXmlDictionary dictionary, XmlBinaryReaderSession session) + public void SetBuffer(byte[] buffer, int offset, int count, IXmlDictionary? dictionary, XmlBinaryReaderSession? session) { SetBuffer(null, buffer, offset, count, dictionary, session); } - private void SetBuffer(Stream stream, byte[] buffer, int offset, int count, IXmlDictionary dictionary, XmlBinaryReaderSession session) + private void SetBuffer(Stream? stream, byte[] buffer, int offset, int count, IXmlDictionary? dictionary, XmlBinaryReaderSession? session) { _stream = stream; _buffer = buffer; @@ -1114,8 +1114,8 @@ public object[] GetList(int offset, int count) XmlBinaryNodeType nodeType = GetNodeType(); SkipNodeType(); DiagnosticUtility.DebugAssert(nodeType != XmlBinaryNodeType.StartListText, ""); - ReadValue(nodeType, _listValue); - objects[i] = _listValue.ToObject(); + ReadValue(nodeType, _listValue!); + objects[i] = _listValue!.ToObject(); } return objects; } @@ -1131,13 +1131,13 @@ public XmlDictionaryString GetDictionaryString(int key) IXmlDictionary keyDictionary; if ((key & 1) != 0) { - keyDictionary = _session; + keyDictionary = _session!; } else { - keyDictionary = _dictionary; + keyDictionary = _dictionary!; } - XmlDictionaryString s; + XmlDictionaryString? s; if (!keyDictionary.TryLookup(key >> 1, out s)) XmlExceptionHelper.ThrowInvalidBinaryFormat(_reader); return s; @@ -1151,7 +1151,7 @@ public int ReadDictionaryKey() if (_session == null) XmlExceptionHelper.ThrowInvalidBinaryFormat(_reader); int sessionKey = (key >> 1); - XmlDictionaryString xmlString; + XmlDictionaryString? xmlString; if (!_session.TryLookup(sessionKey, out xmlString)) { if (sessionKey < XmlDictionaryString.MinKey || sessionKey > XmlDictionaryString.MaxKey) @@ -1164,7 +1164,7 @@ public int ReadDictionaryKey() if (_dictionary == null) XmlExceptionHelper.ThrowInvalidBinaryFormat(_reader); int staticKey = (key >> 1); - XmlDictionaryString xmlString; + XmlDictionaryString? xmlString; if (!_dictionary.TryLookup(staticKey, out xmlString)) { if (staticKey < XmlDictionaryString.MinKey || staticKey > XmlDictionaryString.MaxKey) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlCanonicalWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlCanonicalWriter.cs index e7167b756f5656..2bfed4ea108096 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlCanonicalWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlCanonicalWriter.cs @@ -2,6 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Collections; +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime; using System.Runtime.Serialization; @@ -12,25 +14,25 @@ namespace System.Xml { internal sealed class XmlCanonicalWriter { - private XmlUTF8NodeWriter _writer; - private MemoryStream _elementStream; - private byte[] _elementBuffer; - private XmlUTF8NodeWriter _elementWriter; + private XmlUTF8NodeWriter _writer = null!; // initialized in SetOutput + private MemoryStream _elementStream = null!; // initialized in SetOutput + private byte[]? _elementBuffer; + private XmlUTF8NodeWriter _elementWriter = null!; // initialized in SetOutput private bool _inStartElement; private int _depth; - private Scope[] _scopes; + private Scope[]? _scopes; private int _xmlnsAttributeCount; - private XmlnsAttribute[] _xmlnsAttributes; + private XmlnsAttribute[]? _xmlnsAttributes; private int _attributeCount; - private Attribute[] _attributes; + private Attribute[]? _attributes; private Attribute _attribute; private Element _element; - private byte[] _xmlnsBuffer; + private byte[]? _xmlnsBuffer; private int _xmlnsOffset; private const int maxBytesPerChar = 3; private int _xmlnsStartOffset; private bool _includeComments; - private string[] _inclusivePrefixes; + private string[]? _inclusivePrefixes; private const string xmlnsNamespace = "http://www.w3.org/2000/xmlns/"; private static readonly bool[] s_isEscapedAttributeChar = new bool[] @@ -52,7 +54,7 @@ public XmlCanonicalWriter() { } - public void SetOutput(Stream stream, bool includeComments, string[] inclusivePrefixes) + public void SetOutput(Stream stream, bool includeComments, string[]? inclusivePrefixes) { if (stream == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(stream)); @@ -124,7 +126,7 @@ public void Close() if (_elementWriter != null) _elementWriter.Close(); if (_elementStream != null && _elementStream.Length > 512) - _elementStream = null; + _elementStream = null!; _elementBuffer = null; if (_scopes != null && _scopes.Length > 16) _scopes = null; @@ -153,7 +155,7 @@ public void WriteComment(string value) } } - + [MemberNotNull(nameof(_scopes))] private void StartElement() { if (_scopes == null) @@ -177,7 +179,7 @@ private void StartElement() private void EndElement() { _depth--; - _xmlnsAttributeCount = _scopes[_depth].xmlnsAttributeCount; + _xmlnsAttributeCount = _scopes![_depth].xmlnsAttributeCount; _xmlnsOffset = _scopes[_depth].xmlnsOffset; } @@ -204,7 +206,7 @@ public void WriteStartElement(string prefix, string localName) // Scan through all the namespace declarations in the outer scope. for (int i = 0; i < _scopes[0].xmlnsAttributeCount; ++i) { - if (IsInclusivePrefix(ref _xmlnsAttributes[i])) + if (IsInclusivePrefix(ref _xmlnsAttributes![i])) { XmlnsAttribute attribute = _xmlnsAttributes[i]; AddXmlnsAttribute(ref attribute); @@ -253,7 +255,7 @@ public void WriteStartElement(byte[] prefixBuffer, int prefixOffset, int prefixL // Scan through all the namespace declarations in the outer scope. for (int i = 0; i < _scopes[0].xmlnsAttributeCount; ++i) { - if (IsInclusivePrefix(ref _xmlnsAttributes[i])) + if (IsInclusivePrefix(ref _xmlnsAttributes![i])) { XmlnsAttribute attribute = _xmlnsAttributes[i]; AddXmlnsAttribute(ref attribute); @@ -264,11 +266,11 @@ public void WriteStartElement(byte[] prefixBuffer, int prefixOffset, int prefixL private bool IsInclusivePrefix(ref XmlnsAttribute xmlnsAttribute) { - for (int i = 0; i < _inclusivePrefixes.Length; ++i) + for (int i = 0; i < _inclusivePrefixes!.Length; ++i) { if (_inclusivePrefixes[i].Length == xmlnsAttribute.prefixLength) { - if (string.Compare(Encoding.UTF8.GetString(_xmlnsBuffer, xmlnsAttribute.prefixOffset, xmlnsAttribute.prefixLength), _inclusivePrefixes[i], StringComparison.Ordinal) == 0) + if (string.Compare(Encoding.UTF8.GetString(_xmlnsBuffer!, xmlnsAttribute.prefixOffset, xmlnsAttribute.prefixLength), _inclusivePrefixes[i], StringComparison.Ordinal) == 0) { return true; } @@ -286,14 +288,15 @@ public void WriteEndStartElement(bool isEmpty) _inStartElement = false; ResolvePrefixes(); _writer.WriteStartElement(_elementBuffer, _element.prefixOffset, _element.prefixLength, _elementBuffer, _element.localNameOffset, _element.localNameLength); - for (int i = _scopes[_depth - 1].xmlnsAttributeCount; i < _xmlnsAttributeCount; i++) + for (int i = _scopes![_depth - 1].xmlnsAttributeCount; i < _xmlnsAttributeCount; i++) { // Check if this prefix with the same namespace has already been rendered. int j = i - 1; bool alreadyReferred = false; while (j >= 0) { - if (Equals(_xmlnsBuffer, _xmlnsAttributes[i].prefixOffset, _xmlnsAttributes[i].prefixLength, _xmlnsBuffer, _xmlnsAttributes[j].prefixOffset, _xmlnsAttributes[j].prefixLength)) + Debug.Assert(_xmlnsBuffer != null); + if (Equals(_xmlnsBuffer, _xmlnsAttributes![i].prefixOffset, _xmlnsAttributes[i].prefixLength, _xmlnsBuffer, _xmlnsAttributes[j].prefixOffset, _xmlnsAttributes[j].prefixLength)) { // Check if the namespace is also equal. if (Equals(_xmlnsBuffer, _xmlnsAttributes[i].nsOffset, _xmlnsAttributes[i].nsLength, _xmlnsBuffer, _xmlnsAttributes[j].nsOffset, _xmlnsAttributes[j].nsLength)) @@ -320,7 +323,7 @@ public void WriteEndStartElement(bool isEmpty) if (!alreadyReferred) { - WriteXmlnsAttribute(ref _xmlnsAttributes[i]); + WriteXmlnsAttribute(ref _xmlnsAttributes![i]); } } if (_attributeCount > 0) @@ -332,7 +335,7 @@ public void WriteEndStartElement(bool isEmpty) for (int i = 0; i < _attributeCount; i++) { - _writer.WriteText(_elementBuffer, _attributes[i].offset, _attributes[i].length); + _writer.WriteText(_elementBuffer, _attributes![i].offset, _attributes[i].length); } } _writer.WriteEndStartElement(false); @@ -355,6 +358,7 @@ public void WriteEndElement(string prefix, string localName) EndElement(); } + [MemberNotNull(nameof(_xmlnsBuffer))] private void EnsureXmlnsBuffer(int byteCount) { if (_xmlnsBuffer == null) @@ -369,6 +373,7 @@ private void EnsureXmlnsBuffer(int byteCount) } } + [MemberNotNull(nameof(_xmlnsAttributes))] public void WriteXmlnsAttribute(string prefix, string ns) { if (prefix == null) @@ -393,6 +398,7 @@ public void WriteXmlnsAttribute(string prefix, string ns) AddXmlnsAttribute(ref xmlnsAttribute); } + [MemberNotNull(nameof(_xmlnsAttributes))] public void WriteXmlnsAttribute(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] nsBuffer, int nsOffset, int nsLength) { if (prefixBuffer == null) @@ -693,6 +699,7 @@ private void WriteXmlnsAttribute(ref XmlnsAttribute xmlnsAttribute) { if (xmlnsAttribute.referred) { + Debug.Assert(_xmlnsBuffer != null); _writer.WriteXmlnsAttribute(_xmlnsBuffer, xmlnsAttribute.prefixOffset, xmlnsAttribute.prefixLength, _xmlnsBuffer, xmlnsAttribute.nsOffset, xmlnsAttribute.nsLength); } } @@ -706,7 +713,7 @@ private void SortAttributes() int attributeMin = i; for (int j = i + 1; j < _attributeCount; j++) { - if (Compare(ref _attributes[j], ref _attributes[attributeMin]) < 0) + if (Compare(ref _attributes![j], ref _attributes[attributeMin]) < 0) { attributeMin = j; } @@ -714,7 +721,7 @@ private void SortAttributes() if (attributeMin != i) { - Attribute temp = _attributes[i]; + Attribute temp = _attributes![i]; _attributes[i] = _attributes[attributeMin]; _attributes[attributeMin] = temp; } @@ -743,6 +750,7 @@ private void AddAttribute(ref Attribute attribute) _attributeCount++; } + [MemberNotNull(nameof(_xmlnsAttributes))] private void AddXmlnsAttribute(ref XmlnsAttribute xmlnsAttribute) { // Console.WriteLine("{0}={1}", Encoding.UTF8.GetString(xmlnsBuffer, xmlnsAttribute.prefixOffset, xmlnsAttribute.prefixLength), @@ -778,7 +786,7 @@ private void AddXmlnsAttribute(ref XmlnsAttribute xmlnsAttribute) else { // Sort the xmlns xmlnsAttribute - int xmlnsAttributeIndex = _scopes[_depth - 1].xmlnsAttributeCount; + int xmlnsAttributeIndex = _scopes![_depth - 1].xmlnsAttributeCount; bool isNewPrefix = true; while (xmlnsAttributeIndex < _xmlnsAttributeCount) { @@ -812,13 +820,13 @@ private void AddXmlnsAttribute(ref XmlnsAttribute xmlnsAttribute) private void ResolvePrefix(int prefixOffset, int prefixLength, out int nsOffset, out int nsLength) { - int xmlnsAttributeMin = _scopes[_depth - 1].xmlnsAttributeCount; + int xmlnsAttributeMin = _scopes![_depth - 1].xmlnsAttributeCount; // Lookup the attribute; it has to be there. The decls are in sorted order // so we could do a binary search. int j = _xmlnsAttributeCount - 1; - while (!Equals(_elementBuffer, prefixOffset, prefixLength, - _xmlnsBuffer, _xmlnsAttributes[j].prefixOffset, _xmlnsAttributes[j].prefixLength)) + while (!Equals(_elementBuffer!, prefixOffset, prefixLength, + _xmlnsBuffer!, _xmlnsAttributes![j].prefixOffset, _xmlnsAttributes[j].prefixLength)) { j--; } @@ -866,26 +874,26 @@ private void ResolvePrefixes() for (int i = 0; i < _attributeCount; i++) { - ResolvePrefix(ref _attributes[i]); + ResolvePrefix(ref _attributes![i]); } } private int Compare(ref XmlnsAttribute xmlnsAttribute1, ref XmlnsAttribute xmlnsAttribute2) { - return Compare(_xmlnsBuffer, + return Compare(_xmlnsBuffer!, xmlnsAttribute1.prefixOffset, xmlnsAttribute1.prefixLength, xmlnsAttribute2.prefixOffset, xmlnsAttribute2.prefixLength); } private int Compare(ref Attribute attribute1, ref Attribute attribute2) { - int s = Compare(_xmlnsBuffer, + int s = Compare(_xmlnsBuffer!, attribute1.nsOffset, attribute1.nsLength, attribute2.nsOffset, attribute2.nsLength); if (s == 0) { - s = Compare(_elementBuffer, + s = Compare(_elementBuffer!, attribute1.localNameOffset, attribute1.localNameLength, attribute2.localNameOffset, attribute2.localNameLength); } @@ -961,7 +969,7 @@ public void Sort() Array.Sort(indeces, this); - Attribute[] attributes = new Attribute[_writer._attributes.Length]; + Attribute[] attributes = new Attribute[_writer._attributes!.Length]; for (int i = 0; i < indeces.Length; i++) { attributes[i] = _writer._attributes[(int)indeces[i]]; @@ -970,11 +978,11 @@ public void Sort() _writer._attributes = attributes; } - public int Compare(object obj1, object obj2) + public int Compare(object? obj1, object? obj2) { - int attributeIndex1 = (int)obj1; - int attributeIndex2 = (int)obj2; - return _writer.Compare(ref _writer._attributes[attributeIndex1], ref _writer._attributes[attributeIndex2]); + int attributeIndex1 = (int)obj1!; + int attributeIndex2 = (int)obj2!; + return _writer.Compare(ref _writer._attributes![attributeIndex1], ref _writer._attributes[attributeIndex2]); } } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlConverter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlConverter.cs index 8badd6190e7e08..f58260cb559a80 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlConverter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlConverter.cs @@ -30,10 +30,10 @@ internal static class XmlConverter public const int MaxUInt64Chars = 32; public const int MaxPrimitiveChars = MaxDateTimeChars; - private static UTF8Encoding s_utf8Encoding; - private static UnicodeEncoding s_unicodeEncoding; + private static UTF8Encoding? s_utf8Encoding; + private static UnicodeEncoding? s_unicodeEncoding; - private static Base64Encoding s_base64Encoding; + private static Base64Encoding? s_base64Encoding; public static Base64Encoding Base64Encoding { @@ -456,7 +456,7 @@ private static string ToString(object value) else if (value is bool) return ToString((bool)value); else - return value.ToString(); + return value.ToString()!; // value can only be an object created by ToList() } public static string ToString(object[] objects) diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionary.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionary.cs index bd2326bfbab7cc..49d54b8691fcaa 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionary.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionary.cs @@ -9,15 +9,15 @@ using System.Diagnostics; using System.Text; using System.Runtime.Serialization; - +using System.Diagnostics.CodeAnalysis; namespace System.Xml { public class XmlDictionary : IXmlDictionary { - private static IXmlDictionary s_empty; + private static IXmlDictionary? s_empty; private readonly Dictionary _lookup; - private XmlDictionaryString[] _strings; + private XmlDictionaryString[]? _strings; private int _nextId; public static IXmlDictionary Empty @@ -46,7 +46,7 @@ public XmlDictionary(int capacity) public virtual XmlDictionaryString Add(string value) { - XmlDictionaryString str; + XmlDictionaryString? str; if (!_lookup.TryGetValue(value, out str)) { if (_strings == null) @@ -68,23 +68,23 @@ public virtual XmlDictionaryString Add(string value) return str; } - public virtual bool TryLookup(string value, out XmlDictionaryString result) + public virtual bool TryLookup(string value, [NotNullWhen(true)] out XmlDictionaryString? result) { return _lookup.TryGetValue(value, out result); } - public virtual bool TryLookup(int key, out XmlDictionaryString result) + public virtual bool TryLookup(int key, [NotNullWhen(true)] out XmlDictionaryString? result) { if (key < 0 || key >= _nextId) { result = null; return false; } - result = _strings[key]; + result = _strings![key]; return true; } - public virtual bool TryLookup(XmlDictionaryString value, out XmlDictionaryString result) + public virtual bool TryLookup(XmlDictionaryString value, [NotNullWhen(true)] out XmlDictionaryString? result) { if (value == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(value))); @@ -99,19 +99,19 @@ public virtual bool TryLookup(XmlDictionaryString value, out XmlDictionaryString private class EmptyDictionary : IXmlDictionary { - public bool TryLookup(string value, out XmlDictionaryString result) + public bool TryLookup(string value, [NotNullWhen(true)] out XmlDictionaryString? result) { result = null; return false; } - public bool TryLookup(int key, out XmlDictionaryString result) + public bool TryLookup(int key, [NotNullWhen(true)] out XmlDictionaryString? result) { result = null; return false; } - public bool TryLookup(XmlDictionaryString value, out XmlDictionaryString result) + public bool TryLookup(XmlDictionaryString value, [NotNullWhen(true)] out XmlDictionaryString? result) { result = null; return false; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryAsyncCheckWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryAsyncCheckWriter.cs index e2d186dff2eb3a..bf8e1bc8eb6836 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryAsyncCheckWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryAsyncCheckWriter.cs @@ -14,7 +14,7 @@ namespace System.Xml internal class XmlDictionaryAsyncCheckWriter : XmlDictionaryWriter { private readonly XmlDictionaryWriter _coreWriter; - private Task _lastTask; + private Task? _lastTask; public XmlDictionaryAsyncCheckWriter(XmlDictionaryWriter writer) { @@ -44,7 +44,7 @@ private Task SetLastTask(Task task) return task; } - public override XmlWriterSettings Settings + public override XmlWriterSettings? Settings { get { @@ -62,7 +62,7 @@ public override WriteState WriteState } } - public override string XmlLang + public override string? XmlLang { get { @@ -92,7 +92,7 @@ public override Task FlushAsync() return SetLastTask(CoreWriter.FlushAsync()); } - public override string LookupPrefix(string ns) + public override string? LookupPrefix(string ns) { CheckAsync(); return CoreWriter.LookupPrefix(ns); @@ -134,13 +134,13 @@ public override Task WriteBinHexAsync(byte[] buffer, int index, int count) return SetLastTask(CoreWriter.WriteBinHexAsync(buffer, index, count)); } - public override void WriteCData(string text) + public override void WriteCData(string? text) { CheckAsync(); CoreWriter.WriteCData(text); } - public override Task WriteCDataAsync(string text) + public override Task WriteCDataAsync(string? text) { CheckAsync(); return SetLastTask(CoreWriter.WriteCDataAsync(text)); @@ -170,25 +170,25 @@ public override Task WriteCharsAsync(char[] buffer, int index, int count) return SetLastTask(CoreWriter.WriteCharsAsync(buffer, index, count)); } - public override void WriteComment(string text) + public override void WriteComment(string? text) { CheckAsync(); CoreWriter.WriteComment(text); } - public override Task WriteCommentAsync(string text) + public override Task WriteCommentAsync(string? text) { CheckAsync(); return SetLastTask(CoreWriter.WriteCommentAsync(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) { CheckAsync(); CoreWriter.WriteDocType(name, pubid, sysid, subset); } - public override Task WriteDocTypeAsync(string name, string pubid, string sysid, string subset) + public override Task WriteDocTypeAsync(string name, string? pubid, string? sysid, string? subset) { CheckAsync(); return SetLastTask(CoreWriter.WriteDocTypeAsync(name, pubid, sysid, subset)); @@ -284,25 +284,25 @@ public override Task WriteNodeAsync(XmlReader reader, bool defattr) return SetLastTask(CoreWriter.WriteNodeAsync(reader, defattr)); } - public override void WriteProcessingInstruction(string name, string text) + public override void WriteProcessingInstruction(string name, string? text) { CheckAsync(); CoreWriter.WriteProcessingInstruction(name, text); } - public override Task WriteProcessingInstructionAsync(string name, string text) + public override Task WriteProcessingInstructionAsync(string name, string? text) { CheckAsync(); return SetLastTask(CoreWriter.WriteProcessingInstructionAsync(name, text)); } - public override void WriteQualifiedName(string localName, string ns) + public override void WriteQualifiedName(string localName, string? ns) { CheckAsync(); CoreWriter.WriteQualifiedName(localName, ns); } - public override Task WriteQualifiedNameAsync(string localName, string ns) + public override Task WriteQualifiedNameAsync(string localName, string? ns) { CheckAsync(); return SetLastTask(CoreWriter.WriteQualifiedNameAsync(localName, ns)); @@ -332,7 +332,7 @@ public override Task WriteRawAsync(char[] buffer, int index, int count) return SetLastTask(CoreWriter.WriteRawAsync(buffer, index, count)); } - public override void WriteStartAttribute(string prefix, string localName, string ns) + public override void WriteStartAttribute(string? prefix, string localName, string? ns) { CheckAsync(); CoreWriter.WriteStartAttribute(prefix, localName, ns); @@ -362,25 +362,25 @@ public override Task WriteStartDocumentAsync(bool standalone) return SetLastTask(CoreWriter.WriteStartDocumentAsync(standalone)); } - public override void WriteStartElement(string prefix, string localName, string ns) + public override void WriteStartElement(string? prefix, string localName, string? ns) { CheckAsync(); CoreWriter.WriteStartElement(prefix, localName, ns); } - public override Task WriteStartElementAsync(string prefix, string localName, string ns) + public override Task WriteStartElementAsync(string? prefix, string localName, string? ns) { CheckAsync(); return SetLastTask(CoreWriter.WriteStartElementAsync(prefix, localName, ns)); } - public override void WriteString(string text) + public override void WriteString(string? text) { CheckAsync(); CoreWriter.WriteString(text); } - public override Task WriteStringAsync(string text) + public override Task WriteStringAsync(string? text) { CheckAsync(); return SetLastTask(CoreWriter.WriteStringAsync(text)); @@ -398,7 +398,7 @@ public override Task WriteSurrogateCharEntityAsync(char lowChar, char highChar) return SetLastTask(CoreWriter.WriteSurrogateCharEntityAsync(lowChar, highChar)); } - public override void WriteValue(string value) + public override void WriteValue(string? value) { CheckAsync(); CoreWriter.WriteValue(value); @@ -452,67 +452,67 @@ public override void WriteValue(bool value) CoreWriter.WriteValue(value); } - public override void WriteWhitespace(string ws) + public override void WriteWhitespace(string? ws) { CheckAsync(); CoreWriter.WriteWhitespace(ws); } - public override Task WriteWhitespaceAsync(string ws) + public override Task WriteWhitespaceAsync(string? ws) { CheckAsync(); return SetLastTask(CoreWriter.WriteWhitespaceAsync(ws)); } - public override void WriteStartElement(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri) + public override void WriteStartElement(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri) { CheckAsync(); CoreWriter.WriteStartElement(prefix, localName, namespaceUri); } - public override void WriteStartAttribute(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri) + public override void WriteStartAttribute(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri) { CheckAsync(); CoreWriter.WriteStartAttribute(prefix, localName, namespaceUri); } - public override void WriteXmlnsAttribute(string prefix, string namespaceUri) + public override void WriteXmlnsAttribute(string? prefix, string namespaceUri) { CheckAsync(); CoreWriter.WriteXmlnsAttribute(prefix, namespaceUri); } - public override void WriteXmlnsAttribute(string prefix, XmlDictionaryString namespaceUri) + public override void WriteXmlnsAttribute(string? prefix, XmlDictionaryString namespaceUri) { CheckAsync(); CoreWriter.WriteXmlnsAttribute(prefix, namespaceUri); } - public override void WriteXmlAttribute(string localName, string value) + public override void WriteXmlAttribute(string localName, string? value) { CheckAsync(); CoreWriter.WriteXmlAttribute(localName, value); } - public override void WriteXmlAttribute(XmlDictionaryString localName, XmlDictionaryString value) + public override void WriteXmlAttribute(XmlDictionaryString localName, XmlDictionaryString? value) { CheckAsync(); CoreWriter.WriteXmlAttribute(localName, value); } - public override void WriteString(XmlDictionaryString value) + public override void WriteString(XmlDictionaryString? value) { CheckAsync(); CoreWriter.WriteString(value); } - public override void WriteQualifiedName(XmlDictionaryString localName, XmlDictionaryString namespaceUri) + public override void WriteQualifiedName(XmlDictionaryString localName, XmlDictionaryString? namespaceUri) { CheckAsync(); CoreWriter.WriteQualifiedName(localName, namespaceUri); } - public override void WriteValue(XmlDictionaryString value) + public override void WriteValue(XmlDictionaryString? value) { CheckAsync(); CoreWriter.WriteValue(value); @@ -545,7 +545,7 @@ public override bool CanCanonicalize } } - public override void StartCanonicalization(Stream stream, bool includeComments, string[] inclusivePrefixes) + public override void StartCanonicalization(Stream stream, bool includeComments, string[]? inclusivePrefixes) { CheckAsync(); CoreWriter.StartCanonicalization(stream, includeComments, inclusivePrefixes); @@ -563,121 +563,121 @@ public override void WriteNode(XmlDictionaryReader reader, bool defattr) CoreWriter.WriteNode(reader, defattr); } - public override void WriteArray(string prefix, string localName, string namespaceUri, bool[] array, int offset, int count) + public override void WriteArray(string? prefix, string localName, string? namespaceUri, bool[] array, int offset, int count) { CheckAsync(); CoreWriter.WriteArray(prefix, localName, namespaceUri, array, offset, count); } - public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, bool[] array, int offset, int count) + public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, bool[] array, int offset, int count) { CheckAsync(); CoreWriter.WriteArray(prefix, localName, namespaceUri, array, offset, count); } - public override void WriteArray(string prefix, string localName, string namespaceUri, short[] array, int offset, int count) + public override void WriteArray(string? prefix, string localName, string? namespaceUri, short[] array, int offset, int count) { CheckAsync(); CoreWriter.WriteArray(prefix, localName, namespaceUri, array, offset, count); } - public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, short[] array, int offset, int count) + public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, short[] array, int offset, int count) { CheckAsync(); CoreWriter.WriteArray(prefix, localName, namespaceUri, array, offset, count); } - public override void WriteArray(string prefix, string localName, string namespaceUri, int[] array, int offset, int count) + public override void WriteArray(string? prefix, string localName, string? namespaceUri, int[] array, int offset, int count) { CheckAsync(); CoreWriter.WriteArray(prefix, localName, namespaceUri, array, offset, count); } - public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, int[] array, int offset, int count) + public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, int[] array, int offset, int count) { CheckAsync(); CoreWriter.WriteArray(prefix, localName, namespaceUri, array, offset, count); } - public override void WriteArray(string prefix, string localName, string namespaceUri, long[] array, int offset, int count) + public override void WriteArray(string? prefix, string localName, string? namespaceUri, long[] array, int offset, int count) { CheckAsync(); CoreWriter.WriteArray(prefix, localName, namespaceUri, array, offset, count); } - public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, long[] array, int offset, int count) + public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, long[] array, int offset, int count) { CheckAsync(); CoreWriter.WriteArray(prefix, localName, namespaceUri, array, offset, count); } - public override void WriteArray(string prefix, string localName, string namespaceUri, float[] array, int offset, int count) + public override void WriteArray(string? prefix, string localName, string? namespaceUri, float[] array, int offset, int count) { CheckAsync(); CoreWriter.WriteArray(prefix, localName, namespaceUri, array, offset, count); } - public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, float[] array, int offset, int count) + public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, float[] array, int offset, int count) { CheckAsync(); CoreWriter.WriteArray(prefix, localName, namespaceUri, array, offset, count); } - public override void WriteArray(string prefix, string localName, string namespaceUri, double[] array, int offset, int count) + public override void WriteArray(string? prefix, string localName, string? namespaceUri, double[] array, int offset, int count) { CheckAsync(); CoreWriter.WriteArray(prefix, localName, namespaceUri, array, offset, count); } - public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, double[] array, int offset, int count) + public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, double[] array, int offset, int count) { CheckAsync(); CoreWriter.WriteArray(prefix, localName, namespaceUri, array, offset, count); } - public override void WriteArray(string prefix, string localName, string namespaceUri, decimal[] array, int offset, int count) + public override void WriteArray(string? prefix, string localName, string? namespaceUri, decimal[] array, int offset, int count) { CheckAsync(); CoreWriter.WriteArray(prefix, localName, namespaceUri, array, offset, count); } - public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, decimal[] array, int offset, int count) + public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, decimal[] array, int offset, int count) { CheckAsync(); CoreWriter.WriteArray(prefix, localName, namespaceUri, array, offset, count); } - public override void WriteArray(string prefix, string localName, string namespaceUri, DateTime[] array, int offset, int count) + public override void WriteArray(string? prefix, string localName, string? namespaceUri, DateTime[] array, int offset, int count) { CheckAsync(); CoreWriter.WriteArray(prefix, localName, namespaceUri, array, offset, count); } - public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, DateTime[] array, int offset, int count) + public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, DateTime[] array, int offset, int count) { CheckAsync(); CoreWriter.WriteArray(prefix, localName, namespaceUri, array, offset, count); } - public override void WriteArray(string prefix, string localName, string namespaceUri, Guid[] array, int offset, int count) + public override void WriteArray(string? prefix, string localName, string? namespaceUri, Guid[] array, int offset, int count) { CheckAsync(); CoreWriter.WriteArray(prefix, localName, namespaceUri, array, offset, count); } - public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, Guid[] array, int offset, int count) + public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, Guid[] array, int offset, int count) { CheckAsync(); CoreWriter.WriteArray(prefix, localName, namespaceUri, array, offset, count); } - public override void WriteArray(string prefix, string localName, string namespaceUri, TimeSpan[] array, int offset, int count) + public override void WriteArray(string? prefix, string localName, string? namespaceUri, TimeSpan[] array, int offset, int count) { CheckAsync(); CoreWriter.WriteArray(prefix, localName, namespaceUri, array, offset, count); } - public override void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, TimeSpan[] array, int offset, int count) + public override void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, TimeSpan[] array, int offset, int count) { CheckAsync(); CoreWriter.WriteArray(prefix, localName, namespaceUri, array, offset, count); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryReader.cs index 16d9f55aff293b..79922c417deb3f 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryReader.cs @@ -9,7 +9,7 @@ using System.Text; using System.Runtime.Serialization; using System.Globalization; - +using System.Diagnostics.CodeAnalysis; namespace System.Xml { @@ -24,7 +24,7 @@ public static XmlDictionaryReader CreateDictionaryReader(XmlReader reader) if (reader == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(reader)); - XmlDictionaryReader dictionaryReader = reader as XmlDictionaryReader; + XmlDictionaryReader? dictionaryReader = reader as XmlDictionaryReader; if (dictionaryReader == null) { @@ -46,21 +46,21 @@ public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, return CreateBinaryReader(buffer, offset, count, null, quotas); } - public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas) + public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, IXmlDictionary? dictionary, XmlDictionaryReaderQuotas quotas) { return CreateBinaryReader(buffer, offset, count, dictionary, quotas, null); } - public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession session) + public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, IXmlDictionary? dictionary, XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession? session) { return CreateBinaryReader(buffer, offset, count, dictionary, quotas, session, onClose: null); } public static XmlDictionaryReader CreateBinaryReader(byte[] buffer, int offset, int count, - IXmlDictionary dictionary, + IXmlDictionary? dictionary, XmlDictionaryReaderQuotas quotas, - XmlBinaryReaderSession session, - OnXmlDictionaryReaderClose onClose) + XmlBinaryReaderSession? session, + OnXmlDictionaryReaderClose? onClose) { XmlBinaryReader reader = new XmlBinaryReader(); reader.SetInput(buffer, offset, count, dictionary, quotas, session, onClose); @@ -72,21 +72,21 @@ public static XmlDictionaryReader CreateBinaryReader(Stream stream, XmlDictionar return CreateBinaryReader(stream, null, quotas); } - public static XmlDictionaryReader CreateBinaryReader(Stream stream, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas) + public static XmlDictionaryReader CreateBinaryReader(Stream stream, IXmlDictionary? dictionary, XmlDictionaryReaderQuotas quotas) { return CreateBinaryReader(stream, dictionary, quotas, null); } - public static XmlDictionaryReader CreateBinaryReader(Stream stream, IXmlDictionary dictionary, XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession session) + public static XmlDictionaryReader CreateBinaryReader(Stream stream, IXmlDictionary? dictionary, XmlDictionaryReaderQuotas quotas, XmlBinaryReaderSession? session) { return CreateBinaryReader(stream, dictionary, quotas, session, onClose: null); } public static XmlDictionaryReader CreateBinaryReader(Stream stream, - IXmlDictionary dictionary, + IXmlDictionary? dictionary, XmlDictionaryReaderQuotas quotas, - XmlBinaryReaderSession session, - OnXmlDictionaryReaderClose onClose) + XmlBinaryReaderSession? session, + OnXmlDictionaryReaderClose? onClose) { XmlBinaryReader reader = new XmlBinaryReader(); reader.SetInput(stream, dictionary, quotas, session, onClose); @@ -106,9 +106,9 @@ public static XmlDictionaryReader CreateTextReader(byte[] buffer, int offset, in } public static XmlDictionaryReader CreateTextReader(byte[] buffer, int offset, int count, - Encoding encoding, + Encoding? encoding, XmlDictionaryReaderQuotas quotas, - OnXmlDictionaryReaderClose onClose) + OnXmlDictionaryReaderClose? onClose) { XmlUTF8TextReader reader = new XmlUTF8TextReader(); reader.SetInput(buffer, offset, count, encoding, quotas, onClose); @@ -120,9 +120,9 @@ public static XmlDictionaryReader CreateTextReader(Stream stream, XmlDictionaryR return CreateTextReader(stream, null, quotas, null); } - public static XmlDictionaryReader CreateTextReader(Stream stream, Encoding encoding, + public static XmlDictionaryReader CreateTextReader(Stream stream, Encoding? encoding, XmlDictionaryReaderQuotas quotas, - OnXmlDictionaryReaderClose onClose) + OnXmlDictionaryReaderClose? onClose) { XmlUTF8TextReader reader = new XmlUTF8TextReader(); reader.SetInput(stream, encoding, quotas, onClose); @@ -142,13 +142,13 @@ public static XmlDictionaryReader CreateMtomReader(Stream stream, Encoding[] enc return CreateMtomReader(stream, encodings, null, quotas); } - public static XmlDictionaryReader CreateMtomReader(Stream stream, Encoding[] encodings, string contentType, XmlDictionaryReaderQuotas quotas) + public static XmlDictionaryReader CreateMtomReader(Stream stream, Encoding[] encodings, string? contentType, XmlDictionaryReaderQuotas quotas) { return CreateMtomReader(stream, encodings, contentType, quotas, int.MaxValue, null); } - public static XmlDictionaryReader CreateMtomReader(Stream stream, Encoding[] encodings, string contentType, - XmlDictionaryReaderQuotas quotas, int maxBufferSize, OnXmlDictionaryReaderClose onClose) + public static XmlDictionaryReader CreateMtomReader(Stream stream, Encoding[] encodings, string? contentType, + XmlDictionaryReaderQuotas quotas, int maxBufferSize, OnXmlDictionaryReaderClose? onClose) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_MtomEncoding); } @@ -166,13 +166,13 @@ public static XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, in return CreateMtomReader(buffer, offset, count, encodings, null, quotas); } - public static XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, Encoding[] encodings, string contentType, XmlDictionaryReaderQuotas quotas) + public static XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, Encoding[] encodings, string? contentType, XmlDictionaryReaderQuotas quotas) { return CreateMtomReader(buffer, offset, count, encodings, contentType, quotas, int.MaxValue, null); } - public static XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, Encoding[] encodings, string contentType, - XmlDictionaryReaderQuotas quotas, int maxBufferSize, OnXmlDictionaryReaderClose onClose) + public static XmlDictionaryReader CreateMtomReader(byte[] buffer, int offset, int count, Encoding[] encodings, string? contentType, + XmlDictionaryReaderQuotas quotas, int maxBufferSize, OnXmlDictionaryReaderClose? onClose) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_MtomEncoding); } @@ -193,7 +193,7 @@ public virtual XmlDictionaryReaderQuotas Quotas } } - public virtual void StartCanonicalization(Stream stream, bool includeComments, string[] inclusivePrefixes) + public virtual void StartCanonicalization(Stream stream, bool includeComments, string[]? inclusivePrefixes) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } @@ -349,7 +349,7 @@ public virtual int IndexOfLocalName(XmlDictionaryString[] localNames, XmlDiction return -1; } - public virtual string GetAttribute(XmlDictionaryString localName, XmlDictionaryString namespaceUri) + public virtual string? GetAttribute(XmlDictionaryString localName, XmlDictionaryString namespaceUri) { return GetAttribute(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri)); } @@ -399,7 +399,7 @@ public override string ReadContentAsString() protected string ReadContentAsString(int maxStringContentLength) { - StringBuilder sb = null; + StringBuilder? sb = null; string result = string.Empty; bool done = false; while (true) @@ -480,7 +480,7 @@ protected string ReadString(int maxStringContentLength) if (this.NodeType == XmlNodeType.EndElement) return string.Empty; } - StringBuilder sb = null; + StringBuilder? sb = null; string result = string.Empty; while (IsTextNode(this.NodeType)) { @@ -599,7 +599,7 @@ public virtual int ReadContentAsChars(char[] chars, int offset, int count) return read; } - public override object ReadContentAs(Type type, IXmlNamespaceResolver namespaceResolver) + public override object ReadContentAs(Type type, IXmlNamespaceResolver? namespaceResolver) { if (type == typeof(Guid[])) { @@ -689,7 +689,7 @@ public virtual void ReadContentAsQualifiedName(out string localName, out string { string prefix; XmlConverter.ToQualifiedName(ReadContentAsString(), out prefix, out localName); - namespaceUri = LookupNamespace(prefix); + namespaceUri = LookupNamespace(prefix)!; if (namespaceUri == null) XmlExceptionHelper.ThrowUndefinedPrefix(this, prefix); } @@ -998,19 +998,19 @@ public virtual void GetNonAtomizedNames(out string localName, out string namespa namespaceUri = NamespaceURI; } - public virtual bool TryGetLocalNameAsDictionaryString(out XmlDictionaryString localName) + public virtual bool TryGetLocalNameAsDictionaryString([NotNullWhen(true)] out XmlDictionaryString? localName) { localName = null; return false; } - public virtual bool TryGetNamespaceUriAsDictionaryString(out XmlDictionaryString namespaceUri) + public virtual bool TryGetNamespaceUriAsDictionaryString([NotNullWhen(true)] out XmlDictionaryString? namespaceUri) { namespaceUri = null; return false; } - public virtual bool TryGetValueAsDictionaryString(out XmlDictionaryString value) + public virtual bool TryGetValueAsDictionaryString([NotNullWhen(true)] out XmlDictionaryString? value) { value = null; return false; @@ -1030,7 +1030,7 @@ private void CheckArray(Array array, int offset, int count) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, array.Length - offset))); } - public virtual bool IsStartArray(out Type type) + public virtual bool IsStartArray([NotNullWhen(true)] out Type? type) { type = null; return false; @@ -1328,9 +1328,9 @@ public virtual int ReadArray(XmlDictionaryString localName, XmlDictionaryString private class XmlWrappedReader : XmlDictionaryReader, IXmlLineInfo { private readonly XmlReader _reader; - private XmlNamespaceManager _nsMgr; + private XmlNamespaceManager? _nsMgr; - public XmlWrappedReader(XmlReader reader, XmlNamespaceManager nsMgr) + public XmlWrappedReader(XmlReader reader, XmlNamespaceManager? nsMgr) { _reader = reader; _nsMgr = nsMgr; @@ -1344,7 +1344,7 @@ public override int AttributeCount } } - public override string BaseURI + public override string? BaseURI { get { @@ -1389,12 +1389,12 @@ public override string GetAttribute(int index) return _reader.GetAttribute(index); } - public override string GetAttribute(string name) + public override string? GetAttribute(string name) { return _reader.GetAttribute(name); } - public override string GetAttribute(string name, string namespaceUri) + public override string? GetAttribute(string name, string? namespaceUri) { return _reader.GetAttribute(name, namespaceUri); } @@ -1441,7 +1441,7 @@ public override string LocalName } } - public override string LookupNamespace(string namespaceUri) + public override string? LookupNamespace(string namespaceUri) { return _reader.LookupNamespace(namespaceUri); } @@ -1456,7 +1456,7 @@ public override bool MoveToAttribute(string name) return _reader.MoveToAttribute(name); } - public override bool MoveToAttribute(string name, string namespaceUri) + public override bool MoveToAttribute(string name, string? namespaceUri) { return _reader.MoveToAttribute(name, namespaceUri); } @@ -1574,7 +1574,7 @@ public override string this[int index] } } - public override string this[string name] + public override string? this[string name] { get { @@ -1582,11 +1582,12 @@ public override string this[string name] } } - public override string this[string name, string namespaceUri] + public override string? this[string name, string? namespaceUri] { get { - return _reader[name, namespaceUri]; + // TODO-NULLABLE - unnecessary namespaceUri! - https://github.com/dotnet/roslyn/issues/47221 + return _reader[name, namespaceUri!]; } } @@ -1784,14 +1785,14 @@ public override string ReadContentAsString() } } - public override object ReadContentAs(Type type, IXmlNamespaceResolver namespaceResolver) + public override object ReadContentAs(Type type, IXmlNamespaceResolver? namespaceResolver) { return _reader.ReadContentAs(type, namespaceResolver); } public bool HasLineInfo() { - IXmlLineInfo lineInfo = _reader as IXmlLineInfo; + IXmlLineInfo? lineInfo = _reader as IXmlLineInfo; if (lineInfo == null) return false; @@ -1803,7 +1804,7 @@ public int LineNumber { get { - IXmlLineInfo lineInfo = _reader as IXmlLineInfo; + IXmlLineInfo? lineInfo = _reader as IXmlLineInfo; if (lineInfo == null) return 1; @@ -1816,7 +1817,7 @@ public int LinePosition { get { - IXmlLineInfo lineInfo = _reader as IXmlLineInfo; + IXmlLineInfo? lineInfo = _reader as IXmlLineInfo; if (lineInfo == null) return 1; diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryString.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryString.cs index b1f58f53e983e2..9adecff2542485 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryString.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryString.cs @@ -6,7 +6,7 @@ using System.Text; using System.Diagnostics; using System.Runtime.Serialization; - +using System.Diagnostics.CodeAnalysis; namespace System.Xml { @@ -18,7 +18,7 @@ public class XmlDictionaryString private readonly IXmlDictionary _dictionary; private readonly string _value; private readonly int _key; - private byte[] _buffer; + private byte[]? _buffer; private static readonly EmptyStringDictionary s_emptyStringDictionary = new EmptyStringDictionary(); public XmlDictionaryString(IXmlDictionary dictionary, string value, int key) @@ -34,7 +34,8 @@ public XmlDictionaryString(IXmlDictionary dictionary, string value, int key) _key = key; } - internal static string GetString(XmlDictionaryString s) + [return: NotNullIfNotNull("s")] + internal static string? GetString(XmlDictionaryString? s) { if (s == null) return null; @@ -102,7 +103,7 @@ public XmlDictionaryString EmptyString } } - public bool TryLookup(string value, out XmlDictionaryString result) + public bool TryLookup(string value, [NotNullWhen(true)] out XmlDictionaryString? result) { if (value == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(value)); @@ -115,7 +116,7 @@ public bool TryLookup(string value, out XmlDictionaryString result) return false; } - public bool TryLookup(int key, out XmlDictionaryString result) + public bool TryLookup(int key, [NotNullWhen(true)] out XmlDictionaryString? result) { if (key == 0) { @@ -126,7 +127,7 @@ public bool TryLookup(int key, out XmlDictionaryString result) return false; } - public bool TryLookup(XmlDictionaryString value, out XmlDictionaryString result) + public bool TryLookup(XmlDictionaryString value, [NotNullWhen(true)] out XmlDictionaryString? result) { if (value == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(value))); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryWriter.cs index 2f9e81b3a5b02c..6d2fb2d345e8c2 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlDictionaryWriter.cs @@ -22,17 +22,17 @@ public static XmlDictionaryWriter CreateBinaryWriter(Stream stream) return CreateBinaryWriter(stream, null); } - public static XmlDictionaryWriter CreateBinaryWriter(Stream stream, IXmlDictionary dictionary) + public static XmlDictionaryWriter CreateBinaryWriter(Stream stream, IXmlDictionary? dictionary) { return CreateBinaryWriter(stream, dictionary, null); } - public static XmlDictionaryWriter CreateBinaryWriter(Stream stream, IXmlDictionary dictionary, XmlBinaryWriterSession session) + public static XmlDictionaryWriter CreateBinaryWriter(Stream stream, IXmlDictionary? dictionary, XmlBinaryWriterSession? session) { return CreateBinaryWriter(stream, dictionary, session, true); } - public static XmlDictionaryWriter CreateBinaryWriter(Stream stream, IXmlDictionary dictionary, XmlBinaryWriterSession session, bool ownsStream) + public static XmlDictionaryWriter CreateBinaryWriter(Stream stream, IXmlDictionary? dictionary, XmlBinaryWriterSession? session, bool ownsStream) { XmlBinaryWriter writer = new XmlBinaryWriter(); writer.SetOutput(stream, dictionary, session, ownsStream); @@ -63,7 +63,7 @@ public static XmlDictionaryWriter CreateMtomWriter(Stream stream, Encoding encod return CreateMtomWriter(stream, encoding, maxSizeInBytes, startInfo, null, null, true, true); } - public static XmlDictionaryWriter CreateMtomWriter(Stream stream, Encoding encoding, int maxSizeInBytes, string startInfo, string boundary, string startUri, bool writeMessageHeaders, bool ownsStream) + public static XmlDictionaryWriter CreateMtomWriter(Stream stream, Encoding encoding, int maxSizeInBytes, string startInfo, string? boundary, string? startUri, bool writeMessageHeaders, bool ownsStream) { throw new PlatformNotSupportedException(SR.PlatformNotSupported_MtomEncoding); } @@ -73,7 +73,7 @@ public static XmlDictionaryWriter CreateDictionaryWriter(XmlWriter writer) if (writer == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(writer)); - XmlDictionaryWriter dictionaryWriter = writer as XmlDictionaryWriter; + XmlDictionaryWriter? dictionaryWriter = writer as XmlDictionaryWriter; if (dictionaryWriter == null) { @@ -89,32 +89,32 @@ public override Task WriteBase64Async(byte[] buffer, int index, int count) return Task.CompletedTask; } - public void WriteStartElement(XmlDictionaryString localName, XmlDictionaryString namespaceUri) + public void WriteStartElement(XmlDictionaryString localName, XmlDictionaryString? namespaceUri) { - WriteStartElement((string)null, localName, namespaceUri); + WriteStartElement((string?)null, localName, namespaceUri); } - public virtual void WriteStartElement(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri) + public virtual void WriteStartElement(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri) { WriteStartElement(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri)); } - public void WriteStartAttribute(XmlDictionaryString localName, XmlDictionaryString namespaceUri) + public void WriteStartAttribute(XmlDictionaryString localName, XmlDictionaryString? namespaceUri) { - WriteStartAttribute((string)null, localName, namespaceUri); + WriteStartAttribute((string?)null, localName, namespaceUri); } - public virtual void WriteStartAttribute(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri) + public virtual void WriteStartAttribute(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri) { WriteStartAttribute(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri)); } - public void WriteAttributeString(XmlDictionaryString localName, XmlDictionaryString namespaceUri, string value) + public void WriteAttributeString(XmlDictionaryString localName, XmlDictionaryString? namespaceUri, string? value) { - WriteAttributeString((string)null, localName, namespaceUri, value); + WriteAttributeString((string?)null, localName, namespaceUri, value); } - public virtual void WriteXmlnsAttribute(string prefix, string namespaceUri) + public virtual void WriteXmlnsAttribute(string? prefix, string namespaceUri) { if (namespaceUri == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(namespaceUri)); @@ -128,46 +128,46 @@ public virtual void WriteXmlnsAttribute(string prefix, string namespaceUri) WriteAttributeString("xmlns", prefix, null, namespaceUri); } - public virtual void WriteXmlnsAttribute(string prefix, XmlDictionaryString namespaceUri) + public virtual void WriteXmlnsAttribute(string? prefix, XmlDictionaryString namespaceUri) { WriteXmlnsAttribute(prefix, XmlDictionaryString.GetString(namespaceUri)); } - public virtual void WriteXmlAttribute(string localName, string value) + public virtual void WriteXmlAttribute(string localName, string? value) { WriteAttributeString("xml", localName, null, value); } - public virtual void WriteXmlAttribute(XmlDictionaryString localName, XmlDictionaryString value) + public virtual void WriteXmlAttribute(XmlDictionaryString localName, XmlDictionaryString? value) { WriteXmlAttribute(XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(value)); } - public void WriteAttributeString(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, string value) + public void WriteAttributeString(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, string? value) { WriteStartAttribute(prefix, localName, namespaceUri); WriteString(value); WriteEndAttribute(); } - public void WriteElementString(XmlDictionaryString localName, XmlDictionaryString namespaceUri, string value) + public void WriteElementString(XmlDictionaryString localName, XmlDictionaryString? namespaceUri, string? value) { - WriteElementString((string)null, localName, namespaceUri, value); + WriteElementString((string?)null, localName, namespaceUri, value); } - public void WriteElementString(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, string value) + public void WriteElementString(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, string? value) { WriteStartElement(prefix, localName, namespaceUri); WriteString(value); WriteEndElement(); } - public virtual void WriteString(XmlDictionaryString value) + public virtual void WriteString(XmlDictionaryString? value) { WriteString(XmlDictionaryString.GetString(value)); } - public virtual void WriteQualifiedName(XmlDictionaryString localName, XmlDictionaryString namespaceUri) + public virtual void WriteQualifiedName(XmlDictionaryString localName, XmlDictionaryString? namespaceUri) { if (localName == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(localName))); @@ -177,7 +177,7 @@ public virtual void WriteQualifiedName(XmlDictionaryString localName, XmlDiction WriteQualifiedName(localName.Value, namespaceUri.Value); } - public virtual void WriteValue(XmlDictionaryString value) + public virtual void WriteValue(XmlDictionaryString? value) { WriteValue(XmlDictionaryString.GetString(value)); } @@ -242,7 +242,7 @@ public virtual bool CanCanonicalize } } - public virtual void StartCanonicalization(Stream stream, bool includeComments, string[] inclusivePrefixes) + public virtual void StartCanonicalization(Stream stream, bool includeComments, string[]? inclusivePrefixes) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException()); } @@ -254,8 +254,8 @@ public virtual void EndCanonicalization() private void WriteElementNode(XmlDictionaryReader reader, bool defattr) { - XmlDictionaryString localName; - XmlDictionaryString namespaceUri; + XmlDictionaryString? localName; + XmlDictionaryString? namespaceUri; if (reader.TryGetLocalNameAsDictionaryString(out localName) && reader.TryGetNamespaceUriAsDictionaryString(out namespaceUri)) { WriteStartElement(reader.Prefix, localName, namespaceUri); @@ -361,8 +361,8 @@ private void WriteArrayNode(XmlDictionaryReader reader, string prefix, XmlDictio private void WriteArrayNode(XmlDictionaryReader reader, Type type) { - XmlDictionaryString localName; - XmlDictionaryString namespaceUri; + XmlDictionaryString? localName; + XmlDictionaryString? namespaceUri; if (reader.TryGetLocalNameAsDictionaryString(out localName) && reader.TryGetNamespaceUriAsDictionaryString(out namespaceUri)) WriteArrayNode(reader, reader.Prefix, localName, namespaceUri, type); else @@ -371,7 +371,7 @@ private void WriteArrayNode(XmlDictionaryReader reader, Type type) protected virtual void WriteTextNode(XmlDictionaryReader reader, bool isAttribute) { - XmlDictionaryString value; + XmlDictionaryString? value; if (reader.TryGetValueAsDictionaryString(out value)) { WriteString(value); @@ -388,7 +388,7 @@ protected virtual void WriteTextNode(XmlDictionaryReader reader, bool isAttribut public override void WriteNode(XmlReader reader, bool defattr) { - XmlDictionaryReader dictionaryReader = reader as XmlDictionaryReader; + XmlDictionaryReader? dictionaryReader = reader as XmlDictionaryReader; if (dictionaryReader != null) WriteNode(dictionaryReader, defattr); else @@ -403,7 +403,7 @@ public virtual void WriteNode(XmlDictionaryReader reader, bool defattr) do { XmlNodeType nodeType = reader.NodeType; - Type type; + Type? type; if (nodeType == XmlNodeType.Text || nodeType == XmlNodeType.Whitespace || nodeType == XmlNodeType.SignificantWhitespace) { // This will advance if necessary, so we don't need to call Read() explicitly @@ -463,7 +463,7 @@ private void CheckArray(Array array, int offset, int count) } // bool - public virtual void WriteArray(string prefix, string localName, string namespaceUri, bool[] array, int offset, int count) + public virtual void WriteArray(string? prefix, string localName, string? namespaceUri, bool[] array, int offset, int count) { CheckArray(array, offset, count); for (int i = 0; i < count; i++) @@ -474,13 +474,13 @@ public virtual void WriteArray(string prefix, string localName, string namespace } } - public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, bool[] array, int offset, int count) + public virtual void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, bool[] array, int offset, int count) { WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count); } // Int16 - public virtual void WriteArray(string prefix, string localName, string namespaceUri, short[] array, int offset, int count) + public virtual void WriteArray(string? prefix, string localName, string? namespaceUri, short[] array, int offset, int count) { CheckArray(array, offset, count); for (int i = 0; i < count; i++) @@ -491,13 +491,13 @@ public virtual void WriteArray(string prefix, string localName, string namespace } } - public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, short[] array, int offset, int count) + public virtual void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, short[] array, int offset, int count) { WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count); } // Int32 - public virtual void WriteArray(string prefix, string localName, string namespaceUri, int[] array, int offset, int count) + public virtual void WriteArray(string? prefix, string localName, string? namespaceUri, int[] array, int offset, int count) { CheckArray(array, offset, count); for (int i = 0; i < count; i++) @@ -508,13 +508,13 @@ public virtual void WriteArray(string prefix, string localName, string namespace } } - public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, int[] array, int offset, int count) + public virtual void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, int[] array, int offset, int count) { WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count); } // Int64 - public virtual void WriteArray(string prefix, string localName, string namespaceUri, long[] array, int offset, int count) + public virtual void WriteArray(string? prefix, string localName, string? namespaceUri, long[] array, int offset, int count) { CheckArray(array, offset, count); for (int i = 0; i < count; i++) @@ -525,13 +525,13 @@ public virtual void WriteArray(string prefix, string localName, string namespace } } - public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, long[] array, int offset, int count) + public virtual void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, long[] array, int offset, int count) { WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count); } // float - public virtual void WriteArray(string prefix, string localName, string namespaceUri, float[] array, int offset, int count) + public virtual void WriteArray(string? prefix, string localName, string? namespaceUri, float[] array, int offset, int count) { CheckArray(array, offset, count); for (int i = 0; i < count; i++) @@ -542,13 +542,13 @@ public virtual void WriteArray(string prefix, string localName, string namespace } } - public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, float[] array, int offset, int count) + public virtual void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, float[] array, int offset, int count) { WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count); } // double - public virtual void WriteArray(string prefix, string localName, string namespaceUri, double[] array, int offset, int count) + public virtual void WriteArray(string? prefix, string localName, string? namespaceUri, double[] array, int offset, int count) { CheckArray(array, offset, count); for (int i = 0; i < count; i++) @@ -559,13 +559,13 @@ public virtual void WriteArray(string prefix, string localName, string namespace } } - public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, double[] array, int offset, int count) + public virtual void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, double[] array, int offset, int count) { WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count); } // decimal - public virtual void WriteArray(string prefix, string localName, string namespaceUri, decimal[] array, int offset, int count) + public virtual void WriteArray(string? prefix, string localName, string? namespaceUri, decimal[] array, int offset, int count) { CheckArray(array, offset, count); for (int i = 0; i < count; i++) @@ -576,13 +576,13 @@ public virtual void WriteArray(string prefix, string localName, string namespace } } - public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, decimal[] array, int offset, int count) + public virtual void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, decimal[] array, int offset, int count) { WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count); } // DateTime - public virtual void WriteArray(string prefix, string localName, string namespaceUri, DateTime[] array, int offset, int count) + public virtual void WriteArray(string? prefix, string localName, string? namespaceUri, DateTime[] array, int offset, int count) { CheckArray(array, offset, count); for (int i = 0; i < count; i++) @@ -593,13 +593,13 @@ public virtual void WriteArray(string prefix, string localName, string namespace } } - public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, DateTime[] array, int offset, int count) + public virtual void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, DateTime[] array, int offset, int count) { WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count); } // Guid - public virtual void WriteArray(string prefix, string localName, string namespaceUri, Guid[] array, int offset, int count) + public virtual void WriteArray(string? prefix, string localName, string? namespaceUri, Guid[] array, int offset, int count) { CheckArray(array, offset, count); for (int i = 0; i < count; i++) @@ -610,13 +610,13 @@ public virtual void WriteArray(string prefix, string localName, string namespace } } - public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, Guid[] array, int offset, int count) + public virtual void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, Guid[] array, int offset, int count) { WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count); } // TimeSpan - public virtual void WriteArray(string prefix, string localName, string namespaceUri, TimeSpan[] array, int offset, int count) + public virtual void WriteArray(string? prefix, string localName, string? namespaceUri, TimeSpan[] array, int offset, int count) { CheckArray(array, offset, count); for (int i = 0; i < count; i++) @@ -627,7 +627,7 @@ public virtual void WriteArray(string prefix, string localName, string namespace } } - public virtual void WriteArray(string prefix, XmlDictionaryString localName, XmlDictionaryString namespaceUri, TimeSpan[] array, int offset, int count) + public virtual void WriteArray(string? prefix, XmlDictionaryString localName, XmlDictionaryString? namespaceUri, TimeSpan[] array, int offset, int count) { WriteArray(prefix, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(namespaceUri), array, offset, count); } @@ -664,7 +664,7 @@ public override void Flush() _writer.Flush(); } - public override string LookupPrefix(string namespaceUri) + public override string? LookupPrefix(string namespaceUri) { return _writer.LookupPrefix(namespaceUri); } @@ -684,7 +684,7 @@ public override void WriteBinHex(byte[] buffer, int index, int count) _writer.WriteBinHex(buffer, index, count); } - public override void WriteCData(string text) + public override void WriteCData(string? text) { _writer.WriteCData(text); } @@ -699,12 +699,12 @@ public override void WriteChars(char[] buffer, int index, int count) _writer.WriteChars(buffer, index, count); } - public override void WriteComment(string text) + public override void WriteComment(string? text) { _writer.WriteComment(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) { _writer.WriteDocType(name, pubid, sysid, subset); } @@ -750,12 +750,12 @@ public override void WriteNode(XmlReader reader, bool defattr) _writer.WriteNode(reader, defattr); } - public override void WriteProcessingInstruction(string name, string text) + public override void WriteProcessingInstruction(string name, string? text) { _writer.WriteProcessingInstruction(name, text); } - public override void WriteQualifiedName(string localName, string namespaceUri) + public override void WriteQualifiedName(string localName, string? namespaceUri) { _writer.WriteQualifiedName(localName, namespaceUri); } @@ -770,7 +770,7 @@ public override void WriteRaw(string data) _writer.WriteRaw(data); } - public override void WriteStartAttribute(string prefix, string localName, string namespaceUri) + public override void WriteStartAttribute(string? prefix, string localName, string? namespaceUri) { _writer.WriteStartAttribute(prefix, localName, namespaceUri); _prefix++; @@ -786,7 +786,7 @@ public override void WriteStartDocument(bool standalone) _writer.WriteStartDocument(standalone); } - public override void WriteStartElement(string prefix, string localName, string namespaceUri) + public override void WriteStartElement(string? prefix, string localName, string? namespaceUri) { _writer.WriteStartElement(prefix, localName, namespaceUri); _depth++; @@ -801,7 +801,7 @@ public override WriteState WriteState } } - public override void WriteString(string text) + public override void WriteString(string? text) { _writer.WriteString(text); } @@ -811,7 +811,7 @@ public override void WriteSurrogateCharEntity(char lowChar, char highChar) _writer.WriteSurrogateCharEntity(lowChar, highChar); } - public override void WriteWhitespace(string whitespace) + public override void WriteWhitespace(string? whitespace) { _writer.WriteWhitespace(whitespace); } @@ -821,7 +821,7 @@ public override void WriteValue(object value) _writer.WriteValue(value); } - public override void WriteValue(string value) + public override void WriteValue(string? value) { _writer.WriteValue(value); } @@ -851,7 +851,7 @@ public override void WriteValue(long value) _writer.WriteValue(value); } - public override void WriteXmlnsAttribute(string prefix, string namespaceUri) + public override void WriteXmlnsAttribute(string? prefix, string namespaceUri) { if (namespaceUri == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(namespaceUri)); @@ -874,7 +874,7 @@ public override void WriteXmlnsAttribute(string prefix, string namespaceUri) WriteAttributeString("xmlns", prefix, null, namespaceUri); } - public override string XmlLang + public override string? XmlLang { get { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlExceptionHelper.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlExceptionHelper.cs index b16deded741f21..3d6cc5cb606550 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlExceptionHelper.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlExceptionHelper.cs @@ -3,30 +3,35 @@ using System.Runtime.Serialization; using System.Globalization; +using System.Diagnostics.CodeAnalysis; namespace System.Xml { internal static class XmlExceptionHelper { + [DoesNotReturn] private static void ThrowXmlException(XmlDictionaryReader reader, string res) { ThrowXmlException(reader, res, null); } - public static void ThrowXmlException(XmlDictionaryReader reader, string res, string arg1) + [DoesNotReturn] + public static void ThrowXmlException(XmlDictionaryReader reader, string res, string? arg1) { ThrowXmlException(reader, res, arg1, null); } - private static void ThrowXmlException(XmlDictionaryReader reader, string res, string arg1, string arg2) + [DoesNotReturn] + private static void ThrowXmlException(XmlDictionaryReader reader, string res, string? arg1, string? arg2) { ThrowXmlException(reader, res, arg1, arg2, null); } - private static void ThrowXmlException(XmlDictionaryReader reader, string res, string arg1, string arg2, string arg3) + [DoesNotReturn] + private static void ThrowXmlException(XmlDictionaryReader reader, string res, string? arg1, string? arg2, string? arg3) { string s = SR.Format(res, arg1, arg2, arg3); - IXmlLineInfo lineInfo = reader as IXmlLineInfo; + IXmlLineInfo? lineInfo = reader as IXmlLineInfo; if (lineInfo != null && lineInfo.HasLineInfo()) { s += " " + SR.Format(SR.XmlLineInfo, lineInfo.LineNumber, lineInfo.LinePosition); @@ -35,10 +40,11 @@ private static void ThrowXmlException(XmlDictionaryReader reader, string res, st throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new XmlException(s)); } + [DoesNotReturn] public static void ThrowXmlException(XmlDictionaryReader reader, XmlException exception) { string s = exception.Message; - IXmlLineInfo lineInfo = reader as IXmlLineInfo; + IXmlLineInfo? lineInfo = reader as IXmlLineInfo; if (lineInfo != null && lineInfo.HasLineInfo()) { s += " " + SR.Format(SR.XmlLineInfo, lineInfo.LineNumber, lineInfo.LinePosition); @@ -76,121 +82,145 @@ private static string GetWhatWasFound(XmlDictionaryReader reader) return SR.Format(SR.XmlFoundNodeType, reader.NodeType); } + [DoesNotReturn] public static void ThrowStartElementExpected(XmlDictionaryReader reader) { ThrowXmlException(reader, SR.XmlStartElementExpected, GetWhatWasFound(reader)); } + [DoesNotReturn] public static void ThrowStartElementExpected(XmlDictionaryReader reader, string name) { ThrowXmlException(reader, SR.XmlStartElementNameExpected, name, GetWhatWasFound(reader)); } + [DoesNotReturn] public static void ThrowStartElementExpected(XmlDictionaryReader reader, string localName, string ns) { ThrowXmlException(reader, SR.XmlStartElementLocalNameNsExpected, localName, ns, GetWhatWasFound(reader)); } + [DoesNotReturn] public static void ThrowStartElementExpected(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString ns) { ThrowStartElementExpected(reader, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(ns)); } + [DoesNotReturn] public static void ThrowFullStartElementExpected(XmlDictionaryReader reader) { ThrowXmlException(reader, SR.XmlFullStartElementExpected, GetWhatWasFound(reader)); } + [DoesNotReturn] public static void ThrowFullStartElementExpected(XmlDictionaryReader reader, string name) { ThrowXmlException(reader, SR.XmlFullStartElementNameExpected, name, GetWhatWasFound(reader)); } + [DoesNotReturn] public static void ThrowFullStartElementExpected(XmlDictionaryReader reader, string localName, string ns) { ThrowXmlException(reader, SR.XmlFullStartElementLocalNameNsExpected, localName, ns, GetWhatWasFound(reader)); } + [DoesNotReturn] public static void ThrowFullStartElementExpected(XmlDictionaryReader reader, XmlDictionaryString localName, XmlDictionaryString ns) { ThrowFullStartElementExpected(reader, XmlDictionaryString.GetString(localName), XmlDictionaryString.GetString(ns)); } + [DoesNotReturn] public static void ThrowEndElementExpected(XmlDictionaryReader reader, string localName, string ns) { ThrowXmlException(reader, SR.XmlEndElementExpected, localName, ns, GetWhatWasFound(reader)); } + [DoesNotReturn] public static void ThrowMaxArrayLengthExceeded(XmlDictionaryReader reader, int maxArrayLength) { ThrowXmlException(reader, SR.XmlMaxArrayLengthExceeded, maxArrayLength.ToString(NumberFormatInfo.CurrentInfo)); } + [DoesNotReturn] public static void ThrowMaxBytesPerReadExceeded(XmlDictionaryReader reader, int maxBytesPerRead) { ThrowXmlException(reader, SR.XmlMaxBytesPerReadExceeded, maxBytesPerRead.ToString(NumberFormatInfo.CurrentInfo)); } + [DoesNotReturn] public static void ThrowMaxDepthExceeded(XmlDictionaryReader reader, int maxDepth) { ThrowXmlException(reader, SR.XmlMaxDepthExceeded, maxDepth.ToString()); } + [DoesNotReturn] public static void ThrowMaxStringContentLengthExceeded(XmlDictionaryReader reader, int maxStringContentLength) { ThrowXmlException(reader, SR.XmlMaxStringContentLengthExceeded, maxStringContentLength.ToString(NumberFormatInfo.CurrentInfo)); } + [DoesNotReturn] public static void ThrowBase64DataExpected(XmlDictionaryReader reader) { ThrowXmlException(reader, SR.XmlBase64DataExpected, GetWhatWasFound(reader)); } + [DoesNotReturn] public static void ThrowUndefinedPrefix(XmlDictionaryReader reader, string prefix) { ThrowXmlException(reader, SR.XmlUndefinedPrefix, prefix); } + [DoesNotReturn] public static void ThrowProcessingInstructionNotSupported(XmlDictionaryReader reader) { ThrowXmlException(reader, SR.XmlProcessingInstructionNotSupported); } + [DoesNotReturn] public static void ThrowInvalidXml(XmlDictionaryReader reader, byte b) { ThrowXmlException(reader, SR.XmlInvalidXmlByte, b.ToString("X2", CultureInfo.InvariantCulture)); } + [DoesNotReturn] public static void ThrowUnexpectedEndOfFile(XmlDictionaryReader reader) { ThrowXmlException(reader, SR.XmlUnexpectedEndOfFile, ((XmlBaseReader)reader).GetOpenElements()); } + [DoesNotReturn] public static void ThrowUnexpectedEndElement(XmlDictionaryReader reader) { ThrowXmlException(reader, SR.XmlUnexpectedEndElement); } + [DoesNotReturn] public static void ThrowTokenExpected(XmlDictionaryReader reader, string expected, char found) { ThrowXmlException(reader, SR.XmlTokenExpected, expected, found.ToString()); } + [DoesNotReturn] public static void ThrowTokenExpected(XmlDictionaryReader reader, string expected, string found) { ThrowXmlException(reader, SR.XmlTokenExpected, expected, found); } + [DoesNotReturn] public static void ThrowInvalidCharRef(XmlDictionaryReader reader) { ThrowXmlException(reader, SR.XmlInvalidCharRef); } + [DoesNotReturn] public static void ThrowTagMismatch(XmlDictionaryReader reader, string expectedPrefix, string expectedLocalName, string foundPrefix, string foundLocalName) { ThrowXmlException(reader, SR.XmlTagMismatch, GetName(expectedPrefix, expectedLocalName), GetName(foundPrefix, foundLocalName)); } + [DoesNotReturn] public static void ThrowDuplicateXmlnsAttribute(XmlDictionaryReader reader, string localName, string ns) { string name; @@ -201,51 +231,61 @@ public static void ThrowDuplicateXmlnsAttribute(XmlDictionaryReader reader, stri ThrowXmlException(reader, SR.XmlDuplicateAttribute, name, name, ns); } + [DoesNotReturn] public static void ThrowDuplicateAttribute(XmlDictionaryReader reader, string prefix1, string prefix2, string localName, string ns) { ThrowXmlException(reader, SR.XmlDuplicateAttribute, GetName(prefix1, localName), GetName(prefix2, localName), ns); } + [DoesNotReturn] public static void ThrowInvalidBinaryFormat(XmlDictionaryReader reader) { ThrowXmlException(reader, SR.XmlInvalidFormat); } + [DoesNotReturn] public static void ThrowInvalidRootData(XmlDictionaryReader reader) { ThrowXmlException(reader, SR.XmlInvalidRootData); } + [DoesNotReturn] public static void ThrowMultipleRootElements(XmlDictionaryReader reader) { ThrowXmlException(reader, SR.XmlMultipleRootElements); } + [DoesNotReturn] public static void ThrowDeclarationNotFirst(XmlDictionaryReader reader) { ThrowXmlException(reader, SR.XmlDeclNotFirst); } + [DoesNotReturn] public static void ThrowConversionOverflow(XmlDictionaryReader reader, string value, string type) { ThrowXmlException(reader, SR.XmlConversionOverflow, value, type); } + [DoesNotReturn] public static void ThrowXmlDictionaryStringIDOutOfRange(XmlDictionaryReader reader) { ThrowXmlException(reader, SR.XmlDictionaryStringIDRange, XmlDictionaryString.MinKey.ToString(NumberFormatInfo.CurrentInfo), XmlDictionaryString.MaxKey.ToString(NumberFormatInfo.CurrentInfo)); } + [DoesNotReturn] public static void ThrowXmlDictionaryStringIDUndefinedStatic(XmlDictionaryReader reader, int key) { ThrowXmlException(reader, SR.XmlDictionaryStringIDUndefinedStatic, key.ToString(NumberFormatInfo.CurrentInfo)); } + [DoesNotReturn] public static void ThrowXmlDictionaryStringIDUndefinedSession(XmlDictionaryReader reader, int key) { ThrowXmlException(reader, SR.XmlDictionaryStringIDUndefinedSession, key.ToString(NumberFormatInfo.CurrentInfo)); } + [DoesNotReturn] public static void ThrowEmptyNamespace(XmlDictionaryReader reader) { ThrowXmlException(reader, SR.XmlEmptyNamespaceRequiresNullPrefix); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlNodeWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlNodeWriter.cs index 0953ef1512f243..8cdf0455382f8d 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlNodeWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlNodeWriter.cs @@ -14,7 +14,7 @@ namespace System.Xml { internal abstract class XmlNodeWriter { - private static XmlNodeWriter s_nullNodeWriter; + private static XmlNodeWriter? s_nullNodeWriter; public static XmlNodeWriter Null { @@ -35,8 +35,8 @@ public virtual Task FlushAsync() public abstract void WriteDeclaration(); public abstract void WriteComment(string text); public abstract void WriteCData(string text); - public abstract void WriteStartElement(string prefix, string localName); - public virtual Task WriteStartElementAsync(string prefix, string localName) + public abstract void WriteStartElement(string? prefix, string localName); + public virtual Task WriteStartElementAsync(string? prefix, string localName) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(NotImplemented.ByDesign); } @@ -44,14 +44,14 @@ public virtual void WriteStartElement(byte[] prefixBuffer, int prefixOffset, int { WriteStartElement(Encoding.UTF8.GetString(prefixBuffer, prefixOffset, prefixLength), Encoding.UTF8.GetString(localNameBuffer, localNameOffset, localNameLength)); } - public abstract void WriteStartElement(string prefix, XmlDictionaryString localName); + public abstract void WriteStartElement(string? prefix, XmlDictionaryString localName); public abstract void WriteEndStartElement(bool isEmpty); public virtual Task WriteEndStartElementAsync(bool isEmpty) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(NotImplemented.ByDesign); } - public abstract void WriteEndElement(string prefix, string localName); - public virtual Task WriteEndElementAsync(string prefix, string localName) + public abstract void WriteEndElement(string? prefix, string localName); + public virtual Task WriteEndElementAsync(string? prefix, string localName) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(NotImplemented.ByDesign); } @@ -59,12 +59,12 @@ public virtual void WriteEndElement(byte[] prefixBuffer, int prefixOffset, int p { WriteEndElement(Encoding.UTF8.GetString(prefixBuffer, prefixOffset, prefixLength), Encoding.UTF8.GetString(localNameBuffer, localNameOffset, localNameLength)); } - public abstract void WriteXmlnsAttribute(string prefix, string ns); + public abstract void WriteXmlnsAttribute(string? prefix, string ns); public virtual void WriteXmlnsAttribute(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] nsBuffer, int nsOffset, int nsLength) { WriteXmlnsAttribute(Encoding.UTF8.GetString(prefixBuffer, prefixOffset, prefixLength), Encoding.UTF8.GetString(nsBuffer, nsOffset, nsLength)); } - public abstract void WriteXmlnsAttribute(string prefix, XmlDictionaryString ns); + public abstract void WriteXmlnsAttribute(string? prefix, XmlDictionaryString ns); public abstract void WriteStartAttribute(string prefix, string localName); public virtual void WriteStartAttribute(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] localNameBuffer, int localNameOffset, int localNameLength) { @@ -113,15 +113,15 @@ public override void Close() { } public override void WriteDeclaration() { } public override void WriteComment(string text) { } public override void WriteCData(string text) { } - public override void WriteStartElement(string prefix, string localName) { } + public override void WriteStartElement(string? prefix, string localName) { } public override void WriteStartElement(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] localNameBuffer, int localNameOffset, int localNameLength) { } - public override void WriteStartElement(string prefix, XmlDictionaryString localName) { } + public override void WriteStartElement(string? prefix, XmlDictionaryString localName) { } public override void WriteEndStartElement(bool isEmpty) { } - public override void WriteEndElement(string prefix, string localName) { } + public override void WriteEndElement(string? prefix, string localName) { } public override void WriteEndElement(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] localNameBuffer, int localNameOffset, int localNameLength) { } - public override void WriteXmlnsAttribute(string prefix, string ns) { } + public override void WriteXmlnsAttribute(string? prefix, string ns) { } public override void WriteXmlnsAttribute(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] nsBuffer, int nsOffset, int nsLength) { } - public override void WriteXmlnsAttribute(string prefix, XmlDictionaryString ns) { } + public override void WriteXmlnsAttribute(string? prefix, XmlDictionaryString ns) { } public override void WriteStartAttribute(string prefix, string localName) { } public override void WriteStartAttribute(byte[] prefixBuffer, int prefixOffset, int prefixLength, byte[] localNameBuffer, int localNameOffset, int localNameLength) { } public override void WriteStartAttribute(string prefix, XmlDictionaryString localName) { } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlSigningNodeWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlSigningNodeWriter.cs index d6f05b635c127f..fb539d2ac2ba10 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlSigningNodeWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlSigningNodeWriter.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.IO; using System.Text; @@ -8,10 +9,10 @@ namespace System.Xml { internal class XmlSigningNodeWriter : XmlNodeWriter { - private XmlNodeWriter _writer; - private XmlCanonicalWriter _signingWriter; - private byte[] _chars; - private byte[] _base64Chars; + private XmlNodeWriter _writer = null!; // initialized by SetOutput + private XmlCanonicalWriter _signingWriter = null!; // initialized by SetOutput + private byte[] _chars = null!; // initialized by SetOutput + private byte[]? _base64Chars; private readonly bool _text; public XmlSigningNodeWriter(bool text) @@ -19,7 +20,7 @@ public XmlSigningNodeWriter(bool text) _text = text; } - public void SetOutput(XmlNodeWriter writer, Stream stream, bool includeComments, string[] inclusivePrefixes) + public void SetOutput(XmlNodeWriter writer, Stream stream, bool includeComments, string[]? inclusivePrefixes) { _writer = writer; if (_signingWriter == null) @@ -79,8 +80,9 @@ public override void WriteCData(string text) _signingWriter.WriteEscapedText(text); } - public override void WriteStartElement(string prefix, string localName) + public override void WriteStartElement(string? prefix, string localName) { + Debug.Assert(prefix != null); _writer.WriteStartElement(prefix, localName); _signingWriter.WriteStartElement(prefix, localName); } @@ -92,8 +94,9 @@ public override void WriteStartElement(byte[] prefixBuffer, int prefixOffset, in _signingWriter.WriteStartElement(prefixBuffer, prefixOffset, prefixLength, localNameBuffer, localNameOffset, localNameLength); } - public override void WriteStartElement(string prefix, XmlDictionaryString localName) + public override void WriteStartElement(string? prefix, XmlDictionaryString localName) { + Debug.Assert(prefix != null); _writer.WriteStartElement(prefix, localName); _signingWriter.WriteStartElement(prefix, localName.Value); } @@ -104,14 +107,16 @@ public override void WriteEndStartElement(bool isEmpty) _signingWriter.WriteEndStartElement(isEmpty); } - public override void WriteEndElement(string prefix, string localName) + public override void WriteEndElement(string? prefix, string localName) { + Debug.Assert(prefix != null); _writer.WriteEndElement(prefix, localName); _signingWriter.WriteEndElement(prefix, localName); } - public override void WriteXmlnsAttribute(string prefix, string ns) + public override void WriteXmlnsAttribute(string? prefix, string ns) { + Debug.Assert(prefix != null); _writer.WriteXmlnsAttribute(prefix, ns); _signingWriter.WriteXmlnsAttribute(prefix, ns); } @@ -123,8 +128,9 @@ public override void WriteXmlnsAttribute(byte[] prefixBuffer, int prefixOffset, _signingWriter.WriteXmlnsAttribute(prefixBuffer, prefixOffset, prefixLength, nsBuffer, nsOffset, nsLength); } - public override void WriteXmlnsAttribute(string prefix, XmlDictionaryString ns) + public override void WriteXmlnsAttribute(string? prefix, XmlDictionaryString ns) { + Debug.Assert(prefix != null); _writer.WriteXmlnsAttribute(prefix, ns); _signingWriter.WriteXmlnsAttribute(prefix, ns.Value); } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlStreamNodeWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlStreamNodeWriter.cs index 39f47f5b828eba..6075d0a9c608e6 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlStreamNodeWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlStreamNodeWriter.cs @@ -10,13 +10,13 @@ namespace System.Xml { internal abstract class XmlStreamNodeWriter : XmlNodeWriter { - private Stream _stream; + private Stream _stream = null!; // initialized by SetOutput private readonly byte[] _buffer; private int _offset; private bool _ownsStream; private const int bufferLength = 512; private const int maxBytesPerChar = 3; - private Encoding _encoding; + private Encoding? _encoding; private static readonly UTF8Encoding s_UTF8Encoding = new UTF8Encoding(false, true); protected XmlStreamNodeWriter() @@ -24,7 +24,7 @@ protected XmlStreamNodeWriter() _buffer = new byte[bufferLength]; } - protected void SetOutput(Stream stream, bool ownsStream, Encoding encoding) + protected void SetOutput(Stream stream, bool ownsStream, Encoding? encoding) { _stream = stream; _ownsStream = ownsStream; @@ -462,7 +462,7 @@ public override void Close() { _stream.Dispose(); } - _stream = null; + _stream = null!; } } } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextReader.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextReader.cs index b851af7a0373e4..7d300f1451e7a2 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextReader.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextReader.cs @@ -17,8 +17,8 @@ namespace System.Xml { public interface IXmlTextReaderInitializer { - void SetInput(byte[] buffer, int offset, int count, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose); - void SetInput(Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose); + void SetInput(byte[] buffer, int offset, int count, Encoding? encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose? onClose); + void SetInput(Stream stream, Encoding? encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose? onClose); } internal class XmlUTF8TextReader : XmlBaseReader, IXmlLineInfo, IXmlTextReaderInitializer @@ -27,8 +27,8 @@ internal class XmlUTF8TextReader : XmlBaseReader, IXmlLineInfo, IXmlTextReaderIn private readonly PrefixHandle _prefix; private readonly StringHandle _localName; - private int[] _rowOffsets; - private OnXmlDictionaryReaderClose _onClose; + private int[]? _rowOffsets; + private OnXmlDictionaryReaderClose? _onClose; private bool _buffered; private int _maxBytesPerRead; private static readonly byte[] s_charType = new byte[256] @@ -553,7 +553,7 @@ public XmlUTF8TextReader() _localName = new StringHandle(BufferReader); } - public void SetInput(byte[] buffer, int offset, int count, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose) + public void SetInput(byte[] buffer, int offset, int count, Encoding? encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose? onClose) { if (buffer == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException(nameof(buffer))); @@ -567,11 +567,11 @@ public void SetInput(byte[] buffer, int offset, int count, Encoding encoding, Xm throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentOutOfRangeException(nameof(count), SR.Format(SR.SizeExceedsRemainingBufferSpace, buffer.Length - offset))); MoveToInitial(quotas, onClose); ArraySegment seg = EncodingStreamWrapper.ProcessBuffer(buffer, offset, count, encoding); - BufferReader.SetBuffer(seg.Array, seg.Offset, seg.Count, null, null); + BufferReader.SetBuffer(seg.Array!, seg.Offset, seg.Count, null, null); _buffered = true; } - public void SetInput(Stream stream, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose) + public void SetInput(Stream stream, Encoding? encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose? onClose) { if (stream == null) throw System.Runtime.Serialization.DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(stream)); @@ -581,7 +581,7 @@ public void SetInput(Stream stream, Encoding encoding, XmlDictionaryReaderQuotas _buffered = false; } - private void MoveToInitial(XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose) + private void MoveToInitial(XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose? onClose) { MoveToInitial(quotas); _maxBytesPerRead = quotas.MaxBytesPerRead; @@ -592,7 +592,7 @@ public override void Close() { _rowOffsets = null; base.Close(); - OnXmlDictionaryReaderClose onClose = _onClose; + OnXmlDictionaryReaderClose? onClose = _onClose; _onClose = null; if (onClose != null) { diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextWriter.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextWriter.cs index 55977570f64f87..22e4d66296e80c 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextWriter.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Xml/XmlUTF8TextWriter.cs @@ -14,7 +14,7 @@ public interface IXmlTextWriterInitializer internal class XmlUTF8TextWriter : XmlBaseWriter, IXmlTextWriterInitializer { - private XmlUTF8NodeWriter _writer; + private XmlUTF8NodeWriter? _writer; public void SetOutput(Stream stream, Encoding encoding, bool ownsStream) { @@ -43,14 +43,14 @@ protected override XmlSigningNodeWriter CreateSigningNodeWriter() internal class XmlUTF8NodeWriter : XmlStreamNodeWriter { - private byte[] _entityChars; + private byte[]? _entityChars; private readonly bool[] _isEscapedAttributeChar; private readonly bool[] _isEscapedElementChar; private bool _inAttribute; private const int bufferLength = 512; private const int maxEntityLength = 32; - private Encoding _encoding; - private char[] _chars; + private Encoding? _encoding; + private char[]? _chars; private static readonly byte[] s_startDecl = { @@ -101,9 +101,9 @@ public XmlUTF8NodeWriter(bool[] isEscapedAttributeChar, bool[] isEscapedElementC _inAttribute = false; } - public new void SetOutput(Stream stream, bool ownsStream, Encoding encoding) + public new void SetOutput(Stream stream, bool ownsStream, Encoding? encoding) { - Encoding utf8Encoding = null; + Encoding? utf8Encoding = null; if (encoding != null && encoding.CodePage == Encoding.UTF8.CodePage) { utf8Encoding = encoding; @@ -203,10 +203,10 @@ public override void WriteComment(string text) WriteEndComment(); } - public override void WriteStartElement(string prefix, string localName) + public override void WriteStartElement(string? prefix, string localName) { WriteByte('<'); - if (prefix.Length != 0) + if (!string.IsNullOrEmpty(prefix)) { WritePrefix(prefix); WriteByte(':'); @@ -214,10 +214,10 @@ public override void WriteStartElement(string prefix, string localName) WriteLocalName(localName); } - public override async Task WriteStartElementAsync(string prefix, string localName) + public override async Task WriteStartElementAsync(string? prefix, string localName) { await WriteByteAsync('<').ConfigureAwait(false); - if (prefix.Length != 0) + if (!string.IsNullOrEmpty(prefix)) { // This method calls into unsafe method which cannot run asyncly. WritePrefix(prefix); @@ -228,7 +228,7 @@ public override async Task WriteStartElementAsync(string prefix, string localNam WriteLocalName(localName); } - public override void WriteStartElement(string prefix, XmlDictionaryString localName) + public override void WriteStartElement(string? prefix, XmlDictionaryString localName) { WriteStartElement(prefix, localName.Value); } @@ -268,10 +268,10 @@ public override async Task WriteEndStartElementAsync(bool isEmpty) } } - public override void WriteEndElement(string prefix, string localName) + public override void WriteEndElement(string? prefix, string localName) { WriteBytes('<', '/'); - if (prefix.Length != 0) + if (!string.IsNullOrEmpty(prefix)) { WritePrefix(prefix); WriteByte(':'); @@ -280,10 +280,10 @@ public override void WriteEndElement(string prefix, string localName) WriteByte('>'); } - public override async Task WriteEndElementAsync(string prefix, string localName) + public override async Task WriteEndElementAsync(string? prefix, string localName) { await WriteBytesAsync('<', '/').ConfigureAwait(false); - if (prefix.Length != 0) + if (!string.IsNullOrEmpty(prefix)) { WritePrefix(prefix); await WriteByteAsync(':').ConfigureAwait(false); @@ -318,10 +318,10 @@ private void WriteStartXmlnsAttribute() _inAttribute = true; } - public override void WriteXmlnsAttribute(string prefix, string ns) + public override void WriteXmlnsAttribute(string? prefix, string ns) { WriteStartXmlnsAttribute(); - if (prefix.Length != 0) + if (!string.IsNullOrEmpty(prefix)) { WriteByte(':'); WritePrefix(prefix); @@ -331,7 +331,7 @@ public override void WriteXmlnsAttribute(string prefix, string ns) WriteEndAttribute(); } - public override void WriteXmlnsAttribute(string prefix, XmlDictionaryString ns) + public override void WriteXmlnsAttribute(string? prefix, XmlDictionaryString ns) { WriteXmlnsAttribute(prefix, ns.Value); } 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..d86a6cb380a7b1 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,7 +300,8 @@ public static explicit operator int(XAttribute attribute) /// The content of this as an ?. /// [CLSCompliant(false)] - public static explicit operator int?(XAttribute attribute) + [return: NotNullIfNotNull("attribute")] + public static explicit operator int?(XAttribute? attribute) { if (attribute == null) return null; return XmlConvert.ToInt32(attribute.value); @@ -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/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 752e156d1a2303..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; @@ -278,7 +277,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 +800,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/XmlAsyncCheckWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Core/XmlAsyncCheckWriter.cs index 84990c82955ed0..d96b1b1621dbbb 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; @@ -433,7 +432,7 @@ public override Task WriteCommentAsync(string? text) return task; } - public override Task WriteProcessingInstructionAsync(string name, string text) + public override Task WriteProcessingInstructionAsync(string name, string? text) { CheckAsync(); var task = _coreWriter.WriteProcessingInstructionAsync(name, text); 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..0c6d854e23c87b 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; @@ -138,7 +137,7 @@ public override Task WriteCommentAsync(string? text) return writer.WriteCommentAsync(text); } - public override Task WriteProcessingInstructionAsync(string name, string text) + public override Task WriteProcessingInstructionAsync(string name, string? text) { if (_checkNames) { 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 36abf85f126cf5..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; @@ -378,7 +377,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..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; @@ -48,7 +47,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/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 d00bc27d68c69b..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; @@ -799,7 +798,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..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; @@ -214,7 +213,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/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..f602537d520e81 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; @@ -808,7 +807,7 @@ public override async Task WriteCommentAsync(string? text) } } - public override async Task WriteProcessingInstructionAsync(string name, string text) + public override async Task WriteProcessingInstructionAsync(string name, string? text) { try { 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..6edd2b7e956a0c 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; @@ -69,7 +68,7 @@ public override Task WriteCommentAsync(string? text) return writer.WriteCommentAsync(text); } - public override Task WriteProcessingInstructionAsync(string name, string text) + public override Task WriteProcessingInstructionAsync(string name, string? text) { return writer.WriteProcessingInstructionAsync(name, text); } 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..222b6e7c74d638 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; @@ -100,7 +99,7 @@ public void WriteStartElement(string localName) public abstract void WriteFullEndElement(); // Writes out the attribute with the specified LocalName, value, and NamespaceURI. - public void WriteAttributeString(string localName, string? ns, string value) + public void WriteAttributeString(string localName, string? ns, string? value) { WriteStartAttribute(null, localName, ns); WriteString(value); @@ -108,7 +107,7 @@ public void WriteAttributeString(string localName, string? ns, string value) } // Writes out the attribute with the specified LocalName and value. - public void WriteAttributeString(string localName, string value) + public void WriteAttributeString(string localName, string? value) { WriteStartAttribute(null, localName, (string?)null); WriteString(value); 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..d88d1123fcbcb0 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; @@ -71,7 +70,7 @@ public virtual Task WriteFullEndElementAsync() } // Writes out the attribute with the specified prefix, LocalName, NamespaceURI and value. - public Task WriteAttributeStringAsync(string? prefix, string localName, string? ns, string value) + public Task WriteAttributeStringAsync(string? prefix, string localName, string? ns, string? value) { Task task = WriteStartAttributeAsync(prefix, localName, ns); if (task.IsSuccess()) @@ -84,7 +83,7 @@ public Task WriteAttributeStringAsync(string? prefix, string localName, string? } } - private async Task WriteAttributeStringAsyncHelper(Task task, string value) + private async Task WriteAttributeStringAsyncHelper(Task task, string? value) { await task.ConfigureAwait(false); await WriteStringAsync(value).ConfigureAwait(false); @@ -121,7 +120,7 @@ public virtual Task WriteCommentAsync(string? text) // Writes out a processing instruction with a space between the name and text as follows: - public virtual Task WriteProcessingInstructionAsync(string name, string text) + public virtual Task WriteProcessingInstructionAsync(string name, string? text) { throw new NotImplementedException(); } 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 cc0b4053e85d9d..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; @@ -728,7 +727,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..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; @@ -74,7 +73,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/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..15193b42b73c91 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,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.Xml.Schema; using System.Xml.XPath; using System.Collections; using System.Diagnostics; using System.Globalization; +using System.Diagnostics.CodeAnalysis; namespace System.Xml { @@ -278,7 +278,7 @@ public virtual string GetAttribute(string name) // Sets the value of the attribute // with the specified name. - public virtual void SetAttribute(string name, string value) + public virtual void SetAttribute(string name, string? value) { XmlAttribute? attr = GetAttributeNode(name); if (attr == null) @@ -309,7 +309,7 @@ public virtual void RemoveAttribute(string name) } // Adds the specified XmlAttribute. - public virtual XmlAttribute SetAttributeNode(XmlAttribute newAttr) + public virtual XmlAttribute? SetAttributeNode(XmlAttribute newAttr) { if (newAttr.OwnerElement != null) throw new InvalidOperationException(SR.Xdom_Attr_InUse); @@ -348,7 +348,8 @@ public virtual string GetAttribute(string localName, string? namespaceURI) // Sets the value of the attribute with the specified name // and namespace. - public virtual string SetAttribute(string localName, string? namespaceURI, string value) + [return: NotNullIfNotNull("value")] + public virtual string? SetAttribute(string localName, string? namespaceURI, string? value) { XmlAttribute? attr = GetAttributeNode(localName, namespaceURI); if (attr == null) 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..d296f922b255b2 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; @@ -244,10 +243,10 @@ public bool ParseReaderNode() { Debug.Assert(_parentNode != null); XmlNodeList list = _parentNode.ChildNodes; - XmlNode[] markup = new XmlNode[list.Count]; + XmlNode?[] markup = new XmlNode[list.Count]; for (int i = 0; i < list.Count; i++) { - markup[i] = list[i]!; + markup[i] = list[i]; } _builder!.ProcessMarkup(markup); 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..19451021c19d89 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 @@ -9,7 +8,7 @@ internal abstract class SchemaBuilder internal abstract bool ProcessElement(string prefix, string name, string ns); internal abstract void ProcessAttribute(string prefix, string name, string ns, string value); internal abstract bool IsContentParsed(); - internal abstract void ProcessMarkup(XmlNode[] markup); + internal abstract void ProcessMarkup(XmlNode?[] markup); internal abstract void ProcessCData(string value); internal abstract void StartChildren(); internal abstract void EndChildren(); 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 d64c131d28b13c..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; @@ -24,7 +23,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 +43,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/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..113692da560233 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; @@ -562,7 +561,7 @@ internal override bool IsContentParsed() return true; } - internal override void ProcessMarkup(XmlNode[] markup) + internal override void ProcessMarkup(XmlNode?[] markup) { throw new InvalidOperationException(SR.Xml_InvalidOperation); // should never be called } 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 f6b46e8e5179dd..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; @@ -56,17 +55,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 +135,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 +145,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 +165,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 +173,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/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..0434edf08b908e 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; @@ -10,7 +9,7 @@ namespace System.Xml.Schema public class XmlSchemaAppInfo : XmlSchemaObject { private string? _source; - private XmlNode[]? _markup; + private XmlNode?[]? _markup; [XmlAttribute("source", DataType = "anyURI")] public string? Source @@ -20,7 +19,7 @@ public string? Source } [XmlText, XmlAnyElement] - public XmlNode[]? Markup + public XmlNode?[]? Markup { get { return _markup; } set { _markup = value; } 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..2e4046baa6f171 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; @@ -13,7 +12,7 @@ public class XmlSchemaDocumentation : XmlSchemaObject { private string? _source; private string? _language; - private XmlNode[]? _markup; + private XmlNode?[]? _markup; private static readonly XmlSchemaSimpleType s_languageType = DatatypeImplementation.GetSimpleTypeFromXsdType(new XmlQualifiedName("language", XmlReservedNs.NsXs))!; [XmlAttribute("source", DataType = "anyURI")] @@ -32,7 +31,7 @@ public string? Language } [XmlText, XmlAnyElement] - public XmlNode[]? Markup + public XmlNode?[]? Markup { get { return _markup; } set { _markup = value; } 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..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; @@ -112,6 +111,7 @@ internal bool HasAbstractAttribute } [XmlAttribute("ref")] + [AllowNull] public XmlQualifiedName RefName { get { return _refName; } @@ -119,6 +119,7 @@ public XmlQualifiedName RefName } [XmlAttribute("substitutionGroup")] + [AllowNull] public XmlQualifiedName SubstitutionGroup { get { return _substitutionGroup; } @@ -126,6 +127,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/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 b1bb09829fca6a..4f9ac921ea1c6c 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; @@ -676,7 +675,7 @@ public BuilderNamespaceManager(XmlNamespaceManager nsMgr, XmlReader reader) private XmlSchemaAppInfo? _appInfo; private XmlSchemaDocumentation? _documentation; private XmlSchemaFacet? _facet; - private XmlNode[]? _markup; + private XmlNode?[]? _markup; private XmlSchemaRedefine? _redefine; private readonly ValidationEventHandler? _validationEventHandler; @@ -779,7 +778,7 @@ internal override bool IsContentParsed() return _currentEntry.ParseContent; } - internal override void ProcessMarkup(XmlNode[] markup) + internal override void ProcessMarkup(XmlNode?[] markup) { _markup = markup; } @@ -795,7 +794,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/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/CodeGenerator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeGenerator.cs index 14cd6dbdbd685f..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 @@ -32,14 +32,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 +85,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 +94,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 +121,7 @@ internal MethodBuilder EndMethod() return retVal; } - internal MethodBuilder MethodBuilder + internal MethodBuilder? MethodBuilder { get { return _methodBuilder; } } @@ -135,17 +135,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 +157,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 +178,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 +217,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 +248,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 +260,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 +278,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 +310,7 @@ internal void EndFor() "get_Count", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; Call(ICollection_get_Count); } Blt(forState.BeginLabel); @@ -348,11 +348,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 +366,7 @@ internal void Else() MarkLabel(ifState.ElseBegin); ifState.ElseBegin = ifState.EndIf; - _blockStack.Push(ifState); + _blockStack!.Push(ifState); } internal void EndIf() @@ -381,60 +381,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 +452,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 +484,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 +524,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 +545,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 +562,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 +583,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 +609,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 +622,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 +635,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 +670,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 +716,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 +748,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 +767,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 +814,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 +827,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 +842,7 @@ internal void Ldc(object o) null, new Type[] { typeof(long) }, null - ); + )!; Ldc(((TimeSpan)o).Ticks); // ticks New(TimeSpan_ctor); break; @@ -859,40 +859,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 +905,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 +928,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 +964,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 +974,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 +1022,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 +1067,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 +1140,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 +1185,7 @@ private void InternalConvert(Type source, Type target, bool isAddress) } else { - _ilGen.Emit(opCode); + _ilGen!.Emit(opCode); } } else if (source.IsAssignableFrom(target)) @@ -1224,8 +1224,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 +1250,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 +1264,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 +1278,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 +1299,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 +1311,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 +1352,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 +1366,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 +1393,7 @@ internal void WhileBeginCondition() internal void WhileEndCondition() { - WhileState whileState = _whileStack.Peek(); + WhileState whileState = _whileStack!.Peek(); Brtrue(whileState.StartLabel); } } @@ -1502,7 +1502,7 @@ internal Label ElseBegin internal class LocalScope { - public readonly LocalScope parent; + public readonly LocalScope? parent; private readonly Dictionary _locals; // Root scope @@ -1511,7 +1511,7 @@ public LocalScope() _locals = new Dictionary(); } - public LocalScope(LocalScope parent) : this() + public LocalScope(LocalScope? parent) : this() { this.parent = parent; } @@ -1521,7 +1521,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 +1538,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 +1558,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 +1585,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..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 @@ -9,6 +9,7 @@ using System.Diagnostics; using System.Reflection; using System.Runtime.InteropServices; +using System.Diagnostics.CodeAnalysis; namespace System.Xml.Serialization { @@ -162,10 +163,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 +216,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 +270,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..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 @@ -14,14 +14,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 +131,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 +149,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..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 @@ -10,40 +10,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 +105,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 +119,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 +137,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 +155,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 +180,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 +200,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 +234,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 +269,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 +296,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 +322,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 +330,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 +338,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 +353,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 +372,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 +386,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 +398,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 +420,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 +435,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 +464,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 +479,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 +511,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 +526,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 +549,7 @@ private string ValidateEncodingStyle(string encodingStyle, string methodKey) } else { - if (_methods[methodKey].isSoap) + if (_methods![methodKey].isSoap) { encodingStyle = Soap.Encoding; } @@ -555,28 +557,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 +591,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 +632,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 +659,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..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 @@ -26,7 +26,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 +35,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 +76,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 +95,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/IXmlSerializable.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/IXmlSerializable.cs index 7dcea55f073831..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 @@ -12,7 +12,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/ImportContext.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ImportContext.cs index 79cedd9bb3bd3a..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 @@ -15,16 +15,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 +81,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 +127,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 +135,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 +144,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 +155,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 +171,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 +187,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 +205,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 +221,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 +280,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 +302,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 +312,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 +321,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 +367,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 +377,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 +395,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 +433,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 +454,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 +470,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 +482,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 +500,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 +511,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..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 @@ -11,6 +11,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 +19,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 +32,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 +49,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 +62,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 +98,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 +120,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 +182,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 +281,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 +300,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 +336,7 @@ internal bool IsReference set { _reference = value; } } + [MemberNotNullWhen(false, nameof(_typeName))] internal bool IsAnonymousType { get { return _typeName == null || _typeName.Length == 0; } @@ -338,7 +344,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 +361,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 +371,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 +404,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 +419,7 @@ internal StructMapping TopLevelMapping internal class EnumMapping : PrimitiveMapping { - private ConstantMapping[] _constants; + private ConstantMapping[]? _constants; private bool _isFlags; internal bool IsFlags @@ -422,7 +428,7 @@ internal bool IsFlags set { _isFlags = value; } } - internal ConstantMapping[] Constants + internal ConstantMapping[]? Constants { get { return _constants; } set { _constants = value; } @@ -431,16 +437,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 +464,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 +491,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 +502,7 @@ internal StructMapping BaseMapping } } - internal StructMapping DerivedMappings + internal StructMapping? DerivedMappings { get { return _derivedMappings; } } @@ -521,11 +530,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 +546,7 @@ internal NameTable LocalAttributes LocalElements[name, ns] = value; } } - internal StructMapping NextDerivedMapping + internal StructMapping? NextDerivedMapping { get { return _nextDerivedMapping; } } @@ -551,7 +560,7 @@ internal bool HasXmlnsMember { get { - StructMapping mapping = this; + StructMapping? mapping = this; while (mapping != null) { if (mapping.XmlnsMember != null) @@ -562,13 +571,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 +600,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 +615,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 +626,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 +654,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 +677,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 +695,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 +742,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 +767,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 +783,7 @@ public int Compare(object o1, object o2) } } - internal ElementAccessor[] ElementsSortedByDerivation + internal ElementAccessor[]? ElementsSortedByDerivation { get { @@ -789,19 +798,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 +822,7 @@ internal bool Ignore set { _ignore = value; } } - internal Accessor Accessor + internal Accessor? Accessor { get { @@ -824,7 +833,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 +882,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 +913,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 +957,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 +1001,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 +1018,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 +1068,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 +1103,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 +1112,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 +1162,7 @@ internal string NamespaceList } } - internal SerializableMapping DerivedMappings + internal SerializableMapping? DerivedMappings { get { @@ -1161,7 +1170,7 @@ internal SerializableMapping DerivedMappings } } - internal SerializableMapping NextDerivedMapping + internal SerializableMapping? NextDerivedMapping { get { @@ -1169,19 +1178,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 +1199,7 @@ internal XmlSchemaSet Schemas } } - internal XmlSchema Schema + internal XmlSchema? Schema { get { @@ -1199,7 +1208,7 @@ internal XmlSchema Schema } } - internal XmlQualifiedName XsiType + internal XmlQualifiedName? XsiType { get { @@ -1214,7 +1223,7 @@ internal XmlQualifiedName XsiType } } - internal XmlSchemaType XsdType + internal XmlSchemaType? XsdType { get { @@ -1223,14 +1232,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 +1248,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 +1269,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 +1307,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 +1323,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 +1356,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 +1374,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..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 @@ -37,7 +37,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 +72,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 +122,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 +168,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 +183,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 +193,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 +212,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 +232,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 +250,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 +280,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 +295,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 +345,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 +398,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 +413,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 +422,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..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 @@ -10,16 +10,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 +33,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 +62,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 +74,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..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 @@ -7,7 +7,7 @@ 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 +19,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 +30,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 +41,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 +52,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 +63,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 +74,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 +85,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 +98,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 +109,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 +120,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 +131,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 +142,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 +153,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 +164,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 +176,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 +189,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 +201,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 +212,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 +231,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 +257,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 +281,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 +305,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 +329,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 +353,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 +377,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 +401,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 +425,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 +449,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 +473,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 +497,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 +521,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 +545,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 +569,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 +598,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 +622,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 +652,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 +676,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 +705,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..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 @@ -5,6 +5,7 @@ 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 +13,7 @@ namespace System.Xml.Serialization { - internal delegate void UnknownNodeAction(object o); + internal delegate void UnknownNodeAction(object? o); internal class ReflectionXmlSerializationReader : XmlSerializationReader { @@ -21,7 +22,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 +30,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 +50,7 @@ protected override void InitIDs() { } - public object ReadObject() + public object? ReadObject() { XmlMapping xmlMapping = _mapping; if (!xmlMapping.IsReadable) @@ -87,7 +88,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 +98,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 +128,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 +142,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 +199,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 +225,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 +252,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 +278,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 +315,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 +331,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 +342,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 +377,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 +427,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 +452,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 +481,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 +494,7 @@ private void WriteMemberElements(Member[] expectedMembers, UnknownNodeAction ele return; } - WriteMemberElementsCheckType(checkTypeHrefsSource); + WriteMemberElementsCheckType(checkTypeHrefsSource!); } else { @@ -511,7 +512,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 +533,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 +544,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 +555,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 +570,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 +610,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 +628,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 +638,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 +654,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 +675,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 +688,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 +699,7 @@ private bool WriteMemberText(Member anyText) } } - anyText.Source(value); + anyText.Source!(value); return true; } @@ -713,7 +714,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 +725,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 +738,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 +782,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 +802,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 +822,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 +833,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 +885,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 +902,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 +916,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 +925,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 +945,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 +958,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 +983,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 +998,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 +1012,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 +1047,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 +1084,7 @@ private object WriteArray(ArrayMapping arrayMapping, bool readOnly, bool isNulla throw new InvalidOperationException(SR.XmlInternalError); } - member.Source(rre); + member.Source!(rre); } } @@ -1100,8 +1101,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 +1151,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 +1191,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 +1210,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 +1243,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 +1272,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 +1295,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 +1317,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 +1339,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 +1357,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 +1380,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 +1396,7 @@ private Fixup WriteMemberFixupBegin(Member[] members, object o) } } - Fixup fixup; + Fixup? fixup; if (fixupCount > 0) { fixup = new Fixup(o, CreateWriteFixupMethod(members), fixupCount); @@ -1414,7 +1415,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 +1424,7 @@ private XmlSerializationFixupCallback CreateWriteFixupMethod(Member[] members) if (ids[fixupIndex] != null) { var memberValue = GetTarget(ids[fixupIndex]); - member.Source(memberValue); + member.Source!(memberValue); } } } @@ -1432,17 +1433,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 +1451,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 +1474,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 +1491,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 +1502,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 +1512,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 +1521,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 +1546,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 +1563,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 +1596,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 +1606,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 +1617,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 +1650,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 +1669,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 +1678,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 +1689,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 +1697,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 +1757,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 +1771,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 +1809,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 +1829,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 +1852,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 +1903,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 +1915,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 +1940,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 +1984,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 +1995,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 +2007,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 +2047,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 +2069,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 +2110,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..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 @@ -21,7 +21,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 +42,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 +68,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 +105,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 +117,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 +130,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 +146,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 +161,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 +182,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 +200,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 +217,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 +225,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 +249,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 +264,7 @@ private void WriteElements(object o, object enumSource, ElementAccessor[] elemen if (text != null) { - WriteText(o, text); + WriteText(o!, text); return; } @@ -279,14 +279,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 +303,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 +314,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 +339,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 +348,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 +357,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 +371,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 +381,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 +422,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 +433,7 @@ private void WriteElement(object o, ElementAccessor element, bool writeAccessor) } else { - throw CreateInvalidAnyTypeException(o); + throw CreateInvalidAnyTypeException(o!); } } } @@ -443,7 +443,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 +465,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 +495,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 +508,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 +517,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 +530,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 +554,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 +572,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 +604,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 +623,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 +641,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 +668,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 +677,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 +691,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 +701,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 +739,7 @@ private string WriteEnumMethod(EnumMapping mapping, object v) } else { - throw CreateInvalidEnumValueException(v, mapping.TypeDesc.FullName); + throw CreateInvalidEnumValueException(v, mapping.TypeDesc!.FullName); } } } @@ -749,9 +749,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 +761,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 +775,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 +804,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 +863,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 +873,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 +885,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 +901,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 +919,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 +939,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 +957,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 +1048,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 +1079,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 +1122,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 +1187,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 +1195,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 +1214,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 +1226,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 +1248,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 +1283,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 +1296,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 +1353,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 +1371,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..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 @@ -18,13 +18,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 +114,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 +123,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 +132,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..09a5bfcbc61231 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 @@ -11,14 +11,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 +30,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 +56,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 +136,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 +161,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 +211,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 +222,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 +274,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 +293,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 +316,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 +328,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 +490,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,14 +521,14 @@ 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++) { - XmlNode ai = (XmlNode)a[ia]; + XmlNode ai = (XmlNode)a[ia]!; WriteStartElement("node"); WriteAttribute("xml", "", ai.OuterXml); } @@ -535,18 +536,18 @@ 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++) { - XmlNode ai = (XmlNode)a[ia]; + XmlNode ai = (XmlNode)a[ia]!; WriteStartElement("node"); WriteAttribute("xml", "", ai.OuterXml); } @@ -554,16 +555,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 +585,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 +607,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 +622,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 +661,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 +713,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 +724,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 +742,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 +804,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 +816,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 +843,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 +871,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 +921,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 +950,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 +959,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 +1016,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 +1030,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 +1053,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 +1074,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 +1111,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 +1133,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 +1159,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 +1205,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 +1218,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 +1254,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..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 @@ -4,13 +4,14 @@ 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 +22,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..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 @@ -14,14 +14,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 +34,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 +42,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..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 @@ -20,11 +20,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 +89,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 +107,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..5aa2be39ae0f0b 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 @@ -4,29 +4,32 @@ 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() { } - public SoapElementAttribute(string elementName) + 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..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 @@ -4,11 +4,12 @@ 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 +20,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/SoapReflectionImporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapReflectionImporter.cs index 42cc5acdb9adcc..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 @@ -19,7 +19,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 +27,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 +76,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 +91,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 +129,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 +154,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 +185,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 +229,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 +256,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 +287,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 +339,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 +372,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 +386,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 +404,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 +415,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 +426,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 +443,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 +470,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 +501,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 +529,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 +543,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 +557,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 +569,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 +585,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 +595,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 +625,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 +633,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 +659,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 +704,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 +714,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..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 @@ -4,19 +4,21 @@ 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..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 @@ -4,24 +4,25 @@ 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 +34,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..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 @@ -25,16 +25,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 +45,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 +70,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 +100,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 +115,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 +171,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 +185,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 +217,7 @@ private void ConvertNullableValue(Type nullableType, Type targetType) "get_Value", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ILG.Call(Nullable_get_Value); if (targetType != null) { @@ -231,25 +231,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/TypeExtensions.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/TypeExtensions.cs index 19db82bdb3b8d4..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 @@ -10,7 +10,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..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 @@ -66,22 +66,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 +101,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 +160,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 +341,7 @@ internal bool ConstructorInaccessible get { return (_flags & TypeFlags.CtorInaccessible) != 0; } } - internal Exception Exception + internal Exception? Exception { get { return _exception; } set { _exception = value; } @@ -388,7 +388,7 @@ internal void CheckNeedConstructor() } } - internal TypeDesc ArrayElementTypeDesc + internal TypeDesc? ArrayElementTypeDesc { get { return _arrayElementTypeDesc; } set { _arrayElementTypeDesc = value; } @@ -406,7 +406,7 @@ internal TypeDesc CreateArrayTypeDesc() return _arrayTypeDesc; } - internal TypeDesc BaseTypeDesc + internal TypeDesc? BaseTypeDesc { get { return _baseTypeDesc; } set @@ -418,7 +418,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 +427,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 +656,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 +674,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 +684,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 +713,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 +725,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 +735,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 +747,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 +814,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 +887,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 +948,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 +981,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 +1012,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 +1032,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 +1044,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 +1075,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 +1112,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 +1127,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 +1150,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 +1164,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 +1180,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 +1207,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 +1239,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 +1277,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 +1299,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 +1314,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 +1326,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 +1342,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 +1384,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..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 @@ -4,7 +4,6 @@ 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..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 @@ -2,9 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; +using System.Diagnostics.CodeAnalysis; using System.Xml.Schema; - namespace System.Xml.Serialization { /// @@ -13,8 +13,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 +28,7 @@ public XmlAnyElementAttribute() /// /// [To be supplied.] /// - public XmlAnyElementAttribute(string name) + public XmlAnyElementAttribute(string? name) { _name = name; } @@ -36,7 +36,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 +46,7 @@ public XmlAnyElementAttribute(string name, string ns) /// /// [To be supplied.] /// + [AllowNull] public string Name { get { return _name == null ? string.Empty : _name; } @@ -55,7 +56,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..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 @@ -16,16 +16,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 +33,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 +41,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 +49,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 +57,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..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 @@ -2,9 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; +using System.Diagnostics.CodeAnalysis; using System.Xml.Schema; - namespace System.Xml.Serialization { /// @@ -13,8 +13,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 +29,7 @@ public XmlArrayAttribute() /// /// [To be supplied.] /// - public XmlArrayAttribute(string elementName) + public XmlArrayAttribute(string? elementName) { _elementName = elementName; } @@ -37,6 +37,7 @@ public XmlArrayAttribute(string elementName) /// /// [To be supplied.] /// + [AllowNull] public string ElementName { get { return _elementName == null ? string.Empty : _elementName; } @@ -46,7 +47,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..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 @@ -2,9 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; +using System.Diagnostics.CodeAnalysis; using System.Xml.Schema; - namespace System.Xml.Serialization { /// @@ -13,10 +13,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 +32,7 @@ public XmlArrayItemAttribute() /// /// [To be supplied.] /// - public XmlArrayItemAttribute(string elementName) + public XmlArrayItemAttribute(string? elementName) { _elementName = elementName; } @@ -40,7 +40,7 @@ public XmlArrayItemAttribute(string elementName) /// /// [To be supplied.] /// - public XmlArrayItemAttribute(Type type) + public XmlArrayItemAttribute(Type? type) { _type = type; } @@ -48,7 +48,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 +57,7 @@ public XmlArrayItemAttribute(string elementName, Type type) /// /// [To be supplied.] /// - public Type Type + public Type? Type { get { return _type; } set { _type = value; } @@ -66,6 +66,7 @@ public Type Type /// /// [To be supplied.] /// + [AllowNull] public string ElementName { get { return _elementName == null ? string.Empty : _elementName; } @@ -75,7 +76,7 @@ public string ElementName /// /// [To be supplied.] /// - public string Namespace + public string? Namespace { get { return _ns; } set { _ns = value; } @@ -90,6 +91,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..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 @@ -16,16 +16,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 +33,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 +41,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 +49,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 +57,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..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 @@ -2,9 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; +using System.Diagnostics.CodeAnalysis; using System.Xml.Schema; - namespace System.Xml.Serialization { /// @@ -13,10 +13,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 +29,7 @@ public XmlAttributeAttribute() /// /// [To be supplied.] /// - public XmlAttributeAttribute(string attributeName) + public XmlAttributeAttribute(string? attributeName) { _attributeName = attributeName; } @@ -37,7 +37,7 @@ public XmlAttributeAttribute(string attributeName) /// /// [To be supplied.] /// - public XmlAttributeAttribute(Type type) + public XmlAttributeAttribute(Type? type) { _type = type; } @@ -45,7 +45,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 +54,7 @@ public XmlAttributeAttribute(string attributeName, Type type) /// /// [To be supplied.] /// - public Type Type + public Type? Type { get { return _type; } set { _type = value; } @@ -63,6 +63,7 @@ public Type Type /// /// [To be supplied.] /// + [AllowNull] public string AttributeName { get { return _attributeName == null ? string.Empty : _attributeName; } @@ -72,7 +73,7 @@ public string AttributeName /// /// [To be supplied.] /// - public string Namespace + public string? Namespace { get { return _ns; } set { _ns = value; } @@ -81,6 +82,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..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 @@ -16,7 +16,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 +29,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 +47,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 +58,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..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 @@ -35,18 +35,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 +101,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 +195,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 +213,7 @@ public XmlElementAttributes XmlElements /// /// [To be supplied.] /// - public XmlAttributeAttribute XmlAttribute + public XmlAttributeAttribute? XmlAttribute { get { return _xmlAttribute; } set { _xmlAttribute = value; } @@ -222,7 +222,7 @@ public XmlAttributeAttribute XmlAttribute /// /// [To be supplied.] /// - public XmlEnumAttribute XmlEnum + public XmlEnumAttribute? XmlEnum { get { return _xmlEnum; } set { _xmlEnum = value; } @@ -231,7 +231,7 @@ public XmlEnumAttribute XmlEnum /// /// [To be supplied.] /// - public XmlTextAttribute XmlText + public XmlTextAttribute? XmlText { get { return _xmlText; } set { _xmlText = value; } @@ -240,7 +240,7 @@ public XmlTextAttribute XmlText /// /// [To be supplied.] /// - public XmlArrayAttribute XmlArray + public XmlArrayAttribute? XmlArray { get { return _xmlArray; } set { _xmlArray = value; } @@ -257,7 +257,7 @@ public XmlArrayItemAttributes XmlArrayItems /// /// [To be supplied.] /// - public object XmlDefaultValue + public object? XmlDefaultValue { get { return _xmlDefaultValue; } set { _xmlDefaultValue = value; } @@ -275,7 +275,7 @@ public bool XmlIgnore /// /// [To be supplied.] /// - public XmlTypeAttribute XmlType + public XmlTypeAttribute? XmlType { get { return _xmlType; } set { _xmlType = value; } @@ -284,7 +284,7 @@ public XmlTypeAttribute XmlType /// /// [To be supplied.] /// - public XmlRootAttribute XmlRoot + public XmlRootAttribute? XmlRoot { get { return _xmlRoot; } set { _xmlRoot = value; } @@ -301,13 +301,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..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 @@ -4,7 +4,7 @@ using System; using System.Xml.Schema; using System.Reflection; - +using System.Diagnostics.CodeAnalysis; namespace System.Xml.Serialization { @@ -14,8 +14,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 +27,7 @@ public XmlChoiceIdentifierAttribute() /// /// [To be supplied.] /// - public XmlChoiceIdentifierAttribute(string name) + public XmlChoiceIdentifierAttribute(string? name) { _name = name; } @@ -35,24 +35,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..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 @@ -2,9 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; +using System.Diagnostics.CodeAnalysis; using System.Xml.Schema; - namespace System.Xml.Serialization { /// @@ -13,10 +13,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 +32,7 @@ public XmlElementAttribute() /// /// [To be supplied.] /// - public XmlElementAttribute(string elementName) + public XmlElementAttribute(string? elementName) { _elementName = elementName; } @@ -40,7 +40,7 @@ public XmlElementAttribute(string elementName) /// /// [To be supplied.] /// - public XmlElementAttribute(Type type) + public XmlElementAttribute(Type? type) { _type = type; } @@ -48,7 +48,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 +57,7 @@ public XmlElementAttribute(string elementName, Type type) /// /// [To be supplied.] /// - public Type Type + public Type? Type { get { return _type; } set { _type = value; } @@ -66,6 +66,7 @@ public Type Type /// /// [To be supplied.] /// + [AllowNull] public string ElementName { get { return _elementName == null ? string.Empty : _elementName; } @@ -75,7 +76,7 @@ public string ElementName /// /// [To be supplied.] /// - public string Namespace + public string? Namespace { get { return _ns; } set { _ns = value; } @@ -84,6 +85,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..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 @@ -16,16 +16,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 +33,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 +41,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 +49,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 +57,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..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 @@ -3,7 +3,6 @@ using System; - namespace System.Xml.Serialization { /// @@ -12,7 +11,7 @@ namespace System.Xml.Serialization [AttributeUsage(AttributeTargets.Field)] public class XmlEnumAttribute : System.Attribute { - private string _name; + private string? _name; /// /// [To be supplied.] @@ -24,7 +23,7 @@ public XmlEnumAttribute() /// /// [To be supplied.] /// - public XmlEnumAttribute(string name) + public XmlEnumAttribute(string? name) { _name = name; } @@ -32,7 +31,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..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 @@ -3,7 +3,6 @@ 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..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 @@ -3,7 +3,6 @@ using System; - namespace System.Xml.Serialization { /// @@ -12,12 +11,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 +24,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..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 @@ -7,7 +7,6 @@ using System.Reflection; using System.Xml.Serialization; - namespace System.Xml.Serialization { [Flags] @@ -24,19 +23,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 +48,7 @@ internal ElementAccessor Accessor get { return _accessor; } } - internal TypeScope Scope + internal TypeScope? Scope { get { return _scope; } } @@ -73,7 +72,7 @@ public string XsdElementName /// /// [To be supplied.] /// - public string Namespace + public string? Namespace { get { return _accessor.Namespace; } } @@ -101,27 +100,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 +129,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..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 @@ -4,7 +4,6 @@ using System.Reflection; using System; - namespace System.Xml.Serialization { /// @@ -22,14 +21,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 +36,7 @@ public bool Any /// public string ElementName { - get { return Accessor.UnescapeName(Accessor.Name); } + get { return Accessor.UnescapeName(Accessor!.Name); } } /// @@ -45,15 +44,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 +66,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 +84,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..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 @@ -5,7 +5,6 @@ using System; using System.Text; - namespace System.Xml.Serialization { /// @@ -18,15 +17,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 +36,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..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 @@ -4,7 +4,6 @@ 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..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 @@ -28,16 +28,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 +57,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 +96,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 +112,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 +140,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 +148,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 +156,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 +169,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 +177,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 +186,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 +195,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 +210,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 +226,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 +237,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 +263,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 +278,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 +294,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 +307,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 +329,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 +342,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 +366,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 +421,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 +460,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 +474,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 +484,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 +505,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 +521,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 +565,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 +576,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 +623,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 +648,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 +685,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 +764,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 +817,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 +827,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 +843,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 +878,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 +910,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 +920,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 +967,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 +981,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 +1012,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 +1041,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 +1054,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 +1074,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 +1084,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 +1149,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 +1185,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 +1198,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 +1214,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 +1291,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 +1314,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 +1347,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 +1371,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 +1381,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 +1397,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 +1407,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 +1421,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 +1436,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 +1451,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 +1463,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 +1487,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 +1523,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 +1548,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 +1556,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 +1601,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 +1620,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 +1642,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 +1777,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 +1788,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 +1845,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 +1863,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 +1885,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 +1953,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 +1970,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 +1988,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 +2021,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 +2046,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 +2071,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 +2089,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 +2105,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 +2148,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 +2190,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 +2200,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 +2219,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 +2232,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 +2270,7 @@ internal ImportStructWorkItem this[int index] { get { - return (ImportStructWorkItem)_list[index]; + return (ImportStructWorkItem)_list[index]!; } set { @@ -2316,7 +2316,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..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 @@ -4,7 +4,6 @@ using System; using System.Xml.Serialization; - namespace System.Xml.Serialization { /// @@ -13,8 +12,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 +22,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..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 @@ -6,6 +6,7 @@ //------------------------------------------------------------------------------ using System; +using System.Diagnostics.CodeAnalysis; using System.Xml.Schema; @@ -17,9 +18,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 +51,7 @@ public string ElementName /// /// [To be supplied.] /// - public string Namespace + public string? Namespace { get { return _ns; } set { _ns = value; } @@ -59,6 +60,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..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 @@ -22,7 +22,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 +34,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 +65,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 +73,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 +82,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 +91,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 +114,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 +132,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 +164,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 +181,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 +215,7 @@ public string ExportAnyType(XmlMembersMapping members) } } - private void CheckScope(TypeScope scope) + private void CheckScope(TypeScope? scope) { if (_scope == null) { @@ -227,15 +227,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 +247,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 +278,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 +304,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 +322,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 +332,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 +340,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 +356,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 +371,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 +402,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 +419,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 +482,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 +512,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 +551,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 +576,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 +586,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 +598,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 +610,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 +623,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 +658,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 +677,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 +691,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 +717,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 +730,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 +739,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 +747,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 +813,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 +826,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 +836,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 +849,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 +857,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 +875,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 +894,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 +907,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 +924,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 +938,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 +958,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 +973,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 +986,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 +1004,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 +1020,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 +1051,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 +1069,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 +1088,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 +1110,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 +1129,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 +1149,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 +1172,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..be3bc25ec1f6d5 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 @@ -21,9 +21,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 +37,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 +56,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 +72,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 +90,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 +103,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 +124,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 +141,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 +150,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 +168,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 +183,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 +196,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 +219,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 +234,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 +244,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 +292,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 +314,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 +334,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 +354,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 +387,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 +414,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 +423,7 @@ private TypeMapping ImportType(XmlSchemaComplexType type, string typeNs, string } if (desiredMappingType == typeof(TypeMapping)) { - TypeMapping mapping = null; + TypeMapping? mapping = null; if (baseType == null) { @@ -447,7 +447,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 +461,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 +493,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 +554,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 +570,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 +594,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 +611,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 +677,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 +718,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 +731,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 +748,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 +762,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 +785,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 +810,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 +820,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 +849,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 +861,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 +872,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 +897,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 +921,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 +948,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 +972,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 +980,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 +1025,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 +1057,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 +1068,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 +1106,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 +1115,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 +1128,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 +1137,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 +1156,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 +1177,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 +1205,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 +1260,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 +1276,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 +1300,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 +1310,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 +1327,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 +1373,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 +1399,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 +1416,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 +1445,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 +1473,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,10 +1485,10 @@ 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) + foreach (XmlNode? node in nodes) { if (node is XmlElement) { @@ -1497,7 +1497,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 +1511,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 +1554,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 +1563,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 +1573,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 +1589,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 +1599,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 +1626,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 +1652,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 +1688,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 +1714,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 +1727,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 +1752,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 +1794,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 +1810,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 +1819,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 +1828,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 +1837,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 +1857,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 +1865,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 +1906,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 +1932,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 +1948,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 +1967,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 +1976,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..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 @@ -12,13 +12,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 +26,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..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 @@ -16,26 +16,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 +44,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 +119,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 +156,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 +171,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 +186,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 +208,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 +230,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 +250,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 +360,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 +430,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 +443,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 +456,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 +502,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 +525,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 +606,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 +614,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 +640,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 +708,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 +731,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 +754,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/XmlSerializationGeneratedCode.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationGeneratedCode.cs index 67e10d34cc1b22..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 @@ -15,7 +15,7 @@ namespace System.Xml.Serialization /// public abstract class XmlSerializationGeneratedCode { - internal void Init(TempAssembly tempAssembly) + internal void Init(TempAssembly? tempAssembly) { } @@ -31,11 +31,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 +56,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 +70,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 +97,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 +149,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 +168,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 +179,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 +240,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 +327,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 +347,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 +359,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 +368,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 +402,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..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 @@ -6,6 +6,7 @@ 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 +24,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 +51,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 +68,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 +81,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 +114,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 +141,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 +168,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 +179,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 +189,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 +216,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 +274,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 +283,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 +296,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 +307,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 +315,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 +347,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 +372,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 +396,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 +417,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 +449,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 +461,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 +483,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 +502,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 +522,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 +540,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 +562,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 +570,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 +591,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..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 @@ -5,6 +5,8 @@ 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 +17,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 +171,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 +245,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 +264,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 +509,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 +674,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 +822,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 +835,7 @@ protected bool GetNullAttr() return true; } - protected string ReadNullableString() + protected string? ReadNullableString() { if (ReadNull()) return null; return _r.ReadElementString(); @@ -842,7 +844,7 @@ protected string ReadNullableString() /// /// [To be supplied.] /// - protected XmlQualifiedName ReadNullableQualifiedName() + protected XmlQualifiedName? ReadNullableQualifiedName() { if (ReadNull()) return null; return ReadElementQualifiedName(); @@ -864,9 +866,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 +876,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 +907,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 +922,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 +940,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 +957,7 @@ private struct SoapArrayInfo public int jaggedDimensions; } - private SoapArrayInfo ParseArrayType(string value) + private SoapArrayInfo ParseArrayType(string? value) { if (value == null) { @@ -1036,7 +1041,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 +1115,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 +1161,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 +1170,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 +1186,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 +1202,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 +1235,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 +1268,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 +1299,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 +1319,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 +1339,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 +1359,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 +1372,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 +1396,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 +1420,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 +1449,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 +1466,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 +1480,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 +1489,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 +1502,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 +1525,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 +1540,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 +1557,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 +1576,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 +1590,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 +1608,7 @@ private object ReadArray(string typeName, string typeNs) { if (!_soap12) { - elementType = GetPrimitiveType(qname, true); + elementType = GetPrimitiveType(qname, true)!; isPrimitive = true; } else @@ -1622,7 +1631,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 +1663,7 @@ private object ReadArray(string typeName, string typeNs) _r.MoveToContent(); int arrayLength = 0; - Array array = null; + Array? array = null; if (elementType.IsValueType) { @@ -1677,7 +1686,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 +1707,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 +1718,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 +1744,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 +1761,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 +1772,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 +1805,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 +1831,7 @@ protected object ReadReferencingElement(string name, string ns, bool elementCanB return o; } + [MemberNotNull(nameof(_callbacks))] internal void EnsureCallbackTables() { if (_callbacks == null) @@ -1838,7 +1849,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 +1867,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 +1881,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 +1899,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 +1916,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 +1935,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 +1961,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 +1981,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 +1996,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 +2011,7 @@ public XmlSerializationCollectionFixupCallback Callback get { return _callback; } } - public object Collection + public object? Collection { get { return _collection; } } @@ -2017,15 +2028,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 +2079,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 +2102,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 +2132,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 +2201,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 +2221,7 @@ internal string ChoiceArrayName { get { return _choiceArrayName; } } - internal string ChoiceArraySource + internal string? ChoiceArraySource { get { return _choiceArraySource; } } @@ -2234,7 +2245,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 +2288,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 +2312,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 +2325,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 +2339,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 +2349,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 +2362,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 +2389,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 +2398,7 @@ private void GenerateInitCallbacksMethod() needDummyArrayMethod = true; } else - methodName = (string)MethodNames[mapping]; + methodName = (string)MethodNames[mapping]!; Writer.Write("AddReadCallback("); WriteID(mapping.TypeName); @@ -2431,9 +2442,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 +2474,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 +2496,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 +2511,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 +2541,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 +2555,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 +2629,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 +2651,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 +2691,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 +2717,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 +2757,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 +2774,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 +2786,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 +2827,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 +2845,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 +2873,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 +2899,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 +2931,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 +2975,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 +3002,7 @@ private void WriteEnumMethod(EnumMapping mapping) Writer.Indent++; } - ConstantMapping[] constants = mapping.Constants; + ConstantMapping[] constants = mapping.Constants!; if (mapping.IsFlags) { if (useReflection) @@ -3022,7 +3033,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 +3062,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 +3106,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 +3122,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 +3165,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 +3219,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 +3307,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 +3324,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 +3334,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 +3345,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 +3363,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 +3424,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 +3438,7 @@ private void WriteEncodedStructMethod(StructMapping structMapping) Member[] members; bool anyFixups; - string fixupMethodName; + string? fixupMethodName; if (structMapping.TypeDesc.IsAbstract) { @@ -3488,7 +3499,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 +3524,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 +3552,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 +3567,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 +3631,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 +3648,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 +3666,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 +3674,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 +3683,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 +3702,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 +3747,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 +3787,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 +3805,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 +3845,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 +3857,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 +3880,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 +3920,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 +3933,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 +3999,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 +4018,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 +4086,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 +4107,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 +4118,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 +4141,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 +4164,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 +4194,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 +4218,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 +4261,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 +4291,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 +4301,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 +4327,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 +4407,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 +4440,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 +4452,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 +4470,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 +4487,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 +4502,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 +4530,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 +4549,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 +4566,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 +4632,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 +4646,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 +4657,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 +4678,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 +4693,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 +4762,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 +4786,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 +4801,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 +4815,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 +4835,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 +4844,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 +4876,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 +4889,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 +4922,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 +4940,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 +5051,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 +5098,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..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. - namespace System.Xml.Serialization { using System; @@ -22,7 +21,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 +42,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 +93,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 +155,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 +175,7 @@ internal string ChoiceArrayName { get { return _choiceArrayName; } } - internal string ChoiceArraySource + internal string? ChoiceArraySource { get { return _choiceArraySource; } } @@ -200,7 +199,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 +236,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 +262,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 +280,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 +288,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 +304,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 +324,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 +334,7 @@ private void WriteUnknownNode(string func, string node, ElementAccessor e, bool func, CodeGenerator.InstanceBindingFlags, argTypes.ToArray() - ); + )!; ilg.Call(method); if (anyIfs) { @@ -358,7 +357,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 +374,7 @@ private string GetChoiceIdentifierSource(MemberMapping[] mappings, MemberMapping #endif } - return choiceSource; + return choiceSource!; } private string GetChoiceIdentifierSource(MemberMapping mapping, string parent, TypeDesc parentTypeDesc) @@ -388,7 +387,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 +404,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 +426,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 +441,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 +471,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 +485,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 +506,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 +524,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 +539,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 +549,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 +564,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 +593,7 @@ private string GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping "ReadEndElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_ReadEndElement); @@ -618,21 +617,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 +653,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 +689,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 +706,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 +722,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 +756,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 +772,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 +793,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 +811,7 @@ private void WritePrimitive(TypeMapping mapping, string source) null, new Type[] { typeof(string) }, null - ); + )!; ilg.Call(XmlSerializationReader_CollapseWhitespace); } } @@ -822,12 +821,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 +838,7 @@ private void WritePrimitive(TypeMapping mapping, string source) "CollapseWhitespace", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } - ); + )!; ilg.Call(XmlSerializationReader_CollapseWhitespace); } } @@ -864,7 +863,7 @@ private void WritePrimitive(TypeMapping mapping, string source) "To" + mapping.TypeDesc.FormatterName, bindingFlags, new Type[] { argType } - ); + )!; } else { @@ -872,7 +871,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 +879,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 +895,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 +920,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 +943,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 +982,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 +1015,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 +1054,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 +1097,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 +1118,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 +1138,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 +1161,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 +1191,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 +1235,7 @@ private void WriteEnumAndArrayTypes() "ReadEndElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_ReadEndElement); ilg.Ldloc(eLoc); @@ -1247,7 +1246,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 +1260,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 +1283,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 +1314,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 +1333,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 +1347,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 +1359,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 +1403,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 +1446,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 +1469,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 +1482,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 +1509,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 +1524,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 +1535,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 +1552,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 +1562,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 +1573,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 +1591,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 +1623,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 +1638,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 +1647,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 +1661,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 +1677,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 +1690,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 +1701,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 +1711,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 +1736,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 +1754,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 +1797,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 +1805,7 @@ private void WriteID(string name) //return; name = ""; } - string idName; + string? idName; if (!_idNames.TryGetValue(name, out idName)) { idName = NextIdName(name); @@ -1815,10 +1814,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 +1825,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 +1843,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 +1884,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 +1912,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 +1959,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 +1980,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 +1997,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 +2029,7 @@ private void WriteAttributes(Member[] members, Member anyAttribute, string elseC elseCall, CodeGenerator.InstanceBindingFlags, argTypes.ToArray() - ); + )!; ilg.Call(elseCallMethod); } ilg.EndIf(); @@ -2046,17 +2046,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 +2074,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 +2090,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 +2112,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 +2147,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 +2158,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 +2169,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 +2188,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 +2197,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 +2225,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 +2242,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 +2254,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 +2286,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 +2330,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 +2369,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 +2387,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 +2402,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 +2431,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 +2466,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 +2484,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 +2527,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 +2549,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 +2612,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 +2644,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 +2659,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 +2696,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 +2731,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 +2786,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 +2818,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 +2840,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 +2856,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 +2864,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 +2905,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 +2926,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 +2936,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 +2948,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 +2959,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 +2976,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 +2989,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 +3016,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 +3029,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 +3053,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 +3064,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 +3085,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 +3094,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 +3113,7 @@ private void WriteElement(string source, string arrayName, string choiceSource, "ReadElementQualifiedName", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_ReadElementQualifiedName); } @@ -3133,7 +3133,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 +3142,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 +3154,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 +3171,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 +3179,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 +3193,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 +3202,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 +3220,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 +3231,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 +3239,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 +3255,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 +3278,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 +3299,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 +3309,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 +3326,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 +3335,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 +3353,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 +3373,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 +3398,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 +3434,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 +3455,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 +3466,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 +3500,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 +3587,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..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 @@ -18,26 +18,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 +74,7 @@ protected XmlWriter Writer /// /// [To be supplied.] /// - protected ArrayList Namespaces + protected ArrayList? Namespaces { get { @@ -103,12 +104,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 +145,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 +236,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 +391,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 +414,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 +431,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 +459,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 +498,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 +522,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 +563,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 +577,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 +591,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 +609,7 @@ protected void WriteEndElement() _w.WriteEndElement(); } - protected void WriteEndElement(object o) + protected void WriteEndElement(object? o) { _w.WriteEndElement(); @@ -618,12 +624,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 +647,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 +655,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 +664,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 +672,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 +680,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 +688,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 +699,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 +710,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 +719,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 +729,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 +739,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 +820,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 +855,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 +883,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 +894,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 +906,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 +920,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 +938,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 +952,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 +964,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 +972,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 +1013,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 +1042,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 +1082,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 +1092,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 +1101,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 +1114,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 +1135,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 +1168,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 +1184,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 +1193,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 +1269,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 +1302,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 +1313,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 +1333,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 +1348,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 +1376,7 @@ protected void WriteReferencedElements() for (int i = 0; i < _referencesToWrite.Count; i++) { - WriteReferencedElement(_referencesToWrite[i], null); + WriteReferencedElement(_referencesToWrite[i]!, null); } } @@ -1378,23 +1386,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 +1410,7 @@ protected void WriteNamespaceDeclarations(XmlSerializerNamespaces xmlns) } } } + _namespaces = null; } @@ -1417,14 +1426,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 +1447,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 +1456,7 @@ internal static bool IsTypeDynamic(Type type) { if (type.IsArray) { - isTypeDynamic = IsTypeDynamic(type.GetElementType()); + isTypeDynamic = IsTypeDynamic(type.GetElementType()!); } else if (type.IsGenericType) { @@ -1494,8 +1502,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 +1521,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 +1551,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 +1573,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 +1598,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 +1615,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 +1639,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 +1665,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 +1682,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 +1704,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 +1754,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 +1807,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 +1853,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 +1869,7 @@ internal string GetStringForTypeof(string typeFullName, bool useReflection) { if (useReflection) { - return GetReflectionVariable(typeFullName, null); + return GetReflectionVariable(typeFullName, null)!; } else { @@ -1875,11 +1885,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 +1919,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 +1938,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 +1953,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 +1966,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 +1980,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 +2037,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 +2098,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 +2136,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 +2210,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 +2256,7 @@ internal void GenerateEnd() Writer.WriteLine("}"); } - internal string GenerateElement(XmlMapping xmlMapping) + internal string? GenerateElement(XmlMapping xmlMapping) { if (!xmlMapping.IsWriteable) return null; @@ -2269,9 +2282,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 +2299,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 +2345,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 +2386,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 +2408,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 +2421,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 +2441,7 @@ private void WritePrimitive(string method, string name, string ns, object defaul Writer.Write(", "); WriteQuotedCSharpString(ns); } + Writer.Write(", "); if (mapping is EnumMapping) @@ -2455,7 +2471,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 +2488,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 +2510,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 +2526,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 +2544,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 +2571,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 +2586,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 +2595,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 +2626,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 +2640,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 +2648,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 +2682,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 +2703,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 +2713,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 +2754,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 +2779,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 +2802,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 +2822,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 +2914,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 +2954,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 +2984,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 +3002,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 +3015,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 +3085,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 +3095,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 +3145,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 +3166,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 +3187,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 +3215,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 +3245,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 +3264,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 +3369,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 +3400,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 +3413,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 +3429,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 +3444,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 +3469,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 +3556,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 +3570,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 +3597,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 +3615,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 +3646,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 +3667,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 +3689,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 +3760,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 +3822,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 +3843,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 +3883,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 +3895,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 +3956,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 +3976,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 +3988,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 +4013,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 +4033,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 +4044,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 +4062,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 +4074,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 +4117,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 +4156,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 +4164,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 +4351,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 +4375,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 +4394,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 +4414,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..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 @@ -11,6 +11,7 @@ using System.Text; using System.Xml.Schema; using System.Xml.Extensions; +using System.Diagnostics.CodeAnalysis; namespace System.Xml.Serialization { @@ -36,7 +37,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 +64,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 +89,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 +105,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 +123,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 +147,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 +165,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 +182,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 +220,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 +258,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 +268,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 +277,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 +305,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 +316,7 @@ private void WriteEndElement() "WriteEndElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationWriter_WriteEndElement); } @@ -325,7 +326,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 +334,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 +347,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 +364,7 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) "WriteStartDocument", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationWriter_WriteStartDocument); @@ -371,7 +372,7 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) "TopLevelElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationWriter_TopLevelElement); @@ -387,10 +388,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 +401,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 +444,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 +456,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 +464,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 +501,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 +520,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 +541,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 +556,7 @@ private string GenerateTypeElement(XmlTypeMapping xmlTypeMapping) "WriteStartDocument", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationWriter_WriteStartDocument); @@ -569,13 +570,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 +594,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 +620,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 +630,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 +680,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 +700,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 +734,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 +756,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 +766,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 +787,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 +801,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 +816,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 +852,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 +867,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 +882,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 +907,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 +917,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 +927,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 +941,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 +959,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 +978,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 +993,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 +1011,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 +1046,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 +1056,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 +1073,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 +1082,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 +1101,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 +1116,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 +1139,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 +1160,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 +1168,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 +1192,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 +1207,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 +1224,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 +1245,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 +1266,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 +1288,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 +1304,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 +1314,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 +1324,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 +1332,7 @@ private void WriteMember(SourceInfo source, AttributeAccessor attribute, TypeDes "WriteAttribute", CodeGenerator.InstanceBindingFlags, argTypes.ToArray() - ); + )!; ilg.Call(XmlSerializationWriter_WriteAttribute); ilg.EndIf(); } @@ -1353,14 +1354,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 +1373,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 +1395,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 +1406,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 +1420,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 +1448,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 +1457,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 +1481,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 +1512,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 +1538,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 +1553,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 +1575,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 +1593,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 +1617,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 +1625,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 +1653,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 +1672,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 +1706,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 +1719,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 +1742,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 +1769,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 +1795,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 +1827,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 +1854,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 +1892,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 +1913,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 +1935,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 +1951,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 +1978,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 +1987,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 +1999,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 +2009,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 +2018,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 +2051,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 +2066,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 +2101,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 +2131,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 +2143,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 +2160,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 +2173,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 +2201,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 +2242,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 +2256,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 +2270,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 +2280,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 +2339,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 +2365,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 +2381,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 +2395,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 +2427,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 +2448,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 +2460,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 +2471,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 +2481,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 +2491,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 +2515,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 +2550,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 +2579,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 +2593,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..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 @@ -21,13 +21,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 +40,7 @@ public XmlNodeEventHandler OnUnknownNode } } - public XmlAttributeEventHandler OnUnknownAttribute + public XmlAttributeEventHandler? OnUnknownAttribute { get { @@ -52,7 +52,7 @@ public XmlAttributeEventHandler OnUnknownAttribute } } - public XmlElementEventHandler OnUnknownElement + public XmlElementEventHandler? OnUnknownElement { get { @@ -64,7 +64,7 @@ public XmlElementEventHandler OnUnknownElement } } - public UnreferencedObjectEventHandler OnUnreferencedObject + public UnreferencedObjectEventHandler? OnUnreferencedObject { get { @@ -118,19 +118,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 +155,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 +181,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 +193,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 +208,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 +222,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 +242,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 +253,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 +265,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 +288,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 +304,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 +317,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 +365,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 +374,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 +385,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 +400,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 +409,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 +459,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 +476,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 +493,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 +506,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 +529,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 +549,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 +573,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 +592,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 +608,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 +632,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 +671,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 +701,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 +764,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 +773,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 +858,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 +936,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 +951,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..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 @@ -8,26 +8,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..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 @@ -17,22 +17,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 +44,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..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 @@ -11,13 +11,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 +34,7 @@ public XmlSerializerNamespaces() /// public XmlSerializerNamespaces(XmlSerializerNamespaces namespaces) { - _namespaces = new Dictionary(namespaces.Namespaces); + _namespaces = new Dictionary(namespaces.Namespaces); } /// @@ -51,7 +52,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 +60,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 +86,7 @@ public int Count get { return Namespaces.Count; } } - internal ArrayList NamespaceList + internal ArrayList? NamespaceList { get { @@ -94,24 +95,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..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 @@ -8,40 +8,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..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 @@ -2,7 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; - +using System.Diagnostics.CodeAnalysis; namespace System.Xml.Serialization { @@ -12,8 +12,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 +25,7 @@ public XmlTextAttribute() /// /// [To be supplied.] /// - public XmlTextAttribute(Type type) + public XmlTextAttribute(Type? type) { _type = type; } @@ -33,7 +33,7 @@ public XmlTextAttribute(Type type) /// /// [To be supplied.] /// - public Type Type + public Type? Type { get { return _type; } set { _type = value; } @@ -42,6 +42,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..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 @@ -2,7 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. using System; - +using System.Diagnostics.CodeAnalysis; namespace System.Xml.Serialization { @@ -14,8 +14,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 +27,7 @@ public XmlTypeAttribute() /// /// [To be supplied.] /// - public XmlTypeAttribute(string typeName) + public XmlTypeAttribute(string? typeName) { _typeName = typeName; } @@ -53,6 +53,7 @@ public bool IncludeInSchema /// /// [To be supplied.] /// + [AllowNull] public string TypeName { get { return _typeName == null ? string.Empty : _typeName; } @@ -62,7 +63,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..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 @@ -4,7 +4,6 @@ using System.Reflection; using System; - namespace System.Xml.Serialization { /// @@ -12,11 +11,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 +27,7 @@ public string TypeName { get { - return Mapping.TypeDesc.Name; + return Mapping!.TypeDesc!.Name; } } @@ -39,29 +38,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..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 @@ -33,7 +33,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 +111,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 +158,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 +169,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 +400,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 +433,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 +457,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..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 @@ -9,18 +9,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 +29,7 @@ internal XmlAttributeEventArgs(XmlAttribute attr, int lineNumber, int linePositi _linePosition = linePosition; } - public object ObjectBeingDeserialized + public object? ObjectBeingDeserialized { get { return _o; } } @@ -64,17 +64,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 +83,7 @@ internal XmlElementEventArgs(XmlElement elem, int lineNumber, int linePosition, _linePosition = linePosition; } - public object ObjectBeingDeserialized + public object? ObjectBeingDeserialized { get { return _o; } } @@ -112,18 +112,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 +131,7 @@ internal XmlNodeEventArgs(XmlNode xmlNode, int lineNumber, int linePosition, obj _linePosition = linePosition; } - public object ObjectBeingDeserialized + public object? ObjectBeingDeserialized { get { return _o; } } @@ -156,7 +156,7 @@ public string NamespaceURI get { return _xmlNode.NamespaceURI; } } - public string Text + public string? Text { get { return _xmlNode.Value; } } @@ -178,25 +178,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..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 @@ -33,7 +33,7 @@ internal int Indent } } - internal void Write(string s) + internal void Write(string? s) { if (_needIndent) WriteIndent(); _writer.Write(s); @@ -45,7 +45,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); 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 017f4044d61351..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; @@ -17,7 +16,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 +59,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 +91,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 +99,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.Private.Xml/src/System/Xml/XPath/XPathExpr.cs b/src/libraries/System.Private.Xml/src/System/Xml/XPath/XPathExpr.cs index af967030af5997..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; @@ -51,7 +50,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; } 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 02baf072f2a2c0..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; @@ -1186,7 +1185,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 +1205,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)); } 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