// 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
// 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
// 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;
//
// Fields
//
- private byte[] _buffer;
+ private byte[]? _buffer;
private int _startIndex;
private int _curIndex;
private int _endIndex;
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);
}
{
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;
}
// 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;
{
internal abstract partial class Base64Encoder
{
- private byte[] _leftOverBytes;
+ private byte[]? _leftOverBytes;
private int _leftOverBytesCount;
private readonly char[] _charsLine;
int i = _leftOverBytesCount;
while (i < 3 && count > 0)
{
- _leftOverBytes[i++] = buffer[index++];
+ _leftOverBytes![i++] = buffer[index++];
count--;
}
}
// 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);
}
{
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;
}
// 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;
int i = _leftOverBytesCount;
while (i < 3 && count > 0)
{
- _leftOverBytes[i++] = buffer[index++];
+ _leftOverBytes![i++] = buffer[index++];
count--;
}
}
// 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);
}
{
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;
}
// 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;
//
// Fields
//
- private byte[] _buffer;
+ private byte[]? _buffer;
private int _startIndex;
private int _curIndex;
private int _endIndex;
{
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);
{
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;
}
// 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
// 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
// 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;
/// </summary>
internal class BitStack
{
- private uint[] _bitStack;
+ private uint[]? _bitStack;
private int _stackPos;
private uint _curr;
private void PopCurr()
{
if (_stackPos > 0)
- _curr = _bitStack[--_stackPos];
+ _curr = _bitStack![--_stackPos];
}
}
}
// 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;
// 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
// 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;
// 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;
// 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;
// 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;
// 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;
/// <summary>
/// SYSTEM identifier (URI) of the entity value - only used for external entities
/// </summary>
- string SystemId { get; }
+ string? SystemId { get; }
/// <summary>
/// PUBLIC identifier of the entity value - only used for external entities
/// </summary>
- string PublicId { get; }
+ string? PublicId { get; }
/// <summary>
/// Replacement text of an entity. Valid only for internal entities.
/// </summary>
- string Text { get; }
+ string? Text { get; }
/// <summary>
/// The line number of the entity value
/// </summary>
#nullable enable
using System;
+using System.Diagnostics.CodeAnalysis;
using System.Text;
using System.Xml.Schema;
Uri? BaseUri { get; }
- char[]? ParsingBuffer { get; }
+ char[] ParsingBuffer { get; }
int ParsingBufferLength { get; }
int CurrentPosition { get; set; }
int LineNo { get; }
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);
}
_wrapped.WriteCData(text);
}
- public override void WriteComment(string text)
+ public override void WriteComment(string? text)
{
EndCDataSection();
_wrapped.WriteComment(text);
}
- public override void WriteProcessingInstruction(string name, string text)
+ public override void WriteProcessingInstruction(string name, string? text)
{
EndCDataSection();
_wrapped.WriteProcessingInstruction(name, text);
}
- public override void WriteWhitespace(string ws)
+ public override void WriteWhitespace(string? ws)
{
if (!_inAttr && (_inCDataSection || StartCDataSection()))
_wrapped.WriteCData(ws);
_wrapped.WriteCData(text);
}
- public override void WriteComment(string text)
+ public override void WriteComment(string? text)
{
EndCDataSection();
_wrapped.WriteComment(text);
}
- public override void WriteProcessingInstruction(string name, string text)
+ public override void WriteProcessingInstruction(string name, string? text)
{
EndCDataSection();
_wrapped.WriteProcessingInstruction(name, text);
}
- public override void WriteWhitespace(string ws)
+ public override void WriteWhitespace(string? ws)
{
if (!_inAttr && (_inCDataSection || StartCDataSection()))
_wrapped.WriteCData(ws);
// 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
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;
}
// Static methods
- internal static ReadContentAsBinaryHelper CreateOrReset(ReadContentAsBinaryHelper helper, XmlReader reader)
+ internal static ReadContentAsBinaryHelper CreateOrReset(ReadContentAsBinaryHelper? helper, XmlReader reader)
{
if (helper == null)
{
{
if (_valueOffset < _valueChunkLength)
{
- int decodedCharsCount = _decoder.Decode(_valueChunk, _valueOffset, _valueChunkLength - _valueOffset);
+ int decodedCharsCount = _decoder.Decode(_valueChunk!, _valueOffset, _valueChunkLength - _valueOffset);
_valueOffset += decodedCharsCount;
}
if (_decoder.IsFull)
return _decoder.DecodedCount;
}
Debug.Assert(_valueOffset == _valueChunkLength);
- if ((_valueChunkLength = _reader.ReadValueChunk(_valueChunk, 0, ChunkSize)) == 0)
+ if ((_valueChunkLength = _reader.ReadValueChunk(_valueChunk!, 0, ChunkSize)) == 0)
{
break;
}
// 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;
// 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;
private XmlNodeType _lastNodeType;
private XmlCharType _xmlCharType;
- private ReadContentAsBinaryHelper _readBinaryHelper;
+ private ReadContentAsBinaryHelper? _readBinaryHelper;
//
// Constructor
{
get
{
- XmlReaderSettings settings = reader.Settings;
+ XmlReaderSettings? settings = reader.Settings;
if (settings == null)
{
settings = new XmlReaderSettings();
ValidateQName(base.reader.Name);
CheckCharacters(base.reader.Value);
- string str;
+ string? str;
str = base.reader.GetAttribute("SYSTEM");
if (str != null)
{
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)
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);
}
// 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;
/// </summary>
internal sealed class XmlEventCache : XmlRawWriter
{
- private List<XmlEvent[]> _pages; // All event pages
- private XmlEvent[] _pageCurr; // Page that is currently being built
+ private List<XmlEvent[]>? _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
int idxPage, idxEvent;
byte[] bytes;
char[] chars;
- XmlRawWriter rawWriter;
+ XmlRawWriter? rawWriter;
// Special-case single text node at the top-level
if (_singleText.Count != 0)
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];
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:
break;
case XmlEventType.PI:
- writer.WriteProcessingInstruction(page[idxEvent].String1, page[idxEvent].String2);
+ writer.WriteProcessingInstruction(page[idxEvent].String1!, page[idxEvent].String2);
break;
case XmlEventType.Whitespace:
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:
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:
// Loop over set of pages
inAttr = false;
- for (idxPage = 0; idxPage < _pages.Count; idxPage++)
+ for (idxPage = 0; idxPage < _pages!.Count; idxPage++)
{
page = _pages[idxPage];
// 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);
}
AddEvent(XmlEventType.EndAttr);
}
- public override void WriteCData(string text)
+ public override void WriteCData(string? text)
{
AddEvent(XmlEventType.CData, text);
}
- public override void WriteComment(string text)
+ public override void WriteComment(string? text)
{
AddEvent(XmlEventType.Comment, text);
}
- public override void WriteProcessingInstruction(string name, string text)
+ public override void WriteProcessingInstruction(string name, string? text)
{
AddEvent(XmlEventType.PI, name, text);
}
- public override void WriteWhitespace(string ws)
+ public override void WriteWhitespace(string? ws)
{
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)
/// 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.
/// </summary>
- 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);
}
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()
_singleText.Clear();
}
}
- else if (_pageSize >= _pageCurr.Length)
+ else if (_pageSize >= _pageCurr!.Length)
{
// Create new page
_pageCurr = new XmlEvent[_pageSize * 2];
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;
_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;
_o = o;
}
- public void InitEvent(XmlEventType eventType, object o)
+ public void InitEvent(XmlEventType eventType, object? o)
{
_eventType = eventType;
_o = o;
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; }
}
}
// Forward call to WriteString(string).
- public override void WriteWhitespace(string ws)
+ public override void WriteWhitespace(string? ws)
{
WriteString(ws);
}
{
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.
{
}
- 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);
{
}
- 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);
// 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)
{
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);
}
// 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());
}
}
- internal char[]? DtdParserProxy_ParsingBuffer
+ internal char[] DtdParserProxy_ParsingBuffer
{
get
{
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)
{
}
}
- internal void DtdParserProxy_ParseComment(StringBuilder sb)
+ internal void DtdParserProxy_ParseComment(StringBuilder? sb)
{
Debug.Assert(_parsingMode == ParsingMode.Full);
_ps.eolNormalized = false;
}
+ [DoesNotReturn]
internal void DtdParserProxy_Throw(Exception e)
{
this.Throw(e);
Encoding? enc = _ps.encoding;
PushParsingState();
- InitStringInput(entity.SystemId, enc, string.Empty);
+ InitStringInput(entity.SystemId!, enc, string.Empty);
RegisterEntity(entity);
PushParsingState();
- InitStringInput(entity.DeclaredUriString ?? string.Empty, enc, entity.Text);
+ InitStringInput(entity.DeclaredUriString ?? string.Empty, enc, entity.Text!);
RegisterEntity(entity);
_ps.eolNormalized = true;
- RegisterConsumedCharacters(entity.Text.Length, true);
+ RegisterConsumedCharacters(entity.Text!.Length, true);
}
private void PopEntity()
}
// 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)
{
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);
}
}
// 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;
private Task FinishInitAsync()
{
- switch (_laterInitParam.initType)
+ switch (_laterInitParam!.initType)
{
case InitInputType.UriString:
return FinishInitUriStringAsync();
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)
{
try
{
// init ParsingState
+ Debug.Assert(_reportedBaseUri != null);
await InitStreamInputAsync(_laterInitParam.inputbaseUri, _reportedBaseUri, stream, null, 0, enc).ConfigureAwait(false);
_reportedEncoding = _ps.encoding;
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;
private async Task FinishInitTextReaderAsync()
{
// init ParsingState
- await InitTextReaderInputAsync(_reportedBaseUri, _laterInitParam.inputTextReader).ConfigureAwait(false);
+ await InitTextReaderInputAsync(_reportedBaseUri!, _laterInitParam!.inputTextReader!).ConfigureAwait(false);
_reportedEncoding = _ps.encoding;
// 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);
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);
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);
// 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();
// 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);
}
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;
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)
// parse version, encoding & standalone attributes
int xmlDeclState = 0; // <?xml (0) version='1.0' (1) encoding='__' (2) standalone='__' (3) ?>
- Encoding encoding = null;
+ Encoding? encoding = null;
while (true)
{
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))
{
// read attribute name
int nameEndPos = await ParseNameAsync().ConfigureAwait(false);
- NodeData attr = null;
+ NodeData? attr = null;
switch (_ps.chars[_ps.charPos])
{
case 'v':
}
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;
_ps.charPos++;
if (!isTextDecl)
{
- attr.quoteChar = quoteChar;
+ attr!.quoteChar = quoteChar;
attr.SetLineInfo2(_ps.LineNo, _ps.LinePos);
}
#endif
if (!isTextDecl)
{
- attr.SetValue(_ps.chars, _ps.charPos, pos - _ps.charPos);
+ attr!.SetValue(_ps.chars, _ps.charPos, pos - _ps.charPos);
}
xmlDeclState = 1;
}
encoding = CheckEncoding(encName);
if (!isTextDecl)
{
- attr.SetValue(encName);
+ attr!.SetValue(encName);
}
xmlDeclState = 2;
break;
}
if (!isTextDecl)
{
- attr.SetValue(_ps.chars, _ps.charPos, pos - _ps.charPos);
+ attr!.SetValue(_ps.chars, _ps.charPos, pos - _ps.charPos);
}
xmlDeclState = 3;
break;
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))
{
char[] chars = _ps.chars;
// push namespace context
- _namespaceManager.PushScope();
+ _namespaceManager!.PushScope();
// init the NodeData class
if (colonPos == -1 || !_supportNamespaces)
{
int pos = _ps.charPos;
char[] chars = _ps.chars;
- NodeData attr = null;
+ NodeData? attr = null;
Debug.Assert(_attrCount == 0);
// 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);
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;
// 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<bool> _ParseTextAsync(Task<(int, int, int, bool)> parseTask)
+ private async Task<bool> _ParseTextAsync(Task<(int, int, int, bool)>? parseTask)
{
int startPos;
int endPos;
// return false == unexpanded external entity, stop parsing and return
private async Task<EntityType> 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)
{
// 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<bool> ParsePIAsync(StringBuilder piInDtdStringBuilder)
+ private async Task<bool> ParsePIAsync(StringBuilder? piInDtdStringBuilder)
{
if (_parsingMode == ParsingMode.Full)
{
}
}
- private async Task<int> EatWhitespacesAsync(StringBuilder sb)
+ private async Task<int> EatWhitespacesAsync(StringBuilder? sb)
{
int pos = _ps.charPos;
int wsCount = 0;
// - 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;
// - 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<int> ParseNamedCharRefAsync(bool expand, StringBuilder internalSubsetBuilder)
+ private async Task<int> ParseNamedCharRefAsync(bool expand, StringBuilder? internalSubsetBuilder)
{
while (true)
{
// 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;
{
try
{
- uri = _xmlResolver.ResolveUri(baseUri, publicId);
+ uri = _xmlResolver!.ResolveUri(baseUri, publicId);
if (await OpenAndPushAsync(uri).ConfigureAwait(false))
{
return;
}
// Then try SYSTEM Id
- uri = _xmlResolver.ResolveUri(baseUri, systemId);
+ uri = _xmlResolver!.ResolveUri(baseUri, systemId);
try
{
if (await OpenAndPushAsync(uri).ConfigureAwait(false))
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
{
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);
}
else
{
- Encoding enc = _ps.encoding;
+ Encoding? enc = _ps.encoding;
PushParsingState();
- InitStringInput(entity.SystemId, enc, string.Empty);
+ InitStringInput(entity.SystemId!, enc, string.Empty);
RegisterEntity(entity);
private struct ParsingState
{
// character buffer
- internal char[]? chars;
+ internal char[] chars;
internal int charPos;
internal int charsUsed;
internal Encoding? encoding;
internal void Clear()
{
- chars = null;
+ chars = null!;
charPos = 0;
charsUsed = 0;
encoding = null;
get { return _reader.DtdParserProxy_IsEof; }
}
- char[]? IDtdParserAdapter.ParsingBuffer
+ char[] IDtdParserAdapter.ParsingBuffer
{
get { return _reader.DtdParserProxy_ParsingBuffer; }
}
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);
}
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);
}
_reader.DtdParserProxy_PushInternalDtd(baseUri, internalDtd);
}
+ [DoesNotReturn]
void IDtdParserAdapter.Throw(Exception e)
{
_reader.DtdParserProxy_Throw(e);
// 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;
}
// Writes out a comment <!--...--> containing the specified text.
- public override void WriteComment(string text)
+ public override void WriteComment(string? text)
{
try
{
}
// Writes out the given whitespace.
- public override void WriteWhitespace(string ws)
+ public override void WriteWhitespace(string? ws)
{
try
{
// 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;
// Fields
//
protected XmlReader reader;
- protected IXmlLineInfo readerAsIXmlLineInfo;
+ protected IXmlLineInfo? readerAsIXmlLineInfo;
//
// Constructor
//
// 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; } }
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; } }
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);
}
reader.Skip();
}
- public override string LookupNamespace(string prefix)
+ public override string? LookupNamespace(string prefix)
{
return reader.LookupNamespace(prefix);
}
//
// Internal methods
//
- internal override IDtdInfo DtdInfo
+ internal override IDtdInfo? DtdInfo
{
get
{
// 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;
// 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;
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);
}
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);
}
}
// Writes out the attribute with the specified prefix, LocalName, NamespaceURI and value.
- public void WriteAttributeString(string? prefix, string localName, string? ns, string value)
+ public void WriteAttributeString(string? prefix, string localName, string? ns, string? value)
{
WriteStartAttribute(prefix, localName, ns);
WriteString(value);
// Writes out a comment <!--...-->; containing the specified text.
- public abstract void WriteComment(string text);
+ public abstract void WriteComment(string? text);
// Writes out a processing instruction with a space between the name and text as follows: <?name text?>
- public abstract void WriteProcessingInstruction(string name, string text);
+ public abstract void WriteProcessingInstruction(string name, string? text);
// Writes out an entity reference as follows: "&"+name+";".
// Writes out the given whitespace.
- public abstract void WriteWhitespace(string ws);
+ public abstract void WriteWhitespace(string? ws);
// Writes out the specified text content.
// 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;
goto case CachingReaderState.Record;
case CachingReaderState.Record:
- ValidatingReaderNodeData recordedNode = null;
+ ValidatingReaderNodeData? recordedNode = null;
if (await _coreReader.ReadAsync().ConfigureAwait(false))
{
switch (_coreReader.NodeType)
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)!;
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<string, object>(originalStringValue, ReturnBoxedValue(_attributePSVI.typedAttributeValue, AttributeSchemaInfo.XmlType, unwrapTypedValue)!);
// 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
{
{
s_keepTempFiles = new BooleanSwitch("XmlSerialization.Compilation", "Keep XmlSerialization generated (temp) files.");
}
+
return s_keepTempFiles;
}
}
{
s_nonRecursiveTypeLoading = new BooleanSwitch("XmlSerialization.NonRecursiveTypeLoading", "Turn on non-recursive algorithm generating XmlMappings for CLR types.");
}
+
return s_nonRecursiveTypeLoading;
}
}
// 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;
// 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;
{
#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);
}
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;
}
}
// 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
{
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)
{
object result = _stack[_used];
return result;
}
+
return null;
}
- internal object Peek()
+ internal object? Peek()
{
return _used > 0 ? _stack[_used - 1] : null;
}
// 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;
// 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
// 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
// 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;
// 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
/// </summary>
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,
// 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
{
//
// 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;
public partial class XmlPreloadedResolver : XmlResolver
{
public override Task<object> GetEntityAsync(Uri absoluteUri,
- string role,
- Type ofObjectToReturn)
+ string? role,
+ Type? ofObjectToReturn)
{
if (absoluteUri == null)
{
throw new ArgumentNullException(nameof(absoluteUri));
}
- PreloadedData data;
+ PreloadedData? data;
if (!_mappings.TryGetValue(absoluteUri, out data))
{
if (_fallbackResolver != null)
// 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;
using System.Collections;
using System.Xml.Schema;
using MS.Internal.Xml.XPath;
+ using System.Diagnostics.CodeAnalysis;
/*--------------------------------------------------------------------------------------------- *
* Dynamic Part Below... *
internal void SetDepth(int depth)
{
this.rootDepth = this.curDepth = depth;
- return;
}
// "a/b/c" pointer from b move to a
{
this.isMatch = false;
}
+
if (!AxisStack.Equal(this.curNode.Name, this.curNode.Urn, name, URN))
{
return false;
}
+
if (this.curDepth == -1)
{
SetDepth(depth);
{
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;
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?
}
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;
}
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;
// 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;
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)
{
// run everyone once
}
}
+
return result;
}
}
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;
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;
}
// 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; }
}
// 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));
}
}
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;
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:
// 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;
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)
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)
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)
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));
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));
// 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;
private const int bitSlotShift = 5;
private const int bitSlotMask = (1 << bitSlotShift) - 1;
- private int _count;
+ private readonly int _count;
private uint[] _bits;
- private BitSet()
+ private BitSet(int count, uint[] bits)
{
+ _count = count;
+ _bits = bits;
}
public BitSet(int count)
}
- public override bool Equals(object obj)
+ public override bool Equals(object? obj)
{
// assume the same type
if (obj != null)
public BitSet Clone()
{
- BitSet newset = new BitSet();
- newset._count = _count;
- newset._bits = (uint[])_bits.Clone();
- return newset;
+ return new BitSet(_count, (uint[])_bits.Clone());
}
// 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;
// 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;
/// <summary>
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.
// 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;
{
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
// 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;
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
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)
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++)
public KeySequence PopKS()
{
- return ((KSStruct)_KSs[--_KSpointer]).ks;
+ return ((KSStruct)_KSs[--_KSpointer]!).ks;
}
}
}
}
- private DecimalStruct _dstruct = null;
+ private DecimalStruct? _dstruct = null;
private object _ovalue;
private readonly string _svalue; // only for output
private XmlSchemaDatatype _xsdtype;
}
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
// 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();
}
}
}
}
// 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()
// 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;
/// </summary>
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; } }
}
/// <summary>
{
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()
/// <summary>
/// Add name and return it's number
/// </summary>
- 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;
}
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);
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;
}
{
get
{
- object lookup = _names[name];
+ object? lookup = _names[name];
if (lookup != null)
{
return (int)lookup;
}
+
if (_wildcards != null)
{
lookup = _wildcards[name.Namespace];
return (int)lookup;
}
}
+
return _last; // true wildcard
}
}
/// </summary>
public bool Exists(XmlQualifiedName name)
{
- object lookup = _names[name];
+ object? lookup = _names[name];
if (lookup != null)
{
return true;
}
+
return false;
}
/// <summary>
/// Return content processing mode for the symbol
/// </summary>
- public object GetParticle(int symbol)
+ public object? GetParticle(int symbol)
{
return symbol == _last ? _particleLast : _particles[symbol];
}
/// </summary>
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:*";
}
}
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;
{
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
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)
{
replacementNode = choice;
}
}
+
if (parent.LeftChild == this)
{
parent.LeftChild = replacementNode;
/// </summary>
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; }
this_ = (InteriorNode)this_._leftChild;
continue;
}
- this_._leftChild.ExpandTree(this_, symbols, positions);
+
+ this_._leftChild!.ExpandTree(this_, symbols, positions);
ProcessRight:
if (this_._rightChild != null)
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);
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)
{
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);
}
{
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;
this_ = n as SequenceNode;
}
while (this_ != null);
- return n.IsNullable;
+
+ return n!.IsNullable;
}
}
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;
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);
}
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);
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;
{
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);
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
{
public override void ConstructPos(BitSet firstpos, BitSet lastpos, BitSet[] followpos)
{
- LeftChild.ConstructPos(firstpos, lastpos, followpos);
+ LeftChild!.ConstructPos(firstpos, lastpos, followpos);
}
public override bool 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
{
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);
#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
{
private decimal _min;
private readonly decimal _max;
- private BitSet _nextIteration;
+ private BitSet? _nextIteration;
public LeafRangeNode(decimal min, decimal max) : this(-1, min, max) { }
get { return _min; }
}
- public BitSet NextIteration
+ public BitSet? NextIteration
{
get
{
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;
}
// 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
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;
}
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;
//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);
internal sealed class ParticleContentValidator : ContentValidator
{
- private SymbolsDictionary _symbols;
- private Positions _positions;
- private Stack<SyntaxTreeNode> _stack; // parsing context
- private SyntaxTreeNode _contentNode; // content model points to syntax tree
+ private SymbolsDictionary? _symbols;
+ private Positions? _positions;
+ private Stack<SyntaxTreeNode?>? _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;
{
_symbols = new SymbolsDictionary();
_positions = new Positions();
- _stack = new Stack<SyntaxTreeNode>();
+ _stack = new Stack<SyntaxTreeNode?>();
}
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;
else
{
// some collapsing to do...
- InteriorNode inNode = (InteriorNode)_stack.Pop();
+ InteriorNode? inNode = (InteriorNode?)_stack.Pop();
if (inNode != null)
{
inNode.RightChild = node;
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;
public void AddChoice()
{
- SyntaxTreeNode node = _stack.Pop();
+ SyntaxTreeNode? node = _stack!.Pop();
InteriorNode choice = new ChoiceNode();
choice.LeftChild = node;
_stack.Push(choice);
public void AddSequence()
{
- SyntaxTreeNode node = _stack.Pop();
+ SyntaxTreeNode? node = _stack!.Pop();
InteriorNode sequence = new SequenceNode();
sequence.LeftChild = node;
_stack.Push(sequence);
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();
#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.
// 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)
}
else
{
- int[][] transitionTable = null;
+ int[][]? transitionTable = null;
// if each symbol has unique particle we are golden
if (!_symbols.IsUpaEnforced)
{
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
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
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]);
}
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
{
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]);
}
}
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]);
}
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
/// <summary>
/// Algorithm 3.5 Construction of a DFA from a regular expression
/// </summary>
- 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();
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
// 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;
{
return null;
}
+
unmarked.Enqueue(newset);
stateTable.Add(newset, newState);
transitionTable.Add(new int[symbolsCount + 1]);
{
// 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++)
{
}
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)
{
bb.AppendFormat(" {0:000} ", transitionTable[i][j]);
}
}
+
bb.AppendLine(transitionTable[i][_symbols.Count] == 1 ? "+" : "");
}
}
/// <summary>
/// Algorithm 3.1 Simulating a DFA
/// </summary>
- 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];
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)
{
{
names = new ArrayList();
}
- XmlSchemaParticle p = (XmlSchemaParticle)_symbols.GetParticle(i);
+
+ XmlSchemaParticle? p = (XmlSchemaParticle?)_symbols.GetParticle(i);
if (p == null)
{
string s = _symbols.NameOf(i);
}
}
}
+
return names;
}
{
if (transition[i] != -1)
{
- XmlSchemaParticle p = (XmlSchemaParticle)_symbols.GetParticle(i);
+ XmlSchemaParticle? p = (XmlSchemaParticle?)_symbols.GetParticle(i);
if (p == null)
{
continue;
/// <summary>
/// Algorithm 3.4 Simulation of an NFA
/// </summary>
- 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))
{
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))
{
{
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);
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;
public override void InitValidation(ValidationState context)
{
int positionsCount = _positions.Count;
- List<RangePositionInfo> runningPositions = context.RunningPositions;
+ List<RangePositionInfo>? runningPositions = context.RunningPositions;
if (runningPositions != null)
{
Debug.Assert(_minMaxNodesCount != 0);
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<RangePositionInfo> runningPositions = context.RunningPositions;
+ List<RangePositionInfo>? runningPositions = context.RunningPositions;
int matchCount = context.CurrentState.NumberOfRunningPos;
int k = 0;
RangePositionInfo rposInfo;
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
{ //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
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))
{
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];
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];
}
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];
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;
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)
{
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);
}
}
}
+
return names;
}
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);
}
}
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];
}
{
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;
}
}
// 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;
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;
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;
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];
// 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;
//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);
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;
{ //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)
}
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);
}
}
internal static XmlSchemaSimpleType GetSimpleTypeFromXsdType(XmlQualifiedName qname)
{
- return (XmlSchemaSimpleType)s_builtinTypes[qname];
+ return (XmlSchemaSimpleType)s_builtinTypes[qname]!;
}
internal static XmlSchemaSimpleType GetNormalizedStringTypeV1Compat()
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;
}
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;
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;
return DeriveByList(0, schemaType);
}
- internal XmlSchemaDatatype DeriveByList(int minSize, XmlSchemaType schemaType)
+ internal XmlSchemaDatatype DeriveByList(int minSize, XmlSchemaType? schemaType)
{
if (_variety == XmlSchemaDatatypeVariety.List)
{
}
//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();
return false;
}
- internal virtual XmlValueConverter CreateValueConverter(XmlSchemaType schemaType) { return null; }
+ internal abstract XmlValueConverter CreateValueConverter(XmlSchemaType? schemaType);
internal override FacetsChecker FacetsChecker { get { return miscFacetsChecker; } }
public override XmlTypeCode TypeCode { get { return XmlTypeCode.None; } }
- internal override RestrictionFacets Restriction
+ internal override RestrictionFacets? Restriction
{
get
{
_restriction = value;
}
}
+
internal override bool HasLexicalFacets
{
get
}
}
- protected DatatypeImplementation Base { get { return _baseType; } }
+ protected DatatypeImplementation? Base { get { return _baseType; } }
internal abstract Type ListValueType { get; }
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
}
}
- 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);
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
}
}
- 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
null
};
- private static readonly DatatypeImplementation[] s_tokenizedTypesXsd = {
+ private static readonly DatatypeImplementation?[] s_tokenizedTypesXsd = {
s_string, // CDATA
s_ID, // ID
s_IDREF, // IDREF
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)
{
do
{
- XmlSchemaSimpleTypeList listType = simpleType.Content as XmlSchemaSimpleTypeList;
+ XmlSchemaSimpleTypeList? listType = simpleType.Content as XmlSchemaSimpleTypeList;
if (listType != null)
{
listItemType = listType.BaseItemType;
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);
{
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;
}
{
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;
}
}
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)
{
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;
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);
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;
object array;
if (_itemType.Variety == XmlSchemaDatatypeVariety.Union)
{
- object unionTypedValue;
+ object? unionTypedValue;
string[] splitString = XmlConvert.SplitString(s);
for (int i = 0; i < splitString.Length; ++i)
{
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));
}
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);
}
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;
}
{
for (int i = 0; i < _types.Length; ++i)
{
- if (_types[i].Datatype.Variety == XmlSchemaDatatypeVariety.List)
+ if (_types[i].Datatype!.Variety == XmlSchemaDatatypeVariety.List)
{
return false;
}
{
for (int i = 0; i < _types.Length; ++i)
{
- if (derivedType.IsDerivedFrom(_types[i].Datatype))
+ if (derivedType.IsDerivedFrom(_types[i].Datatype!))
{
return true;
}
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;
//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);
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)
exception = unionFacetsChecker.CheckLexicalFacets(ref s1, this);
if (exception != null) goto Error;
}
+
+ Debug.Assert(memberType != null);
typedValue = new XsdSimpleValue(memberType, valueToCheck);
if (this.HasValueFacets)
{
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;
}
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;
internal class Datatype_anyAtomicType : Datatype_anySimpleType
{
- internal override XmlValueConverter CreateValueConverter(XmlSchemaType schemaType)
+ internal override XmlValueConverter CreateValueConverter(XmlSchemaType? schemaType)
{
return XmlAnyConverter.AnyAtomic;
}
internal class Datatype_untypedAtomicType : Datatype_anyAtomicType
{
- internal override XmlValueConverter CreateValueConverter(XmlSchemaType schemaType)
+ internal override XmlValueConverter CreateValueConverter(XmlSchemaType? schemaType)
{
return XmlUntypedConverter.Untyped;
}
*/
internal class Datatype_string : Datatype_anySimpleType
{
- internal override XmlValueConverter CreateValueConverter(XmlSchemaType schemaType)
+ internal override XmlValueConverter CreateValueConverter(XmlSchemaType? schemaType)
{
return XmlStringConverter.Create(schemaType);
}
}
}
- 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;
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);
}
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);
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);
}
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;
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);
}
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);
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);
}
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;
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);
}
}
- 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)
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)
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;
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);
}
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);
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);
}
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);
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);
}
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);
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);
}
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;
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);
}
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;
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)
{
{
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;
exception = stringFacetsChecker.CheckValueFacets(s, this);
if (exception != null) goto Error;
- nameTable.Add(s);
+ nameTable!.Add(s);
typedValue = s;
return null;
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);
}
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;
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)
{
{
// 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);
{
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;
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;
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;
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;
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;
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;
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;
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;
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;
*/
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
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
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)
{
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
{
}
}
- 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;
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;
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;
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;
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
{
}
}
- 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;
// 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;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
+using System.Diagnostics.CodeAnalysis;
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)
{
// 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;
private bool _v1Compat = false;
// cached character buffer
- private char[] _chars;
+ private char[] _chars = null!;
private int _charsUsed;
private int _curPos;
private int _colonPos;
// value of the internal subset
- private StringBuilder _internalSubsetValueSb = null;
+ private StringBuilder? _internalSubsetValueSb = null;
// entities
private int _externalEntitiesDepth = 0;
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<string, UndeclaredNotation> _undeclaredNotations = null;
- private int[] _condSectionEntityIds = null;
+ private Dictionary<string, UndeclaredNotation>? _undeclaredNotations = null;
+ private int[]? _condSectionEntityIds = null;
private const int CondSectionEntityIdsInitialSize = 2;
_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;
_stringBuilder = new StringBuilder();
- Uri baseUri = readerAdapter.BaseUri;
+ Uri? baseUri = readerAdapter.BaseUri;
if (baseUri != null)
{
_documentBaseUri = baseUri.ToString();
_hasFreeFloatingInternalSubset = true;
}
- Uri baseUriOb = _readerAdapter.BaseUri;
+ Uri? baseUriOb = _readerAdapter.BaseUri;
if (baseUriOb != null)
{
_documentBaseUri = baseUriOb.ToString();
{
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));
return;
}
- Uri baseUri = _readerAdapter.BaseUri;
+ Uri? baseUri = _readerAdapter.BaseUri;
if (baseUri != null)
{
_externalDtdBaseUri = baseUri.ToString();
if (_condSectionDepth > 0)
{
_condSectionDepth--;
- if (_validate && _currentEntityId != _condSectionEntityIds[_condSectionDepth])
+ if (_validate && _currentEntityId != _condSectionEntityIds![_condSectionDepth])
{
SendValidationEvent(_curPos, XmlSeverityType.Error, SR.Sch_ParEntityRefNesting, string.Empty);
}
// element name
XmlQualifiedName elementName = GetNameQualified(true);
- SchemaElementDecl elementDecl;
+ SchemaElementDecl? elementDecl;
if (!_schemaInfo.ElementDecls.TryGetValue(elementName, out elementDecl))
{
if (!_schemaInfo.UndeclaredElementDecls.TryGetValue(elementName, out elementDecl))
}
}
- SchemaAttDef attrDef = null;
+ SchemaAttDef? attrDef = null;
while (true)
{
switch (GetToken(false))
}
if (_validate)
{
- attrDef.CheckXmlSpace(_readerAdapterWithValidation.ValidationEventHandling);
+ attrDef.CheckXmlSpace(_readerAdapterWithValidation!.ValidationEventHandling);
}
}
}
}
if (_validate)
{
- attrDef.CheckXmlSpace(_readerAdapterWithValidation.ValidationEventHandling);
+ attrDef.CheckXmlSpace(_readerAdapterWithValidation!.ValidationEventHandling);
}
}
}
}
// get schema decl for element
- SchemaElementDecl elementDecl = null;
+ SchemaElementDecl? elementDecl = null;
XmlQualifiedName name = GetNameQualified(true);
if (_schemaInfo.ElementDecls.TryGetValue(name, out elementDecl))
}
case Token.None:
{
- ParticleContentValidator pcv = null;
+ ParticleContentValidator? pcv = null;
pcv = new ParticleContentValidator(XmlSchemaContentType.ElementOnly);
pcv.Start();
pcv.OpenGroup();
private void ParseEntityDecl()
{
bool isParamEntity = false;
- SchemaEntity entity = null;
+ SchemaEntity? entity = null;
// get entity name and type
switch (GetToken(true))
{
case Token.PUBLIC:
case Token.SYSTEM:
- string systemId;
- string publicId;
+ string? systemId;
+ string? publicId;
ParseExternalId(token, Token.EntityDecl, out publicId, out systemId);
}
XmlQualifiedName notationName = GetNameQualified(false);
- SchemaNotation notation = null;
+ SchemaNotation? notation = null;
if (!_schemaInfo.Notations.ContainsKey(notationName.Name))
{
if (_undeclaredNotations != null)
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);
_undeclaredNotations = new Dictionary<string, UndeclaredNotation>();
}
UndeclaredNotation un = new UndeclaredNotation(notationName, LineNo, LinePos - notationName.Length);
- UndeclaredNotation loggedUn;
+ UndeclaredNotation? loggedUn;
if (_undeclaredNotations.TryGetValue(notationName, out loggedUn))
{
un.next = loggedUn.next;
if (SaveInternalSubsetValue)
{
_readerAdapter.ParseComment(_internalSubsetValueSb);
- _internalSubsetValueSb.Append("-->");
+ _internalSubsetValueSb!.Append("-->");
}
else
{
if (SaveInternalSubsetValue)
{
_readerAdapter.ParsePI(_internalSubsetValueSb);
- _internalSubsetValueSb.Append("?>");
+ _internalSubsetValueSb!.Append("?>");
}
else
{
}
}
- 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;
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;
}
else
{
- if (entity.Text.Length == 0)
+ if (entity.Text!.Length == 0)
{
return false;
}
{
SaveParsingBuffer();
- IDtdEntityInfo oldEntity;
+ IDtdEntityInfo? oldEntity;
if (!_readerAdapter.PopEntity(out oldEntity, out _currentEntityId))
{
return false;
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);
//
// 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));
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);
{
get
{
- Uri tmp = _readerAdapter.BaseUri;
+ Uri? tmp = _readerAdapter.BaseUri;
return (tmp != null) ? tmp.ToString() : string.Empty;
}
}
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()));
}
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)
}
int startPos = 0;
- StringBuilder norValue = null;
+ StringBuilder? norValue = null;
while (value[startPos] == 0x20)
{
// 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;
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);
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
// 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
// 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;
using System.Diagnostics;
+ using System.Diagnostics.CodeAnalysis;
internal abstract class SchemaDeclBase
{
};
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<string> values; // array of values for enumerated and notation types
+ protected List<string>? values; // array of values for enumerated and notation types
- protected SchemaDeclBase(XmlQualifiedName name, string prefix)
+ protected SchemaDeclBase(XmlQualifiedName name, string? prefix)
{
this.name = name;
this.prefix = prefix;
set { name = value; }
}
+ [AllowNull]
internal string Prefix
{
get { return (prefix == null) ? string.Empty : prefix; }
set { minLength = value; }
}
- internal XmlSchemaType SchemaType
+ internal XmlSchemaType? SchemaType
{
get { return schemaType; }
set { schemaType = value; }
values.Add(value);
}
- internal List<string> Values
+ internal List<string>? Values
{
get { return values; }
set { values = value; }
set { defaultValueRaw = value; }
}
- internal object DefaultValueTyped
+ internal object? DefaultValueTyped
{
get { return defaultValueTyped; }
set { defaultValueTyped = value; }
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)
// 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;
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
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
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; }
}
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; }
set { _ndata = value; }
}
- internal string Text
+ internal string? Text
{
get { return _text; }
set { _text = value; _isExternal = false; }
// 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;
_node = node;
}
- public override string LookupNamespace(string prefix)
+ public override string? LookupNamespace(string prefix)
{
if (prefix == "xml")
{ //Special case for the XML namespace
namespaces = current.Namespaces.Namespaces;
if (namespaces != null && namespaces.Count > 0)
{
- string uri;
+ string? uri;
if (namespaces.TryGetValue(prefix, out uri))
return uri;
}
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
// 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;
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)
{
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; }
// 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
// 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
{
/// <summary>
// 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);
}
// 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;
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;
public BitSet[] CurPos = new BitSet[2];
//For all
- public BitSet AllElementsSet;
+ public BitSet? AllElementsSet;
//For MinMaxNFA
- public List<RangePositionInfo> RunningPositions;
+ public List<RangePositionInfo>? RunningPositions;
public bool TooComplex;
};
}
// 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;
// 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;
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; }
// 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;
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; }
}
[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; }
// 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;
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; }
}
[XmlIgnore]
- internal NamespaceList NamespaceList
+ internal NamespaceList? NamespaceList
{
get { return _namespaceList; }
}
{
get
{
- switch (_namespaceList.Type)
+ switch (_namespaceList!.Type)
{
case NamespaceList.ListType.Any:
return "##any:*";
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)
internal bool Allows(XmlQualifiedName qname)
{
- return _namespaceList.Allows(qname.Namespace);
+ return _namespaceList!.Allows(qname.Namespace);
}
}
}
// 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;
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; }
[XmlIgnore]
- internal NamespaceList NamespaceList
+ internal NamespaceList? NamespaceList
{
get { return _namespaceList; }
}
internal bool Allows(XmlQualifiedName qname)
{
- return _namespaceList.Allows(qname.Namespace);
+ return _namespaceList!.Allows(qname.Namespace);
}
internal static bool IsSubset(XmlSchemaAnyAttribute sub, XmlSchemaAnyAttribute super)
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)
}
}
- 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)
// 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;
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; }
// 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;
{
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;
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; }
[XmlAttribute("fixed")]
[DefaultValue(null)]
- public string FixedValue
+ public string? FixedValue
{
get { return _fixedValue; }
set { _fixedValue = value; }
}
[XmlAttribute("name")]
- public string Name
+ public string? Name
{
get { return _name; }
set { _name = value; }
}
[XmlElement("simpleType")]
- public XmlSchemaSimpleType SchemaType
+ public XmlSchemaSimpleType? SchemaType
{
get { return _type; }
set { _type = value; }
[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
{
}
[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)
{
}
[XmlIgnore]
- internal XmlSchemaDatatype Datatype
+ internal XmlSchemaDatatype? Datatype
{
get
{
_attributeType = value;
}
- internal SchemaAttDef AttDef
+ internal SchemaAttDef? AttDef
{
get { return _attDef; }
set { _attDef = value; }
}
[XmlIgnore]
- internal override string NameAttribute
+ internal override string? NameAttribute
{
get { return Name; }
set { Name = value; }
// 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;
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; }
}
[XmlElement("anyAttribute")]
- public XmlSchemaAnyAttribute AnyAttribute
+ public XmlSchemaAnyAttribute? AnyAttribute
{
get { return _anyAttribute; }
set { _anyAttribute = value; }
}
[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; }
}
[XmlIgnore]
- internal override string NameAttribute
+ internal override string? NameAttribute
{
get { return Name; }
set { Name = value; }
// 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
private XmlQualifiedName _refName = XmlQualifiedName.Empty;
[XmlAttribute("ref")]
+ [AllowNull]
public XmlQualifiedName RefName
{
get { return _refName; }
// 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;
// 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
// 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;
[XmlElement("restriction", typeof(XmlSchemaComplexContentRestriction)),
XmlElement("extension", typeof(XmlSchemaComplexContentExtension))]
- public override XmlSchemaContent Content
+ public override XmlSchemaContent? Content
{
get { return _content; }
set { _content = value; }
// 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;
public class XmlSchemaComplexContentExtension : XmlSchemaContent
{
- private XmlSchemaParticle _particle;
+ private XmlSchemaParticle? _particle;
private XmlSchemaObjectCollection _attributes = new XmlSchemaObjectCollection();
- private XmlSchemaAnyAttribute _anyAttribute;
+ private XmlSchemaAnyAttribute? _anyAttribute;
private XmlQualifiedName _baseTypeName = XmlQualifiedName.Empty;
[XmlAttribute("base")]
XmlElement("choice", typeof(XmlSchemaChoice)),
XmlElement("all", typeof(XmlSchemaAll)),
XmlElement("sequence", typeof(XmlSchemaSequence))]
- public XmlSchemaParticle Particle
+ public XmlSchemaParticle? Particle
{
get { return _particle; }
set { _particle = value; }
get { return _attributes; }
}
-
[XmlElement("anyAttribute")]
- public XmlSchemaAnyAttribute AnyAttribute
+ public XmlSchemaAnyAttribute? AnyAttribute
{
get { return _anyAttribute; }
set { _anyAttribute = value; }
// 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;
public class XmlSchemaComplexContentRestriction : XmlSchemaContent
{
- private XmlSchemaParticle _particle;
+ private XmlSchemaParticle? _particle;
private XmlSchemaObjectCollection _attributes = new XmlSchemaObjectCollection();
- private XmlSchemaAnyAttribute _anyAttribute;
+ private XmlSchemaAnyAttribute? _anyAttribute;
private XmlQualifiedName _baseTypeName = XmlQualifiedName.Empty;
[XmlAttribute("base")]
XmlElement("choice", typeof(XmlSchemaChoice)),
XmlElement("all", typeof(XmlSchemaAll)),
XmlElement("sequence", typeof(XmlSchemaSequence))]
- public XmlSchemaParticle Particle
+ public XmlSchemaParticle? Particle
{
get { return _particle; }
set { _particle = value; }
}
[XmlElement("anyAttribute")]
- public XmlSchemaAnyAttribute AnyAttribute
+ public XmlSchemaAnyAttribute? AnyAttribute
{
get { return _anyAttribute; }
set { _anyAttribute = value; }
{
newComplexRest.Particle = CloneParticle(newComplexRest.Particle, parentSchema);
}
+
newComplexContent.Content = newComplexRest;
}
+
complexType.ContentModel = newComplexContent;
}
}
// 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;
// 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 abstract class XmlSchemaContentModel : XmlSchemaAnnotated
{
[XmlIgnore]
- public abstract XmlSchemaContent Content { get; set; }
+ public abstract XmlSchemaContent? Content { get; set; }
}
}
// 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;
// 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
// 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;
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; } }
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; }
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));
while (enumerator.MoveNext())
{
bldr.Append(" , ");
- cur = enumerator.Current;
+ cur = enumerator.Current!;
if (cur is IFormattable)
{
bldr.Append(((IFormattable)cur).ToString("", CultureInfo.InvariantCulture));
}
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);
}
// 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;
// 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; }
return true;
}
- if ((except & derivedType.DerivedBy) != 0 || !dt.Datatype!.IsDerivedFrom(bt.Datatype))
+ if ((except & derivedType.DerivedBy) != 0 || !dt.Datatype!.IsDerivedFrom(bt.Datatype!))
{
return false;
}
// 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;
/// If the NameTest contains a star, null values for localName (case NCName':*'), or for
/// both localName and prefix (case '*') are returned.
/// </summary>
- 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;
// 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;
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
{
if (s_Lock == null)
{
object o = new object();
- Interlocked.CompareExchange<object>(ref s_Lock, o, null);
+ Interlocked.CompareExchange<object?>(ref s_Lock, o, null);
}
+
return s_Lock;
}
}
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;
// 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;
}
int startPos = 0;
- StringBuilder norValue = null;
+ StringBuilder? norValue = null;
XmlCharType xmlCharType = XmlCharType.Instance;
while (xmlCharType.IsWhiteSpace(value[startPos]))
{
int i = 0;
int startPos = 0;
- StringBuilder norValue = null;
+ StringBuilder? norValue = null;
while (i < len)
{
// 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;
using System.Diagnostics;
using System.Collections;
using System.Text.RegularExpressions;
+using System.Diagnostics.CodeAnalysis;
namespace System.Xml
{
/// DataColumn names, that contain characters that are not permitted in
/// XML names to valid names.</para>
/// </devdoc>
- public static string EncodeName(string name)
+ [return: NotNullIfNotNull("name")]
+ public static string? EncodeName(string? name)
{
return EncodeName(name, true/*Name_not_NmToken*/, false/*Local?*/);
}
/// <para> Verifies the name is valid
/// according to production [7] in the XML spec.</para>
/// </devdoc>
- public static string EncodeNmToken(string name)
+ [return: NotNullIfNotNull("name")]
+ public static string? EncodeNmToken(string? name)
{
return EncodeName(name, false/*Name_not_NmToken*/, false/*Local?*/);
}
/// <para>Converts names, such as DataTable or DataColumn names, that contain
/// characters that are not permitted in XML names to valid names.</para>
/// </devdoc>
- public static string EncodeLocalName(string name)
+ [return: NotNullIfNotNull("name")]
+ public static string? EncodeLocalName(string? name)
{
return EncodeName(name, true/*Name_not_NmToken*/, true/*Local?*/);
}
/// <para>
/// Transforms an XML name into an object name (such as DataTable or DataColumn).</para>
/// </devdoc>
-
- public static string DecodeName(string name)
+ [return: NotNullIfNotNull("name")]
+ 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();
}
int matchPos = -1;
if (en != null && en.MoveNext())
{
- Match m = (Match)en.Current;
+ Match m = (Match)en.Current!;
matchPos = m.Index;
}
{
if (position == matchPos)
{
- if (en.MoveNext())
+ if (en!.MoveNext())
{
- Match m = (Match)en.Current;
+ Match m = (Match)en.Current!;
matchPos = m.Index;
}
{
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)
+ [return: NotNullIfNotNull("name")]
+ 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();
}
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] != ':'))) ||
{
bufBld = new StringBuilder(length + 20);
}
+
bufBld.Append("_x");
if (length > 1 && XmlCharType.IsHighSurrogate(name[0]) && XmlCharType.IsLowSurrogate(name[1]))
{
position++;
if (matchPos == 0)
- if (en.MoveNext())
+ if (en!.MoveNext())
{
- Match m = (Match)en.Current;
+ Match m = (Match)en.Current!;
matchPos = m.Index - 1;
}
}
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;
}
{
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')
{
throw new ArgumentNullException(nameof(s));
}
+
return BinHexDecoder.Decode(s.ToCharArray(), allowOddCount);
}
{
throw new ArgumentNullException(nameof(inArray));
}
+
return BinHexEncoder.Encode(inArray, 0, inArray.Length);
}
{
throw new ArgumentNullException(nameof(name));
}
+
if (name.Length == 0)
{
throw new ArgumentNullException(nameof(name), SR.Xml_EmptyName);
// 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);
}
{
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));
}
{
throw CreateException(SR.Xml_BadNameChar, XmlException.BuildCharExceptionArgs(name, endPos), exceptionType, 0, endPos + 1);
}
+
return name;
}
{
throw new ArgumentNullException(nameof(name));
}
+
if (name.Length == 0)
{
throw new ArgumentNullException(nameof(name), SR.Xml_EmptyLocalName);
return name;
}
- internal static Exception TryVerifyNCName(string name)
+ internal static Exception? TryVerifyNCName(string name)
{
int len = ValidateNames.ParseNCName(name);
{
return ValidateNames.GetInvalidNameException(name, 0, len);
}
+
return null;
}
/// <para>
/// </para>
/// </devdoc>
- public static string VerifyTOKEN(string token)
+ [return: NotNullIfNotNull("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);
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;
}
{
throw new ArgumentNullException(nameof(name));
}
+
if (name.Length == 0)
{
throw CreateException(SR.Xml_InvalidNmToken, name, exceptionType);
{
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;
}
{
throw new ArgumentNullException(nameof(content));
}
+
VerifyCharData(content, ExceptionType.XmlException);
return content;
}
{
throw new XmlException(SR.Xml_InvalidWhitespaceCharacter, XmlException.BuildCharExceptionArgs(content, pos), 0, pos + 1);
}
+
return content;
}
{
return ("-0");
}
+
return value.ToString("R", NumberFormatInfo.InvariantInfo);
}
default:
throw new ArgumentException(SR.Format(SR.Sch_InvalidDateTimeOption, dateTimeOption, nameof(dateTimeOption)));
}
+
XsdDateTime xsdDateTime = new XsdDateTime(value, XsdDateTimeFlags.DateTime);
return xsdDateTime.ToString();
}
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")
result = true;
return null;
}
+
result = false;
return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Boolean"));
}
{
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
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;
}
{
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")
{
return new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Single"));
}
+
if (result == 0 && s[0] == '-')
{
result = -0f;
}
+
return null;
}
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")
{
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] != '+')
}
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);
{
}
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;
}
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)
}
// 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
{
CreateAllDateTimeFormats();
}
- return s_allDateTimeFormats;
+
+ return s_allDateTimeFormats!;
}
}
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;
{
exception = new FormatException(SR.Format(SR.XmlConvert_BadFormat, s, "Guid"));
}
+
return exception;
}
_ => 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;
{
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;
}
internal static string EscapeValueForDebuggerDisplay(string value)
{
- StringBuilder sb = null;
+ StringBuilder? sb = null;
int i = 0;
int start = 0;
while (i < value.Length)
}
i++;
}
+
if (sb == null)
{
return value;
}
+
if (i - start > 0)
{
sb.Append(value, start, i - start);
}
+
return sb.ToString();
}
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);
}
// 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;
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;
}
{
Buffer.BlockCopy(bytes, byteIndex, chars, charIndex * CharSize, byteCount);
}
+
return charCount;
}
{
Buffer.BlockCopy(bytes, byteIndex, chars, charIndex * CharSize, (int)(byteCount & ~0x1));
}
+
charsUsed += byteCount / CharSize;
bytesUsed += byteCount;
internal class Ucs4Encoding : Encoding
{
- internal Ucs4Decoder ucs4Decoder;
+ internal Ucs4Decoder ucs4Decoder = null!; // assigned in the derived classes
public override string WebName
{
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)
{
public override Encoder GetEncoder()
{
- return null;
+ return null!;
}
internal static Encoding UCS4_Littleendian
return "ucs-4 (order 2143)";
}
}
+
public override byte[] GetPreamble()
{
return new byte[4] { 0x00, 0x00, 0xff, 0xfe };
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);
{
lastBytes[j] = bytes[byteIndex + byteCount - bytesLeft + j];
}
+
lastBytesCount = bytesLeft;
}
+
return i;
}
byteCount--;
bytesUsed++;
}
+
// still not enough bytes -> return
if (lbc < 4)
{
completed = true;
return;
}
+
// decode 1 character from the byte cache
i = GetFullChars(lastBytes, 0, 4, chars, charIndex);
{
completed = true;
}
+
bytesUsed += byteCount;
// decode block of byte quadruplets
{
lastBytes[j] = bytes[byteIndex + byteCount - bytesLeft + j];
}
+
lastBytesCount = bytesLeft;
}
}
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)
{
chars[j] = (char)code;
}
}
+
j++;
i += 4;
}
+
return j - charIndex;
}
- };
+ }
internal class Ucs4Decoder1234 : Ucs4Decoder
{
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)
{
chars[j] = (char)code;
}
}
+
j++;
i += 4;
}
+
return j - charIndex;
}
}
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)
{
chars[j] = (char)code;
}
}
+
j++;
i += 4;
}
+
return j - charIndex;
}
}
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)
{
chars[j] = (char)code;
}
}
+
j++;
i += 4;
}
+
return j - charIndex;
}
}
// 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
{
/// <devdoc>
// 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
// 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
{
/// <devdoc>
// 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
// 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);
}
// 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;
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
- public XmlQualifiedName(string name) : this(name, string.Empty) { }
+ public XmlQualifiedName(string? name) : this(name, string.Empty) { }
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
- 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;
}
/// <devdoc>
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
- 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;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
- 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;
}
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
- public static bool operator !=(XmlQualifiedName a, XmlQualifiedName b)
+ public static bool operator !=(XmlQualifiedName? a, XmlQualifiedName? b)
{
return !(a == b);
}
}
// --------- 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()
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)
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();
// 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
{
/// <summary>
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;
}
}
// 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 abstract partial class XmlResolver
{
public virtual Task<object> GetEntityAsync(Uri absoluteUri,
- string role,
- Type ofObjectToReturn)
+ string? role,
+ Type? ofObjectToReturn)
{
throw new NotImplementedException();
}
}
-}
\ No newline at end of file
+}
// 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;
{
private readonly XmlResolver _resolver;
- public XmlSecureResolver(XmlResolver resolver, string securityUrl)
+ public XmlSecureResolver(XmlResolver resolver, string? securityUrl)
{
_resolver = resolver;
}
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);
}
// 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<object> GetEntityAsync(Uri absoluteUri, string role, Type ofObjectToReturn)
+ public override Task<object> GetEntityAsync(Uri absoluteUri, string? role, Type? ofObjectToReturn)
{
return _resolver.GetEntityAsync(absoluteUri, role, ofObjectToReturn);
}
public partial class XmlUrlResolver : XmlResolver
{
// Maps a URI to an Object containing the actual resource.
- public override async Task<object> GetEntityAsync(Uri absoluteUri, string role, Type? ofObjectToReturn)
+ public override async Task<object> GetEntityAsync(Uri absoluteUri, string? role, Type? ofObjectToReturn)
{
if (ofObjectToReturn == null || ofObjectToReturn == typeof(System.IO.Stream) || ofObjectToReturn == typeof(object))
{
// 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.Generic;
using System.Diagnostics;
[EditorBrowsable(EditorBrowsableState.Never)]
public struct StringConcat
{
- private string _s1, _s2, _s3, _s4;
- private string _delimiter;
- private List<string> _strList;
+ private string? _s1, _s2, _s3, _s4;
+ private string? _delimiter;
+ private List<string?>? _strList;
private int _idxStr;
/// <summary>
/// <summary>
/// Gets or sets the string that delimits concatenated strings.
/// </summary>
- public string Delimiter
+ public string? Delimiter
{
get { return _delimiter; }
set { _delimiter = value; }
_idxStr switch
{
0 => string.Empty,
- 1 => _s1,
+ 1 => _s1 ?? string.Empty,
2 => string.Concat(_s1, _s2),
3 => string.Concat(_s1, _s2, _s3),
4 => string.Concat(_s1, _s2, _s3, _s4),
- _ => string.Concat(_strList.ToArray()),
+ _ => string.Concat(_strList!.ToArray()),
};
/// <summary>
/// Concatenate a new string to the result without adding a delimiter.
/// </summary>
- internal void ConcatNoDelimiter(string s)
+ internal void ConcatNoDelimiter(string? s)
{
switch (_idxStr)
{
case 4:
// Calling Clear() is expensive, allocate a new List instead
int capacity = (_strList == null) ? 8 : _strList.Count;
- List<string> strList = _strList = new List<string>(capacity);
+ List<string?> strList = _strList = new List<string?>(capacity);
strList.Add(_s1);
strList.Add(_s2);
strList.Add(_s3);
strList.Add(_s4);
goto default;
default:
- _strList.Add(s);
+ _strList!.Add(s);
break;
}