// 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
/*
These HRESULTs are used for mapping managed exceptions to COM error codes
and vice versa through COM Interop. For background on COM error codes see
// 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.IO;
XSD_UNSIGNEDLONG = 0x8B,
XSD_QNAME = 0x8C,
}
-}
\ 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
using System;
using System.Collections;
using System.IO;
11 => 2,
15 => 3,
19 => 4,
- _ => throw new XmlException(SR.XmlBinary_InvalidSqlDecimal, (string[])null),
+ _ => throw new XmlException(SR.XmlBinary_InvalidSqlDecimal, (string[]?)null),
};
m_bPrec = data[offset + 1];
m_bScale = data[offset + 2];
iulR = ulCarry;
MpNormalize(rgulU, ref ciulU);
}
+
// Normalize multi-precision number - remove leading zeroes
private static void MpNormalize(uint[] rgulU, // In | Number
ref int ciulU // InOut| # of digits
private static ReadOnlySpan<byte> RgCLenFromPrec => new byte[] { // rely on C# compiler optimization to eliminate allocation
1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4
};
+
private static byte CLenFromPrec(byte bPrec)
{
Debug.Assert(bPrec <= s_maxPrecision && bPrec > 0, "bPrec <= MaxPrecision && bPrec > 0", "Invalid numeric precision");
public decimal ToDecimal()
{
if ((int)m_data4 != 0 || m_bScale > 28)
- throw new XmlException(SR.SqlTypes_ArithOverflow, (string)null);
+ throw new XmlException(SR.SqlTypes_ArithOverflow, (string?)null);
return new decimal((int)m_data1, (int)m_data2, (int)m_data3, !IsPositive, m_bScale);
}
goto Error;
return;
Error:
- throw new XmlException(SR.SqlTypes_ArithOverflow, (string)null);
+ throw new XmlException(SR.SqlTypes_ArithOverflow, (string?)null);
}
private static void BreakDownXsdDate(long val, out int yr, out int mnth, out int day, out bool negTimeZone, out int hr, out int min)
goto Error;
return;
Error:
- throw new XmlException(SR.SqlTypes_ArithOverflow, (string)null);
+ throw new XmlException(SR.SqlTypes_ArithOverflow, (string?)null);
}
private static void BreakDownXsdTime(long val, out int hr, out int min, out int sec, out int ms)
goto Error;
return;
Error:
- throw new XmlException(SR.SqlTypes_ArithOverflow, (string)null);
+ throw new XmlException(SR.SqlTypes_ArithOverflow, (string?)null);
}
public static string XsdDateTimeToString(long val)
}
else
{
- throw new XmlException(SR.SqlTypes_ArithOverflow, (string)null);
+ throw new XmlException(SR.SqlTypes_ArithOverflow, (string?)null);
}
return timeTicks * KatmaiTimeScaleMultiplicator[scale];
}
// 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;
internal static readonly Type TypeOfObject = typeof(object);
internal static readonly Type TypeOfString = typeof(string);
- private static volatile Type[] s_tokenTypeMap = null;
+ private static volatile Type?[]? s_tokenTypeMap;
private static ReadOnlySpan<byte> XsdKatmaiTimeScaleToValueLengthMap => new byte[8] { // rely on C# compiler optimization to eliminate allocation
// length scale
{
return lname == this.localname && nsUri == this.namespaceUri;
}
+
public bool MatchPrefix(string prefix, string lname)
{
return lname == this.localname && prefix == this.prefix;
}
- public override bool Equals(object other)
+ public override bool Equals(object? other)
{
if (other is QName)
{
private struct ElemInfo
{
public QName name;
- public string xmlLang;
+ public string? xmlLang;
public XmlSpace xmlSpace;
public bool xmlspacePreserve;
- public NamespaceDecl nsdecls;
+ public NamespaceDecl? nsdecls;
public void Set(QName name, bool xmlspacePreserve)
{
this.xmlSpace = XmlSpace.None;
this.xmlspacePreserve = xmlspacePreserve;
}
- public NamespaceDecl Clear()
+ public NamespaceDecl? Clear()
{
- NamespaceDecl nsdecls = this.nsdecls;
+ NamespaceDecl? nsdecls = this.nsdecls;
this.nsdecls = null;
return nsdecls;
}
private struct AttrInfo
{
public QName name;
- public string val;
+ public string? val;
public int contentPos;
public int hashCode;
public int prevHash;
this.hashCode = 0;
this.prevHash = 0;
}
+
public void Set(QName n, int pos)
{
this.name = n;
{
public string prefix;
public string uri;
- public NamespaceDecl scopeLink;
- public NamespaceDecl prevLink;
+ public NamespaceDecl? scopeLink;
+ public NamespaceDecl? prevLink;
public int scope;
public bool implied;
public NamespaceDecl(string prefix, string nsuri,
- NamespaceDecl nextInScope, NamespaceDecl prevDecl,
+ NamespaceDecl? nextInScope, NamespaceDecl? prevDecl,
int scope, bool implied)
{
this.prefix = prefix;
this.qnameCount = 1;
}
}
+
private class NestedBinXml
{
public SymbolTables symbolTables;
public int docState;
- public NestedBinXml next;
- public NestedBinXml(SymbolTables symbolTables, int docState, NestedBinXml next)
+ public NestedBinXml? next;
+ public NestedBinXml(SymbolTables symbolTables, int docState, NestedBinXml? next)
{
this.symbolTables = symbolTables;
this.docState = docState;
private bool _hasTypedValue;
private System.Type _valueType;
// if it is a simple string value, we cache it
- private string _stringValue;
+ private string? _stringValue;
// hashtable of current namespaces
private readonly Dictionary<string, NamespaceDecl> _namespaces;
//Hashtable namespaces;
// linked list of pushed nametables (to support nested binary-xml documents)
- private NestedBinXml _prevNameInfo;
+ private NestedBinXml? _prevNameInfo;
// XmlTextReader to handle embeded text blocks
- private XmlReader _textXmlReader;
+ private XmlReader? _textXmlReader;
// close input flag
private readonly bool _closeInput;
// current version of the protocol
private byte _version;
- public XmlSqlBinaryReader(System.IO.Stream stream, byte[] data, int len, string baseUri, bool closeInput, XmlReaderSettings settings)
+ public XmlSqlBinaryReader(Stream stream, byte[] data, int len, string baseUri, bool closeInput, XmlReaderSettings settings)
{
_unicode = System.Text.Encoding.Unicode;
_xmlCharType = XmlCharType.Instance;
- _xnt = settings.NameTable;
+ _xnt = settings.NameTable!;
if (_xnt == null)
{
_xnt = new NameTable();
_ignorePIs = settings.IgnoreProcessingInstructions;
_ignoreComments = settings.IgnoreComments;
- if (s_tokenTypeMap == null)
- GenerateTokenTypeMap();
+ s_tokenTypeMap = s_tokenTypeMap ?? GenerateTokenTypeMap();
}
public override XmlReaderSettings Settings
get
{
if (ScanState.XmlText == _state)
+ {
+ Debug.Assert(_textXmlReader != null);
return _textXmlReader.HasValue;
+ }
else
return XmlReader.HasValueInternal(_nodetype);
}
break;
case ScanState.XmlText:
- return _textXmlReader.Value;
+ {
+ Debug.Assert(_textXmlReader != null);
+ return _textXmlReader.Value;
+ }
case ScanState.Attr:
case ScanState.AttrValPseudoValue:
break;
case ScanState.XmlText:
+ Debug.Assert(_textXmlReader != null);
adj = _textXmlReader.Depth;
break;
}
else
{
+ Debug.Assert(_textXmlReader != null);
return _textXmlReader.XmlSpace;
}
}
{
for (int i = _elemDepth; i >= 0; i--)
{
- string xl = _elementStack[i].xmlLang;
+ string? xl = _elementStack[i].xmlLang;
if (null != xl)
return xl;
}
}
else
{
+ Debug.Assert(_textXmlReader != null);
return _textXmlReader.XmlLang;
}
}
case ScanState.AttrValPseudoValue:
return _attrCount;
case ScanState.XmlText:
- return _textXmlReader.AttributeCount;
+ {
+ Debug.Assert(_textXmlReader != null);
+ return _textXmlReader.AttributeCount;
+ }
default:
return 0;
}
}
}
- public override string GetAttribute(string name, string ns)
+ public override string? GetAttribute(string name, string ns)
{
if (ScanState.XmlText == _state)
{
+ Debug.Assert(_textXmlReader != null);
return _textXmlReader.GetAttribute(name, ns);
}
else
}
}
- public override string GetAttribute(string name)
+ public override string? GetAttribute(string name)
{
if (ScanState.XmlText == _state)
{
+ Debug.Assert(_textXmlReader != null);
return _textXmlReader.GetAttribute(name);
}
else
{
if (ScanState.XmlText == _state)
{
+ Debug.Assert(_textXmlReader != null);
return _textXmlReader.GetAttribute(i);
}
else
{
if (ScanState.XmlText == _state)
{
+ Debug.Assert(_textXmlReader != null);
return UpdateFromTextReader(_textXmlReader.MoveToAttribute(name, ns));
}
else
{
if (ScanState.XmlText == _state)
{
+ Debug.Assert(_textXmlReader != null);
return UpdateFromTextReader(_textXmlReader.MoveToAttribute(name));
}
else
{
if (ScanState.XmlText == _state)
{
+ Debug.Assert(_textXmlReader != null);
_textXmlReader.MoveToAttribute(i);
UpdateFromTextReader(true);
}
{
if (ScanState.XmlText == _state)
{
+ Debug.Assert(_textXmlReader != null);
return UpdateFromTextReader(_textXmlReader.MoveToFirstAttribute());
}
else
return true;
case ScanState.XmlText:
+ Debug.Assert(_textXmlReader != null);
return UpdateFromTextReader(_textXmlReader.MoveToNextAttribute());
default:
return true;
case ScanState.XmlText:
+ Debug.Assert(_textXmlReader != null);
return UpdateFromTextReader(_textXmlReader.MoveToElement());
default:
return false;
case ScanState.XmlText:
+ Debug.Assert(_textXmlReader != null);
return UpdateFromTextReader(_textXmlReader.ReadAttributeValue());
default:
_textXmlReader.Close();
_textXmlReader = null;
}
+
if (null != _inStrm && _closeInput)
_inStrm.Dispose();
- _inStrm = null;
+ _inStrm = null!;
_pos = _end = 0;
}
}
}
- public override string LookupNamespace(string prefix)
+ public override string? LookupNamespace(string prefix)
{
if (ScanState.XmlText == _state)
+ {
+ Debug.Assert(_textXmlReader != null);
return _textXmlReader.LookupNamespace(prefix);
- NamespaceDecl decl;
+ }
+
+ NamespaceDecl? decl;
if (prefix != null && _namespaces.TryGetValue(prefix, out decl))
{
Debug.Assert(decl != null);
return ReadDoc();
case ScanState.XmlText:
+ Debug.Assert(_textXmlReader != null);
+
if (_textXmlReader.Read())
{
return UpdateFromTextReader(true);
}
+
_state = ScanState.Doc;
_nodetype = XmlNodeType.None;
_isEmpty = false;
{
if (ScanState.XmlText == _state)
{
+ Debug.Assert(_textXmlReader != null);
IXmlNamespaceResolver resolver = (IXmlNamespaceResolver)_textXmlReader;
return resolver.GetNamespacesInScope(scope);
}
// are we even inside an element? (depth==0 is where we have xml, and xmlns declared...)
if (_elemDepth > 0)
{
- NamespaceDecl nsdecl = _elementStack[_elemDepth].nsdecls;
+ NamespaceDecl? nsdecl = _elementStack[_elemDepth].nsdecls;
while (null != nsdecl)
{
nstable.Add(nsdecl.prefix, nsdecl.uri);
}
}
- string IXmlNamespaceResolver.LookupPrefix(string namespaceName)
+ string? IXmlNamespaceResolver.LookupPrefix(string namespaceName)
{
if (ScanState.XmlText == _state)
{
+ Debug.Assert(_textXmlReader != null);
IXmlNamespaceResolver resolver = (IXmlNamespaceResolver)_textXmlReader;
return resolver.LookupPrefix(namespaceName);
}
if (null == namespaceName)
return null;
- namespaceName = _xnt.Get(namespaceName);
- if (null == namespaceName)
+ string? atomizedNamespaceName = _xnt.Get(namespaceName);
+ if (null == atomizedNamespaceName)
return null;
for (int i = _elemDepth; i >= 0; i--)
{
- NamespaceDecl nsdecl = _elementStack[i].nsdecls;
+ NamespaceDecl? nsdecl = _elementStack[i].nsdecls;
while (null != nsdecl)
{
- if ((object)nsdecl.uri == (object)namespaceName)
+ if ((object)nsdecl.uri == (object?)atomizedNamespaceName)
return nsdecl.prefix;
nsdecl = nsdecl.scopeLink;
}
qnametable[qnameNum].Set(prefixStr, lnameStr, nsUriStr);
return;
BadDecl:
- throw new XmlException(SR.Xml_BadNamespaceDecl, (string[])null);
+ throw new XmlException(SR.Xml_BadNamespaceDecl, (string[]?)null);
}
private void NameFlush()
{
Debug.Assert(pos >= 0 && cch >= 0);
if (checked(pos + (cch * 2)) > _end)
- throw new XmlException(SR.Xml_UnexpectedEOF1, (string[])null);
+ throw new XmlException(SR.Xml_UnexpectedEOF1, (string[]?)null);
if (cch == 0)
return string.Empty;
// GetStringUnaligned is _significantly_ faster than unicode.GetString()
private string GetAttributeText(int i)
{
- string val = _attributes[i].val;
+ string? val = _attributes[i].val;
if (null != val)
return val;
if (prefix == "xml")
return;
int elemDepth = _elemDepth;
- NamespaceDecl curDecl;
+ NamespaceDecl? curDecl;
_namespaces.TryGetValue(prefix, out curDecl);
if (null != curDecl)
{
_namespaces[prefix] = decl;
}
- private void PopNamespaces(NamespaceDecl firstInScopeChain)
+ private void PopNamespaces(NamespaceDecl? firstInScopeChain)
{
- NamespaceDecl decl = firstInScopeChain;
+ NamespaceDecl? decl = firstInScopeChain;
while (null != decl)
{
if (null == decl.prevLink)
_namespaces.Remove(decl.prefix);
else
_namespaces[decl.prefix] = decl.prevLink;
- NamespaceDecl next = decl.scopeLink;
+ NamespaceDecl? next = decl.scopeLink;
// unlink chains for better gc behaviour
decl.prevLink = null;
decl.scopeLink = null;
private void GenerateImpliedXmlnsAttrs()
{
QName name;
- NamespaceDecl decl = _elementStack[_elemDepth].nsdecls;
+ NamespaceDecl? decl = _elementStack[_elemDepth].nsdecls;
while (null != decl)
{
if (decl.implied)
private bool ReadInit(bool skipXmlDecl)
{
- string err = null;
+ string? err = null;
if (!_sniffed)
{
// check magic header
Error:
_state = ScanState.Error;
- throw new XmlException(err, (string[])null);
+ throw new XmlException(err, (string[]?)null);
}
private void ScanAttributes()
int xmllang = -1;
_mark = _pos;
- string curDeclPrefix = null;
+ string? curDeclPrefix = null;
bool lastWasValue = false;
while (BinXmlToken.EndAttrs != (token = NextToken()))
// if char checking is on, we need to scan text values to
// validate that they don't use invalid CharData, so we
// might as well store the saved string for quick attr value access
- string val = _stringValue;
+ string? val = _stringValue;
+
if (null != val)
{
_attributes[_attrCount - 1].val = val;
_stringValue = null;
}
+
// namespace decls can only have text values, and should only
// have a single value, so we just grab it here...
if (null != curDeclPrefix)
PushNamespace(curDeclPrefix, nsuri, false);
curDeclPrefix = null;
}
+
lastWasValue = true;
}
}
next = _attributes[next].prevHash;
}
}
+
Array.Clear(_attrHashTbl, 0, tblSize);
}
Debug.Assert(_stringValue == null, "this.stringValue == null");
Debug.Assert(_token == BinXmlToken.CData, "this.token == BinXmlToken.CData");
string value = GetString(_tokDataPos, _tokLen);
- StringBuilder sb = null;
+ StringBuilder? sb = null;
while (PeekToken() == BinXmlToken.CData)
{
_pos++; // skip over token byte
private void FinishEndElement()
{
- NamespaceDecl nsdecls = _elementStack[_elemDepth].Clear();
+ NamespaceDecl? nsdecls = _elementStack[_elemDepth].Clear();
this.PopNamespaces(nsdecls);
_elemDepth--;
}
{
case BinXmlToken.EOF:
if (_elemDepth > 0)
- throw new XmlException(SR.Xml_UnexpectedEOF1, (string[])null);
+ throw new XmlException(SR.Xml_UnexpectedEOF1, (string[]?)null);
_state = ScanState.EOF;
return false;
private void ImplReadEndNest()
{
+ Debug.Assert(_prevNameInfo != null);
NestedBinXml nested = _prevNameInfo;
_symbolTables = nested.symbolTables;
_docState = nested.docState;
if (decl.scope > 0)
{
#if DEBUG
- if ((object)decl.prefix != (object)this._xnt.Get(decl.prefix))
+ if ((object)decl.prefix != (object?)this._xnt.Get(decl.prefix))
throw new Exception("Prefix not interned: \'" + decl.prefix + "\'");
- if ((object)decl.uri != (object)this._xnt.Get(decl.uri))
+ if ((object)decl.uri != (object?)this._xnt.Get(decl.uri))
throw new Exception("Uri not interned: \'" + decl.uri + "\'");
#endif
xnm.AddNamespace(decl.prefix, decl.uri);
private void UpdateFromTextReader()
{
+ Debug.Assert(_textXmlReader != null);
XmlReader r = _textXmlReader;
_nodetype = r.NodeType;
_qnameOther.prefix = r.Prefix;
}
}
- private void GenerateTokenTypeMap()
+ private Type?[] GenerateTokenTypeMap()
{
- Type[] map = new Type[256];
+ Type?[] map = new Type[256];
map[(int)BinXmlToken.XSD_BOOLEAN] = typeof(bool);
map[(int)BinXmlToken.SQL_TINYINT] = typeof(byte);
map[(int)BinXmlToken.XSD_BYTE] = typeof(sbyte);
map[(int)BinXmlToken.SQL_NVARCHAR] = TypeOfString;
map[(int)BinXmlToken.SQL_NTEXT] = TypeOfString;
map[(int)BinXmlToken.SQL_UUID] = TypeOfString;
- if (s_tokenTypeMap == null)
- s_tokenTypeMap = map;
+ return map;
}
private System.Type GetValueType(BinXmlToken token)
{
- Type t = s_tokenTypeMap[(int)token];
+ Debug.Assert(s_tokenTypeMap != null);
+ Type? t = s_tokenTypeMap[(int)token];
+
if (t == null)
throw ThrowUnexpectedToken(token);
+
return t;
}
{
if (scale > 7)
{
- throw new XmlException(SR.SqlTypes_ArithOverflow, (string)null);
+ throw new XmlException(SR.SqlTypes_ArithOverflow, (string?)null);
}
return XsdKatmaiTimeScaleToValueLengthMap[scale];
}
private Exception ThrowXmlException(string res)
{
_state = ScanState.Error;
- return new XmlException(res, (string[])null);
+ return new XmlException(res, (string[]?)null);
}
private Exception ThrowXmlException(string res, string arg1, string arg2)
// 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;
using System.Globalization;
//
internal class CharEntityEncoderFallback : EncoderFallback
{
- private CharEntityEncoderFallbackBuffer _fallbackBuffer;
+ private CharEntityEncoderFallbackBuffer? _fallbackBuffer;
- private int[] _textContentMarks;
+ private int[]? _textContentMarks;
private int _endMarkPos;
private int _curMarkPos;
private int _startOffset;
internal bool CanReplaceAt(int index)
{
+ Debug.Assert(_textContentMarks != null);
+
int mPos = _curMarkPos;
int charPos = _startOffset + index;
while (mPos < _endMarkPos && charPos >= _textContentMarks[mPos + 1])
// 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 ConformanceLevel
// 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
{
// DtdProcessing enumerations specifies how will an XmlReader handle DTDs in the XML document.
// 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
{
// Specifies how entities are handled in XmlTextReader and XmlValidatingReader.
// 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
// This file is generated by TernaryTreeGenerator.cs,
// and is used by the TernaryTreeRO class.
// 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;
/// <param name="prefix">The prefix of the attribute list to look for</param>
/// <param name="localName">The local name of the attribute list to look for</param>
/// <returns>Interface representing an attribute list or null if none was found.</returns>
- IDtdAttributeListInfo LookupAttributeList(string prefix, string localName);
+ IDtdAttributeListInfo? LookupAttributeList(string prefix, string localName);
/// <summary>
/// Returns an enumerator of all attribute lists defined in the DTD.
// 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;
// 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.Text;
using System.Xml.Schema;
internal partial interface IDtdParserAdapter
{
XmlNameTable NameTable { get; }
- IXmlNamespaceResolver NamespaceResolver { get; }
+ IXmlNamespaceResolver? NamespaceResolver { get; }
- Uri BaseUri { get; }
+ Uri? BaseUri { get; }
- char[] ParsingBuffer { get; }
+ char[]? ParsingBuffer { get; }
int ParsingBufferLength { get; }
int CurrentPosition { get; set; }
int LineNo { get; }
bool PushEntity(IDtdEntityInfo entity, out int entityId);
- bool PopEntity(out IDtdEntityInfo oldEntity, out int newEntityId);
+ bool PopEntity(out IDtdEntityInfo? oldEntity, out int newEntityId);
bool PushExternalSubset(string systemId, string publicId);
internal interface IDtdParserAdapterWithValidation : IDtdParserAdapter
{
bool DtdValidation { get; }
- IValidationEventHandling ValidationEventHandling { get; }
+ IValidationEventHandling? ValidationEventHandling { get; }
}
internal interface IDtdParserAdapterV1 : IDtdParserAdapterWithValidation
// 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.Text;
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.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
namespace System.Xml
{
// NewLineHandling specifies what will XmlWriter do with new line characters. The options are:
// 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
{
// Specifies the state of the XmlReader.
// 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
{
// Specifies the type of validation to perform in XmlValidatingReader or in XmlReaderSettings.
// 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
{
// Specifies how whitespace is handled in XmlTextReader.
// 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.Xml;
using System.Text;
using System;
// Specifies the context that the XmLReader will use for xml fragment
public class XmlParserContext
{
- private XmlNameTable _nt = null;
- private XmlNamespaceManager _nsMgr = null;
+ private XmlNameTable? _nt = null;
+ private XmlNamespaceManager? _nsMgr = null;
private string _docTypeName = string.Empty;
private string _pubId = string.Empty;
private string _sysId = string.Empty;
private string _xmlLang = string.Empty;
private XmlSpace _xmlSpace;
private string _baseURI = string.Empty;
- private Encoding _encoding = null;
+ private Encoding? _encoding = null;
public XmlParserContext(XmlNameTable nt, XmlNamespaceManager nsMgr, string xmlLang, XmlSpace xmlSpace)
: this(nt, nsMgr, null, null, null, null, string.Empty, xmlLang, xmlSpace)
// Intentionally Empty
}
- public XmlParserContext(XmlNameTable nt, XmlNamespaceManager nsMgr, string docTypeName,
- string pubId, string sysId, string internalSubset, string baseURI,
+ public XmlParserContext(XmlNameTable nt, XmlNamespaceManager nsMgr, string? docTypeName,
+ string? pubId, string? sysId, string? internalSubset, string baseURI,
string xmlLang, XmlSpace xmlSpace)
: this(nt, nsMgr, docTypeName, pubId, sysId, internalSubset, baseURI, xmlLang, xmlSpace, null)
{
// Intentionally Empty
}
- public XmlParserContext(XmlNameTable nt, XmlNamespaceManager nsMgr, string docTypeName,
- string pubId, string sysId, string internalSubset, string baseURI,
- string xmlLang, XmlSpace xmlSpace, Encoding enc)
+ public XmlParserContext(XmlNameTable nt, XmlNamespaceManager? nsMgr, string? docTypeName,
+ string? pubId, string? sysId, string? internalSubset, string baseURI,
+ string xmlLang, XmlSpace xmlSpace, Encoding? enc)
{
if (nsMgr != null)
{
}
else
{
- if ((object)nt != (object)nsMgr.NameTable)
+ if ((object)nt != (object?)nsMgr.NameTable)
{
throw new XmlException(SR.Xml_NotSameNametable, string.Empty);
}
_encoding = enc;
}
- public XmlNameTable NameTable
+ public XmlNameTable? NameTable
{
get
{
}
}
- public XmlNamespaceManager NamespaceManager
+ public XmlNamespaceManager? NamespaceManager
{
get
{
}
}
- public Encoding Encoding
+ public Encoding? Encoding
{
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.Collections;
using System.Diagnostics;
using System.Globalization;
internal const int AsyncBufferSize = 64 * 1024; //64KB
// Settings
- public virtual XmlReaderSettings Settings
+ public virtual XmlReaderSettings? Settings
{
get
{
public abstract int Depth { get; }
// Gets the base URI of the current node.
- public abstract string BaseURI { get; }
+ public abstract string? BaseURI { get; }
// Gets a value indicating whether the current node is an empty element (for example, <MyElement/>).
public abstract bool IsEmptyElement { get; }
}
// returns the schema info interface of the reader
- public virtual IXmlSchemaInfo SchemaInfo
+ public virtual IXmlSchemaInfo? SchemaInfo
{
get
{
{
throw CreateReadContentAsException(nameof(ReadContentAsBoolean));
}
+
try
{
return XmlConvert.ToBoolean(InternalReadContentAsString());
{
throw CreateReadContentAsException(nameof(ReadContentAsDateTime));
}
+
try
{
return XmlConvert.ToDateTime(InternalReadContentAsString(), XmlDateTimeSerializationMode.RoundtripKind);
{
throw CreateReadContentAsException(nameof(ReadContentAsDateTimeOffset));
}
+
try
{
return XmlConvert.ToDateTimeOffset(InternalReadContentAsString());
{
throw CreateReadContentAsException(nameof(ReadContentAsDouble));
}
+
try
{
return XmlConvert.ToDouble(InternalReadContentAsString());
{
throw CreateReadContentAsException(nameof(ReadContentAsFloat));
}
+
try
{
return XmlConvert.ToSingle(InternalReadContentAsString());
{
throw CreateReadContentAsException(nameof(ReadContentAsDecimal));
}
+
try
{
return XmlConvert.ToDecimal(InternalReadContentAsString());
{
throw CreateReadContentAsException(nameof(ReadContentAsInt));
}
+
try
{
return XmlConvert.ToInt32(InternalReadContentAsString());
{
throw CreateReadContentAsException(nameof(ReadContentAsLong));
}
+
try
{
return XmlConvert.ToInt64(InternalReadContentAsString());
{
throw CreateReadContentAsException(nameof(ReadContentAsString));
}
+
return InternalReadContentAsString();
}
FinishReadElementContentAsXxx();
return value;
}
+
return string.Empty;
}
FinishReadElementContentAsXxx();
return value;
}
+
return XmlConvert.ToBoolean(string.Empty);
}
FinishReadElementContentAsXxx();
return value;
}
+
return XmlConvert.ToDateTime(string.Empty, XmlDateTimeSerializationMode.RoundtripKind);
}
FinishReadElementContentAsXxx();
return value;
}
+
return XmlConvert.ToDouble(string.Empty);
}
FinishReadElementContentAsXxx();
return value;
}
+
return XmlConvert.ToSingle(string.Empty);
}
FinishReadElementContentAsXxx();
return value;
}
+
return string.Empty;
}
FinishReadElementContentAsXxx();
return value;
}
+
return (returnType == typeof(string)) ? string.Empty : XmlUntypedStringConverter.Instance.FromString(string.Empty, returnType, namespaceResolver);
}
public abstract int AttributeCount { get; }
// Gets the value of the attribute with the specified Name
- public abstract string GetAttribute(string name);
+ public abstract string? GetAttribute(string name);
// Gets the value of the attribute with the LocalName and NamespaceURI
- public abstract string GetAttribute(string name, string namespaceURI);
+ public abstract string? GetAttribute(string name, string namespaceURI);
// Gets the value of the attribute with the specified index.
public abstract string GetAttribute(int i);
}
// Gets the value of the attribute with the specified Name.
- public virtual string this[string name]
+ public virtual string? this[string name]
{
get
{
}
// Gets the value of the attribute with the LocalName and NamespaceURI
- public virtual string this[string name, string namespaceURI]
+ public virtual string? this[string name, string namespaceURI]
{
get
{
public abstract XmlNameTable NameTable { get; }
// Resolves a namespace prefix in the current element's scope.
- public abstract string LookupNamespace(string prefix);
+ public abstract string? LookupNamespace(string prefix);
// Returns true if the XmlReader can expand general entities.
public virtual bool CanResolveEntity
private void SetNamespacesFlag(XmlTextWriter xtw)
{
- XmlTextReader tr = this as XmlTextReader;
+ XmlTextReader? tr = this as XmlTextReader;
if (tr != null)
{
xtw.Namespaces = tr.Namespaces;
else
{
#pragma warning disable 618
- XmlValidatingReader vr = this as XmlValidatingReader;
+ XmlValidatingReader? vr = this as XmlValidatingReader;
if (vr != null)
{
xtw.Namespaces = vr.Namespaces;
{
throw new InvalidOperationException(SR.Xml_ReadSubtreeNotOnElement);
}
+
return new XmlSubtreeReader(this);
}
// Internal methods
//
// Validation support
- internal virtual XmlNamespaceManager NamespaceManager
+ internal virtual XmlNamespaceManager? NamespaceManager
{
get
{
return CanReadContentAs(this.NodeType);
}
- internal static Exception CreateReadContentAsException(string methodName, XmlNodeType nodeType, IXmlLineInfo lineInfo)
+ internal static Exception CreateReadContentAsException(string methodName, XmlNodeType nodeType, IXmlLineInfo? lineInfo)
{
return new InvalidOperationException(AddLineInfo(SR.Format(SR.Xml_InvalidReadContentAs, methodName, nodeType), lineInfo));
}
- internal static Exception CreateReadElementContentAsException(string methodName, XmlNodeType nodeType, IXmlLineInfo lineInfo)
+ internal static Exception CreateReadElementContentAsException(string methodName, XmlNodeType nodeType, IXmlLineInfo? lineInfo)
{
return new InvalidOperationException(AddLineInfo(SR.Format(SR.Xml_InvalidReadElementContentAs, methodName, nodeType), lineInfo));
}
- private static string AddLineInfo(string message, IXmlLineInfo lineInfo)
+ private static string AddLineInfo(string message, IXmlLineInfo? lineInfo)
{
if (lineInfo != null)
{
internal string InternalReadContentAsString()
{
string value = string.Empty;
- StringBuilder sb = null;
+ StringBuilder? sb = null;
do
{
switch (this.NodeType)
{
throw new XmlException(SR.Xml_MixedReadElementContentAs, string.Empty, this as IXmlLineInfo);
}
+
return true;
}
{
throw new XmlException(SR.Xml_InvalidNodeType, this.NodeType.ToString());
}
+
this.Read();
}
{
return true;
}
- IXmlSchemaInfo schemaInfo = this.SchemaInfo;
+
+ IXmlSchemaInfo? schemaInfo = this.SchemaInfo;
if (schemaInfo != null && schemaInfo.IsDefault)
{
return true;
}
+
return false;
}
}
- internal virtual IDtdInfo DtdInfo
+ internal virtual IDtdInfo? DtdInfo
{
get
{
internal static ConformanceLevel GetV1ConformanceLevel(XmlReader reader)
{
- XmlTextReaderImpl tri = GetXmlTextReaderImpl(reader);
+ XmlTextReaderImpl? tri = GetXmlTextReaderImpl(reader);
return tri != null ? tri.V1ComformanceLevel : ConformanceLevel.Document;
}
- private static XmlTextReaderImpl GetXmlTextReaderImpl(XmlReader reader)
+ private static XmlTextReaderImpl? GetXmlTextReaderImpl(XmlReader reader)
{
- XmlTextReaderImpl tri = reader as XmlTextReaderImpl;
+ XmlTextReaderImpl? tri = reader as XmlTextReaderImpl;
+
if (tri != null)
{
return tri;
}
- XmlTextReader tr = reader as XmlTextReader;
+ XmlTextReader? tr = reader as XmlTextReader;
+
if (tr != null)
{
return tr.Impl;
}
- XmlValidatingReaderImpl vri = reader as XmlValidatingReaderImpl;
+ XmlValidatingReaderImpl? vri = reader as XmlValidatingReaderImpl;
+
if (vri != null)
{
return vri.ReaderImpl;
}
+
#pragma warning disable 618
- XmlValidatingReader vr = reader as XmlValidatingReader;
+ XmlValidatingReader? vr = reader as XmlValidatingReader;
#pragma warning restore 618
+
if (vr != null)
{
return vr.Impl.ReaderImpl;
// Creates an XmlReader according to the settings for parsing XML from the given Uri.
public static XmlReader Create(string inputUri, XmlReaderSettings settings)
{
- return XmlReader.Create(inputUri, settings, (XmlParserContext)null);
+ return XmlReader.Create(inputUri, settings, (XmlParserContext?)null);
}
// Creates an XmlReader according to the settings and parser context for parsing XML from the given Uri.
- public static XmlReader Create(string inputUri, XmlReaderSettings settings, XmlParserContext inputContext)
+ public static XmlReader Create(string inputUri, XmlReaderSettings settings, XmlParserContext? inputContext)
{
settings ??= XmlReaderSettings.s_defaultReaderSettings;
return settings.CreateReader(inputUri, inputContext);
// 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.Security;
internal async Task<string> InternalReadContentAsStringAsync()
{
string value = string.Empty;
- StringBuilder sb = null;
+ StringBuilder? sb = null;
do
{
switch (this.NodeType)
// 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.Diagnostics;
using System.Globalization;
// Nametable
- private XmlNameTable _nameTable;
+ private XmlNameTable? _nameTable;
// XmlResolver
- private XmlResolver _xmlResolver = null;
+ private XmlResolver? _xmlResolver = null;
// Text settings
private int _lineNumberOffset;
//Validation settings
private ValidationType _validationType;
private XmlSchemaValidationFlags _validationFlags;
- private XmlSchemaSet _schemas;
- private ValidationEventHandler _valEventHandler;
+ private XmlSchemaSet? _schemas;
+ private ValidationEventHandler? _valEventHandler;
// other settings
private bool _closeInput;
// Creation of validating readers is hidden behind a delegate which is only initialized if the ValidationType
// property is set. This is for AOT builds where the tree shaker can reduce the validating readers away
// if nobody calls the ValidationType setter. Might also help with non-AOT build when ILLinker is used.
- private delegate XmlReader AddValidationFunc(XmlReader reader, XmlResolver resolver, bool addConformanceWrapper);
- private AddValidationFunc _addValidationFunc;
+ private delegate XmlReader AddValidationFunc(XmlReader reader, XmlResolver? resolver, bool addConformanceWrapper);
+ private AddValidationFunc? _addValidationFunc;
//
// Constructor
}
// Nametable
- public XmlNameTable NameTable
+ public XmlNameTable? NameTable
{
get
{
set; // keep set internal as we need to call it from the schema validation code
}
- public XmlResolver XmlResolver
+ public XmlResolver? XmlResolver
{
set
{
}
}
- internal XmlResolver GetXmlResolver()
+ internal XmlResolver? GetXmlResolver()
{
return _xmlResolver;
}
//This is used by get XmlResolver in Xsd.
//Check if the config set to prohibit default resovler
//notice we must keep GetXmlResolver() to avoid dead lock when init System.Config.ConfigurationManager
- internal XmlResolver GetXmlResolver_CheckConfig()
+ internal XmlResolver? GetXmlResolver_CheckConfig()
{
if (!LocalAppContextSwitches.AllowDefaultResolver && !IsXmlResolverSet)
return null;
public XmlReaderSettings Clone()
{
- XmlReaderSettings clonedSettings = this.MemberwiseClone() as XmlReaderSettings;
+ XmlReaderSettings clonedSettings = (this.MemberwiseClone() as XmlReaderSettings)!;
clonedSettings.ReadOnly = false;
return clonedSettings;
}
//
// Internal methods
//
- internal ValidationEventHandler GetEventHandler()
+ internal ValidationEventHandler? GetEventHandler()
{
return _valEventHandler;
}
- internal XmlReader CreateReader(string inputUri, XmlParserContext inputContext)
+ internal XmlReader CreateReader(string inputUri, XmlParserContext? inputContext)
{
if (inputUri == null)
{
return reader;
}
- internal XmlReader CreateReader(Stream input, Uri baseUri, string baseUriString, XmlParserContext inputContext)
+ internal XmlReader CreateReader(Stream input, Uri? baseUri, string baseUriString, XmlParserContext? inputContext)
{
if (input == null)
{
return reader;
}
- internal XmlReader CreateReader(TextReader input, string baseUriString, XmlParserContext inputContext)
+ internal XmlReader CreateReader(TextReader input, string baseUriString, XmlParserContext? inputContext)
{
if (input == null)
{
Initialize(null);
}
- private void Initialize(XmlResolver resolver)
+ private void Initialize(XmlResolver? resolver)
{
_nameTable = null;
_xmlResolver = resolver;
internal XmlReader AddValidation(XmlReader reader)
{
- XmlResolver resolver = null;
+ XmlResolver? resolver = null;
if (_validationType == ValidationType.Schema)
{
resolver = GetXmlResolver_CheckConfig();
private XmlReader AddValidationAndConformanceWrapper(XmlReader reader)
{
- XmlResolver resolver = null;
+ XmlResolver? resolver = null;
if (_validationType == ValidationType.Schema)
{
resolver = GetXmlResolver_CheckConfig();
return AddValidationAndConformanceInternal(reader, resolver, addConformanceWrapper: true);
}
- private XmlReader AddValidationAndConformanceInternal(XmlReader reader, XmlResolver resolver, bool addConformanceWrapper)
+ private XmlReader AddValidationAndConformanceInternal(XmlReader reader, XmlResolver? resolver, bool addConformanceWrapper)
{
// We have to avoid calling the _addValidationFunc delegate if there's no validation to setup
// since it would not be initialized (to allow AOT compilers to reduce it away).
}
else
{
+ Debug.Assert(_addValidationFunc != null);
reader = _addValidationFunc(reader, resolver, addConformanceWrapper);
}
return reader;
}
- private XmlReader AddValidationInternal(XmlReader reader, XmlResolver resolver, bool addConformanceWrapper)
+ private XmlReader AddValidationInternal(XmlReader reader, XmlResolver? resolver, bool addConformanceWrapper)
{
// wrap with DTD validating reader
if (_validationType == ValidationType.DTD)
internal XmlReader AddConformanceWrapper(XmlReader baseReader)
{
- XmlReaderSettings baseReaderSettings = baseReader.Settings;
+ XmlReaderSettings? baseReaderSettings = baseReader.Settings;
bool checkChars = false;
bool noWhitespace = false;
bool noComments = false;
}
// get the V1 XmlTextReader ref
- XmlTextReader v1XmlTextReader = baseReader as XmlTextReader;
+ XmlTextReader? v1XmlTextReader = baseReader as XmlTextReader;
if (v1XmlTextReader == null)
{
- XmlValidatingReader vr = baseReader as XmlValidatingReader;
+ XmlValidatingReader? vr = baseReader as XmlValidatingReader;
if (vr != null)
{
v1XmlTextReader = (XmlTextReader)vr.Reader;
if (needWrap)
{
- IXmlNamespaceResolver readerAsNSResolver = baseReader as IXmlNamespaceResolver;
+ IXmlNamespaceResolver? readerAsNSResolver = baseReader as IXmlNamespaceResolver;
if (readerAsNSResolver != null)
{
return new XmlCharCheckingReaderWithNS(baseReader, readerAsNSResolver, checkChars, noWhitespace, noComments, noPIs, dtdProc);
// 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
{
// An enumeration for the xml:space scope used in XmlReader and XmlWriter.
// 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;
internal string namespaceUri;
internal string value;
- internal NodeData()
+ internal NodeData(XmlNodeType nodeType, string localName, string prefix, string name, string namespaceUri, string value)
{
+ this.type = nodeType;
+ this.localName = localName;
+ this.prefix = prefix;
+ this.name = name;
+ this.namespaceUri = namespaceUri;
+ this.value = value;
}
internal void Set(XmlNodeType nodeType, string localName, string prefix, string name, string namespaceUri, string value)
// namespace management
private readonly XmlNamespaceManager _nsManager;
- private NodeData[] _nsAttributes;
+ private NodeData?[]? _nsAttributes;
private int _nsAttrCount;
private int _curNsAttr = -1;
// incremental reading of added xmlns nodes (ReadValueChunk, ReadContentAsBase64, ReadContentAsBinHex)
private int _nsIncReadOffset;
- private IncrementalReadDecoder _binDecoder;
+ private IncrementalReadDecoder? _binDecoder;
// cached nodes
private bool _useCurNode;
- private NodeData _curNode;
+ private NodeData _curNode = null!;
// node used for a text node of ReadAttributeValue or as Initial or EOF node
private readonly NodeData _tmpNode;
_xmlns = reader.NameTable.Add("xmlns");
_xmlnsUri = reader.NameTable.Add(XmlReservedNs.NsXmlNs);
- _tmpNode = new NodeData();
- _tmpNode.Set(XmlNodeType.None, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty);
+ _tmpNode = new NodeData(XmlNodeType.None, string.Empty, string.Empty, string.Empty, string.Empty, string.Empty);
SetCurrentNode(_tmpNode);
}
{
get
{
- return (_useCurNode) ? _curNode.name : reader.Name;
+ return _useCurNode ? _curNode.name! : reader.Name;
}
}
}
}
- public override string BaseURI
+ public override string? BaseURI
{
get
{
}
}
- public override string GetAttribute(string name)
+ public override string? GetAttribute(string name)
{
if (!InAttributeActiveState)
{
return null;
}
- string attr = reader.GetAttribute(name);
+ string? attr = reader.GetAttribute(name);
if (attr != null)
{
return attr;
}
+
for (int i = 0; i < _nsAttrCount; i++)
{
- if (name == _nsAttributes[i].name)
+ if (name == _nsAttributes![i]!.name)
{
- return _nsAttributes[i].value;
+ // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34644
+ return _nsAttributes[i]!.value;
}
}
return null;
}
- public override string GetAttribute(string name, string namespaceURI)
+ public override string? GetAttribute(string name, string namespaceURI)
{
if (!InAttributeActiveState)
{
return null;
}
- string attr = reader.GetAttribute(name, namespaceURI);
+
+ string? attr = reader.GetAttribute(name, namespaceURI);
if (attr != null)
{
return attr;
}
+
for (int i = 0; i < _nsAttrCount; i++)
{
- if (name == _nsAttributes[i].localName && namespaceURI == _xmlnsUri)
+ if (name == _nsAttributes![i]!.localName && namespaceURI == _xmlnsUri)
{
- return _nsAttributes[i].value;
+ // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34644
+ return _nsAttributes[i]!.value;
}
}
+
return null;
}
}
else if (i - n < _nsAttrCount)
{
- return _nsAttributes[i - n].value;
+ return _nsAttributes![i - n]!.value;
}
else
{
_useCurNode = false;
return true;
}
+
for (int i = 0; i < _nsAttrCount; i++)
{
- if (name == _nsAttributes[i].name)
+ if (name == _nsAttributes![i]!.name)
{
MoveToNsAttribute(i);
return true;
_useCurNode = false;
return true;
}
+
for (int i = 0; i < _nsAttrCount; i++)
{
- if (name == _nsAttributes[i].localName && ns == _xmlnsUri)
+ if (name == _nsAttributes![i]!.localName && ns == _xmlnsUri)
{
MoveToNsAttribute(i);
return true;
{
return 0;
}
+
+ Debug.Assert(_binDecoder != null);
_binDecoder.SetNextOutputBuffer(buffer, index, count);
_nsIncReadOffset += _binDecoder.Decode(_curNode.value, _nsIncReadOffset, _curNode.value.Length - _nsIncReadOffset);
return _binDecoder.DecodedCount;
{
return 0;
}
+
+ Debug.Assert(_binDecoder != null);
_binDecoder.SetNextOutputBuffer(buffer, index, count);
_nsIncReadOffset += _binDecoder.Decode(_curNode.value, _nsIncReadOffset, _curNode.value.Length - _nsIncReadOffset);
return _binDecoder.DecodedCount;
}
}
- public override string LookupNamespace(string prefix)
+ public override string? LookupNamespace(string prefix)
{
return ((IXmlNamespaceResolver)this).LookupNamespace(prefix);
}
{
if (!_useCurNode)
{
- IXmlLineInfo lineInfo = reader as IXmlLineInfo;
+ IXmlLineInfo? lineInfo = reader as IXmlLineInfo;
if (lineInfo != null)
{
return lineInfo.LineNumber;
{
if (!_useCurNode)
{
- IXmlLineInfo lineInfo = reader as IXmlLineInfo;
+ IXmlLineInfo? lineInfo = reader as IXmlLineInfo;
if (lineInfo != null)
{
return lineInfo.LinePosition;
return _nsManager.GetNamespacesInScope(scope);
}
- string IXmlNamespaceResolver.LookupNamespace(string prefix)
+ string? IXmlNamespaceResolver.LookupNamespace(string prefix)
{
if (!InNamespaceActiveState)
{
return _nsManager.LookupNamespace(prefix);
}
- string IXmlNamespaceResolver.LookupPrefix(string namespaceName)
+ string? IXmlNamespaceResolver.LookupPrefix(string namespaceName)
{
if (!InNamespaceActiveState)
{
{
_nsAttributes = new NodeData[InitialNamespaceAttributeCount];
}
+
if (index == _nsAttributes.Length)
{
NodeData[] newNsAttrs = new NodeData[_nsAttributes.Length * 2];
_nsAttributes = newNsAttrs;
}
- if (_nsAttributes[index] == null)
+ string localName;
+ string attrPrefix;
+ string name;
+
+ if (prefix.Length == 0)
{
- _nsAttributes[index] = new NodeData();
+ localName = _xmlns;
+ attrPrefix = string.Empty;
+ name = _xmlns;
}
- if (prefix.Length == 0)
+ else
+ {
+ localName = prefix;
+ attrPrefix = _xmlns;
+ name = reader.NameTable.Add(string.Concat(_xmlns, ":", prefix));
+ }
+
+ if (_nsAttributes[index] == null)
{
- _nsAttributes[index].Set(XmlNodeType.Attribute, _xmlns, string.Empty, _xmlns, _xmlnsUri, ns);
+ _nsAttributes[index] = new NodeData(XmlNodeType.Attribute, localName, attrPrefix, name, _xmlnsUri, ns);
}
else
{
- _nsAttributes[index].Set(XmlNodeType.Attribute, prefix, _xmlns, reader.NameTable.Add(string.Concat(_xmlns, ":", prefix)), _xmlnsUri, ns);
+ _nsAttributes[index]!.Set(XmlNodeType.Attribute, localName, attrPrefix, name, _xmlnsUri, ns);
}
Debug.Assert(_state == State.ClearNsAttributes || _state == State.Interactive || _state == State.PopNamespaceScope);
{
for (int i = 0; i < _nsAttrCount; i++)
{
- if (Ref.Equal(prefix, _nsAttributes[i].prefix) &&
- Ref.Equal(localName, _nsAttributes[i].localName))
+ if (Ref.Equal(prefix, _nsAttributes![i]!.prefix) &&
+ Ref.Equal(localName, _nsAttributes![i]!.localName)) // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34644
{
if (i < _nsAttrCount - 1)
{
// swap
- NodeData tmpNodeData = _nsAttributes[i];
+ NodeData tmpNodeData = _nsAttributes![i]!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/34644
_nsAttributes[i] = _nsAttributes[_nsAttrCount - 1];
_nsAttributes[_nsAttrCount - 1] = tmpNodeData;
}
reader.MoveToElement();
_curNsAttr = index;
_nsIncReadOffset = 0;
- SetCurrentNode(_nsAttributes[index]);
+ SetCurrentNode(_nsAttributes![index]!);
}
private bool InitReadElementContentAsBinary(State binaryState)
// 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;
{
return 0;
}
+
+ Debug.Assert(_binDecoder != null);
_binDecoder.SetNextOutputBuffer(buffer, index, count);
_nsIncReadOffset += _binDecoder.Decode(_curNode.value, _nsIncReadOffset, _curNode.value.Length - _nsIncReadOffset);
return _binDecoder.DecodedCount;
{
return 0;
}
+
+ Debug.Assert(_binDecoder != null);
_binDecoder.SetNextOutputBuffer(buffer, index, count);
_nsIncReadOffset += _binDecoder.Decode(_curNode.value, _nsIncReadOffset, _curNode.value.Length - _nsIncReadOffset);
return _binDecoder.DecodedCount;
// 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;
get { return _impl.Depth; }
}
- public override string BaseURI
+ public override string? BaseURI
{
get { return _impl.BaseURI; }
}
public override int AttributeCount { get { return _impl.AttributeCount; } }
- public override string GetAttribute(string name)
+ public override string? GetAttribute(string name)
{
return _impl.GetAttribute(name);
}
- public override string GetAttribute(string localName, string namespaceURI)
+ public override string? GetAttribute(string localName, string namespaceURI)
{
return _impl.GetAttribute(localName, namespaceURI);
}
get { return _impl.NameTable; }
}
- public override string LookupNamespace(string prefix)
+ public override string? LookupNamespace(string prefix)
{
- string ns = _impl.LookupNamespace(prefix);
+ string? ns = _impl.LookupNamespace(prefix);
if (ns != null && ns.Length == 0)
{
ns = null;
return _impl.GetNamespacesInScope(scope);
}
- string IXmlNamespaceResolver.LookupNamespace(string prefix)
+ string? IXmlNamespaceResolver.LookupNamespace(string prefix)
{
return _impl.LookupNamespace(prefix);
}
- string IXmlNamespaceResolver.LookupPrefix(string namespaceName)
+ string? IXmlNamespaceResolver.LookupPrefix(string namespaceName)
{
return _impl.LookupPrefix(namespaceName);
}
set { _impl.Normalization = value; }
}
- public Encoding Encoding
+ public Encoding? Encoding
{
get { return _impl.Encoding; }
}
get { return _impl; }
}
- internal override XmlNamespaceManager NamespaceManager
+ internal override XmlNamespaceManager? NamespaceManager
{
get { return _impl.NamespaceManager; }
}
set { _impl.XmlValidatingReaderCompatibilityMode = value; }
}
- internal override IDtdInfo DtdInfo
+ internal override IDtdInfo? DtdInfo
{
get { return _impl.DtdInfo; }
}
// 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;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
+using System.Diagnostics.CodeAnalysis;
namespace System.Xml
{
internal partial class XmlTextReaderImpl : XmlReader, IXmlLineInfo, IXmlNamespaceResolver
{
- private static UTF8Encoding s_utf8BomThrowing;
+ private static UTF8Encoding? s_utf8BomThrowing;
private static UTF8Encoding UTF8BomThrowing =>
s_utf8BomThrowing ?? (s_utf8BomThrowing = new UTF8Encoding(encoderShouldEmitUTF8Identifier: true, throwOnInvalidBytes: true));
{
public bool useAsync = false;
- public Stream inputStream;
- public byte[] inputBytes;
+ public Stream? inputStream;
+ public byte[]? inputBytes;
public int inputByteCount;
- public Uri inputbaseUri;
- public string inputUriStr;
- public XmlResolver inputUriResolver;
- public XmlParserContext inputContext;
- public TextReader inputTextReader;
+ public Uri? inputbaseUri;
+ public string? inputUriStr;
+ public XmlResolver? inputUriResolver;
+ public XmlParserContext? inputContext;
+ public TextReader? inputTextReader;
public InitInputType initType = InitInputType.Invalid;
}
- private LaterInitParam _laterInitParam = null;
+ private LaterInitParam? _laterInitParam = null;
private enum InitInputType
{
private int _attrDuplWalkCount;
private bool _attrNeedNamespaceLookup;
private bool _fullAttrCleanup;
- private NodeData[] _attrDuplSortingArray;
+ private NodeData[]? _attrDuplSortingArray;
// name table
- private XmlNameTable _nameTable;
+ private XmlNameTable _nameTable = null!; // TODO-NULLABLE: https://github.com/dotnet/roslyn/issues/43523
private bool _nameTableFromSettings;
// resolver
- private XmlResolver _xmlResolver;
+ private XmlResolver? _xmlResolver;
// this is only for constructors that takes url
private readonly string _url = string.Empty;
private readonly bool _v1Compat;
// namespace handling
- private XmlNamespaceManager _namespaceManager;
+ private XmlNamespaceManager? _namespaceManager;
private string _lastPrefix = string.Empty;
// xml context (xml:space, xml:lang, default namespace)
private XmlContext _xmlContext;
// stack of parsing states (=stack of entities)
- private ParsingState[] _parsingStatesStack;
+ private ParsingState[]? _parsingStatesStack;
private int _parsingStatesStackTop = -1;
// current node base uri and encoding
- private string _reportedBaseUri;
- private Encoding _reportedEncoding;
+ private string? _reportedBaseUri;
+ private Encoding? _reportedEncoding;
// DTD
- private IDtdInfo _dtdInfo;
+ private IDtdInfo? _dtdInfo;
// fragment parsing
private XmlNodeType _fragmentType = XmlNodeType.Document;
- private XmlParserContext _fragmentParserContext;
+ private XmlParserContext? _fragmentParserContext;
private bool _fragment;
// incremental read
- private IncrementalReadDecoder _incReadDecoder;
+ private IncrementalReadDecoder? _incReadDecoder;
private IncrementalReadState _incReadState;
private LineInfo _incReadLineInfo;
- private BinHexDecoder _binHexDecoder;
- private Base64Decoder _base64Decoder;
+ private BinHexDecoder? _binHexDecoder;
+ private Base64Decoder? _base64Decoder;
private int _incReadDepth;
private int _incReadLeftStartPos;
private int _incReadLeftEndPos;
- private IncrementalReadCharsDecoder _readCharsDecoder;
+ private IncrementalReadCharsDecoder? _readCharsDecoder;
// ReadAttributeValue helpers
private int _attributeValueBaseEntityId;
private bool _emptyEntityInAttributeResolved;
// Validation helpers
- private IValidationEventHandling _validationEventHandling;
- private OnDefaultAttributeUseDelegate _onDefaultAttributeUse;
+ private IValidationEventHandling? _validationEventHandling;
+ private OnDefaultAttributeUseDelegate? _onDefaultAttributeUse;
private bool _validatingReaderCompatFlag;
private int _nextEntityId = 1;
private ParsingMode _parsingMode;
private ReadState _readState = ReadState.Initial;
- private IDtdEntityInfo _lastEntity;
+ private IDtdEntityInfo? _lastEntity;
private bool _afterResetState;
private int _documentStartBytePos;
private int _readValueOffset;
private long _charactersFromEntities;
// All entities that are currently being processed
- private Dictionary<IDtdEntityInfo, IDtdEntityInfo> _currentEntities;
+ private Dictionary<IDtdEntityInfo, IDtdEntityInfo>? _currentEntities;
// DOM helpers
private bool _disableUndeclaredEntityCheck;
internal XmlTextReaderImpl()
{
- _curNode = new NodeData();
_parsingFunction = ParsingFunction.NoData;
+ _outerReader = this;
+ _xmlContext = new XmlContext();
+ _nameTable = new NameTable();
+ _nodes = new NodeData[NodesInitialSize];
+ _nodes[0] = new NodeData();
+ _curNode = _nodes[0];
+ _stringBuilder = new StringBuilder();
+ _xml = _nameTable.Add("xml");
+ _xmlNs = _nameTable.Add("xmlns");
}
// Initializes a new instance of the XmlTextReaderImpl class with the specified XmlNameTable.
}
// This constructor is used when creating XmlTextReaderImpl reader via "XmlReader.Create(..)"
- private XmlTextReaderImpl(XmlResolver resolver, XmlReaderSettings settings, XmlParserContext context)
+ private XmlTextReaderImpl(XmlResolver? resolver, XmlReaderSettings settings, XmlParserContext? context)
{
_useAsync = settings.Async;
_v1Compat = false;
_xmlContext = new XmlContext();
// create or get nametable and namespace manager from XmlParserContext
- XmlNameTable nt = settings.NameTable;
+ XmlNameTable? nt = settings.NameTable;
if (context == null)
{
if (nt == null)
{
_nameTableFromSettings = true;
}
+
_nameTable = nt;
_namespaceManager = new XmlNamespaceManager(nt);
}
else
{
SetupFromParserContext(context, settings);
+ Debug.Assert(_nameTable != null);
nt = _nameTable;
}
internal XmlTextReaderImpl(Stream input) : this(string.Empty, input, new NameTable())
{
}
+
internal XmlTextReaderImpl(Stream input, XmlNameTable nt) : this(string.Empty, input, nt)
{
}
+
internal XmlTextReaderImpl(string url, Stream input) : this(url, input, new NameTable())
{
}
+
internal XmlTextReaderImpl(string url, Stream input, XmlNameTable nt) : this(nt)
{
ConvertAbsoluteUnixPathToAbsoluteUri(ref url, resolver: null);
_namespaceManager = new XmlNamespaceManager(nt);
+
if (url == null || url.Length == 0)
{
InitStreamInput(input, null);
{
InitStreamInput(url, input, null);
}
+
_reportedBaseUri = _ps.baseUriStr;
_reportedEncoding = _ps.encoding;
}
internal XmlTextReaderImpl(TextReader input) : this(string.Empty, input, new NameTable())
{
}
+
internal XmlTextReaderImpl(TextReader input, XmlNameTable nt) : this(string.Empty, input, nt)
{
}
+
internal XmlTextReaderImpl(string url, TextReader input) : this(url, input, new NameTable())
{
}
+
internal XmlTextReaderImpl(string url, TextReader input, XmlNameTable nt) : this(nt)
{
ConvertAbsoluteUnixPathToAbsoluteUri(ref url, resolver: null);
internal XmlTextReaderImpl(Stream xmlFragment, XmlNodeType fragType, XmlParserContext context)
: this((context != null && context.NameTable != null) ? context.NameTable : new NameTable())
{
- Encoding enc = (context != null) ? context.Encoding : null;
+ Encoding? enc = (context != null) ? context.Encoding : null;
if (context == null || context.BaseURI == null || context.BaseURI.Length == 0)
{
InitStreamInput(xmlFragment, enc);
// it is safe as this resolver will not be used to resolve DTD url's
InitStreamInput(GetTempResolver().ResolveUri(null, context.BaseURI), xmlFragment, enc);
}
+
InitFragmentReader(fragType, context, false);
_reportedBaseUri = _ps.baseUriStr;
_reportedBaseUri = context.BaseURI;
InitStringInput(context.BaseURI, Encoding.Unicode, xmlFragment);
}
+
InitFragmentReader(fragType, context, false);
_reportedEncoding = _ps.encoding;
}
{
throw new ArgumentNullException(nameof(url));
}
+
if (url.Length == 0)
{
throw new ArgumentException(SR.Xml_EmptyUrl, nameof(url));
}
+
_namespaceManager = new XmlNamespaceManager(nt);
_url = url;
// Initializes a new instance of the XmlTextReaderImpl class with the specified arguments.
// This constructor is used when creating XmlTextReaderImpl via XmlReader.Create
- internal XmlTextReaderImpl(string uriStr, XmlReaderSettings settings, XmlParserContext context, XmlResolver uriResolver)
+ internal XmlTextReaderImpl(string uriStr, XmlReaderSettings settings, XmlParserContext? context, XmlResolver uriResolver)
: this(settings.GetXmlResolver(), settings, context)
{
Uri baseUri = uriResolver.ResolveUri(null, uriStr);
_laterInitParam.inputContext = context;
_laterInitParam.inputUriResolver = uriResolver;
_laterInitParam.initType = InitInputType.UriString;
+
if (!settings.Async)
{
//if not set Async flag, finish the init in create stage.
private void FinishInitUriString()
{
- Stream stream = null;
+ Stream? stream = null;
+ Debug.Assert(_laterInitParam != null);
+ Debug.Assert(_laterInitParam.inputUriResolver != null);
+ Debug.Assert(_laterInitParam.inputbaseUri != null);
+ Debug.Assert(_reportedBaseUri != null);
if (_laterInitParam.useAsync)
{
- //this will be hit when user create a XmlReader by setting Async, but the first call is Read() instead of ReadAsync(),
- //then we still should create an async stream here. And wait for the method finish.
+ // this will be hit when user create a XmlReader by setting Async, but the first call is Read() instead of ReadAsync(),
+ // then we still should create an async stream here. And wait for the method finish.
Task<object> t = _laterInitParam.inputUriResolver.GetEntityAsync(_laterInitParam.inputbaseUri, string.Empty, typeof(Stream));
stream = (Stream)t.GetAwaiter().GetResult();
}
else
{
- stream = (Stream)_laterInitParam.inputUriResolver.GetEntity(_laterInitParam.inputbaseUri, string.Empty, typeof(Stream));
+ stream = (Stream?)_laterInitParam.inputUriResolver.GetEntity(_laterInitParam.inputbaseUri, string.Empty, typeof(Stream));
}
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)
{
stream.Dispose();
throw;
}
+
_laterInitParam = null;
}
// 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,
- XmlParserContext context, bool closeInput)
+ internal XmlTextReaderImpl(Stream stream, byte[]? bytes, int byteCount, XmlReaderSettings settings, Uri? baseUri, string baseUriStr,
+ XmlParserContext? context, bool closeInput)
: this(settings.GetXmlResolver(), settings, context)
{
ConvertAbsoluteUnixPathToAbsoluteUri(ref baseUriStr, settings.GetXmlResolver());
+
// get BaseUri from XmlParserContext
if (context != null)
{
{
Throw(SR.Xml_DoubleBaseUri);
}
+
Debug.Assert(baseUri == null);
baseUriStr = context.BaseURI;
}
private void FinishInitStream()
{
- Encoding enc = null;
+ Encoding? enc = null;
+
+ Debug.Assert(_laterInitParam != null);
+ Debug.Assert(_laterInitParam.inputStream != null);
+ Debug.Assert(_reportedBaseUri != null);
// get Encoding from XmlParserContext
if (_laterInitParam.inputContext != null)
{
ProcessDtdFromParserContext(_laterInitParam.inputContext);
}
+
_laterInitParam = null;
}
// 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());
private void FinishInitTextReader()
{
+ Debug.Assert(_laterInitParam != null);
+ Debug.Assert(_laterInitParam.inputTextReader != null);
+ Debug.Assert(_reportedBaseUri != null);
+
// init ParsingState
InitTextReaderInput(_reportedBaseUri, _laterInitParam.inputTextReader);
case XmlNodeType.Document: settings.ConformanceLevel = ConformanceLevel.Document; break;
default: Debug.Fail($"Unexpected fragment type {_fragmentType}"); goto case XmlNodeType.None;
}
+
settings.CheckCharacters = _checkCharacters;
settings.LineNumberOffset = _lineNumberOffset;
settings.LinePositionOffset = _linePositionOffset;
{
get
{
- return _curNode.ns;
+ return _curNode.ns ?? string.Empty;
}
}
FinishOtherValueIterator();
}
}
+
return _curNode.StringValue;
}
}
}
// Returns the base URI of the current node.
- public override string BaseURI
+ public override string? BaseURI
{
get
{
}
// Returns value of an attribute with the specified Name
- public override string GetAttribute(string name)
+ public override string? GetAttribute(string name)
{
int i;
if (!name.Contains(':'))
{
i = GetIndexOfAttributeWithPrefix(name);
}
+
return (i >= 0) ? _nodes[i].StringValue : null;
}
// Returns value of an attribute with the specified LocalName and NamespaceURI
- public override string GetAttribute(string localName, string namespaceURI)
+ public override string? GetAttribute(string localName, string? namespaceURI)
{
namespaceURI = (namespaceURI == null) ? string.Empty : _nameTable.Get(namespaceURI);
- localName = _nameTable.Get(localName);
+ string? localNameAtomized = _nameTable.Get(localName);
+
for (int i = _index + 1; i < _index + _attrCount + 1; i++)
{
- if (Ref.Equal(_nodes[i].localName, localName) && Ref.Equal(_nodes[i].ns, namespaceURI))
+ if (Ref.Equal(_nodes[i].localName, localNameAtomized) && Ref.Equal(_nodes[i].ns, namespaceURI))
{
return _nodes[i].StringValue;
}
}
+
return null;
}
{
throw new ArgumentOutOfRangeException(nameof(i));
}
+
return _nodes[_index + i + 1].StringValue;
}
// Moves to an attribute with the specified LocalName and NamespceURI
public override bool MoveToAttribute(string localName, string namespaceURI)
{
- namespaceURI = (namespaceURI == null) ? string.Empty : _nameTable.Get(namespaceURI);
- localName = _nameTable.Get(localName);
+ string? namespaceURIAtomized = (namespaceURI == null) ? string.Empty : _nameTable.Get(namespaceURI);
+ string? localNameAtomized = _nameTable.Get(localName);
for (int i = _index + 1; i < _index + _attrCount + 1; i++)
{
- if (Ref.Equal(_nodes[i].localName, localName) &&
- Ref.Equal(_nodes[i].ns, namespaceURI))
+ if (Ref.Equal(_nodes[i].localName, localNameAtomized) &&
+ Ref.Equal(_nodes[i].ns, namespaceURIAtomized))
{
_curAttrIndex = i - _index - 1;
_curNode = _nodes[i];
return true;
}
}
+
return false;
}
{
FinishAttributeValueIterator();
}
+
_curAttrIndex = i;
_curNode = _nodes[_index + 1 + _curAttrIndex];
}
private void FinishInit()
{
+ Debug.Assert(_laterInitParam != null);
+
switch (_laterInitParam.initType)
{
case InitInputType.UriString:
}
// Returns NamespaceURI associated with the specified prefix in the current namespace scope.
- public override string LookupNamespace(string prefix)
+ public override string? LookupNamespace(string prefix)
{
if (!_supportNamespaces)
{
return null;
}
+ Debug.Assert(_namespaceManager != null);
return _namespaceManager.LookupNamespace(prefix);
}
case EntityType.ExpandedInAttribute:
case EntityType.Expanded:
_nextParsingFunction = _parsingFunction;
- if (_ps.charsUsed - _ps.charPos == 0 && !_ps.entity.IsExternal)
+ if (_ps.charsUsed - _ps.charPos == 0 && !_ps.entity!.IsExternal)
{ // empty internal entity value
_parsingFunction = ParsingFunction.AfterResolveEmptyEntityInContent;
}
{
copyCount = endPos - startPos;
}
+
+ Debug.Assert(_ps.chars != null);
BlockCopyChars(_ps.chars, startPos, buffer, (index + readCount), copyCount);
readCount += copyCount;
}
_readValueOffset = 0;
+ Debug.Assert(_ps.chars != null);
_curNode.SetValue(_ps.chars, startPos, endPos - startPos);
}
return readCount;
return this.GetNamespacesInScope(scope);
}
- string IXmlNamespaceResolver.LookupNamespace(string prefix)
+ string? IXmlNamespaceResolver.LookupNamespace(string prefix)
{
return this.LookupNamespace(prefix);
}
- string IXmlNamespaceResolver.LookupPrefix(string namespaceName)
+ string? IXmlNamespaceResolver.LookupPrefix(string namespaceName)
{
return this.LookupPrefix(namespaceName);
}
// Internal IXmlNamespaceResolver methods
internal IDictionary<string, string> GetNamespacesInScope(XmlNamespaceScope scope)
{
+ Debug.Assert(_namespaceManager != null);
return _namespaceManager.GetNamespacesInScope(scope);
}
// NOTE: there already is virtual method for "string LookupNamespace(string prefix)"
- internal string LookupPrefix(string namespaceName)
+ internal string? LookupPrefix(string namespaceName)
{
+ Debug.Assert(_namespaceManager != null);
return _namespaceManager.LookupPrefix(namespaceName);
}
{
throw new InvalidOperationException(SR.Xml_InvalidOperation);
}
+
_supportNamespaces = value;
if (value)
{
_namespaceManager = new XmlNamespaceManager(_nameTable);
}
}
- _xmlContext.defaultNamespace = _namespaceManager.LookupNamespace(string.Empty);
+
+ Debug.Assert(_namespaceManager != null);
+ _xmlContext.defaultNamespace = _namespaceManager.LookupNamespace(string.Empty)!;
}
else
{
{
_namespaceManager = new NoNamespaceManager();
}
+
_xmlContext.defaultNamespace = string.Empty;
}
}
}
// Returns the Encoding of the XML document
- internal Encoding Encoding
+ internal Encoding? Encoding
{
get
{
{
throw new XmlException(SR.Xml_WhitespaceHandling, string.Empty);
}
+
_whitespaceHandling = value;
}
}
{
throw new ArgumentOutOfRangeException(nameof(value));
}
+
_dtdProcessing = value;
}
}
{
throw new XmlException(SR.Xml_EntityHandling, string.Empty);
}
+
_entityHandling = value;
}
}
_xmlResolverIsSet = true;
// invalidate all baseUris on the stack
_ps.baseUri = null;
+
for (int i = 0; i <= _parsingStatesStackTop; i++)
{
- _parsingStatesStack[i].baseUri = null;
+ _parsingStatesStack![i].baseUri = null;
}
}
}
// Clear
ResetAttributes();
+ Debug.Assert(_namespaceManager != null);
while (_namespaceManager.PopScope()) ;
while (InEntity)
internal TextReader GetRemainder()
{
Debug.Assert(_v1Compat, "XmlTextReaderImpl.GetRemainder cannot be called on reader created via XmlReader.Create.");
-
Debug.Assert(_stringBuilder.Length == 0);
switch (_parsingFunction)
{
}
}
- internal IXmlNamespaceResolver DtdParserProxy_NamespaceResolver
+ internal IXmlNamespaceResolver? DtdParserProxy_NamespaceResolver
{
get
{
}
}
- internal Uri DtdParserProxy_BaseUri
+ internal Uri? DtdParserProxy_BaseUri
{
// SxS: ps.baseUri may be initialized in the constructor (public XmlTextReaderImpl( string url, XmlNameTable nt )) based on
// url provided by the user. Here the property returns ps.BaseUri - so it may expose a path.
{
_ps.baseUri = _xmlResolver.ResolveUri(null, _ps.baseUriStr);
}
+
return _ps.baseUri;
}
}
}
}
- internal char[] DtdParserProxy_ParsingBuffer
+ internal char[]? DtdParserProxy_ParsingBuffer
{
get
{
}
}
- internal IValidationEventHandling DtdParserProxy_ValidationEventHandling
+ internal IValidationEventHandling? DtdParserProxy_ValidationEventHandling
{
get
{
return retValue;
}
- internal bool DtdParserProxy_PopEntity(out IDtdEntityInfo oldEntity, out int newEntityId)
+ internal bool DtdParserProxy_PopEntity(out IDtdEntityInfo? oldEntity, out int newEntityId)
{
if (_parsingStatesStackTop == -1)
{
newEntityId = -1;
return false;
}
+
oldEntity = _ps.entity;
PopEntity();
newEntityId = _ps.entityId;
// SxS: The caller did not provide any SxS sensitive name or resource. No resource is being exposed either.
// It is OK to suppress SxS warning.
- internal bool DtdParserProxy_PushExternalSubset(string systemId, string publicId)
+ internal bool DtdParserProxy_PushExternalSubset(string? systemId, string? publicId)
{
Debug.Assert(_parsingStatesStackTop == -1);
Debug.Assert((systemId != null && systemId.Length > 0) || (publicId != null && publicId.Length > 0));
{
return false;
}
+
+ Debug.Assert(_xmlResolver != null);
+
if (_ps.baseUri == null && !string.IsNullOrEmpty(_ps.baseUriStr))
{
_ps.baseUri = _xmlResolver.ResolveUri(null, _ps.baseUriStr);
}
+
PushExternalEntityOrSubset(publicId, systemId, _ps.baseUri, null);
_ps.entity = null;
//
// Throw methods: Sets the reader current position to pos, sets the error state and throws exception
//
+ [DoesNotReturn]
private void Throw(int pos, string res, string arg)
{
_ps.charPos = pos;
Throw(res, arg);
}
+ [DoesNotReturn]
private void Throw(int pos, string res, string[] args)
{
_ps.charPos = pos;
Throw(res, args);
}
+ [DoesNotReturn]
private void Throw(int pos, string res)
{
_ps.charPos = pos;
Throw(res, string.Empty);
}
+ [DoesNotReturn]
private void Throw(string res)
{
Throw(res, string.Empty);
}
+ [DoesNotReturn]
private void Throw(string res, int lineNo, int linePos)
{
Throw(new XmlException(res, string.Empty, lineNo, linePos, _ps.baseUriStr));
}
- private void Throw(string res, string arg)
+ [DoesNotReturn]
+ private void Throw(string res, string? arg)
{
Throw(new XmlException(res, arg, _ps.LineNo, _ps.LinePos, _ps.baseUriStr));
}
- private void Throw(string res, string arg, int lineNo, int linePos)
+ [DoesNotReturn]
+ private void Throw(string res, string? arg, int lineNo, int linePos)
{
Throw(new XmlException(res, arg, lineNo, linePos, _ps.baseUriStr));
}
- private void Throw(string res, string[] args)
+ [DoesNotReturn]
+ private void Throw(string res, string?[] args)
{
Throw(new XmlException(res, args, _ps.LineNo, _ps.LinePos, _ps.baseUriStr));
}
- private void Throw(string res, string arg, Exception innerException)
+ [DoesNotReturn]
+ private void Throw(string res, string? arg, Exception innerException)
{
- Throw(res, new string[] { arg }, innerException);
+ Throw(res, new string?[] { arg }, innerException);
}
- private void Throw(string res, string[] args, Exception innerException)
+ [DoesNotReturn]
+ private void Throw(string res, string?[] args, Exception innerException)
{
Throw(new XmlException(res, args, innerException, _ps.LineNo, _ps.LinePos, _ps.baseUriStr));
}
+ [DoesNotReturn]
private void Throw(Exception e)
{
SetErrorState();
- XmlException xmlEx = e as XmlException;
+ XmlException? xmlEx = e as XmlException;
+
if (xmlEx != null)
{
_curNode.SetLineInfo(xmlEx.LineNumber, xmlEx.LinePosition);
}
+
throw e;
}
+ [DoesNotReturn]
private void ReThrow(Exception e, int lineNo, int linePos)
{
- Throw(new XmlException(e.Message, (Exception)null, lineNo, linePos, _ps.baseUriStr));
+ Throw(new XmlException(e.Message, (Exception?)null, lineNo, linePos, _ps.baseUriStr));
}
+ [DoesNotReturn]
private void ThrowWithoutLineInfo(string res)
{
Throw(new XmlException(res, string.Empty, _ps.baseUriStr));
}
+ [DoesNotReturn]
private void ThrowWithoutLineInfo(string res, string arg)
{
Throw(new XmlException(res, arg, _ps.baseUriStr));
}
- private void ThrowWithoutLineInfo(string res, string[] args, Exception innerException)
+ [DoesNotReturn]
+ private void ThrowWithoutLineInfo(string res, string?[] args, Exception? innerException)
{
Throw(new XmlException(res, args, innerException, 0, 0, _ps.baseUriStr));
}
+ [DoesNotReturn]
private void ThrowInvalidChar(char[] data, int length, int invCharPos)
{
Throw(invCharPos, SR.Xml_InvalidCharacter, XmlException.BuildCharExceptionArgs(data, length, invCharPos));
_readState = ReadState.Error;
}
- private void SendValidationEvent(XmlSeverityType severity, string code, string arg, int lineNo, int linePos)
+ private void SendValidationEvent(XmlSeverityType severity, string code, string? arg, int lineNo, int linePos)
{
SendValidationEvent(severity, new XmlSchemaException(code, arg, _ps.baseUriStr, lineNo, linePos));
}
{
FinishReadContentAsBinary();
}
+
if (_parsingFunction == ParsingFunction.InReadAttributeValue)
{
while (_ps.entityId != _attributeValueBaseEntityId)
}
}
- private void InitStreamInput(Stream stream, Encoding encoding)
+ private void InitStreamInput(Stream stream, Encoding? encoding)
{
InitStreamInput(null, string.Empty, stream, null, 0, encoding);
}
- private void InitStreamInput(string baseUriStr, Stream stream, Encoding encoding)
+ private void InitStreamInput(string baseUriStr, Stream stream, Encoding? encoding)
{
Debug.Assert(baseUriStr != null);
InitStreamInput(null, baseUriStr, stream, null, 0, encoding);
}
- private void InitStreamInput(Uri baseUri, Stream stream, Encoding encoding)
+ private void InitStreamInput(Uri? baseUri, Stream stream, Encoding? encoding)
{
Debug.Assert(baseUri != null);
InitStreamInput(baseUri, baseUri.ToString(), stream, null, 0, encoding);
}
- private void InitStreamInput(Uri baseUri, string baseUriStr, Stream stream, Encoding encoding)
+ private void InitStreamInput(Uri? baseUri, string baseUriStr, Stream stream, Encoding? encoding)
{
InitStreamInput(baseUri, baseUriStr, stream, null, 0, encoding);
}
- private void InitStreamInput(Uri baseUri, string baseUriStr, Stream stream, byte[] bytes, int byteCount, Encoding encoding)
+ private void InitStreamInput(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);
{
encoding = DetectEncoding();
}
+
SetupEncoding(encoding);
// eat preamble
InitTextReaderInput(baseUriStr, null, input);
}
- private void InitTextReaderInput(string baseUriStr, Uri baseUri, TextReader input)
+ private void InitTextReaderInput(string baseUriStr, Uri? baseUri, TextReader input)
{
Debug.Assert(_ps.charPos == 0 && _ps.charsUsed == 0 && _ps.stream == null);
Debug.Assert(baseUriStr != null);
ReadData();
}
- private void InitStringInput(string baseUriStr, Encoding originalEncoding, string str)
+ private void InitStringInput(string baseUriStr, Encoding? originalEncoding, string str)
{
Debug.Assert(_ps.stream == null && _ps.textReader == null);
Debug.Assert(_ps.charPos == 0 && _ps.charsUsed == 0);
_ps.isEof = true;
}
- private void InitFragmentReader(XmlNodeType fragmentType, XmlParserContext parserContext, bool allowXmlDeclFragment)
+ private void InitFragmentReader(XmlNodeType fragmentType, XmlParserContext? parserContext, bool allowXmlDeclFragment)
{
_fragmentParserContext = parserContext;
if (parserContext.NamespaceManager != null)
{
_namespaceManager = parserContext.NamespaceManager;
- _xmlContext.defaultNamespace = _namespaceManager.LookupNamespace(string.Empty);
+ _xmlContext.defaultNamespace = _namespaceManager.LookupNamespace(string.Empty)!;
}
else
{
Throw(SR.Xml_PartialContentNodeTypeNotSupportedEx, fragmentType.ToString());
return;
}
+
_fragmentType = fragmentType;
_fragment = true;
}
try
{
- _ps.stream = (Stream)tmpResolver.GetEntity(_ps.baseUri, null, typeof(Stream));
+ _ps.stream = (Stream?)tmpResolver.GetEntity(_ps.baseUri, null, typeof(Stream));
}
catch
{
ThrowWithoutLineInfo(SR.Xml_CannotResolveUrl, _ps.baseUriStr);
}
+ Debug.Assert(_ps.stream != null);
InitStreamInput(_ps.baseUri, _ps.baseUriStr, _ps.stream, null);
_reportedEncoding = _ps.encoding;
}
// Stream input only: detect encoding from the first 4 bytes of the byte buffer starting at ps.bytes[ps.bytePos]
- private Encoding DetectEncoding()
+ private Encoding? DetectEncoding()
{
Debug.Assert(_ps.bytes != null);
Debug.Assert(_ps.bytePos == 0);
{
return null;
}
+
int first2Bytes = _ps.bytes[0] << 8 | _ps.bytes[1];
int next2Bytes = (_ps.bytesUsed >= 4) ? (_ps.bytes[2] << 8 | _ps.bytes[3]) : 0;
return null;
}
- private void SetupEncoding(Encoding encoding)
+ private void SetupEncoding(Encoding? encoding)
{
if (encoding == null)
{
private void EatPreamble()
{
+ Debug.Assert(_ps.encoding != null);
+ Debug.Assert(_ps.bytes != null);
ReadOnlySpan<byte> preamble = _ps.encoding.Preamble;
int preambleLen = preamble.Length;
int i;
// Switches the reader's encoding
private void SwitchEncoding(Encoding newEncoding)
{
+ Debug.Assert(_ps.encoding != null);
if ((newEncoding.WebName != _ps.encoding.WebName || _ps.decoder is SafeAsciiDecoder) && !_afterResetState)
{
Debug.Assert(_ps.stream != null);
// Performs checks whether switching from current encoding to specified encoding is allowed.
private Encoding CheckEncoding(string newEncodingName)
{
+ Debug.Assert(_ps.encoding != null);
+
// encoding can be switched on stream input only
if (_ps.stream == null)
{
return _ps.encoding;
}
- Encoding newEncoding = null;
+ Encoding? newEncoding = null;
if (string.Equals(newEncodingName, "utf-8", StringComparison.OrdinalIgnoreCase))
{
newEncoding = UTF8BomThrowing;
{
Throw(SR.Xml_UnknownEncoding, newEncodingName, innerEx);
}
+
+ Debug.Assert(newEncoding != null);
Debug.Assert(newEncoding.EncodingName != "UTF-8");
}
"We didn't correctly count some of the decoded characters against the MaxCharactersInDocument.");
_charactersInDocument -= _ps.charsUsed - _ps.charPos;
}
+
if (_maxCharactersFromEntities > 0)
{
if (InEntity)
_ps.bytePos = _documentStartBytePos; // byte position after preamble
if (_ps.charPos > 0)
{
+ Debug.Assert(_ps.encoding != null);
+ Debug.Assert(_ps.chars != null);
_ps.bytePos += _ps.encoding.GetByteCount(_ps.chars, 0, _ps.charPos);
}
+
_ps.charsUsed = _ps.charPos;
_ps.isEof = false;
}
return 0;
}
+ Debug.Assert(_ps.chars != null);
int charsRead;
if (_ps.appendMode)
{
// the byte buffer is full -> allocate a new one
if (_ps.bytesUsed - _ps.bytePos < MaxByteSequenceLen)
{
+ Debug.Assert(_ps.bytes != null);
if (_ps.bytes.Length - _ps.bytesUsed < MaxByteSequenceLen)
{
byte[] newBytes = new byte[_ps.bytes.Length * 2];
}
else
{
+ Debug.Assert(_ps.bytes != null);
BlockCopy(_ps.bytes, _ps.bytePos, _ps.bytes, 0, bytesLeft);
_ps.bytesUsed = bytesLeft;
}
+
_ps.bytePos = 0;
}
}
{
if (!_ps.isStreamEof)
{
+ Debug.Assert(_ps.bytes != null);
+
// read new bytes
if (_ps.bytePos == _ps.bytesUsed && _ps.bytes.Length - _ps.bytesUsed > 0)
{
Debug.Assert(_ps.charsUsed < _ps.chars.Length);
_ps.isEof = true;
}
+
_ps.chars[_ps.charsUsed] = (char)0;
return charsRead;
}
private int GetChars(int maxCharsCount)
{
Debug.Assert(_ps.stream != null && _ps.decoder != null && _ps.bytes != null);
+ Debug.Assert(_ps.chars != null);
Debug.Assert(maxCharsCount <= _ps.chars.Length - _ps.charsUsed - 1);
// determine the maximum number of bytes we can pass to the decoder
int chDec;
int bDec;
bool completed;
+ Debug.Assert(_ps.decoder != null);
+ Debug.Assert(_ps.bytes != null);
+ Debug.Assert(_ps.chars != null);
_ps.decoder.Convert(_ps.bytes, _ps.bytePos + bytesDecoded, 1, _ps.chars, _ps.charsUsed + charsDecoded, 2, false, out bDec, out chDec, out completed);
charsDecoded += chDec;
bytesDecoded += bDec;
}
+
Debug.Fail("We should get an exception again.");
}
catch (ArgumentException)
{
Throw(_ps.charsUsed, SR.Xml_InvalidCharInThisEncoding);
}
+
charsCount = charsDecoded;
bytesCount = bytesDecoded;
}
private void ShiftBuffer(int sourcePos, int destPos, int count)
{
+ Debug.Assert(_ps.chars != null);
BlockCopyChars(_ps.chars, sourcePos, _ps.chars, destPos, count);
}
}
if (!XmlConvert.StrEqual(_ps.chars, _ps.charPos, 5, XmlDeclarationBeginning) ||
- _xmlCharType.IsNameSingleChar(_ps.chars[_ps.charPos + 5])
+ _xmlCharType.IsNameSingleChar(_ps.chars![_ps.charPos + 5])
#if XML10_FIFTH_EDITION
|| xmlCharType.IsNCNameHighSurrogateChar( ps.chars[ps.charPos + 5] )
#endif
_curNode.SetLineInfo(_ps.LineNo, _ps.LinePos + 2);
_curNode.SetNamedNode(XmlNodeType.XmlDeclaration, _xml);
}
+
_ps.charPos += 5;
// parsing of text declarations cannot change global stringBuidler or curNode as we may be in the middle of a text node
// 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
+ Debug.Assert(_ps.encoding != null);
string encodingName = _ps.encoding.WebName;
if (encodingName != "utf-8" && encodingName != "utf-16" &&
encodingName != "utf-16BE" && !(_ps.encoding is Ucs4Encoding))
// read attribute name
int nameEndPos = ParseName();
- NodeData attr = null;
+ NodeData? attr = null;
switch (_ps.chars[_ps.charPos])
{
case 'v':
Throw(isTextDecl ? SR.Xml_InvalidTextDecl : SR.Xml_InvalidXmlDecl);
break;
}
+
if (!isTextDecl)
{
+ Debug.Assert(attr != null);
attr.SetLineInfo(_ps.LineNo, _ps.LinePos);
}
sb.Append(_ps.chars, _ps.charPos, nameEndPos - _ps.charPos);
_ps.charPos++;
if (!isTextDecl)
{
+ Debug.Assert(attr != null);
attr.quoteChar = quoteChar;
attr.SetLineInfo2(_ps.LineNo, _ps.LinePos);
}
#endif
if (!isTextDecl)
{
+ Debug.Assert(attr != null);
attr.SetValue(_ps.chars, _ps.charPos, pos - _ps.charPos);
}
xmlDeclState = 1;
encoding = CheckEncoding(encName);
if (!isTextDecl)
{
+ Debug.Assert(attr != null);
attr.SetValue(encName);
}
xmlDeclState = 2;
}
if (!isTextDecl)
{
+ Debug.Assert(attr != null);
attr.SetValue(_ps.chars, _ps.charPos, pos - _ps.charPos);
}
xmlDeclState = 3;
if (_afterResetState)
{
// check for invalid encoding switches to default encoding
+ Debug.Assert(_ps.encoding != null);
string encodingName = _ps.encoding.WebName;
if (encodingName != "utf-8" && encodingName != "utf-16" &&
encodingName != "utf-16BE" && !(_ps.encoding is Ucs4Encoding))
{
bool needMoreChars = false;
int pos = _ps.charPos;
+ Debug.Assert(_ps.chars != null);
char[] chars = _ps.chars;
// some tag
while (true)
{
int pos = _ps.charPos;
+ Debug.Assert(_ps.chars != null);
char[] chars = _ps.chars;
switch (chars[pos])
_stringBuilder.Append('.');
}
}
+
Throw(_ps.charsUsed, SR.Xml_UnexpectedEOFInElementContent, _stringBuilder.ToString());
}
}
private void ParseElement()
{
int pos = _ps.charPos;
+ Debug.Assert(_ps.chars != null);
char[] chars = _ps.chars;
int colonPos = -1;
SetElement:
// push namespace context
+ Debug.Assert(_namespaceManager != null);
_namespaceManager.PushScope();
// init the NodeData class
private void AddDefaultAttributesAndNormalize()
{
Debug.Assert(_curNode.type == XmlNodeType.Element);
+ Debug.Assert(_dtdInfo != null);
+ IDtdAttributeListInfo? attlistInfo = _dtdInfo.LookupAttributeList(_curNode.localName, _curNode.prefix);
- IDtdAttributeListInfo attlistInfo = _dtdInfo.LookupAttributeList(_curNode.localName, _curNode.prefix);
if (attlistInfo == null)
{
return;
if (defaultAttributes != null)
{
int originalAttrCount = _attrCount;
- NodeData[] nameSortedAttributes = null;
+ NodeData[]? nameSortedAttributes = null;
if (_attrCount >= MaxAttrDuplWalkCount)
{
}
int nameLen;
+ Debug.Assert(_ps.chars != null);
char[] chars = _ps.chars;
if (startTagNode.prefix.Length == 0)
{
int colonPos;
int endPos = ParseQName(out colonPos);
+ Debug.Assert(_ps.chars != null);
string[] args = new string[4];
args[0] = startTag.GetNameWPrefix(_nameTable);
args[1] = startTag.lineInfo.lineNo.ToString(CultureInfo.InvariantCulture);
private void ParseAttributes()
{
int pos = _ps.charPos;
+ Debug.Assert(_ps.chars != null);
char[] chars = _ps.chars;
- NodeData attr = null;
+ NodeData? attr = null;
Debug.Assert(_attrCount == 0);
{
PushXmlContext();
}
+
_xmlContext.defaultNamespace = ns;
AddNamespace(string.Empty, ns, attr);
{
PushXmlContext();
}
+
switch (XmlConvert.TrimString(attr.StringValue))
{
case "preserve":
{
PushXmlContext();
}
+
_xmlContext.xmlLang = attr.StringValue;
break;
}
private void ParseAttributeValueSlow(int curPos, char quoteChar, NodeData attr)
{
int pos = curPos;
+ Debug.Assert(_ps.chars != null);
char[] chars = _ps.chars;
int attributeBaseEntityId = _ps.entityId;
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;
+ Debug.Assert(_ps.entity != null);
entityChunk.SetNamedNode(XmlNodeType.EntityReference, _ps.entity.Name);
AddAttributeChunkToList(attr, entityChunk, ref lastChunk);
_stringBuilder.Length = 0;
}
- private void AddAttributeChunkToList(NodeData attr, NodeData chunk, ref NodeData lastChunk)
+ private void AddAttributeChunkToList(NodeData attr, NodeData chunk, ref NodeData? lastChunk)
{
if (lastChunk == null)
{
{
goto IgnoredNode;
}
+
XmlNodeType nodeType = GetTextNodeType(orChars);
if (nodeType == XmlNodeType.None)
{
goto IgnoredNode;
}
+
Debug.Assert(endPos - startPos > 0);
+ Debug.Assert(_ps.chars != null);
_curNode.SetValueNode(nodeType, _ps.chars, startPos, endPos - startPos);
return true;
}
if (orChars > 0x20)
{
Debug.Assert(endPos - startPos > 0);
+ Debug.Assert(_ps.chars != null);
_curNode.SetValueNode(XmlNodeType.Text, _ps.chars, startPos, endPos - startPos);
_nextParsingFunction = _parsingFunction;
_parsingFunction = ParsingFunction.PartialTextValue;
}
goto IgnoredNode;
}
+
// set value to curNode
_curNode.SetValueNode(nodeType, _stringBuilder.ToString());
_stringBuilder.Length = 0;
_nextParsingFunction = _parsingFunction;
_parsingFunction = ParsingFunction.PartialTextValue;
}
+
return true;
}
}
// Returns true when the whole value has been parsed. Return false when it needs to be called again to get a next chunk of value.
private bool ParseText(out int startPos, out int endPos, ref int outOrChars)
{
+ Debug.Assert(_ps.chars != null);
char[] chars = _ps.chars;
int pos = _ps.charPos;
int rcount = 0;
XmlNodeType nodeType = GetWhitespaceType();
+ Debug.Assert(_ps.chars != null);
if (nodeType == XmlNodeType.None)
{
EatWhitespaces(null);
private void ParseEntityReference()
{
+ Debug.Assert(_ps.chars != null);
Debug.Assert(_ps.chars[_ps.charPos] == '&');
_ps.charPos++;
private EntityType HandleEntityReference(bool isInAttributeValue, EntityExpandType expandType, out int charRefEndPos)
{
+ Debug.Assert(_ps.chars != null);
Debug.Assert(_ps.chars[_ps.charPos] == '&');
if (_ps.charPos + 1 == _ps.charsUsed)
// return false == unexpanded external entity, stop parsing and return
private EntityType HandleGeneralEntityReference(string name, bool isInAttributeValue, bool pushFakeEntityIfNullResolver, int entityStartLinePos)
{
- IDtdEntityInfo entity = null;
+ IDtdEntityInfo? entity = null;
if (_dtdInfo == null && _fragmentParserContext != null && _fragmentParserContext.HasDtdInfo && _dtdProcessing == DtdProcessing.Parse)
{
Throw(SR.Xml_UndeclaredEntity, name, _ps.LineNo, entityStartLinePos);
}
+ Debug.Assert(entity != null);
+
if (entity.IsUnparsedEntity)
{
if (_disableUndeclaredEntityCheck)
{
_curNode = _nodes[_index + _attrCount + 1];
Debug.Assert(_curNode.type == XmlNodeType.EntityReference);
+ Debug.Assert(_lastEntity != null);
Debug.Assert(Ref.Equal(_lastEntity.Name, _curNode.localName));
_curNode.lineInfo.linePos += _curNode.localName.Length;
_curNode.type = XmlNodeType.EndEntity;
// 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 bool ParsePI(StringBuilder piInDtdStringBuilder)
+ private bool ParsePI(StringBuilder? piInDtdStringBuilder)
{
if (_parsingMode == ParsingMode.Full)
{
// parse target name
int nameEndPos = ParseName();
+ Debug.Assert(_ps.chars != null);
string target = _nameTable.Add(_ps.chars, _ps.charPos, nameEndPos - _ps.charPos);
if (string.Equals(target, "xml", StringComparison.OrdinalIgnoreCase))
_stringBuilder.Length = 0;
}
}
+
return true;
}
}
}
+ Debug.Assert(_ps.chars != null);
int pos = _ps.charPos;
char[] chars = _ps.chars;
int rcount = 0;
Debug.Assert(_stringBuilder.Length == 0);
if (ParseCDataOrComment(type, out startPos, out endPos))
{
+ Debug.Assert(_ps.chars != null);
_curNode.SetValueNode(type, _ps.chars, startPos, endPos - startPos);
}
else
{
_stringBuilder.Append(_ps.chars, startPos, endPos - startPos);
} while (!ParseCDataOrComment(type, out startPos, out endPos));
+
_stringBuilder.Append(_ps.chars, startPos, endPos - startPos);
_curNode.SetValueNode(type, _stringBuilder.ToString());
_stringBuilder.Length = 0;
}
}
+ Debug.Assert(_ps.chars != null);
int pos = _ps.charPos;
char[] chars = _ps.chars;
int rcount = 0;
Throw(SR.Xml_UnexpectedEOF, "DOCTYPE");
}
}
+
if (!XmlConvert.StrEqual(_ps.chars, _ps.charPos, 7, "DOCTYPE"))
{
ThrowUnexpectedToken((!_rootElementParsed && _dtdInfo == null) ? "DOCTYPE" : "<!--");
}
+
+ Debug.Assert(_ps.chars != null);
if (!_xmlCharType.IsWhiteSpace(_ps.chars[_ps.charPos + 7]))
{
ThrowExpectingWhitespace(_ps.charPos + 7);
{
Throw(_ps.charPos - 2, SR.Xml_MultipleDTDsProvided); // position just before <!DOCTYPE
}
+
if (_rootElementParsed)
{
Throw(_ps.charPos - 2, SR.Xml_DtdAfterRootElement);
EatWhitespaces(null);
// PUBLIC Id
+ Debug.Assert(_ps.chars != null);
if (_ps.chars[_ps.charPos] == 'P')
{
// make sure we have enough characters
private void SkipPublicOrSystemIdLiteral()
{
+ Debug.Assert(_ps.chars != null);
// check quote char
char quoteChar = _ps.chars[_ps.charPos];
if (quoteChar != '"' && quoteChar != '\'')
bool inPI = false;
char literalQuote = '"';
+ Debug.Assert(_ps.chars != null);
char[] chars = _ps.chars;
int pos = _ps.charPos;
}
}
- private int EatWhitespaces(StringBuilder sb)
+ private int EatWhitespaces(StringBuilder? sb)
{
int pos = _ps.charPos;
int wsCount = 0;
+ Debug.Assert(_ps.chars != null);
char[] chars = _ps.chars;
while (true)
private int ParseCharRefInline(int startPos, out int charCount, out EntityType entityType)
{
+ Debug.Assert(_ps.chars != null);
Debug.Assert(_ps.chars[startPos] == '&');
if (_ps.chars[startPos + 1] == '#')
{
// character or surrogates pair (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 int ParseNumericCharRef(bool expand, StringBuilder internalSubsetBuilder, out EntityType entityType)
+ private int ParseNumericCharRef(bool expand, StringBuilder? internalSubsetBuilder, out EntityType entityType)
{
while (true)
{
{
Throw(SR.Xml_UnexpectedEOF);
}
+
+ Debug.Assert(_ps.chars != null);
Debug.Assert(_ps.chars[_ps.charPos] == '&');
continue;
default:
// - replaces the last one or two character of the entity reference (';' and the character before) with the referenced
// character or surrogates pair (if expand == true)
// - returns position of the end of the character reference, that is of the character next to the original ';'
- private int ParseNumericCharRefInline(int startPos, bool expand, StringBuilder internalSubsetBuilder, out int charCount, out EntityType entityType)
+ private int ParseNumericCharRefInline(int startPos, bool expand, StringBuilder? internalSubsetBuilder, out int charCount, out EntityType entityType)
{
+ Debug.Assert(_ps.chars != null);
Debug.Assert(_ps.chars[startPos] == '&' && _ps.chars[startPos + 1] == '#');
int val;
char[] chars;
val = 0;
- string badDigitExceptionString = null;
+ string? badDigitExceptionString = null;
chars = _ps.chars;
pos = startPos + 2;
charCount = 0;
{
_ps.charPos = pos;
entityType = EntityType.Skipped;
- Throw(SR.Xml_CharEntityOverflow, (string)null, e);
+ Throw(SR.Xml_CharEntityOverflow, (string?)null, e);
}
+ Debug.Assert(badDigitExceptionString != null);
+
if (chars[pos] != ';' || digitPos == pos)
{
if (pos == _ps.charsUsed)
// - 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 int ParseNamedCharRef(bool expand, StringBuilder internalSubsetBuilder)
+ private int ParseNamedCharRef(bool expand, StringBuilder? internalSubsetBuilder)
{
while (true)
{
{
return -1;
}
+
+ Debug.Assert(_ps.chars != null);
Debug.Assert(_ps.chars[_ps.charPos] == '&');
continue;
default:
// Otherwise
// - 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 ';'
- private int ParseNamedCharRefInline(int startPos, bool expand, StringBuilder internalSubsetBuilder)
+ private int ParseNamedCharRefInline(int startPos, bool expand, StringBuilder? internalSubsetBuilder)
{
Debug.Assert(startPos < _ps.charsUsed);
+ Debug.Assert(_ps.chars != null);
Debug.Assert(_ps.chars[startPos] == '&');
Debug.Assert(_ps.chars[startPos + 1] != '#');
int pos = _ps.charPos + startOffset;
ContinueStartName:
+ Debug.Assert(_ps.chars != null);
char[] chars = _ps.chars;
// start name char
{
if (ReadDataInName(ref pos))
{
+ Debug.Assert(_ps.chars != null);
chars = _ps.chars;
goto ContinueName;
}
catch (XmlException)
{
Throw(SR.Xml_ErrorParsingEntityName);
- return null;
+ return null!;
}
+ Debug.Assert(_ps.chars != null);
+
// check ';'
if (_ps.chars[endPos] != ';')
{
private NodeData AddAttribute(int endNamePos, int colonPos)
{
+ Debug.Assert(_ps.chars != null);
+
// setup attribute name
if (colonPos == -1 || !_supportNamespaces)
{
}
}
- private NodeData AddAttribute(string localName, string prefix, string nameWPrefix)
+ private NodeData AddAttribute(string localName, string prefix, string? nameWPrefix)
{
NodeData newAttr = AddNode(_index + _attrCount + 1, _index + 1);
private void PopElementContext()
{
+ Debug.Assert(_namespaceManager != null);
// pop namespace context
_namespaceManager.PopScope();
private string LookupNamespace(NodeData node)
{
- string ns = _namespaceManager.LookupNamespace(node.prefix);
+ Debug.Assert(_namespaceManager != null);
+ string? ns = _namespaceManager.LookupNamespace(node.prefix);
if (ns != null)
{
return ns;
else
{
Throw(SR.Xml_UnknownNs, node.prefix, node.LineNo, node.LinePos);
- return null;
+ return null!;
}
}
Throw(SR.Xml_BadNamespaceDecl, (int)attr.lineInfo.lineNo, (int)attr.lineInfo.linePos);
}
+ Debug.Assert(_namespaceManager != null);
+
try
{
_namespaceManager.AddNamespace(prefix, uri);
{
FullAttributeCleanup();
}
+
_curAttrIndex = -1;
_attrCount = 0;
_attrHashtable = 0;
private void PopXmlContext()
{
Debug.Assert(_curNode.xmlContextPushed);
- _xmlContext = _xmlContext.previousContext;
+ _xmlContext = _xmlContext.previousContext!;
_curNode.xmlContextPushed = false;
}
{
return XmlNodeType.SignificantWhitespace;
}
+
if (_whitespaceHandling == WhitespaceHandling.All)
{
return XmlNodeType.Whitespace;
}
}
+
return XmlNodeType.None;
}
// 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 void PushExternalEntityOrSubset(string publicId, string systemId, Uri baseUri, string entityName)
+ private void PushExternalEntityOrSubset(string? publicId, string? systemId, Uri? baseUri, string? entityName)
{
Uri uri;
+ Debug.Assert(_xmlResolver != null);
+
// First try opening the external reference by PUBLIC Id
if (!string.IsNullOrEmpty(publicId))
{
{
return;
}
+
// resolver returned null, throw exception outside this try-catch
}
catch (Exception e)
{
throw;
}
+
string innerMessage = e.Message;
Throw(new XmlException(entityName == null ? SR.Xml_ErrorOpeningExternalDtd : SR.Xml_ErrorOpeningExternalEntity, new string[] { uri.ToString(), innerMessage }, e, 0, 0));
}
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
{
// First try to get the data as a TextReader
if (_xmlResolver.SupportsType(uri, typeof(TextReader)))
{
- TextReader textReader = (TextReader)_xmlResolver.GetEntity(uri, null, typeof(TextReader));
+ TextReader? textReader = (TextReader?)_xmlResolver.GetEntity(uri, null, typeof(TextReader));
if (textReader == null)
{
return false;
// Then try get it as a Stream
Debug.Assert(_xmlResolver.SupportsType(uri, typeof(Stream)), "Stream must always be a supported type in XmlResolver");
- Stream stream = (Stream)_xmlResolver.GetEntity(uri, null, typeof(Stream));
+ Stream? stream = (Stream?)_xmlResolver.GetEntity(uri, null, typeof(Stream));
if (stream == null)
{
return false;
PushParsingState();
InitStreamInput(uri, stream, null);
}
+
return true;
}
if (!IsResolverNull)
{
- Uri entityBaseUri = null;
+ Debug.Assert(_xmlResolver != null);
+ Uri? entityBaseUri = null;
if (!string.IsNullOrEmpty(entity.BaseUriString))
{
entityBaseUri = _xmlResolver.ResolveUri(null, entity.BaseUriString);
}
+
PushExternalEntityOrSubset(entity.PublicId, entity.SystemId, entityBaseUri, entity.Name);
RegisterEntity(entity);
{
EatWhitespaces(null);
}
+
if (!ParseXmlDeclaration(true))
{
_ps.charPos = initialPos;
}
+
return true;
}
else
{
- Encoding enc = _ps.encoding;
+ Encoding? enc = _ps.encoding;
PushParsingState();
InitStringInput(entity.SystemId, enc, string.Empty);
{
Debug.Assert(!entity.IsExternal);
- Encoding enc = _ps.encoding;
+ Encoding? enc = _ps.encoding;
PushParsingState();
- InitStringInput((entity.DeclaredUriString != null) ? entity.DeclaredUriString : string.Empty, enc, entity.Text ?? string.Empty);
+ InitStringInput(entity.DeclaredUriString ?? string.Empty, enc, entity.Text);
RegisterEntity(entity);
{
_ps.stream.Dispose();
}
+
UnregisterEntity();
PopParsingState();
_curNode.entityId = _ps.entityId;
if (_currentEntities.ContainsKey(entity))
{
Throw(entity.IsParameterEntity ? SR.Xml_RecursiveParEntity : SR.Xml_RecursiveGenEntity, entity.Name,
- _parsingStatesStack[_parsingStatesStackTop].LineNo, _parsingStatesStack[_parsingStatesStackTop].LinePos);
+ _parsingStatesStack![_parsingStatesStackTop].LineNo, _parsingStatesStack[_parsingStatesStackTop].LinePos);
}
}
{
_currentEntities = new Dictionary<IDtdEntityInfo, IDtdEntityInfo>();
}
+
_currentEntities.Add(entity, entity);
}
}
// remove from recursion check registry
if (_ps.entity != null)
{
- _currentEntities.Remove(_ps.entity);
+ _currentEntities!.Remove(_ps.entity);
}
}
private void PopParsingState()
{
Debug.Assert(_parsingStatesStackTop >= 0);
+ Debug.Assert(_parsingStatesStack != null);
_ps.Close(true);
_ps = _parsingStatesStack[_parsingStatesStackTop--];
}
{
throw new ArgumentNullException((_incReadDecoder is IncrementalReadCharsDecoder) ? "buffer" : nameof(array));
}
+
if (count < 0)
{
throw new ArgumentOutOfRangeException((_incReadDecoder is IncrementalReadCharsDecoder) ? nameof(count) : "len");
}
+
if (index < 0)
{
throw new ArgumentOutOfRangeException((_incReadDecoder is IncrementalReadCharsDecoder) ? nameof(index) : "offset");
}
+
if (array.Length - index < count)
{
throw new ArgumentException((_incReadDecoder is IncrementalReadCharsDecoder) ? nameof(count) : "len");
return 0;
}
+ Debug.Assert(_incReadDecoder != null);
_curNode.lineInfo = _incReadLineInfo;
_incReadDecoder.SetNextOutputBuffer(array, index, count);
private int IncrementalRead()
{
+ Debug.Assert(_incReadDecoder != null);
int charsDecoded = 0;
OuterContinue:
_incReadState == IncrementalReadState.Attributes ||
_incReadState == IncrementalReadState.AttributeValue);
+ Debug.Assert(_ps.chars != null);
char[] chars = _ps.chars;
startPos = _ps.charPos;
pos = startPos;
ReThrow(e, (int)_incReadLineInfo.lineNo, (int)_incReadLineInfo.linePos);
return 0;
}
+
Debug.Assert(count == charsParsed || _incReadDecoder.IsFull, "Check if decoded consumed all characters unless it's full.");
charsDecoded += count;
if (_incReadDecoder.IsFull)
private bool ParseAttributeValueChunk()
{
+ Debug.Assert(_ps.chars != null);
+
char[] chars = _ps.chars;
int pos = _ps.charPos;
{
_stringBuilder.Append(chars, _ps.charPos, pos - _ps.charPos);
}
+
_ps.charPos = pos;
// expand char entities but not general entities
{
goto ReadData;
}
+
pos++;
if (XmlCharType.IsLowSurrogate(chars[pos]))
{
continue;
}
}
+
ThrowInvalidChar(chars, _ps.charsUsed, pos);
break;
}
_stringBuilder.Append(chars, _ps.charPos, pos - _ps.charPos);
_ps.charPos = pos;
}
+
// read new characters into the buffer
if (ReadData() == 0)
{
_stringBuilder.Append(chars, _ps.charPos, pos - _ps.charPos);
_ps.charPos = pos;
}
+
_curNode.SetValueNode(XmlNodeType.Text, _stringBuilder.ToString());
_stringBuilder.Length = 0;
return true;
ThrowUnexpectedToken(expectedToken1, null);
}
- private void ThrowUnexpectedToken(int pos, string expectedToken1, string expectedToken2)
+ private void ThrowUnexpectedToken(int pos, string expectedToken1, string? expectedToken2)
{
_ps.charPos = pos;
ThrowUnexpectedToken(expectedToken1, expectedToken2);
}
- private void ThrowUnexpectedToken(string expectedToken1, string expectedToken2)
+ private void ThrowUnexpectedToken(string expectedToken1, string? expectedToken2)
{
- string unexpectedToken = ParseUnexpectedToken();
+ string? unexpectedToken = ParseUnexpectedToken();
if (unexpectedToken == null)
{
Throw(SR.Xml_UnexpectedEOF1);
}
+
if (expectedToken2 != null)
{
- Throw(SR.Xml_UnexpectedTokens2, new string[3] { unexpectedToken, expectedToken1, expectedToken2 });
+ Throw(SR.Xml_UnexpectedTokens2, new string?[3] { unexpectedToken, expectedToken1, expectedToken2 });
}
else
{
- Throw(SR.Xml_UnexpectedTokenEx, new string[2] { unexpectedToken, expectedToken1 });
+ Throw(SR.Xml_UnexpectedTokenEx, new string?[2] { unexpectedToken, expectedToken1 });
}
}
- private string ParseUnexpectedToken(int pos)
+ private string? ParseUnexpectedToken(int pos)
{
_ps.charPos = pos;
return ParseUnexpectedToken();
}
- private string ParseUnexpectedToken()
+ private string? ParseUnexpectedToken()
{
if (_ps.charPos == _ps.charsUsed)
{
return null;
}
+
+ Debug.Assert(_ps.chars != null);
+
if (_xmlCharType.IsNCNameSingleChar(_ps.chars[_ps.charPos]))
{
int pos = _ps.charPos + 1;
private void ThrowExpectingWhitespace(int pos)
{
- string unexpectedToken = ParseUnexpectedToken(pos);
+ string? unexpectedToken = ParseUnexpectedToken(pos);
+
if (unexpectedToken == null)
{
Throw(pos, SR.Xml_UnexpectedEOF1);
private int GetIndexOfAttributeWithoutPrefix(string name)
{
- name = _nameTable.Get(name);
- if (name == null)
+ string? atomizedName = _nameTable.Get(name);
+ if (atomizedName == null)
{
return -1;
}
+
for (int i = _index + 1; i < _index + _attrCount + 1; i++)
{
- if (Ref.Equal(_nodes[i].localName, name) && _nodes[i].prefix.Length == 0)
+ if (Ref.Equal(_nodes[i].localName, atomizedName) && _nodes[i].prefix.Length == 0)
{
return i;
}
}
+
return -1;
}
private int GetIndexOfAttributeWithPrefix(string name)
{
name = _nameTable.Add(name);
+
if (name == null)
{
return -1;
}
+
for (int i = _index + 1; i < _index + _attrCount + 1; i++)
{
if (Ref.Equal(_nodes[i].GetNameWPrefix(_nameTable), name))
return i;
}
}
+
return -1;
}
// Note that this method calls ReadData() which may change the value of ps.chars and ps.charPos.
private bool ZeroEndingStream(int pos)
{
+ Debug.Assert(_ps.chars != null);
+
if (_v1Compat && pos == _ps.charsUsed - 1 && _ps.chars[pos] == (char)0 && ReadData() == 0 && _ps.isStreamEof)
{
_ps.charsUsed--;
return true;
}
+
return false;
}
{
throw new InvalidOperationException(SR.Xml_MixingReadValueChunkWithBinary);
}
+
if (_parsingFunction == ParsingFunction.InIncrementalRead)
{
throw new InvalidOperationException(SR.Xml_MixingV1StreamingWithV2Binary);
// move to content or off the empty element
_outerReader.Read();
+
if (isEmpty)
{
return false;
{
Throw(SR.Xml_InvalidNodeType, _curNode.type.ToString());
}
+
// move off end element
_outerReader.Read();
return false;
}
+
SetupReadContentAsBinaryState(ParsingFunction.InReadElementContentAsBinary);
_incReadLineInfo.Set(_curNode.LineNo, _curNode.LinePos);
return true;
}
moveIfOnContentNode = false;
} while (_outerReader.Read());
+
return false;
}
_parsingFunction = inReadBinaryFunction;
}
+ [MemberNotNull(nameof(_nameTable))]
private void SetupFromParserContext(XmlParserContext context, XmlReaderSettings settings)
{
Debug.Assert(context != null);
// setup nameTable
- XmlNameTable nt = settings.NameTable;
+ XmlNameTable? nt = settings.NameTable;
_nameTableFromSettings = (nt != null);
// get name table from namespace manager in XmlParserContext, if available;
}
// get the namespace manager from context
_namespaceManager = context.NamespaceManager;
- _xmlContext.defaultNamespace = _namespaceManager.LookupNamespace(string.Empty);
+ _xmlContext.defaultNamespace = _namespaceManager.LookupNamespace(string.Empty)!;
// get the nametable from ns manager
nt = _namespaceManager.NameTable;
//
// DtdInfo
//
- internal override IDtdInfo DtdInfo
+ internal override IDtdInfo? DtdInfo
{
get
{
_curNode.type = newNodeType;
}
- internal XmlResolver GetResolver()
+ internal XmlResolver? GetResolver()
{
if (IsResolverNull)
return null;
return _xmlResolver;
}
- internal object InternalSchemaType
+ internal object? InternalSchemaType
{
get
{
}
}
- internal object InternalTypedValue
+ internal object? InternalTypedValue
{
get
{
}
}
- internal override XmlNamespaceManager NamespaceManager
+ internal override XmlNamespaceManager? NamespaceManager
{
get
{
}
}
- private bool AddDefaultAttributeDtd(IDtdDefaultAttributeInfo defAttrInfo, bool definedInDtd, NodeData[] nameSortedNodeData)
+ private bool AddDefaultAttributeDtd(IDtdDefaultAttributeInfo defAttrInfo, bool definedInDtd, NodeData[]? nameSortedNodeData)
{
if (defAttrInfo.Prefix.Length > 0)
{
{
_onDefaultAttributeUse(defAttrInfo, this);
}
+
attr.typedValue = defAttrInfo.DefaultValueTyped;
}
return attr != null;
{
// atomize names - Xsd Validator does not need to have the same nametable
string localName = _nameTable.Add(attrDef.Name.Name);
- string prefix = _nameTable.Add(attrDef.Prefix);
+ string? prefix = _nameTable.Add(attrDef.Prefix);
string ns = _nameTable.Add(attrDef.Name.Namespace);
// atomize namespace - Xsd Validator does not need to have the same nametable
if (prefix.Length == 0 && ns.Length > 0)
{
+ Debug.Assert(_namespaceManager != null);
prefix = _namespaceManager.LookupPrefix(ns);
Debug.Assert(prefix != null);
for (int i = _index + 1; i < _index + 1 + _attrCount; i++)
{
if ((object)_nodes[i].localName == (object)localName &&
- (((object)_nodes[i].prefix == (object)prefix) || ((object)_nodes[i].ns == (object)ns && ns != null)))
+ (((object?)_nodes[i].prefix == (object?)prefix) || ((object?)_nodes[i].ns == (object?)ns && ns != null)))
{
return false;
}
return true;
}
- private NodeData AddDefaultAttributeInternal(string localName, string ns, string prefix, string value,
+ private NodeData AddDefaultAttributeInternal(string localName, string? ns, string prefix, string value,
int lineNo, int linePos, int valueLineNo, int valueLinePos, bool isXmlAttribute)
{
// setup the attribute
// change namespace of current element and attributes
string pref = attr.localName;
Debug.Assert(_nodes[_index].type == XmlNodeType.Element);
+ Debug.Assert(_namespaceManager != null);
for (int i = _index; i < _index + _attrCount + 1; i++)
{
if (_nodes[i].prefix.Equals(pref))
if (_incReadDecoder.IsFull)
{
+ Debug.Assert(_ps.chars != null);
_curNode.SetValue(_ps.chars, startPos, endPos - startPos);
// adjust line info for the chunk that has been already decoded
AdjustLineInfo(_ps.chars, startPos - charsRead, startPos, _ps.eolNormalized, ref _incReadLineInfo);
_incReadState = IncrementalReadState.ReadContentAsBinary_End;
return _incReadDecoder.DecodedCount;
}
+
SetupReadContentAsBinaryState(tmp);
_incReadLineInfo.Set(_curNode.LineNo, _curNode.LinePos);
}
{
return 0;
}
+
int decoded = ReadContentAsBinary(buffer, index, count);
if (decoded > 0)
{
}
// 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)
{
return uri1Str == uri2Str;
}
+
if (uri1 == null)
{
uri1 = resolver.ResolveUri(null, uri1Str);
}
+
Uri uri2 = resolver.ResolveUri(null, uri2Str);
return uri1.Equals(uri2);
}
}
int startPos = 0;
- StringBuilder norValue = null;
+ StringBuilder? norValue = null;
while (value[startPos] == 0x20)
{
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;
using System.Globalization;
using System.Collections.Generic;
using System.Runtime.Versioning;
+using System.Diagnostics.CodeAnalysis;
namespace System.Xml
{
private struct ParsingState
{
// character buffer
- internal char[] chars;
+ internal char[]? chars;
internal int charPos;
internal int charsUsed;
- internal Encoding encoding;
+ internal Encoding? encoding;
internal bool appendMode;
// input stream & byte buffer
- internal Stream stream;
- internal Decoder decoder;
- internal byte[] bytes;
+ internal Stream? stream;
+ internal Decoder? decoder;
+ internal byte[]? bytes;
internal int bytePos;
internal int bytesUsed;
// input text reader
- internal TextReader textReader;
+ internal TextReader? textReader;
// current line number & position
internal int lineNo;
// base uri of the current entity
internal string baseUriStr;
- internal Uri baseUri;
+ internal Uri? baseUri;
// eof flag of the entity
internal bool isEof;
internal bool isStreamEof;
// entity type & id
- internal IDtdEntityInfo entity;
+ internal IDtdEntityInfo? entity;
internal int entityId;
// normalization
internal XmlSpace xmlSpace;
internal string xmlLang;
internal string defaultNamespace;
- internal XmlContext previousContext;
+ internal XmlContext? previousContext;
internal XmlContext()
{
public override bool PopScope() { return false; }
public override void AddNamespace(string prefix, string uri) { }
public override void RemoveNamespace(string prefix, string uri) { }
- public override IEnumerator GetEnumerator() { return null; }
- public override IDictionary<string, string> GetNamespacesInScope(XmlNamespaceScope scope) { return null; }
+ public override IEnumerator GetEnumerator() { return null!; }
+ public override IDictionary<string, string> GetNamespacesInScope(XmlNamespaceScope scope) { return null!; }
public override string LookupNamespace(string prefix) { return string.Empty; }
- public override string LookupPrefix(string uri) { return null; }
+ public override string? LookupPrefix(string uri) { return null; }
public override bool HasNamespace(string prefix) { return false; }
}
get { return _reader.DtdParserProxy_NameTable; }
}
- IXmlNamespaceResolver IDtdParserAdapter.NamespaceResolver
+ IXmlNamespaceResolver? IDtdParserAdapter.NamespaceResolver
{
get { return _reader.DtdParserProxy_NamespaceResolver; }
}
- Uri IDtdParserAdapter.BaseUri
+ Uri? IDtdParserAdapter.BaseUri
{
// SxS: DtdParserProxy_BaseUri property on the reader may expose machine scope resources. This property
// is just returning the value of the other property, so it may expose machine scope resource as well.
get { return _reader.DtdParserProxy_IsEof; }
}
- char[] IDtdParserAdapter.ParsingBuffer
+ char[]? IDtdParserAdapter.ParsingBuffer
{
get { return _reader.DtdParserProxy_ParsingBuffer; }
}
return _reader.DtdParserProxy_PushEntity(entity, out entityId);
}
- bool IDtdParserAdapter.PopEntity(out IDtdEntityInfo oldEntity, out int newEntityId)
+ bool IDtdParserAdapter.PopEntity(out IDtdEntityInfo? oldEntity, out int newEntityId)
{
return _reader.DtdParserProxy_PopEntity(out oldEntity, out newEntityId);
}
get { return _reader.DtdParserProxy_DtdValidation; }
}
- IValidationEventHandling IDtdParserAdapterWithValidation.ValidationEventHandling
+ IValidationEventHandling? IDtdParserAdapterWithValidation.ValidationEventHandling
{
get { return _reader.DtdParserProxy_ValidationEventHandling; }
}
private class NodeData : IComparable
{
// static instance with no data - is used when XmlTextReader is closed
- private static volatile NodeData s_None;
+ private static volatile NodeData? s_None;
// NOTE: Do not use this property for reference comparison. It may not be unique.
internal static NodeData None
internal XmlNodeType type;
// name
- internal string localName;
- internal string prefix;
- internal string ns;
- internal string nameWPrefix;
+ internal string localName = null!;
+ internal string prefix = null!;
+ internal string? ns;
+ internal string? nameWPrefix;
// value:
// value == null -> the value is kept in the 'chars' buffer starting at valueStartPos and valueLength long
- private string _value;
- private char[] _chars;
+ private string? _value;
+ private char[]? _chars;
private int _valueStartPos;
private int _valueLength;
internal bool xmlContextPushed;
// attribute value chunks
- internal NodeData nextAttrValueChunk;
+ internal NodeData? nextAttrValueChunk;
// type info
- internal object schemaType;
- internal object typedValue;
+ internal object? schemaType;
+ internal object? typedValue;
internal NodeData()
{
if (_value == null)
{
+ Debug.Assert(_chars != null);
_value = new string(_chars, _valueStartPos, _valueLength);
}
return _value;
{
if (ValueBuffered)
{
+ Debug.Assert(_chars != null);
XmlTextReaderImpl.StripSpaces(_chars, _valueStartPos, ref _valueLength);
}
else
{
+ Debug.Assert(_value != null);
_value = XmlTextReaderImpl.StripSpaces(_value);
}
}
+ [MemberNotNull("_value")]
+ [MemberNotNull("nameWPrefix")]
+ [MemberNotNull("localName")]
+ [MemberNotNull("prefix")]
+ [MemberNotNull("ns")]
internal void Clear(XmlNodeType type)
{
this.type = type;
ClearName();
_value = string.Empty;
_valueStartPos = -1;
- nameWPrefix = string.Empty;
schemaType = null;
typedValue = null;
}
+ [MemberNotNull("localName")]
+ [MemberNotNull("prefix")]
+ [MemberNotNull("ns")]
+ [MemberNotNull("nameWPrefix")]
internal void ClearName()
{
localName = string.Empty;
SetNamedNode(type, localName, string.Empty, localName);
}
- internal void SetNamedNode(XmlNodeType type, string localName, string prefix, string nameWPrefix)
+ internal void SetNamedNode(XmlNodeType type, string localName, string prefix, string? nameWPrefix)
{
Debug.Assert(localName != null);
Debug.Assert(localName.Length > 0);
}
if (_valueStartPos != -1)
{
+ Debug.Assert(_chars != null);
XmlTextReaderImpl.AdjustLineInfo(_chars, _valueStartPos, _valueStartPos + valueOffset, isNormalized, ref lineInfo);
}
else
{
+ Debug.Assert(_value != null);
XmlTextReaderImpl.AdjustLineInfo(_value, 0, valueOffset, isNormalized, ref lineInfo);
}
}
return nameWPrefix;
}
- int IComparable.CompareTo(object obj)
+ int IComparable.CompareTo(object? obj)
{
- NodeData other = obj as NodeData;
+ NodeData? other = obj as NodeData;
if (other != null)
{
if (Ref.Equal(localName, other.localName))
get { return s_instance; }
}
- public int Compare(object x, object y)
+ public int Compare(object? x, object? y)
{
Debug.Assert(x == null || x is NodeData || x is IDtdDefaultAttributeInfo);
Debug.Assert(y == null || y is NodeData || y is IDtdDefaultAttributeInfo);
return 1;
}
- NodeData nodeData = x as NodeData;
+ NodeData? nodeData = x as NodeData;
if (nodeData != null)
{
localName = nodeData.localName;
}
else
{
- IDtdDefaultAttributeInfo attrDef = x as IDtdDefaultAttributeInfo;
+ IDtdDefaultAttributeInfo? attrDef = x as IDtdDefaultAttributeInfo;
if (attrDef != null)
{
localName = attrDef.LocalName;
}
else
{
- IDtdDefaultAttributeInfo attrDef = y as IDtdDefaultAttributeInfo;
+ IDtdDefaultAttributeInfo? attrDef = y as IDtdDefaultAttributeInfo;
if (attrDef != null)
{
localName2 = attrDef.LocalName;
// 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;
public abstract partial class XmlWriter : IDisposable
{
// Helper buffer for WriteNode(XmlReader, bool)
- private char[] _writeNodeBuffer;
+ private char[]? _writeNodeBuffer;
// Constants
private const int WriteNodeBufferSize = 1024;
// Returns the settings describing the features of the writer. Returns null for V1 XmlWriters (XmlTextWriter).
- public virtual XmlWriterSettings Settings
+ public virtual XmlWriterSettings? Settings
{
get
{
// Writes out the DOCTYPE declaration with the specified name and optional attributes.
- public abstract void WriteDocType(string name, string pubid, string sysid, string subset);
+ public abstract void WriteDocType(string name, string? pubid, string? sysid, string subset);
// Writes out the specified start tag and associates it with the given namespace.
- public void WriteStartElement(string localName, string ns)
+ public void WriteStartElement(string localName, string? ns)
{
WriteStartElement(null, localName, ns);
}
// Writes out the specified start tag and associates it with the given namespace and prefix.
- public abstract void WriteStartElement(string prefix, string localName, string ns);
+ public abstract void WriteStartElement(string? prefix, string localName, string? ns);
// Writes out a start tag with the specified local name with no namespace.
public void WriteStartElement(string localName)
{
- WriteStartElement(null, localName, (string)null);
+ WriteStartElement(null, localName, (string?)null);
}
// Closes one element and pops the corresponding namespace scope.
public abstract void WriteFullEndElement();
// Writes out the attribute with the specified LocalName, value, and NamespaceURI.
- public void WriteAttributeString(string localName, string ns, string value)
+ public void WriteAttributeString(string localName, string? ns, string value)
{
WriteStartAttribute(null, localName, ns);
WriteString(value);
// Writes out the attribute with the specified LocalName and value.
public void WriteAttributeString(string localName, string value)
{
- WriteStartAttribute(null, localName, (string)null);
+ WriteStartAttribute(null, localName, (string?)null);
WriteString(value);
WriteEndAttribute();
}
// 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 the start of an attribute.
- public void WriteStartAttribute(string localName, string ns)
+ public void WriteStartAttribute(string localName, string? ns)
{
WriteStartAttribute(null, localName, ns);
}
// Writes the start of an attribute.
- public abstract void WriteStartAttribute(string prefix, string localName, string ns);
+ public abstract void WriteStartAttribute(string? prefix, string localName, string? ns);
// Writes the start of an attribute.
public void WriteStartAttribute(string localName)
{
- WriteStartAttribute(null, localName, (string)null);
+ WriteStartAttribute(null, localName, (string?)null);
}
// Closes the attribute opened by WriteStartAttribute call.
public abstract void Flush();
// Returns the closest prefix defined in the current namespace scope for the specified namespace URI.
- public abstract string LookupPrefix(string ns);
+ public abstract string? LookupPrefix(string ns);
// Gets an XmlSpace representing the current xml:space scope.
public virtual XmlSpace XmlSpace
}
// Writes out the specified namespace-qualified name by looking up the prefix that is in scope for the given namespace.
- public virtual void WriteQualifiedName(string localName, string ns)
+ public virtual void WriteQualifiedName(string localName, string? ns)
{
if (ns != null && ns.Length > 0)
{
- string prefix = LookupPrefix(ns);
+ string? prefix = LookupPrefix(ns);
if (prefix == null)
{
throw new ArgumentException(SR.Format(SR.Xml_UndefNamespace, ns));
}
// Writes out the specified value.
- public virtual void WriteValue(string value)
+ public virtual void WriteValue(string? value)
{
if (value == null)
{
}
// Writes out an attribute with the specified name, namespace URI and string value.
- public void WriteElementString(string localName, string ns, string value)
+ public void WriteElementString(string localName, string? ns, string value)
{
WriteStartElement(localName, ns);
if (null != value && 0 != value.Length)
}
// Writes out an attribute with the specified name, namespace URI, and string value.
- public void WriteElementString(string prefix, string localName, string ns, string value)
+ public void WriteElementString(string? prefix, string localName, string? ns, string value)
{
WriteStartElement(prefix, localName, ns);
if (null != value && 0 != value.Length)
}
// Creates an XmlWriter wrapped around the provided XmlWriter with the specified settings.
- public static XmlWriter Create(XmlWriter output, XmlWriterSettings settings)
+ public static XmlWriter Create(XmlWriter output, XmlWriterSettings? settings)
{
settings ??= XmlWriterSettings.s_defaultWriterSettings;
return settings.CreateWriter(output);
// 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;
using System;
// Writes out the DOCTYPE declaration with the specified name and optional attributes.
- public virtual Task WriteDocTypeAsync(string name, string pubid, string sysid, string subset)
+ public virtual Task WriteDocTypeAsync(string name, string? pubid, string? sysid, string subset)
{
throw new NotImplementedException();
}
// Writes out the specified start tag and associates it with the given namespace and prefix.
- public virtual Task WriteStartElementAsync(string prefix, string localName, string ns)
+ public virtual Task WriteStartElementAsync(string? prefix, string localName, string? ns)
{
throw new NotImplementedException();
}
// Writes out the attribute with the specified LocalName, value, and NamespaceURI.
// Writes out the attribute with the specified prefix, LocalName, NamespaceURI and value.
- public Task WriteAttributeStringAsync(string prefix, string localName, string ns, string value)
+ public Task WriteAttributeStringAsync(string? prefix, string localName, string? ns, string value)
{
Task task = WriteStartAttributeAsync(prefix, localName, ns);
if (task.IsSuccess())
// Writes the start of an attribute.
- protected internal virtual Task WriteStartAttributeAsync(string prefix, string localName, string ns)
+ protected internal virtual Task WriteStartAttributeAsync(string? prefix, string localName, string? ns)
{
throw new NotImplementedException();
}
}
// Writes out the specified namespace-qualified name by looking up the prefix that is in scope for the given namespace.
- public virtual async Task WriteQualifiedNameAsync(string localName, string ns)
+ public virtual async Task WriteQualifiedNameAsync(string localName, string? ns)
{
if (ns != null && ns.Length > 0)
{
- string prefix = LookupPrefix(ns);
+ string? prefix = LookupPrefix(ns);
if (prefix == null)
{
throw new ArgumentException(SR.Format(SR.Xml_UndefNamespace, ns));
// Element Helper Methods
// Writes out an attribute with the specified name, namespace URI, and string value.
- public async Task WriteElementStringAsync(string prefix, string localName, string ns, string value)
+ public async Task WriteElementStringAsync(string? prefix, string localName, string? ns, string value)
{
await WriteStartElementAsync(prefix, localName, ns).ConfigureAwait(false);
if (null != value && 0 != value.Length)
// 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 IXmlLineInfo
public static PositionInfo GetPositionInfo(object o)
{
- IXmlLineInfo li = o as IXmlLineInfo;
+ IXmlLineInfo? li = o as IXmlLineInfo;
if (li != null)
{
return new ReaderPositionInfo(li);
// 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;
// The "xml" prefix is always mapped to the "http://www.w3.org/XML/1998/namespace" namespace.
// The "xmlns" prefix is always mapped to the "http://www.w3.org/2000/xmlns/" namespace.
// If the default namespace has not been defined, then the "" prefix is mapped to "" (the empty namespace).
- string LookupNamespace(string prefix);
+ string? LookupNamespace(string prefix);
// Return a prefix which is mapped to the specified namespace. Multiple prefixes can be mapped to the
// same namespace, and it is undefined which prefix will be returned. Returns null if no prefixes are
// The "xml" prefix is always mapped to the "http://www.w3.org/XML/1998/namespace" namespace.
// The "xmlns" prefix is always mapped to the "http://www.w3.org/2000/xmlns/" namespace.
// If the default namespace has not been defined, then the "" prefix is mapped to "" (the empty namespace).
- string LookupPrefix(string namespaceName);
+ string? LookupPrefix(string 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.Runtime.InteropServices;
namespace System.Xml
{
throw new ArgumentNullException(nameof(key));
}
+
int len = key.Length;
if (len == 0)
{
return e.str;
}
}
+
return AddEntry(key, hashCode);
}
return e.str;
}
}
+
return AddEntry(new string(key, start, len), hashCode);
}
/// <devdoc>
/// Find the matching string in the NameTable.
/// </devdoc>
- public override string Get(string value)
+ public override string? Get(string value)
{
if (value == null)
{
throw new ArgumentNullException(nameof(value));
}
+
if (value.Length == 0)
{
return string.Empty;
return e.str;
}
}
+
return null;
}
/// Find the matching string atom given a range of
/// characters.
/// </devdoc>
- public override string Get(char[] key, int start, int len)
+ public override string? Get(char[] key, int start, int len)
{
if (len == 0)
{
return e.str;
}
}
+
return null;
}
int index = hashCode & _mask;
Entry e = new Entry(str, hashCode, _entries[index]);
_entries[index] = e;
+
if (_count++ == _mask)
{
Grow();
}
+
return e.str;
}
{
return false;
}
+
// use array.Length to eliminate the range check
for (int i = 0; i < str1.Length; i++)
{
}
return true;
}
+
private static int ComputeHash32(char[] key, int start, int len)
{
ReadOnlySpan<byte> bytes = MemoryMarshal.AsBytes(new ReadOnlySpan<char>(key, start, 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;
using System.IO;
using System.Net;
{
internal partial class XmlDownloadManager
{
- internal Stream GetStream(Uri uri, ICredentials credentials, IWebProxy proxy)
+ internal Stream GetStream(Uri uri, ICredentials? credentials, IWebProxy? proxy)
{
if (uri.Scheme == "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
using System;
using System.IO;
using System.Net;
{
internal partial class XmlDownloadManager
{
- internal Task<Stream> GetStreamAsync(Uri uri, ICredentials credentials, IWebProxy proxy)
+ internal Task<Stream> GetStreamAsync(Uri uri, ICredentials? credentials, IWebProxy? proxy)
{
if (uri.Scheme == "file")
{
}
}
- private async Task<Stream> GetNonFileStreamAsync(Uri uri, ICredentials credentials, IWebProxy proxy)
+ private async Task<Stream> GetNonFileStreamAsync(Uri uri, ICredentials? credentials, IWebProxy? proxy)
{
var handler = new HttpClientHandler();
using (var client = new HttpClient(handler))
// 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.Resources;
using System.Text;
public class XmlException : SystemException
{
private readonly string _res;
- private readonly string[] _args; // this field is not used, it's here just V1.1 serialization compatibility
+ private readonly string?[]? _args; // this field is not used, it's here just V1.1 serialization compatibility
private readonly int _lineNumber;
private readonly int _linePosition;
- private readonly string _sourceUri;
+ private readonly string? _sourceUri;
// message != null for V1 exceptions deserialized in Whidbey
// message == null for V2 or higher exceptions; the exception message is stored on the base class (Exception._message)
- private readonly string _message;
+ private readonly string? _message;
protected XmlException(SerializationInfo info, StreamingContext context) : base(info, context)
{
- _res = (string)info.GetValue("res", typeof(string));
- _args = (string[])info.GetValue("args", typeof(string[]));
- _lineNumber = (int)info.GetValue("lineNumber", typeof(int));
- _linePosition = (int)info.GetValue("linePosition", typeof(int));
+ _res = (string)info.GetValue("res", typeof(string))!;
+ _args = (string?[])info.GetValue("args", typeof(string[]))!;
+ _lineNumber = (int)info.GetValue("lineNumber", typeof(int))!;
+ _linePosition = (int)info.GetValue("linePosition", typeof(int))!;
// deserialize optional members
_sourceUri = string.Empty;
- string version = null;
+ string? version = null;
foreach (SerializationEntry e in info)
{
switch (e.Name)
{
case "sourceUri":
- _sourceUri = (string)e.Value;
+ _sourceUri = (string?)e.Value;
break;
case "version":
- version = (string)e.Value;
+ version = (string?)e.Value;
break;
}
}
}
//provided to meet the ECMA standards
- public XmlException(string message) : this(message, ((Exception)null), 0, 0)
+ public XmlException(string? message) : this(message, ((Exception?)null), 0, 0)
{
-#if DEBUG
Debug.Assert(message == null || !message.StartsWith("Xml_", StringComparison.Ordinal), "Do not pass a resource here!");
-#endif
}
//provided to meet ECMA standards
- public XmlException(string message, Exception innerException) : this(message, innerException, 0, 0)
+ public XmlException(string? message, Exception? innerException) : this(message, innerException, 0, 0)
{
}
//provided to meet ECMA standards
- public XmlException(string message, Exception innerException, int lineNumber, int linePosition) :
+ public XmlException(string? message, Exception? innerException, int lineNumber, int linePosition) :
this(message, innerException, lineNumber, linePosition, null)
{
}
- internal XmlException(string message, Exception innerException, int lineNumber, int linePosition, string sourceUri) :
+ internal XmlException(string? message, Exception? innerException, int lineNumber, int linePosition, string? sourceUri) :
base(FormatUserMessage(message, lineNumber, linePosition), innerException)
{
HResult = HResults.Xml;
_res = (message == null ? SR.Xml_DefaultException : SR.Xml_UserException);
- _args = new string[] { message };
+ _args = new string?[] { message };
_sourceUri = sourceUri;
_lineNumber = lineNumber;
_linePosition = linePosition;
}
- internal XmlException(string res, string[] args) :
+ internal XmlException(string res, string?[]? args) :
this(res, args, null, 0, 0, null)
{ }
- internal XmlException(string res, string arg) :
- this(res, new string[] { arg }, null, 0, 0, null)
+ internal XmlException(string res, string? arg) :
+ this(res, new string?[] { arg }, null, 0, 0, null)
{ }
- internal XmlException(string res, string arg, string sourceUri) :
- this(res, new string[] { arg }, null, 0, 0, sourceUri)
+ internal XmlException(string res, string? arg, string? sourceUri) :
+ this(res, new string?[] { arg }, null, 0, 0, sourceUri)
{ }
- internal XmlException(string res, string arg, IXmlLineInfo lineInfo) :
- this(res, new string[] { arg }, lineInfo, null)
+ internal XmlException(string res, string? arg, IXmlLineInfo? lineInfo) :
+ this(res, new string?[] { arg }, lineInfo, null)
{ }
- internal XmlException(string res, string arg, Exception innerException, IXmlLineInfo lineInfo) :
- this(res, new string[] { arg }, innerException, (lineInfo == null ? 0 : lineInfo.LineNumber), (lineInfo == null ? 0 : lineInfo.LinePosition), null)
+ internal XmlException(string res, string? arg, Exception? innerException, IXmlLineInfo? lineInfo) :
+ this(res, new string?[] { arg }, innerException, (lineInfo == null ? 0 : lineInfo.LineNumber), (lineInfo == null ? 0 : lineInfo.LinePosition), null)
{ }
- internal XmlException(string res, string[] args, IXmlLineInfo lineInfo) :
+ internal XmlException(string res, string?[]? args, IXmlLineInfo? lineInfo) :
this(res, args, lineInfo, null)
{ }
- internal XmlException(string res, string[] args, IXmlLineInfo lineInfo, string sourceUri) :
+ internal XmlException(string res, string?[]? args, IXmlLineInfo? lineInfo, string? sourceUri) :
this(res, args, null, (lineInfo == null ? 0 : lineInfo.LineNumber), (lineInfo == null ? 0 : lineInfo.LinePosition), sourceUri)
{
}
- internal XmlException(string res, string arg, int lineNumber, int linePosition) :
- this(res, new string[] { arg }, null, lineNumber, linePosition, null)
+ internal XmlException(string res, string? arg, int lineNumber, int linePosition) :
+ this(res, new string?[] { arg }, null, lineNumber, linePosition, null)
{ }
- internal XmlException(string res, string arg, int lineNumber, int linePosition, string sourceUri) :
- this(res, new string[] { arg }, null, lineNumber, linePosition, sourceUri)
+ internal XmlException(string res, string? arg, int lineNumber, int linePosition, string? sourceUri) :
+ this(res, new string?[] { arg }, null, lineNumber, linePosition, sourceUri)
{ }
- internal XmlException(string res, string[] args, int lineNumber, int linePosition) :
+ internal XmlException(string res, string?[]? args, int lineNumber, int linePosition) :
this(res, args, null, lineNumber, linePosition, null)
{ }
- internal XmlException(string res, string[] args, int lineNumber, int linePosition, string sourceUri) :
+ internal XmlException(string res, string?[]? args, int lineNumber, int linePosition, string? sourceUri) :
this(res, args, null, lineNumber, linePosition, sourceUri)
{ }
- internal XmlException(string res, string[] args, Exception innerException, int lineNumber, int linePosition) :
+ internal XmlException(string res, string?[]? args, Exception? innerException, int lineNumber, int linePosition) :
this(res, args, innerException, lineNumber, linePosition, null)
{ }
- internal XmlException(string res, string[] args, Exception innerException, int lineNumber, int linePosition, string sourceUri) :
+ internal XmlException(string res, string?[]? args, Exception? innerException, int lineNumber, int linePosition, string? sourceUri) :
base(CreateMessage(res, args, lineNumber, linePosition), innerException)
{
HResult = HResults.Xml;
_linePosition = linePosition;
}
- private static string FormatUserMessage(string message, int lineNumber, int linePosition)
+ private static string FormatUserMessage(string? message, int lineNumber, int linePosition)
{
if (message == null)
{
}
}
- private static string CreateMessage(string res, string[] args, int lineNumber, int linePosition)
+ private static string CreateMessage(string res, string?[]? args, int lineNumber, int linePosition)
{
try
{
- string message;
+ string message = (args == null) ? res : string.Format(res, args);
- // No line information -> get resource string and return
- if (lineNumber == 0)
- {
- message = (args == null) ? res : string.Format(res, args);
- }
// Line information is available -> we need to append it to the error message
- else
+ if (lineNumber != 0)
{
string lineNumberStr = lineNumber.ToString(CultureInfo.InvariantCulture);
string linePositionStr = linePosition.ToString(CultureInfo.InvariantCulture);
- message = string.Format(res, args);
message = SR.Format(SR.Xml_MessageWithErrorPosition, new string[] { message, lineNumberStr, linePositionStr });
}
return message;
get { return _linePosition; }
}
- public string SourceUri
+ public string? SourceUri
{
get { return _sourceUri; }
}
// 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>
/// <para>Gets the atomized String object containing the same
/// chars as the specified range of chars in the given char array.</para>
/// </devdoc>
- public abstract string Get(char[] array, int offset, int length);
+ public abstract string? Get(char[] array, int offset, int length);
/// <devdoc>
/// <para>
/// value as the specified string.
/// </para>
/// </devdoc>
- public abstract string Get(string array);
+ public abstract string? Get(string array);
/// <devdoc>
/// <para>Creates a new atom for the characters at the specified range
// 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.Diagnostics;
private struct NamespaceDeclaration
{
public string prefix;
- public string uri;
+ public string? uri;
public int scopeId;
public int previousNsIndex;
}
// array with namespace declarations
- private NamespaceDeclaration[] _nsdecls;
+ private NamespaceDeclaration[]? _nsdecls;
// index of last declaration
private int _lastDecl = 0;
// name table
- private readonly XmlNameTable _nameTable;
+ private readonly XmlNameTable? _nameTable;
// ID (depth) of the current scope
private int _scopeId;
// hash table for faster lookup when there is lots of namespaces
- private Dictionary<string, int> _hashTable;
+ private Dictionary<string, int>? _hashTable;
private bool _useHashtable;
// atomized prefixes for "xml" and "xmlns"
- private readonly string _xml;
- private readonly string _xmlNs;
+ private readonly string? _xml;
+ private readonly string? _xmlNs;
// Constants
private const int MinDeclsCountForHashtable = 16;
_scopeId = 1;
}
- public virtual XmlNameTable NameTable
+ public virtual XmlNameTable? NameTable
{
get
{
{
get
{
- string defaultNs = LookupNamespace(string.Empty);
+ string? defaultNs = LookupNamespace(string.Empty);
return (defaultNs == null) ? string.Empty : defaultNs;
}
}
{
return false;
}
+
+ Debug.Assert(_nsdecls != null);
+
while (_nsdecls[decl].scopeId == _scopeId)
{
if (_useHashtable)
{
+ Debug.Assert(_hashTable != null);
_hashTable[_nsdecls[decl].prefix] = _nsdecls[decl].previousNsIndex;
}
+
decl--;
Debug.Assert(decl >= 2);
}
+
_lastDecl = decl;
_scopeId--;
return true;
if (prefix == null)
throw new ArgumentNullException(nameof(prefix));
+ Debug.Assert(_nameTable != null);
+ Debug.Assert(_nsdecls != null);
prefix = _nameTable.Add(prefix);
uri = _nameTable.Add(uri);
// add to hashTable
if (_useHashtable)
{
+ Debug.Assert(_hashTable != null);
_hashTable[prefix] = _lastDecl;
}
// or create a new hashTable if the threshold has been reached
{
_hashTable[_nsdecls[i].prefix] = i;
}
+
_useHashtable = true;
}
}
throw new ArgumentNullException(nameof(prefix));
}
+ Debug.Assert(_nsdecls != null);
+
int declIndex = LookupNamespaceDecl(prefix);
while (declIndex != -1)
{
public virtual IEnumerator GetEnumerator()
{
+ Debug.Assert(_nsdecls != null);
+
Dictionary<string, string> prefixes = new Dictionary<string, string>(_lastDecl + 1);
for (int thisDecl = 0; thisDecl <= _lastDecl; thisDecl++)
{
#pragma warning disable 3002
public virtual IDictionary<string, string> GetNamespacesInScope(XmlNamespaceScope scope)
{
+ Debug.Assert(_nsdecls != null);
+
#pragma warning restore 3002
int i = 0;
switch (scope)
Dictionary<string, string> dict = new Dictionary<string, string>(_lastDecl - i + 1);
for (; i <= _lastDecl; i++)
{
- string prefix = _nsdecls[i].prefix;
- string uri = _nsdecls[i].uri;
+ string? prefix = _nsdecls[i].prefix;
+ string? uri = _nsdecls[i].uri;
Debug.Assert(prefix != null);
if (uri != null)
}
}
}
+
return dict;
}
- public virtual string LookupNamespace(string prefix)
+ public virtual string? LookupNamespace(string prefix)
{
+ Debug.Assert(_nsdecls != null);
int declIndex = LookupNamespaceDecl(prefix);
return (declIndex == -1) ? null : _nsdecls[declIndex].uri;
}
private int LookupNamespaceDecl(string prefix)
{
+ Debug.Assert(_nsdecls != null);
+
if (_useHashtable)
{
+ Debug.Assert(_hashTable != null);
int declIndex;
if (_hashTable.TryGetValue(prefix, out declIndex))
{
return -1;
}
- public virtual string LookupPrefix(string uri)
+ public virtual string? LookupPrefix(string uri)
{
+ Debug.Assert(_nsdecls != null);
+
// Don't assume that prefix is atomized
for (int thisDecl = _lastDecl; thisDecl >= 0; thisDecl--)
{
public virtual bool HasNamespace(string prefix)
{
+ Debug.Assert(_nsdecls != null);
+
// Don't assume that prefix is atomized
for (int thisDecl = _lastDecl; _nsdecls[thisDecl].scopeId == _scopeId; thisDecl--)
{
if (string.Equals(_nsdecls[thisDecl].prefix, prefix) && _nsdecls[thisDecl].uri != null)
{
- if (prefix.Length > 0 || _nsdecls[thisDecl].uri.Length > 0)
+ if (prefix.Length > 0 || _nsdecls[thisDecl].uri!.Length > 0)
{
return true;
}
return false;
}
- internal bool GetNamespaceDeclaration(int idx, out string prefix, out string uri)
+ internal bool GetNamespaceDeclaration(int idx, out string? prefix, out string? uri)
{
idx = _lastDecl - idx;
if (idx < 0)
return false;
}
+ Debug.Assert(_nsdecls != null);
prefix = _nsdecls[idx].prefix;
uri = _nsdecls[idx].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
namespace System.Xml
{
using System;
using System.Net;
using System.Threading.Tasks;
using System.Runtime.Versioning;
+ using System.Diagnostics;
/// <devdoc>
/// <para>Resolves external XML resources named by a Uniform
/// URI to an Object containing the actual resource.</para>
/// </devdoc>
- public abstract object GetEntity(Uri absoluteUri,
- string role,
- Type ofObjectToReturn);
+ public abstract object? GetEntity(Uri absoluteUri,
+ string? role,
+ Type? ofObjectToReturn);
/// <devdoc>
/// <para>[To be supplied.]</para>
/// </devdoc>
- public virtual Uri ResolveUri(Uri baseUri, string relativeUri)
+ public virtual Uri ResolveUri(Uri? baseUri, string? relativeUri)
{
if (baseUri == null || (!baseUri.IsAbsoluteUri && baseUri.OriginalString.Length == 0))
{
- Uri uri = new Uri(relativeUri, UriKind.RelativeOrAbsolute);
+ Uri uri = new Uri(relativeUri!, UriKind.RelativeOrAbsolute);
if (!uri.IsAbsoluteUri && uri.OriginalString.Length > 0)
{
- uri = new Uri(Path.GetFullPath(relativeUri));
+ uri = new Uri(Path.GetFullPath(relativeUri!));
}
+
return uri;
}
else
{
return baseUri;
}
+
// relative base Uri
if (!baseUri.IsAbsoluteUri)
{
throw new NotSupportedException(SR.Xml_RelativeUriNotSupported);
}
+
return new Uri(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;
using System.Net;
using System.Net.Cache;
// Resolves external XML resources named by a Uniform Resource Identifier (URI).
public partial class XmlUrlResolver : XmlResolver
{
- private static XmlDownloadManager s_downloadManager;
- private ICredentials _credentials;
- private IWebProxy _proxy;
+ private static XmlDownloadManager? s_downloadManager;
+ private ICredentials? _credentials;
+ private IWebProxy? _proxy;
private static XmlDownloadManager DownloadManager =>
s_downloadManager ??
public XmlUrlResolver() { }
- public override ICredentials Credentials
+ public override ICredentials? Credentials
{
set { _credentials = value; }
}
- public IWebProxy Proxy
+ public IWebProxy? Proxy
{
set { _proxy = value; }
}
}
// Maps a URI to an Object containing the actual resource.
- public override object GetEntity(Uri absoluteUri, string role, Type ofObjectToReturn)
+ public override object? GetEntity(Uri absoluteUri, string? role, Type? ofObjectToReturn)
{
if (ofObjectToReturn is null || ofObjectToReturn == typeof(System.IO.Stream) || ofObjectToReturn == typeof(object))
{
throw new XmlException(SR.Xml_UnsupportedClass, string.Empty);
}
- public override Uri ResolveUri(Uri baseUri, string relativeUri) =>
+ public override Uri ResolveUri(Uri? baseUri, string? relativeUri) =>
base.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.Runtime.Versioning;
using System.Threading.Tasks;
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))
{