From: Krzysztof Wicher Date: Fri, 29 May 2020 21:07:47 +0000 (-0700) Subject: Nullable: System.Xml, part 3 X-Git-Tag: submit/tizen/20210909.063632~7626^2~1 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=67c258ea3f3d9e45be5716f06b64e84ef5cdd9e7;p=platform%2Fupstream%2Fdotnet%2Fruntime.git Nullable: System.Xml, part 3 --- diff --git a/src/libraries/System.Private.CoreLib/src/System/LocalAppContextSwitches.Common.cs b/src/libraries/System.Private.CoreLib/src/System/LocalAppContextSwitches.Common.cs index 0741771..a892b21 100644 --- a/src/libraries/System.Private.CoreLib/src/System/LocalAppContextSwitches.Common.cs +++ b/src/libraries/System.Private.CoreLib/src/System/LocalAppContextSwitches.Common.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Runtime.CompilerServices; namespace System diff --git a/src/libraries/System.Private.Xml/src/System/Xml/AsyncHelper.cs b/src/libraries/System.Private.Xml/src/System/Xml/AsyncHelper.cs index 692b8e2..a527a0c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/AsyncHelper.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/AsyncHelper.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Threading.Tasks; namespace System.Xml diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Base64Decoder.cs b/src/libraries/System.Private.Xml/src/System/Xml/Base64Decoder.cs index 580ff0e..8e2726e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Base64Decoder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Base64Decoder.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Diagnostics; @@ -12,7 +13,7 @@ namespace System.Xml // // Fields // - private byte[] _buffer; + private byte[]? _buffer; private int _startIndex; private int _curIndex; private int _endIndex; @@ -70,7 +71,7 @@ namespace System.Xml int bytesDecoded, charsDecoded; fixed (char* pChars = &chars[startPos]) { - fixed (byte* pBytes = &_buffer[_curIndex]) + fixed (byte* pBytes = &_buffer![_curIndex]) { Decode(pChars, pChars + len, pBytes, pBytes + (_endIndex - _curIndex), out charsDecoded, out bytesDecoded); } @@ -102,14 +103,16 @@ namespace System.Xml { return 0; } + int bytesDecoded, charsDecoded; fixed (char* pChars = str) { - fixed (byte* pBytes = &_buffer[_curIndex]) + fixed (byte* pBytes = &_buffer![_curIndex]) { Decode(pChars + startPos, pChars + startPos + len, pBytes, pBytes + (_endIndex - _curIndex), out charsDecoded, out bytesDecoded); } } + _curIndex += bytesDecoded; return charsDecoded; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Base64Encoder.cs b/src/libraries/System.Private.Xml/src/System/Xml/Base64Encoder.cs index e0fd83a..0fa4326 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Base64Encoder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Base64Encoder.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Text; using System.Diagnostics; @@ -9,7 +10,7 @@ namespace System.Xml { internal abstract partial class Base64Encoder { - private byte[] _leftOverBytes; + private byte[]? _leftOverBytes; private int _leftOverBytesCount; private readonly char[] _charsLine; @@ -48,7 +49,7 @@ namespace System.Xml int i = _leftOverBytesCount; while (i < 3 && count > 0) { - _leftOverBytes[i++] = buffer[index++]; + _leftOverBytes![i++] = buffer[index++]; count--; } @@ -60,7 +61,7 @@ namespace System.Xml } // encode the left-over buffer and write out - int leftOverChars = Convert.ToBase64CharArray(_leftOverBytes, 0, 3, _charsLine, 0); + int leftOverChars = Convert.ToBase64CharArray(_leftOverBytes!, 0, 3, _charsLine, 0); WriteChars(_charsLine, 0, leftOverChars); } @@ -99,7 +100,7 @@ namespace System.Xml { if (_leftOverBytesCount > 0) { - int leftOverChars = Convert.ToBase64CharArray(_leftOverBytes, 0, _leftOverBytesCount, _charsLine, 0); + int leftOverChars = Convert.ToBase64CharArray(_leftOverBytes!, 0, _leftOverBytesCount, _charsLine, 0); WriteChars(_charsLine, 0, leftOverChars); _leftOverBytesCount = 0; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Base64EncoderAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/Base64EncoderAsync.cs index 56ba578..2930e59 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Base64EncoderAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Base64EncoderAsync.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Text; using System.Diagnostics; @@ -38,7 +39,7 @@ namespace System.Xml int i = _leftOverBytesCount; while (i < 3 && count > 0) { - _leftOverBytes[i++] = buffer[index++]; + _leftOverBytes![i++] = buffer[index++]; count--; } @@ -50,7 +51,7 @@ namespace System.Xml } // encode the left-over buffer and write out - int leftOverChars = Convert.ToBase64CharArray(_leftOverBytes, 0, 3, _charsLine, 0); + int leftOverChars = Convert.ToBase64CharArray(_leftOverBytes!, 0, 3, _charsLine, 0); await WriteCharsAsync(_charsLine, 0, leftOverChars).ConfigureAwait(false); } @@ -89,7 +90,7 @@ namespace System.Xml { if (_leftOverBytesCount > 0) { - int leftOverChars = Convert.ToBase64CharArray(_leftOverBytes, 0, _leftOverBytesCount, _charsLine, 0); + int leftOverChars = Convert.ToBase64CharArray(_leftOverBytes!, 0, _leftOverBytesCount, _charsLine, 0); await WriteCharsAsync(_charsLine, 0, leftOverChars).ConfigureAwait(false); _leftOverBytesCount = 0; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/BinHexDecoder.cs b/src/libraries/System.Private.Xml/src/System/Xml/BinHexDecoder.cs index 169c7fa..bed87b0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/BinHexDecoder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/BinHexDecoder.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Diagnostics; @@ -12,7 +13,7 @@ namespace System.Xml // // Fields // - private byte[] _buffer; + private byte[]? _buffer; private int _startIndex; private int _curIndex; private int _endIndex; @@ -61,10 +62,11 @@ namespace System.Xml { return 0; } + int bytesDecoded, charsDecoded; fixed (char* pChars = &chars[startPos]) { - fixed (byte* pBytes = &_buffer[_curIndex]) + fixed (byte* pBytes = &_buffer![_curIndex]) { Decode(pChars, pChars + len, pBytes, pBytes + (_endIndex - _curIndex), ref _hasHalfByteCached, ref _cachedHalfByte, out charsDecoded, out bytesDecoded); @@ -97,15 +99,17 @@ namespace System.Xml { return 0; } + int bytesDecoded, charsDecoded; fixed (char* pChars = str) { - fixed (byte* pBytes = &_buffer[_curIndex]) + fixed (byte* pBytes = &_buffer![_curIndex]) { Decode(pChars + startPos, pChars + startPos + len, pBytes, pBytes + (_endIndex - _curIndex), ref _hasHalfByteCached, ref _cachedHalfByte, out charsDecoded, out bytesDecoded); } } + _curIndex += bytesDecoded; return charsDecoded; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/BinHexEncoder.cs b/src/libraries/System.Private.Xml/src/System/Xml/BinHexEncoder.cs index 4512583..1aba445 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/BinHexEncoder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/BinHexEncoder.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Xml { internal static partial class BinHexEncoder diff --git a/src/libraries/System.Private.Xml/src/System/Xml/BinHexEncoderAsync.cs b/src/libraries/System.Private.Xml/src/System/Xml/BinHexEncoderAsync.cs index 241db76..26b4cb5 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/BinHexEncoderAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/BinHexEncoderAsync.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Threading.Tasks; namespace System.Xml diff --git a/src/libraries/System.Private.Xml/src/System/Xml/BitStack.cs b/src/libraries/System.Private.Xml/src/System/Xml/BitStack.cs index 8330fcb..030cdda 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/BitStack.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/BitStack.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Diagnostics; @@ -12,7 +13,7 @@ namespace System.Xml /// internal class BitStack { - private uint[] _bitStack; + private uint[]? _bitStack; private int _stackPos; private uint _curr; @@ -108,7 +109,7 @@ namespace System.Xml private void PopCurr() { if (_stackPos > 0) - _curr = _bitStack[--_stackPos]; + _curr = _bitStack![--_stackPos]; } } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Bits.cs b/src/libraries/System.Private.Xml/src/System/Xml/Bits.cs index a2c4738..6cbbb30 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Bits.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Bits.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Diagnostics; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/ByteStack.cs b/src/libraries/System.Private.Xml/src/System/Xml/ByteStack.cs index 7c7b9a0..68fef68 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/ByteStack.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/ByteStack.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; namespace System.Xml diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Cache/Shape.cs b/src/libraries/System.Private.Xml/src/System/Xml/Cache/Shape.cs index f92e75c..87de0f7 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Cache/Shape.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Cache/Shape.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable #if ENABLEDATABINDING using System; using System.Xml; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Cache/ShapeGenerator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Cache/ShapeGenerator.cs index 78b2f4c..751083c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Cache/ShapeGenerator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Cache/ShapeGenerator.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable #if ENABLEDATABINDING using System; using System.Xml; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathDocumentView.cs b/src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathDocumentView.cs index f0499ce..786ac87 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathDocumentView.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathDocumentView.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable #if ENABLEDATABINDING using System; using System.Xml; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathNodeView.cs b/src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathNodeView.cs index 5eff6e3..6003f56 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathNodeView.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathNodeView.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable #if ENABLEDATABINDING using System; using System.Xml; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathNodeViewPropertyDescriptor.cs b/src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathNodeViewPropertyDescriptor.cs index 22c7a92..e0e2ec8 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathNodeViewPropertyDescriptor.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Cache/XPathNodeViewPropertyDescriptor.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable #if ENABLEDATABINDING using System; using System.Xml; 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 2eb8905..81c2264 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 @@ -216,15 +216,15 @@ namespace System.Xml /// /// SYSTEM identifier (URI) of the entity value - only used for external entities /// - string SystemId { get; } + string? SystemId { get; } /// /// PUBLIC identifier of the entity value - only used for external entities /// - string PublicId { get; } + string? PublicId { get; } /// /// Replacement text of an entity. Valid only for internal entities. /// - string Text { get; } + string? Text { get; } /// /// The line number of the entity value /// 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 0d9075f..1ecfd3c 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 @@ -4,6 +4,7 @@ #nullable enable using System; +using System.Diagnostics.CodeAnalysis; using System.Text; using System.Xml.Schema; @@ -16,7 +17,7 @@ namespace System.Xml Uri? BaseUri { get; } - char[]? ParsingBuffer { get; } + char[] ParsingBuffer { get; } int ParsingBufferLength { get; } int CurrentPosition { get; set; } int LineNo { get; } @@ -29,21 +30,22 @@ namespace System.Xml void OnNewLine(int pos); - int ParseNumericCharRef(StringBuilder internalSubsetBuilder); - int ParseNamedCharRef(bool expand, StringBuilder internalSubsetBuilder); - void ParsePI(StringBuilder sb); - void ParseComment(StringBuilder sb); + int ParseNumericCharRef(StringBuilder? internalSubsetBuilder); + int ParseNamedCharRef(bool expand, StringBuilder? internalSubsetBuilder); + void ParsePI(StringBuilder? sb); + void ParseComment(StringBuilder? sb); bool PushEntity(IDtdEntityInfo entity, out int entityId); bool PopEntity(out IDtdEntityInfo? oldEntity, out int newEntityId); - bool PushExternalSubset(string systemId, string publicId); + bool PushExternalSubset(string? systemId, string? publicId); void PushInternalDtd(string baseUri, string internalDtd); void OnSystemId(string systemId, LineInfo keywordLineInfo, LineInfo systemLiteralLineInfo); void OnPublicId(string publicId, LineInfo keywordLineInfo, LineInfo publicLiteralLineInfo); + [DoesNotReturn] void Throw(Exception e); } 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 cba84e3..7f88a66 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; namespace System.Xml @@ -23,12 +24,12 @@ namespace System.Xml private bool _isEnd; private readonly bool _canReadValueChunk; - private readonly char[] _valueChunk; + private readonly char[]? _valueChunk; private int _valueChunkLength; - private IncrementalReadDecoder _decoder; - private Base64Decoder _base64Decoder; - private BinHexDecoder _binHexDecoder; + private IncrementalReadDecoder? _decoder; + private Base64Decoder? _base64Decoder; + private BinHexDecoder? _binHexDecoder; // Constants private const int ChunkSize = 256; @@ -46,7 +47,7 @@ namespace System.Xml } // Static methods - internal static ReadContentAsBinaryHelper CreateOrReset(ReadContentAsBinaryHelper helper, XmlReader reader) + internal static ReadContentAsBinaryHelper CreateOrReset(ReadContentAsBinaryHelper? helper, XmlReader reader) { if (helper == null) { @@ -398,7 +399,7 @@ namespace System.Xml { if (_valueOffset < _valueChunkLength) { - int decodedCharsCount = _decoder.Decode(_valueChunk, _valueOffset, _valueChunkLength - _valueOffset); + int decodedCharsCount = _decoder.Decode(_valueChunk!, _valueOffset, _valueChunkLength - _valueOffset); _valueOffset += decodedCharsCount; } if (_decoder.IsFull) @@ -406,7 +407,7 @@ namespace System.Xml return _decoder.DecodedCount; } Debug.Assert(_valueOffset == _valueChunkLength); - if ((_valueChunkLength = _reader.ReadValueChunk(_valueChunk, 0, ChunkSize)) == 0) + if ((_valueChunkLength = _reader.ReadValueChunk(_valueChunk!, 0, ChunkSize)) == 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 1d0230d..3b20dc4 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.IO; using System.Diagnostics; 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 87fad19..73b7910 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Xml; using System.Diagnostics; @@ -42,7 +43,7 @@ namespace System.Xml private XmlNodeType _lastNodeType; private XmlCharType _xmlCharType; - private ReadContentAsBinaryHelper _readBinaryHelper; + private ReadContentAsBinaryHelper? _readBinaryHelper; // // Constructor @@ -75,7 +76,7 @@ namespace System.Xml { get { - XmlReaderSettings settings = reader.Settings; + XmlReaderSettings? settings = reader.Settings; if (settings == null) { settings = new XmlReaderSettings(); @@ -310,7 +311,7 @@ namespace System.Xml ValidateQName(base.reader.Name); CheckCharacters(base.reader.Value); - string str; + string? str; str = base.reader.GetAttribute("SYSTEM"); if (str != null) { @@ -611,13 +612,13 @@ namespace System.Xml private void Throw(string res, string arg) { _state = State.Error; - throw new XmlException(res, arg, (IXmlLineInfo)null); + throw new XmlException(res, arg, (IXmlLineInfo?)null); } private void Throw(string res, string[] args) { _state = State.Error; - throw new XmlException(res, args, (IXmlLineInfo)null); + throw new XmlException(res, args, (IXmlLineInfo?)null); } private void CheckWhitespace(string value) @@ -688,12 +689,12 @@ namespace System.Xml return readerAsNSResolver.GetNamespacesInScope(scope); } - string IXmlNamespaceResolver.LookupNamespace(string prefix) + string? IXmlNamespaceResolver.LookupNamespace(string prefix) { return readerAsNSResolver.LookupNamespace(prefix); } - string IXmlNamespaceResolver.LookupPrefix(string namespaceName) + string? IXmlNamespaceResolver.LookupPrefix(string namespaceName) { return readerAsNSResolver.LookupPrefix(namespaceName); } 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 b036585..3dfee72 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Collections.Generic; using System.Diagnostics; using System.Text; @@ -15,8 +16,8 @@ namespace System.Xml /// internal sealed class XmlEventCache : XmlRawWriter { - private List _pages; // All event pages - private XmlEvent[] _pageCurr; // Page that is currently being built + private List? _pages; // All event pages + private XmlEvent[]? _pageCurr; // Page that is currently being built private int _pageSize; // Number of events in pageCurr private readonly bool _hasRootNode; // True if the cached document has a root node, false if it's a fragment private StringConcat _singleText; // If document consists of a single text node, cache it here rather than creating pages @@ -100,7 +101,7 @@ namespace System.Xml int idxPage, idxEvent; byte[] bytes; char[] chars; - XmlRawWriter rawWriter; + XmlRawWriter? rawWriter; // Special-case single text node at the top-level if (_singleText.Count != 0) @@ -112,7 +113,7 @@ namespace System.Xml rawWriter = writer as XmlRawWriter; // Loop over set of pages - for (idxPage = 0; idxPage < _pages.Count; idxPage++) + for (idxPage = 0; idxPage < _pages!.Count; idxPage++) { page = _pages[idxPage]; @@ -127,15 +128,15 @@ namespace System.Xml return; case XmlEventType.DocType: - writer.WriteDocType(page[idxEvent].String1, page[idxEvent].String2, page[idxEvent].String3, (string)page[idxEvent].Object); + writer.WriteDocType(page[idxEvent].String1!, page[idxEvent].String2, page[idxEvent].String3, (string?)page[idxEvent].Object); break; case XmlEventType.StartElem: - writer.WriteStartElement(page[idxEvent].String1, page[idxEvent].String2, page[idxEvent].String3); + writer.WriteStartElement(page[idxEvent].String1, page[idxEvent].String2!, page[idxEvent].String3); break; case XmlEventType.StartAttr: - writer.WriteStartAttribute(page[idxEvent].String1, page[idxEvent].String2, page[idxEvent].String3); + writer.WriteStartAttribute(page[idxEvent].String1, page[idxEvent].String2!, page[idxEvent].String3); break; case XmlEventType.EndAttr: @@ -147,15 +148,15 @@ namespace System.Xml break; case XmlEventType.Comment: - writer.WriteComment(page[idxEvent].String1); + writer.WriteComment(page[idxEvent].String1!); break; case XmlEventType.PI: - writer.WriteProcessingInstruction(page[idxEvent].String1, page[idxEvent].String2); + writer.WriteProcessingInstruction(page[idxEvent].String1!, page[idxEvent].String2!); break; case XmlEventType.Whitespace: - writer.WriteWhitespace(page[idxEvent].String1); + writer.WriteWhitespace(page[idxEvent].String1!); break; case XmlEventType.String: @@ -163,40 +164,40 @@ namespace System.Xml break; case XmlEventType.Raw: - writer.WriteRaw(page[idxEvent].String1); + writer.WriteRaw(page[idxEvent].String1!); break; case XmlEventType.EntRef: - writer.WriteEntityRef(page[idxEvent].String1); + writer.WriteEntityRef(page[idxEvent].String1!); break; case XmlEventType.CharEnt: - writer.WriteCharEntity((char)page[idxEvent].Object); + writer.WriteCharEntity((char)page[idxEvent].Object!); break; case XmlEventType.SurrCharEnt: - chars = (char[])page[idxEvent].Object; + chars = (char[])page[idxEvent].Object!; writer.WriteSurrogateCharEntity(chars[0], chars[1]); break; case XmlEventType.Base64: - bytes = (byte[])page[idxEvent].Object; + bytes = (byte[])page[idxEvent].Object!; writer.WriteBase64(bytes, 0, bytes.Length); break; case XmlEventType.BinHex: - bytes = (byte[])page[idxEvent].Object; + bytes = (byte[])page[idxEvent].Object!; writer.WriteBinHex(bytes, 0, bytes.Length); break; case XmlEventType.XmlDecl1: if (rawWriter != null) - rawWriter.WriteXmlDeclaration((XmlStandalone)page[idxEvent].Object); + rawWriter.WriteXmlDeclaration((XmlStandalone)page[idxEvent].Object!); break; case XmlEventType.XmlDecl2: if (rawWriter != null) - rawWriter.WriteXmlDeclaration(page[idxEvent].String1); + rawWriter.WriteXmlDeclaration(page[idxEvent].String1!); break; case XmlEventType.StartContent: @@ -206,23 +207,23 @@ namespace System.Xml case XmlEventType.EndElem: if (rawWriter != null) - rawWriter.WriteEndElement(page[idxEvent].String1, page[idxEvent].String2, page[idxEvent].String3); + rawWriter.WriteEndElement(page[idxEvent].String1!, page[idxEvent].String2!, page[idxEvent].String3!); else writer.WriteEndElement(); break; case XmlEventType.FullEndElem: if (rawWriter != null) - rawWriter.WriteFullEndElement(page[idxEvent].String1, page[idxEvent].String2, page[idxEvent].String3); + rawWriter.WriteFullEndElement(page[idxEvent].String1!, page[idxEvent].String2!, page[idxEvent].String3!); else writer.WriteFullEndElement(); break; case XmlEventType.Nmsp: if (rawWriter != null) - rawWriter.WriteNamespaceDeclaration(page[idxEvent].String1, page[idxEvent].String2); + rawWriter.WriteNamespaceDeclaration(page[idxEvent].String1!, page[idxEvent].String2!); else - writer.WriteAttributeString("xmlns", page[idxEvent].String1, XmlReservedNs.NsXmlNs, page[idxEvent].String2); + writer.WriteAttributeString("xmlns", page[idxEvent].String1!, XmlReservedNs.NsXmlNs, page[idxEvent].String2!); break; case XmlEventType.EndBase64: @@ -270,7 +271,7 @@ namespace System.Xml // Loop over set of pages inAttr = false; - for (idxPage = 0; idxPage < _pages.Count; idxPage++) + for (idxPage = 0; idxPage < _pages!.Count; idxPage++) { page = _pages[idxPage]; @@ -315,22 +316,22 @@ namespace System.Xml // XmlWriter interface //----------------------------------------------- - public override XmlWriterSettings Settings + public override XmlWriterSettings? Settings { get { return null; } } - public override void WriteDocType(string name, string pubid, string sysid, string subset) + public override void WriteDocType(string name, string? pubid, string? sysid, string? subset) { AddEvent(XmlEventType.DocType, name, pubid, sysid, subset); } - public override void WriteStartElement(string prefix, string localName, string ns) + public override void WriteStartElement(string? prefix, string localName, string? ns) { AddEvent(XmlEventType.StartElem, prefix, localName, ns); } - public override void WriteStartAttribute(string prefix, string localName, string ns) + public override void WriteStartAttribute(string? prefix, string localName, string? ns) { AddEvent(XmlEventType.StartAttr, prefix, localName, ns); } @@ -340,7 +341,7 @@ namespace System.Xml AddEvent(XmlEventType.EndAttr); } - public override void WriteCData(string text) + public override void WriteCData(string? text) { AddEvent(XmlEventType.CData, text); } @@ -360,7 +361,7 @@ namespace System.Xml AddEvent(XmlEventType.Whitespace, ws); } - public override void WriteString(string text) + public override void WriteString(string? text) { // Special-case single text node at the top level if (_pages == null) @@ -429,12 +430,12 @@ namespace System.Xml /// All other WriteValue methods are implemented by XmlWriter to delegate to WriteValue(object) or WriteValue(string), so /// only these two methods need to be implemented. /// - public override void WriteValue(object value) + public override void WriteValue(object? value) { WriteString(XmlUntypedConverter.Untyped.ToString(value, this.resolver)); } - public override void WriteValue(string value) + public override void WriteValue(string? value) { WriteString(value); } @@ -502,37 +503,37 @@ namespace System.Xml private void AddEvent(XmlEventType eventType) { int idx = NewEvent(); - _pageCurr[idx].InitEvent(eventType); + _pageCurr![idx].InitEvent(eventType); } - private void AddEvent(XmlEventType eventType, string s1) + private void AddEvent(XmlEventType eventType, string? s1) { int idx = NewEvent(); - _pageCurr[idx].InitEvent(eventType, s1); + _pageCurr![idx].InitEvent(eventType, s1); } - private void AddEvent(XmlEventType eventType, string s1, string s2) + private void AddEvent(XmlEventType eventType, string? s1, string? s2) { int idx = NewEvent(); - _pageCurr[idx].InitEvent(eventType, s1, s2); + _pageCurr![idx].InitEvent(eventType, s1, s2); } - private void AddEvent(XmlEventType eventType, string s1, string s2, string s3) + private void AddEvent(XmlEventType eventType, string? s1, string? s2, string? s3) { int idx = NewEvent(); - _pageCurr[idx].InitEvent(eventType, s1, s2, s3); + _pageCurr![idx].InitEvent(eventType, s1, s2, s3); } - private void AddEvent(XmlEventType eventType, string s1, string s2, string s3, object o) + private void AddEvent(XmlEventType eventType, string? s1, string? s2, string? s3, object? o) { int idx = NewEvent(); - _pageCurr[idx].InitEvent(eventType, s1, s2, s3, o); + _pageCurr![idx].InitEvent(eventType, s1, s2, s3, o); } - private void AddEvent(XmlEventType eventType, object o) + private void AddEvent(XmlEventType eventType, object? o) { int idx = NewEvent(); - _pageCurr[idx].InitEvent(eventType, o); + _pageCurr![idx].InitEvent(eventType, o); } private int NewEvent() @@ -551,7 +552,7 @@ namespace System.Xml _singleText.Clear(); } } - else if (_pageSize >= _pageCurr.Length) + else if (_pageSize >= _pageCurr!.Length) { // Create new page _pageCurr = new XmlEvent[_pageSize * 2]; @@ -588,30 +589,30 @@ namespace System.Xml private struct XmlEvent { private XmlEventType _eventType; - private string _s1; - private string _s2; - private string _s3; - private object _o; + private string? _s1; + private string? _s2; + private string? _s3; + private object? _o; public void InitEvent(XmlEventType eventType) { _eventType = eventType; } - public void InitEvent(XmlEventType eventType, string s1) + public void InitEvent(XmlEventType eventType, string? s1) { _eventType = eventType; _s1 = s1; } - public void InitEvent(XmlEventType eventType, string s1, string s2) + public void InitEvent(XmlEventType eventType, string? s1, string? s2) { _eventType = eventType; _s1 = s1; _s2 = s2; } - public void InitEvent(XmlEventType eventType, string s1, string s2, string s3) + public void InitEvent(XmlEventType eventType, string? s1, string? s2, string? s3) { _eventType = eventType; _s1 = s1; @@ -619,7 +620,7 @@ namespace System.Xml _s3 = s3; } - public void InitEvent(XmlEventType eventType, string s1, string s2, string s3, object o) + public void InitEvent(XmlEventType eventType, string? s1, string? s2, string? s3, object? o) { _eventType = eventType; _s1 = s1; @@ -628,7 +629,7 @@ namespace System.Xml _o = o; } - public void InitEvent(XmlEventType eventType, object o) + public void InitEvent(XmlEventType eventType, object? o) { _eventType = eventType; _o = o; @@ -639,22 +640,22 @@ namespace System.Xml get { return _eventType; } } - public string String1 + public string? String1 { get { return _s1; } } - public string String2 + public string? String2 { get { return _s2; } } - public string String3 + public string? String3 { get { return _s3; } } - public object Object + public object? Object { get { return _o; } } 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 bc85615..04ecc7a 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 @@ -7,7 +7,7 @@ namespace System.Xml { internal partial class XmlTextReaderImpl { - static partial void ConvertAbsoluteUnixPathToAbsoluteUri(ref string url, XmlResolver? resolver) + static partial void ConvertAbsoluteUnixPathToAbsoluteUri(ref string? url, XmlResolver? resolver) { // new Uri(uri, UriKind.RelativeOrAbsolute) returns a Relative Uri for absolute unix paths (e.g. /tmp). // We convert the native unix path to a 'file://' uri string to make it an Absolute Uri. 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 7b181e4..684191a 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 @@ -463,7 +463,7 @@ namespace System.Xml { } - internal XmlTextReaderImpl(string url, Stream input, XmlNameTable nt) : this(nt) + internal XmlTextReaderImpl(string? url, Stream input, XmlNameTable nt) : this(nt) { ConvertAbsoluteUnixPathToAbsoluteUri(ref url, resolver: null); _namespaceManager = new XmlNamespaceManager(nt); @@ -495,7 +495,7 @@ namespace System.Xml { } - internal XmlTextReaderImpl(string url, TextReader input, XmlNameTable nt) : this(nt) + internal XmlTextReaderImpl(string? url, TextReader input, XmlNameTable nt) : this(nt) { ConvertAbsoluteUnixPathToAbsoluteUri(ref url, resolver: null); _namespaceManager = new XmlNamespaceManager(nt); @@ -695,7 +695,7 @@ namespace System.Xml // Initializes a new instance of the XmlTextReaderImpl class with the specified arguments. // This constructor is used when creating XmlTextReaderImpl via XmlReader.Create - internal XmlTextReaderImpl(Stream stream, byte[]? bytes, int byteCount, XmlReaderSettings settings, Uri? baseUri, string baseUriStr, + internal XmlTextReaderImpl(Stream stream, byte[]? bytes, int byteCount, XmlReaderSettings settings, Uri? baseUri, string? baseUriStr, XmlParserContext? context, bool closeInput) : this(settings.GetXmlResolver(), settings, context) { @@ -707,7 +707,7 @@ namespace System.Xml if (context.BaseURI != null && context.BaseURI.Length > 0 && !UriEqual(baseUri, baseUriStr, context.BaseURI, settings.GetXmlResolver())) { - if (baseUriStr.Length > 0) + if (baseUriStr!.Length > 0) { Throw(SR.Xml_DoubleBaseUri); } @@ -769,7 +769,7 @@ namespace System.Xml // Initializes a new instance of the XmlTextReaderImpl class with the specified arguments. // This constructor is used when creating XmlTextReaderImpl via XmlReader.Create - internal XmlTextReaderImpl(TextReader input, XmlReaderSettings settings, string baseUriStr, XmlParserContext? context) + internal XmlTextReaderImpl(TextReader input, XmlReaderSettings settings, string? baseUriStr, XmlParserContext? context) : this(settings.GetXmlResolver(), settings, context) { ConvertAbsoluteUnixPathToAbsoluteUri(ref baseUriStr, settings.GetXmlResolver()); @@ -2477,7 +2477,7 @@ namespace System.Xml } } - internal char[]? DtdParserProxy_ParsingBuffer + internal char[] DtdParserProxy_ParsingBuffer { get { @@ -2560,18 +2560,18 @@ namespace System.Xml return this.ReadData(); } - internal int DtdParserProxy_ParseNumericCharRef(StringBuilder internalSubsetBuilder) + internal int DtdParserProxy_ParseNumericCharRef(StringBuilder? internalSubsetBuilder) { EntityType entType; return this.ParseNumericCharRef(true, internalSubsetBuilder, out entType); } - internal int DtdParserProxy_ParseNamedCharRef(bool expand, StringBuilder internalSubsetBuilder) + internal int DtdParserProxy_ParseNamedCharRef(bool expand, StringBuilder? internalSubsetBuilder) { return this.ParseNamedCharRef(expand, internalSubsetBuilder); } - internal void DtdParserProxy_ParsePI(StringBuilder sb) + internal void DtdParserProxy_ParsePI(StringBuilder? sb) { if (sb == null) { @@ -2586,7 +2586,7 @@ namespace System.Xml } } - internal void DtdParserProxy_ParseComment(StringBuilder sb) + internal void DtdParserProxy_ParseComment(StringBuilder? sb) { Debug.Assert(_parsingMode == ParsingMode.Full); @@ -2725,6 +2725,7 @@ namespace System.Xml _ps.eolNormalized = false; } + [DoesNotReturn] internal void DtdParserProxy_Throw(Exception e) { this.Throw(e); @@ -8251,7 +8252,7 @@ namespace System.Xml Encoding? enc = _ps.encoding; PushParsingState(); - InitStringInput(entity.SystemId, enc, string.Empty); + InitStringInput(entity.SystemId!, enc, string.Empty); RegisterEntity(entity); @@ -8269,7 +8270,7 @@ namespace System.Xml PushParsingState(); - InitStringInput(entity.DeclaredUriString ?? string.Empty, enc, entity.Text); + InitStringInput(entity.DeclaredUriString ?? string.Empty, enc, entity.Text!); RegisterEntity(entity); @@ -8278,7 +8279,7 @@ namespace System.Xml _ps.eolNormalized = true; - RegisterConsumedCharacters(entity.Text.Length, true); + RegisterConsumedCharacters(entity.Text!.Length, true); } private void PopEntity() @@ -9746,7 +9747,7 @@ namespace System.Xml } // SxS: URIs are resolved only to be compared. No resource exposure. It's OK to suppress the SxS warning. - private bool UriEqual(Uri? uri1, string uri1Str, string uri2Str, XmlResolver? resolver) + private bool UriEqual(Uri? uri1, string? uri1Str, string? uri2Str, XmlResolver? resolver) { if (resolver == null) { @@ -9996,6 +9997,6 @@ namespace System.Xml Buffer.BlockCopy(src, srcOffset, dst, dstOffset, count); } - static partial void ConvertAbsoluteUnixPathToAbsoluteUri(ref string url, XmlResolver? resolver); + static partial void ConvertAbsoluteUnixPathToAbsoluteUri(ref string? url, XmlResolver? resolver); } } 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 50a4575..72fa418 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.IO; using System.Text; @@ -57,7 +58,7 @@ namespace System.Xml private Task FinishInitAsync() { - switch (_laterInitParam.initType) + switch (_laterInitParam!.initType) { case InitInputType.UriString: return FinishInitUriStringAsync(); @@ -75,14 +76,14 @@ namespace System.Xml private async Task FinishInitUriStringAsync() { - Stream stream = (Stream)(await _laterInitParam.inputUriResolver.GetEntityAsync(_laterInitParam.inputbaseUri, string.Empty, typeof(Stream)).ConfigureAwait(false)); + Stream stream = (Stream)(await _laterInitParam!.inputUriResolver!.GetEntityAsync(_laterInitParam.inputbaseUri!, string.Empty, typeof(Stream)).ConfigureAwait(false)); if (stream == null) { throw new XmlException(SR.Xml_CannotResolveUrl, _laterInitParam.inputUriStr); } - Encoding enc = null; + Encoding? enc = null; // get Encoding from XmlParserContext if (_laterInitParam.inputContext != null) { @@ -92,6 +93,7 @@ namespace System.Xml try { // init ParsingState + Debug.Assert(_reportedBaseUri != null); await InitStreamInputAsync(_laterInitParam.inputbaseUri, _reportedBaseUri, stream, null, 0, enc).ConfigureAwait(false); _reportedEncoding = _ps.encoding; @@ -113,16 +115,17 @@ namespace System.Xml private async Task FinishInitStreamAsync() { - Encoding enc = null; + Encoding? enc = null; // get Encoding from XmlParserContext - if (_laterInitParam.inputContext != null) + if (_laterInitParam!.inputContext != null) { enc = _laterInitParam.inputContext.Encoding; } // init ParsingState - await InitStreamInputAsync(_laterInitParam.inputbaseUri, _reportedBaseUri, _laterInitParam.inputStream, _laterInitParam.inputBytes, _laterInitParam.inputByteCount, enc).ConfigureAwait(false); + Debug.Assert(_reportedBaseUri != null); + await InitStreamInputAsync(_laterInitParam.inputbaseUri, _reportedBaseUri, _laterInitParam!.inputStream!, _laterInitParam.inputBytes, _laterInitParam.inputByteCount, enc).ConfigureAwait(false); _reportedEncoding = _ps.encoding; @@ -137,7 +140,7 @@ namespace System.Xml private async Task FinishInitTextReaderAsync() { // init ParsingState - await InitTextReaderInputAsync(_reportedBaseUri, _laterInitParam.inputTextReader).ConfigureAwait(false); + await InitTextReaderInputAsync(_reportedBaseUri!, _laterInitParam!.inputTextReader!).ConfigureAwait(false); _reportedEncoding = _ps.encoding; @@ -901,7 +904,7 @@ namespace System.Xml // Resolve base URI if (_ps.baseUri == null && !string.IsNullOrEmpty(_ps.baseUriStr)) { - _ps.baseUri = _xmlResolver.ResolveUri(null, _ps.baseUriStr); + _ps.baseUri = _xmlResolver!.ResolveUri(null, _ps.baseUriStr); } await PushExternalEntityOrSubsetAsync(publicId, systemId, _ps.baseUri, null).ConfigureAwait(false); @@ -922,13 +925,13 @@ namespace System.Xml return true; } - private Task InitStreamInputAsync(Uri baseUri, Stream stream, Encoding encoding) + private Task InitStreamInputAsync(Uri baseUri, Stream stream, Encoding? encoding) { Debug.Assert(baseUri != null); return InitStreamInputAsync(baseUri, baseUri.ToString(), stream, null, 0, encoding); } - private async Task InitStreamInputAsync(Uri baseUri, string baseUriStr, Stream stream, byte[] bytes, int byteCount, Encoding encoding) + private async Task InitStreamInputAsync(Uri? baseUri, string baseUriStr, Stream stream, byte[]? bytes, int byteCount, Encoding? encoding) { Debug.Assert(_ps.charPos == 0 && _ps.charsUsed == 0 && _ps.textReader == null); Debug.Assert(baseUriStr != null); @@ -1007,7 +1010,7 @@ namespace System.Xml return InitTextReaderInputAsync(baseUriStr, null, input); } - private Task InitTextReaderInputAsync(string baseUriStr, Uri baseUri, TextReader input) + private Task InitTextReaderInputAsync(string baseUriStr, Uri? baseUri, TextReader input) { Debug.Assert(_ps.charPos == 0 && _ps.charsUsed == 0 && _ps.stream == null); Debug.Assert(baseUriStr != null); @@ -1066,7 +1069,7 @@ namespace System.Xml // Switches the reader's encoding private Task SwitchEncodingAsync(Encoding newEncoding) { - if ((newEncoding.WebName != _ps.encoding.WebName || _ps.decoder is SafeAsciiDecoder) && !_afterResetState) + if ((newEncoding.WebName != _ps.encoding!.WebName || _ps.decoder is SafeAsciiDecoder) && !_afterResetState) { Debug.Assert(_ps.stream != null); UnDecodeChars(); @@ -1118,7 +1121,7 @@ namespace System.Xml // the byte buffer is full -> allocate a new one if (_ps.bytesUsed - _ps.bytePos < MaxByteSequenceLen) { - if (_ps.bytes.Length - _ps.bytesUsed < MaxByteSequenceLen) + if (_ps.bytes!.Length - _ps.bytesUsed < MaxByteSequenceLen) { byte[] newBytes = new byte[_ps.bytes.Length * 2]; BlockCopy(_ps.bytes, 0, newBytes, 0, _ps.bytesUsed); @@ -1176,7 +1179,7 @@ namespace System.Xml } else { - BlockCopy(_ps.bytes, _ps.bytePos, _ps.bytes, 0, bytesLeft); + BlockCopy(_ps.bytes!, _ps.bytePos, _ps.bytes!, 0, bytesLeft); _ps.bytesUsed = bytesLeft; } _ps.bytePos = 0; @@ -1190,7 +1193,7 @@ namespace System.Xml if (!_ps.isStreamEof) { // read new bytes - if (_ps.bytePos == _ps.bytesUsed && _ps.bytes.Length - _ps.bytesUsed > 0) + if (_ps.bytePos == _ps.bytesUsed && _ps.bytes!.Length - _ps.bytesUsed > 0) { int read = await _ps.stream.ReadAsync(_ps.bytes.AsMemory(_ps.bytesUsed)).ConfigureAwait(false); if (read == 0) @@ -1267,7 +1270,7 @@ namespace System.Xml // parse version, encoding & standalone attributes int xmlDeclState = 0; // - Encoding encoding = null; + Encoding? encoding = null; while (true) { @@ -1307,7 +1310,7 @@ namespace System.Xml if (_afterResetState) { // check for invalid encoding switches to default encoding - string encodingName = _ps.encoding.WebName; + string encodingName = _ps.encoding!.WebName; if (encodingName != "utf-8" && encodingName != "utf-16" && encodingName != "utf-16BE" && !(_ps.encoding is Ucs4Encoding)) { @@ -1344,7 +1347,7 @@ namespace System.Xml // read attribute name int nameEndPos = await ParseNameAsync().ConfigureAwait(false); - NodeData attr = null; + NodeData? attr = null; switch (_ps.chars[_ps.charPos]) { case 'v': @@ -1387,7 +1390,7 @@ namespace System.Xml } if (!isTextDecl) { - attr.SetLineInfo(_ps.LineNo, _ps.LinePos); + attr!.SetLineInfo(_ps.LineNo, _ps.LinePos); } sb.Append(_ps.chars, _ps.charPos, nameEndPos - _ps.charPos); _ps.charPos = nameEndPos; @@ -1418,7 +1421,7 @@ namespace System.Xml _ps.charPos++; if (!isTextDecl) { - attr.quoteChar = quoteChar; + attr!.quoteChar = quoteChar; attr.SetLineInfo2(_ps.LineNo, _ps.LinePos); } @@ -1452,7 +1455,7 @@ namespace System.Xml #endif if (!isTextDecl) { - attr.SetValue(_ps.chars, _ps.charPos, pos - _ps.charPos); + attr!.SetValue(_ps.chars, _ps.charPos, pos - _ps.charPos); } xmlDeclState = 1; } @@ -1467,7 +1470,7 @@ namespace System.Xml encoding = CheckEncoding(encName); if (!isTextDecl) { - attr.SetValue(encName); + attr!.SetValue(encName); } xmlDeclState = 2; break; @@ -1487,7 +1490,7 @@ namespace System.Xml } if (!isTextDecl) { - attr.SetValue(_ps.chars, _ps.charPos, pos - _ps.charPos); + attr!.SetValue(_ps.chars, _ps.charPos, pos - _ps.charPos); } xmlDeclState = 3; break; @@ -1533,7 +1536,7 @@ namespace System.Xml if (_afterResetState) { // check for invalid encoding switches to default encoding - string encodingName = _ps.encoding.WebName; + string encodingName = _ps.encoding!.WebName; if (encodingName != "utf-8" && encodingName != "utf-16" && encodingName != "utf-16BE" && !(_ps.encoding is Ucs4Encoding)) { @@ -2048,7 +2051,7 @@ namespace System.Xml char[] chars = _ps.chars; // push namespace context - _namespaceManager.PushScope(); + _namespaceManager!.PushScope(); // init the NodeData class if (colonPos == -1 || !_supportNamespaces) @@ -2409,7 +2412,7 @@ namespace System.Xml { int pos = _ps.charPos; char[] chars = _ps.chars; - NodeData attr = null; + NodeData? attr = null; Debug.Assert(_attrCount == 0); @@ -2727,7 +2730,7 @@ namespace System.Xml // Needed only for XmlTextReader (reporting of entities) int valueChunkStartPos = 0; LineInfo valueChunkLineInfo = new LineInfo(_ps.lineNo, _ps.LinePos); - NodeData lastChunk = null; + NodeData? lastChunk = null; Debug.Assert(_stringBuilder.Length == 0); @@ -2890,7 +2893,7 @@ namespace System.Xml NodeData entityChunk = new NodeData(); entityChunk.lineInfo = entityLineInfo; entityChunk.depth = attr.depth + 1; - entityChunk.SetNamedNode(XmlNodeType.EntityReference, _ps.entity.Name); + entityChunk.SetNamedNode(XmlNodeType.EntityReference, _ps.entity!.Name); AddAttributeChunkToList(attr, entityChunk, ref lastChunk); _fullAttrCleanup = true; @@ -3060,7 +3063,7 @@ namespace System.Xml // Returns true if a node has been parsed and its data set to curNode. // Returns false when a whitespace has been parsed and ignored (according to current whitespace handling) or when parsing mode is not Full. // Also returns false if there is no text to be parsed. - private async Task _ParseTextAsync(Task<(int, int, int, bool)> parseTask) + private async Task _ParseTextAsync(Task<(int, int, int, bool)>? parseTask) { int startPos; int endPos; @@ -3930,7 +3933,7 @@ namespace System.Xml // return false == unexpanded external entity, stop parsing and return private async Task HandleGeneralEntityReferenceAsync(string name, bool isInAttributeValue, bool pushFakeEntityIfNullResolver, int entityStartLinePos) { - IDtdEntityInfo entity = null; + IDtdEntityInfo? entity = null; if (_dtdInfo == null && _fragmentParserContext != null && _fragmentParserContext.HasDtdInfo && _dtdProcessing == DtdProcessing.Parse) { @@ -4020,7 +4023,7 @@ namespace System.Xml // Parses processing instruction; if piInDtdStringBuilder != null, the processing instruction is in DTD and // it will be saved in the passed string builder (target, whitespace & value). - private async Task ParsePIAsync(StringBuilder piInDtdStringBuilder) + private async Task ParsePIAsync(StringBuilder? piInDtdStringBuilder) { if (_parsingMode == ParsingMode.Full) { @@ -4928,7 +4931,7 @@ namespace System.Xml } } - private async Task EatWhitespacesAsync(StringBuilder sb) + private async Task EatWhitespacesAsync(StringBuilder? sb) { int pos = _ps.charPos; int wsCount = 0; @@ -5035,7 +5038,7 @@ namespace System.Xml // - returns position of the end of the character reference, that is of the character next to the original ';' // - if (expand == true) then ps.charPos is changed to point to the replaced character - private async Task<(EntityType, int)> ParseNumericCharRefAsync(bool expand, StringBuilder internalSubsetBuilder) + private async Task<(EntityType, int)> ParseNumericCharRefAsync(bool expand, StringBuilder? internalSubsetBuilder) { EntityType entityType; @@ -5070,7 +5073,7 @@ namespace System.Xml // - replaces the last character of the entity reference (';') with the referenced character (if expand == true) // - returns position of the end of the character reference, that is of the character next to the original ';' // - if (expand == true) then ps.charPos is changed to point to the replaced character - private async Task ParseNamedCharRefAsync(bool expand, StringBuilder internalSubsetBuilder) + private async Task ParseNamedCharRefAsync(bool expand, StringBuilder? internalSubsetBuilder) { while (true) { @@ -5246,7 +5249,7 @@ namespace System.Xml // This method resolves and opens an external DTD subset or an external entity based on its SYSTEM or PUBLIC ID. // SxS: This method may expose a name if a resource in baseUri (ref) parameter. - private async Task PushExternalEntityOrSubsetAsync(string publicId, string systemId, Uri baseUri, string entityName) + private async Task PushExternalEntityOrSubsetAsync(string? publicId, string? systemId, Uri? baseUri, string? entityName) { Uri uri; @@ -5255,7 +5258,7 @@ namespace System.Xml { try { - uri = _xmlResolver.ResolveUri(baseUri, publicId); + uri = _xmlResolver!.ResolveUri(baseUri, publicId); if (await OpenAndPushAsync(uri).ConfigureAwait(false)) { return; @@ -5268,7 +5271,7 @@ namespace System.Xml } // Then try SYSTEM Id - uri = _xmlResolver.ResolveUri(baseUri, systemId); + uri = _xmlResolver!.ResolveUri(baseUri, systemId); try { if (await OpenAndPushAsync(uri).ConfigureAwait(false)) @@ -5290,7 +5293,7 @@ namespace System.Xml if (entityName == null) { - ThrowWithoutLineInfo(SR.Xml_CannotResolveExternalSubset, new string[] { (publicId != null ? publicId : string.Empty), systemId }, null); + ThrowWithoutLineInfo(SR.Xml_CannotResolveExternalSubset, new string?[] { (publicId != null ? publicId : string.Empty), systemId }, null); } else { @@ -5347,11 +5350,11 @@ namespace System.Xml if (!IsResolverNull) { - Uri entityBaseUri = null; + Uri? entityBaseUri = null; // Resolve base URI if (!string.IsNullOrEmpty(entity.BaseUriString)) { - entityBaseUri = _xmlResolver.ResolveUri(null, entity.BaseUriString); + entityBaseUri = _xmlResolver!.ResolveUri(null, entity.BaseUriString); } await PushExternalEntityOrSubsetAsync(entity.PublicId, entity.SystemId, entityBaseUri, entity.Name).ConfigureAwait(false); @@ -5371,10 +5374,10 @@ namespace System.Xml } else { - Encoding enc = _ps.encoding; + Encoding? enc = _ps.encoding; PushParsingState(); - InitStringInput(entity.SystemId, enc, string.Empty); + InitStringInput(entity.SystemId!, enc, string.Empty); RegisterEntity(entity); 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 cea09b3..be5a763 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 @@ -26,7 +26,7 @@ namespace System.Xml private struct ParsingState { // character buffer - internal char[]? chars; + internal char[] chars; internal int charPos; internal int charsUsed; internal Encoding? encoding; @@ -66,7 +66,7 @@ namespace System.Xml internal void Clear() { - chars = null; + chars = null!; charPos = 0; charsUsed = 0; encoding = null; @@ -200,7 +200,7 @@ namespace System.Xml get { return _reader.DtdParserProxy_IsEof; } } - char[]? IDtdParserAdapter.ParsingBuffer + char[] IDtdParserAdapter.ParsingBuffer { get { return _reader.DtdParserProxy_ParsingBuffer; } } @@ -246,22 +246,22 @@ namespace System.Xml return _reader.DtdParserProxy_ReadData(); } - int IDtdParserAdapter.ParseNumericCharRef(StringBuilder internalSubsetBuilder) + int IDtdParserAdapter.ParseNumericCharRef(StringBuilder? internalSubsetBuilder) { return _reader.DtdParserProxy_ParseNumericCharRef(internalSubsetBuilder); } - int IDtdParserAdapter.ParseNamedCharRef(bool expand, StringBuilder internalSubsetBuilder) + int IDtdParserAdapter.ParseNamedCharRef(bool expand, StringBuilder? internalSubsetBuilder) { return _reader.DtdParserProxy_ParseNamedCharRef(expand, internalSubsetBuilder); } - void IDtdParserAdapter.ParsePI(StringBuilder sb) + void IDtdParserAdapter.ParsePI(StringBuilder? sb) { _reader.DtdParserProxy_ParsePI(sb); } - void IDtdParserAdapter.ParseComment(StringBuilder sb) + void IDtdParserAdapter.ParseComment(StringBuilder? sb) { _reader.DtdParserProxy_ParseComment(sb); } @@ -276,7 +276,7 @@ namespace System.Xml return _reader.DtdParserProxy_PopEntity(out oldEntity, out newEntityId); } - bool IDtdParserAdapter.PushExternalSubset(string systemId, string publicId) + bool IDtdParserAdapter.PushExternalSubset(string? systemId, string? publicId) { return _reader.DtdParserProxy_PushExternalSubset(systemId, publicId); } @@ -287,6 +287,7 @@ namespace System.Xml _reader.DtdParserProxy_PushInternalDtd(baseUri, internalDtd); } + [DoesNotReturn] void IDtdParserAdapter.Throw(Exception e) { _reader.DtdParserProxy_Throw(e); 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 ee60888..a062d03 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.IO; using System.Text; 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 28d90db..28966fb 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Xml; using System.Xml.Schema; @@ -16,7 +17,7 @@ namespace System.Xml // Fields // protected XmlReader reader; - protected IXmlLineInfo readerAsIXmlLineInfo; + protected IXmlLineInfo? readerAsIXmlLineInfo; // // Constructor @@ -31,7 +32,7 @@ namespace System.Xml // // XmlReader implementation // - public override XmlReaderSettings Settings { get { return reader.Settings; } } + public override XmlReaderSettings? Settings { get { return reader.Settings; } } public override XmlNodeType NodeType { get { return reader.NodeType; } } public override string Name { get { return reader.Name; } } public override string LocalName { get { return reader.LocalName; } } @@ -40,7 +41,7 @@ namespace System.Xml public override bool HasValue { get { return reader.HasValue; } } public override string Value { get { return reader.Value; } } public override int Depth { get { return reader.Depth; } } - public override string BaseURI { get { return reader.BaseURI; } } + public override string? BaseURI { get { return reader.BaseURI; } } public override bool IsEmptyElement { get { return reader.IsEmptyElement; } } public override bool IsDefault { get { return reader.IsDefault; } } public override XmlSpace XmlSpace { get { return reader.XmlSpace; } } @@ -53,15 +54,15 @@ namespace System.Xml public override XmlNameTable NameTable { get { return reader.NameTable; } } public override bool CanResolveEntity { get { return reader.CanResolveEntity; } } - public override IXmlSchemaInfo SchemaInfo { get { return reader.SchemaInfo; } } + public override IXmlSchemaInfo? SchemaInfo { get { return reader.SchemaInfo; } } public override char QuoteChar { get { return reader.QuoteChar; } } - 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); } @@ -116,7 +117,7 @@ namespace System.Xml reader.Skip(); } - public override string LookupNamespace(string prefix) + public override string? LookupNamespace(string prefix) { return reader.LookupNamespace(prefix); } @@ -158,7 +159,7 @@ namespace System.Xml // // Internal methods // - internal override IDtdInfo DtdInfo + internal override IDtdInfo? DtdInfo { get { 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 c5573cb..501718f 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Xml; using System.Xml.Schema; 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 332dad4..05519fa 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.IO; using System.Xml.Schema; @@ -29,12 +30,12 @@ namespace System.Xml return writer.WriteEndDocumentAsync(); } - public override Task WriteDocTypeAsync(string name, string pubid, string sysid, string subset) + public override Task WriteDocTypeAsync(string name, string? pubid, string? sysid, string subset) { return writer.WriteDocTypeAsync(name, pubid, sysid, subset); } - public override Task WriteStartElementAsync(string prefix, string localName, string ns) + public override Task WriteStartElementAsync(string? prefix, string localName, string? ns) { return writer.WriteStartElementAsync(prefix, localName, ns); } @@ -49,7 +50,7 @@ namespace System.Xml return writer.WriteFullEndElementAsync(); } - protected internal override Task WriteStartAttributeAsync(string prefix, string localName, string ns) + protected internal override Task WriteStartAttributeAsync(string? prefix, string localName, string? ns) { return writer.WriteStartAttributeAsync(prefix, localName, ns); } 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 724e58d..6d4d5ec 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.IO; using System.Text; using System.Xml.Schema; @@ -39,7 +40,7 @@ namespace System.Xml goto case CachingReaderState.Record; case CachingReaderState.Record: - ValidatingReaderNodeData recordedNode = null; + ValidatingReaderNodeData? recordedNode = null; if (await _coreReader.ReadAsync().ConfigureAwait(false)) { switch (_coreReader.NodeType) 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 2115a78..e49c541 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 @@ -2386,7 +2386,7 @@ namespace System.Xml if (_validationState == ValidatingReaderState.OnDefaultAttribute) { XmlSchemaAttribute schemaAttr = _attributePSVI.attributeSchemaInfo.SchemaAttribute; - originalStringValue = (schemaAttr.DefaultValue != null) ? schemaAttr.DefaultValue : schemaAttr.FixedValue; + originalStringValue = (schemaAttr.DefaultValue != null) ? schemaAttr.DefaultValue : schemaAttr.FixedValue!; } return ReturnBoxedValue(_attributePSVI.typedAttributeValue, AttributeSchemaInfo.XmlType, unwrapTypedValue)!; 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 a9953d2..7b6dd75 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 @@ -699,7 +699,7 @@ namespace System.Xml if (_validationState == ValidatingReaderState.OnDefaultAttribute) { XmlSchemaAttribute schemaAttr = _attributePSVI.attributeSchemaInfo.SchemaAttribute; - originalStringValue = (schemaAttr.DefaultValue != null) ? schemaAttr.DefaultValue : schemaAttr.FixedValue; + originalStringValue = (schemaAttr.DefaultValue != null) ? schemaAttr.DefaultValue : schemaAttr.FixedValue!; } tuple = new Tuple(originalStringValue, ReturnBoxedValue(_attributePSVI.typedAttributeValue, AttributeSchemaInfo.XmlType, unwrapTypedValue)!); 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 415d1e1..2504e4f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/DiagnosticsSwitches.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/DiagnosticsSwitches.cs @@ -2,14 +2,15 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Xml { using System.Diagnostics; internal static class DiagnosticsSwitches { - private static volatile BooleanSwitch s_keepTempFiles; - private static volatile BooleanSwitch s_nonRecursiveTypeLoading; + private static volatile BooleanSwitch? s_keepTempFiles; + private static volatile BooleanSwitch? s_nonRecursiveTypeLoading; public static BooleanSwitch KeepTempFiles { @@ -19,6 +20,7 @@ namespace System.Xml { s_keepTempFiles = new BooleanSwitch("XmlSerialization.Compilation", "Keep XmlSerialization generated (temp) files."); } + return s_keepTempFiles; } } @@ -31,6 +33,7 @@ namespace System.Xml { s_nonRecursiveTypeLoading = new BooleanSwitch("XmlSerialization.NonRecursiveTypeLoading", "Turn on non-recursive algorithm generating XmlMappings for CLR types."); } + return s_nonRecursiveTypeLoading; } } 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 26d4116..1a34708 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/EmptyEnumerator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/EmptyEnumerator.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#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 14e3281..43ac77f 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Reflection; @@ -11,12 +12,12 @@ namespace System.Xml.Extensions { #region Contract compliance for System.Type - internal static ConstructorInfo GetConstructor(this Type type, BindingFlags bindingFlags, Type[] parameterTypes) + internal static ConstructorInfo? GetConstructor(this Type type, BindingFlags bindingFlags, Type[] parameterTypes) { return type.GetConstructor(bindingFlags, null, parameterTypes, 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) { return type.GetMethod(methodName, bindingFlags, null, parameterTypes, null); } @@ -33,10 +34,11 @@ namespace System.Xml.Extensions throw new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Uri")); } } - if (!Uri.TryCreate(s, UriKind.RelativeOrAbsolute, out Uri uri)) + if (!Uri.TryCreate(s, UriKind.RelativeOrAbsolute, out Uri? uri)) { throw new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Uri")); } + return uri; } } 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 4f57140..dfdc181 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/HWStack.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/HWStack.cs @@ -2,9 +2,9 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; - namespace System.Xml { // This stack is designed to minimize object creation for the @@ -35,18 +35,21 @@ namespace System.Xml { throw new XmlException(SR.Xml_StackOverflow, string.Empty); } + object[] newstack = new object[_size + _growthRate]; if (_used > 0) { System.Array.Copy(_stack, newstack, _used); } + _stack = newstack; _size += _growthRate; } + return _stack[_used++]; } - internal object Pop() + internal object? Pop() { if (0 < _used) { @@ -54,10 +57,11 @@ namespace System.Xml object result = _stack[_used]; return result; } + return null; } - internal object Peek() + internal object? Peek() { return _used > 0 ? _stack[_used - 1] : null; } 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 ce284aa..9ba64e1 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/IApplicationResourceStreamResolver.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/IApplicationResourceStreamResolver.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#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 72dfeba..19a8d63 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/IHasXmlNode.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/IHasXmlNode.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Xml { public interface IHasXmlNode 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 1b76b28..a7bf894 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/LineInfo.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/LineInfo.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#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 052670e..eadc7ab 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/MTNameTable.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/MTNameTable.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable #if MTNAMETABLE using System; using System.IO; 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 18ed298..056fb35 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Ref.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Ref.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; namespace System.Xml @@ -11,13 +12,13 @@ namespace System.Xml /// internal static class Ref { - public static bool Equal(string strA, string strB) + public static bool Equal(string? strA, string? strB) { #if DEBUG - if (((object)strA != (object)strB) && string.Equals(strA, strB)) + if (((object?)strA != (object?)strB) && string.Equals(strA, strB)) Debug.Fail("Ref.Equal: Object comparison used for non-atomized string '" + strA + "'"); #endif - return (object)strA == (object)strB; + return (object?)strA == (object?)strB; } // Prevent typos. If someone uses Ref.Equals instead of Ref.Equal, 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 f8f3073..5ae750f 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Xml.Resolvers { // 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 62049b7..3d9ee1c 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.IO; using System.Xml; using System.Threading.Tasks; @@ -16,7 +17,7 @@ namespace System.Xml.Resolvers public partial class XmlPreloadedResolver : XmlResolver { public override Task GetEntityAsync(Uri absoluteUri, - string role, + string? role, Type ofObjectToReturn) { if (absoluteUri == null) @@ -24,7 +25,7 @@ namespace System.Xml.Resolvers throw new ArgumentNullException(nameof(absoluteUri)); } - PreloadedData data; + PreloadedData? data; if (!_mappings.TryGetValue(absoluteUri, out data)) { if (_fallbackResolver != null) 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 44ec9d6..02952cd 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Xml.Schema { using System.Xml.XPath; @@ -11,6 +12,7 @@ namespace System.Xml.Schema using System.Collections; using System.Xml.Schema; using MS.Internal.Xml.XPath; + using System.Diagnostics.CodeAnalysis; /*--------------------------------------------------------------------------------------------- * * Dynamic Part Below... * @@ -41,7 +43,6 @@ namespace System.Xml.Schema internal void SetDepth(int depth) { this.rootDepth = this.curDepth = depth; - return; } // "a/b/c" pointer from b move to a @@ -101,10 +102,12 @@ namespace System.Xml.Schema { this.isMatch = false; } + if (!AxisStack.Equal(this.curNode.Name, this.curNode.Urn, name, URN)) { return false; } + if (this.curDepth == -1) { SetDepth(depth); @@ -113,19 +116,22 @@ namespace System.Xml.Schema { return false; } + // matched ... if (this.curNode == parent.TopNode) { this.isMatch = true; return true; } + // move down this.curNode - DoubleLinkAxis nowNode = (DoubleLinkAxis)(this.curNode.Next); + DoubleLinkAxis nowNode = (DoubleLinkAxis)(this.curNode.Next!); if (Asttree.IsAttribute(nowNode)) { this.isMatch = true; // for attribute return false; } + this.curNode = nowNode; this.curDepth++; return false; @@ -214,7 +220,7 @@ namespace System.Xml.Schema for (int i = 0; i < _stack.Count; ++i) { - ((AxisElement)_stack[i]).MoveToParent(depth, _subtree); + ((AxisElement)_stack[i]!).MoveToParent(depth, _subtree); } // in ".//"'s case, since each time you push one new element while match, why not pop one too while match? @@ -236,7 +242,7 @@ namespace System.Xml.Schema } for (int i = 0; i < _stack.Count; ++i) { - if (((AxisElement)_stack[i]).MoveToChild(name, URN, depth, _subtree)) + if (((AxisElement)_stack[i]!).MoveToChild(name, URN, depth, _subtree)) { result = true; } @@ -268,7 +274,7 @@ namespace System.Xml.Schema for (int i = 0; i < _stack.Count; ++i) { - AxisElement eaxis = (AxisElement)_stack[i]; + AxisElement eaxis = (AxisElement)_stack[i]!; if ((eaxis.isMatch) && (eaxis.CurNode == _subtree.TopNode.Input)) { result = true; @@ -312,7 +318,7 @@ namespace System.Xml.Schema // new one stack element for each one for (int i = 0; i < axisTree.SubtreeArray.Count; ++i) { - AxisStack stack = new AxisStack((ForwardAxis)axisTree.SubtreeArray[i], this); + AxisStack stack = new AxisStack((ForwardAxis)axisTree.SubtreeArray[i]!, this); _axisStack.Add(stack); } _isActive = true; @@ -330,7 +336,7 @@ namespace System.Xml.Schema bool result = false; for (int i = 0; i < _axisStack.Count; ++i) { - AxisStack stack = (AxisStack)_axisStack[i]; + AxisStack stack = (AxisStack)_axisStack[i]!; // special case for self tree "." | ".//." if (stack.Subtree.IsSelfAxis) { @@ -349,6 +355,7 @@ namespace System.Xml.Schema // run everyone once } } + return result; } @@ -367,7 +374,7 @@ namespace System.Xml.Schema } for (int i = 0; i < _axisStack.Count; ++i) { - ((AxisStack)_axisStack[i]).MoveToParent(localname, URN, _currentDepth); + ((AxisStack)_axisStack[i]!).MoveToParent(localname, URN, _currentDepth); } _currentDepth--; return false; @@ -383,7 +390,7 @@ namespace System.Xml.Schema bool result = false; for (int i = 0; i < _axisStack.Count; ++i) { - if (((AxisStack)_axisStack[i]).MoveToAttribute(localname, URN, _currentDepth + 1)) + if (((AxisStack)_axisStack[i]!).MoveToAttribute(localname, URN, _currentDepth + 1)) { // don't change depth for attribute, but depth is add 1 result = true; } @@ -399,9 +406,9 @@ namespace System.Xml.Schema // each node in the xpath tree internal class DoubleLinkAxis : Axis { - internal Axis next; + internal Axis? next; - internal Axis Next + internal Axis? Next { get { return this.next; } set { this.next = value; } @@ -421,13 +428,15 @@ namespace System.Xml.Schema } // recursive here - internal static DoubleLinkAxis ConvertTree(Axis axis) + [return: NotNullIfNotNull("axis")] + internal static DoubleLinkAxis? ConvertTree(Axis? axis) { if (axis == null) { return null; } - return (new DoubleLinkAxis(axis, ConvertTree((Axis)(axis.Input)))); + + return new DoubleLinkAxis(axis, ConvertTree((Axis)axis.Input)); } } @@ -491,7 +500,7 @@ namespace System.Xml.Schema internal class Asttree { // set private then give out only get access, to keep it intact all along - private ArrayList _fAxisArray; + private ArrayList _fAxisArray = null!; private readonly string _xpathexpr; private readonly bool _isField; // field or selector private readonly XmlNamespaceManager _nsmgr; @@ -568,7 +577,7 @@ namespace System.Xml.Schema Axis stepAst; for (int i = 0; i < AstArray.Count; ++i) { - Axis ast = (Axis)AstArray[i]; + Axis ast = (Axis)AstArray[i]!; // Restricted form // field can have an attribute: 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 01af3b9..06389c7 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Xml.Schema { using System.Collections; @@ -166,8 +167,8 @@ namespace System.Xml.Schema private bool IsValidAttributeGroupRedefine(XmlSchemaObject existingObject, XmlSchemaObject item, XmlSchemaObjectTable table) { - XmlSchemaAttributeGroup attGroup = item as XmlSchemaAttributeGroup; - XmlSchemaAttributeGroup existingAttGroup = existingObject as XmlSchemaAttributeGroup; + XmlSchemaAttributeGroup attGroup = (item as XmlSchemaAttributeGroup)!; + XmlSchemaAttributeGroup existingAttGroup = (existingObject as XmlSchemaAttributeGroup)!; if (existingAttGroup == attGroup.Redefined) { //attribute group is the redefinition of existingObject if (existingAttGroup.AttributeUses.Count == 0) @@ -185,8 +186,8 @@ namespace System.Xml.Schema private bool IsValidGroupRedefine(XmlSchemaObject existingObject, XmlSchemaObject item, XmlSchemaObjectTable table) { - XmlSchemaGroup group = item as XmlSchemaGroup; - XmlSchemaGroup existingGroup = existingObject as XmlSchemaGroup; + XmlSchemaGroup group = (item as XmlSchemaGroup)!; + XmlSchemaGroup existingGroup = (existingObject as XmlSchemaGroup)!; if (existingGroup == group.Redefined) { //group is the redefinition of existingObject if (existingGroup.CanonicalParticle == null) @@ -204,8 +205,8 @@ namespace System.Xml.Schema private bool IsValidTypeRedefine(XmlSchemaObject existingObject, XmlSchemaObject item, XmlSchemaObjectTable table) { - XmlSchemaType schemaType = item as XmlSchemaType; - XmlSchemaType existingType = existingObject as XmlSchemaType; + XmlSchemaType schemaType = (item as XmlSchemaType)!; + XmlSchemaType existingType = (existingObject as XmlSchemaType)!; if (existingType == schemaType.Redefined) { //schemaType is the redefinition of existingObject if (existingType.ElementDecl == null) 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 237d763..07e75b0 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 @@ -179,11 +179,11 @@ namespace System.Xml.Schema return; } - ContentValidator contentValidator = context.ElementDecl.ContentValidator; + ContentValidator contentValidator = context.ElementDecl!.ContentValidator; XmlSchemaContentType contentType = contentValidator.ContentType; if (contentType == XmlSchemaContentType.ElementOnly) { - ArrayList names = contentValidator.ExpectedElements(context, false); + ArrayList? names = contentValidator.ExpectedElements(context, false); if (names == null) { SendValidationEvent(SR.Sch_InvalidTextInElement, XmlSchemaValidator.BuildElementName(context.LocalName, context.Namespace)); @@ -211,7 +211,7 @@ namespace System.Xml.Schema Debug.Assert(context != null); if (context.NeedValidateChildren) { - XmlSchemaContentType contentType = context.ElementDecl.ContentValidator.ContentType; + XmlSchemaContentType contentType = context.ElementDecl!.ContentValidator.ContentType; if (context.IsNill) { SendValidationEvent(SR.Sch_ContentInNill, XmlSchemaValidator.QNameString(context.LocalName, context.Namespace)); 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 cbd8555..5ce6524 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Xml.Schema { using System.Text; @@ -15,8 +16,10 @@ namespace System.Xml.Schema private int _count; private uint[] _bits; - private BitSet() + private BitSet(int count, uint[] bits) { + _count = count; + _bits = bits; } public BitSet(int count) @@ -147,7 +150,7 @@ namespace System.Xml.Schema } - public override bool Equals(object obj) + public override bool Equals(object? obj) { // assume the same type if (obj != null) @@ -195,10 +198,7 @@ namespace System.Xml.Schema public BitSet Clone() { - BitSet newset = new BitSet(); - newset._count = _count; - newset._bits = (uint[])_bits.Clone(); - return newset; + return new BitSet(_count, (uint[])_bits.Clone()); } 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 9e47bfc..76ac3f7 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Xml.Schema { using System.Collections; @@ -18,7 +19,7 @@ namespace System.Xml.Schema // Original schema (used for reference equality only) // stored only when the chameleonLocation is an empty URI in which case the location // is not a good enough identification of the schema - internal XmlSchema originalSchema; + internal XmlSchema? originalSchema; private int _hashCode; /// @@ -50,13 +51,13 @@ namespace System.Xml.Schema return _hashCode; } - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (Ref.ReferenceEquals(this, obj)) { return true; } - ChameleonKey cKey = obj as ChameleonKey; + ChameleonKey? cKey = obj as ChameleonKey; if (cKey != null) { // We want to compare the target NS and the schema location. 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 a5363db..353b53a 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Xml.Schema { using System.Text; @@ -14,8 +15,8 @@ namespace System.Xml.Schema { internal XmlQualifiedName name = XmlQualifiedName.Empty; private readonly ConstraintRole _role; - private readonly Asttree _selector; - private readonly Asttree[] _fields; + private readonly Asttree _selector = null!; + private readonly Asttree[] _fields = null!; internal XmlQualifiedName refer = XmlQualifiedName.Empty; public enum ConstraintRole 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 c361d8a..d1c1f51 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Xml.Schema { using System; @@ -18,8 +19,8 @@ namespace System.Xml.Schema internal CompiledIdentityConstraint constraint; // pointer to constraint internal SelectorActiveAxis axisSelector; internal ArrayList axisFields; // Add tableDim * LocatedActiveAxis in a loop - internal Hashtable qualifiedTable; // Checking confliction - internal Hashtable keyrefTable; // several keyref tables having connections to this one is possible + internal Hashtable? qualifiedTable; // Checking confliction + internal Hashtable? keyrefTable; // several keyref tables having connections to this one is possible private readonly int _tableDim; // dimension of table = numbers of fields; internal int TableDim @@ -84,7 +85,7 @@ namespace System.Xml.Schema public int lastDepth { - get { return (_KSpointer == 0) ? -1 : ((KSStruct)_KSs[_KSpointer - 1]).depth; } + get { return (_KSpointer == 0) ? -1 : ((KSStruct)_KSs[_KSpointer - 1]!).depth; } } public SelectorActiveAxis(Asttree axisTree, ConstraintStruct cs) : base(axisTree) @@ -115,7 +116,7 @@ namespace System.Xml.Schema if (_KSpointer < _KSs.Count) { // reuse, clear up KSs.KSpointer - kss = (KSStruct)_KSs[_KSpointer]; + kss = (KSStruct)_KSs[_KSpointer]!; kss.ks = ks; // reactivate LocatedActiveAxis for (int i = 0; i < _cs.TableDim; i++) @@ -141,7 +142,7 @@ namespace System.Xml.Schema public KeySequence PopKS() { - return ((KSStruct)_KSs[--_KSpointer]).ks; + return ((KSStruct)_KSs[--_KSpointer]!).ks; } } @@ -187,7 +188,7 @@ namespace System.Xml.Schema } } - private DecimalStruct _dstruct = null; + private DecimalStruct? _dstruct = null; private object _ovalue; private readonly string _svalue; // only for output private XmlSchemaDatatype _xsdtype; @@ -352,29 +353,31 @@ namespace System.Xml.Schema } else { //this is a list and other is a single value - Array arr1 = this.Value as System.Array; - XmlAtomicValue[] atomicValues1 = arr1 as XmlAtomicValue[]; + Array? arr1 = this.Value as System.Array; + XmlAtomicValue[]? atomicValues1 = arr1 as XmlAtomicValue[]; if (atomicValues1 != null) { // this is a list of union - return atomicValues1.Length == 1 && atomicValues1.GetValue(0).Equals(other.Value); + return atomicValues1.Length == 1 && atomicValues1.GetValue(0)!.Equals(other.Value); } else { - return arr1.Length == 1 && arr1.GetValue(0).Equals(other.Value); + Debug.Assert(arr1 != null); + return arr1.Length == 1 && arr1.GetValue(0)!.Equals(other.Value); } } } else if (other.IsList) { - Array arr2 = other.Value as System.Array; - XmlAtomicValue[] atomicValues2 = arr2 as XmlAtomicValue[]; + Array? arr2 = other.Value as System.Array; + XmlAtomicValue[]? atomicValues2 = arr2 as XmlAtomicValue[]; if (atomicValues2 != null) { // other is a list of union - return atomicValues2.Length == 1 && atomicValues2.GetValue(0).Equals(this.Value); + return atomicValues2.Length == 1 && atomicValues2.GetValue(0)!.Equals(this.Value); } else { - return arr2.Length == 1 && arr2.GetValue(0).Equals(this.Value); + Debug.Assert(arr2 != null); + return arr2.Length == 1 && arr2.GetValue(0)!.Equals(this.Value); } } else @@ -456,22 +459,21 @@ namespace System.Xml.Schema // BUGBUG: will need to change below parts, using canonical presentation. else { - Array arr = _ks[i].Value as System.Array; - if (arr != null) + if (_ks[i].Value is Array arr) { - XmlAtomicValue[] atomicValues = arr as XmlAtomicValue[]; + XmlAtomicValue[]? atomicValues = arr as XmlAtomicValue[]; if (atomicValues != null) { for (int j = 0; j < atomicValues.Length; j++) { - _hashcode += ((XmlAtomicValue)atomicValues.GetValue(j)).TypedValue.GetHashCode(); + _hashcode += ((XmlAtomicValue)atomicValues.GetValue(j)!).TypedValue.GetHashCode(); } } else { for (int j = 0; j < ((Array)_ks[i].Value).Length; j++) { - _hashcode += ((Array)_ks[i].Value).GetValue(j).GetHashCode(); + _hashcode += ((Array)_ks[i].Value).GetValue(j)!.GetHashCode(); } } } @@ -485,18 +487,26 @@ namespace System.Xml.Schema } // considering about derived type - public override bool Equals(object other) + public override bool Equals(object? other) { // each key sequence member can have different type - KeySequence keySequence = (KeySequence)other; - for (int i = 0; i < _ks.Length; i++) + if (other is KeySequence keySequence) { - if (!_ks[i].Equals(keySequence._ks[i])) + for (int i = 0; i < _ks.Length; i++) { - return false; + if (!_ks[i].Equals(keySequence._ks[i])) + { + return false; + } } + + return true; + } + else + { + Debug.Fail($"{nameof(other)} is not of type {nameof(KeySequence)}"); + return false; } - return true; } public override string ToString() 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 f687264..b64a8f8 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Collections; using System.Collections.Generic; @@ -18,15 +19,16 @@ namespace System.Xml.Schema /// internal class UpaException : Exception { - private readonly object _particle1; - private readonly object _particle2; - public UpaException(object particle1, object particle2) + private readonly object? _particle1; + private readonly object? _particle2; + public UpaException(object? particle1, object? particle2) { _particle1 = particle1; _particle2 = particle2; } - public object Particle1 { get { return _particle1; } } - public object Particle2 { get { return _particle2; } } + + public object? Particle1 { get { return _particle1; } } + public object? Particle2 { get { return _particle2; } } } /// @@ -40,9 +42,9 @@ namespace System.Xml.Schema { private int _last = 0; private readonly Hashtable _names; - private Hashtable _wildcards = null; + private Hashtable? _wildcards = null; private readonly ArrayList _particles; - private object _particleLast = null; + private object? _particleLast = null; private bool _isUpaEnforced = true; public SymbolsDictionary() @@ -69,9 +71,9 @@ namespace System.Xml.Schema /// /// Add name and return it's number /// - public int AddName(XmlQualifiedName name, object particle) + public int AddName(XmlQualifiedName name, object? particle) { - object lookup = _names[name]; + object? lookup = _names[name]; if (lookup != null) { int symbol = (int)lookup; @@ -106,21 +108,23 @@ namespace System.Xml.Schema } break; case NamespaceList.ListType.Set: - foreach (string wildcard in list.Enumerate) + foreach (string? wildcard in list.Enumerate) { + Debug.Assert(wildcard != null); AddWildcard(wildcard, particle); } break; } } - private void AddWildcard(string wildcard, object particle) + private void AddWildcard(string wildcard, object? particle) { if (_wildcards == null) { _wildcards = new Hashtable(); } - object lookup = _wildcards[wildcard]; + + object? lookup = _wildcards[wildcard]; if (lookup == null) { _wildcards.Add(wildcard, _last); @@ -137,27 +141,32 @@ namespace System.Xml.Schema public ICollection GetNamespaceListSymbols(NamespaceList list) { ArrayList match = new ArrayList(); - foreach (XmlQualifiedName name in _names.Keys) + foreach (XmlQualifiedName? name in _names.Keys) { + Debug.Assert(name != null); if (name != XmlQualifiedName.Empty && list.Allows(name)) { match.Add(_names[name]); } } + if (_wildcards != null) { - foreach (string wildcard in _wildcards.Keys) + foreach (string? wildcard in _wildcards.Keys) { + Debug.Assert(wildcard != null); if (list.Allows(wildcard)) { match.Add(_wildcards[wildcard]); } } } + if (list.Type == NamespaceList.ListType.Any || list.Type == NamespaceList.ListType.Other) { match.Add(_last); // add wildcard } + return match; } @@ -168,11 +177,12 @@ namespace System.Xml.Schema { get { - object lookup = _names[name]; + object? lookup = _names[name]; if (lookup != null) { return (int)lookup; } + if (_wildcards != null) { lookup = _wildcards[name.Namespace]; @@ -181,6 +191,7 @@ namespace System.Xml.Schema return (int)lookup; } } + return _last; // true wildcard } } @@ -190,18 +201,19 @@ namespace System.Xml.Schema /// public bool Exists(XmlQualifiedName name) { - object lookup = _names[name]; + object? lookup = _names[name]; if (lookup != null) { return true; } + return false; } /// /// Return content processing mode for the symbol /// - public object GetParticle(int symbol) + public object? GetParticle(int symbol) { return symbol == _last ? _particleLast : _particles[symbol]; } @@ -211,23 +223,29 @@ namespace System.Xml.Schema /// public string NameOf(int symbol) { +#pragma warning disable CS8605 // TODO-NULLABLE https://github.com/dotnet/csharplang/issues/3214 foreach (DictionaryEntry de in _names) +#pragma warning restore CS8605 { - if ((int)de.Value == symbol) + if ((int)de.Value! == symbol) { return ((XmlQualifiedName)de.Key).ToString(); } } + if (_wildcards != null) { +#pragma warning disable CS8605 // TODO-NULLABLE https://github.com/dotnet/csharplang/issues/3214 foreach (DictionaryEntry de in _wildcards) +#pragma warning restore CS8605 { - if ((int)de.Value == symbol) + if ((int)de!.Value! == symbol) { return (string)de.Key + ":*"; } } } + return "##other:*"; } } @@ -235,8 +253,8 @@ namespace System.Xml.Schema internal struct Position { public int symbol; - public object particle; - public Position(int symbol, object particle) + public object? particle; + public Position(int symbol, object? particle) { this.symbol = symbol; this.particle = particle; @@ -247,14 +265,14 @@ namespace System.Xml.Schema { private readonly ArrayList _positions = new ArrayList(); - public int Add(int symbol, object particle) + public int Add(int symbol, object? particle) { return _positions.Add(new Position(symbol, particle)); } public Position this[int pos] { - get { return (Position)_positions[pos]; } + get { return (Position)_positions[pos]!; } } public int Count @@ -370,13 +388,16 @@ namespace System.Xml.Schema public override void ExpandTree(InteriorNode parent, SymbolsDictionary symbols, Positions positions) { - SyntaxTreeNode replacementNode = null; + SyntaxTreeNode? replacementNode = null; +#pragma warning disable CS8605 // TODO-NULLABLE https://github.com/dotnet/csharplang/issues/3214 foreach (int symbol in GetResolvedSymbols(symbols)) +#pragma warning restore CS8605 { if (symbols.GetParticle(symbol) != particle) { symbols.IsUpaEnforced = false; } + LeafNode node = new LeafNode(positions.Add(symbol, particle)); if (replacementNode == null) { @@ -390,6 +411,7 @@ namespace System.Xml.Schema replacementNode = choice; } } + if (parent.LeftChild == this) { parent.LeftChild = replacementNode; @@ -425,16 +447,16 @@ namespace System.Xml.Schema /// internal abstract class InteriorNode : SyntaxTreeNode { - private SyntaxTreeNode _leftChild; - private SyntaxTreeNode _rightChild; + private SyntaxTreeNode? _leftChild; + private SyntaxTreeNode? _rightChild; - public SyntaxTreeNode LeftChild + public SyntaxTreeNode? LeftChild { get { return _leftChild; } set { _leftChild = value; } } - public SyntaxTreeNode RightChild + public SyntaxTreeNode? RightChild { get { return _rightChild; } set { _rightChild = value; } @@ -453,7 +475,8 @@ namespace System.Xml.Schema this_ = (InteriorNode)this_._leftChild; continue; } - this_._leftChild.ExpandTree(this_, symbols, positions); + + this_._leftChild!.ExpandTree(this_, symbols, positions); ProcessRight: if (this_._rightChild != null) @@ -471,7 +494,7 @@ namespace System.Xml.Schema public override void ExpandTree(InteriorNode parent, SymbolsDictionary symbols, Positions positions) { - _leftChild.ExpandTree(this, symbols, positions); + _leftChild!.ExpandTree(this, symbols, positions); if (_rightChild != null) { _rightChild.ExpandTree(this, symbols, positions); @@ -487,8 +510,8 @@ namespace System.Xml.Schema public SequenceNode this_; public BitSet firstpos; public BitSet lastpos; - public BitSet lastposLeft; - public BitSet firstposRight; + public BitSet? lastposLeft; + public BitSet? firstposRight; public SequenceConstructPosContext(SequenceNode node, BitSet firstpos, BitSet lastpos) { @@ -510,27 +533,28 @@ namespace System.Xml.Schema { SequenceNode this_ = context.this_; context.lastposLeft = new BitSet(lastpos.Count); - if (this_.LeftChild is SequenceNode) + if (this_.LeftChild! is SequenceNode) { contextStack.Push(context); context = new SequenceConstructPosContext((SequenceNode)this_.LeftChild, context.firstpos, context.lastposLeft); continue; } - this_.LeftChild.ConstructPos(context.firstpos, context.lastposLeft, followpos); + + this_.LeftChild!.ConstructPos(context.firstpos, context.lastposLeft, followpos); ProcessRight: context.firstposRight = new BitSet(firstpos.Count); - this_.RightChild.ConstructPos(context.firstposRight, context.lastpos, followpos); + this_.RightChild!.ConstructPos(context.firstposRight, context.lastpos, followpos); - if (this_.LeftChild.IsNullable && !this_.RightChild.IsRangeNode) + if (this_.LeftChild!.IsNullable && !this_.RightChild.IsRangeNode) { context.firstpos.Or(context.firstposRight); } if (this_.RightChild.IsNullable) { - context.lastpos.Or(context.lastposLeft); + context.lastpos.Or(context.lastposLeft!); } - for (int pos = context.lastposLeft.NextSet(-1); pos != -1; pos = context.lastposLeft.NextSet(pos)) + for (int pos = context.lastposLeft!.NextSet(-1); pos != -1; pos = context.lastposLeft.NextSet(pos)) { followpos[pos].Or(context.firstposRight); } @@ -552,11 +576,11 @@ namespace System.Xml.Schema { get { - SyntaxTreeNode n; - SequenceNode this_ = this; + SyntaxTreeNode? n; + SequenceNode? this_ = this; do { - if (this_.RightChild.IsRangeNode && ((LeafRangeNode)this_.RightChild).Min == 0) + if (this_.RightChild!.IsRangeNode && ((LeafRangeNode)this_.RightChild).Min == 0) return true; if (!this_.RightChild.IsNullable && !this_.RightChild.IsRangeNode) return false; @@ -564,7 +588,8 @@ namespace System.Xml.Schema this_ = n as SequenceNode; } while (this_ != null); - return n.IsNullable; + + return n!.IsNullable; } } @@ -588,11 +613,11 @@ namespace System.Xml.Schema this_ = (SequenceNode)this_.LeftChild; continue; } - this_.LeftChild.Dump(bb, symbols, positions); + this_.LeftChild!.Dump(bb, symbols, positions); ProcessRight: bb.Append(", "); - this_.RightChild.Dump(bb, symbols, positions); + this_.RightChild!.Dump(bb, symbols, positions); bb.Append(')'); if (nodeStack.Count == 0) break; @@ -620,15 +645,15 @@ namespace System.Xml.Schema BitSet firstPosTemp = new BitSet(firstpos.Count); BitSet lastPosTemp = new BitSet(lastpos.Count); SyntaxTreeNode n; - ChoiceNode this_ = this; + ChoiceNode? this_ = this; do { - ConstructChildPos(this_.RightChild, firstPosTemp, lastPosTemp, followpos); - n = this_.LeftChild; + ConstructChildPos(this_.RightChild!, firstPosTemp, lastPosTemp, followpos); + n = this_.LeftChild!; this_ = n as ChoiceNode; } while (this_ != null); - n.ConstructPos(firstpos, lastpos, followpos); + n!.ConstructPos(firstpos, lastpos, followpos); firstpos.Or(firstPosTemp); lastpos.Or(lastPosTemp); } @@ -638,12 +663,12 @@ namespace System.Xml.Schema get { SyntaxTreeNode n; - ChoiceNode this_ = this; + ChoiceNode? this_ = this; do { - if (this_.RightChild.IsNullable) + if (this_.RightChild!.IsNullable) return true; - n = this_.LeftChild; + n = this_.LeftChild!; this_ = n as ChoiceNode; } while (this_ != null); @@ -671,11 +696,11 @@ namespace System.Xml.Schema this_ = (ChoiceNode)this_.LeftChild; continue; } - this_.LeftChild.Dump(bb, symbols, positions); + this_.LeftChild!.Dump(bb, symbols, positions); ProcessRight: bb.Append(" | "); - this_.RightChild.Dump(bb, symbols, positions); + this_.RightChild!.Dump(bb, symbols, positions); bb.Append(')'); if (nodeStack.Count == 0) break; @@ -691,7 +716,7 @@ namespace System.Xml.Schema { public override void ConstructPos(BitSet firstpos, BitSet lastpos, BitSet[] followpos) { - LeftChild.ConstructPos(firstpos, lastpos, followpos); + LeftChild!.ConstructPos(firstpos, lastpos, followpos); for (int pos = lastpos.NextSet(-1); pos != -1; pos = lastpos.NextSet(pos)) { followpos[pos].Or(firstpos); @@ -700,13 +725,13 @@ namespace System.Xml.Schema public override bool IsNullable { - get { return LeftChild.IsNullable; } + get { return LeftChild!.IsNullable; } } #if DEBUG public override void Dump(StringBuilder bb, SymbolsDictionary symbols, Positions positions) { - LeftChild.Dump(bb, symbols, positions); + LeftChild!.Dump(bb, symbols, positions); bb.Append('+'); } #endif @@ -716,7 +741,7 @@ namespace System.Xml.Schema { public override void ConstructPos(BitSet firstpos, BitSet lastpos, BitSet[] followpos) { - LeftChild.ConstructPos(firstpos, lastpos, followpos); + LeftChild!.ConstructPos(firstpos, lastpos, followpos); } public override bool IsNullable @@ -727,7 +752,7 @@ namespace System.Xml.Schema #if DEBUG public override void Dump(StringBuilder bb, SymbolsDictionary symbols, Positions positions) { - LeftChild.Dump(bb, symbols, positions); + LeftChild!.Dump(bb, symbols, positions); bb.Append('?'); } #endif @@ -737,7 +762,7 @@ namespace System.Xml.Schema { public override void ConstructPos(BitSet firstpos, BitSet lastpos, BitSet[] followpos) { - LeftChild.ConstructPos(firstpos, lastpos, followpos); + LeftChild!.ConstructPos(firstpos, lastpos, followpos); for (int pos = lastpos.NextSet(-1); pos != -1; pos = lastpos.NextSet(pos)) { followpos[pos].Or(firstpos); @@ -752,7 +777,7 @@ namespace System.Xml.Schema #if DEBUG public override void Dump(StringBuilder bb, SymbolsDictionary symbols, Positions positions) { - LeftChild.Dump(bb, symbols, positions); + LeftChild!.Dump(bb, symbols, positions); bb.Append('*'); } #endif @@ -875,7 +900,7 @@ namespace System.Xml.Schema { private decimal _min; private readonly decimal _max; - private BitSet _nextIteration; + private BitSet? _nextIteration; public LeafRangeNode(decimal min, decimal max) : this(-1, min, max) { } @@ -895,7 +920,7 @@ namespace System.Xml.Schema get { return _min; } } - public BitSet NextIteration + public BitSet? NextIteration { get { @@ -920,7 +945,7 @@ namespace System.Xml.Schema Debug.Assert(parent is SequenceNode); Debug.Assert(this == parent.RightChild); //change the range node min to zero if left is nullable - if (parent.LeftChild.IsNullable) + if (parent.LeftChild!.IsNullable) { _min = 0; } @@ -989,7 +1014,7 @@ namespace System.Xml.Schema // do nothin' } - public virtual object ValidateElement(XmlQualifiedName name, ValidationState context, out int errorCode) + public virtual object? ValidateElement(XmlQualifiedName name, ValidationState context, out int errorCode) { if (_contentType == XmlSchemaContentType.TextOnly || _contentType == XmlSchemaContentType.Empty) { //Cannot have elements in TextOnly or Empty content @@ -1004,12 +1029,12 @@ namespace System.Xml.Schema return true; } - public virtual ArrayList ExpectedElements(ValidationState context, bool isRequiredOnly) + public virtual ArrayList? ExpectedElements(ValidationState context, bool isRequiredOnly) { return null; } - public virtual ArrayList ExpectedParticles(ValidationState context, bool isRequiredOnly, XmlSchemaSet schemaSet) + public virtual ArrayList? ExpectedParticles(ValidationState context, bool isRequiredOnly, XmlSchemaSet schemaSet) { return null; } @@ -1026,7 +1051,7 @@ namespace System.Xml.Schema particles.Add(p); } //Only then it can be head of substitutionGrp, if it is, add its members - XmlSchemaElement elem = p as XmlSchemaElement; + XmlSchemaElement? elem = p as XmlSchemaElement; if (elem != null && (global || !elem.RefName.IsEmpty)) { XmlSchemaObjectTable substitutionGroups = schemaSet.SubstitutionGroups; @@ -1036,7 +1061,7 @@ namespace System.Xml.Schema //Grp members wil contain the head as well, so filter head as we added it already for (int i = 0; i < grp.Members.Count; ++i) { - XmlSchemaElement member = (XmlSchemaElement)grp.Members[i]; + XmlSchemaElement member = (XmlSchemaElement)grp.Members[i]!; if (!elem.QualifiedName.Equals(member.QualifiedName) && !particles.Contains(member)) { //A member might have been directly present as an element in the content model particles.Add(member); @@ -1049,10 +1074,10 @@ namespace System.Xml.Schema internal sealed class ParticleContentValidator : ContentValidator { - private SymbolsDictionary _symbols; - private Positions _positions; - private Stack _stack; // parsing context - private SyntaxTreeNode _contentNode; // content model points to syntax tree + private SymbolsDictionary? _symbols; + private Positions? _positions; + private Stack? _stack; // parsing context + private SyntaxTreeNode? _contentNode; // content model points to syntax tree private bool _isPartial; // whether the closure applies to partial or the whole node that is on top of the stack private int _minMaxNodesCount; private readonly bool _enableUpaCheck; @@ -1088,21 +1113,22 @@ namespace System.Xml.Schema { _symbols = new SymbolsDictionary(); _positions = new Positions(); - _stack = new Stack(); + _stack = new Stack(); } public void OpenGroup() { - _stack.Push(null); + _stack!.Push(null); } public void CloseGroup() { - SyntaxTreeNode node = _stack.Pop(); + SyntaxTreeNode? node = _stack!.Pop(); if (node == null) { return; } + if (_stack.Count == 0) { _contentNode = node; @@ -1111,7 +1137,7 @@ namespace System.Xml.Schema else { // some collapsing to do... - InteriorNode inNode = (InteriorNode)_stack.Pop(); + InteriorNode? inNode = (InteriorNode?)_stack.Pop(); if (inNode != null) { inNode.RightChild = node; @@ -1128,29 +1154,29 @@ namespace System.Xml.Schema public bool Exists(XmlQualifiedName name) { - if (_symbols.Exists(name)) + if (_symbols!.Exists(name)) { return true; } return false; } - public void AddName(XmlQualifiedName name, object particle) + public void AddName(XmlQualifiedName name, object? particle) { - AddLeafNode(new LeafNode(_positions.Add(_symbols.AddName(name, particle), particle))); + AddLeafNode(new LeafNode(_positions!.Add(_symbols!.AddName(name, particle), particle))); } public void AddNamespaceList(NamespaceList namespaceList, object particle) { - _symbols.AddNamespaceList(namespaceList, particle, false); + _symbols!.AddNamespaceList(namespaceList, particle, false); AddLeafNode(new NamespaceListNode(namespaceList, particle)); } private void AddLeafNode(SyntaxTreeNode node) { - if (_stack.Count > 0) + if (_stack!.Count > 0) { - InteriorNode inNode = (InteriorNode)_stack.Pop(); + InteriorNode? inNode = (InteriorNode?)_stack.Pop(); if (inNode != null) { inNode.RightChild = node; @@ -1163,7 +1189,7 @@ namespace System.Xml.Schema public void AddChoice() { - SyntaxTreeNode node = _stack.Pop(); + SyntaxTreeNode? node = _stack!.Pop(); InteriorNode choice = new ChoiceNode(); choice.LeftChild = node; _stack.Push(choice); @@ -1171,7 +1197,7 @@ namespace System.Xml.Schema public void AddSequence() { - SyntaxTreeNode node = _stack.Pop(); + SyntaxTreeNode? node = _stack!.Pop(); InteriorNode sequence = new SequenceNode(); sequence.LeftChild = node; _stack.Push(sequence); @@ -1195,7 +1221,7 @@ namespace System.Xml.Schema public void AddLeafRange(decimal min, decimal max) { LeafRangeNode rNode = new LeafRangeNode(min, max); - int pos = _positions.Add(-2, rNode); + int pos = _positions!.Add(-2, rNode); rNode.Pos = pos; InteriorNode sequence = new SequenceNode(); @@ -1211,10 +1237,10 @@ namespace System.Xml.Schema #endif private void Closure(InteriorNode node) { - if (_stack.Count > 0) + if (_stack!.Count > 0) { - SyntaxTreeNode topNode = _stack.Pop(); - InteriorNode inNode = topNode as InteriorNode; + SyntaxTreeNode? topNode = _stack!.Pop(); + InteriorNode? inNode = topNode as InteriorNode; if (_isPartial && inNode != null) { // need to reach in and wrap right hand side of element. @@ -1258,7 +1284,7 @@ namespace System.Xml.Schema // Add end marker InteriorNode contentRoot = new SequenceNode(); contentRoot.LeftChild = _contentNode; - LeafNode endMarker = new LeafNode(_positions.Add(_symbols.AddName(XmlQualifiedName.Empty, null), null)); + LeafNode endMarker = new LeafNode(_positions!.Add(_symbols!.AddName(XmlQualifiedName.Empty, null), null)); contentRoot.RightChild = endMarker; // Eliminate NamespaceListNode(s) and RangeNode(s) @@ -1293,7 +1319,7 @@ namespace System.Xml.Schema } else { - int[][] transitionTable = null; + int[][]? transitionTable = null; // if each symbol has unique particle we are golden if (!_symbols.IsUpaEnforced) { @@ -1322,7 +1348,7 @@ namespace System.Xml.Schema private BitSet[] CalculateTotalFollowposForRangeNodes(BitSet firstpos, BitSet[] followpos, out BitSet posWithRangeTerminals) { - int positionsCount = _positions.Count; //terminals + int positionsCount = _positions!.Count; //terminals posWithRangeTerminals = new BitSet(positionsCount); //Compute followpos for each range node @@ -1335,14 +1361,14 @@ namespace System.Xml.Schema Position p = _positions[i]; if (p.symbol == -2) { //P is a LeafRangeNode - LeafRangeNode lrNode = p.particle as LeafRangeNode; + LeafRangeNode? lrNode = p.particle as LeafRangeNode; Debug.Assert(lrNode != null); BitSet tempFollowPos = new BitSet(positionsCount); tempFollowPos.Clear(); tempFollowPos.Or(followpos[i]); //Add the followpos of the range node if (lrNode.Min != lrNode.Max) { //If they are the same, then followpos cannot include the firstpos - tempFollowPos.Or(lrNode.NextIteration); //Add the nextIteration of the range node (this is the firstpos of its parent's leftChild) + tempFollowPos.Or(lrNode.NextIteration!); //Add the nextIteration of the range node (this is the firstpos of its parent's leftChild) } //For each position in the bitset, if it is a outer range node (pos > i), then add its followpos as well to the current node's followpos @@ -1353,7 +1379,7 @@ namespace System.Xml.Schema Position p1 = _positions[pos]; if (p1.symbol == -2) { - LeafRangeNode lrNode1 = p1.particle as LeafRangeNode; + LeafRangeNode? lrNode1 = p1.particle as LeafRangeNode; Debug.Assert(lrNode1 != null); tempFollowPos.Or(minmaxFollowPos[lrNode1.Pos]); } @@ -1370,10 +1396,10 @@ namespace System.Xml.Schema private void CheckCMUPAWithLeafRangeNodes(BitSet curpos) { - object[] symbolMatches = new object[_symbols.Count]; + object?[] symbolMatches = new object[_symbols!.Count]; for (int pos = curpos.NextSet(-1); pos != -1; pos = curpos.NextSet(pos)) { - Position currentPosition = _positions[pos]; + Position currentPosition = _positions![pos]; int symbol = currentPosition.symbol; if (symbol >= 0) { //its not a range position @@ -1395,13 +1421,14 @@ namespace System.Xml.Schema { if (curpos.Intersects(posWithRangeTerminals)) { - BitSet newSet = new BitSet(_positions.Count); //Doing work again + BitSet newSet = new BitSet(_positions!.Count); //Doing work again newSet.Or(curpos); newSet.And(posWithRangeTerminals); curpos = curpos.Clone(); for (int pos = newSet.NextSet(-1); pos != -1; pos = newSet.NextSet(pos)) { - LeafRangeNode lrNode = _positions[pos].particle as LeafRangeNode; + LeafRangeNode? lrNode = _positions[pos].particle as LeafRangeNode; + Debug.Assert(lrNode != null); curpos.Or(minmaxFollowPos[lrNode.Pos]); } } @@ -1411,7 +1438,7 @@ namespace System.Xml.Schema private void CheckUniqueParticleAttribution(BitSet firstpos, BitSet[] followpos) { CheckUniqueParticleAttribution(firstpos); - for (int i = 0; i < _positions.Count; i++) + for (int i = 0; i < _positions!.Count; i++) { CheckUniqueParticleAttribution(followpos[i]); } @@ -1420,11 +1447,11 @@ namespace System.Xml.Schema private void CheckUniqueParticleAttribution(BitSet curpos) { // particles will be attributed uniquely if the same symbol never poins to two different ones - object[] particles = new object[_symbols.Count]; + object?[] particles = new object[_symbols!.Count]; for (int pos = curpos.NextSet(-1); pos != -1; pos = curpos.NextSet(pos)) { // if position can follow - int symbol = _positions[pos].symbol; + int symbol = _positions![pos].symbol; if (particles[symbol] == null) { // set particle for the symbol @@ -1441,12 +1468,12 @@ namespace System.Xml.Schema /// /// Algorithm 3.5 Construction of a DFA from a regular expression /// - private int[][] BuildTransitionTable(BitSet firstpos, BitSet[] followpos, int endMarkerPos) + private int[][]? BuildTransitionTable(BitSet firstpos, BitSet[] followpos, int endMarkerPos) { const int TimeConstant = 8192; //(MaxStates * MaxPositions should be a constant) - int positionsCount = _positions.Count; + int positionsCount = _positions!.Count; int MaxStatesCount = TimeConstant / positionsCount; - int symbolsCount = _symbols.Count; + int symbolsCount = _symbols!.Count; // transition table (Dtran in the book) ArrayList transitionTable = new ArrayList(); @@ -1470,8 +1497,8 @@ namespace System.Xml.Schema while (unmarked.Count > 0) { BitSet statePosSet = unmarked.Dequeue(); // all positions that constitute DFA state - Debug.Assert(state == (int)stateTable[statePosSet]); // just make sure that statePosSet is for correct state - int[] transition = (int[])transitionTable[state]; + Debug.Assert(state == (int)stateTable[statePosSet]!); // just make sure that statePosSet is for correct state + int[] transition = (int[])transitionTable[state]!; if (statePosSet[endMarkerPos]) { transition[symbolsCount] = 1; // accepting @@ -1494,7 +1521,7 @@ namespace System.Xml.Schema // if U is not empty and is not in Dstates then // add U as an unmarked state to Dstates - object lookup = stateTable[newset]; + object? lookup = stateTable[newset]; if (lookup != null) { transition[symbol] = (int)lookup; @@ -1507,6 +1534,7 @@ namespace System.Xml.Schema { return null; } + unmarked.Enqueue(newset); stateTable.Add(newset, newState); transitionTable.Add(new int[symbolsCount + 1]); @@ -1524,10 +1552,11 @@ namespace System.Xml.Schema { // Temporary printout bb.AppendLine("Positions"); - for (int i = 0; i < _positions.Count; i++) + for (int i = 0; i < _positions!.Count; i++) { - bb.AppendLine(i + " " + _positions[i].symbol.ToString(NumberFormatInfo.InvariantInfo) + " " + _symbols.NameOf(_positions[i].symbol)); + bb.AppendLine(i + " " + _positions[i].symbol.ToString(NumberFormatInfo.InvariantInfo) + " " + _symbols!.NameOf(_positions[i].symbol)); } + bb.AppendLine("Followpos"); for (int i = 0; i < _positions.Count; i++) { @@ -1537,13 +1566,14 @@ namespace System.Xml.Schema } bb.AppendLine(); } + if (transitionTable != null) { // Temporary printout bb.AppendLine("Transitions"); for (int i = 0; i < transitionTable.Length; i++) { - for (int j = 0; j < _symbols.Count; j++) + for (int j = 0; j < _symbols!.Count; j++) { if (transitionTable[i][j] == -1) { @@ -1554,6 +1584,7 @@ namespace System.Xml.Schema bb.AppendFormat(" {0:000} ", transitionTable[i][j]); } } + bb.AppendLine(transitionTable[i][_symbols.Count] == 1 ? "+" : ""); } } @@ -1591,7 +1622,7 @@ namespace System.Xml.Schema /// /// Algorithm 3.1 Simulating a DFA /// - public override object ValidateElement(XmlQualifiedName name, ValidationState context, out int errorCode) + public override object? ValidateElement(XmlQualifiedName name, ValidationState context, out int errorCode) { int symbol = _symbols[name]; int state = _transitionTable[context.CurrentState.State][symbol]; @@ -1621,9 +1652,9 @@ namespace System.Xml.Schema return true; } - public override ArrayList ExpectedElements(ValidationState context, bool isRequiredOnly) + public override ArrayList? ExpectedElements(ValidationState context, bool isRequiredOnly) { - ArrayList names = null; + ArrayList? names = null; int[] transition = _transitionTable[context.CurrentState.State]; if (transition != null) { @@ -1635,7 +1666,8 @@ namespace System.Xml.Schema { names = new ArrayList(); } - XmlSchemaParticle p = (XmlSchemaParticle)_symbols.GetParticle(i); + + XmlSchemaParticle? p = (XmlSchemaParticle?)_symbols.GetParticle(i); if (p == null) { string s = _symbols.NameOf(i); @@ -1655,6 +1687,7 @@ namespace System.Xml.Schema } } } + return names; } @@ -1668,7 +1701,7 @@ namespace System.Xml.Schema { if (transition[i] != -1) { - XmlSchemaParticle p = (XmlSchemaParticle)_symbols.GetParticle(i); + XmlSchemaParticle? p = (XmlSchemaParticle?)_symbols.GetParticle(i); if (p == null) { continue; @@ -1715,14 +1748,14 @@ namespace System.Xml.Schema /// /// Algorithm 3.4 Simulation of an NFA /// - public override object ValidateElement(XmlQualifiedName name, ValidationState context, out int errorCode) + public override object? ValidateElement(XmlQualifiedName name, ValidationState context, out int errorCode) { BitSet curpos = context.CurPos[context.CurrentState.CurPosIndex]; int next = (context.CurrentState.CurPosIndex + 1) % 2; BitSet nextpos = context.CurPos[next]; nextpos.Clear(); int symbol = _symbols[name]; - object particle = null; + object? particle = null; errorCode = 0; for (int pos = curpos.NextSet(-1); pos != -1; pos = curpos.NextSet(pos)) { @@ -1776,9 +1809,9 @@ namespace System.Xml.Schema return true; } - public override ArrayList ExpectedElements(ValidationState context, bool isRequiredOnly) + public override ArrayList? ExpectedElements(ValidationState context, bool isRequiredOnly) { - ArrayList names = null; + ArrayList? names = null; BitSet curpos = context.CurPos[context.CurrentState.CurPosIndex]; for (int pos = curpos.NextSet(-1); pos != -1; pos = curpos.NextSet(pos)) { @@ -1786,7 +1819,7 @@ namespace System.Xml.Schema { names = new ArrayList(); } - XmlSchemaParticle p = (XmlSchemaParticle)_positions[pos].particle; + XmlSchemaParticle? p = (XmlSchemaParticle?)_positions[pos].particle; if (p == null) { string s = _symbols.NameOf(_positions[pos].symbol); @@ -1813,7 +1846,7 @@ namespace System.Xml.Schema BitSet curpos = context.CurPos[context.CurrentState.CurPosIndex]; for (int pos = curpos.NextSet(-1); pos != -1; pos = curpos.NextSet(pos)) { - XmlSchemaParticle p = (XmlSchemaParticle)_positions[pos].particle; + XmlSchemaParticle? p = (XmlSchemaParticle?)_positions[pos].particle; if (p == null) { continue; @@ -1858,7 +1891,7 @@ namespace System.Xml.Schema public override void InitValidation(ValidationState context) { int positionsCount = _positions.Count; - List runningPositions = context.RunningPositions; + List? runningPositions = context.RunningPositions; if (runningPositions != null) { Debug.Assert(_minMaxNodesCount != 0); @@ -1878,12 +1911,12 @@ namespace System.Xml.Schema context.HasMatched = rposInfo.curpos.Get(_endMarkerPos); } - public override object ValidateElement(XmlQualifiedName name, ValidationState context, out int errorCode) + public override object? ValidateElement(XmlQualifiedName name, ValidationState context, out int errorCode) { errorCode = 0; int symbol = _symbols[name]; bool hasSeenFinalPosition = false; - List runningPositions = context.RunningPositions; + List? runningPositions = context.RunningPositions; int matchCount = context.CurrentState.NumberOfRunningPos; int k = 0; RangePositionInfo rposInfo; @@ -1894,7 +1927,7 @@ namespace System.Xml.Schema while (k < matchCount) { //we are looking for the first match in the list of bitsets - rposInfo = runningPositions[k]; + rposInfo = runningPositions![k]; BitSet curpos = rposInfo.curpos; for (int matchpos = curpos.NextSet(-1); matchpos != -1; matchpos = curpos.NextSet(matchpos)) { //In all sets, have to scan all positions because of Disabled UPA possibility @@ -1927,13 +1960,13 @@ namespace System.Xml.Schema { //There is a match if (k != 0) { //If the first bitset itself matched, then no need to remove anything - runningPositions.RemoveRange(0, k); //Delete entries from 0 to k-1 + runningPositions!.RemoveRange(0, k); //Delete entries from 0 to k-1 } matchCount = matchCount - k; k = 0; // Since we re-sized the array while (k < matchCount) { - rposInfo = runningPositions[k]; + rposInfo = runningPositions![k]; matched = rposInfo.curpos.Get(pos); //Look for the bitset that matches the same position as pos if (matched) { //If match found, get the follow positions of the current matched position @@ -1970,7 +2003,7 @@ namespace System.Xml.Schema for (k = matchCount - 1; k >= 0; k--) { int j = k; - BitSet currentRunningPosition = runningPositions[k].curpos; + BitSet currentRunningPosition = runningPositions![k].curpos; hasSeenFinalPosition = hasSeenFinalPosition || currentRunningPosition.Get(_endMarkerPos); //Accepting position reached if the current position BitSet contains the endPosition while (matchCount < 10000 && currentRunningPosition.Intersects(_positionsWithRangeTerminals)) { @@ -1981,7 +2014,7 @@ namespace System.Xml.Schema BitSet countingPosition = currentRunningPosition.Clone(); countingPosition.And(_positionsWithRangeTerminals); int cPos = countingPosition.NextSet(-1); //Get the first position where leaf range node appears - LeafRangeNode lrNode = _positions[cPos].particle as LeafRangeNode; //For a position with leaf range node, the particle is the node itself + LeafRangeNode? lrNode = _positions[cPos].particle as LeafRangeNode; //For a position with leaf range node, the particle is the node itself Debug.Assert(lrNode != null); rposInfo = runningPositions[j]; @@ -1990,11 +2023,13 @@ namespace System.Xml.Schema runningPositions.Add(default(RangePositionInfo)); runningPositions.Add(default(RangePositionInfo)); } + RangePositionInfo newRPosInfo = runningPositions[matchCount]; if (newRPosInfo.rangeCounters == null) { newRPosInfo.rangeCounters = new decimal[_minMaxNodesCount]; } + Array.Copy(rposInfo.rangeCounters, newRPosInfo.rangeCounters, rposInfo.rangeCounters.Length); decimal count = ++newRPosInfo.rangeCounters[lrNode.Pos]; @@ -2007,14 +2042,14 @@ namespace System.Xml.Schema } else if (count < lrNode.Min) { - newRPosInfo.curpos = lrNode.NextIteration; + newRPosInfo.curpos = lrNode.NextIteration!; runningPositions[matchCount] = newRPosInfo; matchCount++; break; } else { // min <= count < max - newRPosInfo.curpos = lrNode.NextIteration; //set currentpos to firstpos of node which has the range + newRPosInfo.curpos = lrNode.NextIteration!; //set currentpos to firstpos of node which has the range runningPositions[matchCount] = newRPosInfo; j = matchCount + 1; newRPosInfo = runningPositions[j]; @@ -2028,14 +2063,17 @@ namespace System.Xml.Schema runningPositions[j] = newRPosInfo; matchCount += 2; } + currentRunningPosition = runningPositions[j].curpos; hasSeenFinalPosition = hasSeenFinalPosition || currentRunningPosition.Get(_endMarkerPos); } } + context.HasMatched = hasSeenFinalPosition; context.CurrentState.NumberOfRunningPos = matchCount; return _positions[pos].particle; } //matchcount > 0 + errorCode = -1; context.NeedValidateChildren = false; return null; @@ -2046,9 +2084,9 @@ namespace System.Xml.Schema return context.HasMatched; } - public override ArrayList ExpectedElements(ValidationState context, bool isRequiredOnly) + public override ArrayList? ExpectedElements(ValidationState context, bool isRequiredOnly) { - ArrayList names = null; + ArrayList? names = null; BitSet expectedPos; if (context.RunningPositions != null) { @@ -2068,7 +2106,7 @@ namespace System.Xml.Schema int symbol = _positions[pos].symbol; if (symbol >= 0) { //non range nodes - XmlSchemaParticle p = _positions[pos].particle as XmlSchemaParticle; + XmlSchemaParticle? p = _positions[pos].particle as XmlSchemaParticle; if (p == null) { string s = _symbols.NameOf(_positions[pos].symbol); @@ -2088,6 +2126,7 @@ namespace System.Xml.Schema } } } + return names; } @@ -2109,11 +2148,12 @@ namespace System.Xml.Schema int symbol = _positions[pos].symbol; if (symbol >= 0) { //non range nodes - XmlSchemaParticle p = _positions[pos].particle as XmlSchemaParticle; + XmlSchemaParticle? p = _positions[pos].particle as XmlSchemaParticle; if (p == null) { continue; } + AddParticleToExpected(p, schemaSet, particles); } } @@ -2165,30 +2205,34 @@ namespace System.Xml.Schema context.CurrentState.AllElementsRequired = -1; // no elements at all } - public override object ValidateElement(XmlQualifiedName name, ValidationState context, out int errorCode) + public override object? ValidateElement(XmlQualifiedName name, ValidationState context, out int errorCode) { - object lookup = _elements[name]; + object? lookup = _elements[name]; errorCode = 0; if (lookup == null) { context.NeedValidateChildren = false; return null; } + int index = (int)lookup; - if (context.AllElementsSet[index]) + if (context.AllElementsSet![index]) { errorCode = -2; return null; } + if (context.CurrentState.AllElementsRequired == -1) { context.CurrentState.AllElementsRequired = 0; } + context.AllElementsSet.Set(index); if (_isRequired[index]) { context.CurrentState.AllElementsRequired++; } + return _particles[index]; } @@ -2198,36 +2242,44 @@ namespace System.Xml.Schema { return true; } + return false; } - public override ArrayList ExpectedElements(ValidationState context, bool isRequiredOnly) + public override ArrayList? ExpectedElements(ValidationState context, bool isRequiredOnly) { - ArrayList names = null; + ArrayList? names = null; +#pragma warning disable CS8605 // TODO-NULLABLE https://github.com/dotnet/csharplang/issues/3214 foreach (DictionaryEntry entry in _elements) +#pragma warning restore CS8605 { - if (!context.AllElementsSet[(int)entry.Value] && (!isRequiredOnly || _isRequired[(int)entry.Value])) + if (!context.AllElementsSet![(int)entry.Value!] && (!isRequiredOnly || _isRequired[(int)entry.Value])) { if (names == null) { names = new ArrayList(); } + names.Add(entry.Key); } } + return names; } public override ArrayList ExpectedParticles(ValidationState context, bool isRequiredOnly, XmlSchemaSet schemaSet) { ArrayList expectedParticles = new ArrayList(); +#pragma warning disable CS8605 // TODO-NULLABLE https://github.com/dotnet/csharplang/issues/3214 foreach (DictionaryEntry entry in _elements) +#pragma warning restore CS8605 { - if (!context.AllElementsSet[(int)entry.Value] && (!isRequiredOnly || _isRequired[(int)entry.Value])) + if (!context.AllElementsSet![(int)entry.Value!] && (!isRequiredOnly || _isRequired[(int)entry.Value])) { - AddParticleToExpected(_particles[(int)entry.Value] as XmlSchemaParticle, schemaSet, expectedParticles); + AddParticleToExpected((_particles[(int)entry.Value] as XmlSchemaParticle)!, schemaSet, expectedParticles); } } + return expectedParticles; } } 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 56e4646..ccd9415 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Xml.Schema { using System; @@ -81,13 +82,13 @@ namespace System.Xml.Schema internal int Length; internal int MinLength; internal int MaxLength; - internal ArrayList Patterns; - internal ArrayList Enumeration; + internal ArrayList? Patterns; + internal ArrayList? Enumeration; internal XmlSchemaWhiteSpace WhiteSpace; - internal object MaxInclusive; - internal object MaxExclusive; - internal object MinInclusive; - internal object MinExclusive; + internal object? MaxInclusive; + internal object? MaxExclusive; + internal object? MinInclusive; + internal object? MinExclusive; internal int TotalDigits; internal int FractionDigits; internal RestrictionFlags Flags = 0; @@ -97,20 +98,20 @@ namespace System.Xml.Schema internal abstract class DatatypeImplementation : XmlSchemaDatatype { private XmlSchemaDatatypeVariety _variety = XmlSchemaDatatypeVariety.Atomic; - private RestrictionFacets _restriction = null; - private DatatypeImplementation _baseType = null; - private XmlValueConverter _valueConverter; - private XmlSchemaType _parentSchemaType; + private RestrictionFacets? _restriction = null; + private DatatypeImplementation? _baseType = null; + private XmlValueConverter? _valueConverter; + private XmlSchemaType? _parentSchemaType; private static readonly Hashtable s_builtinTypes = new Hashtable(); private static readonly XmlSchemaSimpleType[] s_enumToTypeCode = new XmlSchemaSimpleType[(int)XmlTypeCode.DayTimeDuration + 1]; - private static XmlSchemaSimpleType s__anySimpleType; - private static XmlSchemaSimpleType s__anyAtomicType; - private static XmlSchemaSimpleType s__untypedAtomicType; - private static XmlSchemaSimpleType s_yearMonthDurationType; - private static XmlSchemaSimpleType s_dayTimeDurationType; - private static volatile XmlSchemaSimpleType s_normalizedStringTypeV1Compat; - private static volatile XmlSchemaSimpleType s_tokenTypeV1Compat; + private static XmlSchemaSimpleType s__anySimpleType = null!; + private static XmlSchemaSimpleType s__anyAtomicType = null!; + private static XmlSchemaSimpleType s__untypedAtomicType = null!; + private static XmlSchemaSimpleType s_yearMonthDurationType = null!; + private static XmlSchemaSimpleType s_dayTimeDurationType = null!; + private static volatile XmlSchemaSimpleType? s_normalizedStringTypeV1Compat; + private static volatile XmlSchemaSimpleType? s_tokenTypeV1Compat; private const int anySimpleTypeIndex = 11; @@ -139,23 +140,23 @@ namespace System.Xml.Schema internal static XmlSchemaSimpleType AnyAtomicType { get { return s__anyAtomicType; } } internal static XmlSchemaSimpleType UntypedAtomicType { get { return s__untypedAtomicType; } } - internal static new DatatypeImplementation FromXmlTokenizedType(XmlTokenizedType token) + internal static new DatatypeImplementation? FromXmlTokenizedType(XmlTokenizedType token) { return s_tokenizedTypes[(int)token]; } - internal static new DatatypeImplementation FromXmlTokenizedTypeXsd(XmlTokenizedType token) + internal static new DatatypeImplementation? FromXmlTokenizedTypeXsd(XmlTokenizedType token) { return s_tokenizedTypesXsd[(int)token]; } - internal static new DatatypeImplementation FromXdrName(string name) + internal static new DatatypeImplementation? FromXdrName(string name) { int i = Array.BinarySearch(s_xdrTypes, name, null); return i < 0 ? null : (DatatypeImplementation)s_xdrTypes[i]; } - private static DatatypeImplementation FromTypeName(string name) + private static DatatypeImplementation? FromTypeName(string name) { int i = Array.BinarySearch(s_xsdTypes, name, null); return i < 0 ? null : (DatatypeImplementation)s_xsdTypes[i]; @@ -190,7 +191,7 @@ namespace System.Xml.Schema // Create link from the derived type to the base type derivedType.SetBaseSchemaType(baseType); derivedType.SetDerivedBy(XmlSchemaDerivationMethod.Restriction); - if (derivedType.Datatype.Variety == XmlSchemaDatatypeVariety.Atomic) + if (derivedType.Datatype!.Variety == XmlSchemaDatatypeVariety.Atomic) { //Content is restriction XmlSchemaSimpleTypeRestriction restContent = new XmlSchemaSimpleTypeRestriction(); restContent.BaseTypeName = baseType.QualifiedName; @@ -227,7 +228,7 @@ namespace System.Xml.Schema //Build anySimpleType SchemaDatatypeMap sdm = s_xsdTypes[anySimpleTypeIndex]; //anySimpleType qname = new XmlQualifiedName(sdm.Name, XmlReservedNs.NsXs); - DatatypeImplementation dt = FromTypeName(qname.Name); + DatatypeImplementation dt = FromTypeName(qname.Name)!; s__anySimpleType = StartBuiltinType(qname, dt); dt._parentSchemaType = s__anySimpleType; s_builtinTypes.Add(qname, s__anySimpleType); @@ -243,7 +244,7 @@ namespace System.Xml.Schema sdm = s_xsdTypes[i]; qname = new XmlQualifiedName(sdm.Name, XmlReservedNs.NsXs); - dt = FromTypeName(qname.Name); + dt = FromTypeName(qname.Name)!; simpleType = StartBuiltinType(qname, dt); dt._parentSchemaType = simpleType; @@ -261,8 +262,9 @@ namespace System.Xml.Schema { //anySimpleType continue; } + sdm = s_xsdTypes[i]; - XmlSchemaSimpleType derivedType = (XmlSchemaSimpleType)s_builtinTypes[new XmlQualifiedName(sdm.Name, XmlReservedNs.NsXs)]; + XmlSchemaSimpleType derivedType = (XmlSchemaSimpleType)s_builtinTypes[new XmlQualifiedName(sdm.Name, XmlReservedNs.NsXs)]!; XmlSchemaSimpleType baseType; if (sdm.ParentIndex == anySimpleTypeIndex) @@ -271,7 +273,7 @@ namespace System.Xml.Schema } else { //derived types whose index > 0 - baseType = (XmlSchemaSimpleType)s_builtinTypes[new XmlQualifiedName(((SchemaDatatypeMap)(s_xsdTypes[sdm.ParentIndex])).Name, XmlReservedNs.NsXs)]; + baseType = (XmlSchemaSimpleType)s_builtinTypes[new XmlQualifiedName(((SchemaDatatypeMap)(s_xsdTypes[sdm.ParentIndex])).Name, XmlReservedNs.NsXs)]!; FinishBuiltinType(derivedType, baseType); } } @@ -316,7 +318,7 @@ namespace System.Xml.Schema internal static XmlSchemaSimpleType GetSimpleTypeFromXsdType(XmlQualifiedName qname) { - return (XmlSchemaSimpleType)s_builtinTypes[qname]; + return (XmlSchemaSimpleType)s_builtinTypes[qname]!; } internal static XmlSchemaSimpleType GetNormalizedStringTypeV1Compat() @@ -324,12 +326,13 @@ namespace System.Xml.Schema if (s_normalizedStringTypeV1Compat == null) { XmlSchemaSimpleType correctType = GetSimpleTypeFromTypeCode(XmlTypeCode.NormalizedString); - XmlSchemaSimpleType tempNormalizedStringTypeV1Compat = correctType.Clone() as XmlSchemaSimpleType; + XmlSchemaSimpleType tempNormalizedStringTypeV1Compat = (correctType.Clone() as XmlSchemaSimpleType)!; tempNormalizedStringTypeV1Compat.SetDatatype(c_normalizedStringV1Compat); tempNormalizedStringTypeV1Compat.ElementDecl = new SchemaElementDecl(c_normalizedStringV1Compat); tempNormalizedStringTypeV1Compat.ElementDecl.SchemaType = tempNormalizedStringTypeV1Compat; s_normalizedStringTypeV1Compat = tempNormalizedStringTypeV1Compat; } + return s_normalizedStringTypeV1Compat; } @@ -338,7 +341,7 @@ namespace System.Xml.Schema if (s_tokenTypeV1Compat == null) { XmlSchemaSimpleType correctType = GetSimpleTypeFromTypeCode(XmlTypeCode.Token); - XmlSchemaSimpleType tempTokenTypeV1Compat = correctType.Clone() as XmlSchemaSimpleType; + XmlSchemaSimpleType tempTokenTypeV1Compat = (correctType.Clone() as XmlSchemaSimpleType)!; tempTokenTypeV1Compat.SetDatatype(c_tokenV1Compat); tempTokenTypeV1Compat.ElementDecl = new SchemaElementDecl(c_tokenV1Compat); tempTokenTypeV1Compat.ElementDecl.SchemaType = tempTokenTypeV1Compat; @@ -357,7 +360,7 @@ namespace System.Xml.Schema XmlSchemaSimpleType currentType = s_enumToTypeCode[(int)typeCode]; while (currentType.BaseXmlSchemaType != DatatypeImplementation.AnySimpleType) { - currentType = currentType.BaseXmlSchemaType as XmlSchemaSimpleType; + currentType = (currentType.BaseXmlSchemaType as XmlSchemaSimpleType)!; Debug.Assert(currentType != null); } return currentType.TypeCode; @@ -378,7 +381,7 @@ namespace System.Xml.Schema return DeriveByList(0, schemaType); } - internal XmlSchemaDatatype DeriveByList(int minSize, XmlSchemaType schemaType) + internal XmlSchemaDatatype DeriveByList(int minSize, XmlSchemaType? schemaType) { if (_variety == XmlSchemaDatatypeVariety.List) { @@ -415,13 +418,14 @@ namespace System.Xml.Schema } //Common case - Derived by restriction - for (DatatypeImplementation dt = this; dt != null; dt = dt._baseType) + for (DatatypeImplementation? dt = this; dt != null; dt = dt._baseType) { if (dt == datatype) { return true; } } + if (((DatatypeImplementation)datatype)._baseType == null) { //Both are built-in types Type derivedType = this.GetType(); @@ -464,7 +468,7 @@ namespace System.Xml.Schema return false; } - internal virtual XmlValueConverter CreateValueConverter(XmlSchemaType schemaType) { return null; } + internal abstract XmlValueConverter CreateValueConverter(XmlSchemaType? schemaType); internal override FacetsChecker FacetsChecker { get { return miscFacetsChecker; } } @@ -488,7 +492,7 @@ namespace System.Xml.Schema public override XmlTypeCode TypeCode { get { return XmlTypeCode.None; } } - internal override RestrictionFacets Restriction + internal override RestrictionFacets? Restriction { get { @@ -499,6 +503,7 @@ namespace System.Xml.Schema _restriction = value; } } + internal override bool HasLexicalFacets { get @@ -524,7 +529,7 @@ namespace System.Xml.Schema } } - protected DatatypeImplementation Base { get { return _baseType; } } + protected DatatypeImplementation? Base { get { return _baseType; } } internal abstract Type ListValueType { get; } @@ -532,32 +537,37 @@ namespace System.Xml.Schema internal override XmlSchemaWhiteSpace BuiltInWhitespaceFacet { get { return XmlSchemaWhiteSpace.Preserve; } } - public override object ParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr) + public override object ParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr) { - object typedValue; - Exception exception = TryParseValue(s, nameTable, nsmgr, out typedValue); + object? typedValue; + Exception? exception = TryParseValue(s, nameTable, nsmgr, out typedValue); if (exception != null) { throw new XmlSchemaException(SR.Sch_InvalidValueDetailed, new string[] { s, GetTypeName(), exception.Message }, exception, null, 0, 0, null); } + + Debug.Assert(typedValue != null); + if (this.Variety == XmlSchemaDatatypeVariety.Union) { - XsdSimpleValue simpleValue = typedValue as XsdSimpleValue; + XsdSimpleValue simpleValue = (typedValue as XsdSimpleValue)!; return simpleValue.TypedValue; } return typedValue; } - internal override object ParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr, bool createAtomicValue) + internal override object ParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr, bool createAtomicValue) { if (createAtomicValue) { - object typedValue; - Exception exception = TryParseValue(s, nameTable, nsmgr, out typedValue); + object? typedValue; + Exception? exception = TryParseValue(s, nameTable, nsmgr, out typedValue); if (exception != null) { throw new XmlSchemaException(SR.Sch_InvalidValueDetailed, new string[] { s, GetTypeName(), exception.Message }, exception, null, 0, 0, null); } + + Debug.Assert(typedValue != null); return typedValue; } else @@ -566,15 +576,17 @@ namespace System.Xml.Schema } } - internal override Exception TryParseValue(object value, XmlNameTable nameTable, IXmlNamespaceResolver namespaceResolver, out object typedValue) + internal override Exception? TryParseValue(object value, XmlNameTable? nameTable, IXmlNamespaceResolver? namespaceResolver, out object? typedValue) { - Exception exception = null; + Exception? exception = null; typedValue = null; + if (value == null) { return new ArgumentNullException(nameof(value)); } - string s = value as string; + + string? s = value as string; if (s != null) { return TryParseValue(s, nameTable, namespaceResolver, out typedValue); @@ -623,7 +635,7 @@ namespace System.Xml.Schema internal string GetTypeName() { - XmlSchemaType simpleType = _parentSchemaType; + XmlSchemaType? simpleType = _parentSchemaType; string typeName; if (simpleType == null || simpleType.QualifiedName.IsEmpty) { //If no QName, get typecode, no line info since it is not pertinent without file name @@ -741,10 +753,10 @@ namespace System.Xml.Schema } } - public int CompareTo(object obj) { return string.Compare(_name, (string)obj, StringComparison.Ordinal); } + public int CompareTo(object? obj) { return string.Compare(_name, (string?)obj, StringComparison.Ordinal); } } - private static readonly DatatypeImplementation[] s_tokenizedTypes = { + private static readonly DatatypeImplementation?[] s_tokenizedTypes = { s_string, // CDATA s_ID, // ID s_IDREF, // IDREF @@ -760,7 +772,7 @@ namespace System.Xml.Schema null }; - private static readonly DatatypeImplementation[] s_tokenizedTypesXsd = { + private static readonly DatatypeImplementation?[] s_tokenizedTypesXsd = { s_string, // CDATA s_ID, // ID s_IDREF, // IDREF @@ -913,11 +925,11 @@ namespace System.Xml.Schema private readonly DatatypeImplementation _itemType; private readonly int _minListSize; - internal override XmlValueConverter CreateValueConverter(XmlSchemaType schemaType) + internal override XmlValueConverter CreateValueConverter(XmlSchemaType? schemaType) { - XmlSchemaType listItemType = null; - XmlSchemaSimpleType simpleType; - XmlSchemaComplexType complexType; + XmlSchemaType? listItemType = null; + XmlSchemaSimpleType? simpleType; + XmlSchemaComplexType? complexType; complexType = schemaType as XmlSchemaComplexType; if (complexType != null) @@ -940,7 +952,7 @@ namespace System.Xml.Schema { do { - XmlSchemaSimpleTypeList listType = simpleType.Content as XmlSchemaSimpleTypeList; + XmlSchemaSimpleTypeList? listType = simpleType.Content as XmlSchemaSimpleTypeList; if (listType != null) { listItemType = listType.BaseItemType; @@ -952,7 +964,7 @@ namespace System.Xml.Schema if (listItemType == null) { //Get built-in simple type for the typecode - listItemType = DatatypeImplementation.GetSimpleTypeFromTypeCode(schemaType.Datatype.TypeCode); + listItemType = DatatypeImplementation.GetSimpleTypeFromTypeCode(schemaType!.Datatype!.TypeCode); } return XmlListConverter.Create(listItemType.ValueConverter); @@ -974,16 +986,17 @@ namespace System.Xml.Schema { return -1; } - XmlAtomicValue[] atomicValues1 = arr1 as XmlAtomicValue[]; + + XmlAtomicValue[]? atomicValues1 = arr1 as XmlAtomicValue[]; if (atomicValues1 != null) { - XmlAtomicValue[] atomicValues2 = arr2 as XmlAtomicValue[]; + XmlAtomicValue[]? atomicValues2 = arr2 as XmlAtomicValue[]; Debug.Assert(atomicValues2 != null); XmlSchemaType xmlType1; for (int i = 0; i < atomicValues1.Length; i++) { xmlType1 = atomicValues1[i].XmlType; - if (xmlType1 != atomicValues2[i].XmlType || !xmlType1.Datatype.IsEqual(atomicValues1[i].TypedValue, atomicValues2[i].TypedValue)) + if (xmlType1 != atomicValues2[i].XmlType || !xmlType1.Datatype!.IsEqual(atomicValues1[i].TypedValue, atomicValues2[i].TypedValue)) { return -1; } @@ -994,7 +1007,7 @@ namespace System.Xml.Schema { for (int i = 0; i < arr1.Length; i++) { - if (_itemType.Compare(arr1.GetValue(i), arr2.GetValue(i)) != 0) + if (_itemType.Compare(arr1.GetValue(i)!, arr2.GetValue(i)!) != 0) { return -1; } @@ -1028,14 +1041,15 @@ namespace System.Xml.Schema } internal DatatypeImplementation ItemType { get { return _itemType; } } - internal override Exception TryParseValue(object value, XmlNameTable nameTable, IXmlNamespaceResolver namespaceResolver, out object typedValue) + internal override Exception? TryParseValue(object value, XmlNameTable? nameTable, IXmlNamespaceResolver? namespaceResolver, out object? typedValue) { - Exception exception; + Exception? exception; if (value == null) { throw new ArgumentNullException(nameof(value)); } - string s = value as string; + + string? s = value as string; typedValue = null; if (s != null) { @@ -1045,7 +1059,7 @@ namespace System.Xml.Schema try { object valueToCheck = this.ValueConverter.ChangeType(value, this.ValueType, namespaceResolver); - Array valuesToCheck = valueToCheck as Array; + Array valuesToCheck = (valueToCheck as Array)!; Debug.Assert(valuesToCheck != null); bool checkItemLexical = _itemType.HasLexicalFacets; @@ -1056,7 +1070,7 @@ namespace System.Xml.Schema for (int i = 0; i < valuesToCheck.Length; i++) { - item = valuesToCheck.GetValue(i); + item = valuesToCheck.GetValue(i)!; if (checkItemLexical) { string s1 = (string)itemValueConverter.ChangeType(item, typeof(string), namespaceResolver); @@ -1106,9 +1120,9 @@ namespace System.Xml.Schema return exception; } - internal override Exception TryParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr, out object typedValue) + internal override Exception? TryParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr, out object? typedValue) { - Exception exception; + Exception? exception; typedValue = null; @@ -1119,7 +1133,7 @@ namespace System.Xml.Schema object array; if (_itemType.Variety == XmlSchemaDatatypeVariety.Union) { - object unionTypedValue; + object? unionTypedValue; string[] splitString = XmlConvert.SplitString(s); for (int i = 0; i < splitString.Length; ++i) { @@ -1127,6 +1141,8 @@ namespace System.Xml.Schema exception = _itemType.TryParseValue(splitString[i], nameTable, nsmgr, out unionTypedValue); if (exception != null) goto Error; + Debug.Assert(unionTypedValue != null); + XsdSimpleValue simpleValue = (XsdSimpleValue)unionTypedValue; values.Add(new XmlAtomicValue(simpleValue.XmlType, simpleValue.TypedValue, nsmgr)); } @@ -1169,7 +1185,7 @@ namespace System.Xml.Schema private static readonly Type s_listValueType = typeof(object[]); private readonly XmlSchemaSimpleType[] _types; - internal override XmlValueConverter CreateValueConverter(XmlSchemaType schemaType) + internal override XmlValueConverter CreateValueConverter(XmlSchemaType? schemaType) { return XmlUnionConverter.Create(schemaType); } @@ -1181,21 +1197,23 @@ namespace System.Xml.Schema internal override int Compare(object value1, object value2) { - XsdSimpleValue simpleValue1 = value1 as XsdSimpleValue; - XsdSimpleValue simpleValue2 = value2 as XsdSimpleValue; + XsdSimpleValue? simpleValue1 = value1 as XsdSimpleValue; + XsdSimpleValue? simpleValue2 = value2 as XsdSimpleValue; if (simpleValue1 == null || simpleValue2 == null) { return -1; } + XmlSchemaType schemaType1 = simpleValue1.XmlType; XmlSchemaType schemaType2 = simpleValue2.XmlType; if (schemaType1 == schemaType2) { - XmlSchemaDatatype datatype = schemaType1.Datatype; + XmlSchemaDatatype datatype = schemaType1.Datatype!; return datatype.Compare(simpleValue1.TypedValue, simpleValue2.TypedValue); } + return -1; } @@ -1228,7 +1246,7 @@ namespace System.Xml.Schema { for (int i = 0; i < _types.Length; ++i) { - if (_types[i].Datatype.Variety == XmlSchemaDatatypeVariety.List) + if (_types[i].Datatype!.Variety == XmlSchemaDatatypeVariety.List) { return false; } @@ -1240,7 +1258,7 @@ namespace System.Xml.Schema { for (int i = 0; i < _types.Length; ++i) { - if (derivedType.IsDerivedFrom(_types[i].Datatype)) + if (derivedType.IsDerivedFrom(_types[i].Datatype!)) { return true; } @@ -1248,10 +1266,10 @@ namespace System.Xml.Schema return false; } - internal override Exception TryParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr, out object typedValue) + internal override Exception? TryParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr, out object? typedValue) { - Exception exception; - XmlSchemaSimpleType memberType = null; + Exception? exception; + XmlSchemaSimpleType? memberType = null; typedValue = null; @@ -1261,13 +1279,16 @@ namespace System.Xml.Schema //Parse string to CLR value for (int i = 0; i < _types.Length; ++i) { - exception = _types[i].Datatype.TryParseValue(s, nameTable, nsmgr, out typedValue); + exception = _types[i].Datatype!.TryParseValue(s, nameTable, nsmgr, out typedValue); if (exception == null) { memberType = _types[i]; break; } } + + Debug.Assert(typedValue != null); + if (memberType == null) { exception = new XmlSchemaException(SR.Sch_UnionFailedEx, s); @@ -1284,35 +1305,37 @@ namespace System.Xml.Schema return exception; } - internal override Exception TryParseValue(object value, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr, out object typedValue) + internal override Exception? TryParseValue(object value, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr, out object? typedValue) { - Exception exception; + Exception? exception; if (value == null) { throw new ArgumentNullException(nameof(value)); } typedValue = null; - string s = value as string; + string? s = value as string; if (s != null) { return TryParseValue(s, nameTable, nsmgr, out typedValue); } - object valueToCheck = null; - XmlSchemaSimpleType memberType = null; + object? valueToCheck = null; + XmlSchemaSimpleType? memberType = null; for (int i = 0; i < _types.Length; ++i) { - if (_types[i].Datatype.TryParseValue(value, nameTable, nsmgr, out valueToCheck) == null) + if (_types[i].Datatype!.TryParseValue(value, nameTable, nsmgr, out valueToCheck) == null) { //no error memberType = _types[i]; break; } } + if (valueToCheck == null) { exception = new XmlSchemaException(SR.Sch_UnionFailedEx, value.ToString()); goto Error; } + try { if (this.HasLexicalFacets) @@ -1321,6 +1344,8 @@ namespace System.Xml.Schema exception = unionFacetsChecker.CheckLexicalFacets(ref s1, this); if (exception != null) goto Error; } + + Debug.Assert(memberType != null); typedValue = new XsdSimpleValue(memberType, valueToCheck); if (this.HasValueFacets) { @@ -1358,7 +1383,7 @@ namespace System.Xml.Schema private static readonly Type s_atomicValueType = typeof(string); private static readonly Type s_listValueType = typeof(string[]); - internal override XmlValueConverter CreateValueConverter(XmlSchemaType schemaType) + internal override XmlValueConverter CreateValueConverter(XmlSchemaType? schemaType) { return XmlUntypedConverter.Untyped; } @@ -1383,7 +1408,7 @@ namespace System.Xml.Schema return string.Compare(value1.ToString(), value2.ToString(), StringComparison.Ordinal); } - internal override Exception TryParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr, out object typedValue) + internal override Exception? TryParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr, out object? typedValue) { typedValue = XmlComplianceUtil.NonCDataNormalize(s); //Whitespace facet is treated as collapse since thats the way it was in Everett return null; @@ -1392,7 +1417,7 @@ namespace System.Xml.Schema internal class Datatype_anyAtomicType : Datatype_anySimpleType { - internal override XmlValueConverter CreateValueConverter(XmlSchemaType schemaType) + internal override XmlValueConverter CreateValueConverter(XmlSchemaType? schemaType) { return XmlAnyConverter.AnyAtomic; } @@ -1403,7 +1428,7 @@ namespace System.Xml.Schema internal class Datatype_untypedAtomicType : Datatype_anyAtomicType { - internal override XmlValueConverter CreateValueConverter(XmlSchemaType schemaType) + internal override XmlValueConverter CreateValueConverter(XmlSchemaType? schemaType) { return XmlUntypedConverter.Untyped; } @@ -1438,7 +1463,7 @@ namespace System.Xml.Schema */ internal class Datatype_string : Datatype_anySimpleType { - internal override XmlValueConverter CreateValueConverter(XmlSchemaType schemaType) + internal override XmlValueConverter CreateValueConverter(XmlSchemaType? schemaType) { return XmlStringConverter.Create(schemaType); } @@ -1464,9 +1489,9 @@ namespace System.Xml.Schema } } - internal override Exception TryParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr, out object typedValue) + internal override Exception? TryParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr, out object? typedValue) { - Exception exception; + Exception? exception; typedValue = null; @@ -1509,7 +1534,7 @@ namespace System.Xml.Schema private static readonly Type s_atomicValueType = typeof(bool); private static readonly Type s_listValueType = typeof(bool[]); - internal override XmlValueConverter CreateValueConverter(XmlSchemaType schemaType) + internal override XmlValueConverter CreateValueConverter(XmlSchemaType? schemaType) { return XmlBooleanConverter.Create(schemaType); } @@ -1538,9 +1563,9 @@ namespace System.Xml.Schema return ((bool)value1).CompareTo((bool)value2); } - internal override Exception TryParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr, out object typedValue) + internal override Exception? TryParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr, out object? typedValue) { - Exception exception; + Exception? exception; typedValue = null; exception = miscFacetsChecker.CheckLexicalFacets(ref s, this); @@ -1589,7 +1614,7 @@ namespace System.Xml.Schema private static readonly Type s_atomicValueType = typeof(float); private static readonly Type s_listValueType = typeof(float[]); - internal override XmlValueConverter CreateValueConverter(XmlSchemaType schemaType) + internal override XmlValueConverter CreateValueConverter(XmlSchemaType? schemaType) { return XmlNumeric2Converter.Create(schemaType); } @@ -1623,9 +1648,9 @@ namespace System.Xml.Schema return ((float)value1).CompareTo((float)value2); } - internal override Exception TryParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr, out object typedValue) + internal override Exception? TryParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr, out object? typedValue) { - Exception exception; + Exception? exception; typedValue = null; @@ -1678,7 +1703,7 @@ namespace System.Xml.Schema private static readonly Type s_atomicValueType = typeof(double); private static readonly Type s_listValueType = typeof(double[]); - internal override XmlValueConverter CreateValueConverter(XmlSchemaType schemaType) + internal override XmlValueConverter CreateValueConverter(XmlSchemaType? schemaType) { return XmlNumeric2Converter.Create(schemaType); } @@ -1712,9 +1737,9 @@ namespace System.Xml.Schema return ((double)value1).CompareTo((double)value2); } - internal override Exception TryParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr, out object typedValue) + internal override Exception? TryParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr, out object? typedValue) { - Exception exception; + Exception? exception; typedValue = null; exception = numeric2FacetsChecker.CheckLexicalFacets(ref s, this); @@ -1770,7 +1795,7 @@ namespace System.Xml.Schema private static readonly Type s_listValueType = typeof(decimal[]); private static readonly FacetsChecker s_numeric10FacetsChecker = new Numeric10FacetsChecker(decimal.MinValue, decimal.MaxValue); - internal override XmlValueConverter CreateValueConverter(XmlSchemaType schemaType) + internal override XmlValueConverter CreateValueConverter(XmlSchemaType? schemaType) { return XmlNumeric10Converter.Create(schemaType); } @@ -1806,9 +1831,9 @@ namespace System.Xml.Schema return ((decimal)value1).CompareTo((decimal)value2); } - internal override Exception TryParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr, out object typedValue) + internal override Exception? TryParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr, out object? typedValue) { - Exception exception; + Exception? exception; typedValue = null; @@ -1862,7 +1887,7 @@ namespace System.Xml.Schema private static readonly Type s_atomicValueType = typeof(TimeSpan); private static readonly Type s_listValueType = typeof(TimeSpan[]); - internal override XmlValueConverter CreateValueConverter(XmlSchemaType schemaType) + internal override XmlValueConverter CreateValueConverter(XmlSchemaType? schemaType) { return XmlMiscConverter.Create(schemaType); } @@ -1897,9 +1922,9 @@ namespace System.Xml.Schema } - internal override Exception TryParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr, out object typedValue) + internal override Exception? TryParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr, out object? typedValue) { - Exception exception; + Exception? exception; typedValue = null; if (s == null || s.Length == 0) @@ -1928,9 +1953,9 @@ namespace System.Xml.Schema internal class Datatype_yearMonthDuration : Datatype_duration { - internal override Exception TryParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr, out object typedValue) + internal override Exception? TryParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr, out object? typedValue) { - Exception exception; + Exception? exception; typedValue = null; if (s == null || s.Length == 0) @@ -1966,9 +1991,9 @@ namespace System.Xml.Schema internal class Datatype_dayTimeDuration : Datatype_duration { - internal override Exception TryParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr, out object typedValue) + internal override Exception? TryParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr, out object? typedValue) { - Exception exception; + Exception? exception; typedValue = null; @@ -2008,7 +2033,7 @@ namespace System.Xml.Schema private static readonly Type s_listValueType = typeof(DateTime[]); private readonly XsdDateTimeFlags _dateTimeFlags; - internal override XmlValueConverter CreateValueConverter(XmlSchemaType schemaType) + internal override XmlValueConverter CreateValueConverter(XmlSchemaType? schemaType) { return XmlDateTimeConverter.Create(schemaType); } @@ -2054,9 +2079,9 @@ namespace System.Xml.Schema return dateTime1.CompareTo(dateTime2.ToUniversalTime()); } - internal override Exception TryParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr, out object typedValue) + internal override Exception? TryParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr, out object? typedValue) { - Exception exception; + Exception? exception; typedValue = null; exception = dateTimeFacetsChecker.CheckLexicalFacets(ref s, this); @@ -2406,7 +2431,7 @@ namespace System.Xml.Schema private static readonly Type s_atomicValueType = typeof(byte[]); private static readonly Type s_listValueType = typeof(byte[][]); - internal override XmlValueConverter CreateValueConverter(XmlSchemaType schemaType) + internal override XmlValueConverter CreateValueConverter(XmlSchemaType? schemaType) { return XmlMiscConverter.Create(schemaType); } @@ -2439,16 +2464,16 @@ namespace System.Xml.Schema return Compare((byte[])value1, (byte[])value2); } - internal override Exception TryParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr, out object typedValue) + internal override Exception? TryParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr, out object? typedValue) { - Exception exception; + Exception? exception; typedValue = null; exception = binaryFacetsChecker.CheckLexicalFacets(ref s, this); if (exception != null) goto Error; - byte[] byteArrayValue = null; + byte[]? byteArrayValue = null; try { byteArrayValue = XmlConvert.FromBinHexString(s, false); @@ -2507,7 +2532,7 @@ namespace System.Xml.Schema private static readonly Type s_atomicValueType = typeof(byte[]); private static readonly Type s_listValueType = typeof(byte[][]); - internal override XmlValueConverter CreateValueConverter(XmlSchemaType schemaType) + internal override XmlValueConverter CreateValueConverter(XmlSchemaType? schemaType) { return XmlMiscConverter.Create(schemaType); } @@ -2540,16 +2565,16 @@ namespace System.Xml.Schema return Compare((byte[])value1, (byte[])value2); } - internal override Exception TryParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr, out object typedValue) + internal override Exception? TryParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr, out object? typedValue) { - Exception exception; + Exception? exception; typedValue = null; exception = binaryFacetsChecker.CheckLexicalFacets(ref s, this); if (exception != null) goto Error; - byte[] byteArrayValue = null; + byte[]? byteArrayValue = null; try { byteArrayValue = Convert.FromBase64String(s); @@ -2607,7 +2632,7 @@ namespace System.Xml.Schema private static readonly Type s_atomicValueType = typeof(Uri); private static readonly Type s_listValueType = typeof(Uri[]); - internal override XmlValueConverter CreateValueConverter(XmlSchemaType schemaType) + internal override XmlValueConverter CreateValueConverter(XmlSchemaType? schemaType) { return XmlMiscConverter.Create(schemaType); } @@ -2647,19 +2672,21 @@ namespace System.Xml.Schema return ((Uri)value1).Equals((Uri)value2) ? 0 : -1; } - internal override Exception TryParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr, out object typedValue) + internal override Exception? TryParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr, out object? typedValue) { - Exception exception; + Exception? exception; typedValue = null; exception = stringFacetsChecker.CheckLexicalFacets(ref s, this); if (exception != null) goto Error; - Uri uri; + Uri? uri; exception = XmlConvert.TryToUri(s, out uri); if (exception != null) goto Error; + Debug.Assert(uri != null); + string stringValue = uri.OriginalString; exception = ((StringFacetsChecker)stringFacetsChecker).CheckValueFacets(stringValue, this, false); if (exception != null) goto Error; @@ -2703,7 +2730,7 @@ namespace System.Xml.Schema private static readonly Type s_atomicValueType = typeof(XmlQualifiedName); private static readonly Type s_listValueType = typeof(XmlQualifiedName[]); - internal override XmlValueConverter CreateValueConverter(XmlSchemaType schemaType) + internal override XmlValueConverter CreateValueConverter(XmlSchemaType? schemaType) { return XmlMiscConverter.Create(schemaType); } @@ -2733,9 +2760,9 @@ namespace System.Xml.Schema internal override XmlSchemaWhiteSpace BuiltInWhitespaceFacet { get { return XmlSchemaWhiteSpace.Collapse; } } - internal override Exception TryParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr, out object typedValue) + internal override Exception? TryParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr, out object? typedValue) { - Exception exception; + Exception? exception; typedValue = null; @@ -2747,11 +2774,11 @@ namespace System.Xml.Schema exception = qnameFacetsChecker.CheckLexicalFacets(ref s, this); if (exception != null) goto Error; - XmlQualifiedName qname = null; + XmlQualifiedName? qname = null; try { string prefix; - qname = XmlQualifiedName.Parse(s, nsmgr, out prefix); + qname = XmlQualifiedName.Parse(s, nsmgr!, out prefix); } catch (ArgumentException e) { @@ -2933,9 +2960,9 @@ namespace System.Xml.Schema { public override XmlTypeCode TypeCode { get { return XmlTypeCode.NCName; } } - internal override Exception TryParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr, out object typedValue) + internal override Exception? TryParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr, out object? typedValue) { - Exception exception; + Exception? exception; typedValue = null; @@ -2945,7 +2972,7 @@ namespace System.Xml.Schema exception = stringFacetsChecker.CheckValueFacets(s, this); if (exception != null) goto Error; - nameTable.Add(s); + nameTable!.Add(s); typedValue = s; return null; @@ -3039,7 +3066,7 @@ namespace System.Xml.Schema private static readonly Type s_atomicValueType = typeof(XmlQualifiedName); private static readonly Type s_listValueType = typeof(XmlQualifiedName[]); - internal override XmlValueConverter CreateValueConverter(XmlSchemaType schemaType) + internal override XmlValueConverter CreateValueConverter(XmlSchemaType? schemaType) { return XmlMiscConverter.Create(schemaType); } @@ -3069,9 +3096,9 @@ namespace System.Xml.Schema internal override XmlSchemaWhiteSpace BuiltInWhitespaceFacet { get { return XmlSchemaWhiteSpace.Collapse; } } - internal override Exception TryParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr, out object typedValue) + internal override Exception? TryParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr, out object? typedValue) { - Exception exception; + Exception? exception; typedValue = null; @@ -3083,11 +3110,11 @@ namespace System.Xml.Schema exception = qnameFacetsChecker.CheckLexicalFacets(ref s, this); if (exception != null) goto Error; - XmlQualifiedName qname = null; + XmlQualifiedName? qname = null; try { string prefix; - qname = XmlQualifiedName.Parse(s, nsmgr, out prefix); + qname = XmlQualifiedName.Parse(s, nsmgr!, out prefix); } catch (ArgumentException e) { @@ -3115,13 +3142,13 @@ namespace System.Xml.Schema { // Only datatypes that are derived from NOTATION by specifying a value for enumeration can be used in a schema. // Furthermore, the value of all enumeration facets must match the name of a notation declared in the current schema. // - for (Datatype_NOTATION dt = this; dt != null; dt = (Datatype_NOTATION)dt.Base) + for (Datatype_NOTATION? dt = this; dt != null; dt = (Datatype_NOTATION?)dt.Base) { if (dt.Restriction != null && (dt.Restriction.Flags & RestrictionFlags.Enumeration) != 0) { - for (int i = 0; i < dt.Restriction.Enumeration.Count; ++i) + for (int i = 0; i < dt.Restriction.Enumeration!.Count; ++i) { - XmlQualifiedName notation = (XmlQualifiedName)dt.Restriction.Enumeration[i]; + XmlQualifiedName notation = (XmlQualifiedName)dt.Restriction.Enumeration[i]!; if (!notations.Contains(notation)) { throw new XmlSchemaException(SR.Sch_NotationRequired, caller); @@ -3149,9 +3176,9 @@ namespace System.Xml.Schema { public override XmlTypeCode TypeCode { get { return XmlTypeCode.Integer; } } - internal override Exception TryParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr, out object typedValue) + internal override Exception? TryParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr, out object? typedValue) { - Exception exception; + Exception? exception; typedValue = null; @@ -3267,9 +3294,9 @@ namespace System.Xml.Schema internal override Type ListValueType { get { return s_listValueType; } } - internal override Exception TryParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr, out object typedValue) + internal override Exception? TryParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr, out object? typedValue) { - Exception exception; + Exception? exception; typedValue = null; @@ -3323,9 +3350,9 @@ namespace System.Xml.Schema internal override Type ListValueType { get { return s_listValueType; } } - internal override Exception TryParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr, out object typedValue) + internal override Exception? TryParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr, out object? typedValue) { - Exception exception; + Exception? exception; typedValue = null; @@ -3380,9 +3407,9 @@ namespace System.Xml.Schema internal override Type ListValueType { get { return s_listValueType; } } - internal override Exception TryParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr, out object typedValue) + internal override Exception? TryParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr, out object? typedValue) { - Exception exception; + Exception? exception; typedValue = null; @@ -3436,9 +3463,9 @@ namespace System.Xml.Schema internal override Type ListValueType { get { return s_listValueType; } } - internal override Exception TryParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr, out object typedValue) + internal override Exception? TryParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr, out object? typedValue) { - Exception exception; + Exception? exception; typedValue = null; @@ -3524,9 +3551,9 @@ namespace System.Xml.Schema internal override Type ListValueType { get { return s_listValueType; } } - internal override Exception TryParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr, out object typedValue) + internal override Exception? TryParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr, out object? typedValue) { - Exception exception; + Exception? exception; typedValue = null; @@ -3580,9 +3607,9 @@ namespace System.Xml.Schema internal override Type ListValueType { get { return s_listValueType; } } - internal override Exception TryParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr, out object typedValue) + internal override Exception? TryParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr, out object? typedValue) { - Exception exception; + Exception? exception; typedValue = null; @@ -3636,9 +3663,9 @@ namespace System.Xml.Schema internal override Type ListValueType { get { return s_listValueType; } } - internal override Exception TryParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr, out object typedValue) + internal override Exception? TryParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr, out object? typedValue) { - Exception exception; + Exception? exception; typedValue = null; @@ -3691,9 +3718,9 @@ namespace System.Xml.Schema internal override Type ListValueType { get { return s_listValueType; } } - internal override Exception TryParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr, out object typedValue) + internal override Exception? TryParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr, out object? typedValue) { - Exception exception; + Exception? exception; typedValue = null; @@ -3741,7 +3768,7 @@ namespace System.Xml.Schema */ internal class Datatype_doubleXdr : Datatype_double { - public override object ParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr) + public override object ParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr) { double value; try @@ -3763,7 +3790,7 @@ namespace System.Xml.Schema internal class Datatype_floatXdr : Datatype_float { - public override object ParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr) + public override object ParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr) { float value; try @@ -3790,7 +3817,7 @@ namespace System.Xml.Schema public override XmlTokenizedType TokenizedType { get { return XmlTokenizedType.QName; } } - public override object ParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr) + public override object ParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr) { if (s == null || s.Length == 0) { @@ -3842,7 +3869,7 @@ namespace System.Xml.Schema return ((char)value1).CompareTo((char)value2); } - public override object ParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr) + public override object ParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr) { try { @@ -3858,9 +3885,9 @@ namespace System.Xml.Schema } } - internal override Exception TryParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr, out object typedValue) + internal override Exception? TryParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr, out object? typedValue) { - Exception exception; + Exception? exception; typedValue = null; @@ -3879,13 +3906,13 @@ namespace System.Xml.Schema internal class Datatype_fixed : Datatype_decimal { - public override object ParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr) + public override object ParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr) { - Exception exception; + Exception? exception; try { - Numeric10FacetsChecker facetsChecker = this.FacetsChecker as Numeric10FacetsChecker; + Numeric10FacetsChecker facetsChecker = (this.FacetsChecker as Numeric10FacetsChecker)!; decimal value = XmlConvert.ToDecimal(s); exception = facetsChecker.CheckTotalAndFractionDigits(value, 14 + 4, 4, true, true); if (exception != null) goto Error; @@ -3904,9 +3931,9 @@ namespace System.Xml.Schema throw exception; } - internal override Exception TryParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr, out object typedValue) + internal override Exception? TryParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr, out object? typedValue) { - Exception exception; + Exception? exception; typedValue = null; @@ -3914,7 +3941,7 @@ namespace System.Xml.Schema exception = XmlConvert.TryToDecimal(s, out decimalValue); if (exception != null) goto Error; - Numeric10FacetsChecker facetsChecker = this.FacetsChecker as Numeric10FacetsChecker; + Numeric10FacetsChecker facetsChecker = (this.FacetsChecker as Numeric10FacetsChecker)!; exception = facetsChecker.CheckTotalAndFractionDigits(decimalValue, 14 + 4, 4, true, true); if (exception != null) goto Error; @@ -3943,7 +3970,7 @@ namespace System.Xml.Schema return ((Guid)value1).Equals(value2) ? 0 : -1; } - public override object ParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr) + public override object ParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr) { try { @@ -3959,9 +3986,9 @@ namespace System.Xml.Schema } } - internal override Exception TryParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr, out object typedValue) + internal override Exception? TryParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr, out object? typedValue) { - Exception exception; + Exception? exception; typedValue = null; 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 b0b13b1..26e732d 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.IO; using System.Text; @@ -10,6 +11,7 @@ using System.Diagnostics; using System.Collections; using System.Collections.Generic; using System.Globalization; +using System.Diagnostics.CodeAnalysis; namespace System.Xml { @@ -120,7 +122,7 @@ namespace System.Xml internal string name; internal int lineNo; internal int linePos; - internal UndeclaredNotation next; + internal UndeclaredNotation? next; internal UndeclaredNotation(string name, int lineNo, int linePos) { @@ -135,21 +137,21 @@ namespace System.Xml // Fields // // connector to reader - private IDtdParserAdapter _readerAdapter; - private IDtdParserAdapterWithValidation _readerAdapterWithValidation; + private IDtdParserAdapter _readerAdapter = null!; + private IDtdParserAdapterWithValidation? _readerAdapterWithValidation; // name table - private XmlNameTable _nameTable; + private XmlNameTable _nameTable = null!; // final schema info - private SchemaInfo _schemaInfo; + private SchemaInfo _schemaInfo = null!; // XmlCharType instance private XmlCharType _xmlCharType = XmlCharType.Instance; // system & public id - private string _systemId = string.Empty; - private string _publicId = string.Empty; + private string? _systemId = string.Empty; + private string? _publicId = string.Empty; // flags private bool _normalize = true; @@ -158,7 +160,7 @@ namespace System.Xml private bool _v1Compat = false; // cached character buffer - private char[] _chars; + private char[] _chars = null!; private int _charsUsed; private int _curPos; @@ -177,7 +179,7 @@ namespace System.Xml private int _colonPos; // value of the internal subset - private StringBuilder _internalSubsetValueSb = null; + private StringBuilder? _internalSubsetValueSb = null; // entities private int _externalEntitiesDepth = 0; @@ -188,15 +190,15 @@ namespace System.Xml private bool _hasFreeFloatingInternalSubset = false; // misc - private StringBuilder _stringBuilder; + private StringBuilder _stringBuilder = null!; private int _condSectionDepth = 0; private LineInfo _literalLineInfo = new LineInfo(0, 0); private char _literalQuoteChar = '"'; private string _documentBaseUri = string.Empty; private string _externalDtdBaseUri = string.Empty; - private Dictionary _undeclaredNotations = null; - private int[] _condSectionEntityIds = null; + private Dictionary? _undeclaredNotations = null; + private int[]? _condSectionEntityIds = null; private const int CondSectionEntityIdsInitialSize = 2; @@ -241,12 +243,12 @@ namespace System.Xml _nameTable = readerAdapter.NameTable; - IDtdParserAdapterWithValidation raWithValidation = readerAdapter as IDtdParserAdapterWithValidation; + IDtdParserAdapterWithValidation? raWithValidation = readerAdapter as IDtdParserAdapterWithValidation; if (raWithValidation != null) { _validate = raWithValidation.DtdValidation; } - IDtdParserAdapterV1 raV1 = readerAdapter as IDtdParserAdapterV1; + IDtdParserAdapterV1? raV1 = readerAdapter as IDtdParserAdapterV1; if (raV1 != null) { _v1Compat = raV1.V1CompatibilityMode; @@ -259,7 +261,7 @@ namespace System.Xml _stringBuilder = new StringBuilder(); - Uri baseUri = readerAdapter.BaseUri; + Uri? baseUri = readerAdapter.BaseUri; if (baseUri != null) { _documentBaseUri = baseUri.ToString(); @@ -318,7 +320,7 @@ namespace System.Xml _hasFreeFloatingInternalSubset = true; } - Uri baseUriOb = _readerAdapter.BaseUri; + Uri? baseUriOb = _readerAdapter.BaseUri; if (baseUriOb != null) { _documentBaseUri = baseUriOb.ToString(); @@ -421,7 +423,7 @@ namespace System.Xml { foreach (UndeclaredNotation un in _undeclaredNotations.Values) { - UndeclaredNotation tmpUn = un; + UndeclaredNotation? tmpUn = un; while (tmpUn != null) { SendValidationEvent(XmlSeverityType.Error, new XmlSchemaException(SR.Sch_UndeclaredNotation, un.name, BaseUriStr, (int)un.lineNo, (int)un.linePos)); @@ -509,7 +511,7 @@ namespace System.Xml return; } - Uri baseUri = _readerAdapter.BaseUri; + Uri? baseUri = _readerAdapter.BaseUri; if (baseUri != null) { _externalDtdBaseUri = baseUri.ToString(); @@ -572,7 +574,7 @@ namespace System.Xml if (_condSectionDepth > 0) { _condSectionDepth--; - if (_validate && _currentEntityId != _condSectionEntityIds[_condSectionDepth]) + if (_validate && _currentEntityId != _condSectionEntityIds![_condSectionDepth]) { SendValidationEvent(_curPos, XmlSeverityType.Error, SR.Sch_ParEntityRefNesting, string.Empty); } @@ -656,7 +658,7 @@ namespace System.Xml // element name XmlQualifiedName elementName = GetNameQualified(true); - SchemaElementDecl elementDecl; + SchemaElementDecl? elementDecl; if (!_schemaInfo.ElementDecls.TryGetValue(elementName, out elementDecl)) { if (!_schemaInfo.UndeclaredElementDecls.TryGetValue(elementName, out elementDecl)) @@ -666,7 +668,7 @@ namespace System.Xml } } - SchemaAttDef attrDef = null; + SchemaAttDef? attrDef = null; while (true) { switch (GetToken(false)) @@ -694,7 +696,7 @@ namespace System.Xml } if (_validate) { - attrDef.CheckXmlSpace(_readerAdapterWithValidation.ValidationEventHandling); + attrDef.CheckXmlSpace(_readerAdapterWithValidation!.ValidationEventHandling); } } } @@ -734,7 +736,7 @@ namespace System.Xml } if (_validate) { - attrDef.CheckXmlSpace(_readerAdapterWithValidation.ValidationEventHandling); + attrDef.CheckXmlSpace(_readerAdapterWithValidation!.ValidationEventHandling); } } } @@ -940,7 +942,7 @@ namespace System.Xml } // get schema decl for element - SchemaElementDecl elementDecl = null; + SchemaElementDecl? elementDecl = null; XmlQualifiedName name = GetNameQualified(true); if (_schemaInfo.ElementDecls.TryGetValue(name, out elementDecl)) @@ -990,7 +992,7 @@ namespace System.Xml } case Token.None: { - ParticleContentValidator pcv = null; + ParticleContentValidator? pcv = null; pcv = new ParticleContentValidator(XmlSchemaContentType.ElementOnly); pcv.Start(); pcv.OpenGroup(); @@ -1213,7 +1215,7 @@ namespace System.Xml private void ParseEntityDecl() { bool isParamEntity = false; - SchemaEntity entity = null; + SchemaEntity? entity = null; // get entity name and type switch (GetToken(true)) @@ -1259,8 +1261,8 @@ namespace System.Xml { case Token.PUBLIC: case Token.SYSTEM: - string systemId; - string publicId; + string? systemId; + string? publicId; ParseExternalId(token, Token.EntityDecl, out publicId, out systemId); @@ -1320,7 +1322,7 @@ namespace System.Xml } XmlQualifiedName notationName = GetNameQualified(false); - SchemaNotation notation = null; + SchemaNotation? notation = null; if (!_schemaInfo.Notations.ContainsKey(notationName.Name)) { if (_undeclaredNotations != null) @@ -1343,7 +1345,7 @@ namespace System.Xml Token token = GetToken(true); if (token == Token.SYSTEM || token == Token.PUBLIC) { - string notationPublicId, notationSystemId; + string? notationPublicId, notationSystemId; ParseExternalId(token, Token.NOTATION, out notationPublicId, out notationSystemId); @@ -1369,7 +1371,7 @@ namespace System.Xml _undeclaredNotations = new Dictionary(); } UndeclaredNotation un = new UndeclaredNotation(notationName, LineNo, LinePos - notationName.Length); - UndeclaredNotation loggedUn; + UndeclaredNotation? loggedUn; if (_undeclaredNotations.TryGetValue(notationName, out loggedUn)) { un.next = loggedUn.next; @@ -1389,7 +1391,7 @@ namespace System.Xml if (SaveInternalSubsetValue) { _readerAdapter.ParseComment(_internalSubsetValueSb); - _internalSubsetValueSb.Append("-->"); + _internalSubsetValueSb!.Append("-->"); } else { @@ -1416,7 +1418,7 @@ namespace System.Xml if (SaveInternalSubsetValue) { _readerAdapter.ParsePI(_internalSubsetValueSb); - _internalSubsetValueSb.Append("?>"); + _internalSubsetValueSb!.Append("?>"); } else { @@ -1481,7 +1483,7 @@ namespace System.Xml } } - private void ParseExternalId(Token idTokenType, Token declType, out string publicId, out string systemId) + private void ParseExternalId(Token idTokenType, Token declType, out string? publicId, out string? systemId) { LineInfo keywordLineInfo = new LineInfo(LineNo, LinePos - 6); publicId = null; @@ -3309,7 +3311,7 @@ namespace System.Xml Throw(_curPos - entityName.Name.Length - 1, SR.Xml_InvalidParEntityRef); } - SchemaEntity entity = VerifyEntityReference(entityName, paramEntity, true, inAttribute); + SchemaEntity? entity = VerifyEntityReference(entityName, paramEntity, true, inAttribute); if (entity == null) { return false; @@ -3330,7 +3332,7 @@ namespace System.Xml } else { - if (entity.Text.Length == 0) + if (entity.Text!.Length == 0) { return false; } @@ -3356,7 +3358,7 @@ namespace System.Xml { SaveParsingBuffer(); - IDtdEntityInfo oldEntity; + IDtdEntityInfo? oldEntity; if (!_readerAdapter.PopEntity(out oldEntity, out _currentEntityId)) { return false; @@ -3389,11 +3391,11 @@ namespace System.Xml return true; } - private SchemaEntity VerifyEntityReference(XmlQualifiedName entityName, bool paramEntity, bool mustBeDeclared, bool inAttribute) + private SchemaEntity? VerifyEntityReference(XmlQualifiedName entityName, bool paramEntity, bool mustBeDeclared, bool inAttribute) { Debug.Assert(_chars[_curPos - 1] == ';'); - SchemaEntity entity; + SchemaEntity? entity; if (paramEntity) { _schemaInfo.ParameterEntities.TryGetValue(entityName, out entity); @@ -3445,13 +3447,13 @@ namespace System.Xml // // Helper methods and properties // - private void SendValidationEvent(int pos, XmlSeverityType severity, string code, string arg) + private void SendValidationEvent(int pos, XmlSeverityType severity, string code, string? arg) { Debug.Assert(_validate); SendValidationEvent(severity, new XmlSchemaException(code, arg, BaseUriStr, (int)LineNo, (int)LinePos + (pos - _curPos))); } - private void SendValidationEvent(XmlSeverityType severity, string code, string arg) + private void SendValidationEvent(XmlSeverityType severity, string code, string? arg) { Debug.Assert(_validate); SendValidationEvent(severity, new XmlSchemaException(code, arg, BaseUriStr, (int)LineNo, (int)LinePos)); @@ -3460,7 +3462,7 @@ namespace System.Xml private void SendValidationEvent(XmlSeverityType severity, XmlSchemaException e) { Debug.Assert(_validate); - IValidationEventHandling eventHandling = _readerAdapterWithValidation.ValidationEventHandling; + IValidationEventHandling? eventHandling = _readerAdapterWithValidation!.ValidationEventHandling; if (eventHandling != null) { eventHandling.SendEvent(e, severity); @@ -3492,7 +3494,7 @@ namespace System.Xml { get { - Uri tmp = _readerAdapter.BaseUri; + Uri? tmp = _readerAdapter.BaseUri; return (tmp != null) ? tmp.ToString() : string.Empty; } } @@ -3508,22 +3510,26 @@ namespace System.Xml Throw(curPos, res, string.Empty); } + [DoesNotReturn] private void Throw(int curPos, string res, string arg) { _curPos = curPos; - Uri baseUri = _readerAdapter.BaseUri; + Uri? baseUri = _readerAdapter.BaseUri; _readerAdapter.Throw(new XmlException(res, arg, (int)LineNo, (int)LinePos, baseUri == null ? null : baseUri.ToString())); } + + [DoesNotReturn] private void Throw(int curPos, string res, string[] args) { _curPos = curPos; - Uri baseUri = _readerAdapter.BaseUri; + Uri? baseUri = _readerAdapter.BaseUri; _readerAdapter.Throw(new XmlException(res, args, (int)LineNo, (int)LinePos, baseUri == null ? null : baseUri.ToString())); } + [DoesNotReturn] private void Throw(string res, string arg, int lineNo, int linePos) { - Uri baseUri = _readerAdapter.BaseUri; + Uri? baseUri = _readerAdapter.BaseUri; _readerAdapter.Throw(new XmlException(res, arg, (int)lineNo, (int)linePos, baseUri == null ? null : baseUri.ToString())); } @@ -3542,7 +3548,7 @@ namespace System.Xml ThrowUnexpectedToken(pos, expectedToken, null); } - private void ThrowUnexpectedToken(int pos, string expectedToken1, string expectedToken2) + private void ThrowUnexpectedToken(int pos, string expectedToken1, string? expectedToken2) { string unexpectedToken = ParseUnexpectedToken(pos); if (expectedToken2 != null) @@ -3604,7 +3610,7 @@ namespace System.Xml } int startPos = 0; - StringBuilder norValue = null; + StringBuilder? norValue = null; while (value[startPos] == 0x20) { 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 7c538e3..c4ca280 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Xml.Schema { using System; @@ -15,7 +16,7 @@ namespace System.Xml.Schema internal sealed partial class Parser { - public async Task StartParsingAsync(XmlReader reader, string targetNamespace) + public async Task StartParsingAsync(XmlReader reader, string? targetNamespace) { _reader = reader; _positionInfo = PositionInfo.GetPositionInfo(reader); @@ -44,7 +45,7 @@ namespace System.Xml.Schema if (_schemaType == SchemaType.XSD) { _schema = new XmlSchema(); - _schema.BaseUri = new Uri(reader.BaseURI, UriKind.RelativeOrAbsolute); + _schema.BaseUri = new Uri(reader.BaseURI!, UriKind.RelativeOrAbsolute); _builder = new XsdBuilder(reader, _namespaceManager, _schema, _nameTable, _schemaNames, _eventHandler); } else 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 779da3b..e16ab7c 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Xml.Schema { internal abstract class SchemaBuilder 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 5b8e1eb..4277771 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Xml.Schema { using System.Collections.Generic; @@ -19,20 +20,20 @@ namespace System.Xml.Schema }; protected XmlQualifiedName name = XmlQualifiedName.Empty; - protected string prefix; + protected string? prefix; protected bool isDeclaredInExternal = false; protected Use presence; // the presence, such as fixed, implied, etc - protected XmlSchemaType schemaType; - protected XmlSchemaDatatype datatype; + protected XmlSchemaType? schemaType; + protected XmlSchemaDatatype datatype = null!; - protected string defaultValueRaw; // default value in its original form - protected object defaultValueTyped; + protected string? defaultValueRaw; // default value in its original form + protected object? defaultValueTyped; protected long maxLength; // dt:maxLength protected long minLength; // dt:minLength - protected List values; // array of values for enumerated and notation types + protected List values = null!; // array of values for enumerated and notation types protected SchemaDeclBase(XmlQualifiedName name, string prefix) { @@ -82,7 +83,7 @@ namespace System.Xml.Schema set { minLength = value; } } - internal XmlSchemaType SchemaType + internal XmlSchemaType? SchemaType { get { return schemaType; } set { schemaType = value; } @@ -115,7 +116,7 @@ namespace System.Xml.Schema set { defaultValueRaw = value; } } - internal object DefaultValueTyped + internal object? DefaultValueTyped { get { return defaultValueTyped; } set { defaultValueTyped = value; } @@ -123,7 +124,7 @@ namespace System.Xml.Schema internal bool CheckEnumeration(object pVal) { - return (datatype.TokenizedType != XmlTokenizedType.NOTATION && datatype.TokenizedType != XmlTokenizedType.ENUMERATION) || values.Contains(pVal.ToString()); + return (datatype.TokenizedType != XmlTokenizedType.NOTATION && datatype.TokenizedType != XmlTokenizedType.ENUMERATION) || values.Contains(pVal.ToString()!); } internal bool CheckValue(object pVal) 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 093d1ae..7482d60 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Xml.Schema { using System; @@ -10,9 +11,9 @@ namespace System.Xml.Schema internal sealed class SchemaEntity : IDtdEntityInfo { private readonly XmlQualifiedName _qname; // Name of entity - private string _url; // Url for external entity (system id) - private string _pubid; // Pubid for external entity - private string _text; // Text for internal entity + private string? _url; // Url for external entity (system id) + private string? _pubid; // Pubid for external entity + private string? _text; // Text for internal entity private XmlQualifiedName _ndata = XmlQualifiedName.Empty; // NDATA identifier private int _lineNumber; // line number private int _linePosition; // character position @@ -20,8 +21,8 @@ namespace System.Xml.Schema private bool _isExternal; // external entity flag private bool _parsingInProgress; // whether entity is being parsed (DtdParser infinite recursion check) private bool _isDeclaredInExternal; // declared in external markup or not - private string _baseURI; - private string _declaredURI; + private string? _baseURI; + private string? _declaredURI; // // Constructor @@ -72,17 +73,17 @@ namespace System.Xml.Schema get { return this.DeclaredURI; } } - string IDtdEntityInfo.SystemId + string? IDtdEntityInfo.SystemId { get { return this.Url; } } - string IDtdEntityInfo.PublicId + string? IDtdEntityInfo.PublicId { get { return this.Pubid; } } - string IDtdEntityInfo.Text + string? IDtdEntityInfo.Text { get { return ((SchemaEntity)this).Text; } } @@ -116,13 +117,13 @@ namespace System.Xml.Schema get { return _qname; } } - internal string Url + internal string? Url { get { return _url; } set { _url = value; _isExternal = true; } } - internal string Pubid + internal string? Pubid { get { return _pubid; } set { _pubid = value; } @@ -146,7 +147,7 @@ namespace System.Xml.Schema set { _ndata = value; } } - internal string Text + internal string? Text { get { return _text; } set { _text = value; _isExternal = false; } 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 fc4f7b8..8d3219f 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Xml.Schema { using System; @@ -18,7 +19,7 @@ namespace System.Xml.Schema _node = node; } - public override string LookupNamespace(string prefix) + public override string? LookupNamespace(string prefix) { if (prefix == "xml") { //Special case for the XML namespace @@ -30,7 +31,7 @@ namespace System.Xml.Schema namespaces = current.Namespaces.Namespaces; if (namespaces != null && namespaces.Count > 0) { - string uri; + string? uri; if (namespaces.TryGetValue(prefix, out uri)) return uri; } @@ -38,7 +39,7 @@ namespace System.Xml.Schema return prefix.Length == 0 ? string.Empty : null; } - public override string LookupPrefix(string ns) + public override string? LookupPrefix(string ns) { if (ns == XmlReservedNs.NsXml) { //Special case for the XML namespace 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 c39ad2f..27fe3ac 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Xml.Schema { using System; @@ -13,8 +14,8 @@ namespace System.Xml.Schema internal const int PUBLIC = 1; private readonly XmlQualifiedName _name; - private string _systemLiteral; // System literal - private string _pubid; // pubid literal + private string? _systemLiteral; // System literal + private string? _pubid; // pubid literal internal SchemaNotation(XmlQualifiedName name) { @@ -26,13 +27,13 @@ namespace System.Xml.Schema get { return _name; } } - internal string SystemLiteral + internal string? SystemLiteral { get { return _systemLiteral; } set { _systemLiteral = value; } } - internal string Pubid + internal string? Pubid { get { return _pubid; } set { _pubid = value; } 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 9faac99..bfc70b8 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#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 7670bfa..101cdc2 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#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 668511d..897f3a2 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 @@ -2,7 +2,8 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Xml.Schema { - public delegate void ValidationEventHandler(object sender, ValidationEventArgs e); + 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 0c487fc..a7a8f71 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Xml.Schema { using System; @@ -31,11 +32,11 @@ namespace System.Xml.Schema public bool ValidationSkipped; public XmlSchemaContentProcessing ProcessContents; public XmlSchemaValidity Validity; - public SchemaElementDecl ElementDecl; // ElementDecl - public SchemaElementDecl ElementDeclBeforeXsi; //elementDecl before its changed by that of xsi:type's - public string LocalName; - public string Namespace; - public ConstraintStruct[] Constr; + public SchemaElementDecl? ElementDecl; // ElementDecl + public SchemaElementDecl? ElementDeclBeforeXsi; //elementDecl before its changed by that of xsi:type's + public string? LocalName; + public string? Namespace; + public ConstraintStruct[]? Constr; public StateUnion CurrentState; @@ -46,10 +47,10 @@ namespace System.Xml.Schema public BitSet[] CurPos = new BitSet[2]; //For all - public BitSet AllElementsSet; + public BitSet? AllElementsSet; //For MinMaxNFA - public List RunningPositions; + public List? RunningPositions; public bool TooComplex; }; } 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 6fc8562..6f2b469 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#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 dbb6995..6836b07 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Xml.Schema { using System.Collections; @@ -9,33 +10,33 @@ namespace System.Xml.Schema public class XmlSchemaAnnotated : XmlSchemaObject { - private string _id; - private XmlSchemaAnnotation _annotation; - private XmlAttribute[] _moreAttributes; + private string? _id; + private XmlSchemaAnnotation? _annotation; + private XmlAttribute[]? _moreAttributes; [XmlAttribute("id", DataType = "ID")] - public string Id + public string? Id { get { return _id; } set { _id = value; } } [XmlElement("annotation", typeof(XmlSchemaAnnotation))] - public XmlSchemaAnnotation Annotation + public XmlSchemaAnnotation? Annotation { get { return _annotation; } set { _annotation = value; } } [XmlAnyAttribute] - public XmlAttribute[] UnhandledAttributes + public XmlAttribute[]? UnhandledAttributes { get { return _moreAttributes; } set { _moreAttributes = value; } } [XmlIgnore] - internal override string IdAttribute + internal override string? IdAttribute { get { return Id; } set { Id = value; } 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 c13b3e9..9f28818 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Xml.Schema { using System.Collections; @@ -9,12 +10,12 @@ namespace System.Xml.Schema public class XmlSchemaAnnotation : XmlSchemaObject { - private string _id; + private string? _id; private readonly XmlSchemaObjectCollection _items = new XmlSchemaObjectCollection(); - private XmlAttribute[] _moreAttributes; + private XmlAttribute[]? _moreAttributes; [XmlAttribute("id", DataType = "ID")] - public string Id + public string? Id { get { return _id; } set { _id = value; } @@ -28,14 +29,14 @@ namespace System.Xml.Schema } [XmlAnyAttribute] - public XmlAttribute[] UnhandledAttributes + public XmlAttribute[]? UnhandledAttributes { get { return _moreAttributes; } set { _moreAttributes = value; } } [XmlIgnore] - internal override string IdAttribute + internal override string? IdAttribute { get { return Id; } set { Id = value; } 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 f9aefc6..d8dec83 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Xml.Schema { using System.ComponentModel; @@ -10,12 +11,12 @@ namespace System.Xml.Schema public class XmlSchemaAny : XmlSchemaParticle { - private string _ns; + private string? _ns; private XmlSchemaContentProcessing _processContents = XmlSchemaContentProcessing.None; - private NamespaceList _namespaceList; + private NamespaceList? _namespaceList; [XmlAttribute("namespace")] - public string Namespace + public string? Namespace { get { return _ns; } set { _ns = value; } @@ -29,7 +30,7 @@ namespace System.Xml.Schema } [XmlIgnore] - internal NamespaceList NamespaceList + internal NamespaceList? NamespaceList { get { return _namespaceList; } } @@ -57,7 +58,7 @@ namespace System.Xml.Schema { get { - switch (_namespaceList.Type) + switch (_namespaceList!.Type) { case NamespaceList.ListType.Any: return "##any:*"; @@ -68,7 +69,7 @@ namespace System.Xml.Schema case NamespaceList.ListType.Set: StringBuilder sb = new StringBuilder(); int i = 1; - foreach (string wildcardNS in _namespaceList.Enumerate) + foreach (string? wildcardNS in _namespaceList.Enumerate) { sb.Append(wildcardNS + ":*"); if (i < _namespaceList.Enumerate.Count) @@ -111,7 +112,7 @@ namespace System.Xml.Schema internal bool Allows(XmlQualifiedName qname) { - return _namespaceList.Allows(qname.Namespace); + return _namespaceList!.Allows(qname.Namespace); } } } 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 5601809..ad66699 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Xml.Schema { using System.Collections; @@ -10,12 +11,12 @@ namespace System.Xml.Schema public class XmlSchemaAnyAttribute : XmlSchemaAnnotated { - private string _ns; + private string? _ns; private XmlSchemaContentProcessing _processContents = XmlSchemaContentProcessing.None; - private NamespaceList _namespaceList; + private NamespaceList? _namespaceList; [XmlAttribute("namespace")] - public string Namespace + public string? Namespace { get { return _ns ?? NamespaceList?.ToString(); } set { _ns = value; } @@ -30,7 +31,7 @@ namespace System.Xml.Schema [XmlIgnore] - internal NamespaceList NamespaceList + internal NamespaceList? NamespaceList { get { return _namespaceList; } } @@ -67,7 +68,7 @@ namespace System.Xml.Schema internal bool Allows(XmlQualifiedName qname) { - return _namespaceList.Allows(qname.Namespace); + return _namespaceList!.Allows(qname.Namespace); } internal static bool IsSubset(XmlSchemaAnyAttribute sub, XmlSchemaAnyAttribute super) @@ -75,7 +76,7 @@ namespace System.Xml.Schema return NamespaceList.IsSubset(sub.NamespaceList, super.NamespaceList); } - internal static XmlSchemaAnyAttribute Intersection(XmlSchemaAnyAttribute o1, XmlSchemaAnyAttribute o2, bool v1Compat) + internal static XmlSchemaAnyAttribute? Intersection(XmlSchemaAnyAttribute o1, XmlSchemaAnyAttribute o2, bool v1Compat) { NamespaceList nsl = NamespaceList.Intersection(o1.NamespaceList, o2.NamespaceList, v1Compat); if (nsl != null) @@ -93,7 +94,7 @@ namespace System.Xml.Schema } } - internal static XmlSchemaAnyAttribute Union(XmlSchemaAnyAttribute o1, XmlSchemaAnyAttribute o2, bool v1Compat) + internal static XmlSchemaAnyAttribute? Union(XmlSchemaAnyAttribute o1, XmlSchemaAnyAttribute o2, bool v1Compat) { NamespaceList nsl = NamespaceList.Union(o1.NamespaceList, o2.NamespaceList, v1Compat); if (nsl != null) 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 397d1e6..1d58c5c 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Xml.Schema { using System.Collections; @@ -9,18 +10,18 @@ namespace System.Xml.Schema public class XmlSchemaAppInfo : XmlSchemaObject { - private string _source; - private XmlNode[] _markup; + private string? _source; + private XmlNode[]? _markup; [XmlAttribute("source", DataType = "anyURI")] - public string Source + public string? Source { get { return _source; } set { _source = value; } } [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 0317d68..67d99a7 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Collections; using System.ComponentModel; using System.Xml.Serialization; @@ -10,9 +11,9 @@ namespace System.Xml.Schema { public class XmlSchemaAttribute : XmlSchemaAnnotated { - private string _defaultValue; - private string _fixedValue; - private string _name; + private string? _defaultValue; + private string? _fixedValue; + private string? _name; private XmlSchemaForm _form = XmlSchemaForm.None; private XmlSchemaUse _use = XmlSchemaUse.None; @@ -21,14 +22,14 @@ namespace System.Xml.Schema private XmlQualifiedName _typeName = XmlQualifiedName.Empty; private XmlQualifiedName _qualifiedName = XmlQualifiedName.Empty; - private XmlSchemaSimpleType _type; - private XmlSchemaSimpleType _attributeType; + private XmlSchemaSimpleType? _type; + private XmlSchemaSimpleType? _attributeType; - private SchemaAttDef _attDef; + private SchemaAttDef? _attDef; [XmlAttribute("default")] [DefaultValue(null)] - public string DefaultValue + public string? DefaultValue { get { return _defaultValue; } set { _defaultValue = value; } @@ -36,7 +37,7 @@ namespace System.Xml.Schema [XmlAttribute("fixed")] [DefaultValue(null)] - public string FixedValue + public string? FixedValue { get { return _fixedValue; } set { _fixedValue = value; } @@ -50,7 +51,7 @@ namespace System.Xml.Schema } [XmlAttribute("name")] - public string Name + public string? Name { get { return _name; } set { _name = value; } @@ -71,7 +72,7 @@ namespace System.Xml.Schema } [XmlElement("simpleType")] - public XmlSchemaSimpleType SchemaType + public XmlSchemaSimpleType? SchemaType { get { return _type; } set { _type = value; } @@ -92,7 +93,7 @@ namespace System.Xml.Schema [XmlIgnore] [Obsolete("This property has been deprecated. Please use AttributeSchemaType property that returns a strongly typed attribute type. https://go.microsoft.com/fwlink/?linkid=14202")] - public object AttributeType + public object? AttributeType { get { @@ -108,12 +109,12 @@ namespace System.Xml.Schema } [XmlIgnore] - public XmlSchemaSimpleType AttributeSchemaType + public XmlSchemaSimpleType? AttributeSchemaType { get { return _attributeType; } } - internal XmlReader Validate(XmlReader reader, XmlResolver resolver, XmlSchemaSet schemaSet, ValidationEventHandler valEventHandler) + internal XmlReader? Validate(XmlReader reader, XmlResolver resolver, XmlSchemaSet schemaSet, ValidationEventHandler valEventHandler) { if (schemaSet != null) { @@ -127,7 +128,7 @@ namespace System.Xml.Schema } [XmlIgnore] - internal XmlSchemaDatatype Datatype + internal XmlSchemaDatatype? Datatype { get { @@ -149,7 +150,7 @@ namespace System.Xml.Schema _attributeType = value; } - internal SchemaAttDef AttDef + internal SchemaAttDef? AttDef { get { return _attDef; } set { _attDef = value; } @@ -161,7 +162,7 @@ namespace System.Xml.Schema } [XmlIgnore] - internal override string NameAttribute + internal override string? NameAttribute { get { return Name; } set { Name = value; } 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 694c5b7..98654b5 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Xml.Schema { using System.Collections; @@ -9,17 +10,17 @@ namespace System.Xml.Schema public class XmlSchemaAttributeGroup : XmlSchemaAnnotated { - private string _name; + private string? _name; private XmlSchemaObjectCollection _attributes = new XmlSchemaObjectCollection(); - private XmlSchemaAnyAttribute _anyAttribute; + private XmlSchemaAnyAttribute? _anyAttribute; private XmlQualifiedName _qname = XmlQualifiedName.Empty; - private XmlSchemaAttributeGroup _redefined; - private XmlSchemaObjectTable _attributeUses; - private XmlSchemaAnyAttribute _attributeWildcard; + private XmlSchemaAttributeGroup? _redefined; + private XmlSchemaObjectTable? _attributeUses; + private XmlSchemaAnyAttribute? _attributeWildcard; private int _selfReferenceCount; [XmlAttribute("name")] - public string Name + public string? Name { get { return _name; } set { _name = value; } @@ -33,7 +34,7 @@ namespace System.Xml.Schema } [XmlElement("anyAttribute")] - public XmlSchemaAnyAttribute AnyAttribute + public XmlSchemaAnyAttribute? AnyAttribute { get { return _anyAttribute; } set { _anyAttribute = value; } @@ -59,20 +60,20 @@ namespace System.Xml.Schema } [XmlIgnore] - internal XmlSchemaAnyAttribute AttributeWildcard + internal XmlSchemaAnyAttribute? AttributeWildcard { get { return _attributeWildcard; } set { _attributeWildcard = value; } } [XmlIgnore] - public XmlSchemaAttributeGroup RedefinedAttributeGroup + public XmlSchemaAttributeGroup? RedefinedAttributeGroup { get { return _redefined; } } [XmlIgnore] - internal XmlSchemaAttributeGroup Redefined + internal XmlSchemaAttributeGroup? Redefined { get { return _redefined; } set { _redefined = value; } @@ -86,7 +87,7 @@ namespace System.Xml.Schema } [XmlIgnore] - internal override string NameAttribute + internal override string? NameAttribute { get { return Name; } set { Name = value; } 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 1771aed..7472cf6 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 @@ -2,9 +2,11 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Xml.Schema { using System.Collections; + using System.Diagnostics.CodeAnalysis; using System.Xml.Serialization; public class XmlSchemaAttributeGroupRef : XmlSchemaAnnotated @@ -12,6 +14,7 @@ namespace System.Xml.Schema private XmlQualifiedName _refName = XmlQualifiedName.Empty; [XmlAttribute("ref")] + [AllowNull] public XmlQualifiedName RefName { get { return _refName; } 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 edd5d0c..d19667b 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Xml.Schema { using System.Collections; 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 f6b2b27..6b8c9c3 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#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 6cd9ca5..43b74d7 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 @@ -2,13 +2,14 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Xml.Schema { using System.Xml.Serialization; public class XmlSchemaComplexContent : XmlSchemaContentModel { - private XmlSchemaContent _content; + private XmlSchemaContent? _content; private bool _isMixed; private bool _hasMixedAttribute; @@ -21,7 +22,7 @@ namespace System.Xml.Schema [XmlElement("restriction", typeof(XmlSchemaComplexContentRestriction)), XmlElement("extension", typeof(XmlSchemaComplexContentExtension))] - public override XmlSchemaContent Content + public override XmlSchemaContent? Content { get { return _content; } set { _content = value; } 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 e769cff..b8696aa 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Xml.Schema { using System.Collections; @@ -9,9 +10,9 @@ namespace System.Xml.Schema public class XmlSchemaComplexContentExtension : XmlSchemaContent { - private XmlSchemaParticle _particle; - private XmlSchemaObjectCollection _attributes = new XmlSchemaObjectCollection(); - private XmlSchemaAnyAttribute _anyAttribute; + private XmlSchemaParticle? _particle; + private XmlSchemaObjectCollection? _attributes = new XmlSchemaObjectCollection(); + private XmlSchemaAnyAttribute? _anyAttribute; private XmlQualifiedName _baseTypeName = XmlQualifiedName.Empty; [XmlAttribute("base")] @@ -25,7 +26,7 @@ namespace System.Xml.Schema XmlElement("choice", typeof(XmlSchemaChoice)), XmlElement("all", typeof(XmlSchemaAll)), XmlElement("sequence", typeof(XmlSchemaSequence))] - public XmlSchemaParticle Particle + public XmlSchemaParticle? Particle { get { return _particle; } set { _particle = value; } @@ -33,14 +34,14 @@ namespace System.Xml.Schema [XmlElement("attribute", typeof(XmlSchemaAttribute)), XmlElement("attributeGroup", typeof(XmlSchemaAttributeGroupRef))] - public XmlSchemaObjectCollection Attributes + public XmlSchemaObjectCollection? Attributes { get { return _attributes; } } [XmlElement("anyAttribute")] - public XmlSchemaAnyAttribute AnyAttribute + public XmlSchemaAnyAttribute? AnyAttribute { get { return _anyAttribute; } set { _anyAttribute = value; } 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 17db034..489b180 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Xml.Schema { using System.Collections; @@ -9,9 +10,9 @@ namespace System.Xml.Schema public class XmlSchemaComplexContentRestriction : XmlSchemaContent { - private XmlSchemaParticle _particle; - private XmlSchemaObjectCollection _attributes = new XmlSchemaObjectCollection(); - private XmlSchemaAnyAttribute _anyAttribute; + private XmlSchemaParticle? _particle; + private XmlSchemaObjectCollection? _attributes = new XmlSchemaObjectCollection(); + private XmlSchemaAnyAttribute? _anyAttribute; private XmlQualifiedName _baseTypeName = XmlQualifiedName.Empty; [XmlAttribute("base")] @@ -25,7 +26,7 @@ namespace System.Xml.Schema XmlElement("choice", typeof(XmlSchemaChoice)), XmlElement("all", typeof(XmlSchemaAll)), XmlElement("sequence", typeof(XmlSchemaSequence))] - public XmlSchemaParticle Particle + public XmlSchemaParticle? Particle { get { return _particle; } set { _particle = value; } @@ -33,13 +34,13 @@ namespace System.Xml.Schema [XmlElement("attribute", typeof(XmlSchemaAttribute)), XmlElement("attributeGroup", typeof(XmlSchemaAttributeGroupRef))] - public XmlSchemaObjectCollection Attributes + public XmlSchemaObjectCollection? Attributes { get { return _attributes; } } [XmlElement("anyAttribute")] - public XmlSchemaAnyAttribute AnyAttribute + public XmlSchemaAnyAttribute? AnyAttribute { get { return _anyAttribute; } set { _anyAttribute = value; } 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 77aff53..dd0822b 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#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 53a70e4..d2585b9 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Xml.Schema { using System.Xml.Serialization; @@ -9,6 +10,6 @@ namespace System.Xml.Schema public abstract class XmlSchemaContentModel : XmlSchemaAnnotated { [XmlIgnore] - public abstract XmlSchemaContent Content { get; set; } + public abstract XmlSchemaContent? Content { get; set; } } } 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 abfc2de..c7debfc 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#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 a0cccc6..ff0989a 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#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 11df3ee..665d3c8 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Collections; using System.Diagnostics; using System.ComponentModel; @@ -18,7 +19,7 @@ namespace System.Xml.Schema public abstract XmlTokenizedType TokenizedType { get; } - public abstract object ParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr); + public abstract object ParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr); public virtual XmlSchemaDatatypeVariety Variety { get { return XmlSchemaDatatypeVariety.Atomic; } } @@ -67,15 +68,15 @@ namespace System.Xml.Schema internal abstract XmlValueConverter ValueConverter { get; } - internal abstract RestrictionFacets Restriction { get; set; } + internal abstract RestrictionFacets? Restriction { get; set; } internal abstract int Compare(object value1, object value2); - internal abstract object ParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr, bool createAtomicValue); + internal abstract object ParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr, bool createAtomicValue); - internal abstract Exception TryParseValue(string s, XmlNameTable nameTable, IXmlNamespaceResolver nsmgr, out object typedValue); + internal abstract Exception? TryParseValue(string s, XmlNameTable? nameTable, IXmlNamespaceResolver? nsmgr, out object? typedValue); - internal abstract Exception TryParseValue(object value, XmlNameTable nameTable, IXmlNamespaceResolver namespaceResolver, out object typedValue); + internal abstract Exception? TryParseValue(object value, XmlNameTable? nameTable, IXmlNamespaceResolver? namespaceResolver, out object? typedValue); internal abstract FacetsChecker FacetsChecker { get; } @@ -188,11 +189,11 @@ namespace System.Xml.Schema if (t == typeof(IEnumerable) && t != typeof(string)) { StringBuilder bldr = new StringBuilder(); - IEnumerator enumerator = (value as IEnumerable).GetEnumerator(); + IEnumerator enumerator = (value as IEnumerable)!.GetEnumerator(); if (enumerator.MoveNext()) { bldr.Append('{'); - object cur = enumerator.Current; + object cur = enumerator.Current!; if (cur is IFormattable) { bldr.Append(((IFormattable)cur).ToString("", CultureInfo.InvariantCulture)); @@ -204,7 +205,7 @@ namespace System.Xml.Schema while (enumerator.MoveNext()) { bldr.Append(" , "); - cur = enumerator.Current; + cur = enumerator.Current!; if (cur is IFormattable) { bldr.Append(((IFormattable)cur).ToString("", CultureInfo.InvariantCulture)); @@ -224,22 +225,22 @@ namespace System.Xml.Schema } else { - stringValue = value.ToString(); + stringValue = value.ToString()!; } return stringValue; } - internal static XmlSchemaDatatype FromXmlTokenizedType(XmlTokenizedType token) + internal static XmlSchemaDatatype? FromXmlTokenizedType(XmlTokenizedType token) { return DatatypeImplementation.FromXmlTokenizedType(token); } - internal static XmlSchemaDatatype FromXmlTokenizedTypeXsd(XmlTokenizedType token) + internal static XmlSchemaDatatype? FromXmlTokenizedTypeXsd(XmlTokenizedType token) { return DatatypeImplementation.FromXmlTokenizedTypeXsd(token); } - internal static XmlSchemaDatatype FromXdrName(string name) + internal static XmlSchemaDatatype? FromXdrName(string name) { return DatatypeImplementation.FromXdrName(name); } 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 7bd6968..f25ed70 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 @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#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 8c72cdb..25382a9 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 @@ -2,35 +2,38 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Xml.Schema { using System.Collections; using System.ComponentModel; + using System.Diagnostics.CodeAnalysis; using System.Xml.Serialization; public class XmlSchemaDocumentation : XmlSchemaObject { - private string _source; - private string _language; - private XmlNode[] _markup; + private string? _source; + private string? _language; + private XmlNode[]? _markup; private static readonly XmlSchemaSimpleType s_languageType = DatatypeImplementation.GetSimpleTypeFromXsdType(new XmlQualifiedName("language", XmlReservedNs.NsXs)); [XmlAttribute("source", DataType = "anyURI")] - public string Source + public string? Source { get { return _source; } set { _source = value; } } [XmlAttribute("xml:lang")] - public string Language + [DisallowNull] + public string? Language { get { return _language; } - set { _language = (string)s_languageType.Datatype.ParseValue(value, (XmlNameTable)null, (IXmlNamespaceResolver)null); } + set { _language = (string)s_languageType.Datatype!.ParseValue(value, (XmlNameTable?)null, (IXmlNamespaceResolver?)null); } } [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/XmlSchemaType.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaType.cs index c70077e..7a137d0 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 @@ -308,7 +308,7 @@ namespace System.Xml.Schema return true; } - if ((except & derivedType.DerivedBy) != 0 || !dt.Datatype!.IsDerivedFrom(bt.Datatype)) + if ((except & derivedType.DerivedBy) != 0 || !dt.Datatype!.IsDerivedFrom(bt.Datatype!)) { return false; } 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 e751bc1..22cec5d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/ValidateNames.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/ValidateNames.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.Xml.XPath; using System.Diagnostics; @@ -328,7 +329,7 @@ namespace System.Xml /// If the NameTest contains a star, null values for localName (case NCName':*'), or for /// both localName and prefix (case '*') are returned. /// - internal static void ParseNameTestThrow(string s, out string prefix, out string localName) + internal static void ParseNameTestThrow(string s, out string? prefix, out string? localName) { int len, lenLocal, offset; 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 16af340..66a7d4e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlCharType.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlCharType.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Diagnostics; using System.IO; using System.Threading; @@ -44,7 +45,7 @@ namespace System.Xml private const uint CharPropertiesSize = (uint)char.MaxValue + 1; // static lock for XmlCharType class - private static object s_Lock; + private static object? s_Lock; private static object StaticLock { @@ -53,8 +54,9 @@ namespace System.Xml if (s_Lock == null) { object o = new object(); - Interlocked.CompareExchange(ref s_Lock, o, null); + Interlocked.CompareExchange(ref s_Lock, o, null); } + return s_Lock; } } @@ -70,7 +72,7 @@ namespace System.Xml return; } - UnmanagedMemoryStream memStream = (UnmanagedMemoryStream)typeof(XmlWriter).Assembly.GetManifestResourceStream("XmlCharType.bin"); + UnmanagedMemoryStream memStream = (UnmanagedMemoryStream)typeof(XmlWriter).Assembly.GetManifestResourceStream("XmlCharType.bin")!; Debug.Assert(memStream.Length == CharPropertiesSize); byte* chProps = memStream.PositionPointer; 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 d3aaf4f..4e2987b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlComplianceUtil.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlComplianceUtil.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System; using System.IO; @@ -23,7 +24,7 @@ namespace System.Xml } int startPos = 0; - StringBuilder norValue = null; + StringBuilder? norValue = null; XmlCharType xmlCharType = XmlCharType.Instance; while (xmlCharType.IsWhiteSpace(value[startPos])) { @@ -110,7 +111,7 @@ namespace System.Xml int i = 0; int startPos = 0; - StringBuilder norValue = null; + StringBuilder? norValue = null; while (i < len) { 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 8187578..c14b11b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlConvert.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlConvert.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Text; using System.Globalization; using System.Xml.Schema; @@ -48,7 +49,7 @@ namespace System.Xml /// DataColumn names, that contain characters that are not permitted in /// XML names to valid names. /// - public static string EncodeName(string name) + public static string? EncodeName(string? name) { return EncodeName(name, true/*Name_not_NmToken*/, false/*Local?*/); } @@ -57,7 +58,7 @@ namespace System.Xml /// Verifies the name is valid /// according to production [7] in the XML spec. /// - public static string EncodeNmToken(string name) + public static string? EncodeNmToken(string? name) { return EncodeName(name, false/*Name_not_NmToken*/, false/*Local?*/); } @@ -66,7 +67,7 @@ namespace System.Xml /// Converts names, such as DataTable or DataColumn names, that contain /// characters that are not permitted in XML names to valid names. /// - public static string EncodeLocalName(string name) + public static string? EncodeLocalName(string? name) { return EncodeName(name, true/*Name_not_NmToken*/, true/*Local?*/); } @@ -78,23 +79,24 @@ namespace System.Xml public static string DecodeName(string name) { - if (name == null || name.Length == 0) + if (string.IsNullOrEmpty(name)) return name; - StringBuilder bufBld = null; + StringBuilder? bufBld = null; int length = name.Length; int copyPosition = 0; int underscorePos = name.IndexOf('_'); - MatchCollection mc = null; - IEnumerator en = null; + MatchCollection? mc = null; + IEnumerator? en = null; if (underscorePos >= 0) { if (s_decodeCharPattern == null) { s_decodeCharPattern = new Regex("_[Xx]([0-9a-fA-F]{4}|[0-9a-fA-F]{8})_"); } + mc = s_decodeCharPattern.Matches(name, underscorePos); en = mc.GetEnumerator(); } @@ -105,7 +107,7 @@ namespace System.Xml int matchPos = -1; if (en != null && en.MoveNext()) { - Match m = (Match)en.Current; + Match m = (Match)en.Current!; matchPos = m.Index; } @@ -113,9 +115,9 @@ namespace System.Xml { if (position == matchPos) { - if (en.MoveNext()) + if (en!.MoveNext()) { - Match m = (Match)en.Current; + Match m = (Match)en.Current!; matchPos = m.Index; } @@ -177,33 +179,35 @@ namespace System.Xml { if (copyPosition < length) { - bufBld.Append(name, copyPosition, length - copyPosition); + bufBld!.Append(name, copyPosition, length - copyPosition); } - return bufBld.ToString(); + + return bufBld!.ToString(); } } - private static string EncodeName(string name, /*Name_not_NmToken*/ bool first, bool local) + private static string? EncodeName(string? name, /*Name_not_NmToken*/ bool first, bool local) { if (string.IsNullOrEmpty(name)) { return name; } - StringBuilder bufBld = null; + StringBuilder? bufBld = null; int length = name.Length; int copyPosition = 0; int position = 0; int underscorePos = name.IndexOf('_'); - MatchCollection mc = null; - IEnumerator en = null; + MatchCollection? mc = null; + IEnumerator? en = null; if (underscorePos >= 0) { if (s_encodeCharPattern == null) { s_encodeCharPattern = new Regex("(?<=_)[Xx]([0-9a-fA-F]{4}|[0-9a-fA-F]{8})_"); } + mc = s_encodeCharPattern.Matches(name, underscorePos); en = mc.GetEnumerator(); } @@ -211,9 +215,10 @@ namespace System.Xml int matchPos = -1; if (en != null && en.MoveNext()) { - Match m = (Match)en.Current; + Match m = (Match)en.Current!; matchPos = m.Index - 1; } + if (first) { if ((!s_xmlCharType.IsStartNCNameCharXml4e(name[0]) && (local || (!local && name[0] != ':'))) || @@ -223,6 +228,7 @@ namespace System.Xml { bufBld = new StringBuilder(length + 20); } + bufBld.Append("_x"); if (length > 1 && XmlCharType.IsHighSurrogate(name[0]) && XmlCharType.IsLowSurrogate(name[1])) { @@ -243,9 +249,9 @@ namespace System.Xml position++; if (matchPos == 0) - if (en.MoveNext()) + if (en!.MoveNext()) { - Match m = (Match)en.Current; + Match m = (Match)en.Current!; matchPos = m.Index - 1; } } @@ -261,9 +267,9 @@ namespace System.Xml bufBld = new StringBuilder(length + 20); } if (matchPos == position) - if (en.MoveNext()) + if (en!.MoveNext()) { - Match m = (Match)en.Current; + Match m = (Match)en.Current!; matchPos = m.Index - 1; } @@ -294,15 +300,16 @@ namespace System.Xml { if (copyPosition < length) { - bufBld.Append(name, copyPosition, length - copyPosition); + bufBld!.Append(name, copyPosition, length - copyPosition); } - return bufBld.ToString(); + + return bufBld!.ToString(); } } private const int EncodedCharLength = 7; // ("_xFFFF_".Length); - private static volatile Regex s_encodeCharPattern; - private static volatile Regex s_decodeCharPattern; + private static volatile Regex? s_encodeCharPattern; + private static volatile Regex? s_decodeCharPattern; private static int FromHex(char digit) { return (digit <= '9') @@ -324,6 +331,7 @@ namespace System.Xml { throw new ArgumentNullException(nameof(s)); } + return BinHexDecoder.Decode(s.ToCharArray(), allowOddCount); } @@ -333,6 +341,7 @@ namespace System.Xml { throw new ArgumentNullException(nameof(inArray)); } + return BinHexEncoder.Encode(inArray, 0, inArray.Length); } @@ -348,6 +357,7 @@ namespace System.Xml { throw new ArgumentNullException(nameof(name)); } + if (name.Length == 0) { throw new ArgumentNullException(nameof(name), SR.Xml_EmptyName); @@ -361,13 +371,14 @@ namespace System.Xml // did not parse to the end -> there is invalid character at endPos throw CreateInvalidNameCharException(name, endPos, ExceptionType.XmlException); } + return name; } - internal static Exception TryVerifyName(string name) + internal static Exception? TryVerifyName(string name) { - if (name == null || name.Length == 0) + if (string.IsNullOrEmpty(name)) { return new XmlException(SR.Xml_EmptyName, string.Empty); } @@ -377,12 +388,13 @@ namespace System.Xml { return new XmlException(endPos == 0 ? SR.Xml_BadStartNameChar : SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(name, endPos)); } + return null; } internal static string VerifyQName(string name, ExceptionType exceptionType) { - if (name == null || name.Length == 0) + if (string.IsNullOrEmpty(name)) { throw new ArgumentNullException(nameof(name)); } @@ -394,6 +406,7 @@ namespace System.Xml { throw CreateException(SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(name, endPos), exceptionType, 0, endPos + 1); } + return name; } @@ -412,6 +425,7 @@ namespace System.Xml { throw new ArgumentNullException(nameof(name)); } + if (name.Length == 0) { throw new ArgumentNullException(nameof(name), SR.Xml_EmptyLocalName); @@ -428,7 +442,7 @@ namespace System.Xml return name; } - internal static Exception TryVerifyNCName(string name) + internal static Exception? TryVerifyNCName(string name) { int len = ValidateNames.ParseNCName(name); @@ -436,6 +450,7 @@ namespace System.Xml { return ValidateNames.GetInvalidNameException(name, 0, len); } + return null; } @@ -443,12 +458,13 @@ namespace System.Xml /// /// /// - public static string VerifyTOKEN(string token) + public static string? VerifyTOKEN(string token) { - if (token == null || token.Length == 0) + if (string.IsNullOrEmpty(token)) { return token; } + if (token[0] == ' ' || token[token.Length - 1] == ' ' || token.IndexOfAny(crt) != -1 || token.IndexOf(" ", StringComparison.Ordinal) != -1) { throw new XmlException(SR.Sch_NotTokenString, token); @@ -456,16 +472,18 @@ namespace System.Xml return token; } - internal static Exception TryVerifyTOKEN(string token) + internal static Exception? TryVerifyTOKEN(string token) { if (token == null || token.Length == 0) { return null; } + if (token[0] == ' ' || token[token.Length - 1] == ' ' || token.IndexOfAny(crt) != -1 || token.IndexOf(" ", StringComparison.Ordinal) != -1) { return new XmlException(SR.Sch_NotTokenString, token); } + return null; } @@ -484,6 +502,7 @@ namespace System.Xml { throw new ArgumentNullException(nameof(name)); } + if (name.Length == 0) { throw CreateException(SR.Xml_InvalidNmToken, name, exceptionType); @@ -495,29 +514,33 @@ namespace System.Xml { throw CreateException(SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(name, endPos), exceptionType, 0, endPos + 1); } + return name; } - internal static Exception TryVerifyNMTOKEN(string name) + internal static Exception? TryVerifyNMTOKEN(string name) { if (name == null || name.Length == 0) { return new XmlException(SR.Xml_EmptyName, string.Empty); } + int endPos = ValidateNames.ParseNmtokenNoNamespaces(name, 0); if (endPos != name.Length) { return new XmlException(SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(name, endPos)); } + return null; } - internal static Exception TryVerifyNormalizedString(string str) + internal static Exception? TryVerifyNormalizedString(string str) { if (str.IndexOfAny(crt) != -1) { return new XmlSchemaException(SR.Sch_NotNormalizedString, str); } + return null; } @@ -529,6 +552,7 @@ namespace System.Xml { throw new ArgumentNullException(nameof(content)); } + VerifyCharData(content, ExceptionType.XmlException); return content; } @@ -567,6 +591,7 @@ namespace System.Xml { throw new XmlException(SR.Xml_InvalidWhitespaceCharacter, XmlException.BuildCharExceptionArgs(content, pos), 0, pos + 1); } + return content; } @@ -733,6 +758,7 @@ namespace System.Xml { return ("-0"); } + return value.ToString("R", NumberFormatInfo.InvariantInfo); } @@ -774,6 +800,7 @@ namespace System.Xml default: throw new ArgumentException(SR.Format(SR.Sch_InvalidDateTimeOption, dateTimeOption, nameof(dateTimeOption))); } + XsdDateTime xsdDateTime = new XsdDateTime(value, XsdDateTimeFlags.DateTime); return xsdDateTime.ToString(); } @@ -802,7 +829,7 @@ namespace System.Xml throw new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Boolean")); } - internal static Exception TryToBoolean(string s, out bool result) + internal static Exception? TryToBoolean(string s, out bool result) { s = TrimString(s); if (s == "0" || s == "false") @@ -815,6 +842,7 @@ namespace System.Xml result = true; return null; } + result = false; return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Boolean")); } @@ -825,19 +853,22 @@ namespace System.Xml { throw new ArgumentNullException(nameof(s)); } + if (s.Length != 1) { throw new FormatException(SR.XmlConvert_NotOneCharString); } + return s[0]; } - internal static Exception TryToChar(string s, out char result) + internal static Exception? TryToChar(string s, out char result) { if (!char.TryParse(s, out result)) { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Char")); } + return null; } @@ -846,12 +877,13 @@ namespace System.Xml return decimal.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } - internal static Exception TryToDecimal(string s, out decimal result) + internal static Exception? TryToDecimal(string s, out decimal result) { if (!decimal.TryParse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Decimal")); } + return null; } @@ -860,12 +892,13 @@ namespace System.Xml return decimal.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } - internal static Exception TryToInteger(string s, out decimal result) + internal static Exception? TryToInteger(string s, out decimal result) { if (!decimal.TryParse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Integer")); } + return null; } @@ -875,12 +908,13 @@ namespace System.Xml return sbyte.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } - internal static Exception TryToSByte(string s, out sbyte result) + internal static Exception? TryToSByte(string s, out sbyte result) { if (!sbyte.TryParse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "SByte")); } + return null; } @@ -889,12 +923,13 @@ namespace System.Xml return short.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } - internal static Exception TryToInt16(string s, out short result) + internal static Exception? TryToInt16(string s, out short result) { if (!short.TryParse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Int16")); } + return null; } @@ -903,12 +938,13 @@ namespace System.Xml return int.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } - internal static Exception TryToInt32(string s, out int result) + internal static Exception? TryToInt32(string s, out int result) { if (!int.TryParse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Int32")); } + return null; } @@ -917,12 +953,13 @@ namespace System.Xml return long.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } - internal static Exception TryToInt64(string s, out long result) + internal static Exception? TryToInt64(string s, out long result) { if (!long.TryParse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Int64")); } + return null; } @@ -931,12 +968,13 @@ namespace System.Xml return byte.Parse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } - internal static Exception TryToByte(string s, out byte result) + internal static Exception? TryToByte(string s, out byte result) { if (!byte.TryParse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Byte")); } + return null; } @@ -946,12 +984,13 @@ namespace System.Xml return ushort.Parse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } - internal static Exception TryToUInt16(string s, out ushort result) + internal static Exception? TryToUInt16(string s, out ushort result) { if (!ushort.TryParse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "UInt16")); } + return null; } @@ -961,13 +1000,13 @@ namespace System.Xml return uint.Parse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } - - internal static Exception TryToUInt32(string s, out uint result) + internal static Exception? TryToUInt32(string s, out uint result) { if (!uint.TryParse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "UInt32")); } + return null; } @@ -977,12 +1016,13 @@ namespace System.Xml return ulong.Parse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); } - internal static Exception TryToUInt64(string s, out ulong result) + internal static Exception? TryToUInt64(string s, out ulong result) { if (!ulong.TryParse(s, NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo, out result)) { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "UInt64")); } + return null; } @@ -996,10 +1036,11 @@ namespace System.Xml { return -0f; } + return f; } - internal static Exception TryToSingle(string s, out float result) + internal static Exception? TryToSingle(string s, out float result) { s = TrimString(s); if (s == "-INF") @@ -1016,10 +1057,12 @@ namespace System.Xml { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Single")); } + if (result == 0 && s[0] == '-') { result = -0f; } + return null; } @@ -1028,15 +1071,17 @@ namespace System.Xml s = TrimString(s); if (s == "-INF") return double.NegativeInfinity; if (s == "INF") return double.PositiveInfinity; + double dVal = double.Parse(s, NumberStyles.AllowLeadingSign | NumberStyles.AllowDecimalPoint | NumberStyles.AllowExponent | NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite, NumberFormatInfo.InvariantInfo); if (dVal == 0 && s[0] == '-') { return -0d; } + return dVal; } - internal static Exception TryToDouble(string s, out double result) + internal static Exception? TryToDouble(string s, out double result) { s = TrimString(s); if (s == "-INF") @@ -1053,17 +1098,18 @@ namespace System.Xml { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Double")); } + if (result == 0 && s[0] == '-') { result = -0d; } + return null; } internal static double ToXPathDouble(object o) { - string str = o as string; - if (str != null) + if (o is string str) { str = TrimString(str); if (str.Length != 0 && str[0] != '+') @@ -1076,14 +1122,17 @@ namespace System.Xml } return double.NaN; } - if (o is double) + + if (o is double oDouble) { - return (double)o; + return oDouble; } - if (o is bool) + + if (o is bool oBool) { - return ((bool)o) ? 1.0 : 0.0; + return oBool ? 1.0 : 0.0; } + try { return Convert.ToDouble(o, NumberFormatInfo.InvariantInfo); @@ -1095,13 +1144,13 @@ namespace System.Xml { } catch (ArgumentNullException) { } + return double.NaN; } - internal static string ToXPathString(object value) + internal static string? ToXPathString(object? value) { - string s = value as string; - if (s != null) + if (value is string s) { return s; } @@ -1145,10 +1194,10 @@ namespace System.Xml return timeSpan; } - internal static Exception TryToTimeSpan(string s, out TimeSpan result) + internal static Exception? TryToTimeSpan(string s, out TimeSpan result) { XsdDuration duration; - Exception exception; + Exception? exception; exception = XsdDuration.TryParse(s, out duration); if (exception != null) @@ -1163,7 +1212,7 @@ namespace System.Xml } // use AllDateTimeFormats property to access the formats - private static volatile string[] s_allDateTimeFormats; + private static volatile string[]? s_allDateTimeFormats; // NOTE: Do not use this property for reference comparison. It may not be unique. private static string[] AllDateTimeFormats @@ -1174,7 +1223,8 @@ namespace System.Xml { CreateAllDateTimeFormats(); } - return s_allDateTimeFormats; + + return s_allDateTimeFormats!; } } @@ -1290,9 +1340,9 @@ namespace System.Xml return new Guid(s); } - internal static Exception TryToGuid(string s, out Guid result) + internal static Exception? TryToGuid(string s, out Guid result) { - Exception exception = null; + Exception? exception = null; result = Guid.Empty; @@ -1308,6 +1358,7 @@ namespace System.Xml { exception = new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Guid")); } + return exception; } @@ -1329,25 +1380,28 @@ namespace System.Xml _ => value, }; - internal static Uri ToUri(string s) + internal static Uri ToUri(string? s) { - if (s != null && s.Length > 0) - { //string.Empty is a valid uri but not " " + if (!string.IsNullOrEmpty(s)) + { + // string.Empty is a valid uri but not " " s = TrimString(s); if (s.Length == 0 || s.IndexOf("##", StringComparison.Ordinal) != -1) { throw new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Uri")); } } - Uri uri; + + Uri? uri; if (!Uri.TryCreate(s, UriKind.RelativeOrAbsolute, out uri)) { throw new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Uri")); } + return uri; } - internal static Exception TryToUri(string s, out Uri result) + internal static Exception? TryToUri(string s, out Uri? result) { result = null; @@ -1363,22 +1417,26 @@ namespace System.Xml { return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Uri")); } + return null; } // Compares the given character interval and string and returns true if the characters are identical - internal static bool StrEqual(char[] chars, int strPos1, int strLen1, string str2) + internal static bool StrEqual(char[]? chars, int strPos1, int strLen1, string str2) { if (strLen1 != str2.Length) { return false; } + Debug.Assert(chars != null); + int i = 0; while (i < strLen1 && chars[strPos1 + i] == str2[i]) { i++; } + return i == strLen1; } @@ -1521,7 +1579,7 @@ namespace System.Xml internal static string EscapeValueForDebuggerDisplay(string value) { - StringBuilder sb = null; + StringBuilder? sb = null; int i = 0; int start = 0; while (i < value.Length) @@ -1559,14 +1617,17 @@ namespace System.Xml } i++; } + if (sb == null) { return value; } + if (i - start > 0) { sb.Append(value, start, i - start); } + return sb.ToString(); } @@ -1680,7 +1741,7 @@ namespace System.Xml return CreateException(index == 0 ? SR.Xml_BadStartNameChar : SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(name, index), exceptionType, 0, index + 1); } - internal static ArgumentException CreateInvalidNameArgumentException(string name, string argumentName) + internal static ArgumentException CreateInvalidNameArgumentException(string? name, string? argumentName) { return (name == null) ? new ArgumentNullException(argumentName) : new ArgumentException(SR.Xml_EmptyName, argumentName); } 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 51717e9..78fcdfc 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlEncoding.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlEncoding.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Text; using System.Diagnostics; @@ -29,7 +30,7 @@ namespace System.Xml int byteCount = count + ((_lastByte >= 0) ? 1 : 0); if (flush && (byteCount % CharSize != 0)) { - throw new ArgumentException(SR.Format(SR.Enc_InvalidByteInEncoding, -1), (string)null); + throw new ArgumentException(SR.Format(SR.Enc_InvalidByteInEncoding, -1), (string?)null); } return byteCount / CharSize; } @@ -85,6 +86,7 @@ namespace System.Xml { Buffer.BlockCopy(bytes, byteIndex, chars, charIndex * CharSize, byteCount); } + return charCount; } @@ -149,6 +151,7 @@ namespace System.Xml { Buffer.BlockCopy(bytes, byteIndex, chars, charIndex * CharSize, (int)(byteCount & ~0x1)); } + charsUsed += byteCount / CharSize; bytesUsed += byteCount; @@ -209,7 +212,7 @@ namespace System.Xml internal class Ucs4Encoding : Encoding { - internal Ucs4Decoder ucs4Decoder; + internal Ucs4Decoder ucs4Decoder = null!; // assigned in the derived classes public override string WebName { @@ -236,7 +239,7 @@ namespace System.Xml public override byte[] GetBytes(string s) { - return null; //ucs4Decoder.GetByteCount(chars, index, count); + return null!; //ucs4Decoder.GetByteCount(chars, index, count); } public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { @@ -277,7 +280,7 @@ namespace System.Xml public override Encoder GetEncoder() { - return null; + return null!; } internal static Encoding UCS4_Littleendian @@ -373,6 +376,7 @@ namespace System.Xml return "ucs-4 (order 2143)"; } } + public override byte[] GetPreamble() { return new byte[4] { 0x00, 0x00, 0xff, 0xfe }; @@ -429,11 +433,13 @@ namespace System.Xml byteIndex++; byteCount--; } + // still not enough bytes -> return if (lastBytesCount < 4) { return 0; } + // decode 1 character from the byte cache i = GetFullChars(lastBytes, 0, 4, chars, charIndex); Debug.Assert(i == 1); @@ -456,8 +462,10 @@ namespace System.Xml { lastBytes[j] = bytes[byteIndex + byteCount - bytesLeft + j]; } + lastBytesCount = bytesLeft; } + return i; } @@ -478,6 +486,7 @@ namespace System.Xml byteCount--; bytesUsed++; } + // still not enough bytes -> return if (lbc < 4) { @@ -485,6 +494,7 @@ namespace System.Xml completed = true; return; } + // decode 1 character from the byte cache i = GetFullChars(lastBytes, 0, 4, chars, charIndex); @@ -509,6 +519,7 @@ namespace System.Xml { completed = true; } + bytesUsed += byteCount; // decode block of byte quadruplets @@ -522,6 +533,7 @@ namespace System.Xml { lastBytes[j] = bytes[byteIndex + byteCount - bytesLeft + j]; } + lastBytesCount = bytesLeft; } } @@ -547,7 +559,7 @@ namespace System.Xml code = (uint)((bytes[i + 3] << 24) | (bytes[i + 2] << 16) | (bytes[i + 1] << 8) | bytes[i]); if (code > 0x10FFFF) { - throw new ArgumentException(SR.Format(SR.Enc_InvalidByteInEncoding, new object[1] { i }), (string)null); + throw new ArgumentException(SR.Format(SR.Enc_InvalidByteInEncoding, new object[1] { i }), (string?)null); } else if (code > 0xFFFF) { @@ -565,12 +577,14 @@ namespace System.Xml chars[j] = (char)code; } } + j++; i += 4; } + return j - charIndex; } - }; + } internal class Ucs4Decoder1234 : Ucs4Decoder { @@ -586,7 +600,7 @@ namespace System.Xml code = (uint)((bytes[i] << 24) | (bytes[i + 1] << 16) | (bytes[i + 2] << 8) | bytes[i + 3]); if (code > 0x10FFFF) { - throw new ArgumentException(SR.Format(SR.Enc_InvalidByteInEncoding, new object[1] { i }), (string)null); + throw new ArgumentException(SR.Format(SR.Enc_InvalidByteInEncoding, new object[1] { i }), (string?)null); } else if (code > 0xFFFF) { @@ -604,9 +618,11 @@ namespace System.Xml chars[j] = (char)code; } } + j++; i += 4; } + return j - charIndex; } } @@ -626,7 +642,7 @@ namespace System.Xml code = (uint)((bytes[i + 1] << 24) | (bytes[i] << 16) | (bytes[i + 3] << 8) | bytes[i + 2]); if (code > 0x10FFFF) { - throw new ArgumentException(SR.Format(SR.Enc_InvalidByteInEncoding, new object[1] { i }), (string)null); + throw new ArgumentException(SR.Format(SR.Enc_InvalidByteInEncoding, new object[1] { i }), (string?)null); } else if (code > 0xFFFF) { @@ -644,9 +660,11 @@ namespace System.Xml chars[j] = (char)code; } } + j++; i += 4; } + return j - charIndex; } } @@ -666,7 +684,7 @@ namespace System.Xml code = (uint)((bytes[i + 2] << 24) | (bytes[i + 3] << 16) | (bytes[i] << 8) | bytes[i + 1]); if (code > 0x10FFFF) { - throw new ArgumentException(SR.Format(SR.Enc_InvalidByteInEncoding, new object[1] { i }), (string)null); + throw new ArgumentException(SR.Format(SR.Enc_InvalidByteInEncoding, new object[1] { i }), (string?)null); } else if (code > 0xFFFF) { @@ -684,9 +702,11 @@ namespace System.Xml chars[j] = (char)code; } } + j++; i += 4; } + return j - charIndex; } } 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 e1ef27e..0ceaa97 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlNamespaceScope.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlNamespaceScope.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Xml { /// 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 89b802a..7833b47 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlNodeOrder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlNodeOrder.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#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 972ebd7..c7ef424 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlNodeType.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlNodeType.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#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 e1bc0fb..7904c94 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlNullResolver.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlNullResolver.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Net; namespace System.Xml @@ -13,7 +14,7 @@ namespace System.Xml // Private constructor ensures existing only one instance of XmlNullResolver private XmlNullResolver() { } - public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn) + public override object GetEntity(Uri absoluteUri, string? role, Type? ofObjectToReturn) { throw new XmlException(SR.Xml_NullResolver, string.Empty); } 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 ce05faa..774ac25 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlQualifiedName.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlQualifiedName.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Collections; using System.Diagnostics; @@ -29,15 +30,15 @@ namespace System.Xml /// /// [To be supplied.] /// - public XmlQualifiedName(string name) : this(name, string.Empty) { } + public XmlQualifiedName(string? name) : this(name, string.Empty) { } /// /// [To be supplied.] /// - public XmlQualifiedName(string name, string ns) + public XmlQualifiedName(string? name, string? ns) { - _ns = ns == null ? string.Empty : ns; - _name = name == null ? string.Empty : name; + _ns = ns ?? string.Empty; + _name = name ?? string.Empty; } /// @@ -87,41 +88,40 @@ namespace System.Xml /// /// [To be supplied.] /// - public override bool Equals(object other) + public override bool Equals(object? other) { - XmlQualifiedName qname; - if ((object)this == other) { return true; } - qname = other as XmlQualifiedName; + XmlQualifiedName? qname = other as XmlQualifiedName; if (qname != null) { return (Name == qname.Name && Namespace == qname.Namespace); } + return false; } /// /// [To be supplied.] /// - public static bool operator ==(XmlQualifiedName a, XmlQualifiedName b) + public static bool operator ==(XmlQualifiedName? a, XmlQualifiedName? b) { - if ((object)a == (object)b) + if ((object?)a == (object?)b) return true; - if ((object)a == null || (object)b == null) + if ((object?)a == null || (object?)b == null) return false; - return (a.Name == b.Name && a.Namespace == b.Namespace); + return a.Name == b.Name && a.Namespace == b.Namespace; } /// /// [To be supplied.] /// - public static bool operator !=(XmlQualifiedName a, XmlQualifiedName b) + public static bool operator !=(XmlQualifiedName? a, XmlQualifiedName? b) { return !(a == b); } @@ -135,18 +135,16 @@ namespace System.Xml } // --------- Some useful internal stuff ----------------- - internal void Init(string name, string ns) + internal void Init(string? name, string? ns) { - Debug.Assert(name != null && ns != null); - _name = name; - _ns = ns; + _name = name ?? string.Empty; + _ns = ns ?? string.Empty; _hash = 0; } - internal void SetNamespace(string ns) + internal void SetNamespace(string? ns) { - Debug.Assert(ns != null); - _ns = ns; //Not changing hash since ns is not used to compute hashcode + _ns = ns ?? string.Empty; // Not changing hash since ns is not used to compute hashcode } internal void Verify() @@ -170,7 +168,7 @@ namespace System.Xml string localName; ValidateNames.ParseQNameThrow(s, out prefix, out localName); - string uri = nsmgr.LookupNamespace(prefix); + string? uri = nsmgr.LookupNamespace(prefix); if (uri == null) { if (prefix.Length != 0) @@ -178,12 +176,15 @@ namespace System.Xml throw new XmlException(SR.Xml_UnknownNs, prefix); } else - { //Re-map namespace of empty prefix to string.Empty when there is no default namespace declared + { + // Re-map namespace of empty prefix to string.Empty when there is no default namespace declared uri = string.Empty; } } + return new XmlQualifiedName(localName, uri); } + internal XmlQualifiedName Clone() { return (XmlQualifiedName)MemberwiseClone(); 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 01015ca..c160a2e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlReservedNs.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlReservedNs.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#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 c54d7e6..2ee57eb 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlResolver.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlResolver.cs @@ -73,16 +73,18 @@ namespace System.Xml set { } } - public virtual bool SupportsType(Uri absoluteUri, Type type) + public virtual bool SupportsType(Uri absoluteUri, Type? type) { if (absoluteUri == null) { throw new ArgumentNullException(nameof(absoluteUri)); } + if (type == null || type == typeof(Stream)) { return true; } + return false; } } 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 8d6e124..77357f0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlResolverAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlResolverAsync.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Threading.Tasks; namespace System.Xml @@ -9,10 +10,10 @@ namespace System.Xml public abstract partial class XmlResolver { public virtual Task GetEntityAsync(Uri absoluteUri, - string role, + string? role, Type ofObjectToReturn) { throw new NotImplementedException(); } } -} \ No newline at end of file +} 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 74fc129..72779df 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlSecureResolver.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlSecureResolver.cs @@ -2,6 +2,7 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable namespace System.Xml { using System.Net; @@ -22,12 +23,12 @@ namespace System.Xml set { _resolver.Credentials = value; } } - public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn) + public override object? GetEntity(Uri absoluteUri, string? role, Type? ofObjectToReturn) { return _resolver.GetEntity(absoluteUri, role, ofObjectToReturn); } - public override Uri ResolveUri(Uri baseUri, string relativeUri) + public override Uri ResolveUri(Uri? baseUri, string? relativeUri) { return _resolver.ResolveUri(baseUri, relativeUri); } 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 187d331..e0d15bb 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlSecureResolverAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlSecureResolverAsync.cs @@ -2,13 +2,14 @@ // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. +#nullable enable using System.Threading.Tasks; namespace System.Xml { public partial class XmlSecureResolver : XmlResolver { - public override Task GetEntityAsync(Uri absoluteUri, string role, Type ofObjectToReturn) + public override Task GetEntityAsync(Uri absoluteUri, string? role, Type ofObjectToReturn) { return _resolver.GetEntityAsync(absoluteUri, role, ofObjectToReturn); } 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 290825d..df5f1bf 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/XmlUrlResolverAsync.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/XmlUrlResolverAsync.cs @@ -11,7 +11,7 @@ namespace System.Xml public partial class XmlUrlResolver : XmlResolver { // Maps a URI to an Object containing the actual resource. - public override async Task GetEntityAsync(Uri absoluteUri, string role, Type? ofObjectToReturn) + public override async Task GetEntityAsync(Uri absoluteUri, string? role, Type? ofObjectToReturn) { if (ofObjectToReturn == null || ofObjectToReturn == typeof(System.IO.Stream) || ofObjectToReturn == typeof(object)) {