From 1713d33a14fa8d7feb24a655135c67b2dc55a146 Mon Sep 17 00:00:00 2001 From: Krzysztof Wicher Date: Mon, 24 Aug 2020 15:14:22 +0200 Subject: [PATCH 1/5] Nullable: System.Xml, part 7 (Serialization) --- .../Xml/Schema/SchemaNamespacemanager.cs | 8 +- .../src/System/Xml/Schema/XmlSchema.cs | 14 +- .../src/System/Xml/Schema/XsdBuilder.cs | 2 +- .../Serialization/CodeGenerationoptions.cs | 1 + .../System/Xml/Serialization/CodeGenerator.cs | 298 ++++---- .../Xml/Serialization/CodeIdentifier.cs | 14 +- .../Xml/Serialization/CodeIdentifiers.cs | 5 +- .../System/Xml/Serialization/Compilation.cs | 171 +++-- .../src/System/Xml/Serialization/Compiler.cs | 12 +- .../DateTimeSerializationSection.cs | 1 + .../src/System/Xml/Serialization/Globals.cs | 1 + .../Xml/Serialization/IXmlSerializable.cs | 3 +- .../Xml/Serialization/IXmlTextParser.cs | 1 + .../System/Xml/Serialization/ImportContext.cs | 90 +-- .../src/System/Xml/Serialization/Mappings.cs | 300 ++++---- .../src/System/Xml/Serialization/Models.cs | 47 +- .../src/System/Xml/Serialization/NameTable.cs | 27 +- .../Serialization/PrimitiveXmlSerializers.cs | 193 ++--- .../ReflectionXmlSerializationReader.cs | 444 +++++------ .../ReflectionXmlSerializationWriter.cs | 259 +++---- .../Xml/Serialization/SchemaImporter.cs | 15 +- .../Xml/Serialization/SchemaObjectWriter.cs | 380 +++++----- .../Serialization/SoapAttributeAttribute.cs | 12 +- .../Serialization/SoapAttributeOverrides.cs | 11 +- .../Xml/Serialization/SoapAttributes.cs | 21 +- .../Xml/Serialization/SoapElementAttribute.cs | 8 +- .../Xml/Serialization/SoapEnumAttribute.cs | 5 +- .../Xml/Serialization/SoapIgnoreAttribute.cs | 1 + .../Xml/Serialization/SoapIncludeAttribute.cs | 1 + .../Serialization/SoapReflectionImporter.cs | 121 +-- .../Xml/Serialization/SoapSchemamember.cs | 5 +- .../Xml/Serialization/SoapTypeAttribute.cs | 9 +- .../System/Xml/Serialization/SourceInfo.cs | 57 +- .../src/System/Xml/Serialization/TypeCode.cs | 1 + .../Xml/Serialization/TypeExtensions.cs | 3 +- .../src/System/Xml/Serialization/Types.cs | 151 ++-- .../Serialization/XmlAnyAttributeAttribute.cs | 2 +- .../Serialization/XmlAnyElementAttribute.cs | 10 +- .../Serialization/XmlAnyElementAttributes.cs | 15 +- .../Xml/Serialization/XmlArrayAttribute.cs | 12 +- .../Serialization/XmlArrayItemAttribute.cs | 17 +- .../Serialization/XmlArrayItemAttributes.cs | 15 +- .../Serialization/XmlAttributeAttribute.cs | 17 +- .../Serialization/XmlAttributeOverrides.cs | 11 +- .../System/Xml/Serialization/XmlAttributes.cs | 43 +- .../XmlChoiceIdentifierAttribute.cs | 14 +- .../Xml/Serialization/XmlElementAttribute.cs | 23 +- .../Xml/Serialization/XmlElementAttributes.cs | 15 +- .../Xml/Serialization/XmlEnumAttribute.cs | 8 +- .../Xml/Serialization/XmlIgnoreAttribute.cs | 2 +- .../Xml/Serialization/XmlIncludeAttribute.cs | 8 +- .../System/Xml/Serialization/XmlMapping.cs | 26 +- .../Xml/Serialization/XmlMemberMapping.cs | 24 +- .../Xml/Serialization/XmlMembersMapping.cs | 18 +- .../XmlNamespaceDeclarationsAttribute.cs | 2 +- .../Serialization/XmlReflectionImporter.cs | 329 ++++---- .../Xml/Serialization/XmlReflectionMember.cs | 8 +- .../Xml/Serialization/XmlRootAttribute.cs | 11 +- .../Xml/Serialization/XmlSchemaExporter.cs | 209 ++--- .../Xml/Serialization/XmlSchemaImporter.cs | 325 ++++---- .../XmlSchemaProviderAttribute.cs | 7 +- .../System/Xml/Serialization/XmlSchemas.cs | 73 +- .../XmlSerializationEventSource.cs | 1 + .../XmlSerializationGeneratedCode.cs | 43 +- .../Serialization/XmlSerializationILGen.cs | 100 +-- .../Serialization/XmlSerializationReader.cs | 717 +++++++++--------- .../XmlSerializationReaderILGen.cs | 651 ++++++++-------- .../Serialization/XmlSerializationWriter.cs | 573 +++++++------- .../XmlSerializationWriterILGen.cs | 482 ++++++------ .../System/Xml/Serialization/XmlSerializer.cs | 151 ++-- .../XmlSerializerAssemblyAttribute.cs | 13 +- .../Xml/Serialization/XmlSerializerFactory.cs | 15 +- .../Serialization/XmlSerializerNamespaces.cs | 23 +- .../XmlSerializerVersionAttribute.cs | 19 +- .../Xml/Serialization/XmlTextAttribute.cs | 12 +- .../Xml/Serialization/XmlTypeAttribute.cs | 10 +- .../Xml/Serialization/XmlTypeMapping.cs | 18 +- .../Xml/Serialization/Xmlcustomformatter.cs | 27 +- .../src/System/Xml/Serialization/_Events.cs | 43 +- .../Xml/Serialization/indentedWriter.cs | 5 +- 80 files changed, 3499 insertions(+), 3340 deletions(-) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaNamespacemanager.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaNamespacemanager.cs index d64c131d28b13c..2721d21c35d120 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaNamespacemanager.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/SchemaNamespacemanager.cs @@ -24,7 +24,7 @@ public SchemaNamespaceManager(XmlSchemaObject node) { //Special case for the XML namespace return XmlReservedNs.NsXml; } - Dictionary namespaces; + Dictionary namespaces; for (XmlSchemaObject? current = _node; current != null; current = current.Parent) { namespaces = current.Namespaces.Namespaces; @@ -44,15 +44,15 @@ public SchemaNamespaceManager(XmlSchemaObject node) { //Special case for the XML namespace return "xml"; } - Dictionary namespaces; + Dictionary namespaces; for (XmlSchemaObject? current = _node; current != null; current = current.Parent) { namespaces = current.Namespaces.Namespaces; if (namespaces != null && namespaces.Count > 0) { - foreach (KeyValuePair entry in namespaces) + foreach (KeyValuePair entry in namespaces) { - if (entry.Value.Equals(ns)) + if (entry.Value!.Equals(ns)) { return entry.Key; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchema.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchema.cs index f6b46e8e5179dd..ccc9d028e3536c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchema.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchema.cs @@ -56,17 +56,17 @@ public class XmlSchema : XmlSchemaObject public XmlSchema() { } - public static XmlSchema? Read(TextReader reader, ValidationEventHandler validationEventHandler) + public static XmlSchema? Read(TextReader reader, ValidationEventHandler? validationEventHandler) { return Read(new XmlTextReader(reader), validationEventHandler); } - public static XmlSchema? Read(Stream stream, ValidationEventHandler validationEventHandler) + public static XmlSchema? Read(Stream stream, ValidationEventHandler? validationEventHandler) { return Read(new XmlTextReader(stream), validationEventHandler); } - public static XmlSchema? Read(XmlReader reader, ValidationEventHandler validationEventHandler) + public static XmlSchema? Read(XmlReader reader, ValidationEventHandler? validationEventHandler) { XmlNameTable nameTable = reader.NameTable; Parser parser = new Parser(SchemaType.XSD, nameTable, new SchemaNames(nameTable), validationEventHandler); @@ -136,7 +136,7 @@ public void Write(XmlWriter writer, XmlNamespaceManager? namespaceManager) { ns.Add("xs", XmlReservedNs.NsXs); } - foreach (string? prefix in namespaceManager) + foreach (string prefix in namespaceManager) { if (prefix != "xml" && prefix != "xmlns") { @@ -146,7 +146,7 @@ public void Write(XmlWriter writer, XmlNamespaceManager? namespaceManager) } else if (this.Namespaces != null && this.Namespaces.Count > 0) { - Dictionary serializerNS = this.Namespaces.Namespaces; + Dictionary serializerNS = this.Namespaces.Namespaces; if (!serializerNS.ContainsKey("xs") && !serializerNS.ContainsValue(XmlReservedNs.NsXs)) { //Prefix xs not defined AND schema namespace not already mapped to a prefix serializerNS.Add("xs", XmlReservedNs.NsXs); @@ -166,7 +166,7 @@ public void Write(XmlWriter writer, XmlNamespaceManager? namespaceManager) } [Obsolete("Use System.Xml.Schema.XmlSchemaSet for schema compilation and validation. https://go.microsoft.com/fwlink/?linkid=14202")] - public void Compile(ValidationEventHandler validationEventHandler) + public void Compile(ValidationEventHandler? validationEventHandler) { SchemaInfo sInfo = new SchemaInfo(); sInfo.SchemaType = SchemaType.XSD; @@ -174,7 +174,7 @@ public void Compile(ValidationEventHandler validationEventHandler) } [Obsolete("Use System.Xml.Schema.XmlSchemaSet for schema compilation and validation. https://go.microsoft.com/fwlink/?linkid=14202")] - public void Compile(ValidationEventHandler validationEventHandler, XmlResolver resolver) + public void Compile(ValidationEventHandler? validationEventHandler, XmlResolver resolver) { SchemaInfo sInfo = new SchemaInfo(); sInfo.SchemaType = SchemaType.XSD; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdBuilder.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdBuilder.cs index b1bb09829fca6a..74449d98725f0c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdBuilder.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XsdBuilder.cs @@ -795,7 +795,7 @@ internal override void StartChildren() { if (_namespaces != null && _namespaces.Count > 0) { - _xso.Namespaces.Namespaces = _namespaces; + _xso.Namespaces.Namespaces = _namespaces!; _namespaces = null; } if (_unhandledAttributes.Count != 0) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeGenerationoptions.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeGenerationoptions.cs index 6f7ad17f4e4a36..42fbe3a3442a83 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeGenerationoptions.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeGenerationoptions.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeGenerator.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeGenerator.cs index 14cd6dbdbd685f..22bbca0e50119a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeGenerator.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeGenerator.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; using System.Collections; using System.Collections.Generic; @@ -32,14 +33,14 @@ internal class CodeGenerator internal static MethodAttributes PrivateMethodAttributes = MethodAttributes.Private | MethodAttributes.HideBySig; private readonly TypeBuilder _typeBuilder; - private MethodBuilder _methodBuilder; - private ILGenerator _ilGen; - private Dictionary _argList; - private LocalScope _currentScope; + private MethodBuilder? _methodBuilder; + private ILGenerator? _ilGen; + private Dictionary? _argList; + private LocalScope? _currentScope; // Stores a queue of free locals available in the context of the method, keyed by // type and name of the local - private Dictionary, Queue> _freeLocals; - private Stack _blockStack; + private Dictionary, Queue>? _freeLocals; + private Stack? _blockStack; private Label _methodEndLabel; internal CodeGenerator(TypeBuilder typeBuilder) @@ -85,7 +86,7 @@ internal void BeginMethod(Type returnType, MethodBuilderInfo methodBuilderInfo, private void InitILGeneration(Type[] argTypes, string[] argNames, bool isStatic) { - _methodEndLabel = _ilGen.DefineLabel(); + _methodEndLabel = _ilGen!.DefineLabel(); this.retLabel = _ilGen.DefineLabel(); _blockStack = new Stack(); _whileStack = new Stack(); @@ -94,21 +95,21 @@ private void InitILGeneration(Type[] argTypes, string[] argNames, bool isStatic) _argList = new Dictionary(); // this ptr is arg 0 for non static, assuming ref type (not value type) if (!isStatic) - _argList.Add("this", new ArgBuilder("this", 0, _typeBuilder.BaseType)); + _argList.Add("this", new ArgBuilder("this", 0, _typeBuilder.BaseType!)); for (int i = 0; i < argTypes.Length; i++) { ArgBuilder arg = new ArgBuilder(argNames[i], _argList.Count, argTypes[i]); _argList.Add(arg.Name, arg); - _methodBuilder.DefineParameter(arg.Index, ParameterAttributes.None, arg.Name); + _methodBuilder!.DefineParameter(arg.Index, ParameterAttributes.None, arg.Name); } } - internal MethodBuilder EndMethod() + internal MethodBuilder? EndMethod() { MarkLabel(_methodEndLabel); Ret(); - MethodBuilder retVal = null; + MethodBuilder? retVal = null; retVal = _methodBuilder; _methodBuilder = null; _ilGen = null; @@ -121,7 +122,7 @@ internal MethodBuilder EndMethod() return retVal; } - internal MethodBuilder MethodBuilder + internal MethodBuilder? MethodBuilder { get { return _methodBuilder; } } @@ -135,17 +136,17 @@ internal ArgBuilder GetArg(string name) internal LocalBuilder GetLocal(string name) { System.Diagnostics.Debug.Assert(_currentScope != null && _currentScope.ContainsKey(name)); - return _currentScope[name]; + return _currentScope[name]!; } - internal LocalBuilder retLocal; + internal LocalBuilder? retLocal; internal Label retLabel; internal LocalBuilder ReturnLocal { get { if (retLocal == null) - retLocal = DeclareLocal(_methodBuilder.ReturnType, "_ret"); + retLocal = DeclareLocal(_methodBuilder!.ReturnType, "_ret"); return retLocal; } } @@ -157,7 +158,7 @@ internal Label ReturnLabel private readonly Dictionary _tmpLocals = new Dictionary(); internal LocalBuilder GetTempLocal(Type type) { - LocalBuilder localTmp; + LocalBuilder? localTmp; if (!_tmpLocals.TryGetValue(type, out localTmp)) { localTmp = DeclareLocal(type, "_tmp" + _tmpLocals.Count); @@ -178,22 +179,22 @@ internal Type GetVariableType(object var) internal object GetVariable(string name) { - object var; + object? var; if (TryGetVariable(name, out var)) return var; System.Diagnostics.Debug.Fail("Variable not found"); return null; } - internal bool TryGetVariable(string name, out object variable) + internal bool TryGetVariable(string name, [NotNullWhen(true)] out object? variable) { - LocalBuilder loc; + LocalBuilder? loc; if (_currentScope != null && _currentScope.TryGetValue(name, out loc)) { variable = loc; return true; } - ArgBuilder arg; + ArgBuilder? arg; if (_argList != null && _argList.TryGetValue(name, out arg)) { variable = arg; @@ -217,18 +218,18 @@ internal void EnterScope() internal void ExitScope() { - Debug.Assert(_currentScope.parent != null); - _currentScope.AddToFreeLocals(_freeLocals); + Debug.Assert(_currentScope!.parent != null); + _currentScope.AddToFreeLocals(_freeLocals!); _currentScope = _currentScope.parent; } - private bool TryDequeueLocal(Type type, string name, out LocalBuilder local) + private bool TryDequeueLocal(Type type, string name, [NotNullWhen(true)] out LocalBuilder? local) { // This method can only be called between BeginMethod and EndMethod (i.e. // while we are emitting code for a method Debug.Assert(_freeLocals != null); - Queue freeLocalQueue; + Queue? freeLocalQueue; Tuple key = new Tuple(type, name); if (_freeLocals.TryGetValue(key, out freeLocalQueue)) { @@ -248,11 +249,11 @@ private bool TryDequeueLocal(Type type, string name, out LocalBuilder local) internal LocalBuilder DeclareLocal(Type type, string name) { - Debug.Assert(!_currentScope.ContainsKey(name)); - LocalBuilder local; + Debug.Assert(!_currentScope!.ContainsKey(name)); + LocalBuilder? local; if (!TryDequeueLocal(type, name, out local)) { - local = _ilGen.DeclareLocal(type, false); + local = _ilGen!.DeclareLocal(type, false); } _currentScope[name] = local; return local; @@ -260,8 +261,8 @@ internal LocalBuilder DeclareLocal(Type type, string name) internal LocalBuilder DeclareOrGetLocal(Type type, string name) { - LocalBuilder local; - if (!_currentScope.TryGetValue(name, out local)) + LocalBuilder? local; + if (!_currentScope!.TryGetValue(name, out local)) local = DeclareLocal(type, name); else Debug.Assert(local.LocalType == type); @@ -278,14 +279,14 @@ internal object For(LocalBuilder local, object start, object end) Br(forState.TestLabel); } MarkLabel(forState.BeginLabel); - _blockStack.Push(forState); + _blockStack!.Push(forState); return forState; } internal void EndFor() { - object stackTop = _blockStack.Pop(); - ForState forState = stackTop as ForState; + object stackTop = _blockStack!.Pop(); + ForState? forState = stackTop as ForState; Debug.Assert(forState != null); if (forState.Index != null) { @@ -310,7 +311,7 @@ internal void EndFor() "get_Count", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; Call(ICollection_get_Count); } Blt(forState.BeginLabel); @@ -348,11 +349,11 @@ internal void If(Cmp cmpOp) IfState ifState = new IfState(); ifState.EndIf = DefineLabel(); ifState.ElseBegin = DefineLabel(); - _ilGen.Emit(GetBranchCode(cmpOp), ifState.ElseBegin); - _blockStack.Push(ifState); + _ilGen!.Emit(GetBranchCode(cmpOp), ifState.ElseBegin); + _blockStack!.Push(ifState); } - internal void If(object value1, Cmp cmpOp, object value2) + internal void If(object value1, Cmp cmpOp, object? value2) { Load(value1); Load(value2); @@ -366,7 +367,7 @@ internal void Else() MarkLabel(ifState.ElseBegin); ifState.ElseBegin = ifState.EndIf; - _blockStack.Push(ifState); + _blockStack!.Push(ifState); } internal void EndIf() @@ -381,60 +382,60 @@ internal void EndIf() internal void BeginExceptionBlock() { _leaveLabels.Push(DefineLabel()); - _ilGen.BeginExceptionBlock(); + _ilGen!.BeginExceptionBlock(); } internal void BeginCatchBlock(Type exception) { - _ilGen.BeginCatchBlock(exception); + _ilGen!.BeginCatchBlock(exception); } internal void EndExceptionBlock() { - _ilGen.EndExceptionBlock(); + _ilGen!.EndExceptionBlock(); _ilGen.MarkLabel(_leaveLabels.Pop()); } internal void Leave() { - _ilGen.Emit(OpCodes.Leave, _leaveLabels.Peek()); + _ilGen!.Emit(OpCodes.Leave, _leaveLabels.Peek()); } internal void Call(MethodInfo methodInfo) { Debug.Assert(methodInfo != null); - if (methodInfo.IsVirtual && !methodInfo.DeclaringType.IsValueType) - _ilGen.Emit(OpCodes.Callvirt, methodInfo); + if (methodInfo.IsVirtual && !methodInfo.DeclaringType!.IsValueType) + _ilGen!.Emit(OpCodes.Callvirt, methodInfo); else - _ilGen.Emit(OpCodes.Call, methodInfo); + _ilGen!.Emit(OpCodes.Call, methodInfo); } internal void Call(ConstructorInfo ctor) { Debug.Assert(ctor != null); - _ilGen.Emit(OpCodes.Call, ctor); + _ilGen!.Emit(OpCodes.Call, ctor); } internal void New(ConstructorInfo constructorInfo) { Debug.Assert(constructorInfo != null); - _ilGen.Emit(OpCodes.Newobj, constructorInfo); + _ilGen!.Emit(OpCodes.Newobj, constructorInfo); } internal void InitObj(Type valueType) { - _ilGen.Emit(OpCodes.Initobj, valueType); + _ilGen!.Emit(OpCodes.Initobj, valueType); } internal void NewArray(Type elementType, object len) { Load(len); - _ilGen.Emit(OpCodes.Newarr, elementType); + _ilGen!.Emit(OpCodes.Newarr, elementType); } internal void LoadArrayElement(object obj, object arrayIndex) { - Type objType = GetVariableType(obj).GetElementType(); + Type objType = GetVariableType(obj).GetElementType()!; Load(obj); Load(arrayIndex); if (IsStruct(objType)) @@ -452,11 +453,11 @@ internal void StoreArrayElement(object obj, object arrayIndex, object value) if (arrayType == typeof(Array)) { Load(obj); - Call(typeof(Array).GetMethod("SetValue", new Type[] { typeof(object), typeof(int) })); + Call(typeof(Array).GetMethod("SetValue", new Type[] { typeof(object), typeof(int) })!); } else { - Type objType = arrayType.GetElementType(); + Type objType = arrayType.GetElementType()!; Load(obj); Load(arrayIndex); if (IsStruct(objType)) @@ -484,14 +485,14 @@ internal Type LoadMember(object obj, MemberInfo memberInfo) return LoadMember(memberInfo); } - private static MethodInfo GetPropertyMethodFromBaseType(PropertyInfo propertyInfo, bool isGetter) + private static MethodInfo? GetPropertyMethodFromBaseType(PropertyInfo propertyInfo, bool isGetter) { // we only invoke this when the propertyInfo does not have a GET or SET method on it - Type currentType = propertyInfo.DeclaringType.BaseType; - PropertyInfo currentProperty; + Type? currentType = propertyInfo.DeclaringType!.BaseType; + PropertyInfo? currentProperty; string propertyName = propertyInfo.Name; - MethodInfo result = null; + MethodInfo? result = null; while (currentType != null) { @@ -524,18 +525,18 @@ private static MethodInfo GetPropertyMethodFromBaseType(PropertyInfo propertyInf internal Type LoadMember(MemberInfo memberInfo) { - Type memberType = null; + Type? memberType = null; if (memberInfo is FieldInfo) { FieldInfo fieldInfo = (FieldInfo)memberInfo; memberType = fieldInfo.FieldType; if (fieldInfo.IsStatic) { - _ilGen.Emit(OpCodes.Ldsfld, fieldInfo); + _ilGen!.Emit(OpCodes.Ldsfld, fieldInfo); } else { - _ilGen.Emit(OpCodes.Ldfld, fieldInfo); + _ilGen!.Emit(OpCodes.Ldfld, fieldInfo); } } else @@ -545,7 +546,7 @@ internal Type LoadMember(MemberInfo memberInfo) memberType = property.PropertyType; if (property != null) { - MethodInfo getMethod = property.GetMethod; + MethodInfo? getMethod = property.GetMethod; if (getMethod == null) { @@ -562,18 +563,18 @@ internal Type LoadMember(MemberInfo memberInfo) internal Type LoadMemberAddress(MemberInfo memberInfo) { - Type memberType = null; + Type? memberType = null; if (memberInfo is FieldInfo) { FieldInfo fieldInfo = (FieldInfo)memberInfo; memberType = fieldInfo.FieldType; if (fieldInfo.IsStatic) { - _ilGen.Emit(OpCodes.Ldsflda, fieldInfo); + _ilGen!.Emit(OpCodes.Ldsflda, fieldInfo); } else { - _ilGen.Emit(OpCodes.Ldflda, fieldInfo); + _ilGen!.Emit(OpCodes.Ldflda, fieldInfo); } } else @@ -583,7 +584,7 @@ internal Type LoadMemberAddress(MemberInfo memberInfo) memberType = property.PropertyType; if (property != null) { - MethodInfo getMethod = property.GetMethod; + MethodInfo? getMethod = property.GetMethod; if (getMethod == null) { @@ -609,11 +610,11 @@ internal void StoreMember(MemberInfo memberInfo) FieldInfo fieldInfo = (FieldInfo)memberInfo; if (fieldInfo.IsStatic) { - _ilGen.Emit(OpCodes.Stsfld, fieldInfo); + _ilGen!.Emit(OpCodes.Stsfld, fieldInfo); } else { - _ilGen.Emit(OpCodes.Stfld, fieldInfo); + _ilGen!.Emit(OpCodes.Stfld, fieldInfo); } } else @@ -622,7 +623,7 @@ internal void StoreMember(MemberInfo memberInfo) PropertyInfo property = (PropertyInfo)memberInfo; if (property != null) { - MethodInfo setMethod = property.SetMethod; + MethodInfo? setMethod = property.SetMethod; if (setMethod == null) { @@ -635,10 +636,10 @@ internal void StoreMember(MemberInfo memberInfo) } } - internal void Load(object obj) + internal void Load(object? obj) { if (obj == null) - _ilGen.Emit(OpCodes.Ldnull); + _ilGen!.Emit(OpCodes.Ldnull); else if (obj is ArgBuilder) Ldarg((ArgBuilder)obj); else if (obj is LocalBuilder) @@ -670,17 +671,17 @@ internal void ConvertValue(Type source, Type target) internal void Castclass(Type target) { - _ilGen.Emit(OpCodes.Castclass, target); + _ilGen!.Emit(OpCodes.Castclass, target); } internal void Box(Type type) { - _ilGen.Emit(OpCodes.Box, type); + _ilGen!.Emit(OpCodes.Box, type); } internal void Unbox(Type type) { - _ilGen.Emit(OpCodes.Unbox, type); + _ilGen!.Emit(OpCodes.Unbox, type); } private static readonly OpCode[] s_ldindOpCodes = new OpCode[] { @@ -716,27 +717,27 @@ internal void Ldobj(Type type) OpCode opCode = GetLdindOpCode(type.GetTypeCode()); if (!opCode.Equals(OpCodes.Nop)) { - _ilGen.Emit(opCode); + _ilGen!.Emit(opCode); } else { - _ilGen.Emit(OpCodes.Ldobj, type); + _ilGen!.Emit(OpCodes.Ldobj, type); } } internal void Stobj(Type type) { - _ilGen.Emit(OpCodes.Stobj, type); + _ilGen!.Emit(OpCodes.Stobj, type); } internal void Ceq() { - _ilGen.Emit(OpCodes.Ceq); + _ilGen!.Emit(OpCodes.Ceq); } internal void Clt() { - _ilGen.Emit(OpCodes.Clt); + _ilGen!.Emit(OpCodes.Clt); } internal void Cne() @@ -748,17 +749,17 @@ internal void Cne() internal void Ble(Label label) { - _ilGen.Emit(OpCodes.Ble, label); + _ilGen!.Emit(OpCodes.Ble, label); } internal void Throw() { - _ilGen.Emit(OpCodes.Throw); + _ilGen!.Emit(OpCodes.Throw); } internal void Ldtoken(Type t) { - _ilGen.Emit(OpCodes.Ldtoken, t); + _ilGen!.Emit(OpCodes.Ldtoken, t); } internal void Ldc(object o) @@ -767,7 +768,7 @@ internal void Ldc(object o) if (o is Type) { Ldtoken((Type)o); - Call(typeof(Type).GetMethod("GetTypeFromHandle", BindingFlags.Static | BindingFlags.Public, new Type[] { typeof(RuntimeTypeHandle) })); + Call(typeof(Type).GetMethod("GetTypeFromHandle", BindingFlags.Static | BindingFlags.Public, new Type[] { typeof(RuntimeTypeHandle) })!); } else if (valueType.IsEnum) { @@ -814,7 +815,7 @@ internal void Ldc(object o) ConstructorInfo Decimal_ctor = typeof(decimal).GetConstructor( CodeGenerator.InstanceBindingFlags, new Type[] { typeof(int), typeof(int), typeof(int), typeof(bool), typeof(byte) } - ); + )!; int[] bits = decimal.GetBits((decimal)o); Ldc(bits[0]); // digit Ldc(bits[1]); // digit @@ -827,7 +828,7 @@ internal void Ldc(object o) ConstructorInfo DateTime_ctor = typeof(DateTime).GetConstructor( CodeGenerator.InstanceBindingFlags, new Type[] { typeof(long) } - ); + )!; Ldc(((DateTime)o).Ticks); // ticks New(DateTime_ctor); break; @@ -842,7 +843,7 @@ internal void Ldc(object o) null, new Type[] { typeof(long) }, null - ); + )!; Ldc(((TimeSpan)o).Ticks); // ticks New(TimeSpan_ctor); break; @@ -859,40 +860,40 @@ internal void Ldc(bool boolVar) { if (boolVar) { - _ilGen.Emit(OpCodes.Ldc_I4_1); + _ilGen!.Emit(OpCodes.Ldc_I4_1); } else { - _ilGen.Emit(OpCodes.Ldc_I4_0); + _ilGen!.Emit(OpCodes.Ldc_I4_0); } } internal void Ldc(int intVar) { - _ilGen.Emit(OpCodes.Ldc_I4, intVar); + _ilGen!.Emit(OpCodes.Ldc_I4, intVar); } internal void Ldc(long l) { - _ilGen.Emit(OpCodes.Ldc_I8, l); + _ilGen!.Emit(OpCodes.Ldc_I8, l); } internal void Ldc(float f) { - _ilGen.Emit(OpCodes.Ldc_R4, f); + _ilGen!.Emit(OpCodes.Ldc_R4, f); } internal void Ldc(double d) { - _ilGen.Emit(OpCodes.Ldc_R8, d); + _ilGen!.Emit(OpCodes.Ldc_R8, d); } - internal void Ldstr(string strVar) + internal void Ldstr(string? strVar) { if (strVar == null) - _ilGen.Emit(OpCodes.Ldnull); + _ilGen!.Emit(OpCodes.Ldnull); else - _ilGen.Emit(OpCodes.Ldstr, strVar); + _ilGen!.Emit(OpCodes.Ldstr, strVar); } internal void LdlocAddress(LocalBuilder localBuilder) @@ -905,20 +906,20 @@ internal void LdlocAddress(LocalBuilder localBuilder) internal void Ldloc(LocalBuilder localBuilder) { - _ilGen.Emit(OpCodes.Ldloc, localBuilder); + _ilGen!.Emit(OpCodes.Ldloc, localBuilder); } internal void Ldloc(string name) { - Debug.Assert(_currentScope.ContainsKey(name)); - LocalBuilder local = _currentScope[name]; + Debug.Assert(_currentScope!.ContainsKey(name)); + LocalBuilder local = _currentScope[name]!; Ldloc(local); } internal void Stloc(Type type, string name) { - LocalBuilder local = null; - if (!_currentScope.TryGetValue(name, out local)) + LocalBuilder? local = null; + if (!_currentScope!.TryGetValue(name, out local)) { local = DeclareLocal(type, name); } @@ -928,20 +929,20 @@ internal void Stloc(Type type, string name) internal void Stloc(LocalBuilder local) { - _ilGen.Emit(OpCodes.Stloc, local); + _ilGen!.Emit(OpCodes.Stloc, local); } internal void Ldloc(Type type, string name) { - Debug.Assert(_currentScope.ContainsKey(name)); - LocalBuilder local = _currentScope[name]; + Debug.Assert(_currentScope!.ContainsKey(name)); + LocalBuilder local = _currentScope[name]!; Debug.Assert(local.LocalType == type); Ldloc(local); } internal void Ldloca(LocalBuilder localBuilder) { - _ilGen.Emit(OpCodes.Ldloca, localBuilder); + _ilGen!.Emit(OpCodes.Ldloca, localBuilder); } internal void LdargAddress(ArgBuilder argBuilder) @@ -964,7 +965,7 @@ internal void Ldarg(ArgBuilder arg) internal void Ldarg(int slot) { - _ilGen.Emit(OpCodes.Ldarg, slot); + _ilGen!.Emit(OpCodes.Ldarg, slot); } internal void Ldarga(ArgBuilder argBuilder) @@ -974,12 +975,12 @@ internal void Ldarga(ArgBuilder argBuilder) internal void Ldarga(int slot) { - _ilGen.Emit(OpCodes.Ldarga, slot); + _ilGen!.Emit(OpCodes.Ldarga, slot); } internal void Ldlen() { - _ilGen.Emit(OpCodes.Ldlen); + _ilGen!.Emit(OpCodes.Ldlen); _ilGen.Emit(OpCodes.Conv_I4); } @@ -1022,13 +1023,13 @@ internal void Ldelem(Type arrayElementType) Debug.Assert(!opCode.Equals(OpCodes.Nop)); if (opCode.Equals(OpCodes.Nop)) throw new InvalidOperationException(SR.Format(SR.ArrayTypeIsNotSupported, arrayElementType.AssemblyQualifiedName)); - _ilGen.Emit(opCode); + _ilGen!.Emit(opCode); } } internal void Ldelema(Type arrayElementType) { OpCode opCode = OpCodes.Ldelema; - _ilGen.Emit(opCode, arrayElementType); + _ilGen!.Emit(opCode, arrayElementType); } private static readonly OpCode[] s_stelemOpCodes = new OpCode[] { @@ -1067,68 +1068,68 @@ internal void Stelem(Type arrayElementType) OpCode opCode = GetStelemOpCode(arrayElementType.GetTypeCode()); if (opCode.Equals(OpCodes.Nop)) throw new InvalidOperationException(SR.Format(SR.ArrayTypeIsNotSupported, arrayElementType.AssemblyQualifiedName)); - _ilGen.Emit(opCode); + _ilGen!.Emit(opCode); } } internal Label DefineLabel() { - return _ilGen.DefineLabel(); + return _ilGen!.DefineLabel(); } internal void MarkLabel(Label label) { - _ilGen.MarkLabel(label); + _ilGen!.MarkLabel(label); } internal void Nop() { - _ilGen.Emit(OpCodes.Nop); + _ilGen!.Emit(OpCodes.Nop); } internal void Add() { - _ilGen.Emit(OpCodes.Add); + _ilGen!.Emit(OpCodes.Add); } internal void Ret() { - _ilGen.Emit(OpCodes.Ret); + _ilGen!.Emit(OpCodes.Ret); } internal void Br(Label label) { - _ilGen.Emit(OpCodes.Br, label); + _ilGen!.Emit(OpCodes.Br, label); } internal void Br_S(Label label) { - _ilGen.Emit(OpCodes.Br_S, label); + _ilGen!.Emit(OpCodes.Br_S, label); } internal void Blt(Label label) { - _ilGen.Emit(OpCodes.Blt, label); + _ilGen!.Emit(OpCodes.Blt, label); } internal void Brfalse(Label label) { - _ilGen.Emit(OpCodes.Brfalse, label); + _ilGen!.Emit(OpCodes.Brfalse, label); } internal void Brtrue(Label label) { - _ilGen.Emit(OpCodes.Brtrue, label); + _ilGen!.Emit(OpCodes.Brtrue, label); } internal void Pop() { - _ilGen.Emit(OpCodes.Pop); + _ilGen!.Emit(OpCodes.Pop); } internal void Dup() { - _ilGen.Emit(OpCodes.Dup); + _ilGen!.Emit(OpCodes.Dup); } private void InternalIf(bool negate) @@ -1140,7 +1141,7 @@ private void InternalIf(bool negate) Brtrue(ifState.ElseBegin); else Brfalse(ifState.ElseBegin); - _blockStack.Push(ifState); + _blockStack!.Push(ifState); } private static readonly OpCode[] s_convOpCodes = new OpCode[] { @@ -1185,7 +1186,7 @@ private void InternalConvert(Type source, Type target, bool isAddress) } else { - _ilGen.Emit(opCode); + _ilGen!.Emit(opCode); } } else if (source.IsAssignableFrom(target)) @@ -1224,8 +1225,8 @@ private void InternalConvert(Type source, Type target, bool isAddress) private IfState PopIfState() { - object stackTop = _blockStack.Pop(); - IfState ifState = stackTop as IfState; + object stackTop = _blockStack!.Pop(); + IfState? ifState = stackTop as IfState; Debug.Assert(ifState != null); return ifState; } @@ -1250,11 +1251,11 @@ internal static TypeBuilder CreateTypeBuilder(ModuleBuilder moduleBuilder, strin } private int _initElseIfStack = -1; - private IfState _elseIfState; + private IfState? _elseIfState; internal void InitElseIf() { Debug.Assert(_initElseIfStack == -1); - _elseIfState = (IfState)_blockStack.Pop(); + _elseIfState = (IfState)_blockStack!.Pop(); _initElseIfStack = _blockStack.Count; Br(_elseIfState.EndIf); MarkLabel(_elseIfState.ElseBegin); @@ -1264,12 +1265,12 @@ internal void InitElseIf() internal void InitIf() { Debug.Assert(_initIfStack == -1); - _initIfStack = _blockStack.Count; + _initIfStack = _blockStack!.Count; } internal void AndIf(Cmp cmpOp) { - if (_initIfStack == _blockStack.Count) + if (_initIfStack == _blockStack!.Count) { _initIfStack = -1; If(cmpOp); @@ -1278,19 +1279,19 @@ internal void AndIf(Cmp cmpOp) if (_initElseIfStack == _blockStack.Count) { _initElseIfStack = -1; - _elseIfState.ElseBegin = DefineLabel(); - _ilGen.Emit(GetBranchCode(cmpOp), _elseIfState.ElseBegin); + _elseIfState!.ElseBegin = DefineLabel(); + _ilGen!.Emit(GetBranchCode(cmpOp), _elseIfState.ElseBegin); _blockStack.Push(_elseIfState); return; } Debug.Assert(_initIfStack == -1 && _initElseIfStack == -1); IfState ifState = (IfState)_blockStack.Peek(); - _ilGen.Emit(GetBranchCode(cmpOp), ifState.ElseBegin); + _ilGen!.Emit(GetBranchCode(cmpOp), ifState.ElseBegin); } internal void AndIf() { - if (_initIfStack == _blockStack.Count) + if (_initIfStack == _blockStack!.Count) { _initIfStack = -1; If(); @@ -1299,7 +1300,7 @@ internal void AndIf() if (_initElseIfStack == _blockStack.Count) { _initElseIfStack = -1; - _elseIfState.ElseBegin = DefineLabel(); + _elseIfState!.ElseBegin = DefineLabel(); Brfalse(_elseIfState.ElseBegin); _blockStack.Push(_elseIfState); return; @@ -1311,17 +1312,17 @@ internal void AndIf() internal void IsInst(Type type) { - _ilGen.Emit(OpCodes.Isinst, type); + _ilGen!.Emit(OpCodes.Isinst, type); } internal void Beq(Label label) { - _ilGen.Emit(OpCodes.Beq, label); + _ilGen!.Emit(OpCodes.Beq, label); } internal void Bne(Label label) { - _ilGen.Emit(OpCodes.Bne_Un, label); + _ilGen!.Emit(OpCodes.Bne_Un, label); } internal void GotoMethodEnd() @@ -1352,7 +1353,7 @@ public WhileState(CodeGenerator ilg) // (bool on stack) // WhileEndCondition() // WhileEnd() - private Stack _whileStack; + private Stack? _whileStack; internal void WhileBegin() { WhileState whileState = new WhileState(this); @@ -1366,24 +1367,24 @@ internal void WhileBegin() Ldc(true); Brtrue(whileState.CondLabel); MarkLabel(whileState.StartLabel); - _whileStack.Push(whileState); + _whileStack!.Push(whileState); } internal void WhileEnd() { - WhileState whileState = _whileStack.Pop(); + WhileState whileState = _whileStack!.Pop(); MarkLabel(whileState.EndLabel); } internal void WhileContinue() { - WhileState whileState = _whileStack.Peek(); + WhileState whileState = _whileStack!.Peek(); Br(whileState.CondLabel); } internal void WhileBeginCondition() { - WhileState whileState = _whileStack.Peek(); + WhileState whileState = _whileStack!.Peek(); // If there are two MarkLabel ILs consecutively, Labels will converge to one label. // This could cause the code to look different. We insert Nop here specifically // that the While label stands out. @@ -1393,7 +1394,7 @@ internal void WhileBeginCondition() internal void WhileEndCondition() { - WhileState whileState = _whileStack.Peek(); + WhileState whileState = _whileStack!.Peek(); Brtrue(whileState.StartLabel); } } @@ -1502,7 +1503,7 @@ internal Label ElseBegin internal class LocalScope { - public readonly LocalScope parent; + public readonly LocalScope? parent; private readonly Dictionary _locals; // Root scope @@ -1511,7 +1512,7 @@ public LocalScope() _locals = new Dictionary(); } - public LocalScope(LocalScope parent) : this() + public LocalScope(LocalScope? parent) : this() { this.parent = parent; } @@ -1521,7 +1522,7 @@ public bool ContainsKey(string key) return _locals.ContainsKey(key) || (parent != null && parent.ContainsKey(key)); } - public bool TryGetValue(string key, out LocalBuilder value) + public bool TryGetValue(string key, [NotNullWhen(true)] out LocalBuilder? value) { if (_locals.TryGetValue(key, out value)) { @@ -1538,11 +1539,12 @@ public bool TryGetValue(string key, out LocalBuilder value) } } - public LocalBuilder this[string key] + [DisallowNull] + public LocalBuilder? this[string key] { get { - LocalBuilder value; + LocalBuilder? value; TryGetValue(key, out value); return value; } @@ -1557,7 +1559,7 @@ public void AddToFreeLocals(Dictionary, Queue> foreach (var item in _locals) { Tuple key = new Tuple(item.Value.LocalType, item.Key); - Queue freeLocalQueue; + Queue? freeLocalQueue; if (freeLocals.TryGetValue(key, out freeLocalQueue)) { // Add to end of the queue so that it will be re-used in @@ -1584,7 +1586,7 @@ public MethodBuilderInfo(MethodBuilder methodBuilder, Type[] parameterTypes) this.ParameterTypes = parameterTypes; } - public void Validate(Type returnType, Type[] parameterTypes, MethodAttributes attributes) + public void Validate(Type? returnType, Type[] parameterTypes, MethodAttributes attributes) { #if DEBUG Debug.Assert(this.MethodBuilder.ReturnType == returnType); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeIdentifier.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeIdentifier.cs index b6a9ffd3f347e1..2393f70b554b34 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeIdentifier.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeIdentifier.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; using System.Text; using System.Collections; @@ -9,6 +10,7 @@ using System.Diagnostics; using System.Reflection; using System.Runtime.InteropServices; +using System.Diagnostics.CodeAnalysis; namespace System.Xml.Serialization { @@ -162,10 +164,12 @@ private static bool IsValid(char c) return true; } - internal static void CheckValidIdentifier(string ident) + internal static void CheckValidIdentifier([NotNull] string? ident) { if (!CSharpHelpers.IsValidLanguageIndependentIdentifier(ident)) throw new ArgumentException(SR.Format(SR.XmlInvalidIdentifier, ident), nameof(ident)); + + Debug.Assert(ident != null); } internal static string GetCSharpName(string name) @@ -213,12 +217,13 @@ internal static string GetCSharpName(Type t) int rank = 0; while (t.IsArray) { - t = t.GetElementType(); + t = t.GetElementType()!; rank++; } + StringBuilder sb = new StringBuilder(); sb.Append("global::"); - string ns = t.Namespace; + string? ns = t.Namespace; if (ns != null && ns.Length > 0) { string[] parts = ns.Split('.'); @@ -266,7 +271,8 @@ private static void EscapeKeywords(string identifier, StringBuilder sb) } } - private static string EscapeKeywords(string identifier) + [return: NotNullIfNotNull("identifier")] + private static string? EscapeKeywords(string? identifier) { if (identifier == null || identifier.Length == 0) return identifier; string originalIdentifier = identifier; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeIdentifiers.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeIdentifiers.cs index cd22fb63a5b6f7..a19b6774398882 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeIdentifiers.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeIdentifiers.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; @@ -14,14 +15,14 @@ public CaseInsensitiveKeyComparer() : base(CultureInfo.CurrentCulture) { } - bool IEqualityComparer.Equals(object x, object y) + bool IEqualityComparer.Equals(object? x, object? y) { return (Compare(x, y) == 0); } int IEqualityComparer.GetHashCode(object obj) { - string s = obj as string; + string? s = obj as string; if (s == null) throw new ArgumentException(null, nameof(obj)); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Compilation.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Compilation.cs index 67ce05acdec292..86d3ffaa6f81fb 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Compilation.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Compilation.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System.Reflection; using System.Reflection.Emit; using System.Collections; @@ -10,40 +11,41 @@ using System.Security; using System.Globalization; using System.Collections.Generic; +using System.Diagnostics.CodeAnalysis; namespace System.Xml.Serialization { internal class TempAssembly { internal const string GeneratedAssemblyNamespace = "Microsoft.Xml.Serialization.GeneratedAssembly"; - private readonly Assembly _assembly; - private XmlSerializerImplementation _contract; - private IDictionary _writerMethods; - private IDictionary _readerMethods; - private TempMethodDictionary _methods; + private readonly Assembly? _assembly; + private XmlSerializerImplementation? _contract; + private IDictionary? _writerMethods; + private IDictionary? _readerMethods; + private TempMethodDictionary? _methods; internal class TempMethod { - internal MethodInfo writeMethod; - internal MethodInfo readMethod; - internal string name; - internal string ns; + internal MethodInfo? writeMethod; + internal MethodInfo? readMethod; + internal string? name; + internal string? ns; internal bool isSoap; - internal string methodKey; + internal string? methodKey; } private TempAssembly() { } - internal TempAssembly(XmlMapping[] xmlMappings, Assembly assembly, XmlSerializerImplementation contract) + internal TempAssembly(XmlMapping[] xmlMappings, Assembly assembly, XmlSerializerImplementation? contract) { _assembly = assembly; InitAssemblyMethods(xmlMappings); _contract = contract; } - internal TempAssembly(XmlMapping[] xmlMappings, Type[] types, string defaultNamespace, string location) + internal TempAssembly(XmlMapping[] xmlMappings, Type?[] types, string? defaultNamespace, string? location) { bool containsSoapMapping = false; for (int i = 0; i < xmlMappings.Length; i++) @@ -104,7 +106,7 @@ internal XmlSerializerImplementation Contract { if (_contract == null) { - _contract = (XmlSerializerImplementation)Activator.CreateInstance(GetTypeFromAssembly(_assembly, "XmlSerializerContract")); + _contract = (XmlSerializerImplementation)Activator.CreateInstance(GetTypeFromAssembly(_assembly!, "XmlSerializerContract"))!; } return _contract; } @@ -118,13 +120,13 @@ internal void InitAssemblyMethods(XmlMapping[] xmlMappings) TempMethod method = new TempMethod(); method.isSoap = xmlMappings[i].IsSoap; method.methodKey = xmlMappings[i].Key; - XmlTypeMapping xmlTypeMapping = xmlMappings[i] as XmlTypeMapping; + XmlTypeMapping? xmlTypeMapping = xmlMappings[i] as XmlTypeMapping; if (xmlTypeMapping != null) { method.name = xmlTypeMapping.ElementName; method.ns = xmlTypeMapping.Namespace; } - _methods.Add(xmlMappings[i].Key, method); + _methods.Add(xmlMappings[i].Key!, method); } } @@ -136,11 +138,11 @@ internal void InitAssemblyMethods(XmlMapping[] xmlMappings) /// // SxS: This method does not take any resource name and does not expose any resources to the caller. // It's OK to suppress the SxS warning. - internal static Assembly LoadGeneratedAssembly(Type type, string defaultNamespace, out XmlSerializerImplementation contract) + internal static Assembly? LoadGeneratedAssembly(Type type, string? defaultNamespace, out XmlSerializerImplementation? contract) { - Assembly serializer = null; + Assembly? serializer = null; contract = null; - string serializerName = null; + string? serializerName = null; // check to see if we loading explicit pre-generated assembly object[] attrs = type.GetCustomAttributes(typeof(System.Xml.Serialization.XmlSerializerAssemblyAttribute), false); @@ -154,18 +156,18 @@ internal static Assembly LoadGeneratedAssembly(Type type, string defaultNamespac name.CodeBase = null; name.CultureInfo = CultureInfo.InvariantCulture; - string serializerPath = null; + string? serializerPath = null; try { if (!string.IsNullOrEmpty(type.Assembly.Location)) { - serializerPath = Path.Combine(Path.GetDirectoryName(type.Assembly.Location), serializerName + ".dll"); + serializerPath = Path.Combine(Path.GetDirectoryName(type.Assembly.Location)!, serializerName + ".dll"); } if ((string.IsNullOrEmpty(serializerPath) || !File.Exists(serializerPath)) && !string.IsNullOrEmpty(Assembly.GetEntryAssembly()?.Location)) { - serializerPath = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), serializerName + ".dll"); + serializerPath = Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly()!.Location)!, serializerName + ".dll"); } if (!string.IsNullOrEmpty(serializerPath)) @@ -179,7 +181,7 @@ internal static Assembly LoadGeneratedAssembly(Type type, string defaultNamespac { throw; } - byte[] token = name.GetPublicKeyToken(); + byte[]? token = name.GetPublicKeyToken(); if (token != null && token.Length > 0) { // the parent assembly was signed, so do not try to LoadWithPartialName @@ -199,7 +201,7 @@ internal static Assembly LoadGeneratedAssembly(Type type, string defaultNamespac if (!IsSerializerVersionMatch(serializer, type, defaultNamespace)) { - XmlSerializationEventSource.Log.XmlSerializerExpired(serializerName, type.FullName); + XmlSerializationEventSource.Log.XmlSerializerExpired(serializerName, type.FullName!); return null; } } @@ -233,14 +235,14 @@ internal static Assembly LoadGeneratedAssembly(Type type, string defaultNamespac } } Type contractType = GetTypeFromAssembly(serializer, "XmlSerializerContract"); - contract = (XmlSerializerImplementation)Activator.CreateInstance(contractType); + contract = (XmlSerializerImplementation)Activator.CreateInstance(contractType)!; if (contract.CanSerialize(type)) return serializer; return null; } - private static bool IsSerializerVersionMatch(Assembly serializer, Type type, string defaultNamespace) + private static bool IsSerializerVersionMatch(Assembly serializer, Type type, string? defaultNamespace) { if (serializer == null) return false; @@ -268,21 +270,21 @@ private static string GenerateAssemblyId(Type type) for (int i = 0; i < list.Count; i++) { - sb.Append(list[i].ToString()); + sb.Append(list[i]!.ToString()); sb.Append(','); } return sb.ToString(); } - internal static bool GenerateSerializerToStream(XmlMapping[] xmlMappings, Type[] types, string defaultNamespace, Assembly assembly, Hashtable assemblies, Stream stream) + internal static bool GenerateSerializerToStream(XmlMapping[] xmlMappings, Type?[] types, string? defaultNamespace, Assembly? assembly, Hashtable assemblies, Stream stream) { var compiler = new Compiler(); try { var scopeTable = new Hashtable(); foreach (XmlMapping mapping in xmlMappings) - scopeTable[mapping.Scope] = mapping; + scopeTable[mapping.Scope!] = mapping; var scopes = new TypeScope[scopeTable.Keys.Count]; scopeTable.Keys.CopyTo(scopes, 0); @@ -295,7 +297,7 @@ internal static bool GenerateSerializerToStream(XmlMapping[] xmlMappings, Type[] { compiler.AddImport(t, importedTypes); Assembly a = t.Assembly; - string name = a.FullName; + string name = a.FullName!; if (assemblies[name] != null) { continue; @@ -321,7 +323,7 @@ internal static bool GenerateSerializerToStream(XmlMapping[] xmlMappings, Type[] { for (int i = 0; i < types.Length; i++) { - Type type = types[i]; + Type? type = types[i]; if (type == null) { continue; @@ -329,7 +331,7 @@ internal static bool GenerateSerializerToStream(XmlMapping[] xmlMappings, Type[] if (DynamicAssemblies.IsTypeDynamic(type)) { - throw new InvalidOperationException(SR.Format(SR.XmlPregenTypeDynamic, types[i].FullName)); + throw new InvalidOperationException(SR.Format(SR.XmlPregenTypeDynamic, types[i]!.FullName)); } } @@ -337,7 +339,7 @@ internal static bool GenerateSerializerToStream(XmlMapping[] xmlMappings, Type[] writer.Write(typeof(XmlSerializerVersionAttribute).FullName); writer.Write("("); writer.Write("ParentAssemblyId="); - ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, GenerateAssemblyId(types[0])); + ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, GenerateAssemblyId(types[0]!)); writer.Write(", Version="); ReflectionAwareCodeGen.WriteQuotedCSharpString(writer, ThisAssembly.Version); if (defaultNamespace != null) @@ -352,12 +354,12 @@ internal static bool GenerateSerializerToStream(XmlMapping[] xmlMappings, Type[] var classes = new CodeIdentifiers(); classes.AddUnique("XmlSerializationWriter", "XmlSerializationWriter"); classes.AddUnique("XmlSerializationReader", "XmlSerializationReader"); - string suffix = null; + string? suffix = null; if (types != null && types.Length == 1 && types[0] != null) { - suffix = CodeIdentifier.MakeValid(types[0].Name); - if (types[0].IsArray) + suffix = CodeIdentifier.MakeValid(types[0]!.Name); + if (types[0]!.IsArray) { suffix += "Array"; } @@ -371,7 +373,7 @@ internal static bool GenerateSerializerToStream(XmlMapping[] xmlMappings, Type[] writerClass = classes.AddUnique(writerClass, writerClass); var writerCodeGen = new XmlSerializationWriterCodeGen(writer, scopes, "public", writerClass); writerCodeGen.GenerateBegin(); - string[] writeMethodNames = new string[xmlMappings.Length]; + string?[] writeMethodNames = new string[xmlMappings.Length]; for (int i = 0; i < xmlMappings.Length; i++) { @@ -385,10 +387,10 @@ internal static bool GenerateSerializerToStream(XmlMapping[] xmlMappings, Type[] readerClass = classes.AddUnique(readerClass, readerClass); var readerCodeGen = new XmlSerializationReaderCodeGen(writer, scopes, "public", readerClass); readerCodeGen.GenerateBegin(); - string[] readMethodNames = new string[xmlMappings.Length]; + string?[] readMethodNames = new string[xmlMappings.Length]; for (int i = 0; i < xmlMappings.Length; i++) { - readMethodNames[i] = readerCodeGen.GenerateElement(xmlMappings[i]); + readMethodNames[i] = readerCodeGen.GenerateElement(xmlMappings[i])!; } readerCodeGen.GenerateEnd(readMethodNames, xmlMappings, types); @@ -397,17 +399,17 @@ internal static bool GenerateSerializerToStream(XmlMapping[] xmlMappings, Type[] var serializers = new Hashtable(); for (int i = 0; i < xmlMappings.Length; i++) { - if (serializers[xmlMappings[i].Key] == null) + if (serializers[xmlMappings[i].Key!] == null) { - serializers[xmlMappings[i].Key] = readerCodeGen.GenerateTypedSerializer(readMethodNames[i], writeMethodNames[i], xmlMappings[i], classes, baseSerializer, readerClass, writerClass); + serializers[xmlMappings[i].Key!] = readerCodeGen.GenerateTypedSerializer(readMethodNames[i], writeMethodNames[i], xmlMappings[i], classes, baseSerializer, readerClass, writerClass); } } - readerCodeGen.GenerateSerializerContract("XmlSerializerContract", xmlMappings, types, readerClass, readMethodNames, writerClass, writeMethodNames, serializers); + readerCodeGen.GenerateSerializerContract("XmlSerializerContract", xmlMappings, types!, readerClass, readMethodNames, writerClass, writeMethodNames, serializers); writer.Indent--; writer.WriteLine("}"); - string codecontent = compiler.Source.ToString(); + string codecontent = compiler.Source.ToString()!; byte[] info = new UTF8Encoding(true).GetBytes(codecontent); stream.Write(info, 0, info.Length); stream.Flush(); @@ -419,11 +421,11 @@ internal static bool GenerateSerializerToStream(XmlMapping[] xmlMappings, Type[] } } - internal static Assembly GenerateRefEmitAssembly(XmlMapping[] xmlMappings, Type[] types, string defaultNamespace) + internal static Assembly GenerateRefEmitAssembly(XmlMapping[] xmlMappings, Type?[]? types, string? defaultNamespace) { var scopeTable = new Dictionary(); foreach (XmlMapping mapping in xmlMappings) - scopeTable[mapping.Scope] = mapping; + scopeTable[mapping.Scope!] = mapping; TypeScope[] scopes = new TypeScope[scopeTable.Keys.Count]; scopeTable.Keys.CopyTo(scopes, 0); @@ -434,18 +436,18 @@ internal static Assembly GenerateRefEmitAssembly(XmlMapping[] xmlMappings, Type[ { ConstructorInfo AssemblyVersionAttribute_ctor = typeof(AssemblyVersionAttribute).GetConstructor( new Type[] { typeof(string) } - ); - string assemblyVersion = types[0].Assembly.GetName().Version.ToString(); + )!; + string assemblyVersion = types[0]!.Assembly.GetName().Version!.ToString(); assemblyBuilder.SetCustomAttribute(new CustomAttributeBuilder(AssemblyVersionAttribute_ctor, new object[] { assemblyVersion })); } CodeIdentifiers classes = new CodeIdentifiers(); classes.AddUnique("XmlSerializationWriter", "XmlSerializationWriter"); classes.AddUnique("XmlSerializationReader", "XmlSerializationReader"); - string suffix = null; + string? suffix = null; if (types != null && types.Length == 1 && types[0] != null) { - suffix = CodeIdentifier.MakeValid(types[0].Name); - if (types[0].IsArray) + suffix = CodeIdentifier.MakeValid(types[0]!.Name); + if (types[0]!.IsArray) { suffix += "Array"; } @@ -463,7 +465,7 @@ internal static Assembly GenerateRefEmitAssembly(XmlMapping[] xmlMappings, Type[ for (int i = 0; i < xmlMappings.Length; i++) { - writeMethodNames[i] = writerCodeGen.GenerateElement(xmlMappings[i]); + writeMethodNames[i] = writerCodeGen.GenerateElement(xmlMappings[i])!; } Type writerType = writerCodeGen.GenerateEnd(); @@ -478,27 +480,27 @@ internal static Assembly GenerateRefEmitAssembly(XmlMapping[] xmlMappings, Type[ string[] readMethodNames = new string[xmlMappings.Length]; for (int i = 0; i < xmlMappings.Length; i++) { - readMethodNames[i] = readerCodeGen.GenerateElement(xmlMappings[i]); + readMethodNames[i] = readerCodeGen.GenerateElement(xmlMappings[i])!; } - readerCodeGen.GenerateEnd(readMethodNames, xmlMappings, types); + readerCodeGen.GenerateEnd(readMethodNames, xmlMappings, types!); string baseSerializer = readerCodeGen.GenerateBaseSerializer("XmlSerializer1", readerClass, writerClass, classes); var serializers = new Dictionary(); for (int i = 0; i < xmlMappings.Length; i++) { - if (!serializers.ContainsKey(xmlMappings[i].Key)) + if (!serializers.ContainsKey(xmlMappings[i].Key!)) { - serializers[xmlMappings[i].Key] = readerCodeGen.GenerateTypedSerializer(readMethodNames[i], writeMethodNames[i], xmlMappings[i], classes, baseSerializer, readerClass, writerClass); + serializers[xmlMappings[i].Key!] = readerCodeGen.GenerateTypedSerializer(readMethodNames[i], writeMethodNames[i], xmlMappings[i], classes, baseSerializer, readerClass, writerClass); } } - readerCodeGen.GenerateSerializerContract("XmlSerializerContract", xmlMappings, types, readerClass, readMethodNames, writerClass, writeMethodNames, serializers); + readerCodeGen.GenerateSerializerContract("XmlSerializerContract", xmlMappings, types!, readerClass, readMethodNames, writerClass, writeMethodNames, serializers); return writerType.Assembly; } private static MethodInfo GetMethodFromType(Type type, string methodName) { - MethodInfo method = type.GetMethod(methodName); + MethodInfo? method = type.GetMethod(methodName); if (method != null) return method; @@ -510,7 +512,7 @@ private static MethodInfo GetMethodFromType(Type type, string methodName) internal static Type GetTypeFromAssembly(Assembly assembly, string typeName) { typeName = GeneratedAssemblyNamespace + "." + typeName; - Type type = assembly.GetType(typeName); + Type? type = assembly.GetType(typeName); if (type == null) throw new InvalidOperationException(SR.Format(SR.XmlMissingType, typeName, assembly.FullName)); return type; @@ -525,15 +527,16 @@ internal bool CanRead(XmlMapping mapping, XmlReader xmlReader) { return true; } - TempMethod method = _methods[mapping.Key]; - return xmlReader.IsStartElement(method.name, method.ns); + TempMethod method = _methods![mapping.Key!]; + return xmlReader.IsStartElement(method.name!, method.ns!); } - private string ValidateEncodingStyle(string encodingStyle, string methodKey) + [return: NotNullIfNotNull("encodingStyle")] + private string? ValidateEncodingStyle(string? encodingStyle, string methodKey) { if (encodingStyle != null && encodingStyle.Length > 0) { - if (_methods[methodKey].isSoap) + if (_methods![methodKey].isSoap) { if (encodingStyle != Soap.Encoding && encodingStyle != Soap12.Encoding) { @@ -547,7 +550,7 @@ private string ValidateEncodingStyle(string encodingStyle, string methodKey) } else { - if (_methods[methodKey].isSoap) + if (_methods![methodKey].isSoap) { encodingStyle = Soap.Encoding; } @@ -555,28 +558,28 @@ private string ValidateEncodingStyle(string encodingStyle, string methodKey) return encodingStyle; } - internal object InvokeReader(XmlMapping mapping, XmlReader xmlReader, XmlDeserializationEvents events, string encodingStyle) + internal object? InvokeReader(XmlMapping mapping, XmlReader xmlReader, XmlDeserializationEvents events, string? encodingStyle) { - XmlSerializationReader reader = null; + XmlSerializationReader? reader = null; try { - encodingStyle = ValidateEncodingStyle(encodingStyle, mapping.Key); + encodingStyle = ValidateEncodingStyle(encodingStyle, mapping.Key!); reader = Contract.Reader; reader.Init(xmlReader, events, encodingStyle, this); - if (_methods[mapping.Key].readMethod == null) + if (_methods![mapping.Key!].readMethod == null) { if (_readerMethods == null) { _readerMethods = Contract.ReadMethods; } - string methodName = (string)_readerMethods[mapping.Key]; + string? methodName = (string?)_readerMethods[mapping.Key!]; if (methodName == null) { throw new InvalidOperationException(SR.Format(SR.XmlNotSerializable, mapping.Accessor.Name)); } - _methods[mapping.Key].readMethod = GetMethodFromType(reader.GetType(), methodName); + _methods[mapping.Key!].readMethod = GetMethodFromType(reader.GetType(), methodName); } - return _methods[mapping.Key].readMethod.Invoke(reader, Array.Empty()); + return _methods[mapping.Key!].readMethod!.Invoke(reader, Array.Empty()); } catch (SecurityException e) { @@ -589,28 +592,28 @@ internal object InvokeReader(XmlMapping mapping, XmlReader xmlReader, XmlDeseria } } - internal void InvokeWriter(XmlMapping mapping, XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle, string id) + internal void InvokeWriter(XmlMapping mapping, XmlWriter xmlWriter, object? o, XmlSerializerNamespaces? namespaces, string? encodingStyle, string? id) { - XmlSerializationWriter writer = null; + XmlSerializationWriter? writer = null; try { - encodingStyle = ValidateEncodingStyle(encodingStyle, mapping.Key); + encodingStyle = ValidateEncodingStyle(encodingStyle, mapping.Key!); writer = Contract.Writer; writer.Init(xmlWriter, namespaces, encodingStyle, id, this); - if (_methods[mapping.Key].writeMethod == null) + if (_methods![mapping.Key!].writeMethod == null) { if (_writerMethods == null) { _writerMethods = Contract.WriteMethods; } - string methodName = (string)_writerMethods[mapping.Key]; + string? methodName = (string?)_writerMethods[mapping.Key!]; if (methodName == null) { throw new InvalidOperationException(SR.Format(SR.XmlNotSerializable, mapping.Accessor.Name)); } - _methods[mapping.Key].writeMethod = GetMethodFromType(writer.GetType(), methodName); + _methods[mapping.Key!].writeMethod = GetMethodFromType(writer.GetType(), methodName); } - _methods[mapping.Key].writeMethod.Invoke(writer, new object[] { o }); + _methods[mapping.Key!].writeMethod!.Invoke(writer, new object?[] { o }); } catch (SecurityException e) { @@ -630,18 +633,18 @@ internal sealed class TempMethodDictionary : Dictionary internal class TempAssemblyCacheKey { - private readonly string _ns; + private readonly string? _ns; private readonly object _type; - internal TempAssemblyCacheKey(string ns, object type) + internal TempAssemblyCacheKey(string? ns, object type) { _type = type; _ns = ns; } - public override bool Equals(object o) + public override bool Equals(object? o) { - TempAssemblyCacheKey key = o as TempAssemblyCacheKey; + TempAssemblyCacheKey? key = o as TempAssemblyCacheKey; if (key == null) return false; return (key._type == _type && key._ns == _ns); @@ -657,22 +660,22 @@ internal class TempAssemblyCache { private Dictionary _cache = new Dictionary(); - internal TempAssembly this[string ns, object o] + internal TempAssembly? this[string? ns, object o] { get { - TempAssembly tempAssembly; + TempAssembly? tempAssembly; _cache.TryGetValue(new TempAssemblyCacheKey(ns, o), out tempAssembly); return tempAssembly; } } - internal void Add(string ns, object o, TempAssembly assembly) + internal void Add(string? ns, object o, TempAssembly assembly) { TempAssemblyCacheKey key = new TempAssemblyCacheKey(ns, o); lock (this) { - TempAssembly tempAssembly; + TempAssembly? tempAssembly; if (_cache.TryGetValue(key, out tempAssembly) && tempAssembly == assembly) return; Dictionary _copy = new Dictionary(_cache); // clone diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Compiler.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Compiler.cs index c5782f3cff3fd0..5de0d1bb434a58 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Compiler.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Compiler.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System.Reflection; @@ -26,7 +27,7 @@ internal class Compiler // SxS: This method does not take any resource name and does not expose any resources to the caller. // It's OK to suppress the SxS warning. - internal void AddImport(Type type, Hashtable types) + internal void AddImport(Type? type, Hashtable types) { if (type == null) return; @@ -35,11 +36,11 @@ internal void AddImport(Type type, Hashtable types) if (types[type] != null) return; types[type] = type; - Type baseType = type.BaseType; + Type? baseType = type.BaseType; if (baseType != null) AddImport(baseType, types); - Type declaringType = type.DeclaringType; + Type? declaringType = type.DeclaringType; if (declaringType != null) AddImport(declaringType, types); @@ -76,7 +77,8 @@ internal void AddImport(Type type, Hashtable types) object[] typeForwardedFromAttribute = type.GetCustomAttributes(typeof(TypeForwardedFromAttribute), false); if (typeForwardedFromAttribute.Length > 0) { - TypeForwardedFromAttribute originalAssemblyInfo = typeForwardedFromAttribute[0] as TypeForwardedFromAttribute; + TypeForwardedFromAttribute? originalAssemblyInfo = typeForwardedFromAttribute[0] as TypeForwardedFromAttribute; + Debug.Assert(originalAssemblyInfo != null); Assembly originalAssembly = Assembly.Load(new AssemblyName(originalAssemblyInfo.AssemblyFullName)); } } @@ -94,7 +96,7 @@ internal TextWriter Source get { return _writer; } } - internal static string GetTempAssemblyName(AssemblyName parent, string ns) + internal static string GetTempAssemblyName(AssemblyName parent, string? ns) { return parent.Name + ".XmlSerializers" + (ns == null || ns.Length == 0 ? "" : "." + ns.GetHashCode()); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Configuration/DateTimeSerializationSection.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Configuration/DateTimeSerializationSection.cs index c841409eaea8c1..bad80f2ac8ae30 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Configuration/DateTimeSerializationSection.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Configuration/DateTimeSerializationSection.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization.Configuration { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Globals.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Globals.cs index 1a83cd547d992c..868c60cc311262 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Globals.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Globals.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System.Diagnostics.CodeAnalysis; using System.Security; using System.Reflection; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/IXmlSerializable.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/IXmlSerializable.cs index 7dcea55f073831..e2d444a36bf050 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/IXmlSerializable.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/IXmlSerializable.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System.Xml; @@ -12,7 +13,7 @@ namespace System.Xml.Serialization /// public interface IXmlSerializable { - XmlSchema GetSchema(); + XmlSchema? GetSchema(); void ReadXml(XmlReader reader); void WriteXml(XmlWriter writer); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/IXmlTextParser.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/IXmlTextParser.cs index 4e1acb19e25816..685485f3da0dfa 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/IXmlTextParser.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/IXmlTextParser.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System.Xml; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ImportContext.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ImportContext.cs index 79cedd9bb3bd3a..6af84291c6edf5 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ImportContext.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ImportContext.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; @@ -15,16 +16,17 @@ namespace System.Xml.Serialization public class ImportContext { private readonly bool _shareTypes; - private SchemaObjectCache _cache; // cached schema top-level items - private Hashtable _mappings; // XmlSchema -> SerializableMapping, XmlSchemaSimpleType -> EnumMapping, XmlSchemaComplexType -> StructMapping - private Hashtable _elements; // XmlSchemaElement -> ElementAccessor - private CodeIdentifiers _typeIdentifiers; + private SchemaObjectCache? _cache; // cached schema top-level items + private Hashtable? _mappings; // XmlSchema -> SerializableMapping, XmlSchemaSimpleType -> EnumMapping, XmlSchemaComplexType -> StructMapping + private Hashtable? _elements; // XmlSchemaElement -> ElementAccessor + private CodeIdentifiers? _typeIdentifiers; - public ImportContext(CodeIdentifiers identifiers, bool shareTypes) + public ImportContext(CodeIdentifiers? identifiers, bool shareTypes) { _typeIdentifiers = identifiers; _shareTypes = shareTypes; } + internal ImportContext() : this(null, false) { } internal SchemaObjectCache Cache @@ -80,10 +82,10 @@ public StringCollection Warnings internal class SchemaObjectCache { - private Hashtable _graph; - private Hashtable _hash; - private Hashtable _objectCache; - private StringCollection _warnings; + private Hashtable? _graph; + private Hashtable? _hash; + private Hashtable? _objectCache; + private StringCollection? _warnings; // UNDONE remove me soon, this is debug only code internal Hashtable looks = new Hashtable(); private Hashtable Graph @@ -126,7 +128,7 @@ internal StringCollection Warnings } } - internal XmlSchemaObject AddItem(XmlSchemaObject item, XmlQualifiedName qname, XmlSchemas schemas) + internal XmlSchemaObject? AddItem(XmlSchemaObject? item, XmlQualifiedName? qname, XmlSchemas schemas) { if (item == null) return null; @@ -134,7 +136,7 @@ internal XmlSchemaObject AddItem(XmlSchemaObject item, XmlQualifiedName qname, X return null; string key = item.GetType().Name + ":" + qname.ToString(); - ArrayList list = (ArrayList)ObjectCache[key]; + ArrayList? list = (ArrayList?)ObjectCache[key]; if (list == null) { list = new ArrayList(); @@ -143,7 +145,7 @@ internal XmlSchemaObject AddItem(XmlSchemaObject item, XmlQualifiedName qname, X for (int i = 0; i < list.Count; i++) { - XmlSchemaObject cachedItem = (XmlSchemaObject)list[i]; + XmlSchemaObject cachedItem = (XmlSchemaObject)list[i]!; if (cachedItem == item) return cachedItem; @@ -154,7 +156,7 @@ internal XmlSchemaObject AddItem(XmlSchemaObject item, XmlQualifiedName qname, X else { Warnings.Add(SR.Format(SR.XmlMismatchSchemaObjects, item.GetType().Name, qname.Name, qname.Namespace)); - Warnings.Add("DEBUG:Cached item key:\r\n" + (string)looks[cachedItem] + "\r\nnew item key:\r\n" + (string)looks[item]); + Warnings.Add("DEBUG:Cached item key:\r\n" + (string?)looks[cachedItem] + "\r\nnew item key:\r\n" + (string?)looks[item]); } } // no match found we need to insert the new type in the cache @@ -170,7 +172,7 @@ internal bool Match(XmlSchemaObject o1, XmlSchemaObject o2, bool shareTypes) return false; if (Hash[o1] == null) Hash[o1] = GetHash(o1); - int hash1 = (int)Hash[o1]; + int hash1 = (int)Hash[o1]!; int hash2 = GetHash(o2); if (hash1 != hash2) return false; @@ -186,12 +188,12 @@ private ArrayList GetDependencies(XmlSchemaObject o, ArrayList deps, Hashtable r { refs[o] = o; deps.Add(o); - ArrayList list = Graph[o] as ArrayList; + ArrayList? list = Graph[o] as ArrayList; if (list != null) { for (int i = 0; i < list.Count; i++) { - GetDependencies((XmlSchemaObject)list[i], deps, refs); + GetDependencies((XmlSchemaObject)list[i]!, deps, refs); } } } @@ -204,7 +206,7 @@ private int CompositeHash(XmlSchemaObject o, int hash) double tmp = 0; for (int i = 0; i < list.Count; i++) { - object cachedHash = Hash[list[i]]; + object? cachedHash = Hash[list[i]!]; if (cachedHash is int) { tmp += (int)cachedHash / list.Count; @@ -220,13 +222,13 @@ internal void GenerateSchemaGraph(XmlSchemas schemas) for (int i = 0; i < items.Count; i++) { - GetHash((XmlSchemaObject)items[i]); + GetHash((XmlSchemaObject)items[i]!); } } private int GetHash(XmlSchemaObject o) { - object hash = Hash[o]; + object? hash = Hash[o]; if (hash != null) { if (hash is XmlSchemaObject) @@ -279,15 +281,15 @@ internal ArrayList GetItems() return new ArrayList(_scope.Keys); } - internal void AddRef(ArrayList list, XmlSchemaObject o) + internal void AddRef(ArrayList list, XmlSchemaObject? o) { if (o == null) return; if (_schemas.IsReference(o)) return; - if (o.Parent is XmlSchema) + if (o.Parent is XmlSchema parent) { - string ns = ((XmlSchema)o.Parent).TargetNamespace; + string? ns = parent.TargetNamespace; if (ns == XmlSchema.Namespace) return; if (list.Contains(o)) @@ -301,7 +303,7 @@ internal ArrayList Depends(XmlSchemaObject item) if (item.Parent is XmlSchema) { if (_scope[item] != null) - return (ArrayList)_scope[item]; + return (ArrayList)_scope[item]!; ArrayList refs = new ArrayList(); Depends(item, refs); @@ -311,7 +313,7 @@ internal ArrayList Depends(XmlSchemaObject item) return _empty; } - internal void Depends(XmlSchemaObject item, ArrayList refs) + internal void Depends(XmlSchemaObject? item, ArrayList refs) { if (item == null || _scope[item] != null) return; @@ -320,16 +322,16 @@ internal void Depends(XmlSchemaObject item, ArrayList refs) if (typeof(XmlSchemaType).IsAssignableFrom(t)) { XmlQualifiedName baseName = XmlQualifiedName.Empty; - XmlSchemaType baseType = null; - XmlSchemaParticle particle = null; - XmlSchemaObjectCollection attributes = null; + XmlSchemaType? baseType = null; + XmlSchemaParticle? particle = null; + XmlSchemaObjectCollection? attributes = null; if (item is XmlSchemaComplexType) { XmlSchemaComplexType ct = (XmlSchemaComplexType)item; if (ct.ContentModel != null) { - XmlSchemaContent content = ct.ContentModel.Content; + XmlSchemaContent? content = ct.ContentModel.Content; if (content is XmlSchemaComplexContentRestriction) { baseName = ((XmlSchemaComplexContentRestriction)content).BaseTypeName; @@ -366,7 +368,7 @@ internal void Depends(XmlSchemaObject item, ArrayList refs) if (particle is XmlSchemaGroupRef) { XmlSchemaGroupRef refGroup = (XmlSchemaGroupRef)particle; - particle = ((XmlSchemaGroup)_schemas.Find(refGroup.RefName, typeof(XmlSchemaGroup), false)).Particle; + particle = ((XmlSchemaGroup)_schemas.Find(refGroup.RefName, typeof(XmlSchemaGroup), false)!).Particle; } else if (particle is XmlSchemaGroupBase) { @@ -376,7 +378,7 @@ internal void Depends(XmlSchemaObject item, ArrayList refs) else if (item is XmlSchemaSimpleType) { XmlSchemaSimpleType simpleType = (XmlSchemaSimpleType)item; - XmlSchemaSimpleTypeContent content = simpleType.Content; + XmlSchemaSimpleTypeContent? content = simpleType.Content; if (content is XmlSchemaSimpleTypeRestriction) { baseType = ((XmlSchemaSimpleTypeRestriction)content).BaseType; @@ -394,20 +396,20 @@ internal void Depends(XmlSchemaObject item, ArrayList refs) } else if (t == typeof(XmlSchemaSimpleTypeUnion)) { - XmlQualifiedName[] memberTypes = ((XmlSchemaSimpleTypeUnion)item).MemberTypes; + XmlQualifiedName[]? memberTypes = ((XmlSchemaSimpleTypeUnion)item).MemberTypes; if (memberTypes != null) { for (int i = 0; i < memberTypes.Length; i++) { - XmlSchemaType type = (XmlSchemaType)_schemas.Find(memberTypes[i], typeof(XmlSchemaType), false); + XmlSchemaType? type = (XmlSchemaType?)_schemas.Find(memberTypes[i], typeof(XmlSchemaType), false); AddRef(refs, type); } } } } if (baseType == null && !baseName.IsEmpty && baseName.Namespace != XmlSchema.Namespace) - baseType = (XmlSchemaType)_schemas.Find(baseName, typeof(XmlSchemaType), false); + baseType = (XmlSchemaType?)_schemas.Find(baseName, typeof(XmlSchemaType), false); if (baseType != null) { @@ -432,18 +434,18 @@ internal void Depends(XmlSchemaObject item, ArrayList refs) { if (el.SubstitutionGroup.Namespace != XmlSchema.Namespace) { - XmlSchemaElement head = (XmlSchemaElement)_schemas.Find(el.SubstitutionGroup, typeof(XmlSchemaElement), false); + XmlSchemaElement? head = (XmlSchemaElement?)_schemas.Find(el.SubstitutionGroup, typeof(XmlSchemaElement), false); AddRef(refs, head); } } if (!el.RefName.IsEmpty) { - el = (XmlSchemaElement)_schemas.Find(el.RefName, typeof(XmlSchemaElement), false); + el = (XmlSchemaElement)_schemas.Find(el.RefName, typeof(XmlSchemaElement), false)!; AddRef(refs, el); } else if (!el.SchemaTypeName.IsEmpty) { - XmlSchemaType type = (XmlSchemaType)_schemas.Find(el.SchemaTypeName, typeof(XmlSchemaType), false); + XmlSchemaType? type = (XmlSchemaType?)_schemas.Find(el.SchemaTypeName, typeof(XmlSchemaType), false); AddRef(refs, type); } else @@ -453,11 +455,11 @@ internal void Depends(XmlSchemaObject item, ArrayList refs) } else if (t == typeof(XmlSchemaGroup)) { - Depends(((XmlSchemaGroup)item).Particle); + Depends(((XmlSchemaGroup)item).Particle!); } else if (t == typeof(XmlSchemaGroupRef)) { - XmlSchemaGroup group = (XmlSchemaGroup)_schemas.Find(((XmlSchemaGroupRef)item).RefName, typeof(XmlSchemaGroup), false); + XmlSchemaGroup? group = (XmlSchemaGroup?)_schemas.Find(((XmlSchemaGroupRef)item).RefName, typeof(XmlSchemaGroup), false); AddRef(refs, group); } else if (typeof(XmlSchemaGroupBase).IsAssignableFrom(t)) @@ -469,7 +471,7 @@ internal void Depends(XmlSchemaObject item, ArrayList refs) } else if (t == typeof(XmlSchemaAttributeGroupRef)) { - XmlSchemaAttributeGroup group = (XmlSchemaAttributeGroup)_schemas.Find(((XmlSchemaAttributeGroupRef)item).RefName, typeof(XmlSchemaAttributeGroup), false); + XmlSchemaAttributeGroup? group = (XmlSchemaAttributeGroup?)_schemas.Find(((XmlSchemaAttributeGroupRef)item).RefName, typeof(XmlSchemaAttributeGroup), false); AddRef(refs, group); } else if (t == typeof(XmlSchemaAttributeGroup)) @@ -481,15 +483,15 @@ internal void Depends(XmlSchemaObject item, ArrayList refs) } else if (t == typeof(XmlSchemaAttribute)) { - XmlSchemaAttribute at = (XmlSchemaAttribute)item; + XmlSchemaAttribute? at = (XmlSchemaAttribute)item; if (!at.RefName.IsEmpty) { - at = (XmlSchemaAttribute)_schemas.Find(at.RefName, typeof(XmlSchemaAttribute), false); + at = (XmlSchemaAttribute?)_schemas.Find(at.RefName, typeof(XmlSchemaAttribute), false); AddRef(refs, at); } else if (!at.SchemaTypeName.IsEmpty) { - XmlSchemaType type = (XmlSchemaType)_schemas.Find(at.SchemaTypeName, typeof(XmlSchemaType), false); + XmlSchemaType? type = (XmlSchemaType?)_schemas.Find(at.SchemaTypeName, typeof(XmlSchemaType), false); AddRef(refs, type); } else @@ -499,7 +501,7 @@ internal void Depends(XmlSchemaObject item, ArrayList refs) } if (typeof(XmlSchemaAnnotated).IsAssignableFrom(t)) { - XmlAttribute[] attrs = (XmlAttribute[])((XmlSchemaAnnotated)item).UnhandledAttributes; + XmlAttribute[]? attrs = (XmlAttribute[]?)((XmlSchemaAnnotated)item).UnhandledAttributes; if (attrs != null) { @@ -510,7 +512,7 @@ internal void Depends(XmlSchemaObject item, ArrayList refs) { string dims; XmlQualifiedName qname = TypeScope.ParseWsdlArrayType(attribute.Value, out dims, item); - XmlSchemaType type = (XmlSchemaType)_schemas.Find(qname, typeof(XmlSchemaType), false); + XmlSchemaType? type = (XmlSchemaType?)_schemas.Find(qname, typeof(XmlSchemaType), false); AddRef(refs, type); } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Mappings.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Mappings.cs index d77c6828383e79..9a67c0df253350 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Mappings.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Mappings.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System.Reflection; @@ -11,6 +12,7 @@ namespace System.Xml.Serialization using System.ComponentModel; using System.Xml; using System.Xml.Serialization; + using System.Diagnostics.CodeAnalysis; // These classes represent a mapping between classes and a particular XML format. // There are two class of mapping information: accessors (such as elements and @@ -18,12 +20,12 @@ namespace System.Xml.Serialization internal abstract class Accessor { - private string _name; - private object _defaultValue; - private string _ns; - private TypeMapping _mapping; + private string? _name; + private object? _defaultValue; + private string? _ns; + private TypeMapping? _mapping; private bool _any; - private string _anyNs; + private string? _anyNs; private bool _topLevelInSchema; private bool _isFixed; private bool _isOptional; @@ -31,13 +33,13 @@ internal abstract class Accessor internal Accessor() { } - internal TypeMapping Mapping + internal TypeMapping? Mapping { get { return _mapping; } set { _mapping = value; } } - internal object Default + internal object? Default { get { return _defaultValue; } set { _defaultValue = value; } @@ -48,6 +50,7 @@ internal bool HasDefault get { return _defaultValue != null && _defaultValue != DBNull.Value; } } + [AllowNull] internal virtual string Name { get { return _name == null ? string.Empty : _name; } @@ -60,13 +63,13 @@ internal bool Any set { _any = value; } } - internal string AnyNamespaces + internal string? AnyNamespaces { get { return _anyNs; } set { _anyNs = value; } } - internal string Namespace + internal string? Namespace { get { return _ns; } set { _ns = value; } @@ -96,13 +99,15 @@ internal bool IsTopLevelInSchema set { _topLevelInSchema = value; } } - internal static string EscapeName(string name) + [return: NotNullIfNotNull("name")] + internal static string? EscapeName(string? name) { if (name == null || name.Length == 0) return name; return XmlConvert.EncodeLocalName(name); } - internal static string EscapeQName(string name) + [return: NotNullIfNotNull("name")] + internal static string? EscapeQName(string? name) { if (name == null || name.Length == 0) return name; int colon = name.LastIndexOf(':'); @@ -116,12 +121,13 @@ internal static string EscapeQName(string name) } } - internal static string UnescapeName(string name) + [return: NotNullIfNotNull("name")] + internal static string? UnescapeName(string? name) { return XmlConvert.DecodeName(name); } - internal string ToString(string defaultNs) + internal string ToString(string? defaultNs) { if (Any) { @@ -177,23 +183,23 @@ internal ElementAccessor Clone() internal class ChoiceIdentifierAccessor : Accessor { - private string _memberName; - private string[] _memberIds; - private MemberInfo _memberInfo; + private string? _memberName; + private string[]? _memberIds; + private MemberInfo? _memberInfo; - internal string MemberName + internal string? MemberName { get { return _memberName; } set { _memberName = value; } } - internal string[] MemberIds + internal string[]? MemberIds { get { return _memberIds; } set { _memberIds = value; } } - internal MemberInfo MemberInfo + internal MemberInfo? MemberInfo { get { return _memberInfo; } set { _memberInfo = value; } @@ -276,9 +282,9 @@ internal bool IsSoap internal abstract class TypeMapping : Mapping { - private TypeDesc _typeDesc; - private string _typeNs; - private string _typeName; + private TypeDesc? _typeDesc; + private string? _typeNs; + private string? _typeName; private bool _referencedByElement; private bool _referencedByTopLevelElement; private bool _includeInSchema = true; @@ -295,19 +301,19 @@ internal bool ReferencedByElement get { return _referencedByElement || _referencedByTopLevelElement; } set { _referencedByElement = value; } } - internal string Namespace + internal string? Namespace { get { return _typeNs; } set { _typeNs = value; } } - internal string TypeName + internal string? TypeName { get { return _typeName; } set { _typeName = value; } } - internal TypeDesc TypeDesc + internal TypeDesc? TypeDesc { get { return _typeDesc; } set { _typeDesc = value; } @@ -331,6 +337,7 @@ internal bool IsReference set { _reference = value; } } + [MemberNotNullWhen(false, nameof(_typeName))] internal bool IsAnonymousType { get { return _typeName == null || _typeName.Length == 0; } @@ -338,7 +345,7 @@ internal bool IsAnonymousType internal virtual string DefaultElementName { - get { return IsAnonymousType ? XmlConvert.EncodeLocalName(_typeDesc.Name) : _typeName; } + get { return IsAnonymousType ? XmlConvert.EncodeLocalName(_typeDesc!.Name) : _typeName; } } } @@ -355,9 +362,9 @@ internal override bool IsList internal class NullableMapping : TypeMapping { - private TypeMapping _baseMapping; + private TypeMapping? _baseMapping; - internal TypeMapping BaseMapping + internal TypeMapping? BaseMapping { get { return _baseMapping; } set { _baseMapping = value; } @@ -365,24 +372,24 @@ internal TypeMapping BaseMapping internal override string DefaultElementName { - get { return BaseMapping.DefaultElementName; } + get { return BaseMapping!.DefaultElementName; } } } internal class ArrayMapping : TypeMapping { - private ElementAccessor[] _elements; - private ElementAccessor[] _sortedElements; - private ArrayMapping _next; - private StructMapping _topLevelMapping; + private ElementAccessor[]? _elements; + private ElementAccessor[]? _sortedElements; + private ArrayMapping? _next; + private StructMapping? _topLevelMapping; - internal ElementAccessor[] Elements + internal ElementAccessor[]? Elements { get { return _elements; } set { _elements = value; _sortedElements = null; } } - internal ElementAccessor[] ElementsSortedByDerivation + internal ElementAccessor[]? ElementsSortedByDerivation { get { @@ -398,13 +405,13 @@ internal ElementAccessor[] ElementsSortedByDerivation } - internal ArrayMapping Next + internal ArrayMapping? Next { get { return _next; } set { _next = value; } } - internal StructMapping TopLevelMapping + internal StructMapping? TopLevelMapping { get { return _topLevelMapping; } set { _topLevelMapping = value; } @@ -413,7 +420,7 @@ internal StructMapping TopLevelMapping internal class EnumMapping : PrimitiveMapping { - private ConstantMapping[] _constants; + private ConstantMapping[]? _constants; private bool _isFlags; internal bool IsFlags @@ -422,7 +429,7 @@ internal bool IsFlags set { _isFlags = value; } } - internal ConstantMapping[] Constants + internal ConstantMapping[]? Constants { get { return _constants; } set { _constants = value; } @@ -431,16 +438,18 @@ internal ConstantMapping[] Constants internal class ConstantMapping : Mapping { - private string _xmlName; - private string _name; + private string? _xmlName; + private string? _name; private long _value; + [AllowNull] internal string XmlName { get { return _xmlName == null ? string.Empty : _xmlName; } set { _xmlName = value; } } + [AllowNull] internal string Name { get { return _name == null ? string.Empty : _name; } @@ -456,19 +465,20 @@ internal long Value internal class StructMapping : TypeMapping, INameScope { - private MemberMapping[] _members; - private StructMapping _baseMapping; - private StructMapping _derivedMappings; - private StructMapping _nextDerivedMapping; - private MemberMapping _xmlnsMember; + private MemberMapping[]? _members; + private StructMapping? _baseMapping; + private StructMapping? _derivedMappings; + private StructMapping? _nextDerivedMapping; + private MemberMapping? _xmlnsMember; private bool _hasSimpleContent; private bool _openModel; private bool _isSequence; - private NameTable _elements; - private NameTable _attributes; - private CodeIdentifiers _scope; + private NameTable? _elements; + private NameTable? _attributes; + private CodeIdentifiers? _scope; - internal StructMapping BaseMapping + [DisallowNull] + internal StructMapping? BaseMapping { get { return _baseMapping; } set @@ -482,9 +492,9 @@ internal StructMapping BaseMapping if (value._isSequence && !_isSequence) { _isSequence = true; - if (_baseMapping.IsSequence) + if (_baseMapping!.IsSequence) { - for (StructMapping derived = _derivedMappings; derived != null; derived = derived.NextDerivedMapping) + for (StructMapping? derived = _derivedMappings; derived != null; derived = derived.NextDerivedMapping) { derived.SetSequence(); } @@ -493,7 +503,7 @@ internal StructMapping BaseMapping } } - internal StructMapping DerivedMappings + internal StructMapping? DerivedMappings { get { return _derivedMappings; } } @@ -521,11 +531,11 @@ internal NameTable LocalAttributes return _attributes; } } - object INameScope.this[string name, string ns] + object? INameScope.this[string? name, string? ns] { get { - object named = LocalElements[name, ns]; + object? named = LocalElements[name, ns]; if (named != null) return named; if (_baseMapping != null) @@ -537,7 +547,7 @@ internal NameTable LocalAttributes LocalElements[name, ns] = value; } } - internal StructMapping NextDerivedMapping + internal StructMapping? NextDerivedMapping { get { return _nextDerivedMapping; } } @@ -551,7 +561,7 @@ internal bool HasXmlnsMember { get { - StructMapping mapping = this; + StructMapping? mapping = this; while (mapping != null) { if (mapping.XmlnsMember != null) @@ -562,13 +572,13 @@ internal bool HasXmlnsMember } } - internal MemberMapping[] Members + internal MemberMapping[]? Members { get { return _members; } set { _members = value; } } - internal MemberMapping XmlnsMember + internal MemberMapping? XmlnsMember { get { return _xmlnsMember; } set { _xmlnsMember = value; } @@ -591,12 +601,12 @@ internal CodeIdentifiers Scope set { _scope = value; } } - internal MemberMapping FindDeclaringMapping(MemberMapping member, out StructMapping declaringMapping, string parent) + internal MemberMapping? FindDeclaringMapping(MemberMapping member, out StructMapping? declaringMapping, string? parent) { declaringMapping = null; if (BaseMapping != null) { - MemberMapping baseMember = BaseMapping.FindDeclaringMapping(member, out declaringMapping, parent); + MemberMapping? baseMember = BaseMapping.FindDeclaringMapping(member, out declaringMapping, parent); if (baseMember != null) return baseMember; } if (_members == null) return null; @@ -606,7 +616,7 @@ internal MemberMapping FindDeclaringMapping(MemberMapping member, out StructMapp if (_members[i].Name == member.Name) { if (_members[i].TypeDesc != member.TypeDesc) - throw new InvalidOperationException(SR.Format(SR.XmlHiddenMember, parent, member.Name, member.TypeDesc.FullName, this.TypeName, _members[i].Name, _members[i].TypeDesc.FullName)); + throw new InvalidOperationException(SR.Format(SR.XmlHiddenMember, parent, member.Name, member.TypeDesc!.FullName, this.TypeName, _members[i].Name, _members[i].TypeDesc!.FullName)); else if (!_members[i].Match(member)) { throw new InvalidOperationException(SR.Format(SR.XmlInvalidXmlOverride, parent, member.Name, this.TypeName, _members[i].Name)); @@ -617,24 +627,24 @@ internal MemberMapping FindDeclaringMapping(MemberMapping member, out StructMapp } return null; } - internal bool Declares(MemberMapping member, string parent) + internal bool Declares(MemberMapping member, string? parent) { - StructMapping m; + StructMapping? m; return (FindDeclaringMapping(member, out m, parent) != null); } - internal void SetContentModel(TextAccessor text, bool hasElements) + internal void SetContentModel(TextAccessor? text, bool hasElements) { - if (BaseMapping == null || BaseMapping.TypeDesc.IsRoot) + if (BaseMapping == null || BaseMapping.TypeDesc!.IsRoot) { - _hasSimpleContent = !hasElements && text != null && !text.Mapping.IsList; + _hasSimpleContent = !hasElements && text != null && !text.Mapping!.IsList; } else if (BaseMapping.HasSimpleContent) { if (text != null || hasElements) { // we can only extent a simleContent type with attributes - throw new InvalidOperationException(SR.Format(SR.XmlIllegalSimpleContentExtension, TypeDesc.FullName, BaseMapping.TypeDesc.FullName)); + throw new InvalidOperationException(SR.Format(SR.XmlIllegalSimpleContentExtension, TypeDesc!.FullName, BaseMapping.TypeDesc.FullName)); } else { @@ -645,9 +655,9 @@ internal void SetContentModel(TextAccessor text, bool hasElements) { _hasSimpleContent = false; } - if (!_hasSimpleContent && text != null && !text.Mapping.TypeDesc.CanBeTextValue && !(BaseMapping != null && !BaseMapping.TypeDesc.IsRoot && (text.Mapping.TypeDesc.IsEnum || text.Mapping.TypeDesc.IsPrimitive))) + if (!_hasSimpleContent && text != null && !text.Mapping!.TypeDesc!.CanBeTextValue && !(BaseMapping != null && !BaseMapping.TypeDesc!.IsRoot && (text.Mapping.TypeDesc.IsEnum || text.Mapping.TypeDesc.IsPrimitive))) { - throw new InvalidOperationException(SR.Format(SR.XmlIllegalTypedTextAttribute, TypeDesc.FullName, text.Name, text.Mapping.TypeDesc.FullName)); + throw new InvalidOperationException(SR.Format(SR.XmlIllegalTypedTextAttribute, TypeDesc!.FullName, text.Name, text.Mapping.TypeDesc.FullName)); } } @@ -668,17 +678,17 @@ internal bool HasExplicitSequence() internal void SetSequence() { - if (TypeDesc.IsRoot) + if (TypeDesc!.IsRoot) return; StructMapping start = this; // find first mapping that does not have the sequence set - while (start.BaseMapping != null && !start.BaseMapping.IsSequence && !start.BaseMapping.TypeDesc.IsRoot) + while (start.BaseMapping != null && !start.BaseMapping.IsSequence && !start.BaseMapping.TypeDesc!.IsRoot) start = start.BaseMapping; start.IsSequence = true; - for (StructMapping derived = start.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) + for (StructMapping? derived = start.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) { derived.SetSequence(); } @@ -686,20 +696,20 @@ internal void SetSequence() internal bool IsSequence { - get { return _isSequence && !TypeDesc.IsRoot; } + get { return _isSequence && !TypeDesc!.IsRoot; } set { _isSequence = value; } } } internal abstract class AccessorMapping : Mapping { - private TypeDesc _typeDesc; - private AttributeAccessor _attribute; - private ElementAccessor[] _elements; - private ElementAccessor[] _sortedElements; - private TextAccessor _text; - private ChoiceIdentifierAccessor _choiceIdentifier; - private XmlnsAccessor _xmlns; + private TypeDesc? _typeDesc; + private AttributeAccessor? _attribute; + private ElementAccessor[]? _elements; + private ElementAccessor[]? _sortedElements; + private TextAccessor? _text; + private ChoiceIdentifierAccessor? _choiceIdentifier; + private XmlnsAccessor? _xmlns; private bool _ignore; internal AccessorMapping() @@ -733,19 +743,19 @@ internal bool IsParticle get { return (_elements != null && _elements.Length > 0); } } - internal TypeDesc TypeDesc + internal TypeDesc? TypeDesc { get { return _typeDesc; } set { _typeDesc = value; } } - internal AttributeAccessor Attribute + internal AttributeAccessor? Attribute { get { return _attribute; } set { _attribute = value; } } - internal ElementAccessor[] Elements + internal ElementAccessor[]? Elements { get { return _elements; } set { _elements = value; _sortedElements = null; } @@ -758,14 +768,14 @@ internal static void SortMostToLeastDerived(ElementAccessor[] elements) internal class AccessorComparer : IComparer { - public int Compare(object o1, object o2) + public int Compare(object? o1, object? o2) { if (o1 == o2) return 0; - Accessor a1 = (Accessor)o1; - Accessor a2 = (Accessor)o2; - int w1 = a1.Mapping.TypeDesc.Weight; - int w2 = a2.Mapping.TypeDesc.Weight; + Accessor a1 = (Accessor)o1!; + Accessor a2 = (Accessor)o2!; + int w1 = a1.Mapping!.TypeDesc!.Weight; + int w2 = a2.Mapping!.TypeDesc!.Weight; if (w1 == w2) return 0; if (w1 < w2) @@ -774,7 +784,7 @@ public int Compare(object o1, object o2) } } - internal ElementAccessor[] ElementsSortedByDerivation + internal ElementAccessor[]? ElementsSortedByDerivation { get { @@ -789,19 +799,19 @@ internal ElementAccessor[] ElementsSortedByDerivation } } - internal TextAccessor Text + internal TextAccessor? Text { get { return _text; } set { _text = value; } } - internal ChoiceIdentifierAccessor ChoiceIdentifier + internal ChoiceIdentifierAccessor? ChoiceIdentifier { get { return _choiceIdentifier; } set { _choiceIdentifier = value; } } - internal XmlnsAccessor Xmlns + internal XmlnsAccessor? Xmlns { get { return _xmlns; } set { _xmlns = value; } @@ -813,7 +823,7 @@ internal bool Ignore set { _ignore = value; } } - internal Accessor Accessor + internal Accessor? Accessor { get { @@ -824,7 +834,7 @@ internal Accessor Accessor } } - internal static bool ElementsMatch(ElementAccessor[] a, ElementAccessor[] b) + internal static bool ElementsMatch(ElementAccessor[]? a, ElementAccessor[]? b) { if (a == null) { @@ -873,10 +883,10 @@ internal bool Match(AccessorMapping mapping) internal class MemberMappingComparer : IComparer { - public int Compare(object o1, object o2) + public int Compare(object? o1, object? o2) { - MemberMapping m1 = (MemberMapping)o1; - MemberMapping m2 = (MemberMapping)o2; + MemberMapping m1 = (MemberMapping)o1!; + MemberMapping m2 = (MemberMapping)o2!; bool m1Text = m1.IsText; if (m1Text) @@ -904,15 +914,15 @@ public int Compare(object o1, object o2) internal class MemberMapping : AccessorMapping { - private string _name; + private string? _name; private bool _checkShouldPersist; private SpecifiedAccessor _checkSpecified; private bool _isReturnValue; private bool _readOnly; private int _sequenceId = -1; - private MemberInfo _memberInfo; - private MemberInfo _checkSpecifiedMemberInfo; - private MethodInfo _checkShouldPersistMethodInfo; + private MemberInfo? _memberInfo; + private MemberInfo? _checkSpecifiedMemberInfo; + private MethodInfo? _checkShouldPersistMethodInfo; internal MemberMapping() { } @@ -948,19 +958,19 @@ internal string Name set { _name = value; } } - internal MemberInfo MemberInfo + internal MemberInfo? MemberInfo { get { return _memberInfo; } set { _memberInfo = value; } } - internal MemberInfo CheckSpecifiedMemberInfo + internal MemberInfo? CheckSpecifiedMemberInfo { get { return _checkSpecifiedMemberInfo; } set { _checkSpecifiedMemberInfo = value; } } - internal MethodInfo CheckShouldPersistMethodInfo + internal MethodInfo? CheckShouldPersistMethodInfo { get { return _checkShouldPersistMethodInfo; } set { _checkShouldPersistMethodInfo = value; } @@ -992,7 +1002,7 @@ internal int SequenceId private string GetNullableType(TypeDesc td) { // SOAP encoded arrays not mapped to Nullable since they always derive from soapenc:Array - if (td.IsMappedType || (!td.IsValueType && (Elements[0].IsSoap || td.ArrayElementTypeDesc == null))) + if (td.IsMappedType || (!td.IsValueType && (Elements![0].IsSoap || td.ArrayElementTypeDesc == null))) return td.FullName; if (td.ArrayElementTypeDesc != null) { @@ -1009,19 +1019,19 @@ internal MemberMapping Clone() internal class MembersMapping : TypeMapping { - private MemberMapping[] _members; + private MemberMapping[]? _members; private bool _hasWrapperElement = true; private bool _validateRpcWrapperElement; private bool _writeAccessors = true; - private MemberMapping _xmlnsMember; + private MemberMapping? _xmlnsMember; - internal MemberMapping[] Members + internal MemberMapping[]? Members { get { return _members; } set { _members = value; } } - internal MemberMapping XmlnsMember + internal MemberMapping? XmlnsMember { get { return _xmlnsMember; } set { _xmlnsMember = value; } @@ -1059,25 +1069,25 @@ internal bool NamedAny internal class SerializableMapping : SpecialMapping { - private XmlSchema _schema; - private Type _type; + private XmlSchema? _schema; + private Type? _type; private bool _needSchema = true; // new implementation of the IXmlSerializable - private readonly MethodInfo _getSchemaMethod; - private XmlQualifiedName _xsiType; - private XmlSchemaType _xsdType; - private XmlSchemaSet _schemas; + private readonly MethodInfo? _getSchemaMethod; + private XmlQualifiedName? _xsiType; + private XmlSchemaType? _xsdType; + private XmlSchemaSet? _schemas; private bool _any; - private string _namespaces; + private string? _namespaces; - private SerializableMapping _baseMapping; - private SerializableMapping _derivedMappings; - private SerializableMapping _nextDerivedMapping; - private SerializableMapping _next; // all mappings with the same qname + private SerializableMapping? _baseMapping; + private SerializableMapping? _derivedMappings; + private SerializableMapping? _nextDerivedMapping; + private SerializableMapping? _next; // all mappings with the same qname internal SerializableMapping() { } - internal SerializableMapping(MethodInfo getSchemaMethod, bool any, string ns) + internal SerializableMapping(MethodInfo getSchemaMethod, bool any, string? ns) { _getSchemaMethod = getSchemaMethod; _any = any; @@ -1094,7 +1104,7 @@ internal SerializableMapping(XmlQualifiedName xsiType, XmlSchemaSet schemas) _needSchema = false; } - internal void SetBaseMapping(SerializableMapping mapping) + internal void SetBaseMapping(SerializableMapping? mapping) { _baseMapping = mapping; if (_baseMapping != null) @@ -1103,7 +1113,7 @@ internal void SetBaseMapping(SerializableMapping mapping) _baseMapping._derivedMappings = this; if (this == _nextDerivedMapping) { - throw new InvalidOperationException(SR.Format(SR.XmlCircularDerivation, TypeDesc.FullName)); + throw new InvalidOperationException(SR.Format(SR.XmlCircularDerivation, TypeDesc!.FullName)); } } } @@ -1153,7 +1163,7 @@ internal string NamespaceList } } - internal SerializableMapping DerivedMappings + internal SerializableMapping? DerivedMappings { get { @@ -1161,7 +1171,7 @@ internal SerializableMapping DerivedMappings } } - internal SerializableMapping NextDerivedMapping + internal SerializableMapping? NextDerivedMapping { get { @@ -1169,19 +1179,19 @@ internal SerializableMapping NextDerivedMapping } } - internal SerializableMapping Next + internal SerializableMapping? Next { get { return _next; } set { _next = value; } } - internal Type Type + internal Type? Type { get { return _type; } set { _type = value; } } - internal XmlSchemaSet Schemas + internal XmlSchemaSet? Schemas { get { @@ -1190,7 +1200,7 @@ internal XmlSchemaSet Schemas } } - internal XmlSchema Schema + internal XmlSchema? Schema { get { @@ -1199,7 +1209,7 @@ internal XmlSchema Schema } } - internal XmlQualifiedName XsiType + internal XmlQualifiedName? XsiType { get { @@ -1214,7 +1224,7 @@ internal XmlQualifiedName XsiType } } - internal XmlSchemaType XsdType + internal XmlSchemaType? XsdType { get { @@ -1223,14 +1233,14 @@ internal XmlSchemaType XsdType } } - internal static void ValidationCallbackWithErrorCode(object sender, ValidationEventArgs args) + internal static void ValidationCallbackWithErrorCode(object? sender, ValidationEventArgs args) { // CONSIDER: need the real type name if (args.Severity == XmlSeverityType.Error) throw new InvalidOperationException(SR.Format(SR.XmlSerializableSchemaError, typeof(IXmlSerializable).Name, args.Message)); } - internal void CheckDuplicateElement(XmlSchemaElement element, string elementNs) + internal void CheckDuplicateElement(XmlSchemaElement? element, string? elementNs) { if (element == null) return; @@ -1239,7 +1249,7 @@ internal void CheckDuplicateElement(XmlSchemaElement element, string elementNs) if (element.Parent == null || !(element.Parent is XmlSchema)) return; - XmlSchemaObjectTable elements = null; + XmlSchemaObjectTable? elements = null; if (Schema != null && Schema.TargetNamespace == elementNs) { XmlSchemas.Preprocess(Schema); @@ -1260,7 +1270,7 @@ internal void CheckDuplicateElement(XmlSchemaElement element, string elementNs) if (Match(e, element)) return; // XmlSerializableRootDupName=Cannot reconcile schema for '{0}'. Please use [XmlRoot] attribute to change name or namepace of the top-level element to avoid duplicate element declarations: element name='{1} namespace='{2}'. - throw new InvalidOperationException(SR.Format(SR.XmlSerializableRootDupName, _getSchemaMethod.DeclaringType.FullName, e.Name, elementNs)); + throw new InvalidOperationException(SR.Format(SR.XmlSerializableRootDupName, _getSchemaMethod!.DeclaringType!.FullName, e.Name, elementNs)); } } } @@ -1298,7 +1308,7 @@ private void RetrieveSerializableSchema() // get the type info if (_schemas == null) _schemas = new XmlSchemaSet(); - object typeInfo = _getSchemaMethod.Invoke(null, new object[] { _schemas }); + object? typeInfo = _getSchemaMethod.Invoke(null, new object[] { _schemas }); _xsiType = XmlQualifiedName.Empty; if (typeInfo != null) @@ -1314,12 +1324,12 @@ private void RetrieveSerializableSchema() _xsiType = (XmlQualifiedName)typeInfo; if (_xsiType.IsEmpty) { - throw new InvalidOperationException(SR.Format(SR.XmlGetSchemaEmptyTypeName, _type.FullName, _getSchemaMethod.Name)); + throw new InvalidOperationException(SR.Format(SR.XmlGetSchemaEmptyTypeName, _type!.FullName, _getSchemaMethod.Name)); } } else { - throw new InvalidOperationException(SR.Format(SR.XmlGetSchemaMethodReturnType, _type.Name, _getSchemaMethod.Name, typeof(XmlSchemaProviderAttribute).Name, typeof(XmlQualifiedName).FullName)); + throw new InvalidOperationException(SR.Format(SR.XmlGetSchemaMethodReturnType, _type!.Name, _getSchemaMethod.Name, typeof(XmlSchemaProviderAttribute).Name, typeof(XmlQualifiedName).FullName)); } } else @@ -1347,17 +1357,17 @@ private void RetrieveSerializableSchema() } if (srcSchemas.Count > 1) { - throw new InvalidOperationException(SR.Format(SR.XmlGetSchemaInclude, _xsiType.Namespace, _getSchemaMethod.DeclaringType.FullName, _getSchemaMethod.Name)); + throw new InvalidOperationException(SR.Format(SR.XmlGetSchemaInclude, _xsiType.Namespace, _getSchemaMethod.DeclaringType!.FullName, _getSchemaMethod.Name)); } - XmlSchema s = (XmlSchema)srcSchemas[0]; + XmlSchema? s = (XmlSchema?)srcSchemas[0]; if (s == null) { throw new InvalidOperationException(SR.Format(SR.XmlMissingSchema, _xsiType.Namespace)); } - _xsdType = (XmlSchemaType)s.SchemaTypes[_xsiType]; + _xsdType = (XmlSchemaType?)s.SchemaTypes[_xsiType]; if (_xsdType == null) { - throw new InvalidOperationException(SR.Format(SR.XmlGetSchemaTypeMissing, _getSchemaMethod.DeclaringType.FullName, _getSchemaMethod.Name, _xsiType.Name, _xsiType.Namespace)); + throw new InvalidOperationException(SR.Format(SR.XmlGetSchemaTypeMissing, _getSchemaMethod.DeclaringType!.FullName, _getSchemaMethod.Name, _xsiType.Name, _xsiType.Namespace)); } _xsdType = _xsdType.Redefined != null ? _xsdType.Redefined : _xsdType; } @@ -1365,12 +1375,12 @@ private void RetrieveSerializableSchema() } else { - IXmlSerializable serializable = (IXmlSerializable)Activator.CreateInstance(_type); + IXmlSerializable serializable = (IXmlSerializable)Activator.CreateInstance(_type!)!; _schema = serializable.GetSchema(); if (_schema != null) { - if (_schema.Id == null || _schema.Id.Length == 0) throw new InvalidOperationException(SR.Format(SR.XmlSerializableNameMissing1, _type.FullName)); + if (_schema.Id == null || _schema.Id.Length == 0) throw new InvalidOperationException(SR.Format(SR.XmlSerializableNameMissing1, _type!.FullName)); } } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Models.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Models.cs index 6bfa59fd802686..9d0010e2baaa73 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Models.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Models.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; @@ -37,7 +38,7 @@ internal TypeModel GetTypeModel(Type type) internal TypeModel GetTypeModel(Type type, bool directReference) { - TypeModel model; + TypeModel? model; if (_models.TryGetValue(type, out model)) return model; TypeDesc typeDesc = _typeScope.GetTypeDesc(type, null, directReference); @@ -72,7 +73,7 @@ internal TypeModel GetTypeModel(Type type, bool directReference) internal ArrayModel GetArrayModel(Type type) { - TypeModel model; + TypeModel? model; if (!_arrayModels.TryGetValue(type, out model)) { model = GetTypeModel(type); @@ -122,7 +123,7 @@ internal ArrayModel(Type type, TypeDesc typeDesc, ModelScope scope) : base(type, internal TypeModel Element { - get { return ModelScope.GetTypeModel(TypeScope.GetArrayElementType(Type, null)); } + get { return ModelScope.GetTypeModel(TypeScope.GetArrayElementType(Type, null)!); } } } @@ -168,9 +169,9 @@ internal MemberInfo[] GetMemberInfos() return fieldsAndProps; } - internal FieldModel GetFieldModel(MemberInfo memberInfo) + internal FieldModel? GetFieldModel(MemberInfo memberInfo) { - FieldModel model = null; + FieldModel? model = null; if (memberInfo is FieldInfo) model = GetFieldModel((FieldInfo)memberInfo); else if (memberInfo is PropertyInfo) @@ -183,7 +184,7 @@ internal FieldModel GetFieldModel(MemberInfo memberInfo) return model; } - private void CheckSupportedMember(TypeDesc typeDesc, MemberInfo member, Type type) + private void CheckSupportedMember(TypeDesc? typeDesc, MemberInfo member, Type type) { if (typeDesc == null) return; @@ -193,13 +194,13 @@ private void CheckSupportedMember(TypeDesc typeDesc, MemberInfo member, Type typ { typeDesc.Exception = new NotSupportedException(SR.Format(SR.XmlSerializerUnsupportedType, typeDesc.FullName)); } - throw new InvalidOperationException(SR.Format(SR.XmlSerializerUnsupportedMember, member.DeclaringType.FullName + "." + member.Name, type.FullName), typeDesc.Exception); + throw new InvalidOperationException(SR.Format(SR.XmlSerializerUnsupportedMember, member.DeclaringType!.FullName + "." + member.Name, type.FullName), typeDesc.Exception); } CheckSupportedMember(typeDesc.BaseTypeDesc, member, type); CheckSupportedMember(typeDesc.ArrayElementTypeDesc, member, type); } - private FieldModel GetFieldModel(FieldInfo fieldInfo) + private FieldModel? GetFieldModel(FieldInfo fieldInfo) { if (fieldInfo.IsStatic) return null; if (fieldInfo.DeclaringType != Type) return null; @@ -212,7 +213,7 @@ private FieldModel GetFieldModel(FieldInfo fieldInfo) return new FieldModel(fieldInfo, fieldInfo.FieldType, typeDesc); } - private FieldModel GetPropertyModel(PropertyInfo propertyInfo) + private FieldModel? GetPropertyModel(PropertyInfo propertyInfo) { if (propertyInfo.DeclaringType != Type) return null; if (CheckPropertyRead(propertyInfo)) @@ -232,7 +233,7 @@ internal static bool CheckPropertyRead(PropertyInfo propertyInfo) { if (!propertyInfo.CanRead) return false; - MethodInfo getMethod = propertyInfo.GetMethod; + MethodInfo getMethod = propertyInfo.GetMethod!; if (getMethod.IsStatic) return false; ParameterInfo[] parameters = getMethod.GetParameters(); if (parameters.Length > 0) return false; @@ -250,9 +251,9 @@ internal enum SpecifiedAccessor internal class FieldModel { private readonly SpecifiedAccessor _checkSpecified = SpecifiedAccessor.None; - private readonly MemberInfo _memberInfo; - private readonly MemberInfo _checkSpecifiedMemberInfo; - private readonly MethodInfo _checkShouldPersistMethodInfo; + private readonly MemberInfo? _memberInfo; + private readonly MemberInfo? _checkSpecifiedMemberInfo; + private readonly MethodInfo? _checkShouldPersistMethodInfo; private readonly bool _checkShouldPersist; private readonly bool _readOnly; private readonly bool _isProperty; @@ -280,10 +281,10 @@ internal FieldModel(MemberInfo memberInfo, Type fieldType, TypeDesc fieldTypeDes _fieldType = fieldType; _fieldTypeDesc = fieldTypeDesc; _memberInfo = memberInfo; - _checkShouldPersistMethodInfo = memberInfo.DeclaringType.GetMethod("ShouldSerialize" + memberInfo.Name, Array.Empty()); + _checkShouldPersistMethodInfo = memberInfo.DeclaringType!.GetMethod("ShouldSerialize" + memberInfo.Name, Array.Empty()); _checkShouldPersist = _checkShouldPersistMethodInfo != null; - FieldInfo specifiedField = memberInfo.DeclaringType.GetField(memberInfo.Name + "Specified"); + FieldInfo? specifiedField = memberInfo.DeclaringType.GetField(memberInfo.Name + "Specified"); if (specifiedField != null) { if (specifiedField.FieldType != typeof(bool)) @@ -295,7 +296,7 @@ internal FieldModel(MemberInfo memberInfo, Type fieldType, TypeDesc fieldTypeDes } else { - PropertyInfo specifiedProperty = memberInfo.DeclaringType.GetProperty(memberInfo.Name + "Specified"); + PropertyInfo? specifiedProperty = memberInfo.DeclaringType.GetProperty(memberInfo.Name + "Specified"); if (specifiedProperty != null) { if (StructModel.CheckPropertyRead(specifiedProperty)) @@ -345,15 +346,15 @@ internal SpecifiedAccessor CheckSpecified get { return _checkSpecified; } } - internal MemberInfo MemberInfo + internal MemberInfo? MemberInfo { get { return _memberInfo; } } - internal MemberInfo CheckSpecifiedMemberInfo + internal MemberInfo? CheckSpecifiedMemberInfo { get { return _checkSpecifiedMemberInfo; } } - internal MethodInfo CheckShouldPersistMethodInfo + internal MethodInfo? CheckShouldPersistMethodInfo { get { return _checkShouldPersistMethodInfo; } } @@ -398,7 +399,7 @@ internal FieldInfo FieldInfo internal class EnumModel : TypeModel { - private ConstantModel[] _constants; + private ConstantModel[]? _constants; internal EnumModel(Type type, TypeDesc typeDesc, ModelScope scope) : base(type, typeDesc, scope) { } @@ -413,7 +414,7 @@ internal ConstantModel[] Constants for (int i = 0; i < fields.Length; i++) { FieldInfo field = fields[i]; - ConstantModel constant = GetConstantModel(field); + ConstantModel? constant = GetConstantModel(field); if (constant != null) list.Add(constant); } _constants = list.ToArray(); @@ -422,10 +423,10 @@ internal ConstantModel[] Constants } } - private ConstantModel GetConstantModel(FieldInfo fieldInfo) + private ConstantModel? GetConstantModel(FieldInfo fieldInfo) { if (fieldInfo.IsSpecialName) return null; - return new ConstantModel(fieldInfo, ((IConvertible)fieldInfo.GetValue(null)).ToInt64(null)); + return new ConstantModel(fieldInfo, ((IConvertible)fieldInfo.GetValue(null)!).ToInt64(null)); } } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/NameTable.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/NameTable.cs index d00b04b1e005cb..f7f43ad4683a5a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/NameTable.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/NameTable.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System.Xml; @@ -10,16 +11,16 @@ namespace System.Xml.Serialization internal class NameKey { - private readonly string _ns; - private readonly string _name; + private readonly string? _ns; + private readonly string? _name; - internal NameKey(string name, string ns) + internal NameKey(string? name, string? ns) { _name = name; _ns = ns; } - public override bool Equals(object other) + public override bool Equals(object? other) { if (!(other is NameKey)) return false; NameKey key = (NameKey)other; @@ -33,28 +34,28 @@ public override int GetHashCode() } internal interface INameScope { - object this[string name, string ns] { get; set; } + object? this[string? name, string? ns] { get; set; } } internal class NameTable : INameScope { - private readonly Dictionary _table = new Dictionary(); + private readonly Dictionary _table = new Dictionary(); internal void Add(XmlQualifiedName qname, object value) { Add(qname.Name, qname.Namespace, value); } - internal void Add(string name, string ns, object value) + internal void Add(string? name, string? ns, object value) { NameKey key = new NameKey(name, ns); _table.Add(key, value); } - internal object this[XmlQualifiedName qname] + internal object? this[XmlQualifiedName qname] { get { - object obj; + object? obj; return _table.TryGetValue(new NameKey(qname.Name, qname.Namespace), out obj) ? obj : null; } set @@ -62,11 +63,11 @@ internal object this[XmlQualifiedName qname] _table[new NameKey(qname.Name, qname.Namespace)] = value; } } - internal object this[string name, string ns] + internal object? this[string? name, string? ns] { get { - object obj; + object? obj; return _table.TryGetValue(new NameKey(name, ns), out obj) ? obj : null; } set @@ -74,11 +75,11 @@ internal object this[XmlQualifiedName qname] _table[new NameKey(name, ns)] = value; } } - object INameScope.this[string name, string ns] + object? INameScope.this[string? name, string? ns] { get { - object obj; + object? obj; _table.TryGetValue(new NameKey(name, ns), out obj); return obj; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/PrimitiveXmlSerializers.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/PrimitiveXmlSerializers.cs index 4198fe1c4077fe..4eb47af828865d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/PrimitiveXmlSerializers.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/PrimitiveXmlSerializers.cs @@ -1,13 +1,14 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; namespace System.Xml.Serialization { internal class XmlSerializationPrimitiveWriter : System.Xml.Serialization.XmlSerializationWriter { - internal void Write_string(object o) + internal void Write_string(object? o) { WriteStartDocument(); if (o == null) @@ -19,7 +20,7 @@ internal void Write_string(object o) WriteNullableStringLiteral(@"string", @"", ((string)o)); } - internal void Write_int(object o) + internal void Write_int(object? o) { WriteStartDocument(); if (o == null) @@ -30,7 +31,7 @@ internal void Write_int(object o) WriteElementStringRaw(@"int", @"", System.Xml.XmlConvert.ToString((int)((int)o))); } - internal void Write_boolean(object o) + internal void Write_boolean(object? o) { WriteStartDocument(); if (o == null) @@ -41,7 +42,7 @@ internal void Write_boolean(object o) WriteElementStringRaw(@"boolean", @"", System.Xml.XmlConvert.ToString((bool)((bool)o))); } - internal void Write_short(object o) + internal void Write_short(object? o) { WriteStartDocument(); if (o == null) @@ -52,7 +53,7 @@ internal void Write_short(object o) WriteElementStringRaw(@"short", @"", System.Xml.XmlConvert.ToString((short)((short)o))); } - internal void Write_long(object o) + internal void Write_long(object? o) { WriteStartDocument(); if (o == null) @@ -63,7 +64,7 @@ internal void Write_long(object o) WriteElementStringRaw(@"long", @"", System.Xml.XmlConvert.ToString((long)((long)o))); } - internal void Write_float(object o) + internal void Write_float(object? o) { WriteStartDocument(); if (o == null) @@ -74,7 +75,7 @@ internal void Write_float(object o) WriteElementStringRaw(@"float", @"", System.Xml.XmlConvert.ToString((float)((float)o))); } - internal void Write_double(object o) + internal void Write_double(object? o) { WriteStartDocument(); if (o == null) @@ -85,7 +86,7 @@ internal void Write_double(object o) WriteElementStringRaw(@"double", @"", System.Xml.XmlConvert.ToString((double)((double)o))); } - internal void Write_decimal(object o) + internal void Write_decimal(object? o) { WriteStartDocument(); if (o == null) @@ -98,7 +99,7 @@ internal void Write_decimal(object o) WriteElementStringRaw(@"decimal", @"", System.Xml.XmlConvert.ToString(d)); } - internal void Write_dateTime(object o) + internal void Write_dateTime(object? o) { WriteStartDocument(); if (o == null) @@ -109,7 +110,7 @@ internal void Write_dateTime(object o) WriteElementStringRaw(@"dateTime", @"", FromDateTime(((System.DateTime)o))); } - internal void Write_unsignedByte(object o) + internal void Write_unsignedByte(object? o) { WriteStartDocument(); if (o == null) @@ -120,7 +121,7 @@ internal void Write_unsignedByte(object o) WriteElementStringRaw(@"unsignedByte", @"", System.Xml.XmlConvert.ToString((byte)((byte)o))); } - internal void Write_byte(object o) + internal void Write_byte(object? o) { WriteStartDocument(); if (o == null) @@ -131,7 +132,7 @@ internal void Write_byte(object o) WriteElementStringRaw(@"byte", @"", System.Xml.XmlConvert.ToString((sbyte)((sbyte)o))); } - internal void Write_unsignedShort(object o) + internal void Write_unsignedShort(object? o) { WriteStartDocument(); if (o == null) @@ -142,7 +143,7 @@ internal void Write_unsignedShort(object o) WriteElementStringRaw(@"unsignedShort", @"", System.Xml.XmlConvert.ToString((ushort)((ushort)o))); } - internal void Write_unsignedInt(object o) + internal void Write_unsignedInt(object? o) { WriteStartDocument(); if (o == null) @@ -153,7 +154,7 @@ internal void Write_unsignedInt(object o) WriteElementStringRaw(@"unsignedInt", @"", System.Xml.XmlConvert.ToString((uint)((uint)o))); } - internal void Write_unsignedLong(object o) + internal void Write_unsignedLong(object? o) { WriteStartDocument(); if (o == null) @@ -164,7 +165,7 @@ internal void Write_unsignedLong(object o) WriteElementStringRaw(@"unsignedLong", @"", System.Xml.XmlConvert.ToString((ulong)((ulong)o))); } - internal void Write_base64Binary(object o) + internal void Write_base64Binary(object? o) { WriteStartDocument(); if (o == null) @@ -176,7 +177,7 @@ internal void Write_base64Binary(object o) WriteNullableStringLiteralRaw(@"base64Binary", @"", FromByteArrayBase64(((byte[])o))); } - internal void Write_guid(object o) + internal void Write_guid(object? o) { WriteStartDocument(); if (o == null) @@ -189,7 +190,7 @@ internal void Write_guid(object o) WriteElementStringRaw(@"guid", @"", System.Xml.XmlConvert.ToString(guid)); } - internal void Write_TimeSpan(object o) + internal void Write_TimeSpan(object? o) { WriteStartDocument(); if (o == null) @@ -201,7 +202,7 @@ internal void Write_TimeSpan(object o) WriteElementStringRaw(@"TimeSpan", @"", System.Xml.XmlConvert.ToString(timeSpan)); } - internal void Write_char(object o) + internal void Write_char(object? o) { WriteStartDocument(); if (o == null) @@ -212,7 +213,7 @@ internal void Write_char(object o) WriteElementString(@"char", @"", FromChar(((char)o))); } - internal void Write_QName(object o) + internal void Write_QName(object? o) { WriteStartDocument(); if (o == null) @@ -231,9 +232,9 @@ protected override void InitCallbacks() internal class XmlSerializationPrimitiveReader : System.Xml.Serialization.XmlSerializationReader { - internal object Read_string() + internal object? Read_string() { - object o = null; + object? o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { @@ -257,12 +258,12 @@ internal object Read_string() { UnknownNode(null); } - return (object)o; + return (object?)o; } - internal object Read_int() + internal object? Read_int() { - object o = null; + object? o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { @@ -281,12 +282,12 @@ internal object Read_int() { UnknownNode(null); } - return (object)o; + return (object?)o; } - internal object Read_boolean() + internal object? Read_boolean() { - object o = null; + object? o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { @@ -305,12 +306,12 @@ internal object Read_boolean() { UnknownNode(null); } - return (object)o; + return (object?)o; } - internal object Read_short() + internal object? Read_short() { - object o = null; + object? o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { @@ -329,12 +330,12 @@ internal object Read_short() { UnknownNode(null); } - return (object)o; + return (object?)o; } - internal object Read_long() + internal object? Read_long() { - object o = null; + object? o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { @@ -353,12 +354,12 @@ internal object Read_long() { UnknownNode(null); } - return (object)o; + return (object?)o; } - internal object Read_float() + internal object? Read_float() { - object o = null; + object? o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { @@ -377,12 +378,12 @@ internal object Read_float() { UnknownNode(null); } - return (object)o; + return (object?)o; } - internal object Read_double() + internal object? Read_double() { - object o = null; + object? o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { @@ -401,12 +402,12 @@ internal object Read_double() { UnknownNode(null); } - return (object)o; + return (object?)o; } - internal object Read_decimal() + internal object? Read_decimal() { - object o = null; + object? o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { @@ -425,12 +426,12 @@ internal object Read_decimal() { UnknownNode(null); } - return (object)o; + return (object?)o; } - internal object Read_dateTime() + internal object? Read_dateTime() { - object o = null; + object? o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { @@ -449,12 +450,12 @@ internal object Read_dateTime() { UnknownNode(null); } - return (object)o; + return (object?)o; } - internal object Read_unsignedByte() + internal object? Read_unsignedByte() { - object o = null; + object? o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { @@ -473,12 +474,12 @@ internal object Read_unsignedByte() { UnknownNode(null); } - return (object)o; + return (object?)o; } - internal object Read_byte() + internal object? Read_byte() { - object o = null; + object? o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { @@ -497,12 +498,12 @@ internal object Read_byte() { UnknownNode(null); } - return (object)o; + return (object?)o; } - internal object Read_unsignedShort() + internal object? Read_unsignedShort() { - object o = null; + object? o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { @@ -521,12 +522,12 @@ internal object Read_unsignedShort() { UnknownNode(null); } - return (object)o; + return (object?)o; } - internal object Read_unsignedInt() + internal object? Read_unsignedInt() { - object o = null; + object? o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { @@ -545,12 +546,12 @@ internal object Read_unsignedInt() { UnknownNode(null); } - return (object)o; + return (object?)o; } - internal object Read_unsignedLong() + internal object? Read_unsignedLong() { - object o = null; + object? o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { @@ -569,12 +570,12 @@ internal object Read_unsignedLong() { UnknownNode(null); } - return (object)o; + return (object?)o; } - internal object Read_base64Binary() + internal object? Read_base64Binary() { - object o = null; + object? o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { @@ -598,12 +599,12 @@ internal object Read_base64Binary() { UnknownNode(null); } - return (object)o; + return (object?)o; } - internal object Read_guid() + internal object? Read_guid() { - object o = null; + object? o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { @@ -622,12 +623,12 @@ internal object Read_guid() { UnknownNode(null); } - return (object)o; + return (object?)o; } - internal object Read_TimeSpan() + internal object? Read_TimeSpan() { - object o = null; + object? o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { @@ -652,12 +653,12 @@ internal object Read_TimeSpan() { UnknownNode(null); } - return (object)o; + return (object?)o; } - internal object Read_char() + internal object? Read_char() { - object o = null; + object? o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { @@ -676,12 +677,12 @@ internal object Read_char() { UnknownNode(null); } - return (object)o; + return (object?)o; } - internal object Read_QName() + internal object? Read_QName() { - object o = null; + object? o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { @@ -705,33 +706,33 @@ internal object Read_QName() { UnknownNode(null); } - return (object)o; + return (object?)o; } protected override void InitCallbacks() { } - private string _id4_boolean; - private string _id14_unsignedInt; - private string _id15_unsignedLong; - private string _id7_float; - private string _id10_dateTime; - private string _id6_long; - private string _id9_decimal; - private string _id8_double; - private string _id17_guid; - private string _id19_TimeSpan; - private string _id2_Item; - private string _id13_unsignedShort; - private string _id18_char; - private string _id3_int; - private string _id12_byte; - private string _id16_base64Binary; - private string _id11_unsignedByte; - private string _id5_short; - private string _id1_string; - private string _id1_QName; + private string _id4_boolean = null!; + private string _id14_unsignedInt = null!; + private string _id15_unsignedLong = null!; + private string _id7_float = null!; + private string _id10_dateTime = null!; + private string _id6_long = null!; + private string _id9_decimal = null!; + private string _id8_double = null!; + private string _id17_guid = null!; + private string _id19_TimeSpan = null!; + private string _id2_Item = null!; + private string _id13_unsignedShort = null!; + private string _id18_char = null!; + private string _id3_int = null!; + private string _id12_byte = null!; + private string _id16_base64Binary = null!; + private string _id11_unsignedByte = null!; + private string _id5_short = null!; + private string _id1_string = null!; + private string _id1_QName = null!; protected override void InitIDs() { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationReader.cs index 597c4fa9b2a503..908ea01deb8ae4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationReader.cs @@ -1,10 +1,12 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; using System.Linq.Expressions; using System.Reflection; using System.Xml.Extensions; @@ -12,7 +14,7 @@ namespace System.Xml.Serialization { - internal delegate void UnknownNodeAction(object o); + internal delegate void UnknownNodeAction(object? o); internal class ReflectionXmlSerializationReader : XmlSerializationReader { @@ -21,7 +23,7 @@ internal class ReflectionXmlSerializationReader : XmlSerializationReader private readonly XmlMapping _mapping; - public ReflectionXmlSerializationReader(XmlMapping mapping, XmlReader xmlReader, XmlDeserializationEvents events, string encodingStyle) + public ReflectionXmlSerializationReader(XmlMapping mapping, XmlReader xmlReader, XmlDeserializationEvents events, string? encodingStyle) { Init(xmlReader, events, encodingStyle, tempAssembly: null); _mapping = mapping; @@ -29,17 +31,17 @@ public ReflectionXmlSerializationReader(XmlMapping mapping, XmlReader xmlReader, protected override void InitCallbacks() { - TypeScope scope = _mapping.Scope; + TypeScope scope = _mapping.Scope!; foreach (TypeMapping mapping in scope.TypeMappings) { if (mapping.IsSoap && (mapping is StructMapping || mapping is EnumMapping || mapping is ArrayMapping || mapping is NullableMapping) && - !mapping.TypeDesc.IsRoot) + !mapping.TypeDesc!.IsRoot) { AddReadCallback( - mapping.TypeName, - mapping.Namespace, - mapping.TypeDesc.Type, + mapping.TypeName!, + mapping.Namespace!, + mapping.TypeDesc.Type!, CreateXmlSerializationReadCallback(mapping)); } } @@ -49,7 +51,7 @@ protected override void InitIDs() { } - public object ReadObject() + public object? ReadObject() { XmlMapping xmlMapping = _mapping; if (!xmlMapping.IsReadable) @@ -87,7 +89,7 @@ private object GenerateMembersElement(XmlMembersMapping xmlMembersMapping) private object GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping) { ElementAccessor element = xmlMembersMapping.Accessor; - MemberMapping[] mappings = ((MembersMapping)element.Mapping).Members; + MemberMapping[] mappings = ((MembersMapping)element.Mapping!).Members!; bool hasWrapperElement = ((MembersMapping)element.Mapping).HasWrapperElement; Reader.MoveToContent(); @@ -97,7 +99,7 @@ private object GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping if (hasWrapperElement) { string elementName = element.Name; - string elementNs = element.Form == XmlSchemaForm.Qualified ? element.Namespace : string.Empty; + string elementNs = element.Form == XmlSchemaForm.Qualified ? element.Namespace! : string.Empty; Reader.MoveToContent(); while (Reader.NodeType != XmlNodeType.EndElement && Reader.NodeType != XmlNodeType.None) { @@ -127,11 +129,11 @@ private object GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping return p; } - private bool GenerateLiteralMembersElementInternal(MemberMapping[] mappings, bool hasWrapperElement, object[] p) + private bool GenerateLiteralMembersElementInternal(MemberMapping[] mappings, bool hasWrapperElement, object?[] p) { - Member anyText = null; - Member anyElement = null; - Member anyAttribute = null; + Member? anyText = null; + Member? anyElement = null; + Member? anyAttribute = null; var membersList = new List(); var textOrArrayMembersList = new List(); @@ -141,7 +143,7 @@ private bool GenerateLiteralMembersElementInternal(MemberMapping[] mappings, boo { int index = i; MemberMapping mapping = mappings[index]; - Action source = (o) => p[index] = o; + Action source = (o) => p[index] = o; Member member = new Member(mapping); Member anyMember = new Member(mapping); @@ -198,7 +200,7 @@ private bool GenerateLiteralMembersElementInternal(MemberMapping[] mappings, boo if (!mapping.IsSequence) { - for (int j = 0; j < mapping.Elements.Length; j++) + for (int j = 0; j < mapping.Elements!.Length; j++) { if (mapping.Elements[j].Any && mapping.Elements[j].Name.Length == 0) { @@ -224,8 +226,8 @@ private bool GenerateLiteralMembersElementInternal(MemberMapping[] mappings, boo { membersList.Add(anyMember); } - else if (mapping.TypeDesc.IsArrayLike - && !(mapping.Elements.Length == 1 && mapping.Elements[0].Mapping is ArrayMapping)) + else if (mapping.TypeDesc!.IsArrayLike + && !(mapping.Elements!.Length == 1 && mapping.Elements[0].Mapping is ArrayMapping)) { anyMember.Collection = new CollectionMember(); anyMember.ArraySource = (item) => @@ -251,7 +253,7 @@ private bool GenerateLiteralMembersElementInternal(MemberMapping[] mappings, boo if (attributeMembersList.Count > 0) { Member[] attributeMembers = attributeMembersList.ToArray(); - object tempObject = null; + object? tempObject = null; WriteAttributes(attributeMembers, anyAttribute, UnknownNode, ref tempObject); Reader.MoveToElement(); } @@ -277,36 +279,36 @@ private bool GenerateLiteralMembersElementInternal(MemberMapping[] mappings, boo foreach (Member member in textOrArrayMembers) { - object value = null; - SetCollectionObjectWithCollectionMember(ref value, member.Collection, member.Mapping.TypeDesc.Type); - member.Source(value); + object? value = null; + SetCollectionObjectWithCollectionMember(ref value, member.Collection!, member.Mapping.TypeDesc!.Type!); + member.Source!(value); } if (anyAttribute != null) { - object value = null; - SetCollectionObjectWithCollectionMember(ref value, anyAttribute.Collection, anyAttribute.Mapping.TypeDesc.Type); - anyAttribute.ArraySource(value); + object? value = null; + SetCollectionObjectWithCollectionMember(ref value, anyAttribute.Collection!, anyAttribute.Mapping.TypeDesc!.Type!); + anyAttribute.ArraySource!(value); } return true; } - private void InitializeValueTypes(object[] p, MemberMapping[] mappings) + private void InitializeValueTypes(object?[] p, MemberMapping[] mappings) { for (int i = 0; i < mappings.Length; i++) { - if (!mappings[i].TypeDesc.IsValueType) + if (!mappings[i].TypeDesc!.IsValueType) continue; - if (mappings[i].TypeDesc.IsOptionalValue && mappings[i].TypeDesc.BaseTypeDesc.UseReflection) + if (mappings[i].TypeDesc!.IsOptionalValue && mappings[i].TypeDesc!.BaseTypeDesc!.UseReflection) { p[i] = null; } else { - p[i] = ReflectionCreateObject(mappings[i].TypeDesc.Type); + p[i] = ReflectionCreateObject(mappings[i].TypeDesc!.Type!); } } } @@ -314,14 +316,14 @@ private void InitializeValueTypes(object[] p, MemberMapping[] mappings) private object GenerateEncodedMembersElement(XmlMembersMapping xmlMembersMapping) { ElementAccessor element = xmlMembersMapping.Accessor; - var membersMapping = (MembersMapping)element.Mapping; - MemberMapping[] mappings = membersMapping.Members; + var membersMapping = (MembersMapping)element.Mapping!; + MemberMapping[] mappings = membersMapping.Members!; bool hasWrapperElement = membersMapping.HasWrapperElement; bool writeAccessors = membersMapping.WriteAccessors; Reader.MoveToContent(); - object[] p = new object[mappings.Length]; + object?[] p = new object[mappings.Length]; InitializeValueTypes(p, mappings); bool isEmptyWrapper = true; @@ -330,7 +332,7 @@ private object GenerateEncodedMembersElement(XmlMembersMapping xmlMembersMapping Reader.MoveToContent(); while (Reader.NodeType == XmlNodeType.Element) { - string root = Reader.GetAttribute("root", Soap.Encoding); + string? root = Reader.GetAttribute("root", Soap.Encoding); if (root == null || XmlConvert.ToBoolean(root)) break; @@ -341,7 +343,7 @@ private object GenerateEncodedMembersElement(XmlMembersMapping xmlMembersMapping if (membersMapping.ValidateRpcWrapperElement) { string name = element.Name; - string ns = element.Form == XmlSchemaForm.Qualified ? element.Namespace : string.Empty; + string? ns = element.Form == XmlSchemaForm.Qualified ? element.Namespace : string.Empty; if (!XmlNodeEqual(Reader, name, ns)) { throw CreateUnknownNodeException(); @@ -376,13 +378,13 @@ private object GenerateEncodedMembersElement(XmlMembersMapping xmlMembersMapping } - Fixup fixup = WriteMemberFixupBegin(members, p); + Fixup? fixup = WriteMemberFixupBegin(members, p); if (members.Length > 0 && members[0].Mapping.IsReturnValue) { IsReturnValue = true; } - List checkTypeHrefSource = null; + List? checkTypeHrefSource = null; if (!hasWrapperElement && !writeAccessors) { checkTypeHrefSource = new List(); @@ -426,7 +428,7 @@ private object GenerateEncodedMembersElement(XmlMembersMapping xmlMembersMapping { bool isReferenced = true; bool isObject = currentySource.IsObject; - object refObj = isObject ? currentySource.RefObject : GetTarget((string)currentySource.RefObject); + object? refObj = isObject ? currentySource.RefObject : GetTarget((string)currentySource.RefObject!); if (refObj == null) { continue; @@ -451,17 +453,17 @@ private object GenerateEncodedMembersElement(XmlMembersMapping xmlMembersMapping return p; } - private object GenerateTypeElement(XmlTypeMapping xmlTypeMapping) + private object? GenerateTypeElement(XmlTypeMapping xmlTypeMapping) { ElementAccessor element = xmlTypeMapping.Accessor; - TypeMapping mapping = element.Mapping; + TypeMapping mapping = element.Mapping!; Reader.MoveToContent(); var memberMapping = new MemberMapping(); memberMapping.TypeDesc = mapping.TypeDesc; memberMapping.Elements = new ElementAccessor[] { element }; - object o = null; + object? o = null; var holder = new ObjectHolder(); var member = new Member(memberMapping); member.Source = (value) => holder.Object = value; @@ -480,7 +482,7 @@ private object GenerateTypeElement(XmlTypeMapping xmlTypeMapping) return o; } - private void WriteMemberElements(Member[] expectedMembers, UnknownNodeAction elementElseAction, UnknownNodeAction elseAction, Member anyElement, Member anyText, Fixup fixup = null, List checkTypeHrefsSource = null) + private void WriteMemberElements(Member[] expectedMembers, UnknownNodeAction elementElseAction, UnknownNodeAction elseAction, Member? anyElement, Member? anyText, Fixup? fixup = null, List? checkTypeHrefsSource = null) { bool checkType = checkTypeHrefsSource != null; if (Reader.NodeType == XmlNodeType.Element) @@ -493,7 +495,7 @@ private void WriteMemberElements(Member[] expectedMembers, UnknownNodeAction ele return; } - WriteMemberElementsCheckType(checkTypeHrefsSource); + WriteMemberElementsCheckType(checkTypeHrefsSource!); } else { @@ -511,7 +513,7 @@ private void WriteMemberElements(Member[] expectedMembers, UnknownNodeAction ele private void WriteMemberElementsCheckType(List checkTypeHrefsSource) { - object RefElememnt = ReadReferencingElement(null, null, true, out string refElemId); + object? RefElememnt = ReadReferencingElement(null, null, true, out string? refElemId); var source = new CheckTypeSource(); if (refElemId != null) { @@ -532,7 +534,7 @@ private void ProcessUnknownNode(UnknownNodeAction action) action?.Invoke(null); } - private void WriteMembers(ref object o, Member[] members, UnknownNodeAction elementElseAction, UnknownNodeAction elseAction, Member anyElement, Member anyText) + private void WriteMembers(ref object? o, Member[] members, UnknownNodeAction elementElseAction, UnknownNodeAction elseAction, Member? anyElement, Member? anyText) { Reader.MoveToContent(); @@ -543,7 +545,7 @@ private void WriteMembers(ref object o, Member[] members, UnknownNodeAction elem } } - private void SetCollectionObjectWithCollectionMember(ref object collection, CollectionMember collectionMember, Type collectionType) + private void SetCollectionObjectWithCollectionMember([NotNull] ref object? collection, CollectionMember collectionMember, Type collectionType) { if (collectionType.IsArray) { @@ -554,7 +556,7 @@ private void SetCollectionObjectWithCollectionMember(ref object collection, Coll } else { - Type elementType = collectionType.GetElementType(); + Type elementType = collectionType.GetElementType()!; a = Array.CreateInstance(elementType, collectionMember.Count); } @@ -569,32 +571,32 @@ private void SetCollectionObjectWithCollectionMember(ref object collection, Coll { if (collection == null) { - collection = ReflectionCreateObject(collectionType); + collection = ReflectionCreateObject(collectionType)!; } AddObjectsIntoTargetCollection(collection, collectionMember, collectionType); } } - private static void AddObjectsIntoTargetCollection(object targetCollection, List sourceCollection, Type targetCollectionType) + private static void AddObjectsIntoTargetCollection(object targetCollection, List sourceCollection, Type targetCollectionType) { if (targetCollection is IList targetList) { - foreach (object item in sourceCollection) + foreach (object? item in sourceCollection) { targetList.Add(item); } } else { - MethodInfo addMethod = targetCollectionType.GetMethod("Add"); + MethodInfo? addMethod = targetCollectionType.GetMethod("Add"); if (addMethod == null) { throw new InvalidOperationException(SR.XmlInternalError); } - object[] arguments = new object[1]; - foreach (object item in sourceCollection) + object?[] arguments = new object?[1]; + foreach (object? item in sourceCollection) { arguments[0] = item; addMethod.Invoke(targetCollection, arguments); @@ -609,7 +611,7 @@ private static ReflectionXmlSerializationReaderHelper.SetMemberValueDelegate Get Debug.Assert(o != null, "Object o should not be null"); Debug.Assert(!string.IsNullOrEmpty(memberName), "memberName must have a value"); var typeMemberNameTuple = Tuple.Create(o.GetType(), memberName); - if (!s_setMemberValueDelegateCache.TryGetValue(typeMemberNameTuple, out ReflectionXmlSerializationReaderHelper.SetMemberValueDelegate result)) + if (!s_setMemberValueDelegateCache.TryGetValue(typeMemberNameTuple, out ReflectionXmlSerializationReaderHelper.SetMemberValueDelegate? result)) { MemberInfo memberInfo = ReflectionXmlSerializationHelper.GetMember(o.GetType(), memberName); Debug.Assert(memberInfo != null, "memberInfo could not be retrieved"); @@ -627,7 +629,7 @@ private static ReflectionXmlSerializationReaderHelper.SetMemberValueDelegate Get throw new InvalidOperationException(SR.XmlInternalError); } - MethodInfo getSetMemberValueDelegateWithTypeGenericMi = typeof(ReflectionXmlSerializationReaderHelper).GetMethod("GetSetMemberValueDelegateWithType", BindingFlags.Static | BindingFlags.Public); + MethodInfo getSetMemberValueDelegateWithTypeGenericMi = typeof(ReflectionXmlSerializationReaderHelper).GetMethod("GetSetMemberValueDelegateWithType", BindingFlags.Static | BindingFlags.Public)!; MethodInfo getSetMemberValueDelegateWithTypeMi = getSetMemberValueDelegateWithTypeGenericMi.MakeGenericMethod(o.GetType(), memberType); var getSetMemberValueDelegateWithType = (Func)getSetMemberValueDelegateWithTypeMi.CreateDelegate(typeof(Func)); result = getSetMemberValueDelegateWithType(memberInfo); @@ -637,7 +639,7 @@ private static ReflectionXmlSerializationReaderHelper.SetMemberValueDelegate Get return result; } - private object GetMemberValue(object o, MemberInfo memberInfo) + private object? GetMemberValue(object o, MemberInfo memberInfo) { if (memberInfo is PropertyInfo propertyInfo) { @@ -653,17 +655,17 @@ private object GetMemberValue(object o, MemberInfo memberInfo) private bool WriteMemberText(Member anyText) { - object value; + object? value; MemberMapping anyTextMapping = anyText.Mapping; if ((Reader.NodeType == XmlNodeType.Text || Reader.NodeType == XmlNodeType.CDATA || Reader.NodeType == XmlNodeType.Whitespace || Reader.NodeType == XmlNodeType.SignificantWhitespace)) { - TextAccessor text = anyTextMapping.Text; + TextAccessor text = anyTextMapping.Text!; if (text.Mapping is SpecialMapping special) { - if (special.TypeDesc.Kind == TypeKind.Node) + if (special.TypeDesc!.Kind == TypeKind.Node) { value = Document.CreateTextNode(Reader.ReadString()); } @@ -674,9 +676,9 @@ private bool WriteMemberText(Member anyText) } else { - if (anyTextMapping.TypeDesc.IsArrayLike) + if (anyTextMapping.TypeDesc!.IsArrayLike) { - if (text.Mapping.TypeDesc.CollapseWhitespace) + if (text.Mapping!.TypeDesc!.CollapseWhitespace) { value = CollapseWhitespace(Reader.ReadString()); } @@ -687,7 +689,7 @@ private bool WriteMemberText(Member anyText) } else { - if (text.Mapping.TypeDesc == StringTypeDesc || text.Mapping.TypeDesc.FormatterName == "String") + if (text.Mapping!.TypeDesc == StringTypeDesc || text.Mapping.TypeDesc!.FormatterName == "String") { value = ReadString(null, text.Mapping.TypeDesc.CollapseWhitespace); } @@ -698,7 +700,7 @@ private bool WriteMemberText(Member anyText) } } - anyText.Source(value); + anyText.Source!(value); return true; } @@ -713,7 +715,7 @@ private bool IsSequence(Member[] members) return false; } - private void WriteMemberElementsIf(Member[] expectedMembers, Member anyElementMember, UnknownNodeAction elementElseAction, Fixup fixup = null, CheckTypeSource checkTypeSource = null) + private void WriteMemberElementsIf(Member[] expectedMembers, Member? anyElementMember, UnknownNodeAction elementElseAction, Fixup? fixup = null, CheckTypeSource? checkTypeSource = null) { bool checkType = checkTypeSource != null; bool isSequence = IsSequence(expectedMembers); @@ -724,8 +726,8 @@ private void WriteMemberElementsIf(Member[] expectedMembers, Member anyElementMe // But potentially we can do some optimization for types that have ordered properties. } - ElementAccessor e = null; - Member member = null; + ElementAccessor? e = null; + Member? member = null; bool foundElement = false; int elementIndex = -1; foreach (Member m in expectedMembers) @@ -737,24 +739,24 @@ private void WriteMemberElementsIf(Member[] expectedMembers, Member anyElementMe if (isSequence && (m.Mapping.IsText || m.Mapping.IsAttribute)) continue; - for (int i = 0; i < m.Mapping.Elements.Length; i++) + for (int i = 0; i < m.Mapping.Elements!.Length; i++) { ElementAccessor ele = m.Mapping.Elements[i]; - string ns = ele.Form == XmlSchemaForm.Qualified ? ele.Namespace : string.Empty; + string? ns = ele.Form == XmlSchemaForm.Qualified ? ele.Namespace : string.Empty; if (checkType) { Type elementType; if (ele.Mapping is NullableMapping nullableMapping) { - TypeDesc td = nullableMapping.BaseMapping.TypeDesc; - elementType = td.Type; + TypeDesc td = nullableMapping.BaseMapping!.TypeDesc!; + elementType = td.Type!; } else { - elementType = ele.Mapping.TypeDesc.Type; + elementType = ele.Mapping!.TypeDesc!.Type!; } - if (elementType.IsAssignableFrom(checkTypeSource.Type)) + if (elementType.IsAssignableFrom(checkTypeSource!.Type)) { foundElement = true; } @@ -781,17 +783,17 @@ private void WriteMemberElementsIf(Member[] expectedMembers, Member anyElementMe { if (checkType) { - member.Source(checkTypeSource.RefObject); + member!.Source!(checkTypeSource!.RefObject!); if (member.FixupIndex >= 0) { - fixup.Ids[member.FixupIndex] = checkTypeSource.Id; + fixup!.Ids![member.FixupIndex] = checkTypeSource.Id; } } else { - string ns = e.Form == XmlSchemaForm.Qualified ? e.Namespace : string.Empty; - bool isList = member.Mapping.TypeDesc.IsArrayLike && !member.Mapping.TypeDesc.IsArray; + string? ns = e!.Form == XmlSchemaForm.Qualified ? e.Namespace : string.Empty; + bool isList = member!.Mapping.TypeDesc!.IsArrayLike && !member.Mapping.TypeDesc.IsArray; WriteElement(e, member.Mapping.CheckSpecified == SpecifiedAccessor.ReadWrite, isList && member.Mapping.TypeDesc.IsNullable, member.Mapping.ReadOnly, ns, member.FixupIndex, elementIndex, fixup, member); } } @@ -801,13 +803,13 @@ private void WriteMemberElementsIf(Member[] expectedMembers, Member anyElementMe { MemberMapping anyElement = anyElementMember.Mapping; member = anyElementMember; - ElementAccessor[] elements = anyElement.Elements; + ElementAccessor[] elements = anyElement.Elements!; for (int i = 0; i < elements.Length; i++) { ElementAccessor element = elements[i]; if (element.Any && element.Name.Length == 0) { - string ns = element.Form == XmlSchemaForm.Qualified ? element.Namespace : string.Empty; + string? ns = element.Form == XmlSchemaForm.Qualified ? element.Namespace : string.Empty; WriteElement(element, anyElement.CheckSpecified == SpecifiedAccessor.ReadWrite, false, false, ns, fixup: fixup, member: member); break; } @@ -821,9 +823,9 @@ private void WriteMemberElementsIf(Member[] expectedMembers, Member anyElementMe } } - private object WriteElement(ElementAccessor element, bool checkSpecified, bool checkForNull, bool readOnly, string defaultNamespace, int fixupIndex = -1, int elementIndex = -1, Fixup fixup = null, Member member = null) + private object? WriteElement(ElementAccessor element, bool checkSpecified, bool checkForNull, bool readOnly, string? defaultNamespace, int fixupIndex = -1, int elementIndex = -1, Fixup? fixup = null, Member? member = null) { - object value = null; + object? value = null; if (element.Mapping is ArrayMapping arrayMapping) { value = WriteArray(arrayMapping, readOnly, element.IsNullable, defaultNamespace, fixupIndex, fixup, member); @@ -832,25 +834,25 @@ private object WriteElement(ElementAccessor element, bool checkSpecified, bool c { value = WriteNullableMethod(nullableMapping, true, defaultNamespace); } - else if (!element.Mapping.IsSoap && (element.Mapping is PrimitiveMapping)) + else if (!element.Mapping!.IsSoap && (element.Mapping is PrimitiveMapping)) { if (element.IsNullable && ReadNull()) { - if (element.Mapping.TypeDesc.IsValueType) + if (element.Mapping.TypeDesc!.IsValueType) { - value = ReflectionCreateObject(element.Mapping.TypeDesc.Type); + value = ReflectionCreateObject(element.Mapping.TypeDesc.Type!); } else { value = null; } } - else if ((element.Default != null && element.Default != DBNull.Value && element.Mapping.TypeDesc.IsValueType) + else if ((element.Default != null && element.Default != DBNull.Value && element.Mapping.TypeDesc!.IsValueType) && (Reader.IsEmptyElement)) { Reader.Skip(); } - else if (element.Mapping.TypeDesc.Type == typeof(TimeSpan) && Reader.IsEmptyElement) + else if (element.Mapping.TypeDesc!.Type == typeof(TimeSpan) && Reader.IsEmptyElement) { Reader.Skip(); value = default(TimeSpan); @@ -884,11 +886,11 @@ private object WriteElement(ElementAccessor element, bool checkSpecified, bool c TypeMapping mapping = element.Mapping; if (mapping.IsSoap) { - object rre = fixupIndex >= 0 ? - ReadReferencingElement(mapping.TypeName, mapping.Namespace, out fixup.Ids[fixupIndex]) + object? rre = fixupIndex >= 0 ? + ReadReferencingElement(mapping.TypeName, mapping.Namespace, out fixup!.Ids![fixupIndex]) : ReadReferencedElement(mapping.TypeName, mapping.Namespace); - if (!mapping.TypeDesc.IsValueType || rre != null) + if (!mapping.TypeDesc!.IsValueType || rre != null) { value = rre; Referenced(value); @@ -901,13 +903,13 @@ private object WriteElement(ElementAccessor element, bool checkSpecified, bool c throw new InvalidOperationException(SR.XmlInternalError); } - member.Source(value); + member.Source!(value!); return value; } } else { - if (checkForNull && (member.Source == null && member.ArraySource == null)) + if (checkForNull && (member!.Source == null && member.ArraySource == null)) { Reader.Skip(); } @@ -915,7 +917,7 @@ private object WriteElement(ElementAccessor element, bool checkSpecified, bool c { value = WriteStructMethod( mapping: (StructMapping)mapping, - isNullable: mapping.TypeDesc.IsNullable && element.IsNullable, + isNullable: mapping.TypeDesc!.IsNullable && element.IsNullable, checkType: true, defaultNamespace: defaultNamespace ); @@ -924,7 +926,7 @@ private object WriteElement(ElementAccessor element, bool checkSpecified, bool c } else if (element.Mapping is SpecialMapping specialMapping) { - switch (specialMapping.TypeDesc.Kind) + switch (specialMapping.TypeDesc!.Kind) { case TypeKind.Node: bool isDoc = specialMapping.TypeDesc.FullName == typeof(XmlDocument).FullName; @@ -944,8 +946,8 @@ private object WriteElement(ElementAccessor element, bool checkSpecified, bool c bool flag = true; if (sm.DerivedMappings != null) { - XmlQualifiedName tser = GetXsiType(); - if (tser == null || QNameEqual(tser, sm.XsiType.Name, sm.XsiType.Namespace, defaultNamespace)) + XmlQualifiedName? tser = GetXsiType(); + if (tser == null || QNameEqual(tser, sm.XsiType!.Name, sm.XsiType.Namespace, defaultNamespace)) { } else @@ -957,7 +959,7 @@ private object WriteElement(ElementAccessor element, bool checkSpecified, bool c if (flag) { bool isWrappedAny = !element.Any && IsWildcard(sm); - value = ReadSerializable((IXmlSerializable)ReflectionCreateObject(sm.TypeDesc.Type), isWrappedAny); + value = ReadSerializable((IXmlSerializable)ReflectionCreateObject(sm.TypeDesc!.Type!)!, isWrappedAny); } if (sm.DerivedMappings != null) @@ -982,11 +984,11 @@ private object WriteElement(ElementAccessor element, bool checkSpecified, bool c if (member?.ArraySource != null) { - member?.ArraySource(value); + member?.ArraySource(value!); } else { - member?.Source?.Invoke(value); + member?.Source?.Invoke(value!); member?.CheckSpecifiedSource?.Invoke(true); } @@ -997,7 +999,7 @@ private XmlSerializationReadCallback CreateXmlSerializationReadCallback(TypeMapp { if (mapping is StructMapping structMapping) { - return () => WriteStructMethod(structMapping, mapping.TypeDesc.IsNullable, true, defaultNamespace: null); + return () => WriteStructMethod(structMapping, mapping.TypeDesc!.IsNullable, true, defaultNamespace: null); } else if (mapping is EnumMapping enumMapping) { @@ -1011,11 +1013,11 @@ private XmlSerializationReadCallback CreateXmlSerializationReadCallback(TypeMapp return DummyReadArrayMethod; } - private static void NoopAction(object o) + private static void NoopAction(object? o) { } - private object DummyReadArrayMethod() + private object? DummyReadArrayMethod() { UnknownNode(null); return null; @@ -1046,30 +1048,30 @@ private static bool IsWildcard(SpecialMapping mapping) if (mapping is SerializableMapping serializableMapping) return serializableMapping.IsAny; - return mapping.TypeDesc.CanBeElementValue; + return mapping.TypeDesc!.CanBeElementValue; } - private object WriteArray(ArrayMapping arrayMapping, bool readOnly, bool isNullable, string defaultNamespace, int fixupIndex = -1, Fixup fixup = null, Member member = null) + private object? WriteArray(ArrayMapping arrayMapping, bool readOnly, bool isNullable, string? defaultNamespace, int fixupIndex = -1, Fixup? fixup = null, Member? member = null) { - object o = null; + object? o = null; if (arrayMapping.IsSoap) { - object rre; + object? rre; if (fixupIndex >= 0) { - rre = ReadReferencingElement(arrayMapping.TypeName, arrayMapping.Namespace, out fixup.Ids[fixupIndex]); + rre = ReadReferencingElement(arrayMapping.TypeName, arrayMapping.Namespace, out fixup!.Ids![fixupIndex]); } else { rre = ReadReferencedElement(arrayMapping.TypeName, arrayMapping.Namespace); } - TypeDesc td = arrayMapping.TypeDesc; + TypeDesc td = arrayMapping.TypeDesc!; if (rre != null) { if (td.IsEnumerable || td.IsCollection) { - WriteAddCollectionFixup(member.GetSource, member.Source, rre, td, readOnly); + WriteAddCollectionFixup(member!.GetSource!, member.Source!, rre, td, readOnly); // member.Source has been set at this point. // Setting the source to no-op to avoid setting the @@ -1083,7 +1085,7 @@ private object WriteArray(ArrayMapping arrayMapping, bool readOnly, bool isNulla throw new InvalidOperationException(SR.XmlInternalError); } - member.Source(rre); + member.Source!(rre); } } @@ -1100,8 +1102,8 @@ private object WriteArray(ArrayMapping arrayMapping, bool readOnly, bool isNulla ReadOnly = readOnly }; - Type collectionType = memberMapping.TypeDesc.Type; - o = ReflectionCreateObject(memberMapping.TypeDesc.Type); + Type collectionType = memberMapping.TypeDesc!.Type!; + o = ReflectionCreateObject(memberMapping.TypeDesc.Type!); if (memberMapping.ChoiceIdentifier != null) { @@ -1150,7 +1152,7 @@ private object WritePrimitive(TypeMapping mapping, Func readFunc { return readFunc(funcState); } - else if (mapping.TypeDesc.FormatterName == "String") + else if (mapping.TypeDesc!.FormatterName == "String") { if (mapping.TypeDesc.CollapseWhitespace) { @@ -1190,18 +1192,18 @@ private object WritePrimitive(TypeMapping mapping, Func readFunc else { string methodName = "To" + mapping.TypeDesc.FormatterName; - MethodInfo method = typeof(XmlSerializationReader).GetMethod(methodName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, new Type[] { typeof(string) }); + MethodInfo? method = typeof(XmlSerializationReader).GetMethod(methodName, BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, new Type[] { typeof(string) }); if (method == null) { throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, $"unknown FormatterName: {mapping.TypeDesc.FormatterName}")); } - return method.Invoke(this, new object[] { readFunc(funcState) }); + return method.Invoke(this, new object[] { readFunc(funcState) })!; } } } - private object WriteStructMethod(StructMapping mapping, bool isNullable, bool checkType, string defaultNamespace) + private object? WriteStructMethod(StructMapping mapping, bool isNullable, bool checkType, string? defaultNamespace) { if (mapping.IsSoap) return WriteEncodedStructMethod(mapping); @@ -1209,15 +1211,15 @@ private object WriteStructMethod(StructMapping mapping, bool isNullable, bool ch return WriteLiteralStructMethod(mapping, isNullable, checkType, defaultNamespace); } - private object WriteNullableMethod(NullableMapping nullableMapping, bool checkType, string defaultNamespace) + private object? WriteNullableMethod(NullableMapping nullableMapping, bool checkType, string? defaultNamespace) { - object o = Activator.CreateInstance(nullableMapping.TypeDesc.Type); + object? o = Activator.CreateInstance(nullableMapping.TypeDesc!.Type!); if (!ReadNull()) { ElementAccessor element = new ElementAccessor(); element.Mapping = nullableMapping.BaseMapping; element.Any = false; - element.IsNullable = nullableMapping.BaseMapping.TypeDesc.IsNullable; + element.IsNullable = nullableMapping.BaseMapping!.TypeDesc!.IsNullable; o = WriteElement(element, false, false, false, defaultNamespace); } @@ -1242,27 +1244,27 @@ private object WriteEnumMethod(EnumMapping mapping, string source) { if (mapping.IsFlags) { - Hashtable table = WriteHashtable(mapping, mapping.TypeDesc.Name); - return Enum.ToObject(mapping.TypeDesc.Type, ToEnum(source, table, mapping.TypeDesc.Name)); + Hashtable table = WriteHashtable(mapping, mapping.TypeDesc!.Name); + return Enum.ToObject(mapping.TypeDesc.Type!, ToEnum(source, table, mapping.TypeDesc.Name)); } else { - foreach (ConstantMapping c in mapping.Constants) + foreach (ConstantMapping c in mapping.Constants!) { if (string.Equals(c.XmlName, source)) { - return Enum.Parse(mapping.TypeDesc.Type, c.Name); + return Enum.Parse(mapping.TypeDesc!.Type!, c.Name); } } - throw CreateUnknownConstantException(source, mapping.TypeDesc.Type); + throw CreateUnknownConstantException(source, mapping.TypeDesc!.Type!); } } private Hashtable WriteHashtable(EnumMapping mapping, string name) { var h = new Hashtable(); - ConstantMapping[] constants = mapping.Constants; + ConstantMapping[] constants = mapping.Constants!; for (int i = 0; i < constants.Length; i++) { h.Add(constants[i].XmlName, constants[i].Value); @@ -1271,16 +1273,16 @@ private Hashtable WriteHashtable(EnumMapping mapping, string name) return h; } - private object ReflectionCreateObject(Type type) + private object? ReflectionCreateObject(Type type) { - object obj; + object? obj; if (type.IsArray) { obj = Activator.CreateInstance(type, 32); } else { - ConstructorInfo ci = GetDefaultConstructor(type); + ConstructorInfo? ci = GetDefaultConstructor(type); if (ci != null) { obj = ci.Invoke(Array.Empty()); @@ -1294,16 +1296,16 @@ private object ReflectionCreateObject(Type type) return obj; } - private ConstructorInfo GetDefaultConstructor(Type type) + private ConstructorInfo? GetDefaultConstructor(Type type) { if (type.IsValueType) return null; - ConstructorInfo ctor = FindDefaultConstructor(type.GetTypeInfo()); + ConstructorInfo? ctor = FindDefaultConstructor(type.GetTypeInfo()); return ctor; } - private static ConstructorInfo FindDefaultConstructor(TypeInfo ti) + private static ConstructorInfo? FindDefaultConstructor(TypeInfo ti) { foreach (ConstructorInfo ci in ti.DeclaredConstructors) { @@ -1316,12 +1318,12 @@ private static ConstructorInfo FindDefaultConstructor(TypeInfo ti) return null; } - private object WriteEncodedStructMethod(StructMapping structMapping) + private object? WriteEncodedStructMethod(StructMapping structMapping) { - if (structMapping.TypeDesc.IsRoot) + if (structMapping.TypeDesc!.IsRoot) return null; - Member[] members = null; + Member[]? members = null; if (structMapping.TypeDesc.IsAbstract) { @@ -1329,7 +1331,7 @@ private object WriteEncodedStructMethod(StructMapping structMapping) } else { - object o = ReflectionCreateObject(structMapping.TypeDesc.Type); + object? o = ReflectionCreateObject(structMapping.TypeDesc.Type!); MemberMapping[] mappings = TypeScope.GetSettableMembers(structMapping); members = new Member[mappings.Length]; @@ -1338,14 +1340,14 @@ private object WriteEncodedStructMethod(StructMapping structMapping) MemberMapping mapping = mappings[i]; var member = new Member(mapping); - TypeDesc td = member.Mapping.TypeDesc; + TypeDesc td = member.Mapping.TypeDesc!; if (td.IsCollection || td.IsEnumerable) { - member.Source = (value) => WriteAddCollectionFixup(o, member, value); + member.Source = (value) => WriteAddCollectionFixup(o!, member, value!); } else if (!member.Mapping.ReadOnly) { - var setterDelegate = GetSetMemberValueDelegate(o, member.Mapping.MemberInfo.Name); + var setterDelegate = GetSetMemberValueDelegate(o!, member.Mapping.MemberInfo!.Name); member.Source = (value) => setterDelegate(o, value); } else @@ -1356,7 +1358,7 @@ private object WriteEncodedStructMethod(StructMapping structMapping) members[i] = member; } - Fixup fixup = WriteMemberFixupBegin(members, o); + Fixup? fixup = WriteMemberFixupBegin(members, o); UnknownNodeAction unknownNodeAction = (_) => UnknownNode(o); WriteAttributes(members, null, unknownNodeAction, ref o); Reader.MoveToElement(); @@ -1379,15 +1381,15 @@ private object WriteEncodedStructMethod(StructMapping structMapping) } } - private Fixup WriteMemberFixupBegin(Member[] members, object o) + private Fixup? WriteMemberFixupBegin(Member[] members, object? o) { int fixupCount = 0; foreach (Member member in members) { - if (member.Mapping.Elements.Length == 0) + if (member.Mapping.Elements!.Length == 0) continue; - TypeMapping mapping = member.Mapping.Elements[0].Mapping; + TypeMapping? mapping = member.Mapping.Elements[0].Mapping; if (mapping is StructMapping || mapping is ArrayMapping || mapping is PrimitiveMapping || mapping is NullableMapping) { member.MultiRef = true; @@ -1395,7 +1397,7 @@ private Fixup WriteMemberFixupBegin(Member[] members, object o) } } - Fixup fixup; + Fixup? fixup; if (fixupCount > 0) { fixup = new Fixup(o, CreateWriteFixupMethod(members), fixupCount); @@ -1414,7 +1416,7 @@ private XmlSerializationFixupCallback CreateWriteFixupMethod(Member[] members) return (fixupObject) => { var fixup = (Fixup)fixupObject; - string[] ids = fixup.Ids; + string[] ids = fixup.Ids!; foreach (Member member in members) { if (member.MultiRef) @@ -1423,7 +1425,7 @@ private XmlSerializationFixupCallback CreateWriteFixupMethod(Member[] members) if (ids[fixupIndex] != null) { var memberValue = GetTarget(ids[fixupIndex]); - member.Source(memberValue); + member.Source!(memberValue); } } } @@ -1432,17 +1434,17 @@ private XmlSerializationFixupCallback CreateWriteFixupMethod(Member[] members) private void WriteAddCollectionFixup(object o, Member member, object memberValue) { - TypeDesc typeDesc = member.Mapping.TypeDesc; + TypeDesc typeDesc = member.Mapping.TypeDesc!; bool readOnly = member.Mapping.ReadOnly; - Func getSource = () => GetMemberValue(o, member.Mapping.MemberInfo); - var setterDelegate = GetSetMemberValueDelegate(o, member.Mapping.MemberInfo.Name); - Action setSource = (value) => setterDelegate(o, value); + Func getSource = () => GetMemberValue(o, member.Mapping.MemberInfo!); + var setterDelegate = GetSetMemberValueDelegate(o, member.Mapping.MemberInfo!.Name); + Action setSource = (value) => setterDelegate(o, value); WriteAddCollectionFixup(getSource, setSource, memberValue, typeDesc, readOnly); } - private object WriteAddCollectionFixup(Func getSource, Action setSource, object memberValue, TypeDesc typeDesc, bool readOnly) + private object? WriteAddCollectionFixup(Func getSource, Action setSource, object memberValue, TypeDesc typeDesc, bool readOnly) { - object memberSource = getSource(); + object? memberSource = getSource(); if (memberSource == null) { if (readOnly) @@ -1450,13 +1452,13 @@ private object WriteAddCollectionFixup(Func getSource, Action se throw CreateReadOnlyCollectionException(typeDesc.CSharpName); } - memberSource = ReflectionCreateObject(typeDesc.Type); + memberSource = ReflectionCreateObject(typeDesc.Type!); setSource(memberSource); } var collectionFixup = new CollectionFixup( memberSource, - new XmlSerializationCollectionFixupCallback(GetCreateCollectionOfObjectsCallback(typeDesc.Type)), + new XmlSerializationCollectionFixupCallback(GetCreateCollectionOfObjectsCallback(typeDesc.Type!)), memberValue); AddFixup(collectionFixup); @@ -1473,7 +1475,7 @@ private XmlSerializationCollectionFixupCallback GetCreateCollectionOfObjectsCall if (collection == null) return; - var listOfItems = new List(); + var listOfItems = new List(); if (collectionItems is IEnumerable enumerableItems) { foreach (var item in enumerableItems) @@ -1490,9 +1492,9 @@ private XmlSerializationCollectionFixupCallback GetCreateCollectionOfObjectsCall }; } - private object WriteLiteralStructMethod(StructMapping structMapping, bool isNullable, bool checkType, string defaultNamespace) + private object? WriteLiteralStructMethod(StructMapping structMapping, bool isNullable, bool checkType, string? defaultNamespace) { - XmlQualifiedName xsiType = checkType ? GetXsiType() : null; + XmlQualifiedName? xsiType = checkType ? GetXsiType() : null; bool isNull = false; if (isNullable) { @@ -1501,7 +1503,7 @@ private object WriteLiteralStructMethod(StructMapping structMapping, bool isNull if (checkType) { - if (structMapping.TypeDesc.IsRoot && isNull) + if (structMapping.TypeDesc!.IsRoot && isNull) { if (xsiType != null) { @@ -1511,7 +1513,7 @@ private object WriteLiteralStructMethod(StructMapping structMapping, bool isNull { if (structMapping.TypeDesc.IsValueType) { - return ReflectionCreateObject(structMapping.TypeDesc.Type); + return ReflectionCreateObject(structMapping.TypeDesc.Type!); } else { @@ -1520,7 +1522,7 @@ private object WriteLiteralStructMethod(StructMapping structMapping, bool isNull } } - object o = null; + object? o = null; if (xsiType == null || (!structMapping.TypeDesc.IsRoot && QNameEqual(xsiType, structMapping.TypeName, structMapping.Namespace, defaultNamespace))) { if (structMapping.TypeDesc.IsRoot) @@ -1545,7 +1547,7 @@ private object WriteLiteralStructMethod(StructMapping structMapping, bool isNull } } - if (structMapping.TypeDesc.IsNullable && isNull) + if (structMapping.TypeDesc!.IsNullable && isNull) { return null; } @@ -1562,14 +1564,14 @@ private object WriteLiteralStructMethod(StructMapping structMapping, bool isNull throw new NotImplementedException(nameof(XmlSchemaObject)); } - object o = ReflectionCreateObject(structMapping.TypeDesc.Type); + object? o = ReflectionCreateObject(structMapping.TypeDesc.Type!)!; MemberMapping[] mappings = TypeScope.GetSettableMembers(structMapping); - MemberMapping anyText = null; - MemberMapping anyElement = null; - Member anyAttribute = null; - Member anyElementMember = null; - Member anyTextMember = null; + MemberMapping? anyText = null; + MemberMapping? anyElement = null; + Member? anyAttribute = null; + Member? anyElementMember = null; + Member? anyTextMember = null; bool isSequence = structMapping.HasExplicitSequence(); @@ -1595,7 +1597,7 @@ private object WriteLiteralStructMethod(StructMapping structMapping, bool isNull if (mapping.Attribute != null) { - member.Source = (value) => SetOrAddValueToMember(o, value, member.Mapping.MemberInfo); + member.Source = (value) => SetOrAddValueToMember(o!, value!, member.Mapping.MemberInfo!); if (mapping.Attribute.Any) { anyAttribute = member; @@ -1605,7 +1607,7 @@ private object WriteLiteralStructMethod(StructMapping structMapping, bool isNull if (!isSequence) { // find anyElement if present. - for (int j = 0; j < mapping.Elements.Length; j++) + for (int j = 0; j < mapping.Elements!.Length; j++) { if (mapping.Elements[j].Any && (mapping.Elements[j].Name == null || mapping.Elements[j].Name.Length == 0)) { @@ -1616,13 +1618,13 @@ private object WriteLiteralStructMethod(StructMapping structMapping, bool isNull } else if (mapping.IsParticle && !mapping.IsSequence) { - structMapping.FindDeclaringMapping(mapping, out StructMapping declaringMapping, structMapping.TypeName); - throw new InvalidOperationException(SR.Format(SR.XmlSequenceHierarchy, structMapping.TypeDesc.FullName, mapping.Name, declaringMapping.TypeDesc.FullName, "Order")); + structMapping.FindDeclaringMapping(mapping, out StructMapping? declaringMapping, structMapping.TypeName!); + throw new InvalidOperationException(SR.Format(SR.XmlSequenceHierarchy, structMapping.TypeDesc.FullName, mapping.Name, declaringMapping!.TypeDesc!.FullName, "Order")); } - if (mapping.TypeDesc.IsArrayLike) + if (mapping.TypeDesc!.IsArrayLike) { - if (member.Source == null && mapping.TypeDesc.IsArrayLike && !(mapping.Elements.Length == 1 && mapping.Elements[0].Mapping is ArrayMapping)) + if (member.Source == null && mapping.TypeDesc.IsArrayLike && !(mapping.Elements!.Length == 1 && mapping.Elements[0].Mapping is ArrayMapping)) { member.Source = (item) => { @@ -1649,7 +1651,7 @@ private object WriteLiteralStructMethod(StructMapping structMapping, bool isNull { member.Source = (value) => { - var getOnlyList = (IList)pi.GetValue(o); + var getOnlyList = (IList)pi.GetValue(o)!; if (value is IList valueList) { foreach (var v in valueList) @@ -1668,7 +1670,7 @@ private object WriteLiteralStructMethod(StructMapping structMapping, bool isNull if (member.Mapping.Xmlns != null) { var xmlSerializerNamespaces = new XmlSerializerNamespaces(); - var setMemberValue = GetSetMemberValueDelegate(o, member.Mapping.Name); + var setMemberValue = GetSetMemberValueDelegate(o!, member.Mapping.Name); setMemberValue(o, xmlSerializerNamespaces); member.XmlnsSource = (ns, name) => { @@ -1677,7 +1679,7 @@ private object WriteLiteralStructMethod(StructMapping structMapping, bool isNull } else { - var setterDelegate = GetSetMemberValueDelegate(o, member.Mapping.Name); + var setterDelegate = GetSetMemberValueDelegate(o!, member.Mapping.Name); member.Source = (value) => setterDelegate(o, value); } } @@ -1688,7 +1690,7 @@ private object WriteLiteralStructMethod(StructMapping structMapping, bool isNull member.CheckSpecifiedSource = (_) => { string specifiedMemberName = member.Mapping.Name + "Specified"; - MethodInfo specifiedMethodInfo = o.GetType().GetMethod("set_" + specifiedMemberName); + MethodInfo? specifiedMethodInfo = o!.GetType().GetMethod("set_" + specifiedMemberName); if (specifiedMethodInfo != null) { specifiedMethodInfo.Invoke(o, new object[] { true }); @@ -1696,18 +1698,18 @@ private object WriteLiteralStructMethod(StructMapping structMapping, bool isNull }; } - ChoiceIdentifierAccessor choice = mapping.ChoiceIdentifier; + ChoiceIdentifierAccessor? choice = mapping.ChoiceIdentifier; if (choice != null && o != null) { member.ChoiceSource = (elementNameObject) => { - string elementName = elementNameObject as string; - foreach (var name in choice.MemberIds) + string? elementName = elementNameObject as string; + foreach (var name in choice.MemberIds!) { if (name == elementName) { - object choiceValue = Enum.Parse(choice.Mapping.TypeDesc.Type, name); - SetOrAddValueToMember(o, choiceValue, choice.MemberInfo); + object choiceValue = Enum.Parse(choice.Mapping!.TypeDesc!.Type!, name); + SetOrAddValueToMember(o, choiceValue, choice.MemberInfo!); break; } @@ -1756,10 +1758,10 @@ private object WriteLiteralStructMethod(StructMapping structMapping, bool isNull { if (member.Collection != null) { - MemberInfo[] memberInfos = o.GetType().GetMember(member.Mapping.Name); + MemberInfo[] memberInfos = o!.GetType().GetMember(member.Mapping.Name); MemberInfo memberInfo = memberInfos[0]; - object collection = null; - SetCollectionObjectWithCollectionMember(ref collection, member.Collection, member.Mapping.TypeDesc.Type); + object? collection = null; + SetCollectionObjectWithCollectionMember(ref collection, member.Collection, member.Mapping.TypeDesc!.Type!); var setMemberValue = GetSetMemberValueDelegate(o, memberInfo.Name); setMemberValue(o, collection); } @@ -1770,9 +1772,9 @@ private object WriteLiteralStructMethod(StructMapping structMapping, bool isNull } } - private bool WriteEnumAndArrayTypes(out object o, StructMapping mapping, XmlQualifiedName xsiType, string defaultNamespace) + private bool WriteEnumAndArrayTypes(out object? o, StructMapping mapping, XmlQualifiedName xsiType, string? defaultNamespace) { - foreach (var m in _mapping.Scope.TypeMappings) + foreach (var m in _mapping.Scope!.TypeMappings) { if (m is EnumMapping enumMapping) { @@ -1808,9 +1810,9 @@ private bool WriteEnumAndArrayTypes(out object o, StructMapping mapping, XmlQual return false; } - private bool WriteDerivedTypes(out object o, StructMapping mapping, XmlQualifiedName xsiType, string defaultNamespace, bool checkType, bool isNullable) + private bool WriteDerivedTypes(out object? o, StructMapping mapping, XmlQualifiedName xsiType, string? defaultNamespace, bool checkType, bool isNullable) { - for (StructMapping derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) + for (StructMapping? derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) { if (QNameEqual(xsiType, derived.TypeName, derived.Namespace, defaultNamespace)) { @@ -1828,9 +1830,9 @@ private bool WriteDerivedTypes(out object o, StructMapping mapping, XmlQualified return false; } - private void WriteAttributes(Member[] members, Member anyAttribute, UnknownNodeAction elseCall, ref object o) + private void WriteAttributes(Member[] members, Member? anyAttribute, UnknownNodeAction elseCall, ref object? o) { - Member xmlnsMember = null; + Member? xmlnsMember = null; var attributes = new List(); foreach (Member member in members) { @@ -1851,7 +1853,7 @@ private void WriteAttributes(Member[] members, Member anyAttribute, UnknownNodeA continue; } - AttributeAccessor attribute = member.Mapping.Attribute; + AttributeAccessor? attribute = member.Mapping.Attribute; if (attribute == null) continue; if (attribute.Any) continue; @@ -1902,7 +1904,7 @@ private void WriteAttributes(Member[] members, Member anyAttribute, UnknownNodeA { if (anyAttribute != null) { - var attr = Document.ReadNode(Reader) as XmlAttribute; + var attr = (Document.ReadNode(Reader) as XmlAttribute)!; ParseWsdlArrayType(attr); WriteAttribute(anyAttribute, attr); } @@ -1914,13 +1916,13 @@ private void WriteAttributes(Member[] members, Member anyAttribute, UnknownNodeA } } - private void WriteAttribute(Member member, object attr = null) + private void WriteAttribute(Member member, object? attr = null) { - AttributeAccessor attribute = member.Mapping.Attribute; - object value = null; + AttributeAccessor attribute = member.Mapping.Attribute!; + object? value = null; if (attribute.Mapping is SpecialMapping special) { - if (special.TypeDesc.Kind == TypeKind.Attribute) + if (special.TypeDesc!.Kind == TypeKind.Attribute) { value = attr; } @@ -1939,21 +1941,21 @@ private void WriteAttribute(Member member, object attr = null) { string listValues = Reader.Value; string[] vals = listValues.Split(null); - Array arrayValue = Array.CreateInstance(member.Mapping.TypeDesc.Type.GetElementType(), vals.Length); + Array arrayValue = Array.CreateInstance(member.Mapping.TypeDesc!.Type!.GetElementType()!, vals.Length); for (int i = 0; i < vals.Length; i++) { - arrayValue.SetValue(WritePrimitive(attribute.Mapping, (state) => ((string[])state)[i], vals), i); + arrayValue.SetValue(WritePrimitive(attribute.Mapping!, (state) => ((string[])state)[i], vals), i); } value = arrayValue; } else { - value = WritePrimitive(attribute.Mapping, (state) => ((XmlReader)state).Value, Reader); + value = WritePrimitive(attribute.Mapping!, (state) => ((XmlReader)state).Value, Reader); } } - member.Source(value); + member.Source!(value); if (member.Mapping.CheckSpecified == SpecifiedAccessor.ReadWrite) { @@ -1983,7 +1985,7 @@ private void SetOrAddValueToMember(object o, object value, MemberInfo memberInfo private void AddItemInArrayMember(object o, MemberInfo memberInfo, Type memberType, object item) { - var currentArray = (Array)GetMemberValue(o, memberInfo); + var currentArray = (Array?)GetMemberValue(o, memberInfo); int length; if (currentArray == null) { @@ -1994,7 +1996,7 @@ private void AddItemInArrayMember(object o, MemberInfo memberInfo, Type memberTy length = currentArray.Length; } - var newArray = Array.CreateInstance(memberType.GetElementType(), length + 1); + var newArray = Array.CreateInstance(memberType.GetElementType()!, length + 1); if (currentArray != null) { Array.Copy(currentArray, newArray, length); @@ -2006,37 +2008,37 @@ private void AddItemInArrayMember(object o, MemberInfo memberInfo, Type memberTy } // WriteXmlNodeEqual - private bool XmlNodeEqual(XmlReader source, string name, string ns) + private bool XmlNodeEqual(XmlReader source, string name, string? ns) { return source.LocalName == name && string.Equals(source.NamespaceURI, ns); } - private bool QNameEqual(XmlQualifiedName xsiType, string name, string ns, string defaultNamespace) + private bool QNameEqual(XmlQualifiedName xsiType, string? name, string? ns, string? defaultNamespace) { return xsiType.Name == name && string.Equals(xsiType.Namespace, defaultNamespace); } - private void CreateUnknownNodeException(object o) + private void CreateUnknownNodeException(object? o) { CreateUnknownNodeException(); } - internal class CollectionMember : List + internal class CollectionMember : List { } internal class Member { public MemberMapping Mapping; - public CollectionMember Collection; + public CollectionMember? Collection; public int FixupIndex = -1; public bool MultiRef; - public Action Source; - public Func GetSource; - public Action ArraySource; - public Action CheckSpecifiedSource; - public Action ChoiceSource; - public Action XmlnsSource; + public Action? Source; + public Func? GetSource; + public Action? ArraySource; + public Action? CheckSpecifiedSource; + public Action? ChoiceSource; + public Action? XmlnsSource; public Member(MemberMapping mapping) { @@ -2046,21 +2048,21 @@ public Member(MemberMapping mapping) internal class CheckTypeSource { - public string Id { get; set; } + public string? Id { get; set; } public bool IsObject { get; set; } - public Type Type { get; set; } - public object RefObject { get; set; } + public Type? Type { get; set; } + public object? RefObject { get; set; } } internal class ObjectHolder { - public object Object; + public object? Object; } } internal static class ReflectionXmlSerializationReaderHelper { - public delegate void SetMemberValueDelegate(object o, object val); + public delegate void SetMemberValueDelegate(object? o, object? val); public static SetMemberValueDelegate GetSetMemberValueDelegateWithType(MemberInfo memberInfo) { @@ -2068,14 +2070,14 @@ public static SetMemberValueDelegate GetSetMemberValueDelegateWithType setTypedDelegate = null; + Action? setTypedDelegate = null; if (memberInfo is PropertyInfo propInfo) { var setMethod = propInfo.GetSetMethod(true); if (setMethod == null) { - return delegate (object o, object p) + return delegate (object? o, object? p) { // Maintain the same failure behavior as non-cached delegate propInfo.SetValue(o, p); @@ -2109,9 +2111,9 @@ public static SetMemberValueDelegate GetSetMemberValueDelegateWithType>(assignExpr, objectParam, valueParam).Compile(); } - return delegate (object o, object p) + return delegate (object? o, object? p) { - setTypedDelegate((TObj)o, (TParam)p); + setTypedDelegate!((TObj)o!, (TParam)p!); }; } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs index 6d86828c7cf883..9edc0cff47ef4c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; using System.Collections; using System.Collections.Generic; @@ -21,7 +22,7 @@ internal class ReflectionXmlSerializationWriter : XmlSerializationWriter internal static TypeDesc StringTypeDesc { get; private set; } = (new TypeScope()).GetTypeDesc(typeof(string)); internal static TypeDesc QnameTypeDesc { get; private set; } = (new TypeScope()).GetTypeDesc(typeof(XmlQualifiedName)); - public ReflectionXmlSerializationWriter(XmlMapping xmlMapping, XmlWriter xmlWriter, XmlSerializerNamespaces namespaces, string encodingStyle, string id) + public ReflectionXmlSerializationWriter(XmlMapping xmlMapping, XmlWriter xmlWriter, XmlSerializerNamespaces namespaces, string? encodingStyle, string? id) { Init(xmlWriter, namespaces, encodingStyle, id, null); @@ -42,18 +43,18 @@ public ReflectionXmlSerializationWriter(XmlMapping xmlMapping, XmlWriter xmlWrit protected override void InitCallbacks() { - TypeScope scope = _mapping.Scope; + TypeScope scope = _mapping.Scope!; foreach (TypeMapping mapping in scope.TypeMappings) { if (mapping.IsSoap && (mapping is StructMapping || mapping is EnumMapping) && - !mapping.TypeDesc.IsRoot) + !mapping.TypeDesc!.IsRoot) { AddWriteCallback( - mapping.TypeDesc.Type, - mapping.TypeName, + mapping.TypeDesc.Type!, + mapping.TypeName!, mapping.Namespace, - CreateXmlSerializationWriteCallback(mapping, mapping.TypeName, mapping.Namespace, mapping.TypeDesc.IsNullable) + CreateXmlSerializationWriteCallback(mapping, mapping.TypeName!, mapping.Namespace, mapping.TypeDesc.IsNullable) ); } } @@ -77,15 +78,15 @@ private void WriteObjectOfTypeElement(object o, XmlTypeMapping mapping) GenerateTypeElement(o, mapping); } - private void GenerateTypeElement(object o, XmlTypeMapping xmlMapping) + private void GenerateTypeElement(object? o, XmlTypeMapping xmlMapping) { ElementAccessor element = xmlMapping.Accessor; - TypeMapping mapping = element.Mapping; + TypeMapping mapping = element.Mapping!; WriteStartDocument(); if (o == null) { - string ns = (element.Form == XmlSchemaForm.Qualified ? element.Namespace : string.Empty); + string? ns = (element.Form == XmlSchemaForm.Qualified ? element.Namespace : string.Empty); if (element.IsNullable) { if (mapping.IsSoap) @@ -105,7 +106,7 @@ private void GenerateTypeElement(object o, XmlTypeMapping xmlMapping) return; } - if (!mapping.TypeDesc.IsValueType && !mapping.TypeDesc.Type.IsPrimitive) + if (!mapping.TypeDesc!.IsValueType && !mapping.TypeDesc.Type!.IsPrimitive) { TopLevelElement(); } @@ -117,12 +118,12 @@ private void GenerateTypeElement(object o, XmlTypeMapping xmlMapping) } } - private void WriteMember(object o, object choiceSource, ElementAccessor[] elements, TextAccessor text, ChoiceIdentifierAccessor choice, TypeDesc memberTypeDesc, bool writeAccessors) + private void WriteMember(object? o, object? choiceSource, ElementAccessor[] elements, TextAccessor? text, ChoiceIdentifierAccessor? choice, TypeDesc memberTypeDesc, bool writeAccessors) { if (memberTypeDesc.IsArrayLike && !(elements.Length == 1 && elements[0].Mapping is ArrayMapping)) { - WriteArray(o, choiceSource, elements, text, choice, memberTypeDesc); + WriteArray(o!, choiceSource, elements, text, choice, memberTypeDesc); } else { @@ -130,7 +131,7 @@ private void WriteMember(object o, object choiceSource, ElementAccessor[] elemen } } - private void WriteArray(object o, object choiceSource, ElementAccessor[] elements, TextAccessor text, ChoiceIdentifierAccessor choice, TypeDesc arrayTypeDesc) + private void WriteArray(object o, object? choiceSource, ElementAccessor[] elements, TextAccessor? text, ChoiceIdentifierAccessor? choice, TypeDesc arrayTypeDesc) { if (elements.Length == 0 && text == null) { @@ -146,14 +147,14 @@ private void WriteArray(object o, object choiceSource, ElementAccessor[] element { if (choiceSource == null || ((Array)choiceSource).Length < ((Array)o).Length) { - throw CreateInvalidChoiceIdentifierValueException(choice.Mapping.TypeDesc.FullName, choice.MemberName); + throw CreateInvalidChoiceIdentifierValueException(choice.Mapping!.TypeDesc!.FullName, choice.MemberName!); } } WriteArrayItems(elements, text, choice, arrayTypeDesc, o); } - private void WriteArrayItems(ElementAccessor[] elements, TextAccessor text, ChoiceIdentifierAccessor choice, TypeDesc arrayTypeDesc, object o) + private void WriteArrayItems(ElementAccessor[] elements, TextAccessor? text, ChoiceIdentifierAccessor? choice, TypeDesc? arrayTypeDesc, object o) { var arr = o as IList; @@ -161,7 +162,7 @@ private void WriteArrayItems(ElementAccessor[] elements, TextAccessor text, Choi { for (int i = 0; i < arr.Count; i++) { - object ai = arr[i]; + object? ai = arr[i]; WriteElements(ai, null/*choiceName + "i"*/, elements, text, choice, true, true); } } @@ -182,7 +183,7 @@ private void WriteArrayItems(ElementAccessor[] elements, TextAccessor text, Choi } } - private void WriteElements(object o, object enumSource, ElementAccessor[] elements, TextAccessor text, ChoiceIdentifierAccessor choice, bool writeAccessors, bool isNullable) + private void WriteElements(object? o, object? enumSource, ElementAccessor[] elements, TextAccessor? text, ChoiceIdentifierAccessor? choice, bool writeAccessors, bool isNullable) { if (elements.Length == 0 && text == null) return; @@ -200,8 +201,8 @@ private void WriteElements(object o, object enumSource, ElementAccessor[] elemen int anyCount = 0; var namedAnys = new List(); - ElementAccessor unnamedAny = null; // can only have one - string enumTypeName = choice?.Mapping.TypeDesc.FullName; + ElementAccessor? unnamedAny = null; // can only have one + string? enumTypeName = choice?.Mapping!.TypeDesc!.FullName; for (int i = 0; i < elements.Length; i++) { @@ -217,7 +218,7 @@ private void WriteElements(object o, object enumSource, ElementAccessor[] elemen } else if (choice != null) { - if (o != null && o.GetType() == element.Mapping.TypeDesc.Type) + if (o != null && o.GetType() == element.Mapping!.TypeDesc!.Type) { WriteElement(o, element, writeAccessors); return; @@ -225,8 +226,8 @@ private void WriteElements(object o, object enumSource, ElementAccessor[] elemen } else { - TypeDesc td = element.IsUnbounded ? element.Mapping.TypeDesc.CreateArrayTypeDesc() : element.Mapping.TypeDesc; - if (o.GetType() == td.Type) + TypeDesc td = element.IsUnbounded ? element.Mapping!.TypeDesc!.CreateArrayTypeDesc() : element.Mapping!.TypeDesc!; + if (o!.GetType() == td.Type) { WriteElement(o, element, writeAccessors); return; @@ -249,7 +250,7 @@ private void WriteElements(object o, object enumSource, ElementAccessor[] elemen if (choice != null) { - throw CreateChoiceIdentifierValueException(choice.Mapping.TypeDesc.FullName, choice.MemberName, elem.Name, elem.NamespaceURI); + throw CreateChoiceIdentifierValueException(choice.Mapping.TypeDesc!.FullName, choice.MemberName!, elem.Name, elem.NamespaceURI); } if (unnamedAny != null) @@ -264,7 +265,7 @@ private void WriteElements(object o, object enumSource, ElementAccessor[] elemen if (text != null) { - WriteText(o, text); + WriteText(o!, text); return; } @@ -279,14 +280,14 @@ private void WriteText(object o, TextAccessor text) { if (text.Mapping is PrimitiveMapping primitiveMapping) { - string stringValue; + string? stringValue; if (text.Mapping is EnumMapping enumMapping) { stringValue = WriteEnumMethod(enumMapping, o); } else { - if (!WritePrimitiveValue(primitiveMapping.TypeDesc, o, false, out stringValue)) + if (!WritePrimitiveValue(primitiveMapping.TypeDesc!, o, false, out stringValue)) { Debug.Assert(o is byte[]); } @@ -303,7 +304,7 @@ private void WriteText(object o, TextAccessor text) } else if (text.Mapping is SpecialMapping specialMapping) { - switch (specialMapping.TypeDesc.Kind) + switch (specialMapping.TypeDesc!.Kind) { case TypeKind.Node: ((XmlNode)o).WriteTo(Writer); @@ -314,10 +315,10 @@ private void WriteText(object o, TextAccessor text) } } - private void WriteElement(object o, ElementAccessor element, bool writeAccessor) + private void WriteElement(object? o, ElementAccessor element, bool writeAccessor) { - string name = writeAccessor ? element.Name : element.Mapping.TypeName; - string ns = element.Any && element.Name.Length == 0 ? null : (element.Form == XmlSchemaForm.Qualified ? (writeAccessor ? element.Namespace : element.Mapping.Namespace) : string.Empty); + string name = writeAccessor ? element.Name : element.Mapping!.TypeName!; + string? ns = element.Any && element.Name.Length == 0 ? null : (element.Form == XmlSchemaForm.Qualified ? (writeAccessor ? element.Namespace : element.Mapping!.Namespace) : string.Empty); if (element.Mapping is NullableMapping nullableMapping) { @@ -339,7 +340,7 @@ private void WriteElement(object o, ElementAccessor element, bool writeAccessor) { WriteNullTagLiteral(element.Name, element.Form == XmlSchemaForm.Qualified ? element.Namespace : string.Empty); } - else if (mapping.IsSoap) + else if (mapping!.IsSoap) { if (mapping.Elements == null || mapping.Elements.Length != 1) { @@ -348,7 +349,7 @@ private void WriteElement(object o, ElementAccessor element, bool writeAccessor) if (!writeAccessor) { - WritePotentiallyReferencingElement(name, ns, o, mapping.TypeDesc.Type, true, element.IsNullable); + WritePotentiallyReferencingElement(name, ns, o, mapping.TypeDesc!.Type, true, element.IsNullable); } else { @@ -357,8 +358,8 @@ private void WriteElement(object o, ElementAccessor element, bool writeAccessor) } else if (element.IsUnbounded) { - TypeDesc arrayTypeDesc = mapping.TypeDesc.CreateArrayTypeDesc(); - var enumerable = (IEnumerable)o; + TypeDesc arrayTypeDesc = mapping.TypeDesc!.CreateArrayTypeDesc(); + var enumerable = (IEnumerable)o!; foreach (var e in enumerable) { element.IsUnbounded = false; @@ -371,7 +372,7 @@ private void WriteElement(object o, ElementAccessor element, bool writeAccessor) if (o != null) { WriteStartElement(name, ns, false); - WriteArrayItems(mapping.ElementsSortedByDerivation, null, null, mapping.TypeDesc, o); + WriteArrayItems(mapping.ElementsSortedByDerivation!, null, null, mapping.TypeDesc, o); WriteEndElement(); } } @@ -381,37 +382,37 @@ private void WriteElement(object o, ElementAccessor element, bool writeAccessor) if (element.Mapping.IsSoap) { Writer.WriteStartElement(name, ns); - WriteEnumMethod((EnumMapping)element.Mapping, o); + WriteEnumMethod((EnumMapping)element.Mapping, o!); WriteEndElement(); } else { - WritePrimitive(WritePrimitiveMethodRequirement.WriteElementString, name, ns, element.Default, o, element.Mapping, false, true, element.IsNullable); + WritePrimitive(WritePrimitiveMethodRequirement.WriteElementString, name, ns!, element.Default, o!, element.Mapping, false, true, element.IsNullable); } } else if (element.Mapping is PrimitiveMapping) { var mapping = element.Mapping as PrimitiveMapping; - if (mapping.TypeDesc == QnameTypeDesc) + if (mapping!.TypeDesc == QnameTypeDesc) { - WriteQualifiedNameElement(name, ns, element.Default, (XmlQualifiedName)o, element.IsNullable, mapping.IsSoap, mapping); + WriteQualifiedNameElement(name, ns!, element.Default, (XmlQualifiedName)o!, element.IsNullable, mapping.IsSoap, mapping); } else { WritePrimitiveMethodRequirement suffixNullable = mapping.IsSoap ? WritePrimitiveMethodRequirement.Encoded : WritePrimitiveMethodRequirement.None; - WritePrimitiveMethodRequirement suffixRaw = mapping.TypeDesc.XmlEncodingNotRequired ? WritePrimitiveMethodRequirement.Raw : WritePrimitiveMethodRequirement.None; + WritePrimitiveMethodRequirement suffixRaw = mapping.TypeDesc!.XmlEncodingNotRequired ? WritePrimitiveMethodRequirement.Raw : WritePrimitiveMethodRequirement.None; WritePrimitive(element.IsNullable ? WritePrimitiveMethodRequirement.WriteNullableStringLiteral | suffixNullable | suffixRaw : WritePrimitiveMethodRequirement.WriteElementString | suffixRaw, - name, ns, element.Default, o, mapping, mapping.IsSoap, true, element.IsNullable); + name, ns!, element.Default, o!, mapping, mapping.IsSoap, true, element.IsNullable); } } else if (element.Mapping is StructMapping) { var mapping = element.Mapping as StructMapping; - if (mapping.IsSoap) + if (mapping!.IsSoap) { - WritePotentiallyReferencingElement(name, ns, o, !writeAccessor ? mapping.TypeDesc.Type : null, !writeAccessor, element.IsNullable); + WritePotentiallyReferencingElement(name, ns, o, !writeAccessor ? mapping.TypeDesc!.Type : null, !writeAccessor, element.IsNullable); } else { @@ -422,7 +423,7 @@ private void WriteElement(object o, ElementAccessor element, bool writeAccessor) { if (element.Mapping is SerializableMapping) { - WriteSerializable((IXmlSerializable)o, name, ns, element.IsNullable, !element.Any); + WriteSerializable((IXmlSerializable)o!, name, ns, element.IsNullable, !element.Any); } else { @@ -433,7 +434,7 @@ private void WriteElement(object o, ElementAccessor element, bool writeAccessor) } else { - throw CreateInvalidAnyTypeException(o); + throw CreateInvalidAnyTypeException(o!); } } } @@ -443,7 +444,7 @@ private void WriteElement(object o, ElementAccessor element, bool writeAccessor) } } - private XmlSerializationWriteCallback CreateXmlSerializationWriteCallback(TypeMapping mapping, string name, string ns, bool isNullable) + private XmlSerializationWriteCallback CreateXmlSerializationWriteCallback(TypeMapping mapping, string name, string? ns, bool isNullable) { if (mapping is StructMapping structMapping) { @@ -465,10 +466,10 @@ private XmlSerializationWriteCallback CreateXmlSerializationWriteCallback(TypeMa } } - private void WriteQualifiedNameElement(string name, string ns, object defaultValue, XmlQualifiedName o, bool nullable, bool isSoap, PrimitiveMapping mapping) + private void WriteQualifiedNameElement(string name, string ns, object? defaultValue, XmlQualifiedName o, bool nullable, bool isSoap, PrimitiveMapping mapping) { - bool hasDefault = defaultValue != null && defaultValue != DBNull.Value && mapping.TypeDesc.HasDefaultSupport; - if (hasDefault && IsDefaultValue(mapping, o, defaultValue, nullable)) + bool hasDefault = defaultValue != null && defaultValue != DBNull.Value && mapping.TypeDesc!.HasDefaultSupport; + if (hasDefault && IsDefaultValue(mapping, o, defaultValue!, nullable)) return; if (isSoap) @@ -495,9 +496,9 @@ private void WriteQualifiedNameElement(string name, string ns, object defaultVal } } - private void WriteStructMethod(StructMapping mapping, string n, string ns, object o, bool isNullable, bool needType) + private void WriteStructMethod(StructMapping mapping, string n, string? ns, object? o, bool isNullable, bool needType) { - if (mapping.IsSoap && mapping.TypeDesc.IsRoot) return; + if (mapping.IsSoap && mapping.TypeDesc!.IsRoot) return; if (!mapping.IsSoap) { @@ -508,7 +509,7 @@ private void WriteStructMethod(StructMapping mapping, string n, string ns, objec } if (!needType - && o.GetType() != mapping.TypeDesc.Type) + && o.GetType() != mapping.TypeDesc!.Type) { if (WriteDerivedTypes(mapping, n, ns, o, isNullable)) { @@ -517,7 +518,7 @@ private void WriteStructMethod(StructMapping mapping, string n, string ns, objec if (mapping.TypeDesc.IsRoot) { - if (WriteEnumAndArrayTypes(mapping, o, n, ns)) + if (WriteEnumAndArrayTypes(mapping, o, n!, ns)) { return; } @@ -530,20 +531,20 @@ private void WriteStructMethod(StructMapping mapping, string n, string ns, objec } } - if (!mapping.TypeDesc.IsAbstract) + if (!mapping.TypeDesc!.IsAbstract) { if (mapping.TypeDesc.Type != null && typeof(XmlSchemaObject).IsAssignableFrom(mapping.TypeDesc.Type)) { EscapeName = false; } - XmlSerializerNamespaces xmlnsSource = null; + XmlSerializerNamespaces? xmlnsSource = null; MemberMapping[] members = TypeScope.GetAllMembers(mapping); int xmlnsMember = FindXmlnsIndex(members); if (xmlnsMember >= 0) { MemberMapping member = members[xmlnsMember]; - xmlnsSource = (XmlSerializerNamespaces)GetMemberValue(o, member.Name); + xmlnsSource = (XmlSerializerNamespaces?)GetMemberValue(o!, member.Name); } if (!mapping.IsSoap) @@ -554,7 +555,7 @@ private void WriteStructMethod(StructMapping mapping, string n, string ns, objec { if (needType) { - WriteXsiType(mapping.TypeName, mapping.Namespace); + WriteXsiType(mapping.TypeName!, mapping.Namespace); } } } @@ -572,22 +573,22 @@ private void WriteStructMethod(StructMapping mapping, string n, string ns, objec if (m.CheckSpecified != SpecifiedAccessor.None) { string specifiedMemberName = m.Name + "Specified"; - isSpecified = (bool)GetMemberValue(o, specifiedMemberName); + isSpecified = (bool)GetMemberValue(o!, specifiedMemberName)!; } if (m.CheckShouldPersist) { string methodInvoke = "ShouldSerialize" + m.Name; - MethodInfo method = o.GetType().GetTypeInfo().GetDeclaredMethod(methodInvoke); - shouldPersist = (bool)method.Invoke(o, Array.Empty()); + MethodInfo method = o!.GetType().GetTypeInfo().GetDeclaredMethod(methodInvoke)!; + shouldPersist = (bool)method.Invoke(o, Array.Empty())!; } if (m.Attribute != null) { if (isSpecified && shouldPersist) { - object memberValue = GetMemberValue(o, m.Name); - WriteMember(memberValue, m.Attribute, m.TypeDesc, o); + object? memberValue = GetMemberValue(o!, m.Name); + WriteMember(memberValue, m.Attribute, m.TypeDesc!, o); } } } @@ -604,17 +605,17 @@ private void WriteStructMethod(StructMapping mapping, string n, string ns, objec if (m.CheckSpecified != SpecifiedAccessor.None) { string specifiedMemberName = m.Name + "Specified"; - isSpecified = (bool)GetMemberValue(o, specifiedMemberName); + isSpecified = (bool)GetMemberValue(o!, specifiedMemberName)!; } if (m.CheckShouldPersist) { string methodInvoke = "ShouldSerialize" + m.Name; - MethodInfo method = o.GetType().GetTypeInfo().GetDeclaredMethod(methodInvoke); - shouldPersist = (bool)method.Invoke(o, Array.Empty()); + MethodInfo method = o!.GetType().GetTypeInfo().GetDeclaredMethod(methodInvoke)!; + shouldPersist = (bool)method.Invoke(o, Array.Empty())!; } - bool checkShouldPersist = m.CheckShouldPersist && (m.Elements.Length > 0 || m.Text != null); + bool checkShouldPersist = m.CheckShouldPersist && (m.Elements!.Length > 0 || m.Text != null); if (!checkShouldPersist) { @@ -623,14 +624,14 @@ private void WriteStructMethod(StructMapping mapping, string n, string ns, objec if (isSpecified && shouldPersist) { - object choiceSource = null; + object? choiceSource = null; if (m.ChoiceIdentifier != null) { - choiceSource = GetMemberValue(o, m.ChoiceIdentifier.MemberName); + choiceSource = GetMemberValue(o!, m.ChoiceIdentifier.MemberName!); } - object memberValue = GetMemberValue(o, m.Name); - WriteMember(memberValue, choiceSource, m.ElementsSortedByDerivation, m.Text, m.ChoiceIdentifier, m.TypeDesc, true); + object? memberValue = GetMemberValue(o!, m.Name); + WriteMember(memberValue, choiceSource, m.ElementsSortedByDerivation!, m.Text, m.ChoiceIdentifier, m.TypeDesc!, true); } } @@ -641,24 +642,24 @@ private void WriteStructMethod(StructMapping mapping, string n, string ns, objec } } - private object GetMemberValue(object o, string memberName) + private object? GetMemberValue(object o, string memberName) { MemberInfo memberInfo = ReflectionXmlSerializationHelper.GetMember(o.GetType(), memberName); - object memberValue = GetMemberValue(o, memberInfo); + object? memberValue = GetMemberValue(o, memberInfo); return memberValue; } - private bool WriteEnumAndArrayTypes(StructMapping structMapping, object o, string n, string ns) + private bool WriteEnumAndArrayTypes(StructMapping structMapping, object o, string n, string? ns) { if (o is Enum) { Writer.WriteStartElement(n, ns); - EnumMapping enumMapping = null; + EnumMapping? enumMapping = null; Type enumType = o.GetType(); - foreach (var m in _mapping.Scope.TypeMappings) + foreach (var m in _mapping.Scope!.TypeMappings) { - if (m is EnumMapping em && em.TypeDesc.Type == enumType) + if (m is EnumMapping em && em.TypeDesc!.Type == enumType) { enumMapping = em; break; @@ -668,7 +669,7 @@ private bool WriteEnumAndArrayTypes(StructMapping structMapping, object o, strin if (enumMapping == null) throw new InvalidOperationException(SR.XmlInternalError); - WriteXsiType(enumMapping.TypeName, ns); + WriteXsiType(enumMapping.TypeName!, ns); Writer.WriteString(WriteEnumMethod(enumMapping, o)); Writer.WriteEndElement(); return true; @@ -677,11 +678,11 @@ private bool WriteEnumAndArrayTypes(StructMapping structMapping, object o, strin if (o is Array) { Writer.WriteStartElement(n, ns); - ArrayMapping arrayMapping = null; + ArrayMapping? arrayMapping = null; Type arrayType = o.GetType(); - foreach (var m in _mapping.Scope.TypeMappings) + foreach (var m in _mapping.Scope!.TypeMappings) { - if (m is ArrayMapping am && am.TypeDesc.Type == arrayType) + if (m is ArrayMapping am && am.TypeDesc!.Type == arrayType) { arrayMapping = am; break; @@ -691,8 +692,8 @@ private bool WriteEnumAndArrayTypes(StructMapping structMapping, object o, strin if (arrayMapping == null) throw new InvalidOperationException(SR.XmlInternalError); - WriteXsiType(arrayMapping.TypeName, ns); - WriteMember(o, null, arrayMapping.ElementsSortedByDerivation, null, null, arrayMapping.TypeDesc, true); + WriteXsiType(arrayMapping.TypeName!, ns); + WriteMember(o, null, arrayMapping.ElementsSortedByDerivation!, null, null, arrayMapping.TypeDesc!, true); Writer.WriteEndElement(); return true; @@ -701,12 +702,12 @@ private bool WriteEnumAndArrayTypes(StructMapping structMapping, object o, strin return false; } - private string WriteEnumMethod(EnumMapping mapping, object v) + private string? WriteEnumMethod(EnumMapping mapping, object v) { - string returnString = null; + string? returnString = null; if (mapping != null) { - ConstantMapping[] constants = mapping.Constants; + ConstantMapping[] constants = mapping.Constants!; if (constants.Length > 0) { bool foundValue = false; @@ -739,7 +740,7 @@ private string WriteEnumMethod(EnumMapping mapping, object v) } else { - throw CreateInvalidEnumValueException(v, mapping.TypeDesc.FullName); + throw CreateInvalidEnumValueException(v, mapping.TypeDesc!.FullName); } } } @@ -749,9 +750,9 @@ private string WriteEnumMethod(EnumMapping mapping, object v) returnString = v.ToString(); } - if (mapping.IsSoap) + if (mapping!.IsSoap) { - WriteXsiType(mapping.TypeName, mapping.Namespace); + WriteXsiType(mapping.TypeName!, mapping.Namespace); Writer.WriteString(returnString); return null; } @@ -761,7 +762,7 @@ private string WriteEnumMethod(EnumMapping mapping, object v) } } - private object GetMemberValue(object o, MemberInfo memberInfo) + private object? GetMemberValue(object? o, MemberInfo memberInfo) { if (memberInfo is PropertyInfo memberProperty) { @@ -775,13 +776,13 @@ private object GetMemberValue(object o, MemberInfo memberInfo) throw new InvalidOperationException(SR.XmlInternalError); } - private void WriteMember(object memberValue, AttributeAccessor attribute, TypeDesc memberTypeDesc, object container) + private void WriteMember(object? memberValue, AttributeAccessor attribute, TypeDesc memberTypeDesc, object? container) { if (memberTypeDesc.IsAbstract) return; if (memberTypeDesc.IsArrayLike) { var sb = new StringBuilder(); - TypeDesc arrayElementTypeDesc = memberTypeDesc.ArrayElementTypeDesc; + TypeDesc? arrayElementTypeDesc = memberTypeDesc.ArrayElementTypeDesc; bool canOptimizeWriteListSequence = CanOptimizeWriteListSequence(arrayElementTypeDesc); if (attribute.IsList) { @@ -804,14 +805,14 @@ private void WriteMember(object memberValue, AttributeAccessor attribute, TypeDe if (attribute.IsList) { - string stringValue; + string? stringValue; if (attribute.Mapping is EnumMapping enumMapping) { stringValue = WriteEnumMethod(enumMapping, ai); } else { - if (!WritePrimitiveValue(arrayElementTypeDesc, ai, true, out stringValue)) + if (!WritePrimitiveValue(arrayElementTypeDesc!, ai, true, out stringValue)) { Debug.Assert(ai is byte[]); } @@ -863,7 +864,7 @@ private void WriteMember(object memberValue, AttributeAccessor attribute, TypeDe { if (sb.Length != 0) { - string ns = attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : string.Empty; + string? ns = attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : string.Empty; WriteAttribute(attribute.Name, ns, sb.ToString()); } } @@ -873,11 +874,11 @@ private void WriteMember(object memberValue, AttributeAccessor attribute, TypeDe } else { - WriteAttribute(memberValue, attribute, container); + WriteAttribute(memberValue!, attribute, container); } } - private bool CanOptimizeWriteListSequence(TypeDesc listElementTypeDesc) + private bool CanOptimizeWriteListSequence(TypeDesc? listElementTypeDesc) { // check to see if we can write values of the attribute sequentially // currently we have only one data type (XmlQualifiedName) that we can not write "inline", @@ -885,12 +886,12 @@ private bool CanOptimizeWriteListSequence(TypeDesc listElementTypeDesc) return (listElementTypeDesc != null && listElementTypeDesc != QnameTypeDesc); } - private void WriteAttribute(object memberValue, AttributeAccessor attribute, object container) + private void WriteAttribute(object memberValue, AttributeAccessor attribute, object? container) { // TODO: this block is never hit by our tests. if (attribute.Mapping is SpecialMapping special) { - if (special.TypeDesc.Kind == TypeKind.Attribute || special.TypeDesc.CanBeAttributeValue) + if (special.TypeDesc!.Kind == TypeKind.Attribute || special.TypeDesc.CanBeAttributeValue) { WriteXmlAttribute((XmlNode)memberValue, container); } @@ -901,8 +902,8 @@ private void WriteAttribute(object memberValue, AttributeAccessor attribute, obj } else { - string ns = attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : string.Empty; - WritePrimitive(WritePrimitiveMethodRequirement.WriteAttribute, attribute.Name, ns, attribute.Default, memberValue, attribute.Mapping, false, false, false); + string? ns = attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : string.Empty; + WritePrimitive(WritePrimitiveMethodRequirement.WriteAttribute, attribute.Name, ns, attribute.Default, memberValue, attribute.Mapping!, false, false, false); } } @@ -919,12 +920,12 @@ private int FindXmlnsIndex(MemberMapping[] members) return -1; } - private bool WriteDerivedTypes(StructMapping mapping, string n, string ns, object o, bool isNullable) + private bool WriteDerivedTypes(StructMapping mapping, string n, string? ns, object o, bool isNullable) { Type t = o.GetType(); - for (StructMapping derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) + for (StructMapping? derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) { - if (t == derived.TypeDesc.Type) + if (t == derived.TypeDesc!.Type) { WriteStructMethod(derived, n, ns, o, isNullable, needType: true); return true; @@ -939,17 +940,17 @@ private bool WriteDerivedTypes(StructMapping mapping, string n, string ns, objec return false; } - private void WritePrimitive(WritePrimitiveMethodRequirement method, string name, string ns, object defaultValue, object o, TypeMapping mapping, bool writeXsiType, bool isElement, bool isNullable) + private void WritePrimitive(WritePrimitiveMethodRequirement method, string name, string? ns, object? defaultValue, object o, TypeMapping mapping, bool writeXsiType, bool isElement, bool isNullable) { - TypeDesc typeDesc = mapping.TypeDesc; - bool hasDefault = defaultValue != null && defaultValue != DBNull.Value && mapping.TypeDesc.HasDefaultSupport; + TypeDesc typeDesc = mapping.TypeDesc!; + bool hasDefault = defaultValue != null && defaultValue != DBNull.Value && mapping.TypeDesc!.HasDefaultSupport; if (hasDefault) { if (mapping is EnumMapping) { if (((EnumMapping)mapping).IsFlags) { - IEnumerable defaultEnumFlagValues = defaultValue.ToString().Split((char[])null, StringSplitOptions.RemoveEmptyEntries); + IEnumerable defaultEnumFlagValues = defaultValue!.ToString()!.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries); string defaultEnumFlagString = string.Join(", ", defaultEnumFlagValues); if (o.ToString() == defaultEnumFlagString) @@ -957,26 +958,26 @@ private void WritePrimitive(WritePrimitiveMethodRequirement method, string name, } else { - if (o.ToString() == defaultValue.ToString()) + if (o.ToString() == defaultValue!.ToString()) return; } } else { - if (IsDefaultValue(mapping, o, defaultValue, isNullable)) + if (IsDefaultValue(mapping, o, defaultValue!, isNullable)) { return; } } } - XmlQualifiedName xmlQualifiedName = null; + XmlQualifiedName? xmlQualifiedName = null; if (writeXsiType) { xmlQualifiedName = new XmlQualifiedName(mapping.TypeName, mapping.Namespace); } - string stringValue = null; + string? stringValue = null; bool hasValidStringValue = false; if (mapping is EnumMapping enumMapping) { @@ -1048,7 +1049,7 @@ private void WritePrimitive(WritePrimitiveMethodRequirement method, string name, } else if (hasRequirement(method, WritePrimitiveMethodRequirement.WriteAttribute)) { - WriteAttribute(name, ns, a); + WriteAttribute(name, ns!, a); } else { @@ -1079,18 +1080,18 @@ private bool IsDefaultValue(TypeMapping mapping, object o, object value, bool is } } - private bool WritePrimitiveValue(TypeDesc typeDesc, object o, bool isElement, out string stringValue) + private bool WritePrimitiveValue(TypeDesc typeDesc, object? o, bool isElement, out string? stringValue) { if (typeDesc == StringTypeDesc || typeDesc.FormatterName == "String") { - stringValue = (string)o; + stringValue = (string?)o; return true; } else { if (!typeDesc.HasCustomFormatter) { - stringValue = ConvertPrimitiveToString(o, typeDesc); + stringValue = ConvertPrimitiveToString(o!, typeDesc); return true; } else if (o is byte[] && typeDesc.FormatterName == "ByteArrayHex") @@ -1122,7 +1123,7 @@ private bool WritePrimitiveValue(TypeDesc typeDesc, object o, bool isElement, ou } else if (typeDesc == QnameTypeDesc) { - stringValue = FromXmlQualifiedName((XmlQualifiedName)o); + stringValue = FromXmlQualifiedName((XmlQualifiedName?)o); return true; } else if (o is string) @@ -1187,7 +1188,7 @@ private string ConvertPrimitiveToString(object o, TypeDesc typeDesc) "Guid" => XmlConvert.ToString((Guid)o), "Char" => XmlConvert.ToString((char)o), "TimeSpan" => XmlConvert.ToString((TimeSpan)o), - _ => o.ToString(), + _ => o.ToString()!, }; return stringValue; } @@ -1195,7 +1196,7 @@ private string ConvertPrimitiveToString(object o, TypeDesc typeDesc) private void GenerateMembersElement(object o, XmlMembersMapping xmlMembersMapping) { ElementAccessor element = xmlMembersMapping.Accessor; - MembersMapping mapping = (MembersMapping)element.Mapping; + MembersMapping mapping = (MembersMapping)element.Mapping!; bool hasWrapperElement = mapping.HasWrapperElement; bool writeAccessors = mapping.WriteAccessors; bool isRpc = xmlMembersMapping.IsSoap && writeAccessors; @@ -1214,10 +1215,10 @@ private void GenerateMembersElement(object o, XmlMembersMapping xmlMembersMappin { WriteStartElement(element.Name, (element.Form == XmlSchemaForm.Qualified ? element.Namespace : string.Empty), mapping.IsSoap); - int xmlnsMember = FindXmlnsIndex(mapping.Members); + int xmlnsMember = FindXmlnsIndex(mapping.Members!); if (xmlnsMember >= 0) { - MemberMapping member = mapping.Members[xmlnsMember]; + MemberMapping member = mapping.Members![xmlnsMember]; var source = (XmlSerializerNamespaces)p[xmlnsMember]; if (pLength > xmlnsMember) @@ -1226,7 +1227,7 @@ private void GenerateMembersElement(object o, XmlMembersMapping xmlMembersMappin } } - for (int i = 0; i < mapping.Members.Length; i++) + for (int i = 0; i < mapping.Members!.Length; i++) { MemberMapping member = mapping.Members[i]; if (member.Attribute != null && !member.Ignore) @@ -1248,13 +1249,13 @@ private void GenerateMembersElement(object o, XmlMembersMapping xmlMembersMappin if (pLength > i && (specifiedSource == null || specifiedSource.Value)) { - WriteMember(source, member.Attribute, member.TypeDesc, null); + WriteMember(source, member.Attribute, member.TypeDesc!, null); } } } } - for (int i = 0; i < mapping.Members.Length; i++) + for (int i = 0; i < mapping.Members!.Length; i++) { MemberMapping member = mapping.Members[i]; if (member.Xmlns != null) @@ -1283,7 +1284,7 @@ private void GenerateMembersElement(object o, XmlMembersMapping xmlMembersMappin { object source = p[i]; - object enumSource = null; + object? enumSource = null; if (member.ChoiceIdentifier != null) { for (int j = 0; j < mapping.Members.Length; j++) @@ -1296,13 +1297,13 @@ private void GenerateMembersElement(object o, XmlMembersMapping xmlMembersMappin } } - if (isRpc && member.IsReturnValue && member.Elements.Length > 0) + if (isRpc && member.IsReturnValue && member.Elements!.Length > 0) { WriteRpcResult(member.Elements[0].Name, string.Empty); } // override writeAccessors choice when we've written a wrapper element - WriteMember(source, enumSource, member.ElementsSortedByDerivation, member.Text, member.ChoiceIdentifier, member.TypeDesc, writeAccessors || hasWrapperElement); + WriteMember(source, enumSource, member.ElementsSortedByDerivation!, member.Text, member.ChoiceIdentifier, member.TypeDesc!, writeAccessors || hasWrapperElement); } } } @@ -1353,7 +1354,7 @@ public static MemberInfo GetMember(Type declaringType, string memberName) if (memberInfos == null || memberInfos.Length == 0) { bool foundMatchedMember = false; - Type currentType = declaringType.BaseType; + Type? currentType = declaringType.BaseType; while (currentType != null) { memberInfos = currentType.GetMember(memberName); @@ -1371,10 +1372,10 @@ public static MemberInfo GetMember(Type declaringType, string memberName) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, $"Could not find member named {memberName} of type {declaringType}")); } - declaringType = currentType; + declaringType = currentType!; } - MemberInfo memberInfo = memberInfos[0]; + MemberInfo memberInfo = memberInfos![0]; if (memberInfos.Length != 1) { foreach (MemberInfo mi in memberInfos) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaImporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaImporter.cs index 2c14c351a3f2bc..c3ef906d46f5fa 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaImporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaImporter.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; @@ -18,13 +19,13 @@ namespace System.Xml.Serialization public abstract class SchemaImporter { private XmlSchemas _schemas; - private StructMapping _root; + private StructMapping? _root; private readonly CodeGenerationOptions _options; - private TypeScope _scope; + private TypeScope? _scope; private ImportContext _context; private bool _rootImported; - private NameTable _typesInUse; - private NameTable _groupsInUse; + private NameTable? _typesInUse; + private NameTable? _groupsInUse; internal SchemaImporter(XmlSchemas schemas, CodeGenerationOptions options, ImportContext context) { @@ -114,7 +115,7 @@ internal CodeGenerationOptions Options get { return _options; } } - internal void MakeDerived(StructMapping structMapping, Type baseType, bool baseTypeCanBeIndirect) + internal void MakeDerived(StructMapping structMapping, Type? baseType, bool baseTypeCanBeIndirect) { structMapping.ReferencedByTopLevelElement = true; TypeDesc baseTypeDesc; @@ -123,7 +124,7 @@ internal void MakeDerived(StructMapping structMapping, Type baseType, bool baseT baseTypeDesc = Scope.GetTypeDesc(baseType); if (baseTypeDesc != null) { - TypeDesc typeDescToChange = structMapping.TypeDesc; + TypeDesc typeDescToChange = structMapping.TypeDesc!; if (baseTypeCanBeIndirect) { // if baseTypeCanBeIndirect is true, we apply the supplied baseType to the top of the @@ -132,7 +133,7 @@ internal void MakeDerived(StructMapping structMapping, Type baseType, bool baseT typeDescToChange = typeDescToChange.BaseTypeDesc; } if (typeDescToChange.BaseTypeDesc != null && typeDescToChange.BaseTypeDesc != baseTypeDesc) - throw new InvalidOperationException(SR.Format(SR.XmlInvalidBaseType, structMapping.TypeDesc.FullName, baseType.FullName, typeDescToChange.BaseTypeDesc.FullName)); + throw new InvalidOperationException(SR.Format(SR.XmlInvalidBaseType, structMapping.TypeDesc!.FullName, baseType.FullName, typeDescToChange.BaseTypeDesc.FullName)); typeDescToChange.BaseTypeDesc = baseTypeDesc; } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaObjectWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaObjectWriter.cs index 7ede7de2b421f6..f4b469f61e4f99 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaObjectWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SchemaObjectWriter.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; @@ -11,14 +12,14 @@ namespace System.Xml.Serialization using System.Xml.Serialization; using System.Collections; using System.Collections.Specialized; - + using System.Diagnostics.CodeAnalysis; internal class XmlAttributeComparer : IComparer { - public int Compare(object o1, object o2) + public int Compare(object? o1, object? o2) { - XmlAttribute a1 = (XmlAttribute)o1; - XmlAttribute a2 = (XmlAttribute)o2; + XmlAttribute a1 = (XmlAttribute)o1!; + XmlAttribute a2 = (XmlAttribute)o2!; int ns = string.Compare(a1.NamespaceURI, a2.NamespaceURI, StringComparison.Ordinal); if (ns == 0) { @@ -30,20 +31,20 @@ public int Compare(object o1, object o2) internal class XmlFacetComparer : IComparer { - public int Compare(object o1, object o2) + public int Compare(object? o1, object? o2) { - XmlSchemaFacet f1 = (XmlSchemaFacet)o1; - XmlSchemaFacet f2 = (XmlSchemaFacet)o2; + XmlSchemaFacet f1 = (XmlSchemaFacet)o1!; + XmlSchemaFacet f2 = (XmlSchemaFacet)o2!; return string.Compare(f1.GetType().Name + ":" + f1.Value, f2.GetType().Name + ":" + f2.Value, StringComparison.Ordinal); } } internal class QNameComparer : IComparer { - public int Compare(object o1, object o2) + public int Compare(object? o1, object? o2) { - XmlQualifiedName qn1 = (XmlQualifiedName)o1; - XmlQualifiedName qn2 = (XmlQualifiedName)o2; + XmlQualifiedName qn1 = (XmlQualifiedName)o1!; + XmlQualifiedName qn2 = (XmlQualifiedName)o2!; int ns = string.Compare(qn1.Namespace, qn2.Namespace, StringComparison.Ordinal); if (ns == 0) { @@ -56,12 +57,12 @@ public int Compare(object o1, object o2) internal class XmlSchemaObjectComparer : IComparer { private readonly QNameComparer _comparer = new QNameComparer(); - public int Compare(object o1, object o2) + public int Compare(object? o1, object? o2) { - return _comparer.Compare(NameOf((XmlSchemaObject)o1), NameOf((XmlSchemaObject)o2)); + return _comparer.Compare(NameOf((XmlSchemaObject?)o1), NameOf((XmlSchemaObject?)o2)); } - internal static XmlQualifiedName NameOf(XmlSchemaObject o) + internal static XmlQualifiedName NameOf(XmlSchemaObject? o) { if (o is XmlSchemaAttribute) { @@ -136,10 +137,10 @@ internal static XmlQualifiedName NameOf(XmlSchemaObjectCollection items) list.Add(NameOf(items[i])); } list.Sort(new QNameComparer()); - return (XmlQualifiedName)list[0]; + return (XmlQualifiedName)list[0]!; } - internal static string Namespace(XmlSchemaObject o) + internal static string? Namespace(XmlSchemaObject? o) { while (o != null && !(o is XmlSchema)) { @@ -161,7 +162,7 @@ private void WriteIndent() _w.Append(' '); } } - protected void WriteAttribute(string localName, string ns, string value) + protected void WriteAttribute(string localName, string ns, string? value) { if (value == null || value.Length == 0) return; @@ -211,7 +212,7 @@ private void WriteAttribute(XmlAttribute a) } } - private void WriteAttributes(XmlAttribute[] a, XmlSchemaObject o) + private void WriteAttributes(XmlAttribute[]? a, XmlSchemaObject o) { if (a == null) return; ArrayList attrs = new ArrayList(); @@ -222,12 +223,13 @@ private void WriteAttributes(XmlAttribute[] a, XmlSchemaObject o) attrs.Sort(new XmlAttributeComparer()); for (int i = 0; i < attrs.Count; i++) { - XmlAttribute attribute = (XmlAttribute)attrs[i]; + XmlAttribute attribute = (XmlAttribute)attrs[i]!; WriteAttribute(attribute); } } - internal static string ToString(NamespaceList list) + [return: NotNullIfNotNull("list")] + internal static string? ToString(NamespaceList? list) { if (list == null) return null; @@ -273,14 +275,14 @@ internal static string ToString(NamespaceList list) } } - internal string WriteXmlSchemaObject(XmlSchemaObject o) + internal string WriteXmlSchemaObject(XmlSchemaObject? o) { if (o == null) return string.Empty; - Write3_XmlSchemaObject((XmlSchemaObject)o); + Write3_XmlSchemaObject((XmlSchemaObject?)o); return GetString(); } - private void WriteSortedItems(XmlSchemaObjectCollection items) + private void WriteSortedItems(XmlSchemaObjectCollection? items) { if (items == null) return; @@ -292,18 +294,18 @@ private void WriteSortedItems(XmlSchemaObjectCollection items) list.Sort(new XmlSchemaObjectComparer()); for (int i = 0; i < list.Count; i++) { - Write3_XmlSchemaObject((XmlSchemaObject)list[i]); + Write3_XmlSchemaObject((XmlSchemaObject?)list[i]); } } - private void Write1_XmlSchemaAttribute(XmlSchemaAttribute o) + private void Write1_XmlSchemaAttribute(XmlSchemaAttribute? o) { - if ((object)o == null) return; + if ((object?)o == null) return; WriteStartElement("attribute"); - WriteAttribute(@"id", @"", ((string)o.@Id)); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); - WriteAttribute(@"default", @"", ((string)o.@DefaultValue)); - WriteAttribute(@"fixed", @"", ((string)o.@FixedValue)); + WriteAttribute(@"id", @"", ((string?)o.@Id)); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + WriteAttribute(@"default", @"", ((string?)o.@DefaultValue)); + WriteAttribute(@"fixed", @"", ((string?)o.@FixedValue)); if (o.Parent != null && !(o.Parent is XmlSchema)) { if (o.QualifiedName != null && !o.QualifiedName.IsEmpty && o.QualifiedName.Namespace != null && o.QualifiedName.Namespace.Length != 0) @@ -315,7 +317,7 @@ private void Write1_XmlSchemaAttribute(XmlSchemaAttribute o) WriteAttribute(@"form", @"", "unqualified"); } } - WriteAttribute(@"name", @"", ((string)o.@Name)); + WriteAttribute(@"name", @"", ((string?)o.@Name)); if (!o.RefName.IsEmpty) { @@ -327,14 +329,14 @@ private void Write1_XmlSchemaAttribute(XmlSchemaAttribute o) } XmlSchemaUse use = o.Use == XmlSchemaUse.None ? XmlSchemaUse.Optional : o.Use; WriteAttribute(@"use", @"", Write30_XmlSchemaUse(use)); - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); - Write9_XmlSchemaSimpleType((XmlSchemaSimpleType)o.@SchemaType); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); + Write9_XmlSchemaSimpleType((XmlSchemaSimpleType?)o.@SchemaType); WriteEndElement(); } - private void Write3_XmlSchemaObject(XmlSchemaObject o) + private void Write3_XmlSchemaObject(XmlSchemaObject? o) { - if ((object)o == null) return; + if ((object?)o == null) return; System.Type t = o.GetType(); if (t == typeof(XmlSchemaComplexType)) @@ -489,13 +491,13 @@ private void Write3_XmlSchemaObject(XmlSchemaObject o) } } - private void Write5_XmlSchemaAnnotation(XmlSchemaAnnotation o) + private void Write5_XmlSchemaAnnotation(XmlSchemaAnnotation? o) { - if ((object)o == null) return; + if ((object?)o == null) return; WriteStartElement("annotation"); - WriteAttribute(@"id", @"", ((string)o.@Id)); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); + WriteAttribute(@"id", @"", ((string?)o.@Id)); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); System.Xml.Schema.XmlSchemaObjectCollection a = (System.Xml.Schema.XmlSchemaObjectCollection)o.@Items; if (a != null) { @@ -520,9 +522,9 @@ private void Write6_XmlSchemaDocumentation(XmlSchemaDocumentation o) if ((object)o == null) return; WriteStartElement("documentation"); - WriteAttribute(@"source", @"", ((string)o.@Source)); - WriteAttribute(@"lang", @"http://www.w3.org/XML/1998/namespace", ((string)o.@Language)); - XmlNode[] a = (XmlNode[])o.@Markup; + WriteAttribute(@"source", @"", ((string?)o.@Source)); + WriteAttribute(@"lang", @"http://www.w3.org/XML/1998/namespace", ((string?)o.@Language)); + XmlNode[]? a = (XmlNode[]?)o.@Markup; if (a != null) { for (int ia = 0; ia < a.Length; ia++) @@ -535,13 +537,13 @@ private void Write6_XmlSchemaDocumentation(XmlSchemaDocumentation o) WriteEndElement(); } - private void Write7_XmlSchemaAppInfo(XmlSchemaAppInfo o) + private void Write7_XmlSchemaAppInfo(XmlSchemaAppInfo? o) { - if ((object)o == null) return; + if ((object?)o == null) return; WriteStartElement("appinfo"); WriteAttribute("source", "", o.Source); - XmlNode[] a = (XmlNode[])o.@Markup; + XmlNode[]? a = (XmlNode[]?)o.@Markup; if (a != null) { for (int ia = 0; ia < a.Length; ia++) @@ -554,16 +556,16 @@ private void Write7_XmlSchemaAppInfo(XmlSchemaAppInfo o) WriteEndElement(); } - private void Write9_XmlSchemaSimpleType(XmlSchemaSimpleType o) + private void Write9_XmlSchemaSimpleType(XmlSchemaSimpleType? o) { - if ((object)o == null) return; + if ((object?)o == null) return; WriteStartElement("simpleType"); - WriteAttribute(@"id", @"", ((string)o.@Id)); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); - WriteAttribute(@"name", @"", ((string)o.@Name)); + WriteAttribute(@"id", @"", ((string?)o.@Id)); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + WriteAttribute(@"name", @"", ((string?)o.@Name)); WriteAttribute(@"final", @"", Write11_XmlSchemaDerivationMethod(o.FinalResolved)); - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); if (o.@Content is XmlSchemaSimpleTypeUnion) { Write12_XmlSchemaSimpleTypeUnion((XmlSchemaSimpleTypeUnion)o.@Content); @@ -584,13 +586,13 @@ private string Write11_XmlSchemaDerivationMethod(XmlSchemaDerivationMethod v) return v.ToString(); } - private void Write12_XmlSchemaSimpleTypeUnion(XmlSchemaSimpleTypeUnion o) + private void Write12_XmlSchemaSimpleTypeUnion(XmlSchemaSimpleTypeUnion? o) { - if ((object)o == null) return; + if ((object?)o == null) return; WriteStartElement("union"); - WriteAttribute(@"id", @"", ((string)o.@Id)); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); + WriteAttribute(@"id", @"", ((string?)o.@Id)); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); if (o.MemberTypes != null) { @@ -606,12 +608,12 @@ private void Write12_XmlSchemaSimpleTypeUnion(XmlSchemaSimpleTypeUnion o) for (int i = 0; i < list.Count; i++) { - XmlQualifiedName q = (XmlQualifiedName)list[i]; + XmlQualifiedName q = (XmlQualifiedName)list[i]!; _w.Append(q.ToString()); _w.Append(','); } } - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); WriteSortedItems(o.@BaseTypes); WriteEndElement(); } @@ -621,34 +623,34 @@ private void Write14_XmlSchemaSimpleTypeList(XmlSchemaSimpleTypeList o) if ((object)o == null) return; WriteStartElement("list"); - WriteAttribute(@"id", @"", ((string)o.@Id)); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); + WriteAttribute(@"id", @"", ((string?)o.@Id)); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); if (!o.@ItemTypeName.IsEmpty) { WriteAttribute(@"itemType", @"", o.@ItemTypeName); } - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); - Write9_XmlSchemaSimpleType((XmlSchemaSimpleType)o.@ItemType); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); + Write9_XmlSchemaSimpleType((XmlSchemaSimpleType?)o.@ItemType); WriteEndElement(); } - private void Write15_XmlSchemaSimpleTypeRestriction(XmlSchemaSimpleTypeRestriction o) + private void Write15_XmlSchemaSimpleTypeRestriction(XmlSchemaSimpleTypeRestriction? o) { - if ((object)o == null) return; + if ((object?)o == null) return; WriteStartElement("restriction"); - WriteAttribute(@"id", @"", ((string)o.@Id)); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); + WriteAttribute(@"id", @"", ((string?)o.@Id)); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); if (!o.@BaseTypeName.IsEmpty) { WriteAttribute(@"base", @"", o.@BaseTypeName); } - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); - Write9_XmlSchemaSimpleType((XmlSchemaSimpleType)o.@BaseType); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); + Write9_XmlSchemaSimpleType((XmlSchemaSimpleType?)o.@BaseType); WriteFacets(o.Facets); WriteEndElement(); } - private void WriteFacets(XmlSchemaObjectCollection facets) + private void WriteFacets(XmlSchemaObjectCollection? facets) { if (facets == null) return; @@ -660,7 +662,7 @@ private void WriteFacets(XmlSchemaObjectCollection facets) a.Sort(new XmlFacetComparer()); for (int ia = 0; ia < a.Count; ia++) { - XmlSchemaObject ai = (XmlSchemaObject)a[ia]; + XmlSchemaObject? ai = (XmlSchemaObject?)a[ia]; if (ai is XmlSchemaMinExclusiveFacet) { Write_XmlSchemaFacet("minExclusive", (XmlSchemaFacet)ai); @@ -712,9 +714,9 @@ private void WriteFacets(XmlSchemaObjectCollection facets) } } - private void Write_XmlSchemaFacet(string name, XmlSchemaFacet o) + private void Write_XmlSchemaFacet(string name, XmlSchemaFacet? o) { - if ((object)o == null) return; + if ((object?)o == null) return; WriteStartElement(name); WriteAttribute("id", "", o.Id); @@ -723,14 +725,14 @@ private void Write_XmlSchemaFacet(string name, XmlSchemaFacet o) { WriteAttribute(@"fixed", @"", XmlConvert.ToString(o.IsFixed)); } - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); WriteEndElement(); } - private string Write30_XmlSchemaUse(XmlSchemaUse v) + private string? Write30_XmlSchemaUse(XmlSchemaUse v) { - string s = null; + string? s = null; switch (v) { case XmlSchemaUse.@Optional: s = @"optional"; break; @@ -741,53 +743,53 @@ private string Write30_XmlSchemaUse(XmlSchemaUse v) return s; } - private void Write31_XmlSchemaAttributeGroup(XmlSchemaAttributeGroup o) + private void Write31_XmlSchemaAttributeGroup(XmlSchemaAttributeGroup? o) { - if ((object)o == null) return; + if ((object?)o == null) return; WriteStartElement("attributeGroup"); - WriteAttribute(@"id", @"", ((string)o.@Id)); - WriteAttribute(@"name", @"", ((string)o.@Name)); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); + WriteAttribute(@"id", @"", ((string?)o.@Id)); + WriteAttribute(@"name", @"", ((string?)o.@Name)); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); WriteSortedItems(o.Attributes); - Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute)o.@AnyAttribute); + Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute?)o.@AnyAttribute); WriteEndElement(); } - private void Write32_XmlSchemaAttributeGroupRef(XmlSchemaAttributeGroupRef o) + private void Write32_XmlSchemaAttributeGroupRef(XmlSchemaAttributeGroupRef? o) { - if ((object)o == null) return; + if ((object?)o == null) return; WriteStartElement("attributeGroup"); - WriteAttribute(@"id", @"", ((string)o.@Id)); + WriteAttribute(@"id", @"", ((string?)o.@Id)); if (!o.RefName.IsEmpty) { WriteAttribute("ref", "", o.RefName); } - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); WriteEndElement(); } - private void Write33_XmlSchemaAnyAttribute(XmlSchemaAnyAttribute o) + private void Write33_XmlSchemaAnyAttribute(XmlSchemaAnyAttribute? o) { - if ((object)o == null) return; + if ((object?)o == null) return; WriteStartElement("anyAttribute"); - WriteAttribute(@"id", @"", ((string)o.@Id)); + WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttribute("namespace", "", ToString(o.NamespaceList)); XmlSchemaContentProcessing process = o.@ProcessContents == XmlSchemaContentProcessing.@None ? XmlSchemaContentProcessing.Strict : o.@ProcessContents; WriteAttribute(@"processContents", @"", Write34_XmlSchemaContentProcessing(process)); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); WriteEndElement(); } - private string Write34_XmlSchemaContentProcessing(XmlSchemaContentProcessing v) + private string? Write34_XmlSchemaContentProcessing(XmlSchemaContentProcessing v) { - string s = null; + string? s = null; switch (v) { case XmlSchemaContentProcessing.@Skip: s = @"skip"; break; @@ -803,8 +805,8 @@ private void Write35_XmlSchemaComplexType(XmlSchemaComplexType o) if ((object)o == null) return; WriteStartElement("complexType"); - WriteAttribute(@"id", @"", ((string)o.@Id)); - WriteAttribute(@"name", @"", ((string)o.@Name)); + WriteAttribute(@"id", @"", ((string?)o.@Id)); + WriteAttribute(@"name", @"", ((string?)o.@Name)); WriteAttribute(@"final", @"", Write11_XmlSchemaDerivationMethod(o.FinalResolved)); if (((bool)o.@IsAbstract) != false) { @@ -815,8 +817,8 @@ private void Write35_XmlSchemaComplexType(XmlSchemaComplexType o) { WriteAttribute(@"mixed", @"", XmlConvert.ToString((bool)((bool)o.@IsMixed))); } - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); if (o.@ContentModel is XmlSchemaComplexContent) { Write41_XmlSchemaComplexContent((XmlSchemaComplexContent)o.@ContentModel); @@ -842,18 +844,18 @@ private void Write35_XmlSchemaComplexType(XmlSchemaComplexType o) Write43_XmlSchemaAll((XmlSchemaAll)o.@Particle); } WriteSortedItems(o.Attributes); - Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute)o.@AnyAttribute); + Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute?)o.@AnyAttribute); WriteEndElement(); } - private void Write36_XmlSchemaSimpleContent(XmlSchemaSimpleContent o) + private void Write36_XmlSchemaSimpleContent(XmlSchemaSimpleContent? o) { - if ((object)o == null) return; + if ((object?)o == null) return; WriteStartElement("simpleContent"); - WriteAttribute(@"id", @"", ((string)o.@Id)); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); + WriteAttribute(@"id", @"", ((string?)o.@Id)); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); if (o.@Content is XmlSchemaSimpleContentRestriction) { Write40_XmlSchemaSimpleContentRestriction((XmlSchemaSimpleContentRestriction)o.@Content); @@ -870,45 +872,45 @@ private void Write38_XmlSchemaSimpleContentExtension(XmlSchemaSimpleContentExten if ((object)o == null) return; WriteStartElement("extension"); - WriteAttribute(@"id", @"", ((string)o.@Id)); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); + WriteAttribute(@"id", @"", ((string?)o.@Id)); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); if (!o.@BaseTypeName.IsEmpty) { WriteAttribute(@"base", @"", o.@BaseTypeName); } - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); WriteSortedItems(o.Attributes); - Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute)o.@AnyAttribute); + Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute?)o.@AnyAttribute); WriteEndElement(); } - private void Write40_XmlSchemaSimpleContentRestriction(XmlSchemaSimpleContentRestriction o) + private void Write40_XmlSchemaSimpleContentRestriction(XmlSchemaSimpleContentRestriction? o) { - if ((object)o == null) return; + if ((object?)o == null) return; WriteStartElement("restriction"); - WriteAttribute(@"id", @"", ((string)o.@Id)); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); + WriteAttribute(@"id", @"", ((string?)o.@Id)); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); if (!o.@BaseTypeName.IsEmpty) { WriteAttribute(@"base", @"", o.@BaseTypeName); } - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); - Write9_XmlSchemaSimpleType((XmlSchemaSimpleType)o.@BaseType); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); + Write9_XmlSchemaSimpleType((XmlSchemaSimpleType?)o.@BaseType); WriteFacets(o.Facets); WriteSortedItems(o.Attributes); - Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute)o.@AnyAttribute); + Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute?)o.@AnyAttribute); WriteEndElement(); } - private void Write41_XmlSchemaComplexContent(XmlSchemaComplexContent o) + private void Write41_XmlSchemaComplexContent(XmlSchemaComplexContent? o) { - if ((object)o == null) return; + if ((object?)o == null) return; WriteStartElement("complexContent"); - WriteAttribute(@"id", @"", ((string)o.@Id)); + WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttribute(@"mixed", @"", XmlConvert.ToString((bool)((bool)o.@IsMixed))); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); if (o.@Content is XmlSchemaComplexContentRestriction) { Write56_XmlSchemaComplexContentRestriction((XmlSchemaComplexContentRestriction)o.@Content); @@ -920,18 +922,18 @@ private void Write41_XmlSchemaComplexContent(XmlSchemaComplexContent o) WriteEndElement(); } - private void Write42_XmlSchemaComplexContentExtension(XmlSchemaComplexContentExtension o) + private void Write42_XmlSchemaComplexContentExtension(XmlSchemaComplexContentExtension? o) { - if ((object)o == null) return; + if ((object?)o == null) return; WriteStartElement("extension"); - WriteAttribute(@"id", @"", ((string)o.@Id)); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); + WriteAttribute(@"id", @"", ((string?)o.@Id)); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); if (!o.@BaseTypeName.IsEmpty) { WriteAttribute(@"base", @"", o.@BaseTypeName); } - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); if (o.@Particle is XmlSchemaSequence) { Write54_XmlSchemaSequence((XmlSchemaSequence)o.@Particle); @@ -949,7 +951,7 @@ private void Write42_XmlSchemaComplexContentExtension(XmlSchemaComplexContentExt Write43_XmlSchemaAll((XmlSchemaAll)o.@Particle); } WriteSortedItems(o.Attributes); - Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute)o.@AnyAttribute); + Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute?)o.@AnyAttribute); WriteEndElement(); } @@ -958,18 +960,18 @@ private void Write43_XmlSchemaAll(XmlSchemaAll o) if ((object)o == null) return; WriteStartElement("all"); - WriteAttribute(@"id", @"", ((string)o.@Id)); + WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs)); WriteAttribute("maxOccurs", "", o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs)); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); WriteSortedItems(o.@Items); WriteEndElement(); } - private void Write46_XmlSchemaElement(XmlSchemaElement o) + private void Write46_XmlSchemaElement(XmlSchemaElement? o) { - if ((object)o == null) return; + if ((object?)o == null) return; System.Type t = o.GetType(); WriteStartElement("element"); WriteAttribute(@"id", @"", o.Id); @@ -1015,7 +1017,7 @@ private void Write46_XmlSchemaElement(XmlSchemaElement o) WriteAttribute("type", "", o.SchemaTypeName); } - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); Write5_XmlSchemaAnnotation(o.Annotation); if (o.SchemaType is XmlSchemaComplexType) { @@ -1029,16 +1031,16 @@ private void Write46_XmlSchemaElement(XmlSchemaElement o) WriteEndElement(); } - private void Write47_XmlSchemaKey(XmlSchemaKey o) + private void Write47_XmlSchemaKey(XmlSchemaKey? o) { - if ((object)o == null) return; + if ((object?)o == null) return; System.Type t = o.GetType(); WriteStartElement("key"); - WriteAttribute(@"id", @"", ((string)o.@Id)); - WriteAttribute(@"name", @"", ((string)o.@Name)); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); - Write49_XmlSchemaXPath(@"selector", @"", (XmlSchemaXPath)o.@Selector); + WriteAttribute(@"id", @"", ((string?)o.@Id)); + WriteAttribute(@"name", @"", ((string?)o.@Name)); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); + Write49_XmlSchemaXPath(@"selector", @"", (XmlSchemaXPath?)o.@Selector); { XmlSchemaObjectCollection a = (XmlSchemaObjectCollection)o.@Fields; if (a != null) @@ -1052,9 +1054,9 @@ private void Write47_XmlSchemaKey(XmlSchemaKey o) WriteEndElement(); } - private void Write48_XmlSchemaIdentityConstraint(XmlSchemaIdentityConstraint o) + private void Write48_XmlSchemaIdentityConstraint(XmlSchemaIdentityConstraint? o) { - if ((object)o == null) return; + if ((object?)o == null) return; System.Type t = o.GetType(); if (t == typeof(XmlSchemaUnique)) { @@ -1073,30 +1075,30 @@ private void Write48_XmlSchemaIdentityConstraint(XmlSchemaIdentityConstraint o) } } - private void Write49_XmlSchemaXPath(string name, string ns, XmlSchemaXPath o) + private void Write49_XmlSchemaXPath(string name, string ns, XmlSchemaXPath? o) { - if ((object)o == null) return; + if ((object?)o == null) return; WriteStartElement(name); WriteAttribute(@"id", @"", o.@Id); WriteAttribute(@"xpath", @"", o.@XPath); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); WriteEndElement(); } - private void Write50_XmlSchemaKeyref(XmlSchemaKeyref o) + private void Write50_XmlSchemaKeyref(XmlSchemaKeyref? o) { - if ((object)o == null) return; + if ((object?)o == null) return; System.Type t = o.GetType(); WriteStartElement("keyref"); - WriteAttribute(@"id", @"", ((string)o.@Id)); - WriteAttribute(@"name", @"", ((string)o.@Name)); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); + WriteAttribute(@"id", @"", ((string?)o.@Id)); + WriteAttribute(@"name", @"", ((string?)o.@Name)); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); // UNDONE compare reference here WriteAttribute(@"refer", @"", o.@Refer); - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); - Write49_XmlSchemaXPath(@"selector", @"", (XmlSchemaXPath)o.@Selector); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); + Write49_XmlSchemaXPath(@"selector", @"", (XmlSchemaXPath?)o.@Selector); { XmlSchemaObjectCollection a = (XmlSchemaObjectCollection)o.@Fields; if (a != null) @@ -1110,17 +1112,17 @@ private void Write50_XmlSchemaKeyref(XmlSchemaKeyref o) WriteEndElement(); } - private void Write51_XmlSchemaUnique(XmlSchemaUnique o) + private void Write51_XmlSchemaUnique(XmlSchemaUnique? o) { - if ((object)o == null) return; + if ((object?)o == null) return; System.Type t = o.GetType(); WriteStartElement("unique"); - WriteAttribute(@"id", @"", ((string)o.@Id)); - WriteAttribute(@"name", @"", ((string)o.@Name)); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); - Write49_XmlSchemaXPath("selector", "", (XmlSchemaXPath)o.@Selector); + WriteAttribute(@"id", @"", ((string?)o.@Id)); + WriteAttribute(@"name", @"", ((string?)o.@Name)); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); + Write49_XmlSchemaXPath("selector", "", (XmlSchemaXPath?)o.@Selector); XmlSchemaObjectCollection a = (XmlSchemaObjectCollection)o.@Fields; if (a != null) { @@ -1132,24 +1134,24 @@ private void Write51_XmlSchemaUnique(XmlSchemaUnique o) WriteEndElement(); } - private void Write52_XmlSchemaChoice(XmlSchemaChoice o) + private void Write52_XmlSchemaChoice(XmlSchemaChoice? o) { - if ((object)o == null) return; + if ((object?)o == null) return; System.Type t = o.GetType(); WriteStartElement("choice"); - WriteAttribute(@"id", @"", ((string)o.@Id)); + WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs)); WriteAttribute(@"maxOccurs", @"", o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs)); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); WriteSortedItems(o.@Items); WriteEndElement(); } - private void Write53_XmlSchemaAny(XmlSchemaAny o) + private void Write53_XmlSchemaAny(XmlSchemaAny? o) { - if ((object)o == null) return; + if ((object?)o == null) return; WriteStartElement("any"); WriteAttribute(@"id", @"", o.@Id); @@ -1158,21 +1160,21 @@ private void Write53_XmlSchemaAny(XmlSchemaAny o) WriteAttribute(@"namespace", @"", ToString(o.NamespaceList)); XmlSchemaContentProcessing process = o.@ProcessContents == XmlSchemaContentProcessing.@None ? XmlSchemaContentProcessing.Strict : o.@ProcessContents; WriteAttribute(@"processContents", @"", Write34_XmlSchemaContentProcessing(process)); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); WriteEndElement(); } - private void Write54_XmlSchemaSequence(XmlSchemaSequence o) + private void Write54_XmlSchemaSequence(XmlSchemaSequence? o) { - if ((object)o == null) return; + if ((object?)o == null) return; WriteStartElement("sequence"); - WriteAttribute(@"id", @"", ((string)o.@Id)); + WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs)); WriteAttribute("maxOccurs", "", o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs)); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); XmlSchemaObjectCollection a = (XmlSchemaObjectCollection)o.@Items; if (a != null) { @@ -1204,12 +1206,12 @@ private void Write54_XmlSchemaSequence(XmlSchemaSequence o) WriteEndElement(); } - private void Write55_XmlSchemaGroupRef(XmlSchemaGroupRef o) + private void Write55_XmlSchemaGroupRef(XmlSchemaGroupRef? o) { - if ((object)o == null) return; + if ((object?)o == null) return; WriteStartElement("group"); - WriteAttribute(@"id", @"", ((string)o.@Id)); + WriteAttribute(@"id", @"", ((string?)o.@Id)); WriteAttribute("minOccurs", "", XmlConvert.ToString(o.MinOccurs)); WriteAttribute(@"maxOccurs", @"", o.MaxOccurs == decimal.MaxValue ? "unbounded" : XmlConvert.ToString(o.MaxOccurs)); @@ -1217,25 +1219,25 @@ private void Write55_XmlSchemaGroupRef(XmlSchemaGroupRef o) { WriteAttribute("ref", "", o.RefName); } - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); WriteEndElement(); } - private void Write56_XmlSchemaComplexContentRestriction(XmlSchemaComplexContentRestriction o) + private void Write56_XmlSchemaComplexContentRestriction(XmlSchemaComplexContentRestriction? o) { - if ((object)o == null) return; + if ((object?)o == null) return; WriteStartElement("restriction"); - WriteAttribute(@"id", @"", ((string)o.@Id)); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); + WriteAttribute(@"id", @"", ((string?)o.@Id)); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); if (!o.@BaseTypeName.IsEmpty) { WriteAttribute(@"base", @"", o.@BaseTypeName); } - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); if (o.@Particle is XmlSchemaSequence) { Write54_XmlSchemaSequence((XmlSchemaSequence)o.@Particle); @@ -1253,19 +1255,19 @@ private void Write56_XmlSchemaComplexContentRestriction(XmlSchemaComplexContentR Write43_XmlSchemaAll((XmlSchemaAll)o.@Particle); } WriteSortedItems(o.Attributes); - Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute)o.@AnyAttribute); + Write33_XmlSchemaAnyAttribute((XmlSchemaAnyAttribute?)o.@AnyAttribute); WriteEndElement(); } - private void Write57_XmlSchemaGroup(XmlSchemaGroup o) + private void Write57_XmlSchemaGroup(XmlSchemaGroup? o) { - if ((object)o == null) return; + if ((object?)o == null) return; WriteStartElement("group"); - WriteAttribute(@"id", @"", ((string)o.@Id)); - WriteAttribute(@"name", @"", ((string)o.@Name)); - WriteAttributes((XmlAttribute[])o.@UnhandledAttributes, o); - Write5_XmlSchemaAnnotation((XmlSchemaAnnotation)o.@Annotation); + WriteAttribute(@"id", @"", ((string?)o.@Id)); + WriteAttribute(@"name", @"", ((string?)o.@Name)); + WriteAttributes((XmlAttribute[]?)o.@UnhandledAttributes, o); + Write5_XmlSchemaAnnotation((XmlSchemaAnnotation?)o.@Annotation); if (o.@Particle is XmlSchemaSequence) { Write54_XmlSchemaSequence((XmlSchemaSequence)o.@Particle); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapAttributeAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapAttributeAttribute.cs index fea02f71483475..5ba74b764905f9 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapAttributeAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapAttributeAttribute.cs @@ -1,16 +1,18 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; + using System.Diagnostics.CodeAnalysis; [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue)] public class SoapAttributeAttribute : System.Attribute { - private string _attributeName; - private string _ns; - private string _dataType; + private string? _attributeName; + private string? _ns; + private string? _dataType; public SoapAttributeAttribute() { @@ -21,18 +23,20 @@ public SoapAttributeAttribute(string attributeName) _attributeName = attributeName; } + [AllowNull] public string AttributeName { get { return _attributeName == null ? string.Empty : _attributeName; } set { _attributeName = value; } } - public string Namespace + public string? Namespace { get { return _ns; } set { _ns = value; } } + [AllowNull] public string DataType { get { return _dataType == null ? string.Empty : _dataType; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapAttributeOverrides.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapAttributeOverrides.cs index 38f970be4558ed..cc2538ebedf319 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapAttributeOverrides.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapAttributeOverrides.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System.Reflection; @@ -21,7 +22,7 @@ public void Add(Type type, SoapAttributes attributes) public void Add(Type type, string member, SoapAttributes attributes) { - Hashtable members = (Hashtable)_types[type]; + Hashtable? members = (Hashtable?)_types[type]; if (members == null) { members = new Hashtable(); @@ -34,7 +35,7 @@ public void Add(Type type, string member, SoapAttributes attributes) members.Add(member, attributes); } - public SoapAttributes this[Type type] + public SoapAttributes? this[Type type] { get { @@ -42,13 +43,13 @@ public SoapAttributes this[Type type] } } - public SoapAttributes this[Type type, string member] + public SoapAttributes? this[Type type, string member] { get { - Hashtable members = (Hashtable)_types[type]; + Hashtable? members = (Hashtable?)_types[type]; if (members == null) return null; - return (SoapAttributes)members[member]; + return (SoapAttributes?)members[member]; } } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapAttributes.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapAttributes.cs index f632645a9c4951..0d57c9755fea88 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapAttributes.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapAttributes.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; @@ -20,11 +21,11 @@ internal enum SoapAttributeFlags public class SoapAttributes { private bool _soapIgnore; - private SoapTypeAttribute _soapType; - private SoapElementAttribute _soapElement; - private SoapAttributeAttribute _soapAttribute; - private SoapEnumAttribute _soapEnum; - private object _soapDefaultValue; + private SoapTypeAttribute? _soapType; + private SoapElementAttribute? _soapElement; + private SoapAttributeAttribute? _soapAttribute; + private SoapEnumAttribute? _soapEnum; + private object? _soapDefaultValue; public SoapAttributes() { @@ -89,13 +90,13 @@ internal SoapAttributeFlags GetSoapFlags() return SoapFlags; } - public SoapTypeAttribute SoapType + public SoapTypeAttribute? SoapType { get { return _soapType; } set { _soapType = value; } } - public SoapEnumAttribute SoapEnum + public SoapEnumAttribute? SoapEnum { get { return _soapEnum; } set { _soapEnum = value; } @@ -107,19 +108,19 @@ public bool SoapIgnore set { _soapIgnore = value; } } - public SoapElementAttribute SoapElement + public SoapElementAttribute? SoapElement { get { return _soapElement; } set { _soapElement = value; } } - public SoapAttributeAttribute SoapAttribute + public SoapAttributeAttribute? SoapAttribute { get { return _soapAttribute; } set { _soapAttribute = value; } } - public object SoapDefaultValue + public object? SoapDefaultValue { get { return _soapDefaultValue; } set { _soapDefaultValue = value; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapElementAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapElementAttribute.cs index ed56eb1ffccee4..98975be0429eed 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapElementAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapElementAttribute.cs @@ -1,15 +1,17 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; + using System.Diagnostics.CodeAnalysis; [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue)] public class SoapElementAttribute : System.Attribute { - private string _elementName; - private string _dataType; + private string? _elementName; + private string? _dataType; private bool _nullable; public SoapElementAttribute() @@ -21,12 +23,14 @@ public SoapElementAttribute(string elementName) _elementName = elementName; } + [AllowNull] public string ElementName { get { return _elementName == null ? string.Empty : _elementName; } set { _elementName = value; } } + [AllowNull] public string DataType { get { return _dataType == null ? string.Empty : _dataType; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapEnumAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapEnumAttribute.cs index 606ec240d0ed9b..23c86a4080df5a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapEnumAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapEnumAttribute.cs @@ -1,14 +1,16 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; + using System.Diagnostics.CodeAnalysis; [AttributeUsage(AttributeTargets.Field)] public class SoapEnumAttribute : System.Attribute { - private string _name; + private string? _name; public SoapEnumAttribute() { @@ -19,6 +21,7 @@ public SoapEnumAttribute(string name) _name = name; } + [AllowNull] public string Name { get { return _name == null ? string.Empty : _name; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapIgnoreAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapIgnoreAttribute.cs index 23c6971bbdda1d..2fdd91dc5b2533 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapIgnoreAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapIgnoreAttribute.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapIncludeAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapIncludeAttribute.cs index 1b66ac7409e761..1c41a6bf5b3c32 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapIncludeAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapIncludeAttribute.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapReflectionImporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapReflectionImporter.cs index 42cc5acdb9adcc..4963f64508a799 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapReflectionImporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapReflectionImporter.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System.Reflection; @@ -19,7 +20,7 @@ public class SoapReflectionImporter private readonly SoapAttributeOverrides _attributeOverrides; private readonly NameTable _types = new NameTable(); // xmltypename + xmlns -> Mapping private readonly NameTable _nullables = new NameTable(); // xmltypename + xmlns -> NullableMapping - private StructMapping _root; + private StructMapping? _root; private readonly string _defaultNs; private readonly ModelScope _modelScope; @@ -27,15 +28,15 @@ public SoapReflectionImporter() : this(null, null) { } - public SoapReflectionImporter(string defaultNamespace) : this(null, defaultNamespace) + public SoapReflectionImporter(string? defaultNamespace) : this(null, defaultNamespace) { } - public SoapReflectionImporter(SoapAttributeOverrides attributeOverrides) : this(attributeOverrides, null) + public SoapReflectionImporter(SoapAttributeOverrides? attributeOverrides) : this(attributeOverrides, null) { } - public SoapReflectionImporter(SoapAttributeOverrides attributeOverrides, string defaultNamespace) + public SoapReflectionImporter(SoapAttributeOverrides? attributeOverrides, string? defaultNamespace) { if (defaultNamespace == null) defaultNamespace = string.Empty; @@ -76,7 +77,7 @@ public XmlTypeMapping ImportTypeMapping(Type type) return ImportTypeMapping(type, null); } - public XmlTypeMapping ImportTypeMapping(Type type, string defaultNamespace) + public XmlTypeMapping ImportTypeMapping(Type type, string? defaultNamespace) { ElementAccessor element = new ElementAccessor(); element.IsSoap = true; @@ -129,14 +130,14 @@ private Exception ReflectionException(string context, Exception e) private SoapAttributes GetAttributes(Type type) { - SoapAttributes attrs = _attributeOverrides[type]; + SoapAttributes? attrs = _attributeOverrides[type]; if (attrs != null) return attrs; return new SoapAttributes(type); } private SoapAttributes GetAttributes(MemberInfo memberInfo) { - SoapAttributes attrs = _attributeOverrides[memberInfo.DeclaringType, memberInfo.Name]; + SoapAttributes? attrs = _attributeOverrides[memberInfo.DeclaringType!, memberInfo.Name]; if (attrs != null) return attrs; return new SoapAttributes(memberInfo); } @@ -154,7 +155,7 @@ private TypeMapping ImportTypeMapping(TypeModel model, string dataType, Recursio { throw new InvalidOperationException(SR.Format(SR.XmlInvalidDataTypeUsage, dataType, "SoapElementAttribute.DataType")); } - TypeDesc td = _typeScope.GetTypeDesc(dataType, XmlSchema.Namespace); + TypeDesc? td = _typeScope.GetTypeDesc(dataType!, XmlSchema.Namespace); if (td == null) { throw new InvalidOperationException(SR.Format(SR.XmlInvalidXsdDataType, dataType, "SoapElementAttribute.DataType", new XmlQualifiedName(dataType, XmlSchema.Namespace).ToString())); @@ -185,17 +186,17 @@ private TypeMapping ImportTypeMapping(TypeModel model, string dataType, Recursio case TypeKind.Struct: if (model.TypeDesc.IsOptionalValue) { - TypeDesc baseTypeDesc = model.TypeDesc.BaseTypeDesc; - SoapAttributes baseAttributes = GetAttributes(baseTypeDesc.Type); + TypeDesc? baseTypeDesc = model.TypeDesc.BaseTypeDesc; + SoapAttributes baseAttributes = GetAttributes(baseTypeDesc!.Type!); string typeNs = _defaultNs; if (baseAttributes.SoapType != null && baseAttributes.SoapType.Namespace != null) typeNs = baseAttributes.SoapType.Namespace; - TypeDesc valueTypeDesc = string.IsNullOrEmpty(dataType) ? model.TypeDesc.BaseTypeDesc : _typeScope.GetTypeDesc(dataType, XmlSchema.Namespace); - string xsdTypeName = string.IsNullOrEmpty(dataType) ? model.TypeDesc.BaseTypeDesc.Name : dataType; - TypeMapping baseMapping = GetTypeMapping(xsdTypeName, typeNs, valueTypeDesc); + TypeDesc valueTypeDesc = string.IsNullOrEmpty(dataType) ? model.TypeDesc.BaseTypeDesc! : _typeScope.GetTypeDesc(dataType, XmlSchema.Namespace)!; + string xsdTypeName = string.IsNullOrEmpty(dataType) ? model.TypeDesc.BaseTypeDesc!.Name : dataType; + TypeMapping? baseMapping = GetTypeMapping(xsdTypeName, typeNs, valueTypeDesc); if (baseMapping == null) - baseMapping = ImportTypeMapping(_modelScope.GetTypeModel(baseTypeDesc.Type), dataType, limiter); - return CreateNullableMapping(baseMapping, model.TypeDesc.Type); + baseMapping = ImportTypeMapping(_modelScope.GetTypeModel(baseTypeDesc.Type!), dataType, limiter); + return CreateNullableMapping(baseMapping, model.TypeDesc.Type!); } else { @@ -229,19 +230,19 @@ private StructMapping GetRootMapping() return _root; } - private TypeMapping GetTypeMapping(string typeName, string ns, TypeDesc typeDesc) + private TypeMapping? GetTypeMapping(string typeName, string ns, TypeDesc typeDesc) { - TypeMapping mapping = (TypeMapping)_types[typeName, ns]; + TypeMapping? mapping = (TypeMapping?)_types[typeName, ns]; if (mapping == null) return null; if (mapping.TypeDesc != typeDesc) - throw new InvalidOperationException(SR.Format(SR.XmlTypesDuplicate, typeDesc.FullName, mapping.TypeDesc.FullName, typeName, ns)); + throw new InvalidOperationException(SR.Format(SR.XmlTypesDuplicate, typeDesc.FullName, mapping.TypeDesc!.FullName, typeName, ns)); return mapping; } private NullableMapping CreateNullableMapping(TypeMapping baseMapping, Type type) { - TypeDesc typeDesc = baseMapping.TypeDesc.GetNullableTypeDesc(type); - TypeMapping existingMapping = (TypeMapping)_nullables[baseMapping.TypeName, baseMapping.Namespace]; + TypeDesc typeDesc = baseMapping.TypeDesc!.GetNullableTypeDesc(type); + TypeMapping? existingMapping = (TypeMapping?)_nullables[baseMapping.TypeName!, baseMapping.Namespace]; NullableMapping mapping; if (existingMapping != null) { @@ -256,12 +257,12 @@ private NullableMapping CreateNullableMapping(TypeMapping baseMapping, Type type } else { - throw new InvalidOperationException(SR.Format(SR.XmlTypesDuplicate, typeDesc.FullName, existingMapping.TypeDesc.FullName, typeDesc.Name, existingMapping.Namespace)); + throw new InvalidOperationException(SR.Format(SR.XmlTypesDuplicate, typeDesc.FullName, existingMapping.TypeDesc!.FullName, typeDesc.Name, existingMapping.Namespace)); } } else if (!(baseMapping is PrimitiveMapping)) { - throw new InvalidOperationException(SR.Format(SR.XmlTypesDuplicate, typeDesc.FullName, existingMapping.TypeDesc.FullName, typeDesc.Name, existingMapping.Namespace)); + throw new InvalidOperationException(SR.Format(SR.XmlTypesDuplicate, typeDesc.FullName, existingMapping.TypeDesc!.FullName, typeDesc.Name, existingMapping.Namespace)); } } mapping = new NullableMapping(); @@ -287,7 +288,7 @@ private StructMapping ImportStructLikeMapping(StructModel model, RecursionLimite string typeName = XsdTypeName(model.Type, a, model.TypeDesc.Name); typeName = XmlConvert.EncodeLocalName(typeName); - StructMapping mapping = (StructMapping)GetTypeMapping(typeName, typeNs, model.TypeDesc); + StructMapping? mapping = (StructMapping?)GetTypeMapping(typeName, typeNs, model.TypeDesc); if (mapping == null) { mapping = new StructMapping(); @@ -339,10 +340,10 @@ private bool InitializeStructMembers(StructMapping mapping, StructModel model, R return true; if (model.TypeDesc.BaseTypeDesc != null) { - StructMapping baseMapping = ImportStructLikeMapping((StructModel)_modelScope.GetTypeModel(model.Type.BaseType, false), limiter); + StructMapping baseMapping = ImportStructLikeMapping((StructModel)_modelScope.GetTypeModel(model.Type.BaseType!, false), limiter); // check to see if the import of the baseMapping was deferred - int baseIndex = limiter.DeferredWorkItems.IndexOf(mapping.BaseMapping); + int baseIndex = limiter.DeferredWorkItems.IndexOf(mapping.BaseMapping!); if (baseIndex < 0) { mapping.BaseMapping = baseMapping; @@ -372,12 +373,12 @@ private bool InitializeStructMembers(StructMapping mapping, StructModel model, R continue; SoapAttributes memberAttrs = GetAttributes(memberInfo); if (memberAttrs.SoapIgnore) continue; - FieldModel fieldModel = model.GetFieldModel(memberInfo); + FieldModel? fieldModel = model.GetFieldModel(memberInfo); if (fieldModel == null) continue; - MemberMapping member = ImportFieldMapping(fieldModel, memberAttrs, mapping.Namespace, limiter); + MemberMapping? member = ImportFieldMapping(fieldModel, memberAttrs, mapping.Namespace!, limiter); if (member == null) continue; - if (!member.TypeDesc.IsPrimitive && !member.TypeDesc.IsEnum && !member.TypeDesc.IsOptionalValue) + if (!member.TypeDesc!.IsPrimitive && !member.TypeDesc.IsEnum && !member.TypeDesc.IsOptionalValue) { if (model.TypeDesc.IsValueType) throw new NotSupportedException(SR.Format(SR.XmlRpcRefsInValueType, model.TypeDesc.FullName)); @@ -386,7 +387,7 @@ private bool InitializeStructMembers(StructMapping mapping, StructModel model, R } if (mapping.BaseMapping != null) { - if (mapping.BaseMapping.Declares(member, mapping.TypeName)) continue; + if (mapping.BaseMapping.Declares(member, mapping.TypeName!)) continue; } members.Add(member); } @@ -404,7 +405,7 @@ private ArrayMapping ImportArrayLikeMapping(ArrayModel model, RecursionLimiter l mapping.IsSoap = true; TypeMapping itemTypeMapping = ImportTypeMapping(model.Element, limiter); - if (itemTypeMapping.TypeDesc.IsValueType && !itemTypeMapping.TypeDesc.IsPrimitive && !itemTypeMapping.TypeDesc.IsEnum) + if (itemTypeMapping.TypeDesc!.IsValueType && !itemTypeMapping.TypeDesc.IsPrimitive && !itemTypeMapping.TypeDesc.IsEnum) throw new NotSupportedException(SR.Format(SR.XmlRpcArrayOfValueTypes, model.TypeDesc.FullName)); mapping.TypeDesc = model.TypeDesc; @@ -415,7 +416,7 @@ private ArrayMapping ImportArrayLikeMapping(ArrayModel model, RecursionLimiter l // in the case of an ArrayMapping we can have more that one mapping correspond to a type // examples of that are ArrayList and object[] both will map tp ArrayOfur-type // so we create a link list for all mappings of the same XSD type - ArrayMapping existingMapping = (ArrayMapping)_types[mapping.TypeName, mapping.Namespace]; + ArrayMapping? existingMapping = (ArrayMapping?)_types[mapping.TypeName!, mapping.Namespace]; if (existingMapping != null) { ArrayMapping first = existingMapping; @@ -426,7 +427,7 @@ private ArrayMapping ImportArrayLikeMapping(ArrayModel model, RecursionLimiter l existingMapping = existingMapping.Next; } mapping.Next = first; - _types[mapping.TypeName, mapping.Namespace] = mapping; + _types[mapping.TypeName!, mapping.Namespace] = mapping; return mapping; } _typeScope.AddTypeMapping(mapping); @@ -443,26 +444,26 @@ private void SetArrayMappingType(ArrayMapping mapping) string itemTypeName; string itemTypeNamespace; - TypeMapping itemTypeMapping; - if (mapping.Elements.Length == 1) + TypeMapping? itemTypeMapping; + if (mapping.Elements!.Length == 1) itemTypeMapping = mapping.Elements[0].Mapping; else itemTypeMapping = null; if (itemTypeMapping is EnumMapping) { - itemTypeNamespace = itemTypeMapping.Namespace; - itemTypeName = itemTypeMapping.TypeName; + itemTypeNamespace = itemTypeMapping.Namespace!; + itemTypeName = itemTypeMapping.TypeName!; } else if (itemTypeMapping is PrimitiveMapping) { - itemTypeNamespace = itemTypeMapping.TypeDesc.IsXsdType ? XmlSchema.Namespace : UrtTypes.Namespace; - itemTypeName = itemTypeMapping.TypeDesc.DataType.Name; + itemTypeNamespace = itemTypeMapping.TypeDesc!.IsXsdType ? XmlSchema.Namespace : UrtTypes.Namespace; + itemTypeName = itemTypeMapping.TypeDesc.DataType!.Name!; useDefaultNs = true; } else if (itemTypeMapping is StructMapping) { - if (itemTypeMapping.TypeDesc.IsRoot) + if (itemTypeMapping.TypeDesc!.IsRoot) { itemTypeNamespace = XmlSchema.Namespace; itemTypeName = Soap.UrType; @@ -470,25 +471,25 @@ private void SetArrayMappingType(ArrayMapping mapping) } else { - itemTypeNamespace = itemTypeMapping.Namespace; - itemTypeName = itemTypeMapping.TypeName; + itemTypeNamespace = itemTypeMapping.Namespace!; + itemTypeName = itemTypeMapping.TypeName!; } } else if (itemTypeMapping is ArrayMapping) { - itemTypeNamespace = itemTypeMapping.Namespace; - itemTypeName = itemTypeMapping.TypeName; + itemTypeNamespace = itemTypeMapping.Namespace!; + itemTypeName = itemTypeMapping.TypeName!; } else { - throw new InvalidOperationException(SR.Format(SR.XmlInvalidSoapArray, mapping.TypeDesc.FullName)); + throw new InvalidOperationException(SR.Format(SR.XmlInvalidSoapArray, mapping.TypeDesc!.FullName)); } itemTypeName = CodeIdentifier.MakePascal(itemTypeName); string uniqueName = "ArrayOf" + itemTypeName; string ns = useDefaultNs ? _defaultNs : itemTypeNamespace; int i = 1; - TypeMapping existingMapping = (TypeMapping)_types[uniqueName, ns]; + TypeMapping? existingMapping = (TypeMapping?)_types[uniqueName, ns]; while (existingMapping != null) { if (existingMapping is ArrayMapping) @@ -501,7 +502,7 @@ private void SetArrayMappingType(ArrayMapping mapping) } // need to re-name the mapping uniqueName = itemTypeName + i.ToString(CultureInfo.InvariantCulture); - existingMapping = (TypeMapping)_types[uniqueName, ns]; + existingMapping = (TypeMapping?)_types[uniqueName, ns]; i++; } mapping.Namespace = ns; @@ -529,7 +530,7 @@ private PrimitiveMapping ImportPrimitiveMapping(PrimitiveModel model, string dat { mapping.TypeDesc = model.TypeDesc; } - mapping.TypeName = mapping.TypeDesc.DataType.Name; + mapping.TypeName = mapping.TypeDesc.DataType!.Name; mapping.Namespace = mapping.TypeDesc.IsXsdType ? XmlSchema.Namespace : UrtTypes.Namespace; return mapping; } @@ -543,7 +544,7 @@ private EnumMapping ImportEnumMapping(EnumModel model) string typeName = XsdTypeName(model.Type, a, model.TypeDesc.Name); typeName = XmlConvert.EncodeLocalName(typeName); - EnumMapping mapping = (EnumMapping)GetTypeMapping(typeName, typeNs, model.TypeDesc); + EnumMapping? mapping = (EnumMapping?)GetTypeMapping(typeName, typeNs, model.TypeDesc); if (mapping == null) { mapping = new EnumMapping(); @@ -557,7 +558,7 @@ private EnumMapping ImportEnumMapping(EnumModel model) ArrayList constants = new ArrayList(); for (int i = 0; i < model.Constants.Length; i++) { - ConstantMapping constant = ImportConstantMapping(model.Constants[i]); + ConstantMapping? constant = ImportConstantMapping(model.Constants[i]); if (constant != null) constants.Add(constant); } if (constants.Count == 0) @@ -569,7 +570,7 @@ private EnumMapping ImportEnumMapping(EnumModel model) return mapping; } - private ConstantMapping ImportConstantMapping(ConstantModel model) + private ConstantMapping? ImportConstantMapping(ConstantModel model) { SoapAttributes a = GetAttributes(model.FieldInfo); if (a.SoapIgnore) return null; @@ -595,13 +596,13 @@ private MembersMapping ImportMembersMapping(XmlReflectionMember[] xmlReflectionM try { XmlReflectionMember member = xmlReflectionMembers[i]; - MemberMapping mapping = ImportMemberMapping(member, ns, xmlReflectionMembers, hasWrapperElement ? XmlSchemaForm.Unqualified : XmlSchemaForm.Qualified, limiter); + MemberMapping? mapping = ImportMemberMapping(member, ns, xmlReflectionMembers, hasWrapperElement ? XmlSchemaForm.Unqualified : XmlSchemaForm.Qualified, limiter); if (member.IsReturnValue && writeAccessors) { // no special treatment for return values with doc/enc if (i > 0) throw new InvalidOperationException(SR.XmlInvalidReturnPosition); - mapping.IsReturnValue = true; + mapping!.IsReturnValue = true; } - mappings[i] = mapping; + mappings[i] = mapping!; } catch (Exception e) { @@ -625,7 +626,7 @@ private MembersMapping ImportMembersMapping(XmlReflectionMember[] xmlReflectionM return members; } - private MemberMapping ImportMemberMapping(XmlReflectionMember xmlReflectionMember, string ns, XmlReflectionMember[] xmlReflectionMembers, XmlSchemaForm form, RecursionLimiter limiter) + private MemberMapping? ImportMemberMapping(XmlReflectionMember xmlReflectionMember, string ns, XmlReflectionMember[] xmlReflectionMembers, XmlSchemaForm form, RecursionLimiter limiter) { SoapAttributes a = xmlReflectionMember.SoapAttributes; if (a.SoapIgnore) return null; @@ -633,17 +634,17 @@ private MemberMapping ImportMemberMapping(XmlReflectionMember xmlReflectionMembe member.IsSoap = true; member.Name = xmlReflectionMember.MemberName; bool checkSpecified = XmlReflectionImporter.FindSpecifiedMember(xmlReflectionMember.MemberName, xmlReflectionMembers) != null; - FieldModel model = new FieldModel(xmlReflectionMember.MemberName, xmlReflectionMember.MemberType, _typeScope.GetTypeDesc(xmlReflectionMember.MemberType), checkSpecified, false); + FieldModel model = new FieldModel(xmlReflectionMember.MemberName, xmlReflectionMember.MemberType!, _typeScope.GetTypeDesc(xmlReflectionMember.MemberType!), checkSpecified, false); member.CheckShouldPersist = model.CheckShouldPersist; member.CheckSpecified = model.CheckSpecified; member.ReadOnly = model.ReadOnly; // || !model.FieldTypeDesc.HasDefaultConstructor; ImportAccessorMapping(member, model, a, ns, form, limiter); if (xmlReflectionMember.OverrideIsNullable) - member.Elements[0].IsNullable = false; + member.Elements![0].IsNullable = false; return member; } - private MemberMapping ImportFieldMapping(FieldModel model, SoapAttributes a, string ns, RecursionLimiter limiter) + private MemberMapping? ImportFieldMapping(FieldModel model, SoapAttributes a, string ns, RecursionLimiter limiter) { if (a.SoapIgnore) return null; MemberMapping member = new MemberMapping(); @@ -659,7 +660,7 @@ private MemberMapping ImportFieldMapping(FieldModel model, SoapAttributes a, str return member; } - private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, SoapAttributes a, string ns, XmlSchemaForm form, RecursionLimiter limiter) + private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, SoapAttributes a, string? ns, XmlSchemaForm form, RecursionLimiter limiter) { Type accessorType = model.FieldType; string accessorName = model.Name; @@ -704,7 +705,7 @@ private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, Soa } } - private static ElementAccessor CreateElementAccessor(TypeMapping mapping, string ns) + private static ElementAccessor CreateElementAccessor(TypeMapping mapping, string? ns) { ElementAccessor element = new ElementAccessor(); element.IsSoap = true; @@ -714,7 +715,7 @@ private static ElementAccessor CreateElementAccessor(TypeMapping mapping, string return element; } - private object GetDefaultValue(TypeDesc fieldTypeDesc, SoapAttributes a) + private object? GetDefaultValue(TypeDesc fieldTypeDesc, SoapAttributes a) { if (a.SoapDefaultValue == null || a.SoapDefaultValue == DBNull.Value) return null; if (!(fieldTypeDesc.Kind == TypeKind.Primitive || fieldTypeDesc.Kind == TypeKind.Enum)) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapSchemamember.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapSchemamember.cs index 886ec02af9b97a..8eba2817bfcee9 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapSchemamember.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapSchemamember.cs @@ -1,14 +1,16 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; + using System.Diagnostics.CodeAnalysis; using System.Xml; public class SoapSchemaMember { - private string _memberName; + private string? _memberName; private XmlQualifiedName _type = XmlQualifiedName.Empty; public XmlQualifiedName MemberType @@ -17,6 +19,7 @@ public XmlQualifiedName MemberType set { _type = value; } } + [AllowNull] public string MemberName { get { return _memberName == null ? string.Empty : _memberName; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapTypeAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapTypeAttribute.cs index 2c205e8d6844b6..b19407178c68cd 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapTypeAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapTypeAttribute.cs @@ -1,15 +1,17 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; + using System.Diagnostics.CodeAnalysis; [AttributeUsage(AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Struct)] public class SoapTypeAttribute : System.Attribute { - private string _ns; - private string _typeName; + private string? _ns; + private string? _typeName; private bool _includeInSchema = true; public SoapTypeAttribute() @@ -33,13 +35,14 @@ public bool IncludeInSchema set { _includeInSchema = value; } } + [AllowNull] public string TypeName { get { return _typeName == null ? string.Empty : _typeName; } set { _typeName = value; } } - public string Namespace + public string? Namespace { get { return _ns; } set { _ns = value; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SourceInfo.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SourceInfo.cs index d510ba55f422de..ff16ce43b56768 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SourceInfo.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SourceInfo.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; using System.Collections; using System.Diagnostics; @@ -25,16 +26,16 @@ internal class SourceInfo return typeof(IList).GetMethod( "get_Item", new Type[] { typeof(int) } - ); + )!; }); public string Source; public readonly string Arg; - public readonly MemberInfo MemberInfo; - public readonly Type Type; + public readonly MemberInfo? MemberInfo; + public readonly Type? Type; public readonly CodeGenerator ILG; - public SourceInfo(string source, string arg, MemberInfo memberInfo, Type type, CodeGenerator ilg) + public SourceInfo(string source, string? arg, MemberInfo? memberInfo, Type? type, CodeGenerator ilg) { this.Source = source; this.Arg = arg ?? source; @@ -45,20 +46,20 @@ public SourceInfo(string source, string arg, MemberInfo memberInfo, Type type, C public SourceInfo CastTo(TypeDesc td) { - return new SourceInfo("((" + td.CSharpName + ")" + Source + ")", Arg, MemberInfo, td.Type, ILG); + return new SourceInfo("((" + td.CSharpName + ")" + Source + ")", Arg, MemberInfo, td.Type!, ILG); } - public void LoadAddress(Type elementType) + public void LoadAddress(Type? elementType) { InternalLoad(elementType, asAddress: true); } - public void Load(Type elementType) + public void Load(Type? elementType) { InternalLoad(elementType); } - private void InternalLoad(Type elementType, bool asAddress = false) + private void InternalLoad(Type? elementType, bool asAddress = false) { Match match = s_regex.Match(Arg); if (match.Success) @@ -70,11 +71,11 @@ private void InternalLoad(Type elementType, bool asAddress = false) { ILG.Load(varA); ILG.Load(varIA); - Type eType = varType.GetElementType(); + Type eType = varType.GetElementType()!; if (CodeGenerator.IsNullableGenericType(eType)) { ILG.Ldelema(eType); - ConvertNullableValue(eType, elementType); + ConvertNullableValue(eType, elementType!); } else { @@ -100,7 +101,7 @@ private void InternalLoad(Type elementType, bool asAddress = false) "get_Item", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(int) } - ); + )!; if (get_Item == null && typeof(IList).IsAssignableFrom(varType)) { @@ -115,7 +116,7 @@ private void InternalLoad(Type elementType, bool asAddress = false) LocalBuilder localTmp = ILG.GetTempLocal(eType); ILG.Stloc(localTmp); ILG.Ldloca(localTmp); - ConvertNullableValue(eType, elementType); + ConvertNullableValue(eType, elementType!); } else if ((elementType != null) && !(eType.IsAssignableFrom(elementType) || elementType.IsAssignableFrom(eType))) { @@ -171,7 +172,7 @@ private void InternalLoad(Type elementType, bool asAddress = false) if (CodeGenerator.IsNullableGenericType(memberType)) { ILG.LoadMemberAddress(MemberInfo); - ConvertNullableValue(memberType, elementType); + ConvertNullableValue(memberType, elementType!); } else { @@ -185,19 +186,19 @@ private void InternalLoad(Type elementType, bool asAddress = false) if (match.Success) { Debug.Assert(match.Groups["arg"].Value == Arg); - Debug.Assert(match.Groups["cast"].Value == CodeIdentifier.GetCSharpName(Type)); + Debug.Assert(match.Groups["cast"].Value == CodeIdentifier.GetCSharpName(Type!)); if (asAddress) - ILG.ConvertAddress(varType, Type); + ILG.ConvertAddress(varType, Type!); else - ILG.ConvertValue(varType, Type); - varType = Type; + ILG.ConvertValue(varType, Type!); + varType = Type!; } - Convert(varType, elementType, asAddress); + Convert(varType!, elementType, asAddress); } } } - private void Convert(Type sourceType, Type targetType, bool asAddress) + private void Convert(Type sourceType, Type? targetType, bool asAddress) { if (targetType != null) { @@ -217,7 +218,7 @@ private void ConvertNullableValue(Type nullableType, Type targetType) "get_Value", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ILG.Call(Nullable_get_Value); if (targetType != null) { @@ -231,25 +232,25 @@ public static implicit operator string(SourceInfo source) return source.Source; } - public static bool operator !=(SourceInfo a, SourceInfo b) + public static bool operator !=(SourceInfo? a, SourceInfo? b) { - if ((object)a != null) + if ((object?)a != null) return !a.Equals(b); - return (object)b != null; + return (object?)b != null; } - public static bool operator ==(SourceInfo a, SourceInfo b) + public static bool operator ==(SourceInfo? a, SourceInfo? b) { - if ((object)a != null) + if ((object?)a != null) return a.Equals(b); - return (object)b == null; + return (object?)b == null; } - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (obj == null) return Source == null; - SourceInfo info = obj as SourceInfo; + SourceInfo? info = obj as SourceInfo; if (info != null) return Source == info.Source; return false; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/TypeCode.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/TypeCode.cs index ccdd17406242fe..e980e75935be73 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/TypeCode.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/TypeCode.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/TypeExtensions.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/TypeExtensions.cs index 19db82bdb3b8d4..bde6ff093bd432 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/TypeExtensions.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/TypeExtensions.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; @@ -10,7 +11,7 @@ internal static class TypeExtensions { private const string ImplicitCastOperatorName = "op_Implicit"; - public static bool TryConvertTo(this Type targetType, object data, out object returnValue) + public static bool TryConvertTo(this Type targetType, object? data, out object? returnValue) { if (targetType == null) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Types.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Types.cs index db42b0d1f316d6..02739759f465d0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Types.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Types.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; @@ -66,22 +67,22 @@ internal class TypeDesc { private readonly string _name; private readonly string _fullName; - private string _cSharpName; - private TypeDesc _arrayElementTypeDesc; - private TypeDesc _arrayTypeDesc; - private TypeDesc _nullableTypeDesc; + private string? _cSharpName; + private TypeDesc? _arrayElementTypeDesc; + private TypeDesc? _arrayTypeDesc; + private TypeDesc? _nullableTypeDesc; private readonly TypeKind _kind; - private readonly XmlSchemaType _dataType; - private Type _type; - private TypeDesc _baseTypeDesc; + private readonly XmlSchemaType? _dataType; + private Type? _type; + private TypeDesc? _baseTypeDesc; private TypeFlags _flags; - private readonly string _formatterName; + private readonly string? _formatterName; private readonly bool _isXsdType; private bool _isMixed; private int _weight; - private Exception _exception; + private Exception? _exception; - internal TypeDesc(string name, string fullName, XmlSchemaType dataType, TypeKind kind, TypeDesc baseTypeDesc, TypeFlags flags, string formatterName) + internal TypeDesc(string name, string fullName, XmlSchemaType? dataType, TypeKind kind, TypeDesc? baseTypeDesc, TypeFlags flags, string? formatterName) { _name = name.Replace('+', '.'); _fullName = fullName.Replace('+', '.'); @@ -101,17 +102,17 @@ internal TypeDesc(string name, string fullName, XmlSchemaType dataType, TypeKind _formatterName = formatterName; } - internal TypeDesc(string name, string fullName, TypeKind kind, TypeDesc baseTypeDesc, TypeFlags flags) - : this(name, fullName, (XmlSchemaType)null, kind, baseTypeDesc, flags, null) + internal TypeDesc(string name, string fullName, TypeKind kind, TypeDesc? baseTypeDesc, TypeFlags flags) + : this(name, fullName, (XmlSchemaType?)null, kind, baseTypeDesc, flags, null) { } internal TypeDesc(Type type, bool isXsdType, XmlSchemaType dataType, string formatterName, TypeFlags flags) - : this(type.Name, type.FullName, dataType, TypeKind.Primitive, (TypeDesc)null, flags, formatterName) + : this(type!.Name, type.FullName!, dataType, TypeKind.Primitive, (TypeDesc?)null, flags, formatterName) { _isXsdType = isXsdType; _type = type; } - internal TypeDesc(Type type, string name, string fullName, TypeKind kind, TypeDesc baseTypeDesc, TypeFlags flags, TypeDesc arrayElementTypeDesc) + internal TypeDesc(Type? type, string name, string fullName, TypeKind kind, TypeDesc? baseTypeDesc, TypeFlags flags, TypeDesc? arrayElementTypeDesc) : this(name, fullName, null, kind, baseTypeDesc, flags, null) { _arrayElementTypeDesc = arrayElementTypeDesc; @@ -160,17 +161,17 @@ internal string CSharpName } } - internal XmlSchemaType DataType + internal XmlSchemaType? DataType { get { return _dataType; } } - internal Type Type + internal Type? Type { get { return _type; } } - internal string FormatterName + internal string? FormatterName { get { return _formatterName; } } @@ -341,7 +342,7 @@ internal bool ConstructorInaccessible get { return (_flags & TypeFlags.CtorInaccessible) != 0; } } - internal Exception Exception + internal Exception? Exception { get { return _exception; } set { _exception = value; } @@ -388,7 +389,7 @@ internal void CheckNeedConstructor() } } - internal TypeDesc ArrayElementTypeDesc + internal TypeDesc? ArrayElementTypeDesc { get { return _arrayElementTypeDesc; } set { _arrayElementTypeDesc = value; } @@ -406,7 +407,7 @@ internal TypeDesc CreateArrayTypeDesc() return _arrayTypeDesc; } - internal TypeDesc BaseTypeDesc + internal TypeDesc? BaseTypeDesc { get { return _baseTypeDesc; } set @@ -418,7 +419,7 @@ internal TypeDesc BaseTypeDesc internal bool IsDerivedFrom(TypeDesc baseTypeDesc) { - TypeDesc typeDesc = this; + TypeDesc? typeDesc = this; while (typeDesc != null) { if (typeDesc == baseTypeDesc) return true; @@ -427,10 +428,10 @@ internal bool IsDerivedFrom(TypeDesc baseTypeDesc) return baseTypeDesc.IsRoot; } - internal static TypeDesc FindCommonBaseTypeDesc(TypeDesc[] typeDescs) + internal static TypeDesc? FindCommonBaseTypeDesc(TypeDesc[] typeDescs) { if (typeDescs.Length == 0) return null; - TypeDesc leastDerivedTypeDesc = null; + TypeDesc? leastDerivedTypeDesc = null; int leastDerivedLevel = int.MaxValue; for (int i = 0; i < typeDescs.Length; i++) @@ -656,14 +657,14 @@ private static void AddSoapEncodedPrimitive(Type type, string dataTypeName, stri AddNonXsdPrimitive(type, dataTypeName, ns, formatterName, baseTypeName, Array.Empty(), flags); } - internal TypeDesc GetTypeDesc(string name, string ns) + internal TypeDesc? GetTypeDesc(string name, string ns) { return GetTypeDesc(name, ns, TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue | TypeFlags.CanBeAttributeValue); } - internal TypeDesc GetTypeDesc(string name, string ns, TypeFlags flags) + internal TypeDesc? GetTypeDesc(string name, string? ns, TypeFlags flags) { - TypeDesc typeDesc = (TypeDesc)s_primitiveNames[name, ns]; + TypeDesc? typeDesc = (TypeDesc?)s_primitiveNames[name, ns]; if (typeDesc != null) { if ((typeDesc.Flags & flags) != 0) @@ -674,9 +675,9 @@ internal TypeDesc GetTypeDesc(string name, string ns, TypeFlags flags) return null; } - internal TypeDesc GetTypeDesc(XmlSchemaSimpleType dataType) + internal TypeDesc? GetTypeDesc(XmlSchemaSimpleType dataType) { - return (TypeDesc)s_primitiveDataTypes[dataType]; + return (TypeDesc?)s_primitiveDataTypes[dataType]; } internal TypeDesc GetTypeDesc(Type type) @@ -684,21 +685,21 @@ internal TypeDesc GetTypeDesc(Type type) return GetTypeDesc(type, null, true, true); } - internal TypeDesc GetTypeDesc(Type type, MemberInfo source, bool directReference) + internal TypeDesc GetTypeDesc(Type type, MemberInfo? source, bool directReference) { return GetTypeDesc(type, source, directReference, true); } - internal TypeDesc GetTypeDesc(Type type, MemberInfo source, bool directReference, bool throwOnError) + internal TypeDesc GetTypeDesc(Type type, MemberInfo? source, bool directReference, bool throwOnError) { if (type.ContainsGenericParameters) { throw new InvalidOperationException(SR.Format(SR.XmlUnsupportedOpenGenericType, type)); } - TypeDesc typeDesc = (TypeDesc)s_primitiveTypes[type]; + TypeDesc? typeDesc = (TypeDesc?)s_primitiveTypes[type]; if (typeDesc == null) { - typeDesc = (TypeDesc)_typeDescs[type]; + typeDesc = (TypeDesc?)_typeDescs[type]; if (typeDesc == null) { typeDesc = ImportTypeDesc(type, source, directReference); @@ -713,7 +714,7 @@ internal TypeDesc GetTypeDesc(Type type, MemberInfo source, bool directReference internal TypeDesc GetArrayTypeDesc(Type type) { - TypeDesc typeDesc = (TypeDesc)_arrayTypeDescs[type]; + TypeDesc? typeDesc = (TypeDesc?)_arrayTypeDescs[type]; if (typeDesc == null) { typeDesc = GetTypeDesc(type); @@ -725,7 +726,7 @@ internal TypeDesc GetArrayTypeDesc(Type type) return typeDesc; } - internal TypeMapping GetTypeMappingFromTypeDesc(TypeDesc typeDesc) + internal TypeMapping? GetTypeMappingFromTypeDesc(TypeDesc typeDesc) { foreach (TypeMapping typeMapping in TypeMappings) { @@ -735,7 +736,7 @@ internal TypeMapping GetTypeMappingFromTypeDesc(TypeDesc typeDesc) return null; } - internal Type GetTypeFromTypeDesc(TypeDesc typeDesc) + internal Type? GetTypeFromTypeDesc(TypeDesc typeDesc) { if (typeDesc.Type != null) return typeDesc.Type; @@ -747,14 +748,14 @@ internal Type GetTypeFromTypeDesc(TypeDesc typeDesc) return null; } - private TypeDesc ImportTypeDesc(Type type, MemberInfo memberInfo, bool directReference) + private TypeDesc ImportTypeDesc(Type type, MemberInfo? memberInfo, bool directReference) { - TypeDesc typeDesc = null; + TypeDesc? typeDesc = null; TypeKind kind; - Type arrayElementType = null; - Type baseType = null; + Type? arrayElementType = null; + Type? baseType = null; TypeFlags flags = 0; - Exception exception = null; + Exception? exception = null; if (!type.IsVisible) { @@ -814,7 +815,7 @@ private TypeDesc ImportTypeDesc(Type type, MemberInfo memberInfo, bool directRef else if (typeof(ICollection).IsAssignableFrom(type) && !IsArraySegment(type)) { kind = TypeKind.Collection; - arrayElementType = GetCollectionElementType(type, memberInfo == null ? null : memberInfo.DeclaringType.FullName + "." + memberInfo.Name); + arrayElementType = GetCollectionElementType(type, memberInfo == null ? null : memberInfo.DeclaringType!.FullName + "." + memberInfo.Name); flags |= GetConstructorFlags(type, ref exception); } else if (type == typeof(XmlQualifiedName)) @@ -887,7 +888,7 @@ private TypeDesc ImportTypeDesc(Type type, MemberInfo memberInfo, bool directRef } else { - exception = new NotSupportedException(SR.Format(SR.XmlUnsupportedInterfaceDetails, memberInfo.DeclaringType.FullName + "." + memberInfo.Name, type.FullName)); + exception = new NotSupportedException(SR.Format(SR.XmlUnsupportedInterfaceDetails, memberInfo.DeclaringType!.FullName + "." + memberInfo.Name, type.FullName)); } } } @@ -948,7 +949,7 @@ private TypeDesc ImportTypeDesc(Type type, MemberInfo memberInfo, bool directRef } if (type.IsNestedPublic) { - for (Type t = type.DeclaringType; t != null && !t.ContainsGenericParameters && !(t.IsAbstract && t.IsSealed); t = t.DeclaringType) + for (Type? t = type.DeclaringType; t != null && !t.ContainsGenericParameters && !(t.IsAbstract && t.IsSealed); t = t.DeclaringType) GetTypeDesc(t, null, false); } return typeDesc; @@ -981,7 +982,7 @@ internal static string TypeName(Type t) { if (t.IsArray) { - return "ArrayOf" + TypeName(t.GetElementType()); + return "ArrayOf" + TypeName(t.GetElementType()!); } else if (t.IsGenericType) { @@ -1012,7 +1013,7 @@ internal static string TypeName(Type t) return t.Name; } - internal static Type GetArrayElementType(Type type, string memberInfo) + internal static Type? GetArrayElementType(Type type, string? memberInfo) { if (type.IsArray) return type.GetElementType(); @@ -1032,7 +1033,7 @@ internal static Type GetArrayElementType(Type type, string memberInfo) internal static MemberMapping[] GetAllMembers(StructMapping mapping) { if (mapping.BaseMapping == null) - return mapping.Members; + return mapping.Members!; ArrayList list = new ArrayList(); GetAllMembers(mapping, list); return (MemberMapping[])list.ToArray(typeof(MemberMapping)); @@ -1044,7 +1045,7 @@ internal static void GetAllMembers(StructMapping mapping, ArrayList list) { GetAllMembers(mapping.BaseMapping, list); } - for (int i = 0; i < mapping.Members.Length; i++) + for (int i = 0; i < mapping.Members!.Length; i++) { list.Add(mapping.Members[i]); } @@ -1075,9 +1076,9 @@ private static void GetSettableMembers(StructMapping mapping, ArrayList list) { foreach (MemberMapping memberMapping in mapping.Members) { - MemberInfo memberInfo = memberMapping.MemberInfo; - PropertyInfo propertyInfo = memberInfo as PropertyInfo; - if (propertyInfo != null && !CanWriteProperty(propertyInfo, memberMapping.TypeDesc)) + MemberInfo? memberInfo = memberMapping.MemberInfo; + PropertyInfo? propertyInfo = memberInfo as PropertyInfo; + if (propertyInfo != null && !CanWriteProperty(propertyInfo, memberMapping.TypeDesc!)) { throw new InvalidOperationException(SR.Format(SR.XmlReadOnlyPropertyError, propertyInfo.DeclaringType, propertyInfo.Name)); } @@ -1112,11 +1113,11 @@ private static void PopulateMemberInfos(StructMapping structMapping, MemberMappi memberInfos.Clear(); for (int i = 0; i < mappings.Length; ++i) { - memberInfos[mappings[i].Name] = mappings[i].MemberInfo; + memberInfos[mappings[i].Name] = mappings[i].MemberInfo!; if (mappings[i].ChoiceIdentifier != null) - memberInfos[mappings[i].ChoiceIdentifier.MemberName] = mappings[i].ChoiceIdentifier.MemberInfo; + memberInfos[mappings[i].ChoiceIdentifier!.MemberName!] = mappings[i].ChoiceIdentifier!.MemberInfo!; if (mappings[i].CheckSpecifiedMemberInfo != null) - memberInfos[mappings[i].Name + "Specified"] = mappings[i].CheckSpecifiedMemberInfo; + memberInfos[mappings[i].Name + "Specified"] = mappings[i].CheckSpecifiedMemberInfo!; } // The scenario here is that user has one base class A and one derived class B and wants to serialize/deserialize an object of B. @@ -1127,11 +1128,11 @@ private static void PopulateMemberInfos(StructMapping structMapping, MemberMappi // If so, replace the one on the base class with the one on the derived class. // 2) Do the same thing for the memberMapping array. Note that we need to create a new copy of MemberMapping object since the old one could still be referenced // by the StructMapping of the baseclass, so updating it directly could lead to other issues. - Dictionary replaceList = null; - MemberInfo replacedInfo = null; + Dictionary? replaceList = null; + MemberInfo? replacedInfo = null; foreach (KeyValuePair pair in memberInfos) { - if (ShouldBeReplaced(pair.Value, structMapping.TypeDesc.Type, out replacedInfo)) + if (ShouldBeReplaced(pair.Value, structMapping.TypeDesc!.Type!, out replacedInfo)) { if (replaceList == null) { @@ -1150,7 +1151,7 @@ private static void PopulateMemberInfos(StructMapping structMapping, MemberMappi } for (int i = 0; i < mappings.Length; i++) { - if (replaceList.TryGetValue(mappings[i].Name, out MemberInfo mi)) + if (replaceList.TryGetValue(mappings[i].Name, out MemberInfo? mi)) { MemberMapping newMapping = mappings[i].Clone(); newMapping.MemberInfo = mi; @@ -1164,7 +1165,7 @@ private static bool ShouldBeReplaced(MemberInfo memberInfoToBeReplaced, Type der { replacedInfo = memberInfoToBeReplaced; Type currentType = derivedType; - Type typeToBeReplaced = memberInfoToBeReplaced.DeclaringType; + Type typeToBeReplaced = memberInfoToBeReplaced.DeclaringType!; if (typeToBeReplaced.IsAssignableFrom(currentType)) { @@ -1180,9 +1181,9 @@ private static bool ShouldBeReplaced(MemberInfo memberInfoToBeReplaced, Type der replacedInfo = info; if (replacedInfo != memberInfoToBeReplaced) { - if (!info.GetMethod.IsPublic + if (!info.GetMethod!.IsPublic && memberInfoToBeReplaced is PropertyInfo - && ((PropertyInfo)memberInfoToBeReplaced).GetMethod.IsPublic + && ((PropertyInfo)memberInfoToBeReplaced).GetMethod!.IsPublic ) { break; @@ -1207,16 +1208,16 @@ private static bool ShouldBeReplaced(MemberInfo memberInfoToBeReplaced, Type der } // we go one level down and try again - currentType = currentType.BaseType; + currentType = currentType.BaseType!; } } return false; } - private static TypeFlags GetConstructorFlags(Type type, ref Exception exception) + private static TypeFlags GetConstructorFlags(Type type, ref Exception? exception) { - ConstructorInfo ctor = type.GetConstructor(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic, Array.Empty()); + ConstructorInfo? ctor = type.GetConstructor(BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic, Array.Empty()); if (ctor != null) { TypeFlags flags = TypeFlags.HasDefaultConstructor; @@ -1239,11 +1240,11 @@ private static TypeFlags GetConstructorFlags(Type type, ref Exception exception) return 0; } - private static Type GetEnumeratorElementType(Type type, ref TypeFlags flags) + private static Type? GetEnumeratorElementType(Type type, ref TypeFlags flags) { if (typeof(IEnumerable).IsAssignableFrom(type)) { - MethodInfo enumerator = type.GetMethod("GetEnumerator", Array.Empty()); + MethodInfo? enumerator = type.GetMethod("GetEnumerator", Array.Empty()); if (enumerator == null || !typeof(IEnumerator).IsAssignableFrom(enumerator.ReturnType)) { @@ -1277,10 +1278,10 @@ private static Type GetEnumeratorElementType(Type type, ref TypeFlags flags) XmlAttributes methodAttrs = new XmlAttributes(enumerator); if (methodAttrs.XmlIgnore) return null; - PropertyInfo p = enumerator.ReturnType.GetProperty("Current"); + PropertyInfo? p = enumerator.ReturnType.GetProperty("Current"); Type currentType = (p == null ? typeof(object) : p.PropertyType); - MethodInfo addMethod = type.GetMethod("Add", new Type[] { currentType }); + MethodInfo? addMethod = type.GetMethod("Add", new Type[] { currentType }); if (addMethod == null && currentType != typeof(object)) { @@ -1299,7 +1300,7 @@ private static Type GetEnumeratorElementType(Type type, ref TypeFlags flags) } } - internal static PropertyInfo GetDefaultIndexer(Type type, string memberInfo) + internal static PropertyInfo GetDefaultIndexer(Type type, string? memberInfo) { if (typeof(IDictionary).IsAssignableFrom(type)) { @@ -1314,10 +1315,10 @@ internal static PropertyInfo GetDefaultIndexer(Type type, string memberInfo) } MemberInfo[] defaultMembers = type.GetDefaultMembers(); - PropertyInfo indexer = null; + PropertyInfo? indexer = null; if (defaultMembers != null && defaultMembers.Length > 0) { - for (Type t = type; t != null; t = t.BaseType) + for (Type? t = type; t != null; t = t.BaseType) { for (int i = 0; i < defaultMembers.Length; i++) { @@ -1326,7 +1327,7 @@ internal static PropertyInfo GetDefaultIndexer(Type type, string memberInfo) PropertyInfo defaultProp = (PropertyInfo)defaultMembers[i]; if (defaultProp.DeclaringType != t) continue; if (!defaultProp.CanRead) continue; - MethodInfo getMethod = defaultProp.GetMethod; + MethodInfo getMethod = defaultProp.GetMethod!; ParameterInfo[] parameters = getMethod.GetParameters(); if (parameters.Length == 1 && parameters[0].ParameterType == typeof(int)) { @@ -1342,19 +1343,19 @@ internal static PropertyInfo GetDefaultIndexer(Type type, string memberInfo) { throw new InvalidOperationException(SR.Format(SR.XmlNoDefaultAccessors, type.FullName)); } - MethodInfo addMethod = type.GetMethod("Add", new Type[] { indexer.PropertyType }); + MethodInfo? addMethod = type.GetMethod("Add", new Type[] { indexer.PropertyType }); if (addMethod == null) { throw new InvalidOperationException(SR.Format(SR.XmlNoAddMethod, type.FullName, indexer.PropertyType, "ICollection")); } return indexer; } - private static Type GetCollectionElementType(Type type, string memberInfo) + private static Type GetCollectionElementType(Type type, string? memberInfo) { return GetDefaultIndexer(type, memberInfo).PropertyType; } - internal static XmlQualifiedName ParseWsdlArrayType(string type, out string dims, XmlSchemaObject parent) + internal static XmlQualifiedName ParseWsdlArrayType(string type, out string dims, XmlSchemaObject? parent) { string ns; string name; @@ -1384,7 +1385,7 @@ internal static XmlQualifiedName ParseWsdlArrayType(string type, out string dims { if (parent.Namespaces != null) { - if (parent.Namespaces.Namespaces.TryGetValue(ns, out string wsdlNs) && wsdlNs != null) + if (parent.Namespaces.Namespaces.TryGetValue(ns, out string? wsdlNs) && wsdlNs != null) { ns = wsdlNs; break; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAnyAttributeAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAnyAttributeAttribute.cs index 8a1d0316bd616c..b57cbffc68df7a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAnyAttributeAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAnyAttributeAttribute.cs @@ -1,10 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; using System.Xml.Schema; - namespace System.Xml.Serialization { /// diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAnyElementAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAnyElementAttribute.cs index ee7d71dd895562..9308f5c8d4ac68 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAnyElementAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAnyElementAttribute.cs @@ -1,10 +1,11 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; +using System.Diagnostics.CodeAnalysis; using System.Xml.Schema; - namespace System.Xml.Serialization { /// @@ -13,8 +14,8 @@ namespace System.Xml.Serialization [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true)] public class XmlAnyElementAttribute : System.Attribute { - private string _name; - private string _ns; + private string? _name; + private string? _ns; private int _order = -1; private bool _nsSpecified; @@ -46,6 +47,7 @@ public XmlAnyElementAttribute(string name, string ns) /// /// [To be supplied.] /// + [AllowNull] public string Name { get { return _name == null ? string.Empty : _name; } @@ -55,7 +57,7 @@ public string Name /// /// [To be supplied.] /// - public string Namespace + public string? Namespace { get { return _ns; } set diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAnyElementAttributes.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAnyElementAttributes.cs index 76b4216ce37c3f..ee3796482a3591 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAnyElementAttributes.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAnyElementAttributes.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; @@ -16,16 +17,16 @@ public class XmlAnyElementAttributes : CollectionBase /// /// [To be supplied.] /// - public XmlAnyElementAttribute this[int index] + public XmlAnyElementAttribute? this[int index] { - get { return (XmlAnyElementAttribute)List[index]; } + get { return (XmlAnyElementAttribute?)List[index]; } set { List[index] = value; } } /// /// [To be supplied.] /// - public int Add(XmlAnyElementAttribute attribute) + public int Add(XmlAnyElementAttribute? attribute) { return List.Add(attribute); } @@ -33,7 +34,7 @@ public int Add(XmlAnyElementAttribute attribute) /// /// [To be supplied.] /// - public void Insert(int index, XmlAnyElementAttribute attribute) + public void Insert(int index, XmlAnyElementAttribute? attribute) { List.Insert(index, attribute); } @@ -41,7 +42,7 @@ public void Insert(int index, XmlAnyElementAttribute attribute) /// /// [To be supplied.] /// - public int IndexOf(XmlAnyElementAttribute attribute) + public int IndexOf(XmlAnyElementAttribute? attribute) { return List.IndexOf(attribute); } @@ -49,7 +50,7 @@ public int IndexOf(XmlAnyElementAttribute attribute) /// /// [To be supplied.] /// - public bool Contains(XmlAnyElementAttribute attribute) + public bool Contains(XmlAnyElementAttribute? attribute) { return List.Contains(attribute); } @@ -57,7 +58,7 @@ public bool Contains(XmlAnyElementAttribute attribute) /// /// [To be supplied.] /// - public void Remove(XmlAnyElementAttribute attribute) + public void Remove(XmlAnyElementAttribute? attribute) { List.Remove(attribute); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlArrayAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlArrayAttribute.cs index a76a8cf2acceae..dec726faaf3904 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlArrayAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlArrayAttribute.cs @@ -1,10 +1,11 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; +using System.Diagnostics.CodeAnalysis; using System.Xml.Schema; - namespace System.Xml.Serialization { /// @@ -13,8 +14,8 @@ namespace System.Xml.Serialization [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = false)] public class XmlArrayAttribute : System.Attribute { - private string _elementName; - private string _ns; + private string? _elementName; + private string? _ns; private bool _nullable; private XmlSchemaForm _form = XmlSchemaForm.None; private int _order = -1; @@ -29,7 +30,7 @@ public XmlArrayAttribute() /// /// [To be supplied.] /// - public XmlArrayAttribute(string elementName) + public XmlArrayAttribute(string? elementName) { _elementName = elementName; } @@ -37,6 +38,7 @@ public XmlArrayAttribute(string elementName) /// /// [To be supplied.] /// + [AllowNull] public string ElementName { get { return _elementName == null ? string.Empty : _elementName; } @@ -46,7 +48,7 @@ public string ElementName /// /// [To be supplied.] /// - public string Namespace + public string? Namespace { get { return _ns; } set { _ns = value; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlArrayItemAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlArrayItemAttribute.cs index 31eb9de53e056e..c1d9719c6e5746 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlArrayItemAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlArrayItemAttribute.cs @@ -1,10 +1,11 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; +using System.Diagnostics.CodeAnalysis; using System.Xml.Schema; - namespace System.Xml.Serialization { /// @@ -13,10 +14,10 @@ namespace System.Xml.Serialization [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true)] public class XmlArrayItemAttribute : System.Attribute { - private string _elementName; - private Type _type; - private string _ns; - private string _dataType; + private string? _elementName; + private Type? _type; + private string? _ns; + private string? _dataType; private bool _nullable; private bool _nullableSpecified; private XmlSchemaForm _form = XmlSchemaForm.None; @@ -57,7 +58,7 @@ public XmlArrayItemAttribute(string elementName, Type type) /// /// [To be supplied.] /// - public Type Type + public Type? Type { get { return _type; } set { _type = value; } @@ -66,6 +67,7 @@ public Type Type /// /// [To be supplied.] /// + [AllowNull] public string ElementName { get { return _elementName == null ? string.Empty : _elementName; } @@ -75,7 +77,7 @@ public string ElementName /// /// [To be supplied.] /// - public string Namespace + public string? Namespace { get { return _ns; } set { _ns = value; } @@ -90,6 +92,7 @@ public int NestingLevel /// /// [To be supplied.] /// + [AllowNull] public string DataType { get { return _dataType == null ? string.Empty : _dataType; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlArrayItemAttributes.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlArrayItemAttributes.cs index 21010185b35d31..dceec59f18997a 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlArrayItemAttributes.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlArrayItemAttributes.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; @@ -16,16 +17,16 @@ public class XmlArrayItemAttributes : CollectionBase /// /// [To be supplied.] /// - public XmlArrayItemAttribute this[int index] + public XmlArrayItemAttribute? this[int index] { - get { return (XmlArrayItemAttribute)List[index]; } + get { return (XmlArrayItemAttribute?)List[index]; } set { List[index] = value; } } /// /// [To be supplied.] /// - public int Add(XmlArrayItemAttribute attribute) + public int Add(XmlArrayItemAttribute? attribute) { return List.Add(attribute); } @@ -33,7 +34,7 @@ public int Add(XmlArrayItemAttribute attribute) /// /// [To be supplied.] /// - public void Insert(int index, XmlArrayItemAttribute attribute) + public void Insert(int index, XmlArrayItemAttribute? attribute) { List.Insert(index, attribute); } @@ -41,7 +42,7 @@ public void Insert(int index, XmlArrayItemAttribute attribute) /// /// [To be supplied.] /// - public int IndexOf(XmlArrayItemAttribute attribute) + public int IndexOf(XmlArrayItemAttribute? attribute) { return List.IndexOf(attribute); } @@ -49,7 +50,7 @@ public int IndexOf(XmlArrayItemAttribute attribute) /// /// [To be supplied.] /// - public bool Contains(XmlArrayItemAttribute attribute) + public bool Contains(XmlArrayItemAttribute? attribute) { return List.Contains(attribute); } @@ -57,7 +58,7 @@ public bool Contains(XmlArrayItemAttribute attribute) /// /// [To be supplied.] /// - public void Remove(XmlArrayItemAttribute attribute) + public void Remove(XmlArrayItemAttribute? attribute) { List.Remove(attribute); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributeAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributeAttribute.cs index 797f9ecdf27076..24b8fa6a48cd82 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributeAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributeAttribute.cs @@ -1,10 +1,11 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; +using System.Diagnostics.CodeAnalysis; using System.Xml.Schema; - namespace System.Xml.Serialization { /// @@ -13,10 +14,10 @@ namespace System.Xml.Serialization [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue)] public class XmlAttributeAttribute : System.Attribute { - private string _attributeName; - private Type _type; - private string _ns; - private string _dataType; + private string? _attributeName; + private Type? _type; + private string? _ns; + private string? _dataType; private XmlSchemaForm _form = XmlSchemaForm.None; /// @@ -54,7 +55,7 @@ public XmlAttributeAttribute(string attributeName, Type type) /// /// [To be supplied.] /// - public Type Type + public Type? Type { get { return _type; } set { _type = value; } @@ -63,6 +64,7 @@ public Type Type /// /// [To be supplied.] /// + [AllowNull] public string AttributeName { get { return _attributeName == null ? string.Empty : _attributeName; } @@ -72,7 +74,7 @@ public string AttributeName /// /// [To be supplied.] /// - public string Namespace + public string? Namespace { get { return _ns; } set { _ns = value; } @@ -81,6 +83,7 @@ public string Namespace /// /// [To be supplied.] /// + [AllowNull] public string DataType { get { return _dataType == null ? string.Empty : _dataType; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributeOverrides.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributeOverrides.cs index ddf4bdac2f7a6b..63af70435d88d8 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributeOverrides.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributeOverrides.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System.Reflection; @@ -31,7 +32,7 @@ public void Add(Type type, XmlAttributes attributes) /// public void Add(Type type, string member, XmlAttributes attributes) { - Dictionary members; + Dictionary? members; if (!_types.TryGetValue(type, out members)) { members = new Dictionary(); @@ -47,7 +48,7 @@ public void Add(Type type, string member, XmlAttributes attributes) /// /// [To be supplied.] /// - public XmlAttributes this[Type type] + public XmlAttributes? this[Type type] { get { @@ -58,12 +59,12 @@ public XmlAttributes this[Type type] /// /// [To be supplied.] /// - public XmlAttributes this[Type type, string member] + public XmlAttributes? this[Type type, string member] { get { - Dictionary members; - XmlAttributes attributes; + Dictionary? members; + XmlAttributes? attributes; return _types.TryGetValue(type, out members) && members.TryGetValue(member, out attributes) ? attributes : null; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributes.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributes.cs index 0d10f57a94a72c..6c1e487b28ba86 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributes.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributes.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; @@ -35,18 +36,18 @@ public class XmlAttributes private readonly XmlElementAttributes _xmlElements = new XmlElementAttributes(); private readonly XmlArrayItemAttributes _xmlArrayItems = new XmlArrayItemAttributes(); private readonly XmlAnyElementAttributes _xmlAnyElements = new XmlAnyElementAttributes(); - private XmlArrayAttribute _xmlArray; - private XmlAttributeAttribute _xmlAttribute; - private XmlTextAttribute _xmlText; - private XmlEnumAttribute _xmlEnum; + private XmlArrayAttribute? _xmlArray; + private XmlAttributeAttribute? _xmlAttribute; + private XmlTextAttribute? _xmlText; + private XmlEnumAttribute? _xmlEnum; private bool _xmlIgnore; private bool _xmlns; - private object _xmlDefaultValue; - private XmlRootAttribute _xmlRoot; - private XmlTypeAttribute _xmlType; - private XmlAnyAttributeAttribute _xmlAnyAttribute; - private readonly XmlChoiceIdentifierAttribute _xmlChoiceIdentifier; - private static volatile Type s_ignoreAttributeType; + private object? _xmlDefaultValue; + private XmlRootAttribute? _xmlRoot; + private XmlTypeAttribute? _xmlType; + private XmlAnyAttributeAttribute? _xmlAnyAttribute; + private readonly XmlChoiceIdentifierAttribute? _xmlChoiceIdentifier; + private static volatile Type? s_ignoreAttributeType; /// @@ -101,7 +102,7 @@ public XmlAttributes(ICustomAttributeProvider provider) object[] attrs = provider.GetCustomAttributes(false); // most generic matches everything - XmlAnyElementAttribute wildcard = null; + XmlAnyElementAttribute? wildcard = null; for (int i = 0; i < attrs.Length; i++) { if (attrs[i] is XmlIgnoreAttribute || attrs[i] is ObsoleteAttribute || attrs[i].GetType() == IgnoreAttribute) @@ -195,7 +196,7 @@ public XmlAttributes(ICustomAttributeProvider provider) } } - internal static object GetAttr(MemberInfo memberInfo, Type attrType) + internal static object? GetAttr(MemberInfo memberInfo, Type attrType) { object[] attrs = memberInfo.GetCustomAttributes(attrType, false); if (attrs.Length == 0) return null; @@ -213,7 +214,7 @@ public XmlElementAttributes XmlElements /// /// [To be supplied.] /// - public XmlAttributeAttribute XmlAttribute + public XmlAttributeAttribute? XmlAttribute { get { return _xmlAttribute; } set { _xmlAttribute = value; } @@ -222,7 +223,7 @@ public XmlAttributeAttribute XmlAttribute /// /// [To be supplied.] /// - public XmlEnumAttribute XmlEnum + public XmlEnumAttribute? XmlEnum { get { return _xmlEnum; } set { _xmlEnum = value; } @@ -231,7 +232,7 @@ public XmlEnumAttribute XmlEnum /// /// [To be supplied.] /// - public XmlTextAttribute XmlText + public XmlTextAttribute? XmlText { get { return _xmlText; } set { _xmlText = value; } @@ -240,7 +241,7 @@ public XmlTextAttribute XmlText /// /// [To be supplied.] /// - public XmlArrayAttribute XmlArray + public XmlArrayAttribute? XmlArray { get { return _xmlArray; } set { _xmlArray = value; } @@ -257,7 +258,7 @@ public XmlArrayItemAttributes XmlArrayItems /// /// [To be supplied.] /// - public object XmlDefaultValue + public object? XmlDefaultValue { get { return _xmlDefaultValue; } set { _xmlDefaultValue = value; } @@ -275,7 +276,7 @@ public bool XmlIgnore /// /// [To be supplied.] /// - public XmlTypeAttribute XmlType + public XmlTypeAttribute? XmlType { get { return _xmlType; } set { _xmlType = value; } @@ -284,7 +285,7 @@ public XmlTypeAttribute XmlType /// /// [To be supplied.] /// - public XmlRootAttribute XmlRoot + public XmlRootAttribute? XmlRoot { get { return _xmlRoot; } set { _xmlRoot = value; } @@ -301,13 +302,13 @@ public XmlAnyElementAttributes XmlAnyElements /// /// [To be supplied.] /// - public XmlAnyAttributeAttribute XmlAnyAttribute + public XmlAnyAttributeAttribute? XmlAnyAttribute { get { return _xmlAnyAttribute; } set { _xmlAnyAttribute = value; } } - public XmlChoiceIdentifierAttribute XmlChoiceIdentifier + public XmlChoiceIdentifierAttribute? XmlChoiceIdentifier { get { return _xmlChoiceIdentifier; } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlChoiceIdentifierAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlChoiceIdentifierAttribute.cs index de9965ef658744..054f6a7c840baa 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlChoiceIdentifierAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlChoiceIdentifierAttribute.cs @@ -1,10 +1,11 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; using System.Xml.Schema; using System.Reflection; - +using System.Diagnostics.CodeAnalysis; namespace System.Xml.Serialization { @@ -14,8 +15,8 @@ namespace System.Xml.Serialization [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = false)] public class XmlChoiceIdentifierAttribute : System.Attribute { - private string _name; - private MemberInfo _memberInfo; + private string? _name; + private MemberInfo? _memberInfo; /// /// [To be supplied.] @@ -35,24 +36,25 @@ public XmlChoiceIdentifierAttribute(string name) /// /// [To be supplied.] /// + [AllowNull] public string MemberName { get { return _name == null ? string.Empty : _name; } set { _name = value; } } - internal MemberInfo MemberInfo + internal MemberInfo? MemberInfo { get { return _memberInfo; } set { _memberInfo = value; } } - internal MemberInfo GetMemberInfo() + internal MemberInfo? GetMemberInfo() { return MemberInfo; } - internal void SetMemberInfo(MemberInfo memberInfo) + internal void SetMemberInfo(MemberInfo? memberInfo) { MemberInfo = memberInfo; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlElementAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlElementAttribute.cs index b2304321eb5a68..a809fb7ea6ca83 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlElementAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlElementAttribute.cs @@ -1,10 +1,11 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; +using System.Diagnostics.CodeAnalysis; using System.Xml.Schema; - namespace System.Xml.Serialization { /// @@ -13,10 +14,10 @@ namespace System.Xml.Serialization [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true)] public class XmlElementAttribute : System.Attribute { - private string _elementName; - private Type _type; - private string _ns; - private string _dataType; + private string? _elementName; + private Type? _type; + private string? _ns; + private string? _dataType; private bool _nullable; private bool _nullableSpecified; private XmlSchemaForm _form = XmlSchemaForm.None; @@ -32,7 +33,7 @@ public XmlElementAttribute() /// /// [To be supplied.] /// - public XmlElementAttribute(string elementName) + public XmlElementAttribute(string? elementName) { _elementName = elementName; } @@ -40,7 +41,7 @@ public XmlElementAttribute(string elementName) /// /// [To be supplied.] /// - public XmlElementAttribute(Type type) + public XmlElementAttribute(Type? type) { _type = type; } @@ -48,7 +49,7 @@ public XmlElementAttribute(Type type) /// /// [To be supplied.] /// - public XmlElementAttribute(string elementName, Type type) + public XmlElementAttribute(string? elementName, Type? type) { _elementName = elementName; _type = type; @@ -57,7 +58,7 @@ public XmlElementAttribute(string elementName, Type type) /// /// [To be supplied.] /// - public Type Type + public Type? Type { get { return _type; } set { _type = value; } @@ -66,6 +67,7 @@ public Type Type /// /// [To be supplied.] /// + [AllowNull] public string ElementName { get { return _elementName == null ? string.Empty : _elementName; } @@ -75,7 +77,7 @@ public string ElementName /// /// [To be supplied.] /// - public string Namespace + public string? Namespace { get { return _ns; } set { _ns = value; } @@ -84,6 +86,7 @@ public string Namespace /// /// [To be supplied.] /// + [AllowNull] public string DataType { get { return _dataType == null ? string.Empty : _dataType; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlElementAttributes.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlElementAttributes.cs index 794623f9853c8a..92392568b2dee1 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlElementAttributes.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlElementAttributes.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; @@ -16,16 +17,16 @@ public class XmlElementAttributes : CollectionBase /// /// [To be supplied.] /// - public XmlElementAttribute this[int index] + public XmlElementAttribute? this[int index] { - get { return (XmlElementAttribute)List[index]; } + get { return (XmlElementAttribute?)List[index]; } set { List[index] = value; } } /// /// [To be supplied.] /// - public int Add(XmlElementAttribute attribute) + public int Add(XmlElementAttribute? attribute) { return List.Add(attribute); } @@ -33,7 +34,7 @@ public int Add(XmlElementAttribute attribute) /// /// [To be supplied.] /// - public void Insert(int index, XmlElementAttribute attribute) + public void Insert(int index, XmlElementAttribute? attribute) { List.Insert(index, attribute); } @@ -41,7 +42,7 @@ public void Insert(int index, XmlElementAttribute attribute) /// /// [To be supplied.] /// - public int IndexOf(XmlElementAttribute attribute) + public int IndexOf(XmlElementAttribute? attribute) { return List.IndexOf(attribute); } @@ -49,7 +50,7 @@ public int IndexOf(XmlElementAttribute attribute) /// /// [To be supplied.] /// - public bool Contains(XmlElementAttribute attribute) + public bool Contains(XmlElementAttribute? attribute) { return List.Contains(attribute); } @@ -57,7 +58,7 @@ public bool Contains(XmlElementAttribute attribute) /// /// [To be supplied.] /// - public void Remove(XmlElementAttribute attribute) + public void Remove(XmlElementAttribute? attribute) { List.Remove(attribute); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlEnumAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlEnumAttribute.cs index 57065628bb2fe8..340c39353f9e2b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlEnumAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlEnumAttribute.cs @@ -1,9 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; - namespace System.Xml.Serialization { /// @@ -12,7 +12,7 @@ namespace System.Xml.Serialization [AttributeUsage(AttributeTargets.Field)] public class XmlEnumAttribute : System.Attribute { - private string _name; + private string? _name; /// /// [To be supplied.] @@ -24,7 +24,7 @@ public XmlEnumAttribute() /// /// [To be supplied.] /// - public XmlEnumAttribute(string name) + public XmlEnumAttribute(string? name) { _name = name; } @@ -32,7 +32,7 @@ public XmlEnumAttribute(string name) /// /// [To be supplied.] /// - public string Name + public string? Name { get { return _name; } set { _name = value; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlIgnoreAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlIgnoreAttribute.cs index f6526835f9e64c..6d1fd60586a3ea 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlIgnoreAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlIgnoreAttribute.cs @@ -1,9 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; - namespace System.Xml.Serialization { /// diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlIncludeAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlIncludeAttribute.cs index fd41d5e1a27e92..7993b4084ecfba 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlIncludeAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlIncludeAttribute.cs @@ -1,9 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; - namespace System.Xml.Serialization { /// @@ -12,12 +12,12 @@ namespace System.Xml.Serialization [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Method, AllowMultiple = true)] public class XmlIncludeAttribute : System.Attribute { - private Type _type; + private Type? _type; /// /// [To be supplied.] /// - public XmlIncludeAttribute(Type type) + public XmlIncludeAttribute(Type? type) { _type = type; } @@ -25,7 +25,7 @@ public XmlIncludeAttribute(Type type) /// /// [To be supplied.] /// - public Type Type + public Type? Type { get { return _type; } set { _type = value; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlMapping.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlMapping.cs index cdf16b04f52573..93d6a0c63a8863 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlMapping.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlMapping.cs @@ -1,13 +1,13 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; using System.ComponentModel; using System.Globalization; using System.Reflection; using System.Xml.Serialization; - namespace System.Xml.Serialization { [Flags] @@ -24,19 +24,19 @@ public enum XmlMappingAccess /// public abstract class XmlMapping { - private readonly TypeScope _scope; + private readonly TypeScope? _scope; private bool _generateSerializer; private bool _isSoap; private readonly ElementAccessor _accessor; - private string _key; + private string? _key; private readonly bool _shallow; private readonly XmlMappingAccess _access; - internal XmlMapping(TypeScope scope, ElementAccessor accessor) : this(scope, accessor, XmlMappingAccess.Read | XmlMappingAccess.Write) + internal XmlMapping(TypeScope? scope, ElementAccessor accessor) : this(scope, accessor, XmlMappingAccess.Read | XmlMappingAccess.Write) { } - internal XmlMapping(TypeScope scope, ElementAccessor accessor, XmlMappingAccess access) + internal XmlMapping(TypeScope? scope, ElementAccessor accessor, XmlMappingAccess access) { _scope = scope; _accessor = accessor; @@ -49,7 +49,7 @@ internal ElementAccessor Accessor get { return _accessor; } } - internal TypeScope Scope + internal TypeScope? Scope { get { return _scope; } } @@ -73,7 +73,7 @@ public string XsdElementName /// /// [To be supplied.] /// - public string Namespace + public string? Namespace { get { return _accessor.Namespace; } } @@ -101,27 +101,28 @@ internal bool IsSoap } /// - public void SetKey(string key) + public void SetKey(string? key) { SetKeyInternal(key); } /// - internal void SetKeyInternal(string key) + internal void SetKeyInternal(string? key) { _key = key; } - internal static string GenerateKey(Type type, XmlRootAttribute root, string ns) + internal static string GenerateKey(Type type, XmlRootAttribute? root, string? ns) { if (root == null) { - root = (XmlRootAttribute)XmlAttributes.GetAttr(type, typeof(XmlRootAttribute)); + root = (XmlRootAttribute?)XmlAttributes.GetAttr(type, typeof(XmlRootAttribute)); } return type.FullName + ":" + (root == null ? string.Empty : root.GetKey()) + ":" + (ns == null ? string.Empty : ns); } - internal string Key { get { return _key; } } + internal string? Key { get { return _key; } } + internal void CheckShallow() { if (_shallow) @@ -129,6 +130,7 @@ internal void CheckShallow() throw new InvalidOperationException(SR.XmlMelformMapping); } } + internal static bool IsShallow(XmlMapping[] mappings) { for (int i = 0; i < mappings.Length; i++) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlMemberMapping.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlMemberMapping.cs index 9b89b94237e24d..6abcd9cc90d507 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlMemberMapping.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlMemberMapping.cs @@ -1,10 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System.Reflection; using System; - namespace System.Xml.Serialization { /// @@ -22,14 +22,14 @@ internal MemberMapping Mapping get { return _mapping; } } - internal Accessor Accessor + internal Accessor? Accessor { get { return _mapping.Accessor; } } public bool Any { - get { return Accessor.Any; } + get { return Accessor!.Any; } } /// @@ -37,7 +37,7 @@ public bool Any /// public string ElementName { - get { return Accessor.UnescapeName(Accessor.Name); } + get { return Accessor.UnescapeName(Accessor!.Name); } } /// @@ -45,15 +45,15 @@ public string ElementName /// public string XsdElementName { - get { return Accessor.Name; } + get { return Accessor!.Name; } } /// /// [To be supplied.] /// - public string Namespace + public string? Namespace { - get { return Accessor.Namespace; } + get { return Accessor!.Namespace; } } /// @@ -67,17 +67,17 @@ public string MemberName /// /// [To be supplied.] /// - public string TypeName + public string? TypeName { - get { return Accessor.Mapping != null ? Accessor.Mapping.TypeName : string.Empty; } + get { return Accessor!.Mapping != null ? Accessor.Mapping.TypeName : string.Empty; } } /// /// [To be supplied.] /// - public string TypeNamespace + public string? TypeNamespace { - get { return Accessor.Mapping != null ? Accessor.Mapping.Namespace : null; } + get { return Accessor!.Mapping != null ? Accessor.Mapping.Namespace : null; } } /// @@ -85,7 +85,7 @@ public string TypeNamespace /// public string TypeFullName { - get { return _mapping.TypeDesc.FullName; } + get { return _mapping.TypeDesc!.FullName; } } /// diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlMembersMapping.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlMembersMapping.cs index ce8ba4ae0b1ef8..21fbe9afa9dffa 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlMembersMapping.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlMembersMapping.cs @@ -1,11 +1,11 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System.Reflection; using System; using System.Text; - namespace System.Xml.Serialization { /// @@ -18,15 +18,15 @@ public class XmlMembersMapping : XmlMapping internal XmlMembersMapping(TypeScope scope, ElementAccessor accessor, XmlMappingAccess access) : base(scope, accessor, access) { - MembersMapping mapping = (MembersMapping)accessor.Mapping; + MembersMapping mapping = (MembersMapping)accessor.Mapping!; StringBuilder key = new StringBuilder(); key.Append(':'); - _mappings = new XmlMemberMapping[mapping.Members.Length]; + _mappings = new XmlMemberMapping[mapping.Members!.Length]; for (int i = 0; i < _mappings.Length; i++) { - if (mapping.Members[i].TypeDesc.Type != null) + if (mapping.Members[i].TypeDesc!.Type != null) { - key.Append(GenerateKey(mapping.Members[i].TypeDesc.Type, null, null)); + key.Append(GenerateKey(mapping.Members[i].TypeDesc!.Type!, null, null)); key.Append(':'); } _mappings[i] = new XmlMemberMapping(mapping.Members[i]); @@ -37,17 +37,17 @@ internal XmlMembersMapping(TypeScope scope, ElementAccessor accessor, XmlMapping /// /// [To be supplied.] /// - public string TypeName + public string? TypeName { - get { return Accessor.Mapping.TypeName; } + get { return Accessor.Mapping!.TypeName; } } /// /// [To be supplied.] /// - public string TypeNamespace + public string? TypeNamespace { - get { return Accessor.Mapping.Namespace; } + get { return Accessor.Mapping!.Namespace; } } /// diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlNamespaceDeclarationsAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlNamespaceDeclarationsAttribute.cs index 34baf124fb383c..8f0bf641bbd986 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlNamespaceDeclarationsAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlNamespaceDeclarationsAttribute.cs @@ -1,10 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; using System.Xml.Schema; - namespace System.Xml.Serialization { /// diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs index 790ad1cce877c9..65d7e022213107 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System.Reflection; @@ -28,16 +29,16 @@ public class XmlReflectionImporter private readonly NameTable _types = new NameTable(); // xmltypename + xmlns -> Mapping private readonly NameTable _nullables = new NameTable(); // xmltypename + xmlns -> NullableMapping private readonly NameTable _elements = new NameTable(); // xmlelementname + xmlns -> ElementAccessor - private NameTable _xsdAttributes; // xmlattributetname + xmlns -> AttributeAccessor - private Hashtable _specials; // type -> SpecialMapping + private NameTable? _xsdAttributes; // xmlattributetname + xmlns -> AttributeAccessor + private Hashtable? _specials; // type -> SpecialMapping private readonly Hashtable _anonymous = new Hashtable(); // type -> AnonymousMapping - private NameTable _serializables; // type name --> new SerializableMapping - private StructMapping _root; + private NameTable? _serializables; // type name --> new SerializableMapping + private StructMapping? _root; private readonly string _defaultNs; private readonly ModelScope _modelScope; private int _arrayNestingLevel; - private XmlArrayItemAttributes _savedArrayItemAttributes; - private string _savedArrayNamespace; + private XmlArrayItemAttributes? _savedArrayItemAttributes; + private string? _savedArrayNamespace; private int _choiceNum = 1; private enum ImportContext @@ -57,21 +58,21 @@ public XmlReflectionImporter() : this(null, null) /// /// [To be supplied.] /// - public XmlReflectionImporter(string defaultNamespace) : this(null, defaultNamespace) + public XmlReflectionImporter(string? defaultNamespace) : this(null, defaultNamespace) { } /// /// [To be supplied.] /// - public XmlReflectionImporter(XmlAttributeOverrides attributeOverrides) : this(attributeOverrides, null) + public XmlReflectionImporter(XmlAttributeOverrides? attributeOverrides) : this(attributeOverrides, null) { } /// /// [To be supplied.] /// - public XmlReflectionImporter(XmlAttributeOverrides attributeOverrides, string defaultNamespace) + public XmlReflectionImporter(XmlAttributeOverrides? attributeOverrides, string? defaultNamespace) { if (defaultNamespace == null) defaultNamespace = string.Empty; @@ -96,7 +97,7 @@ private void IncludeTypes(ICustomAttributeProvider provider, RecursionLimiter li object[] attrs = provider.GetCustomAttributes(typeof(XmlIncludeAttribute), false); for (int i = 0; i < attrs.Length; i++) { - Type type = ((XmlIncludeAttribute)attrs[i]).Type; + Type type = ((XmlIncludeAttribute)attrs[i]).Type!; IncludeType(type, limiter); } } @@ -112,14 +113,14 @@ public void IncludeType(Type type) private void IncludeType(Type type, RecursionLimiter limiter) { int previousNestingLevel = _arrayNestingLevel; - XmlArrayItemAttributes previousArrayItemAttributes = _savedArrayItemAttributes; - string previousArrayNamespace = _savedArrayNamespace; + XmlArrayItemAttributes? previousArrayItemAttributes = _savedArrayItemAttributes; + string? previousArrayNamespace = _savedArrayNamespace; _arrayNestingLevel = 0; _savedArrayItemAttributes = null; _savedArrayNamespace = null; TypeMapping mapping = ImportTypeMapping(_modelScope.GetTypeModel(type), _defaultNs, ImportContext.Element, string.Empty, null, limiter); - if (mapping.IsAnonymousType && !mapping.TypeDesc.IsSpecial) + if (mapping.IsAnonymousType && !mapping.TypeDesc!.IsSpecial) { //XmlAnonymousInclude=Cannot include anonymous type '{0}'. throw new InvalidOperationException(SR.Format(SR.XmlAnonymousInclude, type.FullName)); @@ -156,7 +157,7 @@ public XmlTypeMapping ImportTypeMapping(Type type, XmlRootAttribute root) /// /// [To be supplied.] /// - public XmlTypeMapping ImportTypeMapping(Type type, XmlRootAttribute root, string defaultNamespace) + public XmlTypeMapping ImportTypeMapping(Type type, XmlRootAttribute? root, string? defaultNamespace) { if (type == null) throw new ArgumentNullException(nameof(type)); @@ -210,7 +211,7 @@ public XmlMembersMapping ImportMembersMapping(string elementName, string ns, Xml element = (ElementAccessor)ReconcileAccessor(element, _elements); else { - foreach (MemberMapping mapping in membersMapping.Members) + foreach (MemberMapping mapping in membersMapping.Members!) { if (mapping.Elements != null && mapping.Elements.Length > 0) { @@ -226,7 +227,7 @@ public XmlMembersMapping ImportMembersMapping(string elementName, string ns, Xml private XmlAttributes GetAttributes(Type type, bool canBeSimpleType) { - XmlAttributes attrs = _attributeOverrides[type]; + XmlAttributes? attrs = _attributeOverrides[type]; if (attrs != null) return attrs; if (canBeSimpleType && TypeScope.IsKnownType(type)) { @@ -237,18 +238,18 @@ private XmlAttributes GetAttributes(Type type, bool canBeSimpleType) private XmlAttributes GetAttributes(MemberInfo memberInfo) { - XmlAttributes attrs = _attributeOverrides[memberInfo.DeclaringType, memberInfo.Name]; + XmlAttributes? attrs = _attributeOverrides[memberInfo.DeclaringType!, memberInfo.Name]; if (attrs != null) return attrs; return new XmlAttributes(memberInfo); } - private ElementAccessor ImportElement(TypeModel model, XmlRootAttribute root, string defaultNamespace, RecursionLimiter limiter) + private ElementAccessor ImportElement(TypeModel model, XmlRootAttribute? root, string? defaultNamespace, RecursionLimiter limiter) { XmlAttributes a = GetAttributes(model.Type, true); if (root == null) root = a.XmlRoot; - string ns = root == null ? null : root.Namespace; + string? ns = root == null ? null : root.Namespace; if (ns == null) ns = defaultNamespace; if (ns == null) ns = _defaultNs; @@ -263,9 +264,9 @@ private ElementAccessor ImportElement(TypeModel model, XmlRootAttribute root, st element.Name = XmlConvert.EncodeLocalName(root.ElementName); if (root.GetIsNullableSpecified() && !root.IsNullable && model.TypeDesc.IsOptionalValue) //XmlInvalidNotNullable=IsNullable may not be set to 'false' for a Nullable<{0}> type. Consider using '{0}' type or removing the IsNullable property from the XmlElement attribute. - throw new InvalidOperationException(SR.Format(SR.XmlInvalidNotNullable, model.TypeDesc.BaseTypeDesc.FullName, "XmlRoot")); + throw new InvalidOperationException(SR.Format(SR.XmlInvalidNotNullable, model.TypeDesc.BaseTypeDesc!.FullName, "XmlRoot")); element.IsNullable = root.GetIsNullableSpecified() ? root.IsNullable : model.TypeDesc.IsNullable || model.TypeDesc.IsOptionalValue; - CheckNullable(element.IsNullable, model.TypeDesc, element.Mapping); + CheckNullable(element.IsNullable, model.TypeDesc, element.Mapping!); } else element.IsNullable = model.TypeDesc.IsNullable || model.TypeDesc.IsOptionalValue; @@ -278,12 +279,12 @@ private static string GetMappingName(Mapping mapping) if (mapping is MembersMapping) return "(method)"; else if (mapping is TypeMapping) - return ((TypeMapping)mapping).TypeDesc.FullName; + return ((TypeMapping)mapping).TypeDesc!.FullName; else throw new ArgumentException(SR.XmlInternalError, nameof(mapping)); } - private ElementAccessor ReconcileLocalAccessor(ElementAccessor accessor, string ns) + private ElementAccessor ReconcileLocalAccessor(ElementAccessor accessor, string? ns) { if (accessor.Namespace == ns) return accessor; return (ElementAccessor)ReconcileAccessor(accessor, _elements); @@ -294,7 +295,7 @@ private Accessor ReconcileAccessor(Accessor accessor, NameTable accessors) if (accessor.Any && accessor.Name.Length == 0) return accessor; - Accessor existing = (Accessor)accessors[accessor.Name, accessor.Namespace]; + Accessor? existing = (Accessor?)accessors[accessor.Name, accessor.Namespace]; if (existing == null) { accessor.IsTopLevelInSchema = true; @@ -307,13 +308,13 @@ private Accessor ReconcileAccessor(Accessor accessor, NameTable accessors) if (!(accessor.Mapping is MembersMapping) && !(existing.Mapping is MembersMapping)) { - if (accessor.Mapping.TypeDesc == existing.Mapping.TypeDesc - || (existing.Mapping is NullableMapping && accessor.Mapping.TypeDesc == ((NullableMapping)existing.Mapping).BaseMapping.TypeDesc) - || (accessor.Mapping is NullableMapping && ((NullableMapping)accessor.Mapping).BaseMapping.TypeDesc == existing.Mapping.TypeDesc)) + if (accessor.Mapping!.TypeDesc == existing.Mapping!.TypeDesc + || (existing.Mapping is NullableMapping && accessor.Mapping.TypeDesc == ((NullableMapping)existing.Mapping).BaseMapping!.TypeDesc) + || (accessor.Mapping is NullableMapping && ((NullableMapping)accessor.Mapping).BaseMapping!.TypeDesc == existing.Mapping.TypeDesc)) { // need to compare default values - string value1 = Convert.ToString(accessor.Default, CultureInfo.InvariantCulture); - string value2 = Convert.ToString(existing.Default, CultureInfo.InvariantCulture); + string? value1 = Convert.ToString(accessor.Default, CultureInfo.InvariantCulture); + string? value2 = Convert.ToString(existing.Default, CultureInfo.InvariantCulture); if (value1 == value2) { return existing; @@ -329,11 +330,11 @@ private Accessor ReconcileAccessor(Accessor accessor, NameTable accessors) { if (!(existing.Mapping is ArrayMapping)) { - throw new InvalidOperationException(SR.Format(SR.XmlCannotReconcileAccessor, accessor.Name, accessor.Namespace, GetMappingName(existing.Mapping), GetMappingName(accessor.Mapping))); + throw new InvalidOperationException(SR.Format(SR.XmlCannotReconcileAccessor, accessor.Name, accessor.Namespace, GetMappingName(existing.Mapping!), GetMappingName(accessor.Mapping))); } ArrayMapping mapping = (ArrayMapping)accessor.Mapping; - ArrayMapping existingMapping = mapping.IsAnonymousType ? null : (ArrayMapping)_types[existing.Mapping.TypeName, existing.Mapping.Namespace]; - ArrayMapping first = existingMapping; + ArrayMapping? existingMapping = mapping.IsAnonymousType ? null : (ArrayMapping?)_types[existing.Mapping.TypeName!, existing.Mapping.Namespace]; + ArrayMapping? first = existingMapping; while (existingMapping != null) { if (existingMapping == accessor.Mapping) @@ -342,13 +343,13 @@ private Accessor ReconcileAccessor(Accessor accessor, NameTable accessors) } mapping.Next = first; if (!mapping.IsAnonymousType) - _types[existing.Mapping.TypeName, existing.Mapping.Namespace] = mapping; + _types[existing.Mapping.TypeName!, existing.Mapping.Namespace] = mapping; return existing; } if (accessor is AttributeAccessor) - throw new InvalidOperationException(SR.Format(SR.XmlCannotReconcileAttributeAccessor, accessor.Name, accessor.Namespace, GetMappingName(existing.Mapping), GetMappingName(accessor.Mapping))); + throw new InvalidOperationException(SR.Format(SR.XmlCannotReconcileAttributeAccessor, accessor.Name, accessor.Namespace, GetMappingName(existing.Mapping!), GetMappingName(accessor.Mapping!))); else - throw new InvalidOperationException(SR.Format(SR.XmlCannotReconcileAccessor, accessor.Name, accessor.Namespace, GetMappingName(existing.Mapping), GetMappingName(accessor.Mapping))); + throw new InvalidOperationException(SR.Format(SR.XmlCannotReconcileAccessor, accessor.Name, accessor.Namespace, GetMappingName(existing.Mapping!), GetMappingName(accessor.Mapping!))); } private Exception CreateReflectionException(string context, Exception e) @@ -366,23 +367,23 @@ private Exception CreateMemberReflectionException(FieldModel model, Exception e) return new InvalidOperationException(SR.Format(model.IsProperty ? SR.XmlPropertyReflectionError : SR.XmlFieldReflectionError, model.Name), e); } - private TypeMapping ImportTypeMapping(TypeModel model, string ns, ImportContext context, string dataType, XmlAttributes a, RecursionLimiter limiter) + private TypeMapping ImportTypeMapping(TypeModel model, string? ns, ImportContext context, string dataType, XmlAttributes? a, RecursionLimiter limiter) { return ImportTypeMapping(model, ns, context, dataType, a, false, false, limiter); } - private TypeMapping ImportTypeMapping(TypeModel model, string ns, ImportContext context, string dataType, XmlAttributes a, bool repeats, bool openModel, RecursionLimiter limiter) + private TypeMapping ImportTypeMapping(TypeModel model, string? ns, ImportContext context, string dataType, XmlAttributes? a, bool repeats, bool openModel, RecursionLimiter limiter) { try { if (dataType.Length > 0) { - TypeDesc modelTypeDesc = TypeScope.IsOptionalValue(model.Type) ? model.TypeDesc.BaseTypeDesc : model.TypeDesc; + TypeDesc modelTypeDesc = TypeScope.IsOptionalValue(model.Type) ? model.TypeDesc.BaseTypeDesc! : model.TypeDesc; if (!modelTypeDesc.IsPrimitive) { throw new InvalidOperationException(SR.Format(SR.XmlInvalidDataTypeUsage, dataType, "XmlElementAttribute.DataType")); } - TypeDesc td = _typeScope.GetTypeDesc(dataType, XmlSchema.Namespace); + TypeDesc? td = _typeScope.GetTypeDesc(dataType, XmlSchema.Namespace); if (td == null) { throw new InvalidOperationException(SR.Format(SR.XmlInvalidXsdDataType, dataType, "XmlElementAttribute.DataType", new XmlQualifiedName(dataType, XmlSchema.Namespace).ToString())); @@ -421,12 +422,12 @@ private TypeMapping ImportTypeMapping(TypeModel model, string ns, ImportContext if (context != ImportContext.Element) throw UnsupportedException(model.TypeDesc, context); if (model.TypeDesc.IsOptionalValue) { - TypeDesc valueTypeDesc = string.IsNullOrEmpty(dataType) ? model.TypeDesc.BaseTypeDesc : _typeScope.GetTypeDesc(dataType, XmlSchema.Namespace); - string xsdTypeName = valueTypeDesc.DataType == null ? valueTypeDesc.Name : valueTypeDesc.DataType.Name; - TypeMapping baseMapping = GetTypeMapping(xsdTypeName, ns, valueTypeDesc, _types, null); + TypeDesc valueTypeDesc = string.IsNullOrEmpty(dataType) ? model.TypeDesc.BaseTypeDesc! : _typeScope.GetTypeDesc(dataType, XmlSchema.Namespace)!; + string? xsdTypeName = valueTypeDesc.DataType == null ? valueTypeDesc.Name : valueTypeDesc.DataType.Name; + TypeMapping? baseMapping = GetTypeMapping(xsdTypeName, ns, valueTypeDesc, _types, null); if (baseMapping == null) - baseMapping = ImportTypeMapping(_modelScope.GetTypeModel(model.TypeDesc.BaseTypeDesc.Type), ns, context, dataType, null, repeats, openModel, limiter); - return CreateNullableMapping(baseMapping, model.TypeDesc.Type); + baseMapping = ImportTypeMapping(_modelScope.GetTypeModel(model.TypeDesc.BaseTypeDesc!.Type!), ns, context, dataType, null, repeats, openModel, limiter); + return CreateNullableMapping(baseMapping, model.TypeDesc.Type!); } else { @@ -460,7 +461,7 @@ private TypeMapping ImportTypeMapping(TypeModel model, string ns, ImportContext } } - internal static MethodInfo GetMethodFromSchemaProvider(XmlSchemaProviderAttribute provider, Type type) + internal static MethodInfo? GetMethodFromSchemaProvider(XmlSchemaProviderAttribute provider, Type type) { if (provider.IsAny) { @@ -474,7 +475,7 @@ internal static MethodInfo GetMethodFromSchemaProvider(XmlSchemaProviderAttribut if (!CSharpHelpers.IsValidLanguageIndependentIdentifier(provider.MethodName)) throw new ArgumentException(SR.Format(SR.XmlGetSchemaMethodName, provider.MethodName), nameof(provider.MethodName)); - MethodInfo getMethod = getMethod = type.GetMethod(provider.MethodName, /* BindingFlags.DeclaredOnly | */ BindingFlags.Static | BindingFlags.Public, new Type[] { typeof(XmlSchemaSet) }); + MethodInfo? getMethod = getMethod = type.GetMethod(provider.MethodName, /* BindingFlags.DeclaredOnly | */ BindingFlags.Static | BindingFlags.Public, new Type[] { typeof(XmlSchemaSet) }); if (getMethod == null) throw new InvalidOperationException(SR.Format(SR.XmlGetSchemaMethodMissing, provider.MethodName, typeof(XmlSchemaSet).Name, type.FullName)); @@ -484,19 +485,19 @@ internal static MethodInfo GetMethodFromSchemaProvider(XmlSchemaProviderAttribut return getMethod; } - private SpecialMapping ImportSpecialMapping(Type type, TypeDesc typeDesc, string ns, ImportContext context, RecursionLimiter limiter) + private SpecialMapping ImportSpecialMapping(Type type, TypeDesc typeDesc, string? ns, ImportContext context, RecursionLimiter limiter) { if (_specials == null) _specials = new Hashtable(); - SpecialMapping mapping = (SpecialMapping)_specials[type]; + SpecialMapping? mapping = (SpecialMapping?)_specials[type]; if (mapping != null) { - CheckContext(mapping.TypeDesc, context); + CheckContext(mapping.TypeDesc!, context); return mapping; } if (typeDesc.Kind == TypeKind.Serializable) { - SerializableMapping serializableMapping = null; + SerializableMapping? serializableMapping = null; // get the schema method info object[] attrs = type.GetCustomAttributes(typeof(XmlSchemaProviderAttribute), false); @@ -505,14 +506,14 @@ private SpecialMapping ImportSpecialMapping(Type type, TypeDesc typeDesc, string { // new IXmlSerializable XmlSchemaProviderAttribute provider = (XmlSchemaProviderAttribute)attrs[0]; - MethodInfo method = GetMethodFromSchemaProvider(provider, type); + MethodInfo method = GetMethodFromSchemaProvider(provider, type)!; serializableMapping = new SerializableMapping(method, provider.IsAny, ns); - XmlQualifiedName qname = serializableMapping.XsiType; + XmlQualifiedName? qname = serializableMapping.XsiType; if (qname != null && !qname.IsEmpty) { if (_serializables == null) _serializables = new NameTable(); - SerializableMapping existingMapping = (SerializableMapping)_serializables[qname]; + SerializableMapping? existingMapping = (SerializableMapping?)_serializables[qname]; if (existingMapping != null) { if (existingMapping.Type == null) @@ -521,14 +522,14 @@ private SpecialMapping ImportSpecialMapping(Type type, TypeDesc typeDesc, string } else if (existingMapping.Type != type) { - SerializableMapping next = existingMapping.Next; + SerializableMapping? next = existingMapping.Next; existingMapping.Next = serializableMapping; serializableMapping.Next = next; } } else { - XmlSchemaType xsdType = serializableMapping.XsdType; + XmlSchemaType? xsdType = serializableMapping.XsdType; if (xsdType != null) SetBase(serializableMapping, xsdType.DerivedFrom); _serializables[qname] = serializableMapping; @@ -565,7 +566,7 @@ internal void SetBase(SerializableMapping mapping, XmlQualifiedName baseQname) { if (baseQname.IsEmpty) return; if (baseQname.Namespace == XmlSchema.Namespace) return; - XmlSchemaSet schemas = mapping.Schemas; + XmlSchemaSet schemas = mapping.Schemas!; ArrayList srcSchemas = (ArrayList)schemas.Schemas(baseQname.Namespace); if (srcSchemas.Count == 0) @@ -576,18 +577,18 @@ internal void SetBase(SerializableMapping mapping, XmlQualifiedName baseQname) { throw new InvalidOperationException(SR.Format(SR.XmlGetSchemaInclude, baseQname.Namespace, typeof(IXmlSerializable).Name, "GetSchema")); } - XmlSchema s = (XmlSchema)srcSchemas[0]; + XmlSchema s = (XmlSchema)srcSchemas[0]!; - XmlSchemaType t = (XmlSchemaType)s.SchemaTypes[baseQname]; + XmlSchemaType t = (XmlSchemaType)s.SchemaTypes[baseQname]!; t = t.Redefined != null ? t.Redefined : t; - if (_serializables[baseQname] == null) + if (_serializables![baseQname] == null) { SerializableMapping baseMapping = new SerializableMapping(baseQname, schemas); SetBase(baseMapping, t.DerivedFrom); _serializables.Add(baseQname, baseMapping); } - mapping.SetBaseMapping((SerializableMapping)_serializables[baseQname]); + mapping.SetBaseMapping((SerializableMapping?)_serializables[baseQname]); } private static string GetContextName(ImportContext context) => @@ -623,15 +624,15 @@ private StructMapping CreateRootMapping() private NullableMapping CreateNullableMapping(TypeMapping baseMapping, Type type) { - TypeDesc typeDesc = baseMapping.TypeDesc.GetNullableTypeDesc(type); - TypeMapping existingMapping; + TypeDesc typeDesc = baseMapping.TypeDesc!.GetNullableTypeDesc(type); + TypeMapping? existingMapping; if (!baseMapping.IsAnonymousType) { - existingMapping = (TypeMapping)_nullables[baseMapping.TypeName, baseMapping.Namespace]; + existingMapping = (TypeMapping?)_nullables[baseMapping.TypeName!, baseMapping.Namespace]; } else { - existingMapping = (TypeMapping)_anonymous[type]; + existingMapping = (TypeMapping?)_anonymous[type]; } NullableMapping mapping; @@ -648,12 +649,12 @@ private NullableMapping CreateNullableMapping(TypeMapping baseMapping, Type type } else { - throw new InvalidOperationException(SR.Format(SR.XmlTypesDuplicate, typeDesc.FullName, existingMapping.TypeDesc.FullName, typeDesc.Name, existingMapping.Namespace)); + throw new InvalidOperationException(SR.Format(SR.XmlTypesDuplicate, typeDesc.FullName, existingMapping.TypeDesc!.FullName, typeDesc.Name, existingMapping.Namespace)); } } else { - throw new InvalidOperationException(SR.Format(SR.XmlTypesDuplicate, typeDesc.FullName, existingMapping.TypeDesc.FullName, typeDesc.Name, existingMapping.Namespace)); + throw new InvalidOperationException(SR.Format(SR.XmlTypesDuplicate, typeDesc.FullName, existingMapping.TypeDesc!.FullName, typeDesc.Name, existingMapping.Namespace)); } } mapping = new NullableMapping(); @@ -685,36 +686,36 @@ private StructMapping GetRootMapping() return _root; } - private TypeMapping GetTypeMapping(string typeName, string ns, TypeDesc typeDesc, NameTable typeLib, Type type) + private TypeMapping? GetTypeMapping(string? typeName, string? ns, TypeDesc typeDesc, NameTable typeLib, Type? type) { - TypeMapping mapping; + TypeMapping? mapping; if (typeName == null || typeName.Length == 0) - mapping = type == null ? null : (TypeMapping)_anonymous[type]; + mapping = type == null ? null : (TypeMapping?)_anonymous[type]; else - mapping = (TypeMapping)typeLib[typeName, ns]; + mapping = (TypeMapping?)typeLib[typeName, ns]; if (mapping == null) return null; if (!mapping.IsAnonymousType && mapping.TypeDesc != typeDesc) - throw new InvalidOperationException(SR.Format(SR.XmlTypesDuplicate, typeDesc.FullName, mapping.TypeDesc.FullName, typeName, ns)); + throw new InvalidOperationException(SR.Format(SR.XmlTypesDuplicate, typeDesc.FullName, mapping.TypeDesc!.FullName, typeName, ns)); return mapping; } - private StructMapping ImportStructLikeMapping(StructModel model, string ns, bool openModel, XmlAttributes a, RecursionLimiter limiter) + private StructMapping ImportStructLikeMapping(StructModel model, string? ns, bool openModel, XmlAttributes? a, RecursionLimiter limiter) { if (model.TypeDesc.Kind == TypeKind.Root) return GetRootMapping(); if (a == null) a = GetAttributes(model.Type, false); - string typeNs = ns; + string? typeNs = ns; if (a.XmlType != null && a.XmlType.Namespace != null) typeNs = a.XmlType.Namespace; else if (a.XmlRoot != null && a.XmlRoot.Namespace != null) typeNs = a.XmlRoot.Namespace; - string typeName = IsAnonymousType(a, ns) ? null : XsdTypeName(model.Type, a, model.TypeDesc.Name); + string? typeName = IsAnonymousType(a, ns) ? null : XsdTypeName(model.Type, a, model.TypeDesc.Name); typeName = XmlConvert.EncodeLocalName(typeName); - StructMapping mapping = (StructMapping)GetTypeMapping(typeName, typeNs, model.TypeDesc, _types, model.Type); + StructMapping? mapping = (StructMapping?)GetTypeMapping(typeName, typeNs, model.TypeDesc, _types, model.Type); if (mapping == null) { mapping = new StructMapping(); @@ -764,18 +765,18 @@ private StructMapping ImportStructLikeMapping(StructModel model, string ns, bool return mapping; } - private bool InitializeStructMembers(StructMapping mapping, StructModel model, bool openModel, string typeName, RecursionLimiter limiter) + private bool InitializeStructMembers(StructMapping mapping, StructModel model, bool openModel, string? typeName, RecursionLimiter limiter) { if (mapping.IsFullyInitialized) return true; if (model.TypeDesc.BaseTypeDesc != null) { - TypeModel baseModel = _modelScope.GetTypeModel(model.Type.BaseType, false); + TypeModel baseModel = _modelScope.GetTypeModel(model.Type.BaseType!, false); if (!(baseModel is StructModel)) { //XmlUnsupportedInheritance=Using '{0}' as a base type for a class is not supported by XmlSerializer. - throw new NotSupportedException(SR.Format(SR.XmlUnsupportedInheritance, model.Type.BaseType.FullName)); + throw new NotSupportedException(SR.Format(SR.XmlUnsupportedInheritance, model.Type.BaseType!.FullName)); } StructMapping baseMapping = ImportStructLikeMapping((StructModel)baseModel, mapping.Namespace, openModel, null, limiter); // check to see if the import of the baseMapping was deferred @@ -817,7 +818,7 @@ private bool InitializeStructMembers(StructMapping mapping, StructModel model, b } } ArrayList members = new ArrayList(); - TextAccessor textAccessor = null; + TextAccessor? textAccessor = null; bool hasElements = false; bool isSequence = false; @@ -827,11 +828,11 @@ private bool InitializeStructMembers(StructMapping mapping, StructModel model, b continue; XmlAttributes memberAttrs = GetAttributes(memberInfo); if (memberAttrs.XmlIgnore) continue; - FieldModel fieldModel = model.GetFieldModel(memberInfo); + FieldModel? fieldModel = model.GetFieldModel(memberInfo); if (fieldModel == null) continue; try { - MemberMapping member = ImportFieldMapping(model, fieldModel, memberAttrs, mapping.Namespace, limiter); + MemberMapping? member = ImportFieldMapping(model, fieldModel, memberAttrs, mapping.Namespace, limiter); if (member == null) continue; if (mapping.BaseMapping != null) { @@ -843,7 +844,7 @@ private bool InitializeStructMembers(StructMapping mapping, StructModel model, b if (member.Text != null) { - if (!member.Text.Mapping.TypeDesc.CanBeTextValue && member.Text.Mapping.IsList) + if (!member.Text.Mapping!.TypeDesc!.CanBeTextValue && member.Text.Mapping.IsList) throw new InvalidOperationException(SR.Format(SR.XmlIllegalTypedTextAttribute, typeName, member.Text.Name, member.Text.Mapping.TypeDesc.FullName)); if (textAccessor != null) { @@ -878,7 +879,7 @@ private bool InitializeStructMembers(StructMapping mapping, StructModel model, b Hashtable ids = new Hashtable(); for (int i = 0; i < members.Count; i++) { - MemberMapping member = (MemberMapping)members[i]; + MemberMapping member = (MemberMapping)members[i]!; if (!member.IsParticle) continue; if (member.IsSequence) @@ -910,7 +911,7 @@ private bool InitializeStructMembers(StructMapping mapping, StructModel model, b return true; } - private static bool IsAnonymousType(XmlAttributes a, string contextNs) + private static bool IsAnonymousType(XmlAttributes a, string? contextNs) { if (a.XmlType != null && a.XmlType.AnonymousType) { @@ -920,7 +921,7 @@ private static bool IsAnonymousType(XmlAttributes a, string contextNs) // matches the original referencing element, otherwise revert to // non-Anonymous handling for backward compatibility. // - string originalNs = a.XmlType.Namespace; + string? originalNs = a.XmlType.Namespace; return string.IsNullOrEmpty(originalNs) || originalNs == contextNs; } return false; @@ -967,11 +968,11 @@ private static int CountAtLevel(XmlArrayItemAttributes attributes, int level) { int sum = 0; for (int i = 0; i < attributes.Count; i++) - if (attributes[i].NestingLevel == level) sum++; + if (attributes[i]!.NestingLevel == level) sum++; return sum; } - private void SetArrayMappingType(ArrayMapping mapping, string defaultNs, Type type) + private void SetArrayMappingType(ArrayMapping mapping, string? defaultNs, Type type) { XmlAttributes a = GetAttributes(type, false); bool isAnonymous = IsAnonymousType(a, defaultNs); @@ -981,12 +982,12 @@ private void SetArrayMappingType(ArrayMapping mapping, string defaultNs, Type ty mapping.Namespace = defaultNs; return; } - string name; - string ns; - TypeMapping itemTypeMapping; - ElementAccessor element = null; + string? name; + string? ns; + TypeMapping? itemTypeMapping; + ElementAccessor? element = null; - if (mapping.Elements.Length == 1) + if (mapping.Elements!.Length == 1) { element = mapping.Elements[0]; itemTypeMapping = element.Mapping; @@ -1012,9 +1013,9 @@ private void SetArrayMappingType(ArrayMapping mapping, string defaultNs, Type ty else if (itemTypeMapping is PrimitiveMapping) { ns = defaultNs; - name = itemTypeMapping.TypeDesc.DataType.Name; + name = itemTypeMapping.TypeDesc!.DataType!.Name; } - else if (itemTypeMapping is StructMapping && itemTypeMapping.TypeDesc.IsRoot) + else if (itemTypeMapping is StructMapping && itemTypeMapping.TypeDesc!.IsRoot) { ns = defaultNs; name = Soap.UrType; @@ -1041,7 +1042,7 @@ private void SetArrayMappingType(ArrayMapping mapping, string defaultNs, Type ty string uniqueName = name = generateTypeName ? "ArrayOf" + CodeIdentifier.MakePascal(name) : name; int i = 1; - TypeMapping existingMapping = (TypeMapping)_types[uniqueName, ns]; + TypeMapping? existingMapping = (TypeMapping?)_types[uniqueName, ns]; while (existingMapping != null) { if (existingMapping is ArrayMapping) @@ -1054,14 +1055,14 @@ private void SetArrayMappingType(ArrayMapping mapping, string defaultNs, Type ty } // need to re-name the mapping uniqueName = name + i.ToString(CultureInfo.InvariantCulture); - existingMapping = (TypeMapping)_types[uniqueName, ns]; + existingMapping = (TypeMapping?)_types[uniqueName, ns]; i++; } mapping.TypeName = uniqueName; mapping.Namespace = ns; } - private ArrayMapping ImportArrayLikeMapping(ArrayModel model, string ns, RecursionLimiter limiter) + private ArrayMapping ImportArrayLikeMapping(ArrayModel model, string? ns, RecursionLimiter limiter) { ArrayMapping mapping = new ArrayMapping(); mapping.TypeDesc = model.TypeDesc; @@ -1074,7 +1075,7 @@ private ArrayMapping ImportArrayLikeMapping(ArrayModel model, string ns, Recursi SetArrayMappingType(mapping, ns, model.Type); // reconcile accessors now that we have the ArrayMapping namespace - for (int i = 0; i < mapping.Elements.Length; i++) + for (int i = 0; i < mapping.Elements!.Length; i++) { mapping.Elements[i] = ReconcileLocalAccessor(mapping.Elements[i], mapping.Namespace); } @@ -1084,10 +1085,10 @@ private ArrayMapping ImportArrayLikeMapping(ArrayModel model, string ns, Recursi // in the case of an ArrayMapping we can have more that one mapping correspond to a type // examples of that are ArrayList and object[] both will map tp ArrayOfur-type // so we create a link list for all mappings of the same XSD type - ArrayMapping existingMapping = (ArrayMapping)_types[mapping.TypeName, mapping.Namespace]; + ArrayMapping? existingMapping = (ArrayMapping?)_types[mapping.TypeName, mapping.Namespace]; if (existingMapping != null) { - ArrayMapping first = existingMapping; + ArrayMapping? first = existingMapping; while (existingMapping != null) { if (existingMapping.TypeDesc == model.TypeDesc) @@ -1149,24 +1150,24 @@ private PrimitiveMapping ImportPrimitiveMapping(PrimitiveModel model, ImportCont { mapping.TypeDesc = model.TypeDesc; } - mapping.TypeName = mapping.TypeDesc.DataType.Name; + mapping.TypeName = mapping.TypeDesc.DataType!.Name; mapping.Namespace = mapping.TypeDesc.IsXsdType ? XmlSchema.Namespace : UrtTypes.Namespace; mapping.IsList = repeats; CheckContext(mapping.TypeDesc, context); return mapping; } - private EnumMapping ImportEnumMapping(EnumModel model, string ns, bool repeats) + private EnumMapping ImportEnumMapping(EnumModel model, string? ns, bool repeats) { XmlAttributes a = GetAttributes(model.Type, false); - string typeNs = ns; + string? typeNs = ns; if (a.XmlType != null && a.XmlType.Namespace != null) typeNs = a.XmlType.Namespace; - string typeName = IsAnonymousType(a, ns) ? null : XsdTypeName(model.Type, a, model.TypeDesc.Name); + string? typeName = IsAnonymousType(a, ns) ? null : XsdTypeName(model.Type, a, model.TypeDesc.Name); typeName = XmlConvert.EncodeLocalName(typeName); - EnumMapping mapping = (EnumMapping)GetTypeMapping(typeName, typeNs, model.TypeDesc, _types, model.Type); + EnumMapping? mapping = (EnumMapping?)GetTypeMapping(typeName, typeNs, model.TypeDesc, _types, model.Type); if (mapping == null) { mapping = new EnumMapping(); @@ -1185,7 +1186,7 @@ private EnumMapping ImportEnumMapping(EnumModel model, string ns, bool repeats) ArrayList constants = new ArrayList(); for (int i = 0; i < model.Constants.Length; i++) { - ConstantMapping constant = ImportConstantMapping(model.Constants[i]); + ConstantMapping? constant = ImportConstantMapping(model.Constants[i]); if (constant != null) constants.Add(constant); } if (constants.Count == 0) @@ -1198,7 +1199,7 @@ private EnumMapping ImportEnumMapping(EnumModel model, string ns, bool repeats) return mapping; } - private ConstantMapping ImportConstantMapping(ConstantModel model) + private ConstantMapping? ImportConstantMapping(ConstantModel model) { XmlAttributes a = GetAttributes(model.FieldInfo); if (a.XmlIgnore) return null; @@ -1221,7 +1222,7 @@ private MembersMapping ImportMembersMapping(XmlReflectionMember[] xmlReflectionM MemberMapping[] mappings = new MemberMapping[xmlReflectionMembers.Length]; NameTable elements = new NameTable(); NameTable attributes = new NameTable(); - TextAccessor textAccessor = null; + TextAccessor? textAccessor = null; bool isSequence = false; for (int i = 0; i < mappings.Length; i++) @@ -1295,7 +1296,7 @@ private MemberMapping ImportMemberMapping(XmlReflectionMember xmlReflectionMembe { XmlSchemaForm form = rpc ? XmlSchemaForm.Unqualified : XmlSchemaForm.Qualified; XmlAttributes a = xmlReflectionMember.XmlAttributes; - TypeDesc typeDesc = _typeScope.GetTypeDesc(xmlReflectionMember.MemberType); + TypeDesc typeDesc = _typeScope.GetTypeDesc(xmlReflectionMember.MemberType!); if (a.XmlFlags == 0) { @@ -1314,7 +1315,7 @@ private MemberMapping ImportMemberMapping(XmlReflectionMember xmlReflectionMembe // an XmlRoot attribute on the struct or class. if (typeDesc.IsStructLike) { - XmlAttributes structAttrs = new XmlAttributes(xmlReflectionMember.MemberType); + XmlAttributes structAttrs = new XmlAttributes(xmlReflectionMember.MemberType!); if (structAttrs.XmlRoot != null) { if (structAttrs.XmlRoot.ElementName.Length > 0) @@ -1347,23 +1348,23 @@ private MemberMapping ImportMemberMapping(XmlReflectionMember xmlReflectionMembe MemberMapping member = new MemberMapping(); member.Name = xmlReflectionMember.MemberName; bool checkSpecified = FindSpecifiedMember(xmlReflectionMember.MemberName, xmlReflectionMembers) != null; - FieldModel model = new FieldModel(xmlReflectionMember.MemberName, xmlReflectionMember.MemberType, _typeScope.GetTypeDesc(xmlReflectionMember.MemberType), checkSpecified, false); + FieldModel model = new FieldModel(xmlReflectionMember.MemberName, xmlReflectionMember.MemberType!, _typeScope.GetTypeDesc(xmlReflectionMember.MemberType!), checkSpecified, false); member.CheckShouldPersist = model.CheckShouldPersist; member.CheckSpecified = model.CheckSpecified; member.ReadOnly = model.ReadOnly; // || !model.FieldTypeDesc.HasDefaultConstructor; - Type choiceIdentifierType = null; + Type? choiceIdentifierType = null; if (a.XmlChoiceIdentifier != null) { choiceIdentifierType = GetChoiceIdentifierType(a.XmlChoiceIdentifier, xmlReflectionMembers, typeDesc.IsArrayLike, model.Name); } ImportAccessorMapping(member, model, a, ns, choiceIdentifierType, rpc, openModel, limiter); - if (xmlReflectionMember.OverrideIsNullable && member.Elements.Length > 0) + if (xmlReflectionMember.OverrideIsNullable && member.Elements!.Length > 0) member.Elements[0].IsNullable = false; return member; } - internal static XmlReflectionMember FindSpecifiedMember(string memberName, XmlReflectionMember[] reflectionMembers) + internal static XmlReflectionMember? FindSpecifiedMember(string memberName, XmlReflectionMember[] reflectionMembers) { for (int i = 0; i < reflectionMembers.Length; i++) if (string.Equals(reflectionMembers[i].MemberName, memberName + "Specified", StringComparison.Ordinal)) @@ -1371,7 +1372,7 @@ internal static XmlReflectionMember FindSpecifiedMember(string memberName, XmlRe return null; } - private MemberMapping ImportFieldMapping(StructModel parent, FieldModel model, XmlAttributes a, string ns, RecursionLimiter limiter) + private MemberMapping ImportFieldMapping(StructModel parent, FieldModel model, XmlAttributes a, string? ns, RecursionLimiter limiter) { MemberMapping member = new MemberMapping(); member.Name = model.Name; @@ -1381,7 +1382,7 @@ private MemberMapping ImportFieldMapping(StructModel parent, FieldModel model, X member.CheckSpecifiedMemberInfo = model.CheckSpecifiedMemberInfo; member.CheckShouldPersistMethodInfo = model.CheckShouldPersistMethodInfo; member.ReadOnly = model.ReadOnly; // || !model.FieldTypeDesc.HasDefaultConstructor; - Type choiceIdentifierType = null; + Type? choiceIdentifierType = null; if (a.XmlChoiceIdentifier != null) { choiceIdentifierType = GetChoiceIdentifierType(a.XmlChoiceIdentifier, parent, model.FieldTypeDesc.IsArrayLike, model.Name); @@ -1397,9 +1398,9 @@ private Type CheckChoiceIdentifierType(Type type, bool isArrayLike, string ident if (!isArrayLike) { // Inconsistent type of the choice identifier '{0}'. Please use {1}. - throw new InvalidOperationException(SR.Format(SR.XmlChoiceIdentifierType, identifierName, memberName, type.GetElementType().FullName)); + throw new InvalidOperationException(SR.Format(SR.XmlChoiceIdentifierType, identifierName, memberName, type.GetElementType()!.FullName)); } - type = type.GetElementType(); + type = type.GetElementType()!; } else if (isArrayLike) { @@ -1407,7 +1408,7 @@ private Type CheckChoiceIdentifierType(Type type, bool isArrayLike, string ident throw new InvalidOperationException(SR.Format(SR.XmlChoiceIdentifierArrayType, identifierName, memberName, type.FullName)); } - if (!type.IsEnum) + if (!type!.IsEnum) { // Choice identifier '{0}' must be an enum. throw new InvalidOperationException(SR.Format(SR.XmlChoiceIdentifierTypeEnum, identifierName)); @@ -1421,7 +1422,7 @@ private Type GetChoiceIdentifierType(XmlChoiceIdentifierAttribute choice, XmlRef { if (choice.MemberName == xmlReflectionMembers[i].MemberName) { - return CheckChoiceIdentifierType(xmlReflectionMembers[i].MemberType, isArrayLike, choice.MemberName, accessorName); + return CheckChoiceIdentifierType(xmlReflectionMembers[i].MemberType!, isArrayLike, choice.MemberName, accessorName); } } // Missing '{0}' needed for serialization of choice '{1}'. @@ -1436,7 +1437,7 @@ private Type GetChoiceIdentifierType(XmlChoiceIdentifierAttribute choice, Struct if (infos == null || infos.Length == 0) { // if we can not find the choice identifier between fields, check properties - PropertyInfo info = structModel.Type.GetProperty(choice.MemberName, BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static); + PropertyInfo? info = structModel.Type.GetProperty(choice.MemberName, BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static); if (info == null) { @@ -1451,7 +1452,7 @@ private Type GetChoiceIdentifierType(XmlChoiceIdentifierAttribute choice, Struct throw new InvalidOperationException(SR.Format(SR.XmlChoiceIdentiferAmbiguous, choice.MemberName)); } - FieldModel member = structModel.GetFieldModel(infos[0]); + FieldModel? member = structModel.GetFieldModel(infos[0]); if (member == null) { // Missing '{0}' needed for serialization of choice '{1}'. @@ -1463,13 +1464,13 @@ private Type GetChoiceIdentifierType(XmlChoiceIdentifierAttribute choice, Struct return enumType; } - private void CreateArrayElementsFromAttributes(ArrayMapping arrayMapping, XmlArrayItemAttributes attributes, Type arrayElementType, string arrayElementNs, RecursionLimiter limiter) + private void CreateArrayElementsFromAttributes(ArrayMapping arrayMapping, XmlArrayItemAttributes attributes, Type arrayElementType, string? arrayElementNs, RecursionLimiter limiter) { NameTable arrayItemElements = new NameTable(); // xmlelementname + xmlns -> ElementAccessor for (int i = 0; attributes != null && i < attributes.Count; i++) { - XmlArrayItemAttribute xmlArrayItem = attributes[i]; + XmlArrayItemAttribute xmlArrayItem = attributes[i]!; if (xmlArrayItem.NestingLevel != _arrayNestingLevel) continue; Type targetType = xmlArrayItem.Type != null ? xmlArrayItem.Type : arrayElementType; @@ -1487,13 +1488,13 @@ private void CreateArrayElementsFromAttributes(ArrayMapping arrayMapping, XmlArr arrayMapping.Elements = (ElementAccessor[])arrayItemElements.ToArray(typeof(ElementAccessor)); } - private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, XmlAttributes a, string ns, Type choiceIdentifierType, bool rpc, bool openModel, RecursionLimiter limiter) + private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, XmlAttributes a, string? ns, Type? choiceIdentifierType, bool rpc, bool openModel, RecursionLimiter limiter) { XmlSchemaForm elementFormDefault = XmlSchemaForm.Qualified; int previousNestingLevel = _arrayNestingLevel; int sequenceId = -1; - XmlArrayItemAttributes previousArrayItemAttributes = _savedArrayItemAttributes; - string previousArrayNamespace = _savedArrayNamespace; + XmlArrayItemAttributes? previousArrayItemAttributes = _savedArrayItemAttributes; + string? previousArrayNamespace = _savedArrayNamespace; _arrayNestingLevel = 0; _savedArrayItemAttributes = null; _savedArrayNamespace = null; @@ -1523,20 +1524,20 @@ private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, Xml accessor.ChoiceIdentifier = new ChoiceIdentifierAccessor(); accessor.ChoiceIdentifier.MemberName = a.XmlChoiceIdentifier.MemberName; accessor.ChoiceIdentifier.MemberInfo = a.XmlChoiceIdentifier.GetMemberInfo(); - accessor.ChoiceIdentifier.Mapping = ImportTypeMapping(_modelScope.GetTypeModel(choiceIdentifierType), ns, ImportContext.Element, string.Empty, null, limiter); + accessor.ChoiceIdentifier.Mapping = ImportTypeMapping(_modelScope.GetTypeModel(choiceIdentifierType!), ns, ImportContext.Element, string.Empty, null, limiter); CheckChoiceIdentifierMapping((EnumMapping)accessor.ChoiceIdentifier.Mapping); } if (accessor.TypeDesc.IsArrayLike) { - Type arrayElementType = TypeScope.GetArrayElementType(accessorType, model.FieldTypeDesc.FullName + "." + model.Name); + Type arrayElementType = TypeScope.GetArrayElementType(accessorType, model.FieldTypeDesc.FullName + "." + model.Name)!; if ((flags & attrFlags) != 0) { if ((flags & attrFlags) != flags) throw new InvalidOperationException(SR.XmlIllegalAttributesArrayAttribute); - if (a.XmlAttribute != null && !accessor.TypeDesc.ArrayElementTypeDesc.IsPrimitive && !accessor.TypeDesc.ArrayElementTypeDesc.IsEnum) + if (a.XmlAttribute != null && !accessor.TypeDesc.ArrayElementTypeDesc!.IsPrimitive && !accessor.TypeDesc.ArrayElementTypeDesc.IsEnum) { if (accessor.TypeDesc.ArrayElementTypeDesc.Kind == TypeKind.Serializable) { @@ -1548,7 +1549,7 @@ private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, Xml } } - bool isList = a.XmlAttribute != null && (accessor.TypeDesc.ArrayElementTypeDesc.IsPrimitive || accessor.TypeDesc.ArrayElementTypeDesc.IsEnum); + bool isList = a.XmlAttribute != null && (accessor.TypeDesc.ArrayElementTypeDesc!.IsPrimitive || accessor.TypeDesc.ArrayElementTypeDesc.IsEnum); if (a.XmlAnyAttribute != null) { @@ -1556,7 +1557,7 @@ private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, Xml } AttributeAccessor attribute = new AttributeAccessor(); - Type targetType = a.XmlAttribute.Type == null ? arrayElementType : a.XmlAttribute.Type; + Type targetType = a.XmlAttribute!.Type == null ? arrayElementType : a.XmlAttribute.Type!; TypeDesc targetTypeDesc = _typeScope.GetTypeDesc(targetType); attribute.Name = Accessor.EscapeQName(a.XmlAttribute.AttributeName.Length == 0 ? accessorName : a.XmlAttribute.AttributeName); attribute.Namespace = a.XmlAttribute.Namespace == null ? ns : a.XmlAttribute.Namespace; @@ -1601,7 +1602,7 @@ private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, Xml for (int i = 0; i < a.XmlElements.Count; i++) { - XmlElementAttribute xmlElement = a.XmlElements[i]; + XmlElementAttribute xmlElement = a.XmlElements[i]!; Type targetType = xmlElement.Type == null ? arrayElementType : xmlElement.Type; TypeDesc targetTypeDesc = _typeScope.GetTypeDesc(targetType); TypeModel typeModel = _modelScope.GetTypeModel(targetType); @@ -1620,7 +1621,7 @@ private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, Xml element.Default = GetDefaultValue(model.FieldTypeDesc, model.FieldType, a); if (xmlElement.GetIsNullableSpecified() && !xmlElement.IsNullable && typeModel.TypeDesc.IsOptionalValue) //XmlInvalidNotNullable=IsNullable may not be set to 'false' for a Nullable<{0}> type. Consider using '{0}' type or removing the IsNullable property from the XmlElement attribute. - throw new InvalidOperationException(SR.Format(SR.XmlInvalidNotNullable, typeModel.TypeDesc.BaseTypeDesc.FullName, "XmlElement")); + throw new InvalidOperationException(SR.Format(SR.XmlInvalidNotNullable, typeModel.TypeDesc.BaseTypeDesc!.FullName, "XmlElement")); element.IsNullable = xmlElement.GetIsNullableSpecified() ? xmlElement.IsNullable : typeModel.TypeDesc.IsOptionalValue; element.Form = rpc ? XmlSchemaForm.Unqualified : xmlElement.Form == XmlSchemaForm.None ? elementFormDefault : xmlElement.Form; @@ -1642,12 +1643,12 @@ private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, Xml NameTable anys = new NameTable(); for (int i = 0; i < a.XmlAnyElements.Count; i++) { - XmlAnyElementAttribute xmlAnyElement = a.XmlAnyElements[i]; + XmlAnyElementAttribute xmlAnyElement = a.XmlAnyElements[i]!; Type targetType = typeof(IXmlSerializable).IsAssignableFrom(arrayElementType) ? arrayElementType : typeof(XmlNode).IsAssignableFrom(arrayElementType) ? arrayElementType : typeof(XmlElement); if (!arrayElementType.IsAssignableFrom(targetType)) throw new InvalidOperationException(SR.Format(SR.XmlIllegalAnyElement, arrayElementType.FullName)); string anyName = xmlAnyElement.Name.Length == 0 ? xmlAnyElement.Name : XmlConvert.EncodeLocalName(xmlAnyElement.Name); - string anyNs = xmlAnyElement.GetNamespaceSpecified() ? xmlAnyElement.Namespace : null; + string? anyNs = xmlAnyElement.GetNamespaceSpecified() ? xmlAnyElement.Namespace : null; if (anys[anyName, anyNs] != null) { // ignore duplicate anys @@ -1777,8 +1778,8 @@ private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, Xml for (int i = 0; i < a.XmlElements.Count; i++) { - XmlElementAttribute xmlElement = a.XmlElements[i]; - if (xmlElement.Type != null) + XmlElementAttribute xmlElement = a.XmlElements[i]!; + if (xmlElement!.Type != null) { if (_typeScope.GetTypeDesc(xmlElement.Type) != accessor.TypeDesc) throw new InvalidOperationException(SR.Format(SR.XmlIllegalType, "XmlElement")); @@ -1788,14 +1789,14 @@ private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, Xml element.Namespace = rpc ? null : xmlElement.Namespace == null ? ns : xmlElement.Namespace; TypeModel typeModel = _modelScope.GetTypeModel(accessorType); element.Mapping = ImportTypeMapping(typeModel, rpc ? ns : element.Namespace, ImportContext.Element, xmlElement.DataType, null, limiter); - if (element.Mapping.TypeDesc.Kind == TypeKind.Node) + if (element.Mapping.TypeDesc!.Kind == TypeKind.Node) { element.Any = true; } element.Default = GetDefaultValue(model.FieldTypeDesc, model.FieldType, a); if (xmlElement.GetIsNullableSpecified() && !xmlElement.IsNullable && typeModel.TypeDesc.IsOptionalValue) //XmlInvalidNotNullable=IsNullable may not be set to 'false' for a Nullable<{0}> type. Consider using '{0}' type or removing the IsNullable property from the XmlElement attribute. - throw new InvalidOperationException(SR.Format(SR.XmlInvalidNotNullable, typeModel.TypeDesc.BaseTypeDesc.FullName, "XmlElement")); + throw new InvalidOperationException(SR.Format(SR.XmlInvalidNotNullable, typeModel.TypeDesc.BaseTypeDesc!.FullName, "XmlElement")); element.IsNullable = xmlElement.GetIsNullableSpecified() ? xmlElement.IsNullable : typeModel.TypeDesc.IsOptionalValue; element.Form = rpc ? XmlSchemaForm.Unqualified : xmlElement.Form == XmlSchemaForm.None ? elementFormDefault : xmlElement.Form; @@ -1845,7 +1846,7 @@ private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, Xml a.XmlElements.Add(CreateElementAttribute(accessor.TypeDesc)); for (int i = 0; i < a.XmlElements.Count; i++) { - XmlElementAttribute xmlElement = a.XmlElements[i]; + XmlElementAttribute xmlElement = a.XmlElements[i]!; Type targetType = xmlElement.Type == null ? accessorType : xmlElement.Type; TypeDesc targetTypeDesc = _typeScope.GetTypeDesc(targetType); ElementAccessor element = new ElementAccessor(); @@ -1863,7 +1864,7 @@ private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, Xml element.Default = GetDefaultValue(model.FieldTypeDesc, model.FieldType, a); if (xmlElement.GetIsNullableSpecified() && !xmlElement.IsNullable && typeModel.TypeDesc.IsOptionalValue) //XmlInvalidNotNullable=IsNullable may not be set to 'false' for a Nullable<{0}> type. Consider using '{0}' type or removing the IsNullable property from the XmlElement attribute. - throw new InvalidOperationException(SR.Format(SR.XmlInvalidNotNullable, typeModel.TypeDesc.BaseTypeDesc.FullName, "XmlElement")); + throw new InvalidOperationException(SR.Format(SR.XmlInvalidNotNullable, typeModel.TypeDesc.BaseTypeDesc!.FullName, "XmlElement")); element.IsNullable = xmlElement.GetIsNullableSpecified() ? xmlElement.IsNullable : typeModel.TypeDesc.IsOptionalValue; element.Form = rpc ? XmlSchemaForm.Unqualified : xmlElement.Form == XmlSchemaForm.None ? elementFormDefault : xmlElement.Form; CheckNullable(element.IsNullable, targetTypeDesc, element.Mapping); @@ -1885,13 +1886,13 @@ private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, Xml NameTable anys = new NameTable(); for (int i = 0; i < a.XmlAnyElements.Count; i++) { - XmlAnyElementAttribute xmlAnyElement = a.XmlAnyElements[i]; + XmlAnyElementAttribute xmlAnyElement = a.XmlAnyElements[i]!; Type targetType = typeof(IXmlSerializable).IsAssignableFrom(accessorType) ? accessorType : typeof(XmlNode).IsAssignableFrom(accessorType) ? accessorType : typeof(XmlElement); if (!accessorType.IsAssignableFrom(targetType)) throw new InvalidOperationException(SR.Format(SR.XmlIllegalAnyElement, accessorType.FullName)); string anyName = xmlAnyElement.Name.Length == 0 ? xmlAnyElement.Name : XmlConvert.EncodeLocalName(xmlAnyElement.Name); - string anyNs = xmlAnyElement.GetNamespaceSpecified() ? xmlAnyElement.Namespace : null; + string? anyNs = xmlAnyElement.GetNamespaceSpecified() ? xmlAnyElement.Namespace : null; if (anys[anyName, anyNs] != null) { // ignore duplicate anys @@ -1953,8 +1954,8 @@ private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, Xml { bool found = false; ElementAccessor element = accessor.Elements[i]; - EnumMapping choiceMapping = (EnumMapping)accessor.ChoiceIdentifier.Mapping; - for (int j = 0; j < choiceMapping.Constants.Length; j++) + EnumMapping choiceMapping = (EnumMapping)accessor.ChoiceIdentifier.Mapping!; + for (int j = 0; j < choiceMapping.Constants!.Length; j++) { string xmlName = choiceMapping.Constants[j].XmlName; @@ -1970,7 +1971,7 @@ private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, Xml continue; } int colon = xmlName.LastIndexOf(':'); - string choiceNs = colon < 0 ? choiceMapping.Namespace : xmlName.Substring(0, colon); + string? choiceNs = colon < 0 ? choiceMapping.Namespace : xmlName.Substring(0, colon); string choiceName = colon < 0 ? xmlName : xmlName.Substring(colon + 1); if (element.Name == choiceName) @@ -1988,13 +1989,13 @@ private void ImportAccessorMapping(MemberMapping accessor, FieldModel model, Xml if (element.Any && element.Name.Length == 0) { // Type {0} is missing enumeration value '##any' for XmlAnyElementAttribute. - throw new InvalidOperationException(SR.Format(SR.XmlChoiceMissingAnyValue, accessor.ChoiceIdentifier.Mapping.TypeDesc.FullName)); + throw new InvalidOperationException(SR.Format(SR.XmlChoiceMissingAnyValue, accessor.ChoiceIdentifier.Mapping!.TypeDesc!.FullName)); } else { string id = element.Namespace != null && element.Namespace.Length > 0 ? element.Namespace + ":" + element.Name : element.Name; // Type {0} is missing value for '{1}'. - throw new InvalidOperationException(SR.Format(SR.XmlChoiceMissingValue, accessor.ChoiceIdentifier.Mapping.TypeDesc.FullName, id, element.Name, element.Namespace)); + throw new InvalidOperationException(SR.Format(SR.XmlChoiceMissingValue, accessor.ChoiceIdentifier.Mapping!.TypeDesc!.FullName, id, element.Name, element.Namespace)); } } } @@ -2021,7 +2022,7 @@ private void CheckTopLevelAttributes(XmlAttributes a, string accessorName) { throw new InvalidOperationException(SR.XmlRpcLitElements); } - XmlElementAttribute xmlElement = a.XmlElements[0]; + XmlElementAttribute xmlElement = a.XmlElements[0]!; if (xmlElement.Namespace != null) { throw new InvalidOperationException(SR.Format(SR.XmlRpcLitElementNamespace, "Namespace", xmlElement.Namespace)); @@ -2046,7 +2047,7 @@ private void CheckAmbiguousChoice(XmlAttributes a, Type accessorType, string acc { for (int i = 0; i < elements.Count; i++) { - Type type = elements[i].Type == null ? accessorType : elements[i].Type; + Type type = elements[i]!.Type == null ? accessorType : elements[i]!.Type!; if (choiceTypes.Contains(type)) { // You need to add {0} to the '{1}'. @@ -2071,12 +2072,12 @@ private void CheckAmbiguousChoice(XmlAttributes a, Type accessorType, string acc for (int i = 0; i < items.Count; i++) { - Type type = items[i].Type == null ? accessorType : items[i].Type; - string ns = items[i].NestingLevel.ToString(CultureInfo.InvariantCulture); - XmlArrayItemAttribute item = (XmlArrayItemAttribute)arrayTypes[type.FullName, ns]; + Type type = items[i]!.Type == null ? accessorType : items[i]!.Type!; + string ns = items[i]!.NestingLevel.ToString(CultureInfo.InvariantCulture); + XmlArrayItemAttribute? item = (XmlArrayItemAttribute?)arrayTypes[type.FullName, ns]; if (item != null) { - throw new InvalidOperationException(SR.Format(SR.XmlArrayItemAmbiguousTypes, accessorName, item.ElementName, items[i].ElementName, typeof(XmlElementAttribute).Name, typeof(XmlChoiceIdentifierAttribute).Name, accessorName)); + throw new InvalidOperationException(SR.Format(SR.XmlArrayItemAmbiguousTypes, accessorName, item.ElementName, items[i]!.ElementName, typeof(XmlElementAttribute).Name, typeof(XmlChoiceIdentifierAttribute).Name, accessorName)); } else { @@ -2089,7 +2090,7 @@ private void CheckAmbiguousChoice(XmlAttributes a, Type accessorType, string acc private void CheckChoiceIdentifierMapping(EnumMapping choiceMapping) { NameTable ids = new NameTable(); - for (int i = 0; i < choiceMapping.Constants.Length; i++) + for (int i = 0; i < choiceMapping.Constants!.Length; i++) { string choiceId = choiceMapping.Constants[i].XmlName; int colon = choiceId.LastIndexOf(':'); @@ -2105,7 +2106,7 @@ private void CheckChoiceIdentifierMapping(EnumMapping choiceMapping) } } - private object GetDefaultValue(TypeDesc fieldTypeDesc, Type t, XmlAttributes a) + private object? GetDefaultValue(TypeDesc fieldTypeDesc, Type t, XmlAttributes a) { if (a.XmlDefaultValue == null || a.XmlDefaultValue == DBNull.Value) return null; if (!(fieldTypeDesc.Kind == TypeKind.Primitive || fieldTypeDesc.Kind == TypeKind.Enum)) @@ -2148,7 +2149,7 @@ private static XmlElementAttribute CreateElementAttribute(TypeDesc typeDesc) private static void AddUniqueAccessor(INameScope scope, Accessor accessor) { - Accessor existing = (Accessor)scope[accessor.Name, accessor.Namespace]; + Accessor? existing = (Accessor?)scope[accessor.Name, accessor.Namespace]; if (existing != null) { if (accessor is ElementAccessor) @@ -2190,7 +2191,7 @@ private static void CheckForm(XmlSchemaForm form, bool isQualified) if (isQualified && form == XmlSchemaForm.Unqualified) throw new InvalidOperationException(SR.XmlInvalidFormUnqualified); } - private static void CheckNullable(bool isNullable, TypeDesc typeDesc, TypeMapping mapping) + private static void CheckNullable(bool isNullable, TypeDesc typeDesc, TypeMapping? mapping) { if (mapping is NullableMapping) return; if (mapping is SerializableMapping) return; @@ -2200,7 +2201,7 @@ private static void CheckNullable(bool isNullable, TypeDesc typeDesc, TypeMappin private static ElementAccessor CreateElementAccessor(TypeMapping mapping, string ns) { ElementAccessor element = new ElementAccessor(); - bool isAny = mapping.TypeDesc.Kind == TypeKind.Node; + bool isAny = mapping.TypeDesc!.Kind == TypeKind.Node; if (!isAny && mapping is SerializableMapping) { isAny = ((SerializableMapping)mapping).IsAny; @@ -2219,7 +2220,7 @@ private static ElementAccessor CreateElementAccessor(TypeMapping mapping, string } // will create a shallow type mapping for a top-level type - internal static XmlTypeMapping GetTopLevelMapping(Type type, string defaultNamespace) + internal static XmlTypeMapping GetTopLevelMapping(Type type, string? defaultNamespace) { defaultNamespace = defaultNamespace ?? string.Empty; XmlAttributes a = new XmlAttributes(type); @@ -2232,7 +2233,7 @@ internal static XmlTypeMapping GetTopLevelMapping(Type type, string defaultNames } else { - string ns = a.XmlRoot == null ? defaultNamespace : a.XmlRoot.Namespace; + string? ns = a.XmlRoot == null ? defaultNamespace : a.XmlRoot.Namespace; string typeName = string.Empty; if (a.XmlType != null) typeName = a.XmlType.TypeName; @@ -2270,7 +2271,7 @@ internal ImportStructWorkItem this[int index] { get { - return (ImportStructWorkItem)_list[index]; + return (ImportStructWorkItem)_list[index]!; } set { @@ -2316,7 +2317,7 @@ internal class RecursionLimiter { private readonly int _maxDepth; private int _depth; - private WorkItems _deferredWorkItems; + private WorkItems? _deferredWorkItems; internal RecursionLimiter() { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionMember.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionMember.cs index fa4e204cf73ab2..e7f33264760745 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionMember.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionMember.cs @@ -1,10 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; using System.Xml.Serialization; - namespace System.Xml.Serialization { /// @@ -13,8 +13,8 @@ namespace System.Xml.Serialization /// public class XmlReflectionMember { - private string _memberName; - private Type _type; + private string? _memberName; + private Type? _type; private XmlAttributes _xmlAttributes = new XmlAttributes(); private SoapAttributes _soapAttributes = new SoapAttributes(); private bool _isReturnValue; @@ -23,7 +23,7 @@ public class XmlReflectionMember /// /// [To be supplied.] /// - public Type MemberType + public Type? MemberType { get { return _type; } set { _type = value; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlRootAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlRootAttribute.cs index d4dda29a98296b..9caa2008b20d57 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlRootAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlRootAttribute.cs @@ -5,7 +5,9 @@ // //------------------------------------------------------------------------------ +#nullable enable using System; +using System.Diagnostics.CodeAnalysis; using System.Xml.Schema; @@ -17,9 +19,9 @@ namespace System.Xml.Serialization [AttributeUsage(AttributeTargets.ReturnValue | AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Struct)] public class XmlRootAttribute : System.Attribute { - private string _elementName; - private string _ns; - private string _dataType; + private string? _elementName; + private string? _ns; + private string? _dataType; private bool _nullable = true; private bool _nullableSpecified; @@ -50,7 +52,7 @@ public string ElementName /// /// [To be supplied.] /// - public string Namespace + public string? Namespace { get { return _ns; } set { _ns = value; } @@ -59,6 +61,7 @@ public string Namespace /// /// [To be supplied.] /// + [AllowNull] public string DataType { get { return _dataType == null ? string.Empty : _dataType; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaExporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaExporter.cs index f8ba7df0f1f90a..96420be17f9f96 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaExporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaExporter.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; @@ -22,7 +23,7 @@ public class XmlSchemaExporter private readonly Hashtable _types = new Hashtable(); // StructMapping/EnumMapping -> XmlSchemaComplexType/XmlSchemaSimpleType private readonly Hashtable _references = new Hashtable(); // TypeMappings to keep track of circular references via anonymous types private bool _needToExportRoot; - private TypeScope _scope; + private TypeScope? _scope; public XmlSchemaExporter(XmlSchemas schemas) { @@ -34,24 +35,24 @@ public void ExportTypeMapping(XmlTypeMapping xmlTypeMapping) xmlTypeMapping.CheckShallow(); CheckScope(xmlTypeMapping.Scope); ExportElement(xmlTypeMapping.Accessor); - ExportRootIfNecessary(xmlTypeMapping.Scope); + ExportRootIfNecessary(xmlTypeMapping.Scope!); } - public XmlQualifiedName ExportTypeMapping(XmlMembersMapping xmlMembersMapping) + public XmlQualifiedName? ExportTypeMapping(XmlMembersMapping xmlMembersMapping) { xmlMembersMapping.CheckShallow(); - CheckScope(xmlMembersMapping.Scope); - MembersMapping mapping = (MembersMapping)xmlMembersMapping.Accessor.Mapping; - if (mapping.Members.Length == 1 && mapping.Members[0].Elements[0].Mapping is SpecialMapping) + CheckScope(xmlMembersMapping.Scope!); + MembersMapping mapping = (MembersMapping)xmlMembersMapping.Accessor.Mapping!; + if (mapping.Members!.Length == 1 && mapping.Members[0].Elements![0].Mapping is SpecialMapping) { - SpecialMapping special = (SpecialMapping)mapping.Members[0].Elements[0].Mapping; - XmlSchemaType type = ExportSpecialMapping(special, xmlMembersMapping.Accessor.Namespace, false, null); + SpecialMapping special = (SpecialMapping)mapping.Members[0].Elements![0].Mapping!; + XmlSchemaType? type = ExportSpecialMapping(special, xmlMembersMapping.Accessor.Namespace, false, null); if (type != null && type.Name != null && type.Name.Length > 0) { type.Name = xmlMembersMapping.Accessor.Name; AddSchemaItem(type, xmlMembersMapping.Accessor.Namespace, null); } - ExportRootIfNecessary(xmlMembersMapping.Scope); + ExportRootIfNecessary(xmlMembersMapping.Scope!); return (new XmlQualifiedName(xmlMembersMapping.Accessor.Name, xmlMembersMapping.Accessor.Namespace)); } return null; @@ -65,7 +66,7 @@ public void ExportMembersMapping(XmlMembersMapping xmlMembersMapping) public void ExportMembersMapping(XmlMembersMapping xmlMembersMapping, bool exportEnclosingType) { xmlMembersMapping.CheckShallow(); - MembersMapping mapping = (MembersMapping)xmlMembersMapping.Accessor.Mapping; + MembersMapping mapping = (MembersMapping)xmlMembersMapping.Accessor.Mapping!; CheckScope(xmlMembersMapping.Scope); if (mapping.HasWrapperElement && exportEnclosingType) { @@ -73,7 +74,7 @@ public void ExportMembersMapping(XmlMembersMapping xmlMembersMapping, bool expor } else { - foreach (MemberMapping member in mapping.Members) + foreach (MemberMapping member in mapping.Members!) { if (member.Attribute != null) throw new InvalidOperationException(SR.Format(SR.XmlBareAttributeMember, member.Attribute.Name)); @@ -82,7 +83,7 @@ public void ExportMembersMapping(XmlMembersMapping xmlMembersMapping, bool expor else if (member.Elements == null || member.Elements.Length == 0) continue; - if (member.TypeDesc.IsArrayLike && !(member.Elements[0].Mapping is ArrayMapping)) + if (member.TypeDesc!.IsArrayLike && !(member.Elements[0].Mapping is ArrayMapping)) throw new InvalidOperationException(SR.Format(SR.XmlIllegalArrayElement, member.Elements[0].Name)); if (exportEnclosingType) @@ -91,19 +92,19 @@ public void ExportMembersMapping(XmlMembersMapping xmlMembersMapping, bool expor } else { - ExportMapping(member.Elements[0].Mapping, member.Elements[0].Namespace, member.Elements[0].Any); + ExportMapping(member.Elements[0].Mapping!, member.Elements[0].Namespace, member.Elements[0].Any); } } } - ExportRootIfNecessary(xmlMembersMapping.Scope); + ExportRootIfNecessary(xmlMembersMapping.Scope!); } - private static XmlSchemaType FindSchemaType(string name, XmlSchemaObjectCollection items) + private static XmlSchemaType? FindSchemaType(string name, XmlSchemaObjectCollection items) { // Have to loop through the items because schema.SchemaTypes has not been populated yet. foreach (object o in items) { - XmlSchemaType type = o as XmlSchemaType; + XmlSchemaType? type = o as XmlSchemaType; if (type == null) continue; if (type.Name == name) @@ -114,7 +115,7 @@ private static XmlSchemaType FindSchemaType(string name, XmlSchemaObjectCollecti private static bool IsAnyType(XmlSchemaType schemaType, bool mixed, bool unbounded) { - XmlSchemaComplexType complexType = schemaType as XmlSchemaComplexType; + XmlSchemaComplexType? complexType = schemaType as XmlSchemaComplexType; if (complexType != null) { if (complexType.IsMixed != mixed) @@ -136,12 +137,12 @@ public string ExportAnyType(string ns) { string name = "any"; int i = 0; - XmlSchema schema = _schemas[ns]; + XmlSchema? schema = _schemas[ns]; if (schema != null) { while (true) { - XmlSchemaType schemaType = FindSchemaType(name, schema.Items); + XmlSchemaType? schemaType = FindSchemaType(name, schema.Items); if (schemaType == null) break; if (IsAnyType(schemaType, true, true)) @@ -164,13 +165,13 @@ public string ExportAnyType(string ns) return name; } - public string ExportAnyType(XmlMembersMapping members) + public string? ExportAnyType(XmlMembersMapping members) { if (members.Count == 1 && members[0].Any && members[0].ElementName.Length == 0) { XmlMemberMapping member = members[0]; - string ns = member.Namespace; - bool isUnbounded = member.Mapping.TypeDesc.IsArrayLike; + string? ns = member.Namespace; + bool isUnbounded = member.Mapping.TypeDesc!.IsArrayLike; bool isMixed = isUnbounded && member.Mapping.TypeDesc.ArrayElementTypeDesc != null ? member.Mapping.TypeDesc.ArrayElementTypeDesc.IsMixed : member.Mapping.TypeDesc.IsMixed; if (isMixed && member.Mapping.TypeDesc.IsMixed) @@ -181,12 +182,12 @@ public string ExportAnyType(XmlMembersMapping members) string baseName = isMixed ? "any" : isUnbounded ? "anyElements" : "anyElement"; string name = baseName; int i = 0; - XmlSchema schema = _schemas[ns]; + XmlSchema? schema = _schemas[ns]; if (schema != null) { while (true) { - XmlSchemaType schemaType = FindSchemaType(name, schema.Items); + XmlSchemaType? schemaType = FindSchemaType(name, schema.Items); if (schemaType == null) break; if (IsAnyType(schemaType, isMixed, isUnbounded)) @@ -215,7 +216,7 @@ public string ExportAnyType(XmlMembersMapping members) } } - private void CheckScope(TypeScope scope) + private void CheckScope(TypeScope? scope) { if (_scope == null) { @@ -227,15 +228,15 @@ private void CheckScope(TypeScope scope) } } - private XmlSchemaElement ExportElement(ElementAccessor accessor) + private XmlSchemaElement? ExportElement(ElementAccessor accessor) { - if (!accessor.Mapping.IncludeInSchema && !accessor.Mapping.TypeDesc.IsRoot) + if (!accessor.Mapping!.IncludeInSchema && !accessor.Mapping.TypeDesc!.IsRoot) { return null; } if (accessor.Any && accessor.Name.Length == 0) throw new InvalidOperationException(SR.XmlIllegalWildcard); - XmlSchemaElement element = (XmlSchemaElement)_elements[accessor]; + XmlSchemaElement? element = (XmlSchemaElement?)_elements[accessor]; if (element != null) return element; element = new XmlSchemaElement(); element.Name = accessor.Name; @@ -247,24 +248,24 @@ private XmlSchemaElement ExportElement(ElementAccessor accessor) return element; } - private void CheckForDuplicateType(TypeMapping mapping, string newNamespace) + private void CheckForDuplicateType(TypeMapping mapping, string? newNamespace) { if (mapping.IsAnonymousType) return; - string newTypeName = mapping.TypeName; - XmlSchema schema = _schemas[newNamespace]; + string? newTypeName = mapping.TypeName; + XmlSchema? schema = _schemas[newNamespace]; if (schema != null) { foreach (XmlSchemaObject o in schema.Items) { - XmlSchemaType type = o as XmlSchemaType; + XmlSchemaType? type = o as XmlSchemaType; if (type != null && type.Name == newTypeName) throw new InvalidOperationException(SR.Format(SR.XmlDuplicateTypeName, newTypeName, newNamespace)); } } } - private XmlSchema AddSchema(string targetNamespace) + private XmlSchema AddSchema(string? targetNamespace) { XmlSchema schema = new XmlSchema(); schema.TargetNamespace = string.IsNullOrEmpty(targetNamespace) ? null : targetNamespace; @@ -278,9 +279,9 @@ private XmlSchema AddSchema(string targetNamespace) return schema; } - private void AddSchemaItem(XmlSchemaObject item, string ns, string referencingNs) + private void AddSchemaItem(XmlSchemaObject item, string? ns, string? referencingNs) { - XmlSchema schema = _schemas[ns]; + XmlSchema? schema = _schemas[ns]; if (schema == null) { schema = AddSchema(ns); @@ -304,11 +305,11 @@ private void AddSchemaItem(XmlSchemaObject item, string ns, string referencingNs AddSchemaImport(ns, referencingNs); } - private void AddSchemaImport(string ns, string referencingNs) + private void AddSchemaImport(string? ns, string? referencingNs) { if (referencingNs == null) return; if (NamespacesEqual(ns, referencingNs)) return; - XmlSchema schema = _schemas[referencingNs]; + XmlSchema? schema = _schemas[referencingNs]; if (schema == null) { schema = AddSchema(referencingNs); @@ -322,7 +323,7 @@ private void AddSchemaImport(string ns, string referencingNs) } } - private static bool NamespacesEqual(string ns1, string ns2) + private static bool NamespacesEqual(string? ns1, string? ns2) { if (ns1 == null || ns1.Length == 0) return (ns2 == null || ns2.Length == 0); @@ -332,7 +333,7 @@ private static bool NamespacesEqual(string ns1, string ns2) private bool SchemaContainsItem(XmlSchemaObject item, string ns) { - XmlSchema schema = _schemas[ns]; + XmlSchema? schema = _schemas[ns]; if (schema != null) { return schema.Items.Contains(item); @@ -340,7 +341,7 @@ private bool SchemaContainsItem(XmlSchemaObject item, string ns) return false; } - private XmlSchemaImport FindImport(XmlSchema schema, string ns) + private XmlSchemaImport? FindImport(XmlSchema schema, string? ns) { foreach (object item in schema.Includes) { @@ -356,7 +357,7 @@ private XmlSchemaImport FindImport(XmlSchema schema, string ns) return null; } - private void ExportMapping(Mapping mapping, string ns, bool isAny) + private void ExportMapping(Mapping mapping, string? ns, bool isAny) { if (mapping is ArrayMapping) ExportArrayMapping((ArrayMapping)mapping, ns, null); @@ -371,12 +372,12 @@ private void ExportMapping(Mapping mapping, string ns, bool isAny) else if (mapping is SpecialMapping) ExportSpecialMapping((SpecialMapping)mapping, ns, isAny, null); else if (mapping is NullableMapping) - ExportMapping(((NullableMapping)mapping).BaseMapping, ns, isAny); + ExportMapping(((NullableMapping)mapping).BaseMapping!, ns, isAny); else throw new ArgumentException(SR.XmlInternalError, nameof(mapping)); } - private void ExportElementMapping(XmlSchemaElement element, Mapping mapping, string ns, bool isAny) + private void ExportElementMapping(XmlSchemaElement element, Mapping mapping, string? ns, bool isAny) { if (mapping is ArrayMapping) ExportArrayMapping((ArrayMapping)mapping, ns, element); @@ -402,15 +403,15 @@ private void ExportElementMapping(XmlSchemaElement element, Mapping mapping, str ExportSpecialMapping((SpecialMapping)mapping, ns, isAny, element); else if (mapping is NullableMapping) { - ExportElementMapping(element, ((NullableMapping)mapping).BaseMapping, ns, isAny); + ExportElementMapping(element, ((NullableMapping)mapping).BaseMapping!, ns, isAny); } else throw new ArgumentException(SR.XmlInternalError, nameof(mapping)); } - private XmlQualifiedName ExportNonXsdPrimitiveMapping(PrimitiveMapping mapping, string ns) + private XmlQualifiedName ExportNonXsdPrimitiveMapping(PrimitiveMapping mapping, string? ns) { - XmlSchemaSimpleType type = (XmlSchemaSimpleType)mapping.TypeDesc.DataType; + XmlSchemaSimpleType type = (XmlSchemaSimpleType)mapping.TypeDesc!.DataType!; if (!SchemaContainsItem(type, UrtTypes.Namespace)) { AddSchemaItem(type, UrtTypes.Namespace, ns); @@ -419,12 +420,12 @@ private XmlQualifiedName ExportNonXsdPrimitiveMapping(PrimitiveMapping mapping, { AddSchemaImport(mapping.Namespace, ns); } - return new XmlQualifiedName(mapping.TypeDesc.DataType.Name, UrtTypes.Namespace); + return new XmlQualifiedName(mapping.TypeDesc.DataType!.Name, UrtTypes.Namespace); } - private XmlSchemaType ExportSpecialMapping(SpecialMapping mapping, string ns, bool isAny, XmlSchemaElement element) + private XmlSchemaType? ExportSpecialMapping(SpecialMapping mapping, string? ns, bool isAny, XmlSchemaElement? element) { - switch (mapping.TypeDesc.Kind) + switch (mapping.TypeDesc!.Kind) { case TypeKind.Node: { @@ -482,21 +483,21 @@ private XmlSchemaType ExportSpecialMapping(SpecialMapping mapping, string ns, bo } else if (serializableMapping.XsiType != null || serializableMapping.XsdType != null) { - XmlSchemaType type = serializableMapping.XsdType; + XmlSchemaType? type = serializableMapping.XsdType; // for performance reasons we need to postpone merging of the serializable schemas - foreach (XmlSchema schema in serializableMapping.Schemas.Schemas()) + foreach (XmlSchema schema in serializableMapping.Schemas!.Schemas()) { if (schema.TargetNamespace != XmlSchema.Namespace) { _schemas.Add(schema, true); AddSchemaImport(schema.TargetNamespace, ns); - if (!serializableMapping.XsiType.IsEmpty && serializableMapping.XsiType.Namespace == schema.TargetNamespace) - type = (XmlSchemaType)schema.SchemaTypes[serializableMapping.XsiType]; + if (!serializableMapping.XsiType!.IsEmpty && serializableMapping.XsiType.Namespace == schema.TargetNamespace) + type = (XmlSchemaType?)schema.SchemaTypes[serializableMapping.XsiType]; } } if (element != null) { - element.SchemaTypeName = serializableMapping.XsiType; + element.SchemaTypeName = serializableMapping.XsiType!; if (element.SchemaTypeName.IsEmpty) element.SchemaType = type; } @@ -512,9 +513,9 @@ private XmlSchemaType ExportSpecialMapping(SpecialMapping mapping, string ns, bo XmlSchemaSequence seq = new XmlSchemaSequence(); seq.Items.Add(any); type.Particle = seq; - string anyNs = serializableMapping.Schema.TargetNamespace; + string? anyNs = serializableMapping.Schema.TargetNamespace; any.Namespace = anyNs == null ? "" : anyNs; - XmlSchema existingSchema = _schemas[anyNs]; + XmlSchema? existingSchema = _schemas[anyNs]; if (existingSchema == null) { _schemas.Add(serializableMapping.Schema); @@ -551,10 +552,10 @@ private XmlSchemaType ExportSpecialMapping(SpecialMapping mapping, string ns, bo } } - private XmlSchemaType ExportMembersMapping(MembersMapping mapping, string ns) + private XmlSchemaType ExportMembersMapping(MembersMapping mapping, string? ns) { XmlSchemaComplexType type = new XmlSchemaComplexType(); - ExportTypeMembers(type, mapping.Members, mapping.TypeName, ns, false, false); + ExportTypeMembers(type, mapping.Members!, mapping.TypeName!, ns, false, false); if (mapping.XmlnsMember != null) { @@ -576,7 +577,7 @@ private XmlSchemaType ExportAnonymousPrimitiveMapping(PrimitiveMapping mapping) } } - private XmlQualifiedName ExportPrimitiveMapping(PrimitiveMapping mapping, string ns) + private XmlQualifiedName ExportPrimitiveMapping(PrimitiveMapping mapping, string? ns) { XmlQualifiedName qname; if (mapping is EnumMapping) @@ -586,9 +587,9 @@ private XmlQualifiedName ExportPrimitiveMapping(PrimitiveMapping mapping, string } else { - if (mapping.TypeDesc.IsXsdType) + if (mapping.TypeDesc!.IsXsdType) { - qname = new XmlQualifiedName(mapping.TypeDesc.DataType.Name, XmlSchema.Namespace); + qname = new XmlQualifiedName(mapping.TypeDesc.DataType!.Name, XmlSchema.Namespace); } else { @@ -598,7 +599,7 @@ private XmlQualifiedName ExportPrimitiveMapping(PrimitiveMapping mapping, string return qname; } - private void ExportArrayMapping(ArrayMapping mapping, string ns, XmlSchemaElement element) + private void ExportArrayMapping(ArrayMapping mapping, string? ns, XmlSchemaElement? element) { // some of the items in the linked list differ only by CLR type. We don't need to // export different schema types for these. Look further down the list for another @@ -610,7 +611,7 @@ private void ExportArrayMapping(ArrayMapping mapping, string ns, XmlSchemaElemen { currentMapping = currentMapping.Next; } - XmlSchemaComplexType type = (XmlSchemaComplexType)_types[currentMapping]; + XmlSchemaComplexType? type = (XmlSchemaComplexType?)_types[currentMapping]; if (type == null) { CheckForDuplicateType(currentMapping, currentMapping.Namespace); @@ -623,7 +624,7 @@ private void ExportArrayMapping(ArrayMapping mapping, string ns, XmlSchemaElemen if (!currentMapping.IsAnonymousType) _types.Add(currentMapping, type); XmlSchemaSequence seq = new XmlSchemaSequence(); - ExportElementAccessors(seq, mapping.Elements, true, false, mapping.Namespace); + ExportElementAccessors(seq, mapping.Elements!, true, false, mapping.Namespace); if (seq.Items.Count > 0) { #if DEBUG @@ -658,7 +659,7 @@ private void ExportArrayMapping(ArrayMapping mapping, string ns, XmlSchemaElemen } } - private void ExportElementAccessors(XmlSchemaGroupBase group, ElementAccessor[] accessors, bool repeats, bool valueTypeOptional, string ns) + private void ExportElementAccessors(XmlSchemaGroupBase group, ElementAccessor[] accessors, bool repeats, bool valueTypeOptional, string? ns) { if (accessors.Length == 0) return; if (accessors.Length == 1) @@ -677,7 +678,7 @@ private void ExportElementAccessors(XmlSchemaGroupBase group, ElementAccessor[] } } - private void ExportAttributeAccessor(XmlSchemaComplexType type, AttributeAccessor accessor, bool valueTypeOptional, string ns) + private void ExportAttributeAccessor(XmlSchemaComplexType type, AttributeAccessor? accessor, bool valueTypeOptional, string? ns) { if (accessor == null) return; XmlSchemaObjectCollection attributes; @@ -691,7 +692,7 @@ private void ExportAttributeAccessor(XmlSchemaComplexType type, AttributeAccesso else if (type.ContentModel.Content is XmlSchemaSimpleContentExtension) attributes = ((XmlSchemaSimpleContentExtension)type.ContentModel.Content).Attributes; else - throw new InvalidOperationException(SR.Format(SR.XmlInvalidContent, type.ContentModel.Content.GetType().Name)); + throw new InvalidOperationException(SR.Format(SR.XmlInvalidContent, type.ContentModel.Content!.GetType().Name)); } else { @@ -717,7 +718,7 @@ private void ExportAttributeAccessor(XmlSchemaComplexType type, AttributeAccesso } else { - XmlSchemaContent content = type.ContentModel.Content; + XmlSchemaContent? content = type.ContentModel.Content; if (content is XmlSchemaComplexContentExtension) { XmlSchemaComplexContentExtension extension = (XmlSchemaComplexContentExtension)content; @@ -730,7 +731,7 @@ private void ExportAttributeAccessor(XmlSchemaComplexType type, AttributeAccesso } else if (type.ContentModel.Content is XmlSchemaSimpleContentExtension) { - XmlSchemaSimpleContentExtension extension = (XmlSchemaSimpleContentExtension)content; + XmlSchemaSimpleContentExtension extension = (XmlSchemaSimpleContentExtension)content!; extension.AnyAttribute = new XmlSchemaAnyAttribute(); } } @@ -739,7 +740,7 @@ private void ExportAttributeAccessor(XmlSchemaComplexType type, AttributeAccesso { XmlSchemaAttribute attribute = new XmlSchemaAttribute(); attribute.Use = XmlSchemaUse.None; - if (!accessor.HasDefault && !valueTypeOptional && accessor.Mapping.TypeDesc.IsValueType) + if (!accessor.HasDefault && !valueTypeOptional && accessor.Mapping!.TypeDesc!.IsValueType) { attribute.Use = XmlSchemaUse.Required; } @@ -747,7 +748,7 @@ private void ExportAttributeAccessor(XmlSchemaComplexType type, AttributeAccesso if (accessor.Namespace == null || accessor.Namespace == ns) { // determine the form attribute value - XmlSchema schema = _schemas[ns]; + XmlSchema? schema = _schemas[ns]; if (schema == null) attribute.Form = accessor.Form == attributeFormDefault ? XmlSchemaForm.None : accessor.Form; else @@ -813,7 +814,7 @@ private void ExportAttributeAccessor(XmlSchemaComplexType type, AttributeAccesso } } - private void ExportElementAccessor(XmlSchemaGroupBase group, ElementAccessor accessor, bool repeats, bool valueTypeOptional, string ns) + private void ExportElementAccessor(XmlSchemaGroupBase group, ElementAccessor accessor, bool repeats, bool valueTypeOptional, string? ns) { if (accessor.Any && accessor.Name.Length == 0) { @@ -826,8 +827,8 @@ private void ExportElementAccessor(XmlSchemaGroupBase group, ElementAccessor acc } else { - XmlSchemaElement element = (XmlSchemaElement)_elements[accessor]; - int minOccurs = repeats || accessor.HasDefault || (!accessor.IsNullable && !accessor.Mapping.TypeDesc.IsValueType) || valueTypeOptional ? 0 : 1; + XmlSchemaElement? element = (XmlSchemaElement?)_elements[accessor]; + int minOccurs = repeats || accessor.HasDefault || (!accessor.IsNullable && !accessor.Mapping!.TypeDesc!.IsValueType) || valueTypeOptional ? 0 : 1; decimal maxOccurs = repeats || accessor.IsUnbounded ? decimal.MaxValue : 1; if (element == null) @@ -836,7 +837,7 @@ private void ExportElementAccessor(XmlSchemaGroupBase group, ElementAccessor acc element.IsNillable = accessor.IsNullable; element.Name = accessor.Name; if (accessor.HasDefault) - element.DefaultValue = ExportDefaultValue(accessor.Mapping, accessor.Default); + element.DefaultValue = ExportDefaultValue(accessor.Mapping!, accessor.Default); if (accessor.IsTopLevelInSchema) { @@ -849,7 +850,7 @@ private void ExportElementAccessor(XmlSchemaGroupBase group, ElementAccessor acc element.MinOccurs = minOccurs; element.MaxOccurs = maxOccurs; // determine the form attribute value - XmlSchema schema = _schemas[ns]; + XmlSchema? schema = _schemas[ns]; if (schema == null) element.Form = accessor.Form == elementFormDefault ? XmlSchemaForm.None : accessor.Form; else @@ -857,7 +858,7 @@ private void ExportElementAccessor(XmlSchemaGroupBase group, ElementAccessor acc element.Form = accessor.Form == schema.ElementFormDefault ? XmlSchemaForm.None : accessor.Form; } } - ExportElementMapping(element, (TypeMapping)accessor.Mapping, accessor.Namespace, accessor.Any); + ExportElementMapping(element, (TypeMapping)accessor.Mapping!, accessor.Namespace, accessor.Any); } if (accessor.IsTopLevelInSchema) { @@ -875,7 +876,7 @@ private void ExportElementAccessor(XmlSchemaGroupBase group, ElementAccessor acc } } - internal static string ExportDefaultValue(TypeMapping mapping, object value) + internal static string? ExportDefaultValue(TypeMapping mapping, object? value) { if (!(mapping is PrimitiveMapping)) // should throw, but it will be a breaking change; @@ -894,7 +895,7 @@ internal static string ExportDefaultValue(TypeMapping mapping, object value) #endif // check the validity of the value - ConstantMapping[] c = em.Constants; + ConstantMapping[] c = em.Constants!; if (em.IsFlags) { string[] names = new string[c.Length]; @@ -907,7 +908,7 @@ internal static string ExportDefaultValue(TypeMapping mapping, object value) values.Add(c[i].Name, ids[i]); } long val = XmlCustomFormatter.ToEnum((string)value, values, em.TypeName, false); - return val != 0 ? XmlCustomFormatter.FromEnum(val, names, ids, mapping.TypeDesc.FullName) : null; + return val != 0 ? XmlCustomFormatter.FromEnum(val, names, ids, mapping.TypeDesc!.FullName) : null; } else { @@ -924,7 +925,7 @@ internal static string ExportDefaultValue(TypeMapping mapping, object value) PrimitiveMapping pm = (PrimitiveMapping)mapping; - if (!pm.TypeDesc.HasCustomFormatter) + if (!pm.TypeDesc!.HasCustomFormatter) { #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe @@ -938,13 +939,13 @@ internal static string ExportDefaultValue(TypeMapping mapping, object value) return (string)value; Type formatter = typeof(XmlConvert); - System.Reflection.MethodInfo format = formatter.GetMethod("ToString", new Type[] { pm.TypeDesc.Type }); + System.Reflection.MethodInfo? format = formatter.GetMethod("ToString", new Type[] { pm.TypeDesc.Type }); if (format != null) - return (string)format.Invoke(formatter, new object[] { value }); + return (string)format.Invoke(formatter, new object[] { value })!; } else { - string defaultValue = XmlCustomFormatter.FromDefaultValue(value, pm.TypeDesc.FormatterName); + string defaultValue = XmlCustomFormatter.FromDefaultValue(value, pm.TypeDesc.FormatterName!); if (defaultValue == null) throw new InvalidOperationException(SR.Format(SR.XmlInvalidDefaultValue, value, pm.TypeDesc.Name)); return defaultValue; @@ -958,7 +959,7 @@ private void ExportRootIfNecessary(TypeScope typeScope) return; foreach (TypeMapping mapping in typeScope.TypeMappings) { - if (mapping is StructMapping && mapping.TypeDesc.IsRoot) + if (mapping is StructMapping && mapping.TypeDesc!.IsRoot) { ExportDerivedMappings((StructMapping)mapping); } @@ -973,9 +974,9 @@ private void ExportRootIfNecessary(TypeScope typeScope) } } - private XmlQualifiedName ExportStructMapping(StructMapping mapping, string ns, XmlSchemaElement element) + private XmlQualifiedName ExportStructMapping(StructMapping mapping, string? ns, XmlSchemaElement? element) { - if (mapping.TypeDesc.IsRoot) + if (mapping.TypeDesc!.IsRoot) { _needToExportRoot = true; return XmlQualifiedName.Empty; @@ -986,7 +987,7 @@ private XmlQualifiedName ExportStructMapping(StructMapping mapping, string ns, X throw new InvalidOperationException(SR.Format(SR.XmlCircularReference2, mapping.TypeDesc.Name, "AnonymousType", "false")); _references[mapping] = mapping; } - XmlSchemaComplexType type = (XmlSchemaComplexType)_types[mapping]; + XmlSchemaComplexType? type = (XmlSchemaComplexType?)_types[mapping]; if (type == null) { if (!mapping.IncludeInSchema) throw new InvalidOperationException(SR.Format(SR.XmlCannotIncludeInSchema, mapping.TypeDesc.Name)); @@ -1004,7 +1005,7 @@ private XmlQualifiedName ExportStructMapping(StructMapping mapping, string ns, X { if (mapping.BaseMapping.IsAnonymousType) { - throw new InvalidOperationException(SR.Format(SR.XmlAnonymousBaseType, mapping.TypeDesc.Name, mapping.BaseMapping.TypeDesc.Name, "AnonymousType", "false")); + throw new InvalidOperationException(SR.Format(SR.XmlAnonymousBaseType, mapping.TypeDesc.Name, mapping.BaseMapping.TypeDesc!.Name, "AnonymousType", "false")); } if (mapping.HasSimpleContent) { @@ -1020,12 +1021,12 @@ private XmlQualifiedName ExportStructMapping(StructMapping mapping, string ns, X extension.BaseTypeName = ExportStructMapping(mapping.BaseMapping, mapping.Namespace, null); XmlSchemaComplexContent model = new XmlSchemaComplexContent(); model.Content = extension; - model.IsMixed = XmlSchemaImporter.IsMixed((XmlSchemaComplexType)_types[mapping.BaseMapping]); + model.IsMixed = XmlSchemaImporter.IsMixed((XmlSchemaComplexType)_types[mapping.BaseMapping]!); type.ContentModel = model; } openModel = false; } - ExportTypeMembers(type, mapping.Members, mapping.TypeName, mapping.Namespace, mapping.HasSimpleContent, openModel); + ExportTypeMembers(type, mapping.Members!, mapping.TypeName!, mapping.Namespace, mapping.HasSimpleContent, openModel); ExportDerivedMappings(mapping); if (mapping.XmlnsMember != null) { @@ -1051,10 +1052,10 @@ private XmlQualifiedName ExportStructMapping(StructMapping mapping, string ns, X } } - private void ExportTypeMembers(XmlSchemaComplexType type, MemberMapping[] members, string name, string ns, bool hasSimpleContent, bool openModel) + private void ExportTypeMembers(XmlSchemaComplexType type, MemberMapping[] members, string name, string? ns, bool hasSimpleContent, bool openModel) { XmlSchemaGroupBase seq = new XmlSchemaSequence(); - TypeMapping textMapping = null; + TypeMapping? textMapping = null; for (int i = 0; i < members.Length; i++) { @@ -1069,9 +1070,9 @@ private void ExportTypeMembers(XmlSchemaComplexType type, MemberMapping[] member } textMapping = member.Text.Mapping; } - if (member.Elements.Length > 0) + if (member.Elements!.Length > 0) { - bool repeats = member.TypeDesc.IsArrayLike && + bool repeats = member.TypeDesc!.IsArrayLike && !(member.Elements.Length == 1 && member.Elements[0].Mapping is ArrayMapping); bool valueTypeOptional = member.CheckSpecified != SpecifiedAccessor.None || member.CheckShouldPersist; @@ -1088,7 +1089,7 @@ private void ExportTypeMembers(XmlSchemaComplexType type, MemberMapping[] member else if (type.ContentModel.Content is XmlSchemaComplexContentExtension) ((XmlSchemaComplexContentExtension)type.ContentModel.Content).Particle = seq; else - throw new InvalidOperationException(SR.Format(SR.XmlInvalidContent, type.ContentModel.Content.GetType().Name)); + throw new InvalidOperationException(SR.Format(SR.XmlInvalidContent, type.ContentModel.Content!.GetType().Name)); } else { @@ -1110,7 +1111,7 @@ private void ExportTypeMembers(XmlSchemaComplexType type, MemberMapping[] member { if (pm.IsAnonymousType) { - throw new InvalidOperationException(SR.Format(SR.XmlAnonymousBaseType, textMapping.TypeDesc.Name, pm.TypeDesc.Name, "AnonymousType", "false")); + throw new InvalidOperationException(SR.Format(SR.XmlAnonymousBaseType, textMapping.TypeDesc!.Name, pm.TypeDesc!.Name, "AnonymousType", "false")); } // Create simpleContent XmlSchemaSimpleContent model = new XmlSchemaSimpleContent(); @@ -1129,11 +1130,11 @@ private void ExportTypeMembers(XmlSchemaComplexType type, MemberMapping[] member bool anyAttribute = false; for (int i = 0; i < members.Length; i++) { - AttributeAccessor accessor = members[i].Attribute; + AttributeAccessor? accessor = members[i].Attribute; if (accessor != null) { ExportAttributeAccessor(type, members[i].Attribute, members[i].CheckSpecified != SpecifiedAccessor.None || members[i].CheckShouldPersist, ns); - if (members[i].Attribute.Any) + if (members[i].Attribute!.Any) anyAttribute = true; } } @@ -1149,16 +1150,16 @@ private void ExportDerivedMappings(StructMapping mapping) { if (mapping.IsAnonymousType) return; - for (StructMapping derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) + for (StructMapping? derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) { if (derived.IncludeInSchema) ExportStructMapping(derived, derived.Namespace, null); } } - private XmlSchemaType ExportEnumMapping(EnumMapping mapping, string ns) + private XmlSchemaType ExportEnumMapping(EnumMapping mapping, string? ns) { - if (!mapping.IncludeInSchema) throw new InvalidOperationException(SR.Format(SR.XmlCannotIncludeInSchema, mapping.TypeDesc.Name)); - XmlSchemaSimpleType dataType = (XmlSchemaSimpleType)_types[mapping]; + if (!mapping.IncludeInSchema) throw new InvalidOperationException(SR.Format(SR.XmlCannotIncludeInSchema, mapping.TypeDesc!.Name)); + XmlSchemaSimpleType? dataType = (XmlSchemaSimpleType?)_types[mapping]; if (dataType == null) { CheckForDuplicateType(mapping, mapping.Namespace); @@ -1172,7 +1173,7 @@ private XmlSchemaType ExportEnumMapping(EnumMapping mapping, string ns) XmlSchemaSimpleTypeRestriction restriction = new XmlSchemaSimpleTypeRestriction(); restriction.BaseTypeName = new XmlQualifiedName("string", XmlSchema.Namespace); - for (int i = 0; i < mapping.Constants.Length; i++) + for (int i = 0; i < mapping.Constants!.Length; i++) { ConstantMapping constant = mapping.Constants[i]; XmlSchemaEnumerationFacet enumeration = new XmlSchemaEnumerationFacet(); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaImporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaImporter.cs index a9cb30c25eb8e3..4eb6bc8ac1ea18 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaImporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaImporter.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; @@ -23,7 +24,7 @@ public class XmlSchemaImporter : SchemaImporter public XmlSchemaImporter(XmlSchemas schemas, CodeIdentifiers typeIdentifiers) : base(schemas, CodeGenerationOptions.GenerateProperties, new ImportContext(typeIdentifiers, false)) { } - public XmlTypeMapping ImportDerivedTypeMapping(XmlQualifiedName name, Type baseType) + public XmlTypeMapping ImportDerivedTypeMapping(XmlQualifiedName name, Type? baseType) { return ImportDerivedTypeMapping(name, baseType, false); } @@ -37,12 +38,12 @@ internal TypeMapping GetDefaultMapping(TypeFlags flags) { PrimitiveMapping mapping = new PrimitiveMapping(); mapping.TypeDesc = Scope.GetTypeDesc("string", XmlSchema.Namespace, flags); - mapping.TypeName = mapping.TypeDesc.DataType.Name; + mapping.TypeName = mapping.TypeDesc!.DataType!.Name; mapping.Namespace = XmlSchema.Namespace; return mapping; } - public XmlTypeMapping ImportDerivedTypeMapping(XmlQualifiedName name, Type baseType, bool baseTypeCanBeIndirect) + public XmlTypeMapping ImportDerivedTypeMapping(XmlQualifiedName name, Type? baseType, bool baseTypeCanBeIndirect) { ElementAccessor element = ImportElement(name, typeof(TypeMapping), baseType); @@ -56,7 +57,7 @@ public XmlTypeMapping ImportDerivedTypeMapping(XmlQualifiedName name, Type baseT { // in the case of the ArrayMapping we can use the top-level StructMapping, because it does not have base base type element.Mapping = ((ArrayMapping)element.Mapping).TopLevelMapping; - MakeDerived((StructMapping)element.Mapping, baseType, baseTypeCanBeIndirect); + MakeDerived((StructMapping)element.Mapping!, baseType, baseTypeCanBeIndirect); } else { @@ -77,9 +78,9 @@ public XmlTypeMapping ImportSchemaType(XmlQualifiedName typeName, Type baseType) return ImportSchemaType(typeName, baseType, false); } - public XmlTypeMapping ImportSchemaType(XmlQualifiedName typeName, Type baseType, bool baseTypeCanBeIndirect) + public XmlTypeMapping ImportSchemaType(XmlQualifiedName typeName, Type? baseType, bool baseTypeCanBeIndirect) { - TypeMapping typeMapping = ImportType(typeName, typeof(TypeMapping), baseType, TypeFlags.CanBeElementValue, true); + TypeMapping typeMapping = ImportType(typeName, typeof(TypeMapping), baseType, TypeFlags.CanBeElementValue, true)!; typeMapping.ReferencedByElement = false; ElementAccessor accessor = new ElementAccessor(); @@ -90,7 +91,7 @@ public XmlTypeMapping ImportSchemaType(XmlQualifiedName typeName, Type baseType, if (typeMapping is SpecialMapping && ((SpecialMapping)typeMapping).NamedAny) accessor.Any = true; - accessor.IsNullable = typeMapping.TypeDesc.IsNullable; + accessor.IsNullable = typeMapping.TypeDesc!.IsNullable; accessor.Form = XmlSchemaForm.Qualified; if (accessor.Mapping is StructMapping) @@ -103,7 +104,7 @@ public XmlTypeMapping ImportSchemaType(XmlQualifiedName typeName, Type baseType, { // in the case of the ArrayMapping we can use the top-level StructMapping, because it does not have base base type accessor.Mapping = ((ArrayMapping)accessor.Mapping).TopLevelMapping; - MakeDerived((StructMapping)accessor.Mapping, baseType, baseTypeCanBeIndirect); + MakeDerived((StructMapping)accessor.Mapping!, baseType, baseTypeCanBeIndirect); } else { @@ -124,10 +125,10 @@ public XmlMembersMapping ImportMembersMapping(XmlQualifiedName name) return new XmlMembersMapping(Scope, ImportElement(name, typeof(MembersMapping), null), XmlMappingAccess.Read | XmlMappingAccess.Write); } - public XmlMembersMapping ImportAnyType(XmlQualifiedName typeName, string elementName) + public XmlMembersMapping? ImportAnyType(XmlQualifiedName typeName, string elementName) { - TypeMapping typeMapping = ImportType(typeName, typeof(MembersMapping), null, TypeFlags.CanBeElementValue, true); - MembersMapping mapping = typeMapping as MembersMapping; + TypeMapping? typeMapping = ImportType(typeName, typeof(MembersMapping), null, TypeFlags.CanBeElementValue, true); + MembersMapping? mapping = typeMapping as MembersMapping; if (mapping == null) { @@ -141,7 +142,7 @@ public XmlMembersMapping ImportAnyType(XmlQualifiedName typeName, string element mapping = ImportMembersType(type, typeName.Namespace, elementName); } - if (mapping.Members.Length != 1 || !mapping.Members[0].Accessor.Any) + if (mapping.Members!.Length != 1 || !mapping.Members[0].Accessor!.Any) return null; mapping.Members[0].Name = elementName; ElementAccessor accessor = new ElementAccessor(); @@ -150,10 +151,10 @@ public XmlMembersMapping ImportAnyType(XmlQualifiedName typeName, string element accessor.Mapping = mapping; accessor.Any = true; - XmlSchemaObject xso = Schemas.SchemaSet.GlobalTypes[typeName]; + XmlSchemaObject? xso = Schemas.SchemaSet.GlobalTypes[typeName]; if (xso != null) { - XmlSchema schema = xso.Parent as XmlSchema; + XmlSchema? schema = xso.Parent as XmlSchema; if (schema != null) { accessor.Form = schema.ElementFormDefault == XmlSchemaForm.None ? XmlSchemaForm.Unqualified : schema.ElementFormDefault; @@ -168,7 +169,7 @@ public XmlMembersMapping ImportMembersMapping(XmlQualifiedName[] names) return ImportMembersMapping(names, null, false); } - public XmlMembersMapping ImportMembersMapping(XmlQualifiedName[] names, Type baseType, bool baseTypeCanBeIndirect) + public XmlMembersMapping ImportMembersMapping(XmlQualifiedName[] names, Type? baseType, bool baseTypeCanBeIndirect) { CodeIdentifiers memberScope = new CodeIdentifiers(); memberScope.UseCamelCasing = true; @@ -183,7 +184,7 @@ public XmlMembersMapping ImportMembersMapping(XmlQualifiedName[] names, Type bas MemberMapping member = new MemberMapping(); member.Name = CodeIdentifier.MakeValid(Accessor.UnescapeName(accessor.Name)); member.Name = memberScope.AddUnique(member.Name, member); - member.TypeDesc = accessor.Mapping.TypeDesc; + member.TypeDesc = accessor.Mapping!.TypeDesc; member.Elements = new ElementAccessor[] { accessor }; members[i] = member; } @@ -219,13 +220,13 @@ public XmlMembersMapping ImportMembersMapping(string name, string ns, SoapSchema return new XmlMembersMapping(Scope, accessor, XmlMappingAccess.Read | XmlMappingAccess.Write); } - private ElementAccessor ImportElement(XmlQualifiedName name, Type desiredMappingType, Type baseType) + private ElementAccessor ImportElement(XmlQualifiedName name, Type desiredMappingType, Type? baseType) { XmlSchemaElement element = FindElement(name); - ElementAccessor accessor = (ElementAccessor)ImportedElements[element]; + ElementAccessor? accessor = (ElementAccessor?)ImportedElements[element]; if (accessor != null) return accessor; accessor = ImportElement(element, string.Empty, desiredMappingType, baseType, name.Namespace, true); - ElementAccessor existing = (ElementAccessor)ImportedElements[element]; + ElementAccessor? existing = (ElementAccessor?)ImportedElements[element]; if (existing != null) { return existing; @@ -234,7 +235,7 @@ private ElementAccessor ImportElement(XmlQualifiedName name, Type desiredMapping return accessor; } - private ElementAccessor ImportElement(XmlSchemaElement element, string identifier, Type desiredMappingType, Type baseType, string ns, bool topLevelElement) + private ElementAccessor ImportElement(XmlSchemaElement element, string identifier, Type desiredMappingType, Type? baseType, string? ns, bool topLevelElement) { if (!element.RefName.IsEmpty) { @@ -244,13 +245,13 @@ private ElementAccessor ImportElement(XmlSchemaElement element, string identifie { ElementAccessor refAccessor = topAccessor.Clone(); refAccessor.IsTopLevelInSchema = false; - refAccessor.Mapping.ReferencedByElement = true; + refAccessor.Mapping!.ReferencedByElement = true; return refAccessor; } return topAccessor; } - if (element.Name.Length == 0) + if (element.Name!.Length == 0) { XmlQualifiedName parentType = XmlSchemas.GetParentName(element); throw new InvalidOperationException(SR.Format(SR.XmlElementHasNoName, parentType.Name, parentType.Namespace)); @@ -292,15 +293,15 @@ private ElementAccessor ImportElement(XmlSchemaElement element, string identifie return accessor; } - private TypeMapping ImportElementType(XmlSchemaElement element, string identifier, Type desiredMappingType, Type baseType, string ns) + private TypeMapping ImportElementType(XmlSchemaElement element, string identifier, Type desiredMappingType, Type? baseType, string? ns) { - TypeMapping mapping; + TypeMapping? mapping; if (!element.SchemaTypeName.IsEmpty) { - mapping = ImportType(element.SchemaTypeName, desiredMappingType, baseType, TypeFlags.CanBeElementValue, false); + mapping = ImportType(element.SchemaTypeName, desiredMappingType, baseType, TypeFlags.CanBeElementValue, false)!; if (!mapping.ReferencedByElement) { - object type = FindType(element.SchemaTypeName, TypeFlags.CanBeElementValue); + object? type = FindType(element.SchemaTypeName, TypeFlags.CanBeElementValue); XmlSchemaObject parent = element; while (parent.Parent != null && type != parent) { @@ -314,8 +315,8 @@ private TypeMapping ImportElementType(XmlSchemaElement element, string identifie if (element.SchemaType is XmlSchemaComplexType) mapping = ImportType((XmlSchemaComplexType)element.SchemaType, ns, identifier, desiredMappingType, baseType, TypeFlags.CanBeElementValue); else - mapping = ImportDataType((XmlSchemaSimpleType)element.SchemaType, ns, identifier, baseType, TypeFlags.CanBeElementValue | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeTextValue, false); - mapping.ReferencedByElement = true; + mapping = ImportDataType((XmlSchemaSimpleType)element.SchemaType, ns, identifier, baseType, TypeFlags.CanBeElementValue | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeTextValue, false)!; + mapping!.ReferencedByElement = true; } else if (!element.SubstitutionGroup.IsEmpty) mapping = ImportElementType(FindElement(element.SubstitutionGroup), identifier, desiredMappingType, baseType, ns); @@ -334,18 +335,18 @@ private TypeMapping ImportElementType(XmlSchemaElement element, string identifie throw new InvalidOperationException(SR.Format(SR.XmlElementImportedTwice, element.Name, ns, mapping.GetType().Name, desiredMappingType.Name)); // let the extensions to run - if (!mapping.TypeDesc.IsMappedType) + if (!mapping.TypeDesc!.IsMappedType) { RunSchemaExtensions(mapping, element.SchemaTypeName, element.SchemaType, element, TypeFlags.CanBeElementValue); } return mapping; } - private void RunSchemaExtensions(TypeMapping mapping, XmlQualifiedName qname, XmlSchemaType type, XmlSchemaObject context, TypeFlags flags) + private void RunSchemaExtensions(TypeMapping mapping, XmlQualifiedName qname, XmlSchemaType? type, XmlSchemaObject context, TypeFlags flags) { // nop } - private string GenerateUniqueTypeName(string desiredName, string ns) + private string GenerateUniqueTypeName(string desiredName, string? ns) { int i = 1; @@ -354,7 +355,7 @@ private string GenerateUniqueTypeName(string desiredName, string ns) { XmlQualifiedName qname = new XmlQualifiedName(typeName, ns); - object type = Schemas.Find(qname, typeof(XmlSchemaType)); + object? type = Schemas.Find(qname, typeof(XmlSchemaType)); if (type == null) { break; @@ -387,13 +388,13 @@ internal override void ImportDerivedTypes(XmlQualifiedName baseName) } } - private TypeMapping ImportType(XmlQualifiedName name, Type desiredMappingType, Type baseType, TypeFlags flags, bool addref) + private TypeMapping? ImportType(XmlQualifiedName name, Type desiredMappingType, Type? baseType, TypeFlags flags, bool addref) { if (name.Name == Soap.UrType && name.Namespace == XmlSchema.Namespace) return ImportRootMapping(); - object type = FindType(name, flags); + object type = FindType(name, flags)!; - TypeMapping mapping = (TypeMapping)ImportedMappings[type]; + TypeMapping? mapping = (TypeMapping?)ImportedMappings[type]; if (mapping != null && desiredMappingType.IsAssignableFrom(mapping.GetType())) return mapping; @@ -414,7 +415,7 @@ private TypeMapping ImportType(XmlQualifiedName name, Type desiredMappingType, T return mapping; } - private TypeMapping ImportType(XmlSchemaComplexType type, string typeNs, string identifier, Type desiredMappingType, Type baseType, TypeFlags flags) + private TypeMapping? ImportType(XmlSchemaComplexType type, string? typeNs, string identifier, Type desiredMappingType, Type? baseType, TypeFlags flags) { if (type.Redefined != null) { @@ -423,7 +424,7 @@ private TypeMapping ImportType(XmlSchemaComplexType type, string typeNs, string } if (desiredMappingType == typeof(TypeMapping)) { - TypeMapping mapping = null; + TypeMapping? mapping = null; if (baseType == null) { @@ -447,7 +448,7 @@ private TypeMapping ImportType(XmlSchemaComplexType type, string typeNs, string throw new ArgumentException(SR.XmlInternalError, nameof(desiredMappingType)); } - private MembersMapping ImportMembersType(XmlSchemaType type, string typeNs, string identifier) + private MembersMapping ImportMembersType(XmlSchemaType type, string? typeNs, string identifier) { if (!type.DerivedFrom.IsEmpty) throw new InvalidOperationException(SR.XmlMembersDeriveError); CodeIdentifiers memberScope = new CodeIdentifiers(); @@ -461,10 +462,10 @@ private MembersMapping ImportMembersType(XmlSchemaType type, string typeNs, stri return mappings; } - private StructMapping ImportStructType(XmlSchemaType type, string typeNs, string identifier, Type baseType, bool arrayLike) + private StructMapping ImportStructType(XmlSchemaType type, string? typeNs, string identifier, Type? baseType, bool arrayLike) { - TypeDesc baseTypeDesc = null; - TypeMapping baseMapping = null; + TypeDesc? baseTypeDesc = null; + TypeMapping? baseMapping = null; bool isRootType = false; if (!type.DerivedFrom.IsEmpty) @@ -493,7 +494,7 @@ private StructMapping ImportStructType(XmlSchemaType type, string typeNs, string baseMapping = GetRootMapping(); isRootType = true; } - Mapping previousMapping = (Mapping)ImportedMappings[type]; + Mapping? previousMapping = (Mapping?)ImportedMappings[type]; if (previousMapping != null) { if (previousMapping is StructMapping) @@ -554,10 +555,10 @@ private StructMapping ImportStructType(XmlSchemaType type, string typeNs, string for (int i = 0; i < structMapping.Members.Length; i++) { - StructMapping declaringMapping; - MemberMapping baseMember = ((StructMapping)baseMapping).FindDeclaringMapping(structMapping.Members[i], out declaringMapping, structMapping.TypeName); + StructMapping? declaringMapping; + MemberMapping? baseMember = ((StructMapping)baseMapping).FindDeclaringMapping(structMapping.Members[i], out declaringMapping, structMapping.TypeName); if (baseMember != null && baseMember.TypeDesc != structMapping.Members[i].TypeDesc) - throw new InvalidOperationException(SR.Format(SR.XmlIllegalOverride, type.Name, baseMember.Name, baseMember.TypeDesc.FullName, structMapping.Members[i].TypeDesc.FullName, declaringMapping.TypeDesc.FullName)); + throw new InvalidOperationException(SR.Format(SR.XmlIllegalOverride, type.Name, baseMember.Name, baseMember.TypeDesc!.FullName, structMapping.Members[i].TypeDesc!.FullName, declaringMapping!.TypeDesc!.FullName)); } structMapping.Scope = membersScope; Scope.AddTypeMapping(structMapping); @@ -570,7 +571,7 @@ private bool IsAllGroup(XmlSchemaType type) return (items.Particle != null) && (items.Particle is XmlSchemaAll); } - private StructMapping ImportStructDataType(XmlSchemaSimpleType dataType, string typeNs, string identifier, Type baseType) + private StructMapping ImportStructDataType(XmlSchemaSimpleType dataType, string? typeNs, string identifier, Type baseType) { identifier = Accessor.UnescapeName(identifier); string typeName = GenerateUniqueTypeName(identifier); @@ -594,13 +595,13 @@ private StructMapping ImportStructDataType(XmlSchemaSimpleType dataType, string private class TypeItems { internal XmlSchemaObjectCollection Attributes = new XmlSchemaObjectCollection(); - internal XmlSchemaAnyAttribute AnyAttribute; - internal XmlSchemaGroupBase Particle; - internal XmlQualifiedName baseSimpleType; + internal XmlSchemaAnyAttribute? AnyAttribute; + internal XmlSchemaGroupBase? Particle; + internal XmlQualifiedName? baseSimpleType; internal bool IsUnbounded; } - private MemberMapping[] ImportTypeMembers(XmlSchemaType type, string typeNs, string identifier, CodeIdentifiers members, CodeIdentifiers membersScope, INameScope elementsScope, ref bool needExplicitOrder, bool order, bool allowUnboundedElements) + private MemberMapping[] ImportTypeMembers(XmlSchemaType type, string? typeNs, string identifier, CodeIdentifiers members, CodeIdentifiers membersScope, INameScope elementsScope, ref bool needExplicitOrder, bool order, bool allowUnboundedElements) { TypeItems items = GetTypeItems(type); bool mixed = IsMixed(type); @@ -611,7 +612,7 @@ private MemberMapping[] ImportTypeMembers(XmlSchemaType type, string typeNs, str XmlSchemaType t = type; while (!t.DerivedFrom.IsEmpty) { - t = FindType(t.DerivedFrom, TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue); + t = FindType(t.DerivedFrom, TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue)!; if (IsMixed(t)) { // keep the mixed attribute on the base class @@ -677,11 +678,11 @@ private TypeItems GetTypeItems(XmlSchemaType type) TypeItems items = new TypeItems(); if (type is XmlSchemaComplexType) { - XmlSchemaParticle particle = null; + XmlSchemaParticle? particle = null; XmlSchemaComplexType ct = (XmlSchemaComplexType)type; if (ct.ContentModel != null) { - XmlSchemaContent content = ct.ContentModel.Content; + XmlSchemaContent? content = ct.ContentModel.Content; if (content is XmlSchemaComplexContentExtension) { XmlSchemaComplexContentExtension extension = (XmlSchemaComplexContentExtension)content; @@ -718,7 +719,7 @@ private TypeItems GetTypeItems(XmlSchemaType type) return items; } - private void ImportGroup(XmlSchemaGroupBase group, string identifier, CodeIdentifiers members, CodeIdentifiers membersScope, INameScope elementsScope, string ns, bool mixed, ref bool needExplicitOrder, bool allowDuplicates, bool groupRepeats, bool allowUnboundedElements) + private void ImportGroup(XmlSchemaGroupBase group, string identifier, CodeIdentifiers members, CodeIdentifiers membersScope, INameScope elementsScope, string? ns, bool mixed, ref bool needExplicitOrder, bool allowDuplicates, bool groupRepeats, bool allowUnboundedElements) { if (group is XmlSchemaChoice) ImportChoiceGroup((XmlSchemaChoice)group, identifier, members, membersScope, elementsScope, ns, groupRepeats, ref needExplicitOrder, allowDuplicates); @@ -731,7 +732,7 @@ private void ImportGroup(XmlSchemaGroupBase group, string identifier, CodeIdenti } } - private MemberMapping ImportChoiceGroup(XmlSchemaGroupBase group, string identifier, CodeIdentifiers members, CodeIdentifiers membersScope, INameScope elementsScope, string ns, bool groupRepeats, ref bool needExplicitOrder, bool allowDuplicates) + private MemberMapping ImportChoiceGroup(XmlSchemaGroupBase group, string identifier, CodeIdentifiers? members, CodeIdentifiers? membersScope, INameScope? elementsScope, string? ns, bool groupRepeats, ref bool needExplicitOrder, bool allowDuplicates) { NameTable choiceElements = new NameTable(); if (GatherGroupChoices(group, choiceElements, identifier, ns, ref needExplicitOrder, allowDuplicates)) @@ -748,8 +749,8 @@ private MemberMapping ImportChoiceGroup(XmlSchemaGroupBase group, string identif for (int i = 0; i < member.Elements.Length; i++) { ElementAccessor element = member.Elements[i]; - string tdFullName = element.Mapping.TypeDesc.FullName; - object val = uniqueTypeDescs[tdFullName]; + string tdFullName = element.Mapping!.TypeDesc!.FullName; + object? val = uniqueTypeDescs[tdFullName]; if (val != null) { duplicateTypes = true; @@ -762,14 +763,14 @@ private MemberMapping ImportChoiceGroup(XmlSchemaGroupBase group, string identif uniqueTypeDescs.Add(tdFullName, element); } - ArrayMapping arrayMapping = element.Mapping as ArrayMapping; + ArrayMapping? arrayMapping = element.Mapping as ArrayMapping; if (arrayMapping != null) { if (IsNeedXmlSerializationAttributes(arrayMapping)) { // we cannot use ArrayMapping in choice if additional custom // serialization attributes are needed to serialize it - element.Mapping = arrayMapping.TopLevelMapping; + element.Mapping = arrayMapping.TopLevelMapping!; element.Mapping.ReferencedByTopLevelElement = false; element.Mapping.ReferencedByElement = true; } @@ -785,7 +786,7 @@ private MemberMapping ImportChoiceGroup(XmlSchemaGroupBase group, string identif { if (!enumerator.MoveNext()) break; - typeDescs[i] = ((ElementAccessor)enumerator.Current).Mapping.TypeDesc; + typeDescs[i] = ((ElementAccessor)enumerator.Current).Mapping!.TypeDesc!; } member.TypeDesc = TypeDesc.FindCommonBaseTypeDesc(typeDescs); if (member.TypeDesc == null) member.TypeDesc = Scope.GetTypeDesc(typeof(object)); @@ -810,7 +811,7 @@ private MemberMapping ImportChoiceGroup(XmlSchemaGroupBase group, string identif // we need to create the EnumMapping to store all of the element names member.ChoiceIdentifier.Mapping = ImportEnumeratedChoice(member.Elements, ns, member.Name + "ChoiceType"); member.ChoiceIdentifier.MemberIds = new string[member.Elements.Length]; - ConstantMapping[] constants = ((EnumMapping)member.ChoiceIdentifier.Mapping).Constants; + ConstantMapping[] constants = ((EnumMapping)member.ChoiceIdentifier.Mapping).Constants!; for (int i = 0; i < member.Elements.Length; i++) { member.ChoiceIdentifier.MemberIds[i] = constants[i].Name; @@ -820,7 +821,7 @@ private MemberMapping ImportChoiceGroup(XmlSchemaGroupBase group, string identif choiceIdentifier.Name = member.ChoiceIdentifier.MemberName; if (groupRepeats) { - choiceIdentifier.TypeDesc = member.ChoiceIdentifier.Mapping.TypeDesc.CreateArrayTypeDesc(); + choiceIdentifier.TypeDesc = member.ChoiceIdentifier.Mapping.TypeDesc!.CreateArrayTypeDesc(); } else { @@ -849,11 +850,11 @@ private MemberMapping ImportChoiceGroup(XmlSchemaGroupBase group, string identif private bool IsNeedXmlSerializationAttributes(ArrayMapping arrayMapping) { - if (arrayMapping.Elements.Length != 1) + if (arrayMapping.Elements!.Length != 1) return true; ElementAccessor item = arrayMapping.Elements[0]; - TypeMapping itemMapping = item.Mapping; + TypeMapping itemMapping = item.Mapping!; if (item.Name != itemMapping.DefaultElementName) return true; @@ -861,7 +862,7 @@ private bool IsNeedXmlSerializationAttributes(ArrayMapping arrayMapping) if (item.Form != XmlSchemaForm.None && item.Form != XmlSchemaExporter.elementFormDefault) return true; - if (item.Mapping.TypeDesc != null) + if (item.Mapping!.TypeDesc != null) { if (item.IsNullable != item.Mapping.TypeDesc.IsNullable) return true; @@ -872,12 +873,12 @@ private bool IsNeedXmlSerializationAttributes(ArrayMapping arrayMapping) return false; } - private bool GatherGroupChoices(XmlSchemaGroup group, NameTable choiceElements, string identifier, string ns, ref bool needExplicitOrder, bool allowDuplicates) + private bool GatherGroupChoices(XmlSchemaGroup group, NameTable choiceElements, string identifier, string? ns, ref bool needExplicitOrder, bool allowDuplicates) { return GatherGroupChoices(group.Particle, choiceElements, identifier, ns, ref needExplicitOrder, allowDuplicates); } - private bool GatherGroupChoices(XmlSchemaParticle particle, NameTable choiceElements, string identifier, string ns, ref bool needExplicitOrder, bool allowDuplicates) + private bool GatherGroupChoices(XmlSchemaParticle? particle, NameTable choiceElements, string identifier, string? ns, ref bool needExplicitOrder, bool allowDuplicates) { if (particle is XmlSchemaGroupRef) { @@ -897,7 +898,7 @@ private bool GatherGroupChoices(XmlSchemaParticle particle, NameTable choiceElem { XmlSchemaGroupBase group = (XmlSchemaGroupBase)particle; bool groupRepeats = group.IsMultipleOccurrence; - XmlSchemaAny any = null; + XmlSchemaAny? any = null; bool duplicateElements = false; for (int i = 0; i < group.Items.Count; i++) { @@ -921,7 +922,7 @@ private bool GatherGroupChoices(XmlSchemaParticle particle, NameTable choiceElem else if (item is XmlSchemaElement) { XmlSchemaElement element = (XmlSchemaElement)item; - XmlSchemaElement headElement = GetTopLevelElement(element); + XmlSchemaElement? headElement = GetTopLevelElement(element); if (headElement != null) { XmlSchemaElement[] elements = GetEquivalentElements(headElement); @@ -948,19 +949,19 @@ private bool GatherGroupChoices(XmlSchemaParticle particle, NameTable choiceElem return false; } - private void AddScopeElement(INameScope scope, ElementAccessor element, ref bool duplicateElements, bool allowDuplicates) + private void AddScopeElement(INameScope? scope, ElementAccessor element, ref bool duplicateElements, bool allowDuplicates) { if (scope == null) return; - ElementAccessor scopeElement = (ElementAccessor)scope[element.Name, element.Namespace]; + ElementAccessor? scopeElement = (ElementAccessor?)scope[element.Name, element.Namespace]; if (scopeElement != null) { if (!allowDuplicates) { throw new InvalidOperationException(SR.Format(SR.XmlDuplicateElementInScope, element.Name, element.Namespace)); } - if (scopeElement.Mapping.TypeDesc != element.Mapping.TypeDesc) + if (scopeElement.Mapping!.TypeDesc != element.Mapping!.TypeDesc) { throw new InvalidOperationException(SR.Format(SR.XmlDuplicateElementInScope1, element.Name, element.Namespace)); } @@ -972,7 +973,7 @@ private void AddScopeElement(INameScope scope, ElementAccessor element, ref bool } } - private void AddScopeElements(INameScope scope, ElementAccessor[] elements, ref bool duplicateElements, bool allowDuplicates) + private void AddScopeElements(INameScope? scope, ElementAccessor[] elements, ref bool duplicateElements, bool allowDuplicates) { for (int i = 0; i < elements.Length; i++) { @@ -980,7 +981,7 @@ private void AddScopeElements(INameScope scope, ElementAccessor[] elements, ref } } - private void ImportGroupMembers(XmlSchemaParticle particle, string identifier, CodeIdentifiers members, CodeIdentifiers membersScope, INameScope elementsScope, string ns, bool groupRepeats, ref bool mixed, ref bool needExplicitOrder, bool allowDuplicates, bool allowUnboundedElements) + private void ImportGroupMembers(XmlSchemaParticle? particle, string identifier, CodeIdentifiers members, CodeIdentifiers membersScope, INameScope elementsScope, string? ns, bool groupRepeats, ref bool mixed, ref bool needExplicitOrder, bool allowDuplicates, bool allowUnboundedElements) { if (particle is XmlSchemaGroupRef) { @@ -1025,7 +1026,7 @@ private void ImportGroupMembers(XmlSchemaParticle particle, string identifier, C } } - private XmlSchemaElement GetTopLevelElement(XmlSchemaElement element) + private XmlSchemaElement? GetTopLevelElement(XmlSchemaElement element) { if (!element.RefName.IsEmpty) return FindElement(element.RefName); @@ -1057,7 +1058,7 @@ private XmlSchemaElement[] GetEquivalentElements(XmlSchemaElement element) return (XmlSchemaElement[])equivalentElements.ToArray(typeof(XmlSchemaElement)); } - private bool ImportSubstitutionGroupMember(XmlSchemaElement element, string identifier, CodeIdentifiers members, CodeIdentifiers membersScope, string ns, bool repeats, ref bool needExplicitOrder, bool allowDuplicates) + private bool ImportSubstitutionGroupMember(XmlSchemaElement element, string identifier, CodeIdentifiers members, CodeIdentifiers membersScope, string? ns, bool repeats, ref bool needExplicitOrder, bool allowDuplicates) { XmlSchemaElement[] elements = GetEquivalentElements(element); if (elements.Length == 0) @@ -1068,24 +1069,24 @@ private bool ImportSubstitutionGroupMember(XmlSchemaElement element, string iden if (!element.IsAbstract) choice.Items.Add(element); if (identifier.Length == 0) - identifier = CodeIdentifier.MakeValid(Accessor.UnescapeName(element.Name)); + identifier = CodeIdentifier.MakeValid(Accessor.UnescapeName(element.Name!)); else - identifier += CodeIdentifier.MakePascal(Accessor.UnescapeName(element.Name)); + identifier += CodeIdentifier.MakePascal(Accessor.UnescapeName(element.Name!)); ImportChoiceGroup(choice, identifier, members, membersScope, null, ns, repeats, ref needExplicitOrder, allowDuplicates); return true; } - private void ImportTextMember(CodeIdentifiers members, CodeIdentifiers membersScope, XmlQualifiedName simpleContentType) + private void ImportTextMember(CodeIdentifiers members, CodeIdentifiers membersScope, XmlQualifiedName? simpleContentType) { - TypeMapping mapping; + TypeMapping? mapping; bool isMixed = false; if (simpleContentType != null) { // allow to use all primitive types mapping = ImportType(simpleContentType, typeof(TypeMapping), null, TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue, false); - if (!(mapping is PrimitiveMapping || mapping.TypeDesc.CanBeTextValue)) + if (!(mapping is PrimitiveMapping || mapping!.TypeDesc!.CanBeTextValue)) { return; } @@ -1106,7 +1107,7 @@ private void ImportTextMember(CodeIdentifiers members, CodeIdentifiers membersSc if (isMixed) { // just generate code for the standard mixed case (string[] text) - member.TypeDesc = accessor.Mapping.TypeDesc.CreateArrayTypeDesc(); + member.TypeDesc = accessor.Mapping.TypeDesc!.CreateArrayTypeDesc(); member.Name = members.MakeRightCase("Text"); } else @@ -1115,7 +1116,7 @@ private void ImportTextMember(CodeIdentifiers members, CodeIdentifiers membersSc PrimitiveMapping pm = (PrimitiveMapping)accessor.Mapping; if (pm.IsList) { - member.TypeDesc = accessor.Mapping.TypeDesc.CreateArrayTypeDesc(); + member.TypeDesc = accessor.Mapping.TypeDesc!.CreateArrayTypeDesc(); member.Name = members.MakeRightCase("Text"); } else @@ -1128,7 +1129,7 @@ private void ImportTextMember(CodeIdentifiers members, CodeIdentifiers membersSc members.Add(member.Name, member); } - private MemberMapping ImportAnyMember(XmlSchemaAny any, string identifier, CodeIdentifiers members, CodeIdentifiers membersScope, INameScope elementsScope, string ns, ref bool mixed, ref bool needExplicitOrder, bool allowDuplicates) + private MemberMapping ImportAnyMember(XmlSchemaAny any, string identifier, CodeIdentifiers members, CodeIdentifiers membersScope, INameScope elementsScope, string? ns, ref bool mixed, ref bool needExplicitOrder, bool allowDuplicates) { ElementAccessor[] accessors = ImportAny(any, !mixed, ns); AddScopeElements(elementsScope, accessors, ref needExplicitOrder, allowDuplicates); @@ -1137,7 +1138,7 @@ private MemberMapping ImportAnyMember(XmlSchemaAny any, string identifier, CodeI member.Name = membersScope.MakeRightCase("Any"); member.Name = membersScope.AddUnique(member.Name, member); members.Add(member.Name, member); - member.TypeDesc = ((TypeMapping)accessors[0].Mapping).TypeDesc; + member.TypeDesc = ((TypeMapping)accessors[0].Mapping!).TypeDesc; bool repeats = any.IsMultipleOccurrence; @@ -1156,11 +1157,11 @@ private MemberMapping ImportAnyMember(XmlSchemaAny any, string identifier, CodeI if (repeats) { - member.TypeDesc = member.TypeDesc.CreateArrayTypeDesc(); + member.TypeDesc = member.TypeDesc!.CreateArrayTypeDesc(); } return member; } - private ElementAccessor[] ImportAny(XmlSchemaAny any, bool makeElement, string targetNamespace) + private ElementAccessor[] ImportAny(XmlSchemaAny any, bool makeElement, string? targetNamespace) { SpecialMapping mapping = new SpecialMapping(); @@ -1177,7 +1178,7 @@ private ElementAccessor[] ImportAny(XmlSchemaAny any, bool makeElement, string t if (GenerateOrder && any.Namespace != null) { - NamespaceList list = new NamespaceList(any.Namespace, targetNamespace); + NamespaceList list = new NamespaceList(any.Namespace, targetNamespace!); if (list.Type == NamespaceList.ListType.Set) { @@ -1205,31 +1206,31 @@ private ElementAccessor[] ImportAny(XmlSchemaAny any, bool makeElement, string t return new ElementAccessor[] { anyAccessor }; } - private ElementAccessor ImportArray(XmlSchemaElement element, string identifier, string ns, bool repeats) + private ElementAccessor? ImportArray(XmlSchemaElement element, string identifier, string? ns, bool repeats) { if (repeats) return null; if (element.SchemaType == null) return null; if (element.IsMultipleOccurrence) return null; XmlSchemaType type = element.SchemaType; - ArrayMapping arrayMapping = ImportArrayMapping(type, identifier, ns, repeats); + ArrayMapping? arrayMapping = ImportArrayMapping(type, identifier, ns, repeats); if (arrayMapping == null) return null; ElementAccessor arrayAccessor = new ElementAccessor(); arrayAccessor.Name = element.Name; arrayAccessor.Namespace = ns; arrayAccessor.Mapping = arrayMapping; - if (arrayMapping.TypeDesc.IsNullable) + if (arrayMapping.TypeDesc!.IsNullable) arrayAccessor.IsNullable = element.IsNillable; arrayAccessor.Form = ElementForm(ns, element); return arrayAccessor; } - private ArrayMapping ImportArrayMapping(XmlSchemaType type, string identifier, string ns, bool repeats) + private ArrayMapping? ImportArrayMapping(XmlSchemaType type, string identifier, string? ns, bool repeats) { if (!(type is XmlSchemaComplexType)) return null; if (!type.DerivedFrom.IsEmpty) return null; if (IsMixed(type)) return null; - Mapping previousMapping = (Mapping)ImportedMappings[type]; + Mapping? previousMapping = (Mapping?)ImportedMappings[type]; if (previousMapping != null) { if (previousMapping is ArrayMapping) @@ -1260,7 +1261,7 @@ private ArrayMapping ImportArrayMapping(XmlSchemaType type, string identifier, s if (choiceMember.ChoiceIdentifier != null) return null; arrayMapping.TypeDesc = choiceMember.TypeDesc; arrayMapping.Elements = choiceMember.Elements; - arrayMapping.TypeName = (type.Name == null || type.Name.Length == 0) ? "ArrayOf" + CodeIdentifier.MakePascal(arrayMapping.TypeDesc.Name) : type.Name; + arrayMapping.TypeName = (type.Name == null || type.Name.Length == 0) ? "ArrayOf" + CodeIdentifier.MakePascal(arrayMapping.TypeDesc!.Name) : type.Name; } else if (item is XmlSchemaAll || item is XmlSchemaSequence) { @@ -1276,7 +1277,7 @@ private ArrayMapping ImportArrayMapping(XmlSchemaType type, string identifier, s if (itemAccessor.Any) return null; arrayMapping.Elements = new ElementAccessor[] { itemAccessor }; - arrayMapping.TypeDesc = ((TypeMapping)itemAccessor.Mapping).TypeDesc.CreateArrayTypeDesc(); + arrayMapping.TypeDesc = ((TypeMapping)itemAccessor.Mapping!).TypeDesc!.CreateArrayTypeDesc(); arrayMapping.TypeName = (type.Name == null || type.Name.Length == 0) ? "ArrayOf" + CodeIdentifier.MakePascal(itemAccessor.Mapping.TypeDesc.Name) : type.Name; } else @@ -1300,7 +1301,7 @@ private bool IsCyclicReferencedType(XmlSchemaElement element, List ident if (!element.RefName.IsEmpty) { XmlSchemaElement refElement = FindElement(element.RefName); - string refElementIdentifier = CodeIdentifier.MakeValid(Accessor.UnescapeName(refElement.Name)); + string refElementIdentifier = CodeIdentifier.MakeValid(Accessor.UnescapeName(refElement.Name!)); foreach (string identifier in identifiers) { if (refElementIdentifier == identifier) @@ -1310,7 +1311,7 @@ private bool IsCyclicReferencedType(XmlSchemaElement element, List ident } identifiers.Add(refElementIdentifier); - XmlSchemaType refType = refElement.SchemaType; + XmlSchemaType? refType = refElement.SchemaType; if (refType is XmlSchemaComplexType) { TypeItems items = GetTypeItems(refType); @@ -1327,7 +1328,7 @@ private bool IsCyclicReferencedType(XmlSchemaElement element, List ident return false; } - private SpecialMapping ImportAnyMapping(XmlSchemaType type, string identifier, string ns, bool repeats) + private SpecialMapping? ImportAnyMapping(XmlSchemaType? type, string identifier, string? ns, bool repeats) { if (type == null) return null; if (!type.DerivedFrom.IsEmpty) return null; @@ -1373,15 +1374,15 @@ private SpecialMapping ImportAnyMapping(XmlSchemaType type, string identifier, s return mapping; } - private void ImportElementMember(XmlSchemaElement element, string identifier, CodeIdentifiers members, CodeIdentifiers membersScope, INameScope elementsScope, string ns, bool repeats, ref bool needExplicitOrder, bool allowDuplicates, bool allowUnboundedElements) + private void ImportElementMember(XmlSchemaElement element, string identifier, CodeIdentifiers members, CodeIdentifiers membersScope, INameScope elementsScope, string? ns, bool repeats, ref bool needExplicitOrder, bool allowDuplicates, bool allowUnboundedElements) { repeats = repeats | element.IsMultipleOccurrence; - XmlSchemaElement headElement = GetTopLevelElement(element); + XmlSchemaElement? headElement = GetTopLevelElement(element); if (headElement != null && ImportSubstitutionGroupMember(headElement, identifier, members, membersScope, ns, repeats, ref needExplicitOrder, allowDuplicates)) { return; } - ElementAccessor accessor; + ElementAccessor? accessor; if ((accessor = ImportArray(element, identifier, ns, repeats)) == null) { accessor = ImportElement(element, identifier, typeof(TypeMapping), null, ns, false); @@ -1399,7 +1400,7 @@ private void ImportElementMember(XmlSchemaElement element, string identifier, Co } members.Add(member.Name, member); // we do not support lists for elements - if (accessor.Mapping.IsList) + if (accessor.Mapping!.IsList) { accessor.Mapping = GetDefaultMapping(TypeFlags.CanBeElementValue | TypeFlags.CanBeTextValue); member.TypeDesc = accessor.Mapping.TypeDesc; @@ -1416,22 +1417,22 @@ private void ImportElementMember(XmlSchemaElement element, string identifier, Co { if (!allowUnboundedElements && accessor.Mapping is ArrayMapping) { - accessor.Mapping = ((ArrayMapping)accessor.Mapping).TopLevelMapping; + accessor.Mapping = ((ArrayMapping)accessor.Mapping).TopLevelMapping!; accessor.Mapping.ReferencedByTopLevelElement = false; accessor.Mapping.ReferencedByElement = true; } - member.TypeDesc = accessor.Mapping.TypeDesc.CreateArrayTypeDesc(); + member.TypeDesc = accessor.Mapping.TypeDesc!.CreateArrayTypeDesc(); } - if (element.MinOccurs == 0 && member.TypeDesc.IsValueType && !element.HasDefault && !member.TypeDesc.HasIsEmpty) + if (element.MinOccurs == 0 && member.TypeDesc!.IsValueType && !element.HasDefault && !member.TypeDesc.HasIsEmpty) { member.CheckSpecified = SpecifiedAccessor.ReadWrite; } } - private void ImportAttributeMember(XmlSchemaAttribute attribute, string identifier, CodeIdentifiers members, CodeIdentifiers membersScope, string ns) + private void ImportAttributeMember(XmlSchemaAttribute attribute, string identifier, CodeIdentifiers members, CodeIdentifiers membersScope, string? ns) { - AttributeAccessor accessor = ImportAttribute(attribute, identifier, ns, attribute); + AttributeAccessor? accessor = ImportAttribute(attribute, identifier, ns, attribute); if (accessor == null) return; MemberMapping member = new MemberMapping(); member.Elements = Array.Empty(); @@ -1445,9 +1446,9 @@ private void ImportAttributeMember(XmlSchemaAttribute attribute, string identifi membersScope.Remove(name); } members.Add(member.Name, member); - member.TypeDesc = accessor.IsList ? accessor.Mapping.TypeDesc.CreateArrayTypeDesc() : accessor.Mapping.TypeDesc; + member.TypeDesc = accessor.IsList ? accessor.Mapping!.TypeDesc!.CreateArrayTypeDesc() : accessor.Mapping!.TypeDesc; - if ((attribute.Use == XmlSchemaUse.Optional || attribute.Use == XmlSchemaUse.None) && member.TypeDesc.IsValueType && !attribute.HasDefault && !member.TypeDesc.HasIsEmpty) + if ((attribute.Use == XmlSchemaUse.Optional || attribute.Use == XmlSchemaUse.None) && member.TypeDesc!.IsValueType && !attribute.HasDefault && !member.TypeDesc.HasIsEmpty) { member.CheckSpecified = SpecifiedAccessor.ReadWrite; } @@ -1473,7 +1474,7 @@ private void ImportAnyAttributeMember(XmlSchemaAnyAttribute any, CodeIdentifiers member.TypeDesc = member.TypeDesc.CreateArrayTypeDesc(); } - private bool KeepXmlnsDeclarations(XmlSchemaType type, out string xmlnsMemberName) + private bool KeepXmlnsDeclarations(XmlSchemaType type, out string? xmlnsMemberName) { xmlnsMemberName = null; if (type.Annotation == null) @@ -1485,7 +1486,7 @@ private bool KeepXmlnsDeclarations(XmlSchemaType type, out string xmlnsMemberNam { if (o is XmlSchemaAppInfo) { - XmlNode[] nodes = ((XmlSchemaAppInfo)o).Markup; + XmlNode[]? nodes = ((XmlSchemaAppInfo)o).Markup; if (nodes != null && nodes.Length > 0) { foreach (XmlNode node in nodes) @@ -1497,7 +1498,7 @@ private bool KeepXmlnsDeclarations(XmlSchemaType type, out string xmlnsMemberNam { if (e.LastNode is XmlText) { - xmlnsMemberName = (((XmlText)e.LastNode).Value).Trim(null); + xmlnsMemberName = (((XmlText)e.LastNode).Value!).Trim(null); } return true; } @@ -1511,7 +1512,7 @@ private bool KeepXmlnsDeclarations(XmlSchemaType type, out string xmlnsMemberNam private void ImportXmlnsDeclarationsMember(XmlSchemaType type, CodeIdentifiers members, CodeIdentifiers membersScope) { - string xmlnsMemberName; + string? xmlnsMemberName; if (!KeepXmlnsDeclarations(type, out xmlnsMemberName)) return; TypeDesc xmlnsTypeDesc = Scope.GetTypeDesc(typeof(System.Xml.Serialization.XmlSerializerNamespaces)); @@ -1554,7 +1555,7 @@ private AttributeAccessor ImportSpecialAttribute(XmlQualifiedName name, string i { PrimitiveMapping mapping = new PrimitiveMapping(); mapping.TypeDesc = Scope.GetTypeDesc(typeof(string)); - mapping.TypeName = mapping.TypeDesc.DataType.Name; + mapping.TypeName = mapping.TypeDesc.DataType!.Name; AttributeAccessor accessor = new AttributeAccessor(); accessor.Name = name.Name; accessor.Namespace = XmlReservedNs.NsXml; @@ -1563,7 +1564,7 @@ private AttributeAccessor ImportSpecialAttribute(XmlQualifiedName name, string i return accessor; } - private AttributeAccessor ImportAttribute(XmlSchemaAttribute attribute, string identifier, string ns, XmlSchemaAttribute defaultValueProvider) + private AttributeAccessor? ImportAttribute(XmlSchemaAttribute attribute, string identifier, string? ns, XmlSchemaAttribute defaultValueProvider) { if (attribute.Use == XmlSchemaUse.Prohibited) return null; if (!attribute.RefName.IsEmpty) @@ -1573,14 +1574,14 @@ private AttributeAccessor ImportAttribute(XmlSchemaAttribute attribute, string i else return ImportAttribute(FindAttribute(attribute.RefName), identifier, attribute.RefName.Namespace, defaultValueProvider); } - TypeMapping mapping; - if (attribute.Name.Length == 0) throw new InvalidOperationException(SR.XmlAttributeHasNoName); + TypeMapping? mapping; + if (attribute.Name!.Length == 0) throw new InvalidOperationException(SR.XmlAttributeHasNoName); if (identifier.Length == 0) identifier = CodeIdentifier.MakeValid(attribute.Name); else identifier += CodeIdentifier.MakePascal(attribute.Name); if (!attribute.SchemaTypeName.IsEmpty) - mapping = (TypeMapping)ImportType(attribute.SchemaTypeName, typeof(TypeMapping), null, TypeFlags.CanBeAttributeValue, false); + mapping = (TypeMapping?)ImportType(attribute.SchemaTypeName, typeof(TypeMapping), null, TypeFlags.CanBeAttributeValue, false); else if (attribute.SchemaType != null) mapping = ImportDataType((XmlSchemaSimpleType)attribute.SchemaType, ns, identifier, null, TypeFlags.CanBeAttributeValue, false); else @@ -1589,7 +1590,7 @@ private AttributeAccessor ImportAttribute(XmlSchemaAttribute attribute, string i } // let the extensions to run - if (mapping != null && !mapping.TypeDesc.IsMappedType) + if (mapping != null && !mapping.TypeDesc!.IsMappedType) { RunSchemaExtensions(mapping, attribute.SchemaTypeName, attribute.SchemaType, attribute, TypeFlags.CanBeElementValue | TypeFlags.CanBeAttributeValue | TypeFlags.CanBeTextValue); } @@ -1599,7 +1600,7 @@ private AttributeAccessor ImportAttribute(XmlSchemaAttribute attribute, string i accessor.Form = AttributeForm(ns, attribute); accessor.CheckSpecial(); accessor.Mapping = mapping; - accessor.IsList = mapping.IsList; + accessor.IsList = mapping!.IsList; accessor.IsOptional = attribute.Use != XmlSchemaUse.Required; if (defaultValueProvider.DefaultValue != null) @@ -1626,12 +1627,12 @@ private AttributeAccessor ImportAttribute(XmlSchemaAttribute attribute, string i return accessor; } - private TypeMapping ImportDataType(XmlSchemaSimpleType dataType, string typeNs, string identifier, Type baseType, TypeFlags flags, bool isList) + private TypeMapping? ImportDataType(XmlSchemaSimpleType dataType, string? typeNs, string identifier, Type? baseType, TypeFlags flags, bool isList) { if (baseType != null) return ImportStructDataType(dataType, typeNs, identifier, baseType); - TypeMapping mapping = ImportNonXsdPrimitiveDataType(dataType, typeNs, flags); + TypeMapping? mapping = ImportNonXsdPrimitiveDataType(dataType, typeNs, flags); if (mapping != null) return mapping; @@ -1652,7 +1653,7 @@ private TypeMapping ImportDataType(XmlSchemaSimpleType dataType, string typeNs, else { AddReference(restriction.BaseTypeName, TypesInUse, SR.XmlCircularTypeReference); - mapping = ImportDataType(FindDataType(restriction.BaseTypeName, flags), restriction.BaseTypeName.Namespace, identifier, null, flags, false); + mapping = ImportDataType(FindDataType(restriction.BaseTypeName, flags)!, restriction.BaseTypeName.Namespace, identifier, null, flags, false); if (restriction.BaseTypeName.Namespace != XmlSchema.Namespace) RemoveReference(restriction.BaseTypeName, TypesInUse); return mapping; @@ -1688,19 +1689,19 @@ private TypeMapping ImportDataType(XmlSchemaSimpleType dataType, string typeNs, return ImportPrimitiveDataType(dataType, flags); } - private TypeMapping ImportEnumeratedDataType(XmlSchemaSimpleType dataType, string typeNs, string identifier, TypeFlags flags, bool isList) + private TypeMapping? ImportEnumeratedDataType(XmlSchemaSimpleType dataType, string? typeNs, string identifier, TypeFlags flags, bool isList) { - TypeMapping mapping = (TypeMapping)ImportedMappings[dataType]; + TypeMapping? mapping = (TypeMapping?)ImportedMappings[dataType]; if (mapping != null) return mapping; XmlSchemaType sourceType = dataType; while (!sourceType.DerivedFrom.IsEmpty) { - sourceType = FindType(sourceType.DerivedFrom, TypeFlags.CanBeElementValue | TypeFlags.CanBeAttributeValue); + sourceType = FindType(sourceType.DerivedFrom, TypeFlags.CanBeElementValue | TypeFlags.CanBeAttributeValue)!; } if (sourceType is XmlSchemaComplexType) return null; - TypeDesc sourceTypeDesc = Scope.GetTypeDesc((XmlSchemaSimpleType)sourceType); + TypeDesc? sourceTypeDesc = Scope.GetTypeDesc((XmlSchemaSimpleType)sourceType); if (sourceTypeDesc != null && sourceTypeDesc.FullName != typeof(string).FullName) return ImportPrimitiveDataType(dataType, flags); identifier = Accessor.UnescapeName(identifier); @@ -1714,7 +1715,7 @@ private TypeMapping ImportEnumeratedDataType(XmlSchemaSimpleType dataType, strin enumMapping.IsFlags = isList; CodeIdentifiers constants = new CodeIdentifiers(); - XmlSchemaSimpleTypeContent content = dataType.Content; + XmlSchemaSimpleTypeContent? content = dataType.Content; if (content is XmlSchemaSimpleTypeRestriction) { @@ -1727,15 +1728,16 @@ private TypeMapping ImportEnumeratedDataType(XmlSchemaSimpleType dataType, strin // validate the enumeration value if (sourceTypeDesc != null && sourceTypeDesc.HasCustomFormatter) { - XmlCustomFormatter.ToDefaultValue(enumeration.Value, sourceTypeDesc.FormatterName); + XmlCustomFormatter.ToDefaultValue(enumeration.Value!, sourceTypeDesc.FormatterName!); } ConstantMapping constant = new ConstantMapping(); - string constantName = CodeIdentifier.MakeValid(enumeration.Value); + string constantName = CodeIdentifier.MakeValid(enumeration.Value!); constant.Name = constants.AddUnique(constantName, constant); constant.XmlName = enumeration.Value; constant.Value = i; } } + enumMapping.Constants = (ConstantMapping[])constants.ToArray(typeof(ConstantMapping)); if (isList && enumMapping.Constants.Length > 63) { @@ -1751,15 +1753,15 @@ private TypeMapping ImportEnumeratedDataType(XmlSchemaSimpleType dataType, strin internal class ElementComparer : IComparer { - public int Compare(object o1, object o2) + public int Compare(object? o1, object? o2) { - ElementAccessor e1 = (ElementAccessor)o1; - ElementAccessor e2 = (ElementAccessor)o2; + ElementAccessor e1 = (ElementAccessor)o1!; + ElementAccessor e2 = (ElementAccessor)o2!; return string.Compare(e1.ToString(string.Empty), e2.ToString(string.Empty), StringComparison.Ordinal); } } - private EnumMapping ImportEnumeratedChoice(ElementAccessor[] choice, string typeNs, string typeName) + private EnumMapping ImportEnumeratedChoice(ElementAccessor[] choice, string? typeNs, string typeName) { typeName = GenerateUniqueTypeName(Accessor.UnescapeName(typeName), typeNs); EnumMapping enumMapping = new EnumMapping(); @@ -1793,15 +1795,15 @@ private PrimitiveMapping ImportPrimitiveDataType(XmlSchemaSimpleType dataType, T TypeDesc sourceTypeDesc = GetDataTypeSource(dataType, flags); PrimitiveMapping mapping = new PrimitiveMapping(); mapping.TypeDesc = sourceTypeDesc; - mapping.TypeName = sourceTypeDesc.DataType.Name; + mapping.TypeName = sourceTypeDesc.DataType!.Name; mapping.Namespace = mapping.TypeDesc.IsXsdType ? XmlSchema.Namespace : UrtTypes.Namespace; return mapping; } - private PrimitiveMapping ImportNonXsdPrimitiveDataType(XmlSchemaSimpleType dataType, string ns, TypeFlags flags) + private PrimitiveMapping? ImportNonXsdPrimitiveDataType(XmlSchemaSimpleType dataType, string? ns, TypeFlags flags) { - PrimitiveMapping mapping = null; - TypeDesc typeDesc = null; + PrimitiveMapping? mapping = null; + TypeDesc? typeDesc = null; if (dataType.Name != null && dataType.Name.Length != 0) { typeDesc = Scope.GetTypeDesc(dataType.Name, ns, flags); @@ -1809,7 +1811,7 @@ private PrimitiveMapping ImportNonXsdPrimitiveDataType(XmlSchemaSimpleType dataT { mapping = new PrimitiveMapping(); mapping.TypeDesc = typeDesc; - mapping.TypeName = typeDesc.DataType.Name; + mapping.TypeName = typeDesc.DataType!.Name; mapping.Namespace = mapping.TypeDesc.IsXsdType ? XmlSchema.Namespace : ns; } } @@ -1818,7 +1820,7 @@ private PrimitiveMapping ImportNonXsdPrimitiveDataType(XmlSchemaSimpleType dataT private XmlSchemaGroup FindGroup(XmlQualifiedName name) { - XmlSchemaGroup group = (XmlSchemaGroup)Schemas.Find(name, typeof(XmlSchemaGroup)); + XmlSchemaGroup? group = (XmlSchemaGroup?)Schemas.Find(name, typeof(XmlSchemaGroup)); if (group == null) throw new InvalidOperationException(SR.Format(SR.XmlMissingGroup, name.Name)); @@ -1827,7 +1829,7 @@ private XmlSchemaGroup FindGroup(XmlQualifiedName name) private XmlSchemaAttributeGroup FindAttributeGroup(XmlQualifiedName name) { - XmlSchemaAttributeGroup group = (XmlSchemaAttributeGroup)Schemas.Find(name, typeof(XmlSchemaAttributeGroup)); + XmlSchemaAttributeGroup? group = (XmlSchemaAttributeGroup?)Schemas.Find(name, typeof(XmlSchemaAttributeGroup)); if (group == null) throw new InvalidOperationException(SR.Format(SR.XmlMissingAttributeGroup, name.Name)); @@ -1836,7 +1838,7 @@ private XmlSchemaAttributeGroup FindAttributeGroup(XmlQualifiedName name) internal static XmlQualifiedName BaseTypeName(XmlSchemaSimpleType dataType) { - XmlSchemaSimpleTypeContent content = dataType.Content; + XmlSchemaSimpleTypeContent? content = dataType.Content; if (content is XmlSchemaSimpleTypeRestriction) { return ((XmlSchemaSimpleTypeRestriction)content).BaseTypeName; @@ -1856,7 +1858,7 @@ internal static XmlQualifiedName BaseTypeName(XmlSchemaSimpleType dataType) private TypeDesc GetDataTypeSource(XmlSchemaSimpleType dataType, TypeFlags flags) { - TypeDesc typeDesc = null; + TypeDesc? typeDesc = null; if (dataType.Name != null && dataType.Name.Length != 0) { typeDesc = Scope.GetTypeDesc(dataType); @@ -1864,29 +1866,34 @@ private TypeDesc GetDataTypeSource(XmlSchemaSimpleType dataType, TypeFlags flags } XmlQualifiedName qname = BaseTypeName(dataType); AddReference(qname, TypesInUse, SR.XmlCircularTypeReference); - typeDesc = GetDataTypeSource(FindDataType(qname, flags), flags); + typeDesc = GetDataTypeSource(FindDataType(qname, flags)!, flags); if (qname.Namespace != XmlSchema.Namespace) RemoveReference(qname, TypesInUse); return typeDesc; } - private XmlSchemaSimpleType FindDataType(XmlQualifiedName name, TypeFlags flags) + private XmlSchemaSimpleType? FindDataType(XmlQualifiedName? name, TypeFlags flags) { if (name == null || name.IsEmpty) { - return (XmlSchemaSimpleType)Scope.GetTypeDesc(typeof(string)).DataType; + return (XmlSchemaSimpleType?)Scope.GetTypeDesc(typeof(string)).DataType; } - TypeDesc typeDesc = Scope.GetTypeDesc(name.Name, name.Namespace, flags); + + TypeDesc? typeDesc = Scope.GetTypeDesc(name.Name, name.Namespace, flags); if (typeDesc != null && typeDesc.DataType is XmlSchemaSimpleType) return (XmlSchemaSimpleType)typeDesc.DataType; - XmlSchemaSimpleType dataType = (XmlSchemaSimpleType)Schemas.Find(name, typeof(XmlSchemaSimpleType)); + + XmlSchemaSimpleType? dataType = (XmlSchemaSimpleType?)Schemas.Find(name, typeof(XmlSchemaSimpleType)); if (dataType != null) { return dataType; } + if (name.Namespace == XmlSchema.Namespace) - return (XmlSchemaSimpleType)Scope.GetTypeDesc("string", XmlSchema.Namespace, flags).DataType; + { + return (XmlSchemaSimpleType?)Scope.GetTypeDesc("string", XmlSchema.Namespace, flags)!.DataType; + } else { if (name.Name == Soap.Array && name.Namespace == Soap.Encoding) @@ -1900,23 +1907,25 @@ private XmlSchemaSimpleType FindDataType(XmlQualifiedName name, TypeFlags flags) } } - private XmlSchemaType FindType(XmlQualifiedName name, TypeFlags flags) + private XmlSchemaType? FindType(XmlQualifiedName? name, TypeFlags flags) { if (name == null || name.IsEmpty) { return Scope.GetTypeDesc(typeof(string)).DataType; } - object type = Schemas.Find(name, typeof(XmlSchemaComplexType)); + + object? type = Schemas.Find(name, typeof(XmlSchemaComplexType)); if (type != null) { - return (XmlSchemaComplexType)type; + return (XmlSchemaComplexType?)type; } + return FindDataType(name, flags); } private XmlSchemaElement FindElement(XmlQualifiedName name) { - XmlSchemaElement element = (XmlSchemaElement)Schemas.Find(name, typeof(XmlSchemaElement)); + XmlSchemaElement? element = (XmlSchemaElement?)Schemas.Find(name, typeof(XmlSchemaElement)); if (element == null) throw new InvalidOperationException(SR.Format(SR.XmlMissingElement, name)); return element; @@ -1924,14 +1933,14 @@ private XmlSchemaElement FindElement(XmlQualifiedName name) private XmlSchemaAttribute FindAttribute(XmlQualifiedName name) { - XmlSchemaAttribute attribute = (XmlSchemaAttribute)Schemas.Find(name, typeof(XmlSchemaAttribute)); + XmlSchemaAttribute? attribute = (XmlSchemaAttribute?)Schemas.Find(name, typeof(XmlSchemaAttribute)); if (attribute == null) throw new InvalidOperationException(SR.Format(SR.XmlMissingAttribute, name.Name)); return attribute; } - private XmlSchemaForm ElementForm(string ns, XmlSchemaElement element) + private XmlSchemaForm ElementForm(string? ns, XmlSchemaElement element) { if (element.Form == XmlSchemaForm.None) { @@ -1940,7 +1949,7 @@ private XmlSchemaForm ElementForm(string ns, XmlSchemaElement element) { parent = parent.Parent; } - XmlSchema schema = parent as XmlSchema; + XmlSchema? schema = parent as XmlSchema; if (schema != null) { @@ -1959,7 +1968,7 @@ private XmlSchemaForm ElementForm(string ns, XmlSchemaElement element) return element.Form; } - private XmlSchemaForm AttributeForm(string ns, XmlSchemaAttribute attribute) + private XmlSchemaForm AttributeForm(string? ns, XmlSchemaAttribute attribute) { if (attribute.Form == XmlSchemaForm.None) { @@ -1968,7 +1977,7 @@ private XmlSchemaForm AttributeForm(string ns, XmlSchemaAttribute attribute) { parent = parent.Parent; } - XmlSchema schema = parent as XmlSchema; + XmlSchema? schema = parent as XmlSchema; if (schema != null) { if (ns == null || ns.Length == 0) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaProviderAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaProviderAttribute.cs index 9979421d7d4743..36095d9a673300 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaProviderAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaProviderAttribute.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; @@ -12,13 +13,13 @@ namespace System.Xml.Serialization [AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface | AttributeTargets.Struct)] public sealed class XmlSchemaProviderAttribute : System.Attribute { - private readonly string _methodName; + private readonly string? _methodName; private bool _any; /// /// [To be supplied.] /// - public XmlSchemaProviderAttribute(string methodName) + public XmlSchemaProviderAttribute(string? methodName) { _methodName = methodName; } @@ -26,7 +27,7 @@ public XmlSchemaProviderAttribute(string methodName) /// /// [To be supplied.] /// - public string MethodName + public string? MethodName { get { return _methodName; } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemas.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemas.cs index 06f9c236fde007..241c9a84bbaf67 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemas.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemas.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System.Collections; @@ -16,26 +17,27 @@ namespace System.Xml.Serialization using System.Security; using System.Net; using System.Reflection; + using System.Diagnostics.CodeAnalysis; public class XmlSchemas : CollectionBase, IEnumerable { - private XmlSchemaSet _schemaSet; - private Hashtable _references; - private SchemaObjectCache _cache; // cached schema top-level items + private XmlSchemaSet? _schemaSet; + private Hashtable? _references; + private SchemaObjectCache? _cache; // cached schema top-level items private bool _shareTypes; - private Hashtable _mergedSchemas; + private Hashtable? _mergedSchemas; internal Hashtable delayedSchemas = new Hashtable(); private bool _isCompiled; - private static volatile XmlSchema s_xsd; - private static volatile XmlSchema s_xml; + private static volatile XmlSchema? s_xsd; + private static volatile XmlSchema? s_xml; public XmlSchema this[int index] { - get { return (XmlSchema)List[index]; } + get { return (XmlSchema)List[index]!; } set { List[index] = value; } } - public XmlSchema this[string ns] + public XmlSchema? this[string? ns] { get { @@ -43,13 +45,13 @@ public XmlSchema this[string ns] if (values.Count == 0) return null; if (values.Count == 1) - return (XmlSchema)values[0]; + return (XmlSchema?)values[0]; throw new InvalidOperationException(SR.Format(SR.XmlSchemaDuplicateNamespace, ns)); } } - public IList GetSchemas(string ns) + public IList GetSchemas(string? ns) { return (IList)SchemaSet.Schemas(ns); } @@ -170,14 +172,14 @@ public void CopyTo(XmlSchema[] array, int index) List.CopyTo(array, index); } - protected override void OnInsert(int index, object value) + protected override void OnInsert(int index, object? value) { - AddName((XmlSchema)value); + AddName((XmlSchema)value!); } - protected override void OnRemove(int index, object value) + protected override void OnRemove(int index, object? value) { - RemoveName((XmlSchema)value); + RemoveName((XmlSchema)value!); } protected override void OnClear() @@ -185,10 +187,10 @@ protected override void OnClear() _schemaSet = null; } - protected override void OnSet(int index, object oldValue, object newValue) + protected override void OnSet(int index, object? oldValue, object? newValue) { - RemoveName((XmlSchema)oldValue); - AddName((XmlSchema)newValue); + RemoveName((XmlSchema)oldValue!); + AddName((XmlSchema)newValue!); } private void AddName(XmlSchema schema) @@ -207,7 +209,7 @@ private void Prepare(XmlSchema schema) { // need to remove illegal externals; ArrayList removes = new ArrayList(); - string ns = schema.TargetNamespace; + string? ns = schema.TargetNamespace; foreach (XmlSchemaExternal external in schema.Includes) { if (external is XmlSchemaImport) @@ -229,11 +231,11 @@ private void RemoveName(XmlSchema schema) SchemaSet.Remove(schema); } - public object Find(XmlQualifiedName name, Type type) + public object? Find(XmlQualifiedName name, Type type) { return Find(name, type, true); } - internal object Find(XmlQualifiedName name, Type type, bool checkCache) + internal object? Find(XmlQualifiedName name, Type type, bool checkCache) { if (!IsCompiled) { @@ -249,7 +251,7 @@ internal object Find(XmlQualifiedName name, Type type, bool checkCache) { Preprocess(schema); - XmlSchemaObject ret = null; + XmlSchemaObject? ret = null; if (typeof(XmlSchemaType).IsAssignableFrom(type)) { ret = schema.SchemaTypes[name]; @@ -359,7 +361,7 @@ private void Merge(XmlSchema schema) } } - private void AddImport(IList schemas, string ns) + private void AddImport(IList schemas, string? ns) { foreach (XmlSchema s in schemas) { @@ -429,7 +431,7 @@ private void Merge(IList originals, XmlSchema schema) for (int i = 0; i < schema.Items.Count; i++) { XmlSchemaObject o = schema.Items[i]; - XmlSchemaObject dest = Find(o, originals); + XmlSchemaObject? dest = Find(o, originals); if (dest != null) { if (!Cache.Match(dest, o, _shareTypes)) @@ -442,7 +444,7 @@ private void Merge(IList originals, XmlSchema schema) } if (count != schema.Items.Count) { - XmlSchema destination = (XmlSchema)originals[0]; + XmlSchema destination = (XmlSchema)originals[0]!; for (int i = 0; i < schema.Items.Count; i++) { if (!matchedItems[i]) @@ -455,7 +457,7 @@ private void Merge(IList originals, XmlSchema schema) } } - private static string ItemName(XmlSchemaObject o) + private static string? ItemName(XmlSchemaObject o) { if (o is XmlSchemaNotation) { @@ -501,7 +503,8 @@ internal static XmlQualifiedName GetParentName(XmlSchemaObject item) return XmlQualifiedName.Empty; } - private static string GetSchemaItem(XmlSchemaObject o, string ns, string details) + [return: NotNullIfNotNull("o")] + private static string? GetSchemaItem(XmlSchemaObject? o, string? ns, string? details) { if (o == null) { @@ -523,7 +526,7 @@ private static string GetSchemaItem(XmlSchemaObject o, string ns, string details ns = ((XmlSchema)tmp).TargetNamespace; } } - string item = null; + string? item = null; if (o is XmlSchemaNotation) { item = SR.Format(SR.XmlSchemaNamedItem, ns, "notation", ((XmlSchemaNotation)o).Name, details); @@ -604,7 +607,7 @@ private static string Dump(XmlSchemaObject o) s.Serialize(xmlWriter, o, ns); return sw.ToString(); } - private static string MergeFailedMessage(XmlSchemaObject src, XmlSchemaObject dest, string ns) + private static string MergeFailedMessage(XmlSchemaObject src, XmlSchemaObject dest, string? ns) { string err = SR.Format(SR.XmlSerializableMergeItem, ns, GetSchemaItem(src, ns, null)); err += "\r\n" + Dump(src); @@ -612,9 +615,9 @@ private static string MergeFailedMessage(XmlSchemaObject src, XmlSchemaObject de return err; } - internal XmlSchemaObject Find(XmlSchemaObject o, IList originals) + internal XmlSchemaObject? Find(XmlSchemaObject o, IList originals) { - string name = ItemName(o); + string? name = ItemName(o); if (name == null) return null; @@ -638,7 +641,7 @@ public bool IsCompiled get { return _isCompiled; } } - public void Compile(ValidationEventHandler handler, bool fullCompile) + public void Compile(ValidationEventHandler? handler, bool fullCompile) { if (_isCompiled) return; @@ -706,14 +709,14 @@ public void Compile(ValidationEventHandler handler, bool fullCompile) internal static Exception CreateValidationException(XmlSchemaException exception, string message) { - XmlSchemaObject source = exception.SourceSchemaObject; + XmlSchemaObject? source = exception.SourceSchemaObject; if (exception.LineNumber == 0 && exception.LinePosition == 0) { throw new InvalidOperationException(GetSchemaItem(source, null, message), exception); } else { - string ns = null; + string? ns = null; if (source != null) { while (source.Parent != null) @@ -729,7 +732,7 @@ internal static Exception CreateValidationException(XmlSchemaException exception } } - internal static void IgnoreCompileErrors(object sender, ValidationEventArgs args) + internal static void IgnoreCompileErrors(object? sender, ValidationEventArgs args) { return; } @@ -752,7 +755,7 @@ internal static XmlSchema XmlSchema { if (s_xml == null) { - s_xml = XmlSchema.Read(new StringReader(xmlSchema), null); + s_xml = XmlSchema.Read(new StringReader(xmlSchema), null)!; } return s_xml; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationEventSource.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationEventSource.cs index 605cc23c4d1712..3e8d6f20db9e5d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationEventSource.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationEventSource.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; using System.Collections.Generic; using System.Linq; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationGeneratedCode.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationGeneratedCode.cs index 67e10d34cc1b22..cb4c44d1f5af5c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationGeneratedCode.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationGeneratedCode.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; @@ -15,7 +16,7 @@ namespace System.Xml.Serialization /// public abstract class XmlSerializationGeneratedCode { - internal void Init(TempAssembly tempAssembly) + internal void Init(TempAssembly? tempAssembly) { } @@ -31,11 +32,11 @@ internal class XmlSerializationCodeGen private readonly Hashtable _methodNames = new Hashtable(); private readonly ReflectionAwareCodeGen _raCodeGen; private readonly TypeScope[] _scopes; - private readonly TypeDesc _stringTypeDesc; - private readonly TypeDesc _qnameTypeDesc; + private readonly TypeDesc? _stringTypeDesc; + private readonly TypeDesc? _qnameTypeDesc; private readonly string _access; private readonly string _className; - private TypeMapping[] _referencedMethods; + private TypeMapping[]? _referencedMethods; private int _references; private readonly Hashtable _generatedMethods = new Hashtable(); @@ -56,8 +57,8 @@ internal XmlSerializationCodeGen(IndentedWriter writer, TypeScope[] scopes, stri internal IndentedWriter Writer { get { return _writer; } } internal int NextMethodNumber { get { return _nextMethodNumber; } set { _nextMethodNumber = value; } } internal ReflectionAwareCodeGen RaCodeGen { get { return _raCodeGen; } } - internal TypeDesc StringTypeDesc { get { return _stringTypeDesc; } } - internal TypeDesc QnameTypeDesc { get { return _qnameTypeDesc; } } + internal TypeDesc? StringTypeDesc { get { return _stringTypeDesc; } } + internal TypeDesc? QnameTypeDesc { get { return _qnameTypeDesc; } } internal string ClassName { get { return _className; } } internal string Access { get { return _access; } } internal TypeScope[] Scopes { get { return _scopes; } } @@ -70,22 +71,22 @@ internal void GenerateReferencedMethods() { while (_references > 0) { - TypeMapping mapping = _referencedMethods[--_references]; + TypeMapping mapping = _referencedMethods![--_references]; GenerateMethod(mapping); } } - internal string ReferenceMapping(TypeMapping mapping) + internal string? ReferenceMapping(TypeMapping mapping) { if (!mapping.IsSoap) { if (_generatedMethods[mapping] == null) { - _referencedMethods = EnsureArrayIndex(_referencedMethods, _references); + _referencedMethods = EnsureArrayIndex(_referencedMethods!, _references); _referencedMethods[_references++] = mapping; } } - return (string)_methodNames[mapping]; + return (string?)_methodNames[mapping]; } private TypeMapping[] EnsureArrayIndex(TypeMapping[] a, int index) @@ -97,7 +98,7 @@ private TypeMapping[] EnsureArrayIndex(TypeMapping[] a, int index) return b; } - internal void WriteQuotedCSharpString(string value) + internal void WriteQuotedCSharpString(string? value) { _raCodeGen.WriteQuotedCSharpString(value); } @@ -149,7 +150,7 @@ internal void GenerateHashtableGetEnd(string privateName) _writer.Indent--; _writer.WriteLine("}"); } - internal void GeneratePublicMethods(string privateName, string publicName, string[] methods, XmlMapping[] xmlMappings) + internal void GeneratePublicMethods(string privateName, string publicName, string?[] methods, XmlMapping[] xmlMappings) { GenerateHashtableGetBegin(privateName, publicName); if (methods != null && methods.Length != 0 && xmlMappings != null && xmlMappings.Length == methods.Length) @@ -168,7 +169,7 @@ internal void GeneratePublicMethods(string privateName, string publicName, strin GenerateHashtableGetEnd(privateName); } - internal void GenerateSupportedTypes(Type[] types) + internal void GenerateSupportedTypes(Type?[] types) { _writer.Write("public override "); _writer.Write(typeof(bool).FullName); @@ -179,7 +180,7 @@ internal void GenerateSupportedTypes(Type[] types) Hashtable uniqueTypes = new Hashtable(); for (int i = 0; i < types.Length; i++) { - Type type = types[i]; + Type? type = types[i]; if (type == null) continue; @@ -240,9 +241,9 @@ internal string GenerateBaseSerializer(string baseSerializer, string readerClass return baseSerializer; } - internal string GenerateTypedSerializer(string readMethod, string writeMethod, XmlMapping mapping, CodeIdentifiers classes, string baseSerializer, string readerClass, string writerClass) + internal string GenerateTypedSerializer(string? readMethod, string? writeMethod, XmlMapping mapping, CodeIdentifiers classes, string baseSerializer, string readerClass, string writerClass) { - string serializerName = CodeIdentifier.MakeValid(Accessor.UnescapeName(mapping.Accessor.Mapping.TypeDesc.Name)); + string serializerName = CodeIdentifier.MakeValid(Accessor.UnescapeName(mapping.Accessor.Mapping!.TypeDesc!.Name)); serializerName = classes.AddUnique(serializerName + "Serializer", mapping); _writer.WriteLine(); @@ -327,7 +328,7 @@ private void GenerateTypedSerializers(Hashtable serializers) _writer.Write("_tmp.Add("); WriteQuotedCSharpString(key); _writer.Write(", new "); - _writer.Write((string)serializers[key]); + _writer.Write((string?)serializers[key]); _writer.WriteLine("());"); } GenerateHashtableGetEnd("typedSerializers"); @@ -347,7 +348,7 @@ private void GenerateGetSerializer(Hashtable serializers, XmlMapping[] xmlMappin { if (xmlMappings[i] is XmlTypeMapping) { - Type type = xmlMappings[i].Accessor.Mapping.TypeDesc.Type; + Type? type = xmlMappings[i].Accessor.Mapping!.TypeDesc!.Type; if (type == null) continue; if (!type.IsPublic && !type.IsNestedPublic) @@ -359,7 +360,7 @@ private void GenerateGetSerializer(Hashtable serializers, XmlMapping[] xmlMappin _writer.Write("if (type == typeof("); _writer.Write(CodeIdentifier.GetCSharpName(type)); _writer.Write(")) return new "); - _writer.Write((string)serializers[xmlMappings[i].Key]); + _writer.Write((string)serializers[xmlMappings[i].Key!]!); _writer.WriteLine("();"); } } @@ -368,7 +369,7 @@ private void GenerateGetSerializer(Hashtable serializers, XmlMapping[] xmlMappin _writer.WriteLine("}"); } - internal void GenerateSerializerContract(string className, XmlMapping[] xmlMappings, Type[] types, string readerType, string[] readMethods, string writerType, string[] writerMethods, Hashtable serializers) + internal void GenerateSerializerContract(string className, XmlMapping[] xmlMappings, Type?[] types, string readerType, string?[] readMethods, string writerType, string?[] writerMethods, Hashtable serializers) { _writer.WriteLine(); _writer.Write("public class XmlSerializerContract : global::"); @@ -402,7 +403,7 @@ internal static bool IsWildcard(SpecialMapping mapping) { if (mapping is SerializableMapping) return ((SerializableMapping)mapping).IsAny; - return mapping.TypeDesc.CanBeElementValue; + return mapping.TypeDesc!.CanBeElementValue; } } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationILGen.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationILGen.cs index a014179f33b98c..fe017660a9a700 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationILGen.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationILGen.cs @@ -1,11 +1,13 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; using System.Collections; using System.Collections.Generic; + using System.Diagnostics.CodeAnalysis; using System.Reflection; using System.Reflection.Emit; using System.Text.RegularExpressions; @@ -23,16 +25,16 @@ internal class XmlSerializationILGen internal Dictionary memberInfos = new Dictionary(); private readonly ReflectionAwareILGen _raCodeGen; private readonly TypeScope[] _scopes; - private readonly TypeDesc _stringTypeDesc; - private readonly TypeDesc _qnameTypeDesc; + private readonly TypeDesc? _stringTypeDesc; + private readonly TypeDesc? _qnameTypeDesc; private readonly string _className; - private TypeMapping[] _referencedMethods; + private TypeMapping[]? _referencedMethods; private int _references; private readonly HashSet _generatedMethods = new HashSet(); - private ModuleBuilder _moduleBuilder; + private ModuleBuilder? _moduleBuilder; private readonly TypeAttributes _typeAttributes; - protected TypeBuilder typeBuilder; - protected CodeGenerator ilg; + protected TypeBuilder typeBuilder = null!; + protected CodeGenerator ilg = null!; internal XmlSerializationILGen(TypeScope[] scopes, string access, string className) { @@ -50,8 +52,8 @@ internal XmlSerializationILGen(TypeScope[] scopes, string access, string classNa internal int NextMethodNumber { get { return _nextMethodNumber; } set { _nextMethodNumber = value; } } internal ReflectionAwareILGen RaCodeGen { get { return _raCodeGen; } } - internal TypeDesc StringTypeDesc { get { return _stringTypeDesc; } } - internal TypeDesc QnameTypeDesc { get { return _qnameTypeDesc; } } + internal TypeDesc? StringTypeDesc { get { return _stringTypeDesc; } } + internal TypeDesc? QnameTypeDesc { get { return _qnameTypeDesc; } } internal string ClassName { get { return _className; } } internal TypeScope[] Scopes { get { return _scopes; } } internal Dictionary MethodNames { get { return _methodNames; } } @@ -67,7 +69,7 @@ internal ModuleBuilder ModuleBuilder private static readonly Dictionary s_regexs = new Dictionary(); internal static Regex NewRegex(string pattern) { - Regex regex; + Regex? regex; lock (s_regexs) { if (!s_regexs.TryGetValue(pattern, out regex)) @@ -80,9 +82,9 @@ internal static Regex NewRegex(string pattern) } internal MethodBuilder EnsureMethodBuilder(TypeBuilder typeBuilder, string methodName, - MethodAttributes attributes, Type returnType, Type[] parameterTypes) + MethodAttributes attributes, Type? returnType, Type[] parameterTypes) { - MethodBuilderInfo methodBuilderInfo; + MethodBuilderInfo? methodBuilderInfo; if (!_methodBuilders.TryGetValue(methodName, out methodBuilderInfo)) { MethodBuilder methodBuilder = typeBuilder.DefineMethod( @@ -113,24 +115,25 @@ internal void GenerateReferencedMethods() { while (_references > 0) { - TypeMapping mapping = _referencedMethods[--_references]; + TypeMapping mapping = _referencedMethods![--_references]; GenerateMethod(mapping); } } - internal string ReferenceMapping(TypeMapping mapping) + internal string? ReferenceMapping(TypeMapping mapping) { if (!_generatedMethods.Contains(mapping)) { _referencedMethods = EnsureArrayIndex(_referencedMethods, _references); _referencedMethods[_references++] = mapping; } - string methodName; + + string? methodName; _methodNames.TryGetValue(mapping, out methodName); return methodName; } - private TypeMapping[] EnsureArrayIndex(TypeMapping[] a, int index) + private TypeMapping[] EnsureArrayIndex(TypeMapping[]? a, int index) { if (a == null) return new TypeMapping[32]; if (index < a.Length) return a; @@ -139,7 +142,8 @@ private TypeMapping[] EnsureArrayIndex(TypeMapping[] a, int index) return b; } - internal string GetCSharpString(string value) + [return: NotNullIfNotNull("value")] + internal string? GetCSharpString(string? value) { return ReflectionAwareILGen.GetCSharpString(value); } @@ -165,7 +169,7 @@ internal FieldBuilder GenerateHashtableGetBegin(string privateName, string publi Array.Empty(), Array.Empty(), CodeGenerator.PublicOverrideMethodAttributes | MethodAttributes.SpecialName); - propertyBuilder.SetGetMethod(ilg.MethodBuilder); + propertyBuilder.SetGetMethod(ilg.MethodBuilder!); ilg.Ldarg(0); ilg.LoadMember(fieldBuilder); @@ -176,7 +180,7 @@ internal FieldBuilder GenerateHashtableGetBegin(string privateName, string publi ConstructorInfo Hashtable_ctor = typeof(Hashtable).GetConstructor( CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; LocalBuilder _tmpLoc = ilg.DeclareLocal(typeof(Hashtable), "_tmp"); ilg.New(Hashtable_ctor); ilg.Stloc(_tmpLoc); @@ -186,7 +190,7 @@ internal FieldBuilder GenerateHashtableGetBegin(string privateName, string publi internal void GenerateHashtableGetEnd(FieldBuilder fieldBuilder) { - ilg.Ldarg(0); + ilg!.Ldarg(0); ilg.LoadMember(fieldBuilder); ilg.Load(null); ilg.If(Cmp.EqualTo); @@ -213,12 +217,12 @@ internal FieldBuilder GeneratePublicMethods(string privateName, string publicNam MethodInfo Hashtable_set_Item = typeof(Hashtable).GetMethod( "set_Item", new Type[] { typeof(object), typeof(object) } - ); + )!; for (int i = 0; i < methods.Length; i++) { if (methods[i] == null) continue; - ilg.Ldloc(typeof(Hashtable), "_tmp"); + ilg!.Ldloc(typeof(Hashtable), "_tmp"); ilg.Ldstr(GetCSharpString(xmlMappings[i].Key)); ilg.Ldstr(GetCSharpString(methods[i])); ilg.Call(Hashtable_set_Item); @@ -271,7 +275,7 @@ internal string GenerateBaseSerializer(string baseSerializer, string readerClass baseSerializer = classes.AddUnique(baseSerializer, baseSerializer); TypeBuilder baseSerializerTypeBuilder = CodeGenerator.CreateTypeBuilder( - _moduleBuilder, + _moduleBuilder!, CodeIdentifier.GetCSharpName(baseSerializer), TypeAttributes.Public | TypeAttributes.Abstract | TypeAttributes.BeforeFieldInit, typeof(XmlSerializer), @@ -280,7 +284,7 @@ internal string GenerateBaseSerializer(string baseSerializer, string readerClass ConstructorInfo readerCtor = CreatedTypes[readerClass].GetConstructor( CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg = new CodeGenerator(baseSerializerTypeBuilder); ilg.BeginMethod(typeof(XmlSerializationReader), "CreateReader", @@ -293,7 +297,7 @@ internal string GenerateBaseSerializer(string baseSerializer, string readerClass ConstructorInfo writerCtor = CreatedTypes[writerClass].GetConstructor( CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.BeginMethod(typeof(XmlSerializationWriter), "CreateWriter", Array.Empty(), @@ -304,7 +308,7 @@ internal string GenerateBaseSerializer(string baseSerializer, string readerClass baseSerializerTypeBuilder.DefineDefaultConstructor( MethodAttributes.Family | MethodAttributes.HideBySig | MethodAttributes.SpecialName | MethodAttributes.RTSpecialName); - Type baseSerializerType = baseSerializerTypeBuilder.CreateTypeInfo().AsType(); + Type baseSerializerType = baseSerializerTypeBuilder.CreateTypeInfo()!.AsType(); CreatedTypes.Add(baseSerializerType.Name, baseSerializerType); return baseSerializer; @@ -312,11 +316,11 @@ internal string GenerateBaseSerializer(string baseSerializer, string readerClass internal string GenerateTypedSerializer(string readMethod, string writeMethod, XmlMapping mapping, CodeIdentifiers classes, string baseSerializer, string readerClass, string writerClass) { - string serializerName = CodeIdentifier.MakeValid(Accessor.UnescapeName(mapping.Accessor.Mapping.TypeDesc.Name)); + string serializerName = CodeIdentifier.MakeValid(Accessor.UnescapeName(mapping.Accessor.Mapping!.TypeDesc!.Name)); serializerName = classes.AddUnique(serializerName + "Serializer", mapping); TypeBuilder typedSerializerTypeBuilder = CodeGenerator.CreateTypeBuilder( - _moduleBuilder, + _moduleBuilder!, CodeIdentifier.GetCSharpName(serializerName), TypeAttributes.Public | TypeAttributes.Sealed | TypeAttributes.BeforeFieldInit, CreatedTypes[baseSerializer], @@ -344,7 +348,7 @@ internal string GenerateTypedSerializer(string readMethod, string writeMethod, X "IsStartElement", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string) } - ); + )!; ilg.Ldarg(ilg.GetArg("xmlReader")); ilg.Ldstr(GetCSharpString(mapping.Accessor.Name)); ilg.Ldstr(GetCSharpString(mapping.Accessor.Namespace)); @@ -369,7 +373,7 @@ internal string GenerateTypedSerializer(string readMethod, string writeMethod, X writeMethod, CodeGenerator.InstanceBindingFlags, new Type[] { (mapping is XmlMembersMapping) ? typeof(object[]) : typeof(object) } - ); + )!; ilg.Ldarg("writer"); ilg.Castclass(CreatedTypes[writerClass]); ilg.Ldarg("objectToSerialize"); @@ -393,14 +397,14 @@ internal string GenerateTypedSerializer(string readMethod, string writeMethod, X readMethod, CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg("reader"); ilg.Castclass(CreatedTypes[readerClass]); ilg.Call(readerType_readMethod); ilg.EndMethod(); } typedSerializerTypeBuilder.DefineDefaultConstructor(CodeGenerator.PublicMethodAttributes); - Type typedSerializerType = typedSerializerTypeBuilder.CreateTypeInfo().AsType(); + Type typedSerializerType = typedSerializerTypeBuilder.CreateTypeInfo()!.AsType(); CreatedTypes.Add(typedSerializerType.Name, typedSerializerType); return typedSerializerType.Name; @@ -414,15 +418,15 @@ private FieldBuilder GenerateTypedSerializers(Dictionary seriali "Add", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(object), typeof(object) } - ); + )!; foreach (string key in serializers.Keys) { ConstructorInfo ctor = CreatedTypes[(string)serializers[key]].GetConstructor( CodeGenerator.InstanceBindingFlags, Array.Empty() - ); - ilg.Ldloc(typeof(Hashtable), "_tmp"); + )!; + ilg!.Ldloc(typeof(Hashtable), "_tmp"); ilg.Ldstr(GetCSharpString(key)); ilg.New(ctor); ilg.Call(Hashtable_Add); @@ -446,7 +450,7 @@ private void GenerateGetSerializer(Dictionary serializers, XmlMa { if (xmlMappings[i] is XmlTypeMapping) { - Type type = xmlMappings[i].Accessor.Mapping.TypeDesc.Type; + Type? type = xmlMappings[i].Accessor.Mapping!.TypeDesc!.Type; if (type == null) continue; if (!type.IsPublic && !type.IsNestedPublic) @@ -458,10 +462,10 @@ private void GenerateGetSerializer(Dictionary serializers, XmlMa ilg.Ldc(type); ilg.If(Cmp.EqualTo); { - ConstructorInfo ctor = CreatedTypes[(string)serializers[xmlMappings[i].Key]].GetConstructor( + ConstructorInfo ctor = CreatedTypes[(string)serializers[xmlMappings[i].Key!]].GetConstructor( CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.New(ctor); ilg.Stloc(ilg.ReturnLocal); ilg.Br(ilg.ReturnLabel); @@ -480,7 +484,7 @@ private void GenerateGetSerializer(Dictionary serializers, XmlMa internal void GenerateSerializerContract(string className, XmlMapping[] xmlMappings, Type[] types, string readerType, string[] readMethods, string writerType, string[] writerMethods, Dictionary serializers) { TypeBuilder serializerContractTypeBuilder = CodeGenerator.CreateTypeBuilder( - _moduleBuilder, + _moduleBuilder!, "XmlSerializerContract", TypeAttributes.Public | TypeAttributes.BeforeFieldInit, typeof(XmlSerializerImplementation), @@ -499,11 +503,11 @@ internal void GenerateSerializerContract(string className, XmlMapping[] xmlMappi Array.Empty(), Array.Empty(), CodeGenerator.PublicOverrideMethodAttributes | MethodAttributes.SpecialName); - propertyBuilder.SetGetMethod(ilg.MethodBuilder); + propertyBuilder.SetGetMethod(ilg.MethodBuilder!); ConstructorInfo ctor = CreatedTypes[readerType].GetConstructor( CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.New(ctor); ilg.EndMethod(); @@ -519,11 +523,11 @@ internal void GenerateSerializerContract(string className, XmlMapping[] xmlMappi Array.Empty(), Array.Empty(), CodeGenerator.PublicOverrideMethodAttributes | MethodAttributes.SpecialName); - propertyBuilder.SetGetMethod(ilg.MethodBuilder); + propertyBuilder.SetGetMethod(ilg.MethodBuilder!); ctor = CreatedTypes[writerType].GetConstructor( CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.New(ctor); ilg.EndMethod(); @@ -537,7 +541,7 @@ internal void GenerateSerializerContract(string className, XmlMapping[] xmlMappi ConstructorInfo baseCtor = typeof(XmlSerializerImplementation).GetConstructor( CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg = new CodeGenerator(serializerContractTypeBuilder); ilg.BeginMethod( typeof(void), @@ -559,7 +563,7 @@ internal void GenerateSerializerContract(string className, XmlMapping[] xmlMappi ilg.Call(baseCtor); ilg.EndMethod(); // Instantiate type - Type serializerContractType = serializerContractTypeBuilder.CreateTypeInfo().AsType(); + Type serializerContractType = serializerContractTypeBuilder.CreateTypeInfo()!.AsType(); CreatedTypes.Add(serializerContractType.Name, serializerContractType); } @@ -567,19 +571,19 @@ internal static bool IsWildcard(SpecialMapping mapping) { if (mapping is SerializableMapping) return ((SerializableMapping)mapping).IsAny; - return mapping.TypeDesc.CanBeElementValue; + return mapping.TypeDesc!.CanBeElementValue; } internal void ILGenLoad(string source) { ILGenLoad(source, null); } - internal void ILGenLoad(string source, Type type) + internal void ILGenLoad(string source, Type? type) { if (source.StartsWith("o.@", StringComparison.Ordinal)) { System.Diagnostics.Debug.Assert(memberInfos.ContainsKey(source.Substring(3))); MemberInfo memInfo = memberInfos[source.Substring(3)]; - ilg.LoadMember(ilg.GetVariable("o"), memInfo); + ilg!.LoadMember(ilg.GetVariable("o"), memInfo); if (type != null) { Type memType = (memInfo is FieldInfo) ? ((FieldInfo)memInfo).FieldType : ((PropertyInfo)memInfo).PropertyType; @@ -588,7 +592,7 @@ internal void ILGenLoad(string source, Type type) } else { - SourceInfo info = new SourceInfo(source, null, null, null, ilg); + SourceInfo info = new SourceInfo(source, null, null, null, ilg!); info.Load(type); } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs index 4ecd35f0670c2a..63ad40f71fce5c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs @@ -1,10 +1,13 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; using System.Collections; + using System.Diagnostics; + using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Reflection; @@ -15,98 +18,98 @@ namespace System.Xml.Serialization /// public abstract class XmlSerializationReader : XmlSerializationGeneratedCode { - private XmlReader _r; - private XmlDocument _d; - private Hashtable _callbacks; - private Hashtable _types; - private Hashtable _typesReverse; + private XmlReader _r = null!; + private XmlDocument? _d; + private Hashtable _callbacks = null!; + private Hashtable _types = null!; + private Hashtable _typesReverse = null!; private XmlDeserializationEvents _events; - private Hashtable _targets; - private Hashtable _referencedTargets; - private ArrayList _targetsWithoutIds; - private ArrayList _fixups; - private ArrayList _collectionFixups; + private Hashtable? _targets; + private Hashtable? _referencedTargets; + private ArrayList? _targetsWithoutIds; + private ArrayList? _fixups; + private ArrayList? _collectionFixups; private bool _soap12; private bool _isReturnValue; private bool _decodeName = true; - private string _schemaNsID; - private string _schemaNs1999ID; - private string _schemaNs2000ID; - private string _schemaNonXsdTypesNsID; - private string _instanceNsID; - private string _instanceNs2000ID; - private string _instanceNs1999ID; - private string _soapNsID; - private string _soap12NsID; - private string _schemaID; - private string _wsdlNsID; - private string _wsdlArrayTypeID; - private string _nullID; - private string _nilID; - private string _typeID; - private string _arrayTypeID; - private string _itemTypeID; - private string _arraySizeID; - private string _arrayID; - private string _urTypeID; - private string _stringID; - private string _intID; - private string _booleanID; - private string _shortID; - private string _longID; - private string _floatID; - private string _doubleID; - private string _decimalID; - private string _dateTimeID; - private string _qnameID; - private string _dateID; - private string _timeID; - private string _hexBinaryID; - private string _base64BinaryID; - private string _base64ID; - private string _unsignedByteID; - private string _byteID; - private string _unsignedShortID; - private string _unsignedIntID; - private string _unsignedLongID; - private string _oldDecimalID; - private string _oldTimeInstantID; - - private string _anyURIID; - private string _durationID; - private string _ENTITYID; - private string _ENTITIESID; - private string _gDayID; - private string _gMonthID; - private string _gMonthDayID; - private string _gYearID; - private string _gYearMonthID; - private string _IDID; - private string _IDREFID; - private string _IDREFSID; - private string _integerID; - private string _languageID; - private string _nameID; - private string _NCNameID; - private string _NMTOKENID; - private string _NMTOKENSID; - private string _negativeIntegerID; - private string _nonPositiveIntegerID; - private string _nonNegativeIntegerID; - private string _normalizedStringID; - private string _NOTATIONID; - private string _positiveIntegerID; - private string _tokenID; - - private string _charID; - private string _guidID; - private string _timeSpanID; + private string _schemaNsID = null!; + private string _schemaNs1999ID = null!; + private string _schemaNs2000ID = null!; + private string _schemaNonXsdTypesNsID = null!; + private string _instanceNsID = null!; + private string _instanceNs2000ID = null!; + private string _instanceNs1999ID = null!; + private string _soapNsID = null!; + private string _soap12NsID = null!; + private string _schemaID = null!; + private string _wsdlNsID = null!; + private string _wsdlArrayTypeID = null!; + private string _nullID = null!; + private string _nilID = null!; + private string _typeID = null!; + private string _arrayTypeID = null!; + private string _itemTypeID = null!; + private string _arraySizeID = null!; + private string _arrayID = null!; + private string _urTypeID = null!; + private string _stringID = null!; + private string _intID = null!; + private string _booleanID = null!; + private string _shortID = null!; + private string _longID = null!; + private string _floatID = null!; + private string _doubleID = null!; + private string _decimalID = null!; + private string _dateTimeID = null!; + private string _qnameID = null!; + private string _dateID = null!; + private string _timeID = null!; + private string _hexBinaryID = null!; + private string _base64BinaryID = null!; + private string _base64ID = null!; + private string _unsignedByteID = null!; + private string _byteID = null!; + private string _unsignedShortID = null!; + private string _unsignedIntID = null!; + private string _unsignedLongID = null!; + private string _oldDecimalID = null!; + private string _oldTimeInstantID = null!; + + private string _anyURIID = null!; + private string _durationID = null!; + private string _ENTITYID = null!; + private string _ENTITIESID = null!; + private string _gDayID = null!; + private string _gMonthID = null!; + private string _gMonthDayID = null!; + private string _gYearID = null!; + private string _gYearMonthID = null!; + private string _IDID = null!; + private string _IDREFID = null!; + private string _IDREFSID = null!; + private string _integerID = null!; + private string _languageID = null!; + private string _nameID = null!; + private string _NCNameID = null!; + private string _NMTOKENID = null!; + private string _NMTOKENSID = null!; + private string _negativeIntegerID = null!; + private string _nonPositiveIntegerID = null!; + private string _nonNegativeIntegerID = null!; + private string _normalizedStringID = null!; + private string _NOTATIONID = null!; + private string _positiveIntegerID = null!; + private string _tokenID = null!; + + private string _charID = null!; + private string _guidID = null!; + private string _timeSpanID = null!; protected abstract void InitIDs(); // this method must be called before any generated deserialization methods are called - internal void Init(XmlReader r, XmlDeserializationEvents events, string encodingStyle, TempAssembly tempAssembly) + internal void Init(XmlReader r, XmlDeserializationEvents events, string? encodingStyle, TempAssembly? tempAssembly) { _events = events; _r = r; @@ -169,14 +172,14 @@ protected XmlDocument Document if (_d == null) { _d = new XmlDocument(_r.NameTable); - _d.SetBaseURI(_r.BaseURI); + _d.SetBaseURI(_r.BaseURI!); // TODO-NULLABLE: string.Empty should be passed in case of null URI } return _d; } } /// - protected static Assembly ResolveDynamicAssembly(string assemblyFullName) + protected static Assembly? ResolveDynamicAssembly(string assemblyFullName) { return DynamicAssemblies.Get(assemblyFullName); } @@ -243,9 +246,9 @@ private void InitPrimitiveIDs() /// /// [To be supplied.] /// - protected XmlQualifiedName GetXsiType() + protected XmlQualifiedName? GetXsiType() { - string type = _r.GetAttribute(_typeID, _instanceNsID); + string? type = _r.GetAttribute(_typeID, _instanceNsID); if (type == null) { type = _r.GetAttribute(_typeID, _instanceNs2000ID); @@ -262,7 +265,7 @@ protected XmlQualifiedName GetXsiType() // throwOnUnknown flag controls whether this method throws an exception or just returns // null if typeName.Namespace is unknown. the method still throws if typeName.Namespace // is recognized but typeName.Name isn't. - private Type GetPrimitiveType(XmlQualifiedName typeName, bool throwOnUnknown) + private Type? GetPrimitiveType(XmlQualifiedName typeName, bool throwOnUnknown) { InitPrimitiveIDs(); @@ -507,15 +510,15 @@ private byte[] ReadByteArray(bool isBase64) return result; } - protected object ReadTypedPrimitive(XmlQualifiedName type) + protected object? ReadTypedPrimitive(XmlQualifiedName type) { return ReadTypedPrimitive(type, false); } - private object ReadTypedPrimitive(XmlQualifiedName type, bool elementCanBeType) + private object? ReadTypedPrimitive(XmlQualifiedName type, bool elementCanBeType) { InitPrimitiveIDs(); - object value = null; + object? value = null; if (!IsPrimitiveNamespace(type.Namespace) || (object)type.Name == (object)_urTypeID) return ReadXmlNodes(elementCanBeType); @@ -672,10 +675,10 @@ private object ReadTypedPrimitive(XmlQualifiedName type, bool elementCanBeType) return value; } - protected object ReadTypedNull(XmlQualifiedName type) + protected object? ReadTypedNull(XmlQualifiedName type) { InitPrimitiveIDs(); - object value = null; + object? value = null; if (!IsPrimitiveNamespace(type.Namespace) || (object)type.Name == (object)_urTypeID) { return null; @@ -820,7 +823,7 @@ protected bool ReadNull() protected bool GetNullAttr() { - string isNull = _r.GetAttribute(_nilID, _instanceNsID); + string? isNull = _r.GetAttribute(_nilID, _instanceNsID); if (isNull == null) isNull = _r.GetAttribute(_nullID, _instanceNsID); if (isNull == null) @@ -833,7 +836,7 @@ protected bool GetNullAttr() return true; } - protected string ReadNullableString() + protected string? ReadNullableString() { if (ReadNull()) return null; return _r.ReadElementString(); @@ -842,7 +845,7 @@ protected string ReadNullableString() /// /// [To be supplied.] /// - protected XmlQualifiedName ReadNullableQualifiedName() + protected XmlQualifiedName? ReadNullableQualifiedName() { if (ReadNull()) return null; return ReadElementQualifiedName(); @@ -864,9 +867,9 @@ protected XmlQualifiedName ReadElementQualifiedName() return qname; } - protected XmlDocument ReadXmlDocument(bool wrapped) + protected XmlDocument? ReadXmlDocument(bool wrapped) { - XmlNode n = ReadXmlNode(wrapped); + XmlNode? n = ReadXmlNode(wrapped); if (n == null) return null; XmlDocument doc = new XmlDocument(); @@ -874,16 +877,17 @@ protected XmlDocument ReadXmlDocument(bool wrapped) return doc; } - protected string CollapseWhitespace(string value) + [return: NotNullIfNotNull("value")] + protected string? CollapseWhitespace(string? value) { if (value == null) return null; return value.Trim(); } - protected XmlNode ReadXmlNode(bool wrapped) + protected XmlNode? ReadXmlNode(bool wrapped) { - XmlNode node = null; + XmlNode? node = null; if (wrapped) { if (ReadNull()) return null; @@ -909,7 +913,7 @@ protected static byte[] ToByteArrayBase64(string value) return XmlCustomFormatter.ToByteArrayBase64(value); } - protected byte[] ToByteArrayBase64(bool isNull) + protected byte[]? ToByteArrayBase64(bool isNull) { if (isNull) { @@ -918,12 +922,13 @@ protected byte[] ToByteArrayBase64(bool isNull) return ReadByteArray(true); //means use Base64 } - protected static byte[] ToByteArrayHex(string value) + [return: NotNullIfNotNull("value")] + protected static byte[]? ToByteArrayHex(string? value) { return XmlCustomFormatter.ToByteArrayHex(value); } - protected byte[] ToByteArrayHex(bool isNull) + protected byte[]? ToByteArrayHex(bool isNull) { if (isNull) { @@ -935,7 +940,7 @@ protected byte[] ToByteArrayHex(bool isNull) protected int GetArrayLength(string name, string ns) { if (GetNullAttr()) return 0; - string arrayType = _r.GetAttribute(_arrayTypeID, _soapNsID); + string? arrayType = _r.GetAttribute(_arrayTypeID, _soapNsID); SoapArrayInfo arrayInfo = ParseArrayType(arrayType); if (arrayInfo.dimensions != 1) throw new InvalidOperationException(SR.Format(SR.XmlInvalidArrayDimentions, CurrentTag())); XmlQualifiedName qname = ToXmlQualifiedName(arrayInfo.qname, false); @@ -952,7 +957,7 @@ private struct SoapArrayInfo public int jaggedDimensions; } - private SoapArrayInfo ParseArrayType(string value) + private SoapArrayInfo ParseArrayType(string? value) { if (value == null) { @@ -1036,7 +1041,7 @@ private SoapArrayInfo ParseArrayType(string value) return soapArrayInfo; } - private SoapArrayInfo ParseSoap12ArrayType(string itemType, string arraySize) + private SoapArrayInfo ParseSoap12ArrayType(string? itemType, string? arraySize) { SoapArrayInfo soapArrayInfo = default; @@ -1135,11 +1140,11 @@ protected XmlQualifiedName ToXmlQualifiedName(string value) return ToXmlQualifiedName(value, DecodeName); } - internal XmlQualifiedName ToXmlQualifiedName(string value, bool decodeName) + internal XmlQualifiedName ToXmlQualifiedName(string? value, bool decodeName) { int colon = value == null ? -1 : value.LastIndexOf(':'); - string prefix = colon < 0 ? null : value.Substring(0, colon); - string localName = value.Substring(colon + 1); + string? prefix = colon < 0 ? null : value!.Substring(0, colon); + string localName = value!.Substring(colon + 1); if (decodeName) { @@ -1152,7 +1157,7 @@ internal XmlQualifiedName ToXmlQualifiedName(string value, bool decodeName) } else { - string ns = _r.LookupNamespace(prefix); + string? ns = _r.LookupNamespace(prefix); if (ns == null) { // Namespace prefix '{0}' is not defined. @@ -1166,7 +1171,7 @@ protected void UnknownAttribute(object o, XmlAttribute attr) UnknownAttribute(o, attr, null); } - protected void UnknownAttribute(object o, XmlAttribute attr, string qnames) + protected void UnknownAttribute(object? o, XmlAttribute attr, string? qnames) { if (_events.OnUnknownAttribute != null) { @@ -1177,12 +1182,12 @@ protected void UnknownAttribute(object o, XmlAttribute attr, string qnames) } } - protected void UnknownElement(object o, XmlElement elem) + protected void UnknownElement(object? o, XmlElement elem) { UnknownElement(o, elem, null); } - protected void UnknownElement(object o, XmlElement elem, string qnames) + protected void UnknownElement(object? o, XmlElement elem, string? qnames) { if (_events.OnUnknownElement != null) { @@ -1193,12 +1198,12 @@ protected void UnknownElement(object o, XmlElement elem, string qnames) } } - protected void UnknownNode(object o) + protected void UnknownNode(object? o) { UnknownNode(o, null); } - protected void UnknownNode(object o, string qnames) + protected void UnknownNode(object? o, string? qnames) { if (_r.NodeType == XmlNodeType.None || _r.NodeType == XmlNodeType.Whitespace) { @@ -1226,7 +1231,7 @@ protected void UnknownNode(object o, string qnames) } } - private void UnknownNode(XmlNode unknownNode, object o, string qnames) + private void UnknownNode(XmlNode? unknownNode, object? o, string? qnames) { if (unknownNode == null) return; @@ -1259,7 +1264,7 @@ private void GetCurrentPosition(out int lineNumber, out int linePosition) lineNumber = linePosition = -1; } - protected void UnreferencedObject(string id, object o) + protected void UnreferencedObject(string? id, object o) { if (_events.OnUnreferencedObject != null) { @@ -1285,22 +1290,22 @@ protected Exception CreateUnknownTypeException(XmlQualifiedName type) return new InvalidOperationException(SR.Format(SR.XmlUnknownType, type.Name, type.Namespace, CurrentTag())); } - protected Exception CreateReadOnlyCollectionException(string name) + protected Exception CreateReadOnlyCollectionException(string? name) { return new InvalidOperationException(SR.Format(SR.XmlReadOnlyCollection, name)); } - protected Exception CreateAbstractTypeException(string name, string ns) + protected Exception CreateAbstractTypeException(string? name, string? ns) { return new InvalidOperationException(SR.Format(SR.XmlAbstractType, name, ns, CurrentTag())); } - protected Exception CreateInaccessibleConstructorException(string typeName) + protected Exception CreateInaccessibleConstructorException(string? typeName) { return new InvalidOperationException(SR.Format(SR.XmlConstructorInaccessible, typeName)); } - protected Exception CreateCtorHasSecurityException(string typeName) + protected Exception CreateCtorHasSecurityException(string? typeName) { return new InvalidOperationException(SR.Format(SR.XmlConstructorHasSecurityAttributes, typeName)); } @@ -1310,17 +1315,17 @@ protected Exception CreateUnknownNodeException() return new InvalidOperationException(SR.Format(SR.XmlUnknownNode, CurrentTag())); } - protected Exception CreateUnknownConstantException(string value, Type enumType) + protected Exception CreateUnknownConstantException(string? value, Type enumType) { return new InvalidOperationException(SR.Format(SR.XmlUnknownConstant, value, enumType.Name)); } - protected Exception CreateInvalidCastException(Type type, object value) + protected Exception CreateInvalidCastException(Type type, object? value) { return CreateInvalidCastException(type, value, null); } - protected Exception CreateInvalidCastException(Type type, object value, string id) + protected Exception CreateInvalidCastException(Type type, object? value, string? id) { if (value == null) return new InvalidCastException(SR.Format(SR.XmlInvalidNullCast, type.FullName)); @@ -1330,18 +1335,18 @@ protected Exception CreateInvalidCastException(Type type, object value, string i return new InvalidCastException(SR.Format(SR.XmlInvalidCastWithId, value.GetType().FullName, type.FullName, id)); } - protected Exception CreateBadDerivationException(string xsdDerived, string nsDerived, string xsdBase, string nsBase, string clrDerived, string clrBase) + protected Exception CreateBadDerivationException(string? xsdDerived, string? nsDerived, string? xsdBase, string? nsBase, string? clrDerived, string? clrBase) { return new InvalidOperationException(SR.Format(SR.XmlSerializableBadDerivation, xsdDerived, nsDerived, xsdBase, nsBase, clrDerived, clrBase)); } - protected Exception CreateMissingIXmlSerializableType(string name, string ns, string clrType) + protected Exception CreateMissingIXmlSerializableType(string? name, string? ns, string? clrType) { return new InvalidOperationException(SR.Format(SR.XmlSerializableMissingClrType, name, ns, typeof(XmlIncludeAttribute).Name, clrType)); //XmlSerializableMissingClrType= Type '{0}' from namespace '{1}' doesnot have corresponding IXmlSerializable type. Please consider adding {2} to '{3}'. } - protected Array EnsureArrayIndex(Array a, int index, Type elementType) + protected Array EnsureArrayIndex(Array? a, int index, Type elementType) { if (a == null) return Array.CreateInstance(elementType, 32); if (index < a.Length) return a; @@ -1350,7 +1355,7 @@ protected Array EnsureArrayIndex(Array a, int index, Type elementType) return b; } - protected Array ShrinkArray(Array a, int length, Type elementType, bool isNullable) + protected Array? ShrinkArray(Array? a, int length, Type elementType, bool isNullable) { if (a == null) { @@ -1363,12 +1368,14 @@ protected Array ShrinkArray(Array a, int length, Type elementType, bool isNullab return b; } - protected string ReadString(string value) + [return: NotNullIfNotNull("value")] + protected string? ReadString(string? value) { return ReadString(value, false); } - protected string ReadString(string value, bool trim) + [return: NotNullIfNotNull("value")] + protected string? ReadString(string? value, bool trim) { string str = _r.ReadString(); if (str != null && trim) @@ -1385,8 +1392,8 @@ protected IXmlSerializable ReadSerializable(IXmlSerializable serializable) protected IXmlSerializable ReadSerializable(IXmlSerializable serializable, bool wrappedAny) { - string name = null; - string ns = null; + string? name = null; + string? ns = null; if (wrappedAny) { @@ -1409,9 +1416,9 @@ protected IXmlSerializable ReadSerializable(IXmlSerializable serializable, bool return serializable; } - protected bool ReadReference(out string fixupReference) + protected bool ReadReference([NotNullWhen(true)] out string? fixupReference) { - string href = _soap12 ? _r.GetAttribute("ref", Soap12.Encoding) : _r.GetAttribute("href"); + string? href = _soap12 ? _r.GetAttribute("ref", Soap12.Encoding) : _r.GetAttribute("href"); if (href == null) { fixupReference = null; @@ -1438,7 +1445,7 @@ protected bool ReadReference(out string fixupReference) return true; } - protected void AddTarget(string id, object o) + protected void AddTarget(string? id, object? o) { if (id == null) { @@ -1471,7 +1478,7 @@ protected void AddFixup(CollectionFixup fixup) protected object GetTarget(string id) { - object target = _targets != null ? _targets[id] : null; + object? target = _targets != null ? _targets[id] : null; if (target == null) { throw new InvalidOperationException(SR.Format(SR.XmlInvalidHref, id)); @@ -1480,7 +1487,7 @@ protected object GetTarget(string id) return target; } - protected void Referenced(object o) + protected void Referenced(object? o) { if (o == null) return; if (_referencedTargets == null) _referencedTargets = new Hashtable(); @@ -1493,9 +1500,9 @@ private void HandleUnreferencedObjects() { foreach (DictionaryEntry target in _targets) { - if (_referencedTargets == null || !_referencedTargets.Contains(target.Value)) + if (_referencedTargets == null || !_referencedTargets.Contains(target.Value!)) { - UnreferencedObject((string)target.Key, target.Value); + UnreferencedObject((string)target.Key, target.Value!); } } } @@ -1516,25 +1523,25 @@ private void DoFixups() if (_fixups == null) return; for (int i = 0; i < _fixups.Count; i++) { - Fixup fixup = (Fixup)_fixups[i]; + Fixup fixup = (Fixup)_fixups[i]!; fixup.Callback(fixup); } if (_collectionFixups == null) return; for (int i = 0; i < _collectionFixups.Count; i++) { - CollectionFixup collectionFixup = (CollectionFixup)_collectionFixups[i]; + CollectionFixup collectionFixup = (CollectionFixup)_collectionFixups[i]!; collectionFixup.Callback(collectionFixup.Collection, collectionFixup.CollectionItems); } } protected void FixupArrayRefs(object fixup) { - Fixup f = (Fixup)fixup; - Array array = (Array)f.Source; + Fixup f = (Fixup)fixup!; + Array array = (Array)f.Source!; for (int i = 0; i < array.Length; i++) { - string id = f.Ids[i]; + string? id = f.Ids![i]; if (id == null) continue; object o = GetTarget(id); try @@ -1548,15 +1555,15 @@ protected void FixupArrayRefs(object fixup) } } - private object ReadArray(string typeName, string typeNs) + private object? ReadArray(string? typeName, string? typeNs) { SoapArrayInfo arrayInfo; - Type fallbackElementType = null; + Type? fallbackElementType = null; if (_soap12) { - string itemType = _r.GetAttribute(_itemTypeID, _soap12NsID); - string arraySize = _r.GetAttribute(_arraySizeID, _soap12NsID); - Type arrayType = (Type)_types[new XmlQualifiedName(typeName, typeNs)]; + string? itemType = _r.GetAttribute(_itemTypeID, _soap12NsID); + string? arraySize = _r.GetAttribute(_arraySizeID, _soap12NsID); + Type? arrayType = (Type?)_types[new XmlQualifiedName(typeName, typeNs)]; // no indication that this is an array? if (itemType == null && arraySize == null && (arrayType == null || !arrayType.IsArray)) return null; @@ -1567,7 +1574,7 @@ private object ReadArray(string typeName, string typeNs) } else { - string arrayType = _r.GetAttribute(_arrayTypeID, _soapNsID); + string? arrayType = _r.GetAttribute(_arrayTypeID, _soapNsID); if (arrayType == null) return null; @@ -1581,12 +1588,12 @@ private object ReadArray(string typeName, string typeNs) XmlQualifiedName qname; bool isPrimitive; - Type elementType = null; + Type? elementType = null; XmlQualifiedName urTypeName = new XmlQualifiedName(_urTypeID, _schemaNsID); if (arrayInfo.qname.Length > 0) { qname = ToXmlQualifiedName(arrayInfo.qname, false); - elementType = (Type)_types[qname]; + elementType = (Type?)_types[qname]; } else qname = urTypeName; @@ -1599,7 +1606,7 @@ private object ReadArray(string typeName, string typeNs) { if (!_soap12) { - elementType = GetPrimitiveType(qname, true); + elementType = GetPrimitiveType(qname, true)!; isPrimitive = true; } else @@ -1622,7 +1629,7 @@ private object ReadArray(string typeName, string typeNs) else { elementType = fallbackElementType; - XmlQualifiedName newQname = (XmlQualifiedName)_typesReverse[elementType]; + XmlQualifiedName? newQname = (XmlQualifiedName?)_typesReverse[elementType]; if (newQname == null) { newQname = XmlSerializationWriter.GetPrimitiveTypeNameInternal(elementType); @@ -1654,7 +1661,7 @@ private object ReadArray(string typeName, string typeNs) _r.MoveToContent(); int arrayLength = 0; - Array array = null; + Array? array = null; if (elementType.IsValueType) { @@ -1677,7 +1684,7 @@ private object ReadArray(string typeName, string typeNs) { string type; string typens; - string[] ids = null; + string[]? ids = null; int idsLength = 0; while (_r.NodeType != XmlNodeType.EndElement) @@ -1698,7 +1705,7 @@ private object ReadArray(string typeName, string typeNs) type = qname.Name; typens = qname.Namespace; } - array.SetValue(ReadReferencingElement(type, typens, out ids[idsLength]), arrayLength); + array.SetValue(ReadReferencingElement(type, typens, out ids[idsLength]!), arrayLength); arrayLength++; idsLength++; // CONSIDER, erikc, sparse arrays, perhaps? @@ -1709,10 +1716,10 @@ private object ReadArray(string typeName, string typeNs) // this applies in the doc/enc/bare case if (_soap12 && elementType == typeof(object)) { - Type itemType = null; + Type? itemType = null; for (int i = 0; i < arrayLength; i++) { - object currItem = array.GetValue(i); + object? currItem = array!.GetValue(i); if (currItem != null) { Type currItemType = currItem.GetType(); @@ -1735,7 +1742,7 @@ private object ReadArray(string typeName, string typeNs) if (itemType != null) elementType = itemType; } - ids = (string[])ShrinkArray(ids, idsLength, typeof(string), false); + ids = (string[]?)ShrinkArray(ids, idsLength, typeof(string), false); array = ShrinkArray(array, arrayLength, elementType, false); Fixup fixupArray = new Fixup(array, new XmlSerializationFixupCallback(this.FixupArrayRefs), ids); AddFixup(fixupArray); @@ -1752,7 +1759,7 @@ private object ReadArray(string typeName, string typeNs) protected void ReadReferencedElements() { _r.MoveToContent(); - string dummy; + string? dummy; while (_r.NodeType != XmlNodeType.EndElement && _r.NodeType != XmlNodeType.None) { ReadReferencingElement(null, null, true, out dummy); @@ -1763,30 +1770,30 @@ protected void ReadReferencedElements() HandleUnreferencedObjects(); } - protected object ReadReferencedElement() + protected object? ReadReferencedElement() { return ReadReferencedElement(null, null); } - protected object ReadReferencedElement(string name, string ns) + protected object? ReadReferencedElement(string? name, string? ns) { - string dummy; + string? dummy; return ReadReferencingElement(name, ns, out dummy); } - protected object ReadReferencingElement(out string fixupReference) + protected object? ReadReferencingElement(out string? fixupReference) { return ReadReferencingElement(null, null, out fixupReference); } - protected object ReadReferencingElement(string name, string ns, out string fixupReference) + protected object? ReadReferencingElement(string? name, string? ns, out string? fixupReference) { return ReadReferencingElement(name, ns, false, out fixupReference); } - protected object ReadReferencingElement(string name, string ns, bool elementCanBeType, out string fixupReference) + protected object? ReadReferencingElement(string? name, string? ns, bool elementCanBeType, out string? fixupReference) { - object o = null; + object? o = null; EnsureCallbackTables(); _r.MoveToContent(); @@ -1795,19 +1802,19 @@ protected object ReadReferencingElement(string name, string ns, bool elementCanB if (ReadNull()) return null; - string id = _soap12 ? _r.GetAttribute("id", Soap12.Encoding) : _r.GetAttribute("id", null); + string? id = _soap12 ? _r.GetAttribute("id", Soap12.Encoding) : _r.GetAttribute("id", null); if ((o = ReadArray(name, ns)) == null) { - XmlQualifiedName typeId = GetXsiType(); + XmlQualifiedName? typeId = GetXsiType(); if (typeId == null) { if (name == null) typeId = new XmlQualifiedName(_r.NameTable.Add(_r.LocalName), _r.NameTable.Add(_r.NamespaceURI)); else - typeId = new XmlQualifiedName(_r.NameTable.Add(name), _r.NameTable.Add(ns)); + typeId = new XmlQualifiedName(_r.NameTable.Add(name), _r.NameTable.Add(ns!)); } - XmlSerializationReadCallback callback = (XmlSerializationReadCallback)_callbacks[typeId]; + XmlSerializationReadCallback? callback = (XmlSerializationReadCallback?)_callbacks[typeId]; if (callback != null) { o = callback(); @@ -1856,11 +1863,11 @@ private object ReadXmlNodes(bool elementCanBeType) string elemLocalName = Reader.LocalName; string elemNs = Reader.NamespaceURI; string elemName = Reader.Name; - string xsiTypeName = null; - string xsiTypeNs = null; + string? xsiTypeName = null; + string? xsiTypeNs = null; int skippableNodeCount = 0; int lineNumber = -1, linePosition = -1; - XmlNode unknownNode = null; + XmlNode? unknownNode = null; if (Reader.NodeType == XmlNodeType.Attribute) { XmlAttribute attr = Document.CreateAttribute(elemName, elemNs); @@ -1870,7 +1877,7 @@ private object ReadXmlNodes(bool elementCanBeType) else unknownNode = Document.CreateElement(elemName, elemNs); GetCurrentPosition(out lineNumber, out linePosition); - XmlElement unknownElement = unknownNode as XmlElement; + XmlElement? unknownElement = unknownNode as XmlElement; while (Reader.MoveToNextAttribute()) { @@ -1888,7 +1895,7 @@ private object ReadXmlNodes(bool elementCanBeType) xsiTypeName = (colon >= 0) ? value.Substring(colon + 1) : value; xsiTypeNs = Reader.LookupNamespace((colon >= 0) ? value.Substring(0, colon) : ""); } - XmlAttribute xmlAttribute = (XmlAttribute)Document.ReadNode(_r); + XmlAttribute xmlAttribute = (XmlAttribute)Document.ReadNode(_r)!; xmlNodeList.Add(xmlAttribute); if (unknownElement != null) unknownElement.SetAttributeNode(xmlAttribute); } @@ -1905,9 +1912,9 @@ private object ReadXmlNodes(bool elementCanBeType) xmlNodeList.Add(xsiTypeAttribute); } if (xsiTypeName == Soap.UrType && - ((object)xsiTypeNs == (object)_schemaNsID || - (object)xsiTypeNs == (object)_schemaNs1999ID || - (object)xsiTypeNs == (object)_schemaNs2000ID + ((object?)xsiTypeNs == (object)_schemaNsID || + (object?)xsiTypeNs == (object)_schemaNs1999ID || + (object?)xsiTypeNs == (object)_schemaNs2000ID ) ) skippableNodeCount++; @@ -1924,7 +1931,7 @@ private object ReadXmlNodes(bool elementCanBeType) Reader.MoveToContent(); while (Reader.NodeType != System.Xml.XmlNodeType.EndElement) { - XmlNode xmlNode = Document.ReadNode(_r); + XmlNode xmlNode = Document.ReadNode(_r)!; xmlNodeList.Add(xmlNode); if (unknownElement != null) unknownElement.AppendChild(xmlNode); Reader.MoveToContent(); @@ -1950,15 +1957,15 @@ protected void CheckReaderCount(ref int whileIterations, ref int readerCount) protected class Fixup { private readonly XmlSerializationFixupCallback _callback; - private object _source; - private readonly string[] _ids; + private object? _source; + private readonly string[]? _ids; - public Fixup(object o, XmlSerializationFixupCallback callback, int count) + public Fixup(object? o, XmlSerializationFixupCallback callback, int count) : this(o, callback, new string[count]) { } - public Fixup(object o, XmlSerializationFixupCallback callback, string[] ids) + public Fixup(object? o, XmlSerializationFixupCallback callback, string[]? ids) { _callback = callback; this.Source = o; @@ -1970,13 +1977,13 @@ public XmlSerializationFixupCallback Callback get { return _callback; } } - public object Source + public object? Source { get { return _source; } set { _source = value; } } - public string[] Ids + public string?[]? Ids { get { return _ids; } } @@ -1985,10 +1992,10 @@ public string[] Ids protected class CollectionFixup { private readonly XmlSerializationCollectionFixupCallback _callback; - private readonly object _collection; + private readonly object? _collection; private readonly object _collectionItems; - public CollectionFixup(object collection, XmlSerializationCollectionFixupCallback callback, object collectionItems) + public CollectionFixup(object? collection, XmlSerializationCollectionFixupCallback callback, object collectionItems) { _callback = callback; _collection = collection; @@ -2000,7 +2007,7 @@ public XmlSerializationCollectionFixupCallback Callback get { return _callback; } } - public object Collection + public object? Collection { get { return _collection; } } @@ -2017,15 +2024,15 @@ public object CollectionItems /// - public delegate void XmlSerializationCollectionFixupCallback(object collection, object collectionItems); + public delegate void XmlSerializationCollectionFixupCallback(object? collection, object collectionItems); /// - public delegate object XmlSerializationReadCallback(); + public delegate object? XmlSerializationReadCallback(); internal class XmlSerializationReaderCodeGen : XmlSerializationCodeGen { private readonly Hashtable _idNames = new Hashtable(); - private Hashtable _enums; + private Hashtable? _enums; private readonly Hashtable _createMethods = new Hashtable(); private int _nextCreateMethodNumber; private int _nextIdNumber; @@ -2068,22 +2075,22 @@ private class Member private readonly string _arrayName; private readonly string _arraySource; private readonly string _choiceArrayName; - private readonly string _choiceSource; - private readonly string _choiceArraySource; + private readonly string? _choiceSource; + private readonly string? _choiceArraySource; private readonly MemberMapping _mapping; private readonly bool _isArray; private readonly bool _isList; private bool _isNullable; private bool _multiRef; private int _fixupIndex = -1; - private string _paramsReadSource; - private string _checkSpecifiedSource; + private string? _paramsReadSource; + private string? _checkSpecifiedSource; internal Member(XmlSerializationReaderCodeGen outerClass, string source, string arrayName, int i, MemberMapping mapping) : this(outerClass, source, null, arrayName, i, mapping, false, null) { } - internal Member(XmlSerializationReaderCodeGen outerClass, string source, string arrayName, int i, MemberMapping mapping, string choiceSource) + internal Member(XmlSerializationReaderCodeGen outerClass, string source, string arrayName, int i, MemberMapping mapping, string? choiceSource) : this(outerClass, source, null, arrayName, i, mapping, false, choiceSource) { } @@ -2091,23 +2098,23 @@ internal Member(XmlSerializationReaderCodeGen outerClass, string source, string : this(outerClass, source, arraySource, arrayName, i, mapping, false, null) { } - internal Member(XmlSerializationReaderCodeGen outerClass, string source, string arraySource, string arrayName, int i, MemberMapping mapping, string choiceSource) + internal Member(XmlSerializationReaderCodeGen outerClass, string source, string? arraySource, string arrayName, int i, MemberMapping mapping, string? choiceSource) : this(outerClass, source, arraySource, arrayName, i, mapping, false, choiceSource) { } - internal Member(XmlSerializationReaderCodeGen outerClass, string source, string arrayName, int i, MemberMapping mapping, bool multiRef) + internal Member(XmlSerializationReaderCodeGen outerClass, string source, string? arrayName, int i, MemberMapping mapping, bool multiRef) : this(outerClass, source, null, arrayName, i, mapping, multiRef, null) { } - internal Member(XmlSerializationReaderCodeGen outerClass, string source, string arraySource, string arrayName, int i, MemberMapping mapping, bool multiRef, string choiceSource) + internal Member(XmlSerializationReaderCodeGen outerClass, string source, string? arraySource, string? arrayName, int i, MemberMapping mapping, bool multiRef, string? choiceSource) { _source = source; _arrayName = arrayName + "_" + i.ToString(CultureInfo.InvariantCulture); _choiceArrayName = "choice_" + _arrayName; _choiceSource = choiceSource; - ElementAccessor[] elements = mapping.Elements; + ElementAccessor[]? elements = mapping.Elements; - if (mapping.TypeDesc.IsArrayLike) + if (mapping.TypeDesc!.IsArrayLike) { if (arraySource != null) _arraySource = arraySource; @@ -2121,7 +2128,7 @@ internal Member(XmlSerializationReaderCodeGen outerClass, string source, string string a = _choiceArrayName; string c = "c" + a; - bool choiceUseReflection = mapping.ChoiceIdentifier.Mapping.TypeDesc.UseReflection; + bool choiceUseReflection = mapping.ChoiceIdentifier.Mapping!.TypeDesc!.UseReflection; string choiceTypeFullName = mapping.ChoiceIdentifier.Mapping.TypeDesc.CSharpName; string castString = choiceUseReflection ? "" : "(" + choiceTypeFullName + "[])"; @@ -2190,19 +2197,19 @@ internal int FixupIndex set { _fixupIndex = value; } } - internal string ParamsReadSource + internal string? ParamsReadSource { get { return _paramsReadSource; } set { _paramsReadSource = value; } } - internal string CheckSpecifiedSource + internal string? CheckSpecifiedSource { get { return _checkSpecifiedSource; } set { _checkSpecifiedSource = value; } } - internal string ChoiceSource + internal string? ChoiceSource { get { return _choiceSource; } } @@ -2210,7 +2217,7 @@ internal string ChoiceArrayName { get { return _choiceArrayName; } } - internal string ChoiceArraySource + internal string? ChoiceArraySource { get { return _choiceArraySource; } } @@ -2234,7 +2241,7 @@ internal void GenerateBegin() foreach (TypeMapping mapping in scope.TypeMappings) { if (mapping is StructMapping || mapping is EnumMapping || mapping is NullableMapping) - MethodNames.Add(mapping, NextMethodName(mapping.TypeDesc.Name)); + MethodNames.Add(mapping, NextMethodName(mapping.TypeDesc!.Name)); } RaCodeGen.WriteReflectionInit(scope); } @@ -2277,7 +2284,7 @@ internal override void GenerateMethod(TypeMapping mapping) } } - internal void GenerateEnd(string[] methods, XmlMapping[] xmlMappings, Type[] types) + internal void GenerateEnd(string?[] methods, XmlMapping[] xmlMappings, Type?[]? types) { GenerateReferencedMethods(); GenerateInitCallbacksMethod(); @@ -2301,7 +2308,7 @@ internal void GenerateEnd(string[] methods, XmlMapping[] xmlMappings, Type[] typ foreach (string id in _idNames.Keys) { // CONSIDER, erikc, switch to enumerating via DictionaryEntry when issue recolved in BCL - string idName = (string)_idNames[id]; + string idName = (string)_idNames[id]!; Writer.Write(idName); Writer.Write(" = Reader.NameTable.Add("); WriteQuotedCSharpString(id); @@ -2314,7 +2321,7 @@ internal void GenerateEnd(string[] methods, XmlMapping[] xmlMappings, Type[] typ Writer.WriteLine("}"); } - internal string GenerateElement(XmlMapping xmlMapping) + internal string? GenerateElement(XmlMapping xmlMapping) { if (!xmlMapping.IsReadable) return null; @@ -2328,7 +2335,7 @@ internal string GenerateElement(XmlMapping xmlMapping) throw new ArgumentException(SR.XmlInternalError, nameof(xmlMapping)); } - private void WriteIsStartTag(string name, string ns) + private void WriteIsStartTag(string name, string? ns) { Writer.Write("if (Reader.IsStartElement("); WriteID(name); @@ -2338,7 +2345,7 @@ private void WriteIsStartTag(string name, string ns) Writer.Indent++; } - private void WriteUnknownNode(string func, string node, ElementAccessor e, bool anyIfs) + private void WriteUnknownNode(string func, string node, ElementAccessor? e, bool anyIfs) { if (anyIfs) { @@ -2351,7 +2358,7 @@ private void WriteUnknownNode(string func, string node, ElementAccessor e, bool if (e != null) { Writer.Write(", "); - string expectedElement = e.Form == XmlSchemaForm.Qualified ? e.Namespace : ""; + string? expectedElement = e.Form == XmlSchemaForm.Qualified ? e.Namespace : ""; expectedElement += ":"; expectedElement += e.Name; ReflectionAwareCodeGen.WriteQuotedCSharpString(Writer, expectedElement); @@ -2378,7 +2385,7 @@ private void GenerateInitCallbacksMethod() { if (mapping.IsSoap && (mapping is StructMapping || mapping is EnumMapping || mapping is ArrayMapping || mapping is NullableMapping) && - !mapping.TypeDesc.IsRoot) + !mapping.TypeDesc!.IsRoot) { string methodName; if (mapping is ArrayMapping) @@ -2387,7 +2394,7 @@ private void GenerateInitCallbacksMethod() needDummyArrayMethod = true; } else - methodName = (string)MethodNames[mapping]; + methodName = (string)MethodNames[mapping]!; Writer.Write("AddReadCallback("); WriteID(mapping.TypeName); @@ -2431,9 +2438,9 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) return GenerateLiteralMembersElement(xmlMembersMapping); } - private string GetChoiceIdentifierSource(MemberMapping[] mappings, MemberMapping member) + private string? GetChoiceIdentifierSource(MemberMapping[] mappings, MemberMapping member) { - string choiceSource = null; + string? choiceSource = null; if (member.ChoiceIdentifier != null) { for (int j = 0; j < mappings.Length; j++) @@ -2463,7 +2470,7 @@ private string GetChoiceIdentifierSource(MemberMapping mapping, string parent, T private string GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping) { ElementAccessor element = xmlMembersMapping.Accessor; - MemberMapping[] mappings = ((MembersMapping)element.Mapping).Members; + MemberMapping[] mappings = ((MembersMapping)element.Mapping!).Members!; bool hasWrapperElement = ((MembersMapping)element.Mapping).HasWrapperElement; string methodName = NextMethodName(element.Name); Writer.WriteLine(); @@ -2485,9 +2492,9 @@ private string GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping WriteIsStartTag(element.Name, element.Form == XmlSchemaForm.Qualified ? element.Namespace : ""); } - Member anyText = null; - Member anyElement = null; - Member anyAttribute = null; + Member? anyText = null; + Member? anyElement = null; + Member? anyAttribute = null; ArrayList membersList = new ArrayList(); ArrayList textOrArrayMembersList = new ArrayList(); @@ -2500,9 +2507,9 @@ private string GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping string arraySource = source; if (mapping.Xmlns != null) { - arraySource = "((" + mapping.TypeDesc.CSharpName + ")" + source + ")"; + arraySource = "((" + mapping.TypeDesc!.CSharpName + ")" + source + ")"; } - string choiceSource = GetChoiceIdentifierSource(mappings, mapping); + string? choiceSource = GetChoiceIdentifierSource(mappings, mapping); Member member = new Member(this, source, arraySource, "a", i, mapping, choiceSource); Member anyMember = new Member(this, source, null, "a", i, mapping, choiceSource); if (!mapping.IsSequence) @@ -2530,7 +2537,7 @@ private string GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping if (!mapping.IsSequence) { - for (int j = 0; j < mapping.Elements.Length; j++) + for (int j = 0; j < mapping.Elements!.Length; j++) { if (mapping.Elements[j].Any && mapping.Elements[j].Name.Length == 0) { @@ -2544,7 +2551,7 @@ private string GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping } if (mapping.Attribute != null || mapping.Text != null || foundAnyElement) membersList.Add(anyMember); - else if (mapping.TypeDesc.IsArrayLike && !(mapping.Elements.Length == 1 && mapping.Elements[0].Mapping is ArrayMapping)) + else if (mapping.TypeDesc!.IsArrayLike && !(mapping.Elements!.Length == 1 && mapping.Elements[0].Mapping is ArrayMapping)) { membersList.Add(anyMember); textOrArrayMembersList.Add(anyMember); @@ -2618,20 +2625,20 @@ private void InitializeValueTypes(string arrayName, MemberMapping[] mappings) { for (int i = 0; i < mappings.Length; i++) { - if (!mappings[i].TypeDesc.IsValueType) + if (!mappings[i].TypeDesc!.IsValueType) continue; Writer.Write(arrayName); Writer.Write("["); Writer.Write(i.ToString(CultureInfo.InvariantCulture)); Writer.Write("] = "); - if (mappings[i].TypeDesc.IsOptionalValue && mappings[i].TypeDesc.BaseTypeDesc.UseReflection) + if (mappings[i].TypeDesc!.IsOptionalValue && mappings[i].TypeDesc!.BaseTypeDesc!.UseReflection) { Writer.Write("null"); } else { - Writer.Write(RaCodeGen.GetStringForCreateInstance(mappings[i].TypeDesc.CSharpName, mappings[i].TypeDesc.UseReflection, false, false)); + Writer.Write(RaCodeGen.GetStringForCreateInstance(mappings[i].TypeDesc!.CSharpName, mappings[i].TypeDesc!.UseReflection, false, false)); } Writer.WriteLine(";"); } @@ -2640,8 +2647,8 @@ private void InitializeValueTypes(string arrayName, MemberMapping[] mappings) private string GenerateEncodedMembersElement(XmlMembersMapping xmlMembersMapping) { ElementAccessor element = xmlMembersMapping.Accessor; - MembersMapping membersMapping = (MembersMapping)element.Mapping; - MemberMapping[] mappings = membersMapping.Members; + MembersMapping membersMapping = (MembersMapping)element.Mapping!; + MemberMapping[] mappings = membersMapping.Members!; bool hasWrapperElement = membersMapping.HasWrapperElement; bool writeAccessors = membersMapping.WriteAccessors; string methodName = NextMethodName(element.Name); @@ -2680,7 +2687,7 @@ private string GenerateEncodedMembersElement(XmlMembersMapping xmlMembersMapping string arraySource = source; if (mapping.Xmlns != null) { - arraySource = "((" + mapping.TypeDesc.CSharpName + ")" + source + ")"; + arraySource = "((" + mapping.TypeDesc!.CSharpName + ")" + source + ")"; } Member member = new Member(this, source, arraySource, "a", i, mapping); if (!mapping.IsSequence) @@ -2706,7 +2713,7 @@ private string GenerateEncodedMembersElement(XmlMembersMapping xmlMembersMapping if (members.Length > 0 && members[0].Mapping.IsReturnValue) Writer.WriteLine("IsReturnValue = true;"); - string checkTypeHrefSource = (!hasWrapperElement && !writeAccessors) ? "hrefList" : null; + string? checkTypeHrefSource = (!hasWrapperElement && !writeAccessors) ? "hrefList" : null; if (checkTypeHrefSource != null) WriteInitCheckTypeHrefList(checkTypeHrefSource); @@ -2746,7 +2753,7 @@ private void WriteCreateCollection(TypeDesc td, string source) //cannot call WriteArrayLocalDecl since 'ci' is always //array and 'td' corresponds to 'c' if (arrayElementUseReflection) - item = typeof(Array).FullName; + item = typeof(Array).FullName!; Writer.Write(item); Writer.Write(" "); Writer.Write("ci ="); @@ -2763,7 +2770,7 @@ private void WriteCreateCollection(TypeDesc td, string source) if (!arrayElementUseReflection) Writer.Write("ci[i]"); else - Writer.Write(RaCodeGen.GetReflectionVariable(typeof(Array).FullName, "0") + "[ci , i]"); + Writer.Write(RaCodeGen.GetReflectionVariable(typeof(Array).FullName!, "0") + "[ci , i]"); if (useReflection) Writer.WriteLine("}"); @@ -2775,7 +2782,7 @@ private void WriteCreateCollection(TypeDesc td, string source) private string GenerateTypeElement(XmlTypeMapping xmlTypeMapping) { ElementAccessor element = xmlTypeMapping.Accessor; - TypeMapping mapping = element.Mapping; + TypeMapping mapping = element.Mapping!; string methodName = NextMethodName(element.Name); Writer.WriteLine(); Writer.Write("public object "); @@ -2816,13 +2823,13 @@ private void WritePrimitive(TypeMapping mapping, string source) { if (mapping is EnumMapping) { - string enumMethodName = ReferenceMapping(mapping); - if (enumMethodName == null) throw new InvalidOperationException(SR.Format(SR.XmlMissingMethodEnum, mapping.TypeDesc.Name)); + string? enumMethodName = ReferenceMapping(mapping); + if (enumMethodName == null) throw new InvalidOperationException(SR.Format(SR.XmlMissingMethodEnum, mapping.TypeDesc!.Name)); if (mapping.IsSoap) { // SOAP methods are not strongly-typed (the return object), so we need to add a cast Writer.Write("("); - Writer.Write(mapping.TypeDesc.CSharpName); + Writer.Write(mapping.TypeDesc!.CSharpName); Writer.Write(")"); } Writer.Write(enumMethodName); @@ -2834,7 +2841,7 @@ private void WritePrimitive(TypeMapping mapping, string source) { Writer.Write(source); } - else if (mapping.TypeDesc.FormatterName == "String") + else if (mapping.TypeDesc!.FormatterName == "String") { if (mapping.TypeDesc.CollapseWhitespace) { @@ -2862,10 +2869,10 @@ private void WritePrimitive(TypeMapping mapping, string source) } } - private string MakeUnique(EnumMapping mapping, string name) + private string? MakeUnique(EnumMapping mapping, string name) { string uniqueName = name; - object m = Enums[uniqueName]; + object? m = Enums[uniqueName]; if (m != null) { if (m == mapping) @@ -2888,9 +2895,9 @@ private string MakeUnique(EnumMapping mapping, string name) private string WriteHashtable(EnumMapping mapping, string typeName) { CodeIdentifier.CheckValidIdentifier(typeName); - string propName = MakeUnique(mapping, typeName + "Values"); + string? propName = MakeUnique(mapping, typeName + "Values"); if (propName == null) return CodeIdentifier.GetCSharpName(typeName); - string memberName = MakeUnique(mapping, "_" + propName); + string? memberName = MakeUnique(mapping, "_" + propName); propName = CodeIdentifier.GetCSharpName(propName); Writer.WriteLine(); @@ -2920,13 +2927,13 @@ private string WriteHashtable(EnumMapping mapping, string typeName) Writer.Write(typeof(Hashtable).FullName); Writer.WriteLine("();"); - ConstantMapping[] constants = mapping.Constants; + ConstantMapping[] constants = mapping.Constants!; for (int i = 0; i < constants.Length; i++) { Writer.Write("h.Add("); WriteQuotedCSharpString(constants[i].XmlName); - if (!mapping.TypeDesc.UseReflection) + if (!mapping.TypeDesc!.UseReflection) { Writer.Write(", (long)"); Writer.Write(mapping.TypeDesc.CSharpName); @@ -2964,13 +2971,13 @@ private string WriteHashtable(EnumMapping mapping, string typeName) private void WriteEnumMethod(EnumMapping mapping) { - string tableName = null; + string? tableName = null; if (mapping.IsFlags) - tableName = WriteHashtable(mapping, mapping.TypeDesc.Name); + tableName = WriteHashtable(mapping, mapping.TypeDesc!.Name); - string methodName = (string)MethodNames[mapping]; + string methodName = (string)MethodNames[mapping]!; Writer.WriteLine(); - bool useReflection = mapping.TypeDesc.UseReflection; + bool useReflection = mapping.TypeDesc!.UseReflection; string fullTypeName = mapping.TypeDesc.CSharpName; if (mapping.IsSoap) @@ -2991,7 +2998,7 @@ private void WriteEnumMethod(EnumMapping mapping) Writer.Indent++; } - ConstantMapping[] constants = mapping.Constants; + ConstantMapping[] constants = mapping.Constants!; if (mapping.IsFlags) { if (useReflection) @@ -3022,7 +3029,7 @@ private void WriteEnumMethod(EnumMapping mapping) Writer.WriteLine("switch (s) {"); Writer.Indent++; Hashtable cases = new Hashtable(); - for (int i = 0; i < constants.Length; i++) + for (int i = 0; i < constants!.Length; i++) { ConstantMapping c = constants[i]; @@ -3051,21 +3058,21 @@ private void WriteEnumMethod(EnumMapping mapping) private void WriteDerivedTypes(StructMapping mapping, bool isTypedReturn, string returnTypeName) { - for (StructMapping derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) + for (StructMapping? derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) { Writer.Write("if ("); WriteQNameEqual("xsiType", derived.TypeName, derived.Namespace); Writer.WriteLine(")"); Writer.Indent++; - string methodName = ReferenceMapping(derived); + string? methodName = ReferenceMapping(derived); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe - if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, derived.TypeDesc.Name)); + if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, derived.TypeDesc!.Name)); #endif Writer.Write("return "); - if (derived.TypeDesc.UseReflection && isTypedReturn) + if (derived.TypeDesc!.UseReflection && isTypedReturn) Writer.Write("(" + returnTypeName + ")"); Writer.Write(methodName); Writer.Write("("); @@ -3095,10 +3102,10 @@ private void WriteEnumAndArrayTypes() Writer.WriteLine(") {"); Writer.Indent++; Writer.WriteLine("Reader.ReadStartElement();"); - string methodName = ReferenceMapping(mapping); + string? methodName = ReferenceMapping(mapping); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe - if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc.Name)); + if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc!.Name)); #endif Writer.Write("object e = "); Writer.Write(methodName); @@ -3111,7 +3118,7 @@ private void WriteEnumAndArrayTypes() else if (m is ArrayMapping) { ArrayMapping mapping = (ArrayMapping)m; - if (mapping.TypeDesc.HasDefaultConstructor) + if (mapping.TypeDesc!.HasDefaultConstructor) { Writer.Write("if ("); WriteQNameEqual("xsiType", mapping.TypeName, mapping.Namespace); @@ -3154,9 +3161,9 @@ private void WriteEnumAndArrayTypes() private void WriteNullableMethod(NullableMapping nullableMapping) { - string methodName = (string)MethodNames[nullableMapping]; - bool useReflection = nullableMapping.BaseMapping.TypeDesc.UseReflection; - string typeName = useReflection ? "object" : nullableMapping.TypeDesc.CSharpName; + string methodName = (string)MethodNames[nullableMapping]!; + bool useReflection = nullableMapping.BaseMapping!.TypeDesc!.UseReflection; + string typeName = useReflection ? "object" : nullableMapping.TypeDesc!.CSharpName; Writer.WriteLine(); Writer.Write(typeName); @@ -3208,8 +3215,8 @@ private void WriteStructMethod(StructMapping structMapping) private void WriteLiteralStructMethod(StructMapping structMapping) { - string methodName = (string)MethodNames[structMapping]; - bool useReflection = structMapping.TypeDesc.UseReflection; + string methodName = (string)MethodNames[structMapping]!; + bool useReflection = structMapping.TypeDesc!.UseReflection; string typeName = useReflection ? "object" : structMapping.TypeDesc.CSharpName; Writer.WriteLine(); Writer.Write(typeName); @@ -3296,9 +3303,9 @@ private void WriteLiteralStructMethod(StructMapping structMapping) MemberMapping[] mappings = TypeScope.GetSettableMembers(structMapping); - Member anyText = null; - Member anyElement = null; - Member anyAttribute = null; + Member? anyText = null; + Member? anyElement = null; + Member? anyAttribute = null; bool isSequence = structMapping.HasExplicitSequence(); ArrayList arraysToDeclareList = new ArrayList(mappings.Length); @@ -3313,7 +3320,7 @@ private void WriteLiteralStructMethod(StructMapping structMapping) Member member = new Member(this, source, "a", i, mapping, GetChoiceIdentifierSource(mapping, "o", structMapping.TypeDesc)); if (!mapping.IsSequence) member.ParamsReadSource = "paramsRead[" + i.ToString(CultureInfo.InvariantCulture) + "]"; - member.IsNullable = mapping.TypeDesc.IsNullable; + member.IsNullable = mapping.TypeDesc!.IsNullable; if (mapping.CheckSpecified == SpecifiedAccessor.ReadWrite) member.CheckSpecifiedSource = RaCodeGen.GetStringForMember("o", mapping.Name + "Specified", structMapping.TypeDesc); if (mapping.Text != null) @@ -3323,7 +3330,7 @@ private void WriteLiteralStructMethod(StructMapping structMapping) if (!isSequence) { // find anyElement if present. - for (int j = 0; j < mapping.Elements.Length; j++) + for (int j = 0; j < mapping.Elements!.Length; j++) { if (mapping.Elements[j].Any && (mapping.Elements[j].Name == null || mapping.Elements[j].Name.Length == 0)) { @@ -3334,11 +3341,11 @@ private void WriteLiteralStructMethod(StructMapping structMapping) } else if (mapping.IsParticle && !mapping.IsSequence) { - StructMapping declaringMapping; + StructMapping? declaringMapping; structMapping.FindDeclaringMapping(mapping, out declaringMapping, structMapping.TypeName); - throw new InvalidOperationException(SR.Format(SR.XmlSequenceHierarchy, structMapping.TypeDesc.FullName, mapping.Name, declaringMapping.TypeDesc.FullName, "Order")); + throw new InvalidOperationException(SR.Format(SR.XmlSequenceHierarchy, structMapping.TypeDesc.FullName, mapping.Name, declaringMapping!.TypeDesc!.FullName, "Order")); } - if (mapping.Attribute == null && mapping.Elements.Length == 1 && mapping.Elements[0].Mapping is ArrayMapping) + if (mapping.Attribute == null && mapping.Elements!.Length == 1 && mapping.Elements[0].Mapping is ArrayMapping) { Member arrayMember = new Member(this, source, source, "a", i, mapping, GetChoiceIdentifierSource(mapping, "o", structMapping.TypeDesc)); arrayMember.CheckSpecifiedSource = member.CheckSpecifiedSource; @@ -3352,7 +3359,7 @@ private void WriteLiteralStructMethod(StructMapping structMapping) if (mapping.TypeDesc.IsArrayLike) { arraysToDeclareList.Add(member); - if (mapping.TypeDesc.IsArrayLike && !(mapping.Elements.Length == 1 && mapping.Elements[0].Mapping is ArrayMapping)) + if (mapping.TypeDesc.IsArrayLike && !(mapping.Elements!.Length == 1 && mapping.Elements[0].Mapping is ArrayMapping)) { member.ParamsReadSource = null; // flat arrays -- don't want to count params read. if (member != anyText && member != anyElement) @@ -3413,10 +3420,10 @@ private void WriteLiteralStructMethod(StructMapping structMapping) private void WriteEncodedStructMethod(StructMapping structMapping) { - if (structMapping.TypeDesc.IsRoot) + if (structMapping.TypeDesc!.IsRoot) return; bool useReflection = structMapping.TypeDesc.UseReflection; - string methodName = (string)MethodNames[structMapping]; + string methodName = (string)MethodNames[structMapping]!; Writer.WriteLine(); Writer.Write("object"); Writer.Write(" "); @@ -3427,7 +3434,7 @@ private void WriteEncodedStructMethod(StructMapping structMapping) Member[] members; bool anyFixups; - string fixupMethodName; + string? fixupMethodName; if (structMapping.TypeDesc.IsAbstract) { @@ -3488,7 +3495,7 @@ private void WriteEncodedStructMethod(StructMapping structMapping) if (anyFixups) WriteFixupMethod(fixupMethodName, members, structMapping.TypeDesc.CSharpName, structMapping.TypeDesc.UseReflection, true, "o"); } - private void WriteFixupMethod(string fixupMethodName, Member[] members, string typeName, bool useReflection, bool typed, string source) + private void WriteFixupMethod(string? fixupMethodName, Member[] members, string typeName, bool useReflection, bool typed, string source) { Writer.WriteLine(); Writer.Write("void "); @@ -3513,7 +3520,7 @@ private void WriteFixupMethod(string fixupMethodName, Member[] members, string t string memberSource = /*member.IsList ? source + ".Add(" :*/ member.ArraySource; string targetSource = "GetTarget(ids[" + fixupIndex + "])"; - TypeDesc td = member.Mapping.TypeDesc; + TypeDesc td = member.Mapping.TypeDesc!; if (td.IsCollection || td.IsEnumerable) { WriteAddCollectionFixup(td, member.Mapping.ReadOnly, memberSource, targetSource); @@ -3541,7 +3548,7 @@ private void WriteFixupMethod(string fixupMethodName, Member[] members, string t if (typed) { - WriteCatchCastException(member.Mapping.TypeDesc, targetSource, "ids[" + fixupIndex + "]"); + WriteCatchCastException(member.Mapping.TypeDesc!, targetSource, "ids[" + fixupIndex + "]"); } } Writer.Indent--; @@ -3556,7 +3563,7 @@ private void WriteAddCollectionFixup(TypeDesc typeDesc, bool readOnly, string me { Writer.WriteLine("// get array of the collection items"); bool useReflection = typeDesc.UseReflection; - CreateCollectionInfo create = (CreateCollectionInfo)_createMethods[typeDesc]; + CreateCollectionInfo? create = (CreateCollectionInfo?)_createMethods[typeDesc]; if (create == null) { string createName = "create" + (++_nextCreateMethodNumber).ToString(CultureInfo.InvariantCulture) + "_" + typeDesc.Name; @@ -3620,7 +3627,7 @@ private void WriteCreateCollectionMethod(CreateCollectionInfo c) Writer.WriteLine("}"); } - private void WriteQNameEqual(string source, string name, string ns) + private void WriteQNameEqual(string? source, string? name, string? ns) { Writer.Write("((object) (("); Writer.Write(typeof(XmlQualifiedName).FullName); @@ -3637,7 +3644,7 @@ private void WriteQNameEqual(string source, string name, string ns) Writer.Write(")"); } - private void WriteXmlNodeEqual(string source, string name, string ns) + private void WriteXmlNodeEqual(string? source, string? name, string? ns) { Writer.Write("("); if (name != null && name.Length > 0) @@ -3655,7 +3662,7 @@ private void WriteXmlNodeEqual(string source, string name, string ns) Writer.Write(")"); } - private void WriteID(string name) + private void WriteID(string? name) { if (name == null) { @@ -3663,7 +3670,7 @@ private void WriteID(string name) //return; name = ""; } - string idName = (string)_idNames[name]; + string? idName = (string?)_idNames[name]; if (idName == null) { idName = NextIdName(name); @@ -3672,10 +3679,10 @@ private void WriteID(string name) Writer.Write(idName); } - private void WriteAttributes(Member[] members, Member anyAttribute, string elseCall, string firstParam) + private void WriteAttributes(Member[] members, Member? anyAttribute, string elseCall, string firstParam) { int count = 0; - Member xmlnsMember = null; + Member? xmlnsMember = null; ArrayList attributes = new ArrayList(); Writer.WriteLine("while (Reader.MoveToNextAttribute()) {"); @@ -3691,7 +3698,7 @@ private void WriteAttributes(Member[] members, Member anyAttribute, string elseC } if (member.Mapping.Ignore) continue; - AttributeAccessor attribute = member.Mapping.Attribute; + AttributeAccessor? attribute = member.Mapping.Attribute; if (attribute == null) continue; if (attribute.Any) continue; @@ -3736,7 +3743,7 @@ private void WriteAttributes(Member[] members, Member anyAttribute, string elseC Writer.Write(" == null) "); Writer.Write(xmlnsMember.Source); Writer.Write(" = new "); - Writer.Write(xmlnsMember.Mapping.TypeDesc.CSharpName); + Writer.Write(xmlnsMember.Mapping.TypeDesc!.CSharpName); Writer.WriteLine("();"); //Writer.Write(xmlnsMember.ArraySource); @@ -3776,7 +3783,7 @@ private void WriteAttributes(Member[] members, Member anyAttribute, string elseC for (int i = 0; i < attributes.Count; i++) { - AttributeAccessor attribute = (AttributeAccessor)attributes[i]; + AttributeAccessor attribute = (AttributeAccessor)attributes[i]!; if (i > 0) qnames += ", "; qnames += attribute.IsSpecialXmlNamespace ? XmlReservedNs.NsXml : (attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : "") + ":" + attribute.Name; @@ -3794,13 +3801,13 @@ private void WriteAttributes(Member[] members, Member anyAttribute, string elseC private void WriteAttribute(Member member) { - AttributeAccessor attribute = member.Mapping.Attribute; + AttributeAccessor attribute = member.Mapping.Attribute!; if (attribute.Mapping is SpecialMapping) { SpecialMapping special = (SpecialMapping)attribute.Mapping; - if (special.TypeDesc.Kind == TypeKind.Attribute) + if (special.TypeDesc!.Kind == TypeKind.Attribute) { WriteSourceBegin(member.ArraySource); Writer.Write("attr"); @@ -3834,10 +3841,10 @@ private void WriteAttribute(Member member) Writer.WriteLine("for (int i = 0; i < vals.Length; i++) {"); Writer.Indent++; - string attributeSource = GetArraySource(member.Mapping.TypeDesc, member.ArrayName); + string attributeSource = GetArraySource(member.Mapping.TypeDesc!, member.ArrayName); WriteSourceBegin(attributeSource); - WritePrimitive(attribute.Mapping, "vals[i]"); + WritePrimitive(attribute.Mapping!, "vals[i]"); WriteSourceEnd(attributeSource); Writer.WriteLine(";"); Writer.Indent--; @@ -3846,7 +3853,7 @@ private void WriteAttribute(Member member) else { WriteSourceBegin(member.ArraySource); - WritePrimitive(attribute.Mapping, attribute.IsList ? "vals[i]" : "Reader.Value"); + WritePrimitive(attribute.Mapping!, attribute.IsList ? "vals[i]" : "Reader.Value"); WriteSourceEnd(member.ArraySource); Writer.WriteLine(";"); } @@ -3869,10 +3876,10 @@ private bool WriteMemberFixupBegin(Member[] members, string fixupMethodName, str for (int i = 0; i < members.Length; i++) { Member member = (Member)members[i]; - if (member.Mapping.Elements.Length == 0) + if (member.Mapping.Elements!.Length == 0) continue; - TypeMapping mapping = member.Mapping.Elements[0].Mapping; + TypeMapping? mapping = member.Mapping.Elements[0].Mapping; if (mapping is StructMapping || mapping is ArrayMapping || mapping is PrimitiveMapping || mapping is NullableMapping) { member.MultiRef = true; @@ -3909,10 +3916,10 @@ private void WriteMemberBegin(Member[] members) string a = member.ArrayName; string c = "c" + a; - TypeDesc typeDesc = member.Mapping.TypeDesc; + TypeDesc typeDesc = member.Mapping.TypeDesc!; string typeDescFullName = typeDesc.CSharpName; - if (member.Mapping.TypeDesc.IsArray) + if (member.Mapping.TypeDesc!.IsArray) { WriteArrayLocalDecl(typeDesc.CSharpName, a, "null", typeDesc); @@ -3922,7 +3929,7 @@ private void WriteMemberBegin(Member[] members) if (member.Mapping.ChoiceIdentifier != null) { - WriteArrayLocalDecl(member.Mapping.ChoiceIdentifier.Mapping.TypeDesc.CSharpName + "[]", + WriteArrayLocalDecl(member.Mapping.ChoiceIdentifier.Mapping!.TypeDesc!.CSharpName + "[]", member.ChoiceArrayName, "null", member.Mapping.ChoiceIdentifier.Mapping.TypeDesc); Writer.Write("int c"); @@ -3988,12 +3995,12 @@ private string ExpectedElements(Member[] members) if (member.Mapping.IsText || member.Mapping.IsAttribute) continue; - ElementAccessor[] elements = member.Mapping.Elements; + ElementAccessor[] elements = member.Mapping.Elements!; for (int j = 0; j < elements.Length; j++) { ElementAccessor e = elements[j]; - string ns = e.Form == XmlSchemaForm.Qualified ? e.Namespace : ""; + string? ns = e.Form == XmlSchemaForm.Qualified ? e.Namespace : ""; if (e.Any && (e.Name == null || e.Name.Length == 0)) continue; if (!firstElement) @@ -4007,7 +4014,7 @@ private string ExpectedElements(Member[] members) return writer.ToString(); } - private void WriteMemberElements(Member[] members, string elementElseString, string elseString, Member anyElement, Member anyText, string checkTypeHrefsSource) + private void WriteMemberElements(Member[] members, string elementElseString, string elseString, Member? anyElement, Member? anyText, string? checkTypeHrefsSource) { bool checkType = (checkTypeHrefsSource != null && checkTypeHrefsSource.Length > 0); @@ -4075,13 +4082,13 @@ private void WriteMemberText(Member anyText, string elseString) private void WriteText(Member member) { - TextAccessor text = member.Mapping.Text; + TextAccessor text = member.Mapping.Text!; if (text.Mapping is SpecialMapping) { SpecialMapping special = (SpecialMapping)text.Mapping; WriteSourceBeginTyped(member.ArraySource, special.TypeDesc); - switch (special.TypeDesc.Kind) + switch (special.TypeDesc!.Kind) { case TypeKind.Node: Writer.Write("Document.CreateTextNode(Reader.ReadString())"); @@ -4096,7 +4103,7 @@ private void WriteText(Member member) if (member.IsArrayLike) { WriteSourceBegin(member.ArraySource); - if (text.Mapping.TypeDesc.CollapseWhitespace) + if (text.Mapping!.TypeDesc!.CollapseWhitespace) { Writer.Write("CollapseWhitespace(Reader.ReadString())"); } @@ -4107,10 +4114,10 @@ private void WriteText(Member member) } else { - if (text.Mapping.TypeDesc == StringTypeDesc || text.Mapping.TypeDesc.FormatterName == "String") + if (text.Mapping!.TypeDesc == StringTypeDesc || text.Mapping.TypeDesc!.FormatterName == "String") { Writer.Write("tmp = ReadString(tmp, "); - if (text.Mapping.TypeDesc.CollapseWhitespace) + if (text.Mapping.TypeDesc!.CollapseWhitespace) Writer.WriteLine("true);"); else Writer.WriteLine("false);"); @@ -4130,7 +4137,7 @@ private void WriteText(Member member) Writer.WriteLine(";"); } - private void WriteMemberElementsCheckType(string checkTypeHrefsSource) + private void WriteMemberElementsCheckType(string? checkTypeHrefsSource) { Writer.WriteLine("string refElemId = null;"); Writer.WriteLine("object refElem = ReadReferencingElement(null, null, true, out refElemId);"); @@ -4153,11 +4160,11 @@ private void WriteMemberElementsCheckType(string checkTypeHrefsSource) Writer.WriteLine("}"); } - private void WriteMemberElementsElse(Member anyElement, string elementElseString) + private void WriteMemberElementsElse(Member? anyElement, string elementElseString) { if (anyElement != null) { - ElementAccessor[] elements = anyElement.Mapping.Elements; + ElementAccessor[] elements = anyElement.Mapping.Elements!; for (int i = 0; i < elements.Length; i++) { ElementAccessor element = elements[i]; @@ -4183,7 +4190,7 @@ private bool IsSequence(Member[] members) } return false; } - private void WriteMemberElementsIf(Member[] members, Member anyElement, string elementElseString, string checkTypeSource) + private void WriteMemberElementsIf(Member[] members, Member? anyElement, string elementElseString, string? checkTypeSource) { bool checkType = checkTypeSource != null && checkTypeSource.Length > 0; //int count = checkType ? 1 : 0; @@ -4207,13 +4214,13 @@ private void WriteMemberElementsIf(Member[] members, Member anyElement, string e continue; bool firstElement = true; - ChoiceIdentifierAccessor choice = member.Mapping.ChoiceIdentifier; - ElementAccessor[] elements = member.Mapping.Elements; + ChoiceIdentifierAccessor? choice = member.Mapping.ChoiceIdentifier; + ElementAccessor[] elements = member.Mapping.Elements!; for (int j = 0; j < elements.Length; j++) { ElementAccessor e = elements[j]; - string ns = e.Form == XmlSchemaForm.Qualified ? e.Namespace : ""; + string? ns = e.Form == XmlSchemaForm.Qualified ? e.Namespace : ""; if (!isSequence && e.Any && (e.Name == null || e.Name.Length == 0)) continue; if (!isSequence) { @@ -4250,12 +4257,12 @@ private void WriteMemberElementsIf(Member[] members, Member anyElement, string e { if (e.Mapping is NullableMapping) { - TypeDesc td = ((NullableMapping)e.Mapping).BaseMapping.TypeDesc; + TypeDesc td = ((NullableMapping)e.Mapping).BaseMapping!.TypeDesc!; Writer.Write(RaCodeGen.GetStringForTypeof(td.CSharpName, td.UseReflection)); } else { - Writer.Write(RaCodeGen.GetStringForTypeof(e.Mapping.TypeDesc.CSharpName, e.Mapping.TypeDesc.UseReflection)); + Writer.Write(RaCodeGen.GetStringForTypeof(e.Mapping!.TypeDesc!.CSharpName, e.Mapping.TypeDesc.UseReflection)); } Writer.Write(".IsAssignableFrom("); Writer.Write(checkTypeSource); @@ -4280,7 +4287,7 @@ private void WriteMemberElementsIf(Member[] members, Member anyElement, string e Writer.Indent++; if (checkType) { - if (e.Mapping.TypeDesc.IsValueType || e.Mapping is NullableMapping) + if (e.Mapping!.TypeDesc!.IsValueType || e.Mapping is NullableMapping) { Writer.Write("if ("); Writer.Write(checkTypeSource); @@ -4290,7 +4297,7 @@ private void WriteMemberElementsIf(Member[] members, Member anyElement, string e if (e.Mapping is NullableMapping) { WriteSourceBegin(member.ArraySource); - TypeDesc td = ((NullableMapping)e.Mapping).BaseMapping.TypeDesc; + TypeDesc td = ((NullableMapping)e.Mapping).BaseMapping!.TypeDesc!; Writer.Write(RaCodeGen.GetStringForCreateInstance(e.Mapping.TypeDesc.CSharpName, e.Mapping.TypeDesc.UseReflection, false, true, "(" + td.CSharpName + ")" + checkTypeSource)); } else @@ -4316,7 +4323,7 @@ private void WriteMemberElementsIf(Member[] members, Member anyElement, string e } else { - WriteElement(member.ArraySource, member.ArrayName, member.ChoiceArraySource, e, choice, member.Mapping.CheckSpecified == SpecifiedAccessor.ReadWrite ? member.CheckSpecifiedSource : null, member.IsList && member.Mapping.TypeDesc.IsNullable, member.Mapping.ReadOnly, member.FixupIndex, j); + WriteElement(member.ArraySource, member.ArrayName, member.ChoiceArraySource, e, choice, member.Mapping.CheckSpecified == SpecifiedAccessor.ReadWrite ? member.CheckSpecifiedSource : null, member.IsList && member.Mapping.TypeDesc!.IsNullable, member.Mapping.ReadOnly, member.FixupIndex, j); } if (member.Mapping.IsReturnValue) Writer.WriteLine("IsReturnValue = false;"); @@ -4396,7 +4403,7 @@ private string GetArraySource(TypeDesc typeDesc, string arrayName, bool multiRef bool useReflection = typeDesc.UseReflection; if (typeDesc.IsArray) { - string arrayTypeFullName = typeDesc.ArrayElementTypeDesc.CSharpName; + string arrayTypeFullName = typeDesc.ArrayElementTypeDesc!.CSharpName; bool arrayUseReflection = typeDesc.ArrayElementTypeDesc.UseReflection; string castString = useReflection ? "" : "(" + arrayTypeFullName + "[])"; init = init + a + " = " + castString + @@ -4429,7 +4436,7 @@ private void WriteMemberEnd(Member[] members, bool soapRefs) if (member.IsArrayLike) { - TypeDesc typeDesc = member.Mapping.TypeDesc; + TypeDesc typeDesc = member.Mapping.TypeDesc!; if (typeDesc.IsArray) { @@ -4441,7 +4448,7 @@ private void WriteMemberEnd(Member[] members, bool soapRefs) string a = member.ArrayName; string c = "c" + a; - bool arrayUseReflection = typeDesc.ArrayElementTypeDesc.UseReflection; + bool arrayUseReflection = typeDesc.ArrayElementTypeDesc!.UseReflection; string arrayTypeFullName = typeDesc.ArrayElementTypeDesc.CSharpName; if (!arrayUseReflection) Writer.Write("(" + arrayTypeFullName + "[])"); @@ -4459,11 +4466,11 @@ private void WriteMemberEnd(Member[] members, bool soapRefs) if (member.Mapping.ChoiceIdentifier != null) { - WriteSourceBegin(member.ChoiceSource); + WriteSourceBegin(member.ChoiceSource!); a = member.ChoiceArrayName; c = "c" + a; - bool choiceUseReflection = member.Mapping.ChoiceIdentifier.Mapping.TypeDesc.UseReflection; + bool choiceUseReflection = member.Mapping.ChoiceIdentifier.Mapping!.TypeDesc!.UseReflection; string choiceTypeName = member.Mapping.ChoiceIdentifier.Mapping.TypeDesc.CSharpName; if (!choiceUseReflection) Writer.Write("(" + choiceTypeName + "[])"); @@ -4476,7 +4483,7 @@ private void WriteMemberEnd(Member[] members, bool soapRefs) Writer.Write(", "); WriteBooleanValue(member.IsNullable); Writer.Write(")"); - WriteSourceEnd(member.ChoiceSource); + WriteSourceEnd(member.ChoiceSource!); Writer.WriteLine(";"); } } @@ -4491,7 +4498,7 @@ private void WriteMemberEnd(Member[] members, bool soapRefs) } } - private void WriteSourceBeginTyped(string source, TypeDesc typeDesc) + private void WriteSourceBeginTyped(string source, TypeDesc? typeDesc) { WriteSourceBegin(source); if (typeDesc != null && !typeDesc.UseReflection) @@ -4519,7 +4526,7 @@ private void WriteSourceEnd(string source) Writer.Write("})"); } - private void WriteArray(string source, string arrayName, ArrayMapping arrayMapping, bool readOnly, bool isNullable, int fixupIndex) + private void WriteArray(string source, string? arrayName, ArrayMapping arrayMapping, bool readOnly, bool isNullable, int fixupIndex) { if (arrayMapping.IsSoap) { @@ -4538,7 +4545,7 @@ private void WriteArray(string source, string arrayName, ArrayMapping arrayMappi } Writer.WriteLine(");"); - TypeDesc td = arrayMapping.TypeDesc; + TypeDesc td = arrayMapping.TypeDesc!; if (td.IsEnumerable || td.IsCollection) { Writer.WriteLine("if (rre != null) {"); @@ -4555,7 +4562,7 @@ private void WriteArray(string source, string arrayName, ArrayMapping arrayMappi Writer.Write("rre"); WriteSourceEnd(source); Writer.WriteLine(";"); - WriteCatchCastException(arrayMapping.TypeDesc, "rre", null); + WriteCatchCastException(arrayMapping.TypeDesc!, "rre", null); } } else @@ -4621,7 +4628,7 @@ private void WriteArray(string source, string arrayName, ArrayMapping arrayMappi } } - private void WriteElement(string source, string arrayName, string choiceSource, ElementAccessor element, ChoiceIdentifierAccessor choice, string checkSpecified, bool checkForNull, bool readOnly, int fixupIndex, int elementIndex) + private void WriteElement(string source, string? arrayName, string? choiceSource, ElementAccessor element, ChoiceIdentifierAccessor? choice, string? checkSpecified, bool checkForNull, bool readOnly, int fixupIndex, int elementIndex) { if (checkSpecified != null && checkSpecified.Length > 0) { @@ -4635,10 +4642,10 @@ private void WriteElement(string source, string arrayName, string choiceSource, } else if (element.Mapping is NullableMapping) { - string methodName = ReferenceMapping(element.Mapping); + string? methodName = ReferenceMapping(element.Mapping); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe - if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, element.Mapping.TypeDesc.Name)); + if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, element.Mapping.TypeDesc!.Name)); #endif WriteSourceBegin(source); Writer.Write(methodName); @@ -4646,14 +4653,14 @@ private void WriteElement(string source, string arrayName, string choiceSource, WriteSourceEnd(source); Writer.WriteLine(";"); } - else if (!element.Mapping.IsSoap && (element.Mapping is PrimitiveMapping)) + else if (!element.Mapping!.IsSoap && (element.Mapping is PrimitiveMapping)) { if (element.IsNullable) { Writer.WriteLine("if (ReadNull()) {"); Writer.Indent++; WriteSourceBegin(source); - if (element.Mapping.TypeDesc.IsValueType) + if (element.Mapping.TypeDesc!.IsValueType) { Writer.Write(RaCodeGen.GetStringForCreateInstance(element.Mapping.TypeDesc.CSharpName, element.Mapping.TypeDesc.UseReflection, false, false)); } @@ -4667,7 +4674,7 @@ private void WriteElement(string source, string arrayName, string choiceSource, Writer.WriteLine("}"); Writer.Write("else "); } - if (element.Default != null && element.Default != DBNull.Value && element.Mapping.TypeDesc.IsValueType) + if (element.Default != null && element.Default != DBNull.Value && element.Mapping.TypeDesc!.IsValueType) { Writer.WriteLine("if (Reader.IsEmptyElement) {"); Writer.Indent++; @@ -4682,7 +4689,7 @@ private void WriteElement(string source, string arrayName, string choiceSource, } Writer.Indent++; - if (element.Mapping.TypeDesc.Type == typeof(TimeSpan)) + if (element.Mapping.TypeDesc!.Type == typeof(TimeSpan)) { Writer.WriteLine("if (Reader.IsEmptyElement) {"); Writer.Indent++; @@ -4751,7 +4758,7 @@ private void WriteElement(string source, string arrayName, string choiceSource, WriteSourceEnd(source); Writer.WriteLine(";"); - if (mapping.TypeDesc.IsValueType) + if (mapping.TypeDesc!.IsValueType) { Writer.WriteLine("if (rre != null) {"); Writer.Indent++; @@ -4775,10 +4782,10 @@ private void WriteElement(string source, string arrayName, string choiceSource, } else { - string methodName = ReferenceMapping(mapping); + string? methodName = ReferenceMapping(mapping); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe - if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc.Name)); + if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc!.Name)); #endif if (checkForNull) @@ -4790,7 +4797,7 @@ private void WriteElement(string source, string arrayName, string choiceSource, WriteSourceBegin(source); Writer.Write(methodName); Writer.Write("("); - if (mapping.TypeDesc.IsNullable) + if (mapping.TypeDesc!.IsNullable) { WriteBooleanValue(element.IsNullable); Writer.Write(", "); @@ -4804,7 +4811,7 @@ private void WriteElement(string source, string arrayName, string choiceSource, else if (element.Mapping is SpecialMapping) { SpecialMapping special = (SpecialMapping)element.Mapping; - switch (special.TypeDesc.Kind) + switch (special.TypeDesc!.Kind) { case TypeKind.Node: bool isDoc = special.TypeDesc.FullName == typeof(XmlDocument).FullName; @@ -4824,7 +4831,7 @@ private void WriteElement(string source, string arrayName, string choiceSource, Writer.WriteLine(" tser = GetXsiType();"); Writer.Write("if (tser == null"); Writer.Write(" || "); - WriteQNameEqual("tser", sm.XsiType.Name, sm.XsiType.Namespace); + WriteQNameEqual("tser", sm.XsiType!.Name, sm.XsiType.Namespace); Writer.WriteLine(") {"); Writer.Indent++; @@ -4833,7 +4840,7 @@ private void WriteElement(string source, string arrayName, string choiceSource, Writer.Write("ReadSerializable(( "); Writer.Write(typeof(IXmlSerializable).FullName); Writer.Write(")"); - Writer.Write(RaCodeGen.GetStringForCreateInstance(sm.TypeDesc.CSharpName, sm.TypeDesc.UseReflection, sm.TypeDesc.CannotNew, false)); + Writer.Write(RaCodeGen.GetStringForCreateInstance(sm.TypeDesc!.CSharpName, sm.TypeDesc.UseReflection, sm.TypeDesc.CannotNew, false)); bool isWrappedAny = !element.Any && IsWildcard(sm); if (isWrappedAny) { @@ -4865,10 +4872,10 @@ private void WriteElement(string source, string arrayName, string choiceSource, if (choiceSource == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, "need parent for the " + source)); #endif - string enumTypeName = choice.Mapping.TypeDesc.CSharpName; + string enumTypeName = choice.Mapping!.TypeDesc!.CSharpName; Writer.Write(choiceSource); Writer.Write(" = "); - CodeIdentifier.CheckValidIdentifier(choice.MemberIds[elementIndex]); + CodeIdentifier.CheckValidIdentifier(choice.MemberIds![elementIndex]); Writer.Write(RaCodeGen.GetStringForEnumMember(enumTypeName, choice.MemberIds[elementIndex], choice.Mapping.TypeDesc.UseReflection)); Writer.WriteLine(";"); } @@ -4878,24 +4885,24 @@ private void WriteDerivedSerializable(SerializableMapping head, SerializableMapp { if (mapping == null) return; - for (SerializableMapping derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) + for (SerializableMapping? derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) { Writer.Write("else if (tser == null"); Writer.Write(" || "); - WriteQNameEqual("tser", derived.XsiType.Name, derived.XsiType.Namespace); + WriteQNameEqual("tser", derived.XsiType!.Name, derived.XsiType.Namespace); Writer.WriteLine(") {"); Writer.Indent++; if (derived.Type != null) { - if (head.Type.IsAssignableFrom(derived.Type)) + if (head.Type!.IsAssignableFrom(derived.Type)) { WriteSourceBeginTyped(source, head.TypeDesc); Writer.Write("ReadSerializable(( "); Writer.Write(typeof(IXmlSerializable).FullName); Writer.Write(")"); - Writer.Write(RaCodeGen.GetStringForCreateInstance(derived.TypeDesc.CSharpName, derived.TypeDesc.UseReflection, derived.TypeDesc.CannotNew, false)); + Writer.Write(RaCodeGen.GetStringForCreateInstance(derived.TypeDesc!.CSharpName, derived.TypeDesc.UseReflection, derived.TypeDesc.CannotNew, false)); if (isWrappedAny) { Writer.WriteLine(", true"); @@ -4911,7 +4918,7 @@ private void WriteDerivedSerializable(SerializableMapping head, SerializableMapp Writer.Write(", "); WriteQuotedCSharpString(derived.XsiType.Namespace); Writer.Write(", "); - WriteQuotedCSharpString(head.XsiType.Name); + WriteQuotedCSharpString(head.XsiType!.Name); Writer.Write(", "); WriteQuotedCSharpString(head.XsiType.Namespace); Writer.Write(", "); @@ -4929,7 +4936,7 @@ private void WriteDerivedSerializable(SerializableMapping head, SerializableMapp Writer.Write(", "); WriteQuotedCSharpString(derived.XsiType.Namespace); Writer.Write(", "); - WriteQuotedCSharpString(head.Type.FullName); + WriteQuotedCSharpString(head.Type!.FullName); Writer.WriteLine(");"); } @@ -5040,7 +5047,7 @@ private void WriteIfNotSoapRoot(string source) private void WriteCreateMapping(TypeMapping mapping, string local) { - string fullTypeName = mapping.TypeDesc.CSharpName; + string fullTypeName = mapping.TypeDesc!.CSharpName; bool useReflection = mapping.TypeDesc.UseReflection; bool ctorInaccessible = mapping.TypeDesc.CannotNew; @@ -5087,7 +5094,7 @@ private void WriteCatchException(Type exceptionType) Writer.WriteLine(") {"); } - private void WriteCatchCastException(TypeDesc typeDesc, string source, string id) + private void WriteCatchCastException(TypeDesc typeDesc, string source, string? id) { WriteCatchException(typeof(InvalidCastException)); Writer.Indent++; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs index 549f2b7b7d72b2..833f2cf86579b9 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs @@ -1,7 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. - +#nullable enable namespace System.Xml.Serialization { using System; @@ -22,7 +22,7 @@ internal class XmlSerializationReaderILGen : XmlSerializationILGen private readonly Dictionary _idNames = new Dictionary(); // Mapping name->id_XXXNN field private readonly Dictionary _idNameFields = new Dictionary(); - private Dictionary _enums; + private Dictionary? _enums; private int _nextIdNumber; internal Dictionary Enums @@ -43,44 +43,44 @@ private class Member private readonly string _arrayName; private readonly string _arraySource; private readonly string _choiceArrayName; - private readonly string _choiceSource; - private readonly string _choiceArraySource; + private readonly string? _choiceSource; + private readonly string? _choiceArraySource; private readonly MemberMapping _mapping; private readonly bool _isArray; private readonly bool _isList; private bool _isNullable; private int _fixupIndex = -1; - private string _paramsReadSource; - private string _checkSpecifiedSource; + private string? _paramsReadSource; + private string? _checkSpecifiedSource; - internal Member(XmlSerializationReaderILGen outerClass, string source, string arrayName, int i, MemberMapping mapping) + internal Member(XmlSerializationReaderILGen outerClass, string source, string? arrayName, int i, MemberMapping mapping) : this(outerClass, source, null, arrayName, i, mapping, false, null) { } - internal Member(XmlSerializationReaderILGen outerClass, string source, string arrayName, int i, MemberMapping mapping, string choiceSource) + internal Member(XmlSerializationReaderILGen outerClass, string source, string? arrayName, int i, MemberMapping mapping, string? choiceSource) : this(outerClass, source, null, arrayName, i, mapping, false, choiceSource) { } - internal Member(XmlSerializationReaderILGen outerClass, string source, string arraySource, string arrayName, int i, MemberMapping mapping) + internal Member(XmlSerializationReaderILGen outerClass, string source, string? arraySource, string? arrayName, int i, MemberMapping mapping) : this(outerClass, source, arraySource, arrayName, i, mapping, false, null) { } - internal Member(XmlSerializationReaderILGen outerClass, string source, string arraySource, string arrayName, int i, MemberMapping mapping, string choiceSource) + internal Member(XmlSerializationReaderILGen outerClass, string source, string? arraySource, string? arrayName, int i, MemberMapping mapping, string? choiceSource) : this(outerClass, source, arraySource, arrayName, i, mapping, false, choiceSource) { } - internal Member(XmlSerializationReaderILGen outerClass, string source, string arrayName, int i, MemberMapping mapping, bool multiRef) + internal Member(XmlSerializationReaderILGen outerClass, string source, string? arrayName, int i, MemberMapping mapping, bool multiRef) : this(outerClass, source, null, arrayName, i, mapping, multiRef, null) { } - internal Member(XmlSerializationReaderILGen outerClass, string source, string arraySource, string arrayName, int i, MemberMapping mapping, bool multiRef, string choiceSource) + internal Member(XmlSerializationReaderILGen outerClass, string source, string? arraySource, string? arrayName, int i, MemberMapping mapping, bool multiRef, string? choiceSource) { _source = source; _arrayName = arrayName + "_" + i.ToString(CultureInfo.InvariantCulture); _choiceArrayName = "choice_" + _arrayName; _choiceSource = choiceSource; - if (mapping.TypeDesc.IsArrayLike) + if (mapping.TypeDesc!.IsArrayLike) { if (arraySource != null) _arraySource = arraySource; @@ -94,7 +94,7 @@ internal Member(XmlSerializationReaderILGen outerClass, string source, string ar string a = _choiceArrayName; string c = "c" + a; - string choiceTypeFullName = mapping.ChoiceIdentifier.Mapping.TypeDesc.CSharpName; + string choiceTypeFullName = mapping.ChoiceIdentifier.Mapping!.TypeDesc!.CSharpName; string castString = "(" + choiceTypeFullName + "[])"; string init = a + " = " + castString + @@ -156,19 +156,19 @@ internal int FixupIndex set { _fixupIndex = value; } } - internal string ParamsReadSource + internal string? ParamsReadSource { get { return _paramsReadSource; } set { _paramsReadSource = value; } } - internal string CheckSpecifiedSource + internal string? CheckSpecifiedSource { get { return _checkSpecifiedSource; } set { _checkSpecifiedSource = value; } } - internal string ChoiceSource + internal string? ChoiceSource { get { return _choiceSource; } } @@ -176,7 +176,7 @@ internal string ChoiceArrayName { get { return _choiceArrayName; } } - internal string ChoiceArraySource + internal string? ChoiceArraySource { get { return _choiceArraySource; } } @@ -200,7 +200,7 @@ internal void GenerateBegin() foreach (TypeMapping mapping in scope.TypeMappings) { if (mapping is StructMapping || mapping is EnumMapping || mapping is NullableMapping) - MethodNames.Add(mapping, NextMethodName(mapping.TypeDesc.Name)); + MethodNames.Add(mapping, NextMethodName(mapping.TypeDesc!.Name)); } RaCodeGen.WriteReflectionInit(scope); } @@ -237,17 +237,17 @@ internal void GenerateEnd(string[] methods, XmlMapping[] xmlMappings, Type[] typ "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_get_NameTable = typeof(XmlReader).GetMethod( "get_NameTable", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlNameTable_Add = typeof(XmlNameTable).GetMethod( "Add", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } - ); + )!; foreach (string id in _idNames.Keys) { ilg.Ldarg(0); @@ -263,11 +263,11 @@ internal void GenerateEnd(string[] methods, XmlMapping[] xmlMappings, Type[] typ this.typeBuilder.DefineDefaultConstructor( CodeGenerator.PublicMethodAttributes); - Type readerType = this.typeBuilder.CreateTypeInfo().AsType(); + Type readerType = this.typeBuilder.CreateTypeInfo()!.AsType(); CreatedTypes.Add(readerType.Name, readerType); } - internal string GenerateElement(XmlMapping xmlMapping) + internal string? GenerateElement(XmlMapping xmlMapping) { if (!xmlMapping.IsReadable) return null; @@ -281,7 +281,7 @@ internal string GenerateElement(XmlMapping xmlMapping) throw new ArgumentException(SR.XmlInternalError, nameof(xmlMapping)); } - private void WriteIsStartTag(string name, string ns) + private void WriteIsStartTag(string? name, string? ns) { WriteID(name); WriteID(ns); @@ -289,12 +289,12 @@ private void WriteIsStartTag(string name, string ns) "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_IsStartElement = typeof(XmlReader).GetMethod( "IsStartElement", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Ldarg(0); @@ -305,7 +305,7 @@ private void WriteIsStartTag(string name, string ns) ilg.If(); } - private void WriteUnknownNode(string func, string node, ElementAccessor e, bool anyIfs) + private void WriteUnknownNode(string func, string node, ElementAccessor? e, bool anyIfs) { if (anyIfs) { @@ -325,7 +325,7 @@ private void WriteUnknownNode(string func, string node, ElementAccessor e, bool argTypes.Add(typeof(object)); if (e != null) { - string expectedElement = e.Form == XmlSchemaForm.Qualified ? e.Namespace : ""; + string? expectedElement = e.Form == XmlSchemaForm.Qualified ? e.Namespace : ""; expectedElement += ":"; expectedElement += e.Name; ilg.Ldstr(ReflectionAwareILGen.GetCSharpString(expectedElement)); @@ -335,7 +335,7 @@ private void WriteUnknownNode(string func, string node, ElementAccessor e, bool func, CodeGenerator.InstanceBindingFlags, argTypes.ToArray() - ); + )!; ilg.Call(method); if (anyIfs) { @@ -358,7 +358,7 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) private string GetChoiceIdentifierSource(MemberMapping[] mappings, MemberMapping member) { - string choiceSource = null; + string? choiceSource = null; if (member.ChoiceIdentifier != null) { for (int j = 0; j < mappings.Length; j++) @@ -375,7 +375,7 @@ private string GetChoiceIdentifierSource(MemberMapping[] mappings, MemberMapping #endif } - return choiceSource; + return choiceSource!; } private string GetChoiceIdentifierSource(MemberMapping mapping, string parent, TypeDesc parentTypeDesc) @@ -388,7 +388,7 @@ private string GetChoiceIdentifierSource(MemberMapping mapping, string parent, T private string GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping) { ElementAccessor element = xmlMembersMapping.Accessor; - MemberMapping[] mappings = ((MembersMapping)element.Mapping).Members; + MemberMapping[] mappings = ((MembersMapping)element.Mapping!).Members!; bool hasWrapperElement = ((MembersMapping)element.Mapping).HasWrapperElement; string methodName = NextMethodName(element.Name); ilg = new CodeGenerator(this.typeBuilder); @@ -405,12 +405,12 @@ private string GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_MoveToContent = typeof(XmlReader).GetMethod( "MoveToContent", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_MoveToContent); @@ -427,9 +427,9 @@ private string GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping WriteIsStartTag(element.Name, element.Form == XmlSchemaForm.Qualified ? element.Namespace : ""); } - Member anyText = null; - Member anyElement = null; - Member anyAttribute = null; + Member? anyText = null; + Member? anyElement = null; + Member? anyAttribute = null; var membersList = new List(); var textOrArrayMembersList = new List(); @@ -442,7 +442,7 @@ private string GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping string arraySource = source; if (mapping.Xmlns != null) { - arraySource = "((" + mapping.TypeDesc.CSharpName + ")" + source + ")"; + arraySource = "((" + mapping.TypeDesc!.CSharpName + ")" + source + ")"; } string choiceSource = GetChoiceIdentifierSource(mappings, mapping); Member member = new Member(this, source, arraySource, "a", i, mapping, choiceSource); @@ -472,7 +472,7 @@ private string GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping if (!mapping.IsSequence) { - for (int j = 0; j < mapping.Elements.Length; j++) + for (int j = 0; j < mapping.Elements!.Length; j++) { if (mapping.Elements[j].Any && mapping.Elements[j].Name.Length == 0) { @@ -486,7 +486,7 @@ private string GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping } if (mapping.Attribute != null || mapping.Text != null || foundAnyElement) membersList.Add(anyMember); - else if (mapping.TypeDesc.IsArrayLike && !(mapping.Elements.Length == 1 && mapping.Elements[0].Mapping is ArrayMapping)) + else if (mapping.TypeDesc!.IsArrayLike && !(mapping.Elements!.Length == 1 && mapping.Elements[0].Mapping is ArrayMapping)) { membersList.Add(anyMember); textOrArrayMembersList.Add(anyMember); @@ -507,7 +507,7 @@ private string GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping "set_IsReturnValue", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(bool) } - ); + )!; ilg.Ldarg(0); ilg.Ldc(true); ilg.Call(XmlSerializationReader_set_IsReturnValue); @@ -525,7 +525,7 @@ private string GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping "MoveToElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_MoveToElement); @@ -540,7 +540,7 @@ private string GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping "get_IsEmptyElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_IsEmptyElement); @@ -550,7 +550,7 @@ private string GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping "Skip", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_Skip); @@ -565,7 +565,7 @@ private string GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping "ReadStartElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_ReadStartElement); @@ -594,7 +594,7 @@ private string GenerateLiteralMembersElement(XmlMembersMapping xmlMembersMapping "ReadEndElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_ReadEndElement); @@ -618,21 +618,21 @@ private void InitializeValueTypes(string arrayName, MemberMapping[] mappings) { for (int i = 0; i < mappings.Length; i++) { - if (!mappings[i].TypeDesc.IsValueType) + if (!mappings[i].TypeDesc!.IsValueType) continue; LocalBuilder arrayLoc = ilg.GetLocal(arrayName); ilg.Ldloc(arrayLoc); ilg.Ldc(i); - RaCodeGen.ILGenForCreateInstance(ilg, mappings[i].TypeDesc.Type, false, false); - ilg.ConvertValue(mappings[i].TypeDesc.Type, typeof(object)); - ilg.Stelem(arrayLoc.LocalType.GetElementType()); + RaCodeGen.ILGenForCreateInstance(ilg, mappings[i].TypeDesc!.Type!, false, false); + ilg.ConvertValue(mappings[i].TypeDesc!.Type!, typeof(object)); + ilg.Stelem(arrayLoc.LocalType.GetElementType()!); } } private string GenerateTypeElement(XmlTypeMapping xmlTypeMapping) { ElementAccessor element = xmlTypeMapping.Accessor; - TypeMapping mapping = element.Mapping; + TypeMapping mapping = element.Mapping!; string methodName = NextMethodName(element.Name); ilg = new CodeGenerator(this.typeBuilder); ilg.BeginMethod( @@ -654,12 +654,12 @@ private string GenerateTypeElement(XmlTypeMapping xmlTypeMapping) "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_MoveToContent = typeof(XmlReader).GetMethod( "MoveToContent", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_MoveToContent); @@ -690,14 +690,14 @@ private void WritePrimitive(TypeMapping mapping, string source) || source == "false" || source == "Reader.Value" || source == "vals[i]"); if (mapping is EnumMapping) { - string enumMethodName = ReferenceMapping(mapping); - if (enumMethodName == null) throw new InvalidOperationException(SR.Format(SR.XmlMissingMethodEnum, mapping.TypeDesc.Name)); + string? enumMethodName = ReferenceMapping(mapping); + if (enumMethodName == null) throw new InvalidOperationException(SR.Format(SR.XmlMissingMethodEnum, mapping.TypeDesc!.Name)); // For enum, its read method (eg. Read1_Gender) could be called multiple times // prior to its declaration. MethodBuilder methodBuilder = EnsureMethodBuilder(typeBuilder, enumMethodName, CodeGenerator.PrivateMethodAttributes, - mapping.TypeDesc.Type, + mapping.TypeDesc!.Type, new Type[] { typeof(string) } ); ilg.Ldarg(0); @@ -707,12 +707,12 @@ private void WritePrimitive(TypeMapping mapping, string source) "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_ReadXXXString = typeof(XmlReader).GetMethod( source == "Reader.ReadElementString()" ? "ReadElementContentAsString" : "ReadContentAsString", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_ReadXXXString); @@ -723,12 +723,12 @@ private void WritePrimitive(TypeMapping mapping, string source) "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_get_Value = typeof(XmlReader).GetMethod( "get_Value", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_Value); @@ -757,12 +757,12 @@ private void WritePrimitive(TypeMapping mapping, string source) "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_ReadXXXString = typeof(XmlReader).GetMethod( source == "Reader.ReadElementString()" ? "ReadElementContentAsString" : "ReadContentAsString", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_ReadXXXString); @@ -773,12 +773,12 @@ private void WritePrimitive(TypeMapping mapping, string source) "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_get_Value = typeof(XmlReader).GetMethod( "get_Value", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_Value); @@ -794,7 +794,7 @@ private void WritePrimitive(TypeMapping mapping, string source) throw Globals.NotSupported("Unexpected: " + source); } } - else if (mapping.TypeDesc.FormatterName == "String") + else if (mapping.TypeDesc!.FormatterName == "String") { System.Diagnostics.Debug.Assert(source == "Reader.Value" || source == "Reader.ReadElementString()" || source == "vals[i]"); if (source == "vals[i]") @@ -812,7 +812,7 @@ private void WritePrimitive(TypeMapping mapping, string source) null, new Type[] { typeof(string) }, null - ); + )!; ilg.Call(XmlSerializationReader_CollapseWhitespace); } } @@ -822,12 +822,12 @@ private void WritePrimitive(TypeMapping mapping, string source) "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_method = typeof(XmlReader).GetMethod( source == "Reader.Value" ? "get_Value" : "ReadElementContentAsString", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; if (mapping.TypeDesc.CollapseWhitespace) ilg.Ldarg(0); ilg.Ldarg(0); @@ -839,7 +839,7 @@ private void WritePrimitive(TypeMapping mapping, string source) "CollapseWhitespace", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } - ); + )!; ilg.Call(XmlSerializationReader_CollapseWhitespace); } } @@ -864,7 +864,7 @@ private void WritePrimitive(TypeMapping mapping, string source) "To" + mapping.TypeDesc.FormatterName, bindingFlags, new Type[] { argType } - ); + )!; } else { @@ -872,7 +872,7 @@ private void WritePrimitive(TypeMapping mapping, string source) "To" + mapping.TypeDesc.FormatterName, CodeGenerator.StaticBindingFlags, new Type[] { argType } - ); + )!; } if (source == "Reader.ReadElementString()" || source == "Reader.ReadString()") { @@ -880,12 +880,12 @@ private void WritePrimitive(TypeMapping mapping, string source) "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_ReadXXXString = typeof(XmlReader).GetMethod( source == "Reader.ReadElementString()" ? "ReadElementContentAsString" : "ReadContentAsString", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_ReadXXXString); @@ -896,12 +896,12 @@ private void WritePrimitive(TypeMapping mapping, string source) "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_get_Value = typeof(XmlReader).GetMethod( "get_Value", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_Value); @@ -921,10 +921,10 @@ private void WritePrimitive(TypeMapping mapping, string source) } } - private string MakeUnique(EnumMapping mapping, string name) + private string? MakeUnique(EnumMapping mapping, string name) { string uniqueName = name; - EnumMapping m; + EnumMapping? m; if (Enums.TryGetValue(uniqueName, out m)) { if (m == mapping) @@ -944,14 +944,14 @@ private string MakeUnique(EnumMapping mapping, string name) return uniqueName; } - private string WriteHashtable(EnumMapping mapping, string typeName, out MethodBuilder get_TableName) + private string WriteHashtable(EnumMapping mapping, string typeName, out MethodBuilder? get_TableName) { get_TableName = null; CodeIdentifier.CheckValidIdentifier(typeName); - string propName = MakeUnique(mapping, typeName + "Values"); + string? propName = MakeUnique(mapping, typeName + "Values"); if (propName == null) return CodeIdentifier.GetCSharpName(typeName); - string memberName = MakeUnique(mapping, "_" + propName); + string memberName = MakeUnique(mapping, "_" + propName)!; propName = CodeIdentifier.GetCSharpName(propName); FieldBuilder fieldBuilder = this.typeBuilder.DefineField( @@ -983,24 +983,24 @@ private string WriteHashtable(EnumMapping mapping, string typeName, out MethodBu ConstructorInfo Hashtable_ctor = typeof(Hashtable).GetConstructor( CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; LocalBuilder hLoc = ilg.DeclareLocal(typeof(Hashtable), "h"); ilg.New(Hashtable_ctor); ilg.Stloc(hLoc); - ConstantMapping[] constants = mapping.Constants; + ConstantMapping[] constants = mapping.Constants!; MethodInfo Hashtable_Add = typeof(Hashtable).GetMethod( "Add", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(object), typeof(object) } - ); + )!; for (int i = 0; i < constants.Length; i++) { ilg.Ldloc(hLoc); ilg.Ldstr(GetCSharpString(constants[i].XmlName)); - ilg.Ldc(Enum.ToObject(mapping.TypeDesc.Type, constants[i].Value)); - ilg.ConvertValue(mapping.TypeDesc.Type, typeof(long)); + ilg.Ldc(Enum.ToObject(mapping.TypeDesc!.Type!, constants[i].Value)); + ilg.ConvertValue(mapping.TypeDesc.Type!, typeof(long)); ilg.ConvertValue(typeof(long), typeof(object)); ilg.Call(Hashtable_Add); @@ -1016,38 +1016,38 @@ private string WriteHashtable(EnumMapping mapping, string typeName, out MethodBu ilg.LoadMember(fieldBuilder); get_TableName = ilg.EndMethod(); - propertyBuilder.SetGetMethod(get_TableName); + propertyBuilder.SetGetMethod(get_TableName!); return propName; } private void WriteEnumMethod(EnumMapping mapping) { - MethodBuilder get_TableName = null; + MethodBuilder? get_TableName = null; if (mapping.IsFlags) - WriteHashtable(mapping, mapping.TypeDesc.Name, out get_TableName); + WriteHashtable(mapping, mapping.TypeDesc!.Name, out get_TableName); - string methodName; + string? methodName; MethodNames.TryGetValue(mapping, out methodName); - string fullTypeName = mapping.TypeDesc.CSharpName; + string fullTypeName = mapping.TypeDesc!.CSharpName; List argTypes = new List(); List argNames = new List(); Type returnType; Type underlyingType; - returnType = mapping.TypeDesc.Type; + returnType = mapping.TypeDesc.Type!; underlyingType = Enum.GetUnderlyingType(returnType); argTypes.Add(typeof(string)); argNames.Add("s"); ilg = new CodeGenerator(this.typeBuilder); ilg.BeginMethod( returnType, - GetMethodBuilder(methodName), + GetMethodBuilder(methodName!), argTypes.ToArray(), argNames.ToArray(), CodeGenerator.PrivateMethodAttributes); - ConstantMapping[] constants = mapping.Constants; + ConstantMapping[] constants = mapping.Constants!; if (mapping.IsFlags) { { @@ -1055,7 +1055,7 @@ private void WriteEnumMethod(EnumMapping mapping) "ToEnum", CodeGenerator.StaticBindingFlags, new Type[] { typeof(string), typeof(Hashtable), typeof(string) } - ); + )!; ilg.Ldarg("s"); ilg.Ldarg(0); Debug.Assert(get_TableName != null); @@ -1098,11 +1098,11 @@ private void WriteEnumMethod(EnumMapping mapping) "op_Equality", CodeGenerator.StaticBindingFlags, new Type[] { typeof(string), typeof(string) } - ); + )!; ilg.Call(String_op_Equality); ilg.Brtrue(caseLabel); caseLabels.Add(caseLabel); - retValues.Add(Enum.ToObject(mapping.TypeDesc.Type, c.Value)); + retValues.Add(Enum.ToObject(mapping.TypeDesc.Type!, c.Value)); } } @@ -1119,13 +1119,13 @@ private void WriteEnumMethod(EnumMapping mapping) "CreateUnknownConstantException", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(Type) } - ); + )!; // Default body ilg.MarkLabel(defaultLabel); ilg.Ldarg(0); ilg.Ldarg("s"); // typeof(..) - ilg.Ldc(mapping.TypeDesc.Type); + ilg.Ldc(mapping.TypeDesc.Type!); ilg.Call(XmlSerializationReader_CreateUnknownConstantException); ilg.Throw(); // End switch @@ -1139,21 +1139,21 @@ private void WriteEnumMethod(EnumMapping mapping) private void WriteDerivedTypes(StructMapping mapping, bool isTypedReturn, string returnTypeName) { - for (StructMapping derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) + for (StructMapping? derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) { ilg.InitElseIf(); WriteQNameEqual("xsiType", derived.TypeName, derived.Namespace); ilg.AndIf(); - string methodName = ReferenceMapping(derived); + string? methodName = ReferenceMapping(derived); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe - if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, derived.TypeDesc.Name)); + if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, derived.TypeDesc!.Name)); #endif List argTypes = new List(); ilg.Ldarg(0); - if (derived.TypeDesc.IsNullable) + if (derived.TypeDesc!.IsNullable) { ilg.Ldarg("isNullable"); argTypes.Add(typeof(bool)); @@ -1192,37 +1192,37 @@ private void WriteEnumAndArrayTypes() "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_ReadStartElement = typeof(XmlReader).GetMethod( "ReadStartElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_ReadStartElement); - string methodName = ReferenceMapping(mapping); + string? methodName = ReferenceMapping(mapping); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe - if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc.Name)); + if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc!.Name)); #endif LocalBuilder eLoc = ilg.DeclareOrGetLocal(typeof(object), "e"); MethodBuilder methodBuilder = EnsureMethodBuilder(typeBuilder, methodName, CodeGenerator.PrivateMethodAttributes, - mapping.TypeDesc.Type, + mapping.TypeDesc!.Type, new Type[] { typeof(string) } ); MethodInfo XmlSerializationReader_CollapseWhitespace = typeof(XmlSerializationReader).GetMethod( "CollapseWhitespace", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } - ); + )!; MethodInfo XmlReader_ReadString = typeof(XmlReader).GetMethod( "ReadContentAsString", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Ldarg(0); ilg.Ldarg(0); @@ -1236,7 +1236,7 @@ private void WriteEnumAndArrayTypes() "ReadEndElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_ReadEndElement); ilg.Ldloc(eLoc); @@ -1247,7 +1247,7 @@ private void WriteEnumAndArrayTypes() else if (m is ArrayMapping) { ArrayMapping mapping = (ArrayMapping)m; - if (mapping.TypeDesc.HasDefaultConstructor) + if (mapping.TypeDesc!.HasDefaultConstructor) { ilg.InitElseIf(); WriteQNameEqual("xsiType", mapping.TypeName, mapping.Namespace); @@ -1261,10 +1261,10 @@ private void WriteEnumAndArrayTypes() Member member = new Member(this, aVar, zVar, 0, memberMapping); TypeDesc td = mapping.TypeDesc; - LocalBuilder aLoc = ilg.DeclareLocal(mapping.TypeDesc.Type, aVar); + LocalBuilder aLoc = ilg.DeclareLocal(mapping.TypeDesc.Type!, aVar); if (mapping.TypeDesc.IsValueType) { - RaCodeGen.ILGenForCreateInstance(ilg, td.Type, false, false); + RaCodeGen.ILGenForCreateInstance(ilg, td.Type!, false, false); } else ilg.Load(null); @@ -1284,24 +1284,24 @@ private void WriteEnumAndArrayTypes() private void WriteNullableMethod(NullableMapping nullableMapping) { - string methodName; + string? methodName; MethodNames.TryGetValue(nullableMapping, out methodName); ilg = new CodeGenerator(this.typeBuilder); ilg.BeginMethod( - nullableMapping.TypeDesc.Type, - GetMethodBuilder(methodName), + nullableMapping.TypeDesc!.Type!, + GetMethodBuilder(methodName!), new Type[] { typeof(bool) }, new string[] { "checkType" }, CodeGenerator.PrivateMethodAttributes); - LocalBuilder oLoc = ilg.DeclareLocal(nullableMapping.TypeDesc.Type, "o"); + LocalBuilder oLoc = ilg.DeclareLocal(nullableMapping.TypeDesc.Type!, "o"); ilg.LoadAddress(oLoc); - ilg.InitObj(nullableMapping.TypeDesc.Type); + ilg.InitObj(nullableMapping.TypeDesc.Type!); MethodInfo XmlSerializationReader_ReadNull = typeof(XmlSerializationReader).GetMethod( "ReadNull", CodeGenerator.InstanceBindingFlags, - Array.Empty()); + Array.Empty())!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_ReadNull); ilg.If(); @@ -1315,7 +1315,7 @@ private void WriteNullableMethod(NullableMapping nullableMapping) ElementAccessor element = new ElementAccessor(); element.Mapping = nullableMapping.BaseMapping; element.Any = false; - element.IsNullable = nullableMapping.BaseMapping.TypeDesc.IsNullable; + element.IsNullable = nullableMapping.BaseMapping!.TypeDesc!.IsNullable; WriteElement("o", null, null, element, null, null, false, false, -1, -1); ilg.Ldloc(oLoc); @@ -1334,9 +1334,9 @@ private void WriteStructMethod(StructMapping structMapping) private void WriteLiteralStructMethod(StructMapping structMapping) { - string methodName; + string? methodName; MethodNames.TryGetValue(structMapping, out methodName); - string typeName = structMapping.TypeDesc.CSharpName; + string typeName = structMapping.TypeDesc!.CSharpName; ilg = new CodeGenerator(this.typeBuilder); List argTypes = new List(); List argNames = new List(); @@ -1348,8 +1348,8 @@ private void WriteLiteralStructMethod(StructMapping structMapping) argTypes.Add(typeof(bool)); argNames.Add("checkType"); ilg.BeginMethod( - structMapping.TypeDesc.Type, - GetMethodBuilder(methodName), + structMapping.TypeDesc.Type!, + GetMethodBuilder(methodName!), argTypes.ToArray(), argNames.ToArray(), CodeGenerator.PrivateMethodAttributes); @@ -1360,12 +1360,12 @@ private void WriteLiteralStructMethod(StructMapping structMapping) "GetXsiType", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlSerializationReader_ReadNull = typeof(XmlSerializationReader).GetMethod( "ReadNull", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; Label labelTrue = ilg.DefineLabel(); Label labelEnd = ilg.DefineLabel(); ilg.Ldarg("checkType"); @@ -1404,7 +1404,7 @@ private void WriteLiteralStructMethod(StructMapping structMapping) "ReadTypedNull", CodeGenerator.InstanceBindingFlags, new Type[] { locXsiType.LocalType } - ); + )!; ilg.Ldarg(0); ilg.Ldloc(locXsiType); ilg.Call(XmlSerializationReader_ReadTypedNull); @@ -1447,12 +1447,12 @@ private void WriteLiteralStructMethod(StructMapping structMapping) ConstructorInfo XmlQualifiedName_ctor = typeof(XmlQualifiedName).GetConstructor( CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string) } - ); + )!; MethodInfo XmlSerializationReader_ReadTypedPrimitive = typeof(XmlSerializationReader).GetMethod( "ReadTypedPrimitive", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(XmlQualifiedName) } - ); + )!; ilg.Ldarg(0); ilg.Ldstr(Soap.UrType); ilg.Ldstr(XmlSchema.Namespace); @@ -1470,7 +1470,7 @@ private void WriteLiteralStructMethod(StructMapping structMapping) "ReadTypedPrimitive", CodeGenerator.InstanceBindingFlags, new Type[] { locXsiType.LocalType } - ); + )!; ilg.Ldarg(0); ilg.Ldloc(locXsiType); ilg.Call(XmlSerializationReader_ReadTypedPrimitive); @@ -1483,7 +1483,7 @@ private void WriteLiteralStructMethod(StructMapping structMapping) "CreateUnknownTypeException", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(XmlQualifiedName) } - ); + )!; ilg.Ldarg(0); ilg.Ldloc(locXsiType); ilg.Call(XmlSerializationReader_CreateUnknownTypeException); @@ -1510,7 +1510,7 @@ private void WriteLiteralStructMethod(StructMapping structMapping) "CreateAbstractTypeException", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Ldstr(GetCSharpString(structMapping.TypeName)); ilg.Ldstr(GetCSharpString(structMapping.Namespace)); @@ -1525,7 +1525,7 @@ private void WriteLiteralStructMethod(StructMapping structMapping) "set_DecodeName", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(bool) } - ); + )!; ilg.Ldarg(0); ilg.Ldc(false); ilg.Call(XmlSerializationReader_set_DecodeName); @@ -1536,9 +1536,9 @@ private void WriteLiteralStructMethod(StructMapping structMapping) // this method populates the memberInfos dictionary based on the structMapping MemberMapping[] mappings = TypeScope.GetSettableMembers(structMapping, memberInfos); - Member anyText = null; - Member anyElement = null; - Member anyAttribute = null; + Member? anyText = null; + Member? anyElement = null; + Member? anyAttribute = null; bool isSequence = structMapping.HasExplicitSequence(); var arraysToDeclareList = new List(mappings.Length); @@ -1553,7 +1553,7 @@ private void WriteLiteralStructMethod(StructMapping structMapping) Member member = new Member(this, source, "a", i, mapping, GetChoiceIdentifierSource(mapping, "o", structMapping.TypeDesc)); if (!mapping.IsSequence) member.ParamsReadSource = "paramsRead[" + i.ToString(CultureInfo.InvariantCulture) + "]"; - member.IsNullable = mapping.TypeDesc.IsNullable; + member.IsNullable = mapping.TypeDesc!.IsNullable; if (mapping.CheckSpecified == SpecifiedAccessor.ReadWrite) member.CheckSpecifiedSource = RaCodeGen.GetStringForMember("o", mapping.Name + "Specified", structMapping.TypeDesc); if (mapping.Text != null) @@ -1563,7 +1563,7 @@ private void WriteLiteralStructMethod(StructMapping structMapping) if (!isSequence) { // find anyElement if present. - for (int j = 0; j < mapping.Elements.Length; j++) + for (int j = 0; j < mapping.Elements!.Length; j++) { if (mapping.Elements[j].Any && (mapping.Elements[j].Name == null || mapping.Elements[j].Name.Length == 0)) { @@ -1574,11 +1574,11 @@ private void WriteLiteralStructMethod(StructMapping structMapping) } else if (mapping.IsParticle && !mapping.IsSequence) { - StructMapping declaringMapping; + StructMapping? declaringMapping; structMapping.FindDeclaringMapping(mapping, out declaringMapping, structMapping.TypeName); - throw new InvalidOperationException(SR.Format(SR.XmlSequenceHierarchy, structMapping.TypeDesc.FullName, mapping.Name, declaringMapping.TypeDesc.FullName, "Order")); + throw new InvalidOperationException(SR.Format(SR.XmlSequenceHierarchy, structMapping.TypeDesc.FullName, mapping.Name, declaringMapping!.TypeDesc!.FullName, "Order")); } - if (mapping.Attribute == null && mapping.Elements.Length == 1 && mapping.Elements[0].Mapping is ArrayMapping) + if (mapping.Attribute == null && mapping.Elements!.Length == 1 && mapping.Elements[0].Mapping is ArrayMapping) { Member arrayMember = new Member(this, source, source, "a", i, mapping, GetChoiceIdentifierSource(mapping, "o", structMapping.TypeDesc)); arrayMember.CheckSpecifiedSource = member.CheckSpecifiedSource; @@ -1592,7 +1592,7 @@ private void WriteLiteralStructMethod(StructMapping structMapping) if (mapping.TypeDesc.IsArrayLike) { arraysToDeclareList.Add(member); - if (mapping.TypeDesc.IsArrayLike && !(mapping.Elements.Length == 1 && mapping.Elements[0].Mapping is ArrayMapping)) + if (mapping.TypeDesc.IsArrayLike && !(mapping.Elements!.Length == 1 && mapping.Elements[0].Mapping is ArrayMapping)) { member.ParamsReadSource = null; // flat arrays -- don't want to count params read. if (member != anyText && member != anyElement) @@ -1624,12 +1624,12 @@ private void WriteLiteralStructMethod(StructMapping structMapping) "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_MoveToElement = typeof(XmlReader).GetMethod( "MoveToElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_MoveToElement); @@ -1639,7 +1639,7 @@ private void WriteLiteralStructMethod(StructMapping structMapping) "get_IsEmptyElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_IsEmptyElement); @@ -1648,7 +1648,7 @@ private void WriteLiteralStructMethod(StructMapping structMapping) "Skip", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_Skip); @@ -1662,7 +1662,7 @@ private void WriteLiteralStructMethod(StructMapping structMapping) "ReadStartElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_ReadStartElement); @@ -1678,7 +1678,7 @@ private void WriteLiteralStructMethod(StructMapping structMapping) "MoveToContent", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_MoveToContent); @@ -1691,10 +1691,10 @@ private void WriteLiteralStructMethod(StructMapping structMapping) "ReadEndElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_ReadEndElement); - ilg.Ldloc(structMapping.TypeDesc.Type, "o"); + ilg.Ldloc(structMapping.TypeDesc.Type!, "o"); ilg.Stloc(ilg.ReturnLocal); } ilg.MarkLabel(ilg.ReturnLabel); @@ -1702,7 +1702,7 @@ private void WriteLiteralStructMethod(StructMapping structMapping) ilg.EndMethod(); } - private void WriteQNameEqual(string source, string name, string ns) + private void WriteQNameEqual(string source, string? name, string? ns) { WriteID(name); WriteID(ns); @@ -1712,12 +1712,12 @@ private void WriteQNameEqual(string source, string name, string ns) "get_Name", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlQualifiedName_get_Namespace = typeof(XmlQualifiedName).GetMethod( "get_Namespace", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; Label labelEnd = ilg.DefineLabel(); Label labelFalse = ilg.DefineLabel(); LocalBuilder sLoc = ilg.GetLocal(source); @@ -1737,11 +1737,11 @@ private void WriteQNameEqual(string source, string name, string ns) ilg.MarkLabel(labelEnd); } - private void WriteXmlNodeEqual(string source, string name, string ns) + private void WriteXmlNodeEqual(string source, string name, string? ns) { WriteXmlNodeEqual(source, name, ns, true); } - private void WriteXmlNodeEqual(string source, string name, string ns, bool doAndIf) + private void WriteXmlNodeEqual(string source, string name, string? ns, bool doAndIf) { bool isNameNullOrEmpty = string.IsNullOrEmpty(name); if (!isNameNullOrEmpty) @@ -1755,17 +1755,17 @@ private void WriteXmlNodeEqual(string source, string name, string ns, bool doAnd "get_" + source, CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_get_LocalName = typeof(XmlReader).GetMethod( "get_LocalName", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_get_NamespaceURI = typeof(XmlReader).GetMethod( "get_NamespaceURI", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; Label labelFalse = ilg.DefineLabel(); Label labelEnd = ilg.DefineLabel(); @@ -1798,7 +1798,7 @@ private void WriteXmlNodeEqual(string source, string name, string ns, bool doAnd ilg.AndIf(); } - private void WriteID(string name) + private void WriteID(string? name) { if (name == null) { @@ -1806,7 +1806,7 @@ private void WriteID(string name) //return; name = ""; } - string idName; + string? idName; if (!_idNames.TryGetValue(name, out idName)) { idName = NextIdName(name); @@ -1815,10 +1815,10 @@ private void WriteID(string name) } } - private void WriteAttributes(Member[] members, Member anyAttribute, string elseCall, LocalBuilder firstParam) + private void WriteAttributes(Member[] members, Member? anyAttribute, string elseCall, LocalBuilder firstParam) { int count = 0; - Member xmlnsMember = null; + Member? xmlnsMember = null; var attributes = new List(); // Condition do at the end, so C# looks the same @@ -1826,12 +1826,12 @@ private void WriteAttributes(Member[] members, Member anyAttribute, string elseC "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_MoveToNextAttribute = typeof(XmlReader).GetMethod( "MoveToNextAttribute", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.WhileBegin(); for (int i = 0; i < members.Length; i++) @@ -1844,7 +1844,8 @@ private void WriteAttributes(Member[] members, Member anyAttribute, string elseC } if (member.Mapping.Ignore) continue; - AttributeAccessor attribute = member.Mapping.Attribute; + + AttributeAccessor? attribute = member.Mapping.Attribute; if (attribute == null) continue; if (attribute.Any) continue; @@ -1884,22 +1885,22 @@ private void WriteAttributes(Member[] members, Member anyAttribute, string elseC "IsXmlnsAttribute", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } - ); + )!; MethodInfo XmlReader_get_Name = typeof(XmlReader).GetMethod( "get_Name", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_get_LocalName = typeof(XmlReader).GetMethod( "get_LocalName", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_get_Value = typeof(XmlReader).GetMethod( "get_Value", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); @@ -1912,26 +1913,26 @@ private void WriteAttributes(Member[] members, Member anyAttribute, string elseC ilg.Load(null); ilg.If(Cmp.EqualTo); WriteSourceBegin(xmlnsMember.Source); - ConstructorInfo ctor = xmlnsMember.Mapping.TypeDesc.Type.GetConstructor( + ConstructorInfo ctor = xmlnsMember.Mapping.TypeDesc!.Type!.GetConstructor( CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.New(ctor); - WriteSourceEnd(xmlnsMember.Source, xmlnsMember.Mapping.TypeDesc.Type); + WriteSourceEnd(xmlnsMember.Source, xmlnsMember.Mapping.TypeDesc.Type!); ilg.EndIf(); // if (xmlnsMember.Source == null Label labelEqual5 = ilg.DefineLabel(); Label labelEndLength = ilg.DefineLabel(); - MethodInfo Add = xmlnsMember.Mapping.TypeDesc.Type.GetMethod( + MethodInfo Add = xmlnsMember.Mapping.TypeDesc.Type!.GetMethod( "Add", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string) } - ); + )!; MethodInfo String_get_Length = typeof(string).GetMethod( "get_Length", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ILGenLoad(xmlnsMember.ArraySource, xmlnsMember.Mapping.TypeDesc.Type); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); @@ -1959,12 +1960,12 @@ private void WriteAttributes(Member[] members, Member anyAttribute, string elseC "IsXmlnsAttribute", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } - ); + )!; MethodInfo XmlReader_get_Name = typeof(XmlReader).GetMethod( "get_Name", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); @@ -1980,12 +1981,12 @@ private void WriteAttributes(Member[] members, Member anyAttribute, string elseC "get_Document", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlDocument_ReadNode = typeof(XmlDocument).GetMethod( "ReadNode", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(XmlReader) } - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Document); ilg.Ldarg(0); @@ -1997,7 +1998,7 @@ private void WriteAttributes(Member[] members, Member anyAttribute, string elseC "ParseWsdlArrayType", CodeGenerator.InstanceBindingFlags, new Type[] { localAttr.LocalType } - ); + )!; ilg.Ldarg(0); ilg.Ldloc(localAttr); ilg.Call(XmlSerializationReader_ParseWsdlArrayType); @@ -2029,7 +2030,7 @@ private void WriteAttributes(Member[] members, Member anyAttribute, string elseC elseCall, CodeGenerator.InstanceBindingFlags, argTypes.ToArray() - ); + )!; ilg.Call(elseCallMethod); } ilg.EndIf(); @@ -2046,17 +2047,17 @@ private void WriteAttributes(Member[] members, Member anyAttribute, string elseC private void WriteAttribute(Member member) { - AttributeAccessor attribute = member.Mapping.Attribute; + AttributeAccessor attribute = member.Mapping.Attribute!; if (attribute.Mapping is SpecialMapping) { SpecialMapping special = (SpecialMapping)attribute.Mapping; - if (special.TypeDesc.Kind == TypeKind.Attribute) + if (special.TypeDesc!.Kind == TypeKind.Attribute) { WriteSourceBegin(member.ArraySource); ilg.Ldloc("attr"); - WriteSourceEnd(member.ArraySource, member.Mapping.TypeDesc.IsArrayLike ? member.Mapping.TypeDesc.ArrayElementTypeDesc.Type : member.Mapping.TypeDesc.Type); + WriteSourceEnd(member.ArraySource, member.Mapping.TypeDesc!.IsArrayLike ? member.Mapping.TypeDesc.ArrayElementTypeDesc!.Type! : member.Mapping.TypeDesc.Type!); } else if (special.TypeDesc.CanBeAttributeValue) { @@ -2074,7 +2075,7 @@ private void WriteAttribute(Member member) WriteSourceBegin(member.ArraySource); ilg.Ldloc(attrLoc); ilg.ConvertValue(attrLoc.LocalType, typeof(XmlAttribute)); - WriteSourceEnd(member.ArraySource, member.Mapping.TypeDesc.IsArrayLike ? member.Mapping.TypeDesc.ArrayElementTypeDesc.Type : member.Mapping.TypeDesc.Type); + WriteSourceEnd(member.ArraySource, member.Mapping.TypeDesc!.IsArrayLike ? member.Mapping.TypeDesc.ArrayElementTypeDesc!.Type! : member.Mapping.TypeDesc.Type!); ilg.EndIf(); } else @@ -2090,17 +2091,17 @@ private void WriteAttribute(Member member) "Split", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(char[]) } - ); + )!; MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_get_Value = typeof(XmlReader).GetMethod( "get_Value", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_Value); @@ -2112,18 +2113,18 @@ private void WriteAttribute(Member member) LocalBuilder localI = ilg.DeclareOrGetLocal(typeof(int), "i"); ilg.For(localI, 0, locVals); - string attributeSource = GetArraySource(member.Mapping.TypeDesc, member.ArrayName); + string attributeSource = GetArraySource(member.Mapping.TypeDesc!, member.ArrayName); WriteSourceBegin(attributeSource); - WritePrimitive(attribute.Mapping, "vals[i]"); - WriteSourceEnd(attributeSource, member.Mapping.TypeDesc.ArrayElementTypeDesc.Type); + WritePrimitive(attribute.Mapping!, "vals[i]"); + WriteSourceEnd(attributeSource, member.Mapping.TypeDesc!.ArrayElementTypeDesc!.Type!); ilg.EndFor(); } else { WriteSourceBegin(member.ArraySource); - WritePrimitive(attribute.Mapping, attribute.IsList ? "vals[i]" : "Reader.Value"); - WriteSourceEnd(member.ArraySource, member.Mapping.TypeDesc.IsArrayLike ? member.Mapping.TypeDesc.ArrayElementTypeDesc.Type : member.Mapping.TypeDesc.Type); + WritePrimitive(attribute.Mapping!, attribute.IsList ? "vals[i]" : "Reader.Value"); + WriteSourceEnd(member.ArraySource, member.Mapping.TypeDesc!.IsArrayLike ? member.Mapping.TypeDesc.ArrayElementTypeDesc!.Type! : member.Mapping.TypeDesc.Type!); } } if (member.Mapping.CheckSpecified == SpecifiedAccessor.ReadWrite && member.CheckSpecifiedSource != null && member.CheckSpecifiedSource.Length > 0) @@ -2147,9 +2148,9 @@ private void WriteMemberBegin(Member[] members) string a = member.ArrayName; string c = "c" + a; - TypeDesc typeDesc = member.Mapping.TypeDesc; + TypeDesc typeDesc = member.Mapping.TypeDesc!; - if (member.Mapping.TypeDesc.IsArray) + if (member.Mapping.TypeDesc!.IsArray) { WriteArrayLocalDecl(typeDesc.CSharpName, a, "null", typeDesc); @@ -2158,7 +2159,7 @@ private void WriteMemberBegin(Member[] members) if (member.Mapping.ChoiceIdentifier != null) { - WriteArrayLocalDecl(member.Mapping.ChoiceIdentifier.Mapping.TypeDesc.CSharpName + "[]", + WriteArrayLocalDecl(member.Mapping.ChoiceIdentifier.Mapping!.TypeDesc!.CSharpName + "[]", member.ChoiceArrayName, "null", member.Mapping.ChoiceIdentifier.Mapping.TypeDesc); ilg.Ldc(0); @@ -2169,10 +2170,10 @@ private void WriteMemberBegin(Member[] members) { if (member.Source[member.Source.Length - 1] == '(' || member.Source[member.Source.Length - 1] == '{') { - WriteCreateInstance(a, typeDesc.CannotNew, typeDesc.Type); + WriteCreateInstance(a, typeDesc.CannotNew, typeDesc.Type!); WriteSourceBegin(member.Source); ilg.Ldloc(ilg.GetLocal(a)); - WriteSourceEnd(member.Source, typeDesc.Type); + WriteSourceEnd(member.Source, typeDesc.Type!); } else { @@ -2188,7 +2189,7 @@ private void WriteMemberBegin(Member[] members) "CreateReadOnlyCollectionException", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Ldstr(GetCSharpString(member.Mapping.TypeDesc.CSharpName)); ilg.Call(XmlSerializationReader_CreateReadOnlyCollectionException); @@ -2197,8 +2198,8 @@ private void WriteMemberBegin(Member[] members) else { WriteSourceBegin(member.Source); - RaCodeGen.ILGenForCreateInstance(ilg, member.Mapping.TypeDesc.Type, typeDesc.CannotNew, true); - WriteSourceEnd(member.Source, member.Mapping.TypeDesc.Type); + RaCodeGen.ILGenForCreateInstance(ilg, member.Mapping.TypeDesc.Type!, typeDesc.CannotNew, true); + WriteSourceEnd(member.Source, member.Mapping.TypeDesc.Type!); } ilg.EndIf(); // if ((object)(member.Source) == null } @@ -2225,12 +2226,12 @@ private string ExpectedElements(Member[] members) if (member.Mapping.IsText || member.Mapping.IsAttribute) continue; - ElementAccessor[] elements = member.Mapping.Elements; + ElementAccessor[] elements = member.Mapping.Elements!; for (int j = 0; j < elements.Length; j++) { ElementAccessor e = elements[j]; - string ns = e.Form == XmlSchemaForm.Qualified ? e.Namespace : ""; + string? ns = e.Form == XmlSchemaForm.Qualified ? e.Namespace : ""; if (e.Any && (e.Name == null || e.Name.Length == 0)) continue; if (!firstElement) @@ -2242,7 +2243,7 @@ private string ExpectedElements(Member[] members) return ReflectionAwareILGen.GetQuotedCSharpString(qnames); } - private void WriteMemberElements(Member[] members, string elementElseString, string elseString, Member anyElement, Member anyText) + private void WriteMemberElements(Member[] members, string elementElseString, string elseString, Member? anyElement, Member? anyText) { if (anyText != null) { @@ -2254,12 +2255,12 @@ private void WriteMemberElements(Member[] members, string elementElseString, str "get_NodeType", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; int XmlNodeType_Element = 1; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); @@ -2286,12 +2287,12 @@ private void WriteMemberText(Member anyText, string elseString) "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_get_NodeType = typeof(XmlReader).GetMethod( "get_NodeType", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_NodeType); @@ -2330,35 +2331,35 @@ private void WriteMemberText(Member anyText, string elseString) private void WriteText(Member member) { - TextAccessor text = member.Mapping.Text; + TextAccessor text = member.Mapping.Text!; if (text.Mapping is SpecialMapping) { SpecialMapping special = (SpecialMapping)text.Mapping; WriteSourceBeginTyped(member.ArraySource, special.TypeDesc); - switch (special.TypeDesc.Kind) + switch (special.TypeDesc!.Kind) { case TypeKind.Node: MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_ReadString = typeof(XmlReader).GetMethod( "ReadContentAsString", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlSerializationReader_get_Document = typeof(XmlSerializationReader).GetMethod( "get_Document", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlDocument_CreateTextNode = typeof(XmlDocument).GetMethod( "CreateTextNode", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Document); ilg.Ldarg(0); @@ -2369,14 +2370,14 @@ private void WriteText(Member member) default: throw new InvalidOperationException(SR.XmlInternalError); } - WriteSourceEnd(member.ArraySource, special.TypeDesc.Type); + WriteSourceEnd(member.ArraySource, special.TypeDesc.Type!); } else { if (member.IsArrayLike) { WriteSourceBegin(member.ArraySource); - if (text.Mapping.TypeDesc.CollapseWhitespace) + if (text.Mapping!.TypeDesc!.CollapseWhitespace) { ilg.Ldarg(0); // for calling CollapseWhitespace } @@ -2387,12 +2388,12 @@ private void WriteText(Member member) "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_ReadString = typeof(XmlReader).GetMethod( "ReadContentAsString", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_ReadString); @@ -2402,23 +2403,23 @@ private void WriteText(Member member) "CollapseWhitespace", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } - ); + )!; ilg.Call(XmlSerializationReader_CollapseWhitespace); } } else { - if (text.Mapping.TypeDesc == StringTypeDesc || text.Mapping.TypeDesc.FormatterName == "String") + if (text.Mapping!.TypeDesc == StringTypeDesc || text.Mapping.TypeDesc!.FormatterName == "String") { LocalBuilder tmpLoc = ilg.GetLocal("tmp"); MethodInfo XmlSerializationReader_ReadString = typeof(XmlSerializationReader).GetMethod( "ReadString", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(bool) } - ); + )!; ilg.Ldarg(0); ilg.Ldloc(tmpLoc); - ilg.Ldc(text.Mapping.TypeDesc.CollapseWhitespace); + ilg.Ldc(text.Mapping.TypeDesc!.CollapseWhitespace); ilg.Call(XmlSerializationReader_ReadString); ilg.Stloc(tmpLoc); @@ -2431,16 +2432,16 @@ private void WriteText(Member member) WritePrimitive(text.Mapping, "Reader.ReadString()"); } } - WriteSourceEnd(member.ArraySource, text.Mapping.TypeDesc.Type); + WriteSourceEnd(member.ArraySource, text.Mapping.TypeDesc.Type!); } } - private void WriteMemberElementsElse(Member anyElement, string elementElseString) + private void WriteMemberElementsElse(Member? anyElement, string elementElseString) { if (anyElement != null) { - ElementAccessor[] elements = anyElement.Mapping.Elements; + ElementAccessor[] elements = anyElement.Mapping.Elements!; for (int i = 0; i < elements.Length; i++) { ElementAccessor element = elements[i]; @@ -2466,7 +2467,7 @@ private bool IsSequence(Member[] members) } return false; } - private void WriteMemberElementsIf(Member[] members, Member anyElement, string elementElseString) + private void WriteMemberElementsIf(Member[] members, Member? anyElement, string elementElseString) { int count = 0; @@ -2484,13 +2485,13 @@ private void WriteMemberElementsIf(Member[] members, Member anyElement, string e continue; bool firstElement = true; - ChoiceIdentifierAccessor choice = member.Mapping.ChoiceIdentifier; - ElementAccessor[] elements = member.Mapping.Elements; + ChoiceIdentifierAccessor? choice = member.Mapping.ChoiceIdentifier; + ElementAccessor[] elements = member.Mapping.Elements!; for (int j = 0; j < elements.Length; j++) { ElementAccessor e = elements[j]; - string ns = e.Form == XmlSchemaForm.Qualified ? e.Namespace : ""; + string? ns = e.Form == XmlSchemaForm.Qualified ? e.Namespace : ""; if (!isSequence && e.Any && (e.Name == null || e.Name.Length == 0)) continue; if (!firstElement || (!isSequence && count > 0)) { @@ -2527,7 +2528,7 @@ private void WriteMemberElementsIf(Member[] members, Member anyElement, string e "get_IsReturnValue", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_IsReturnValue); ilg.Brtrue(labelTrue); @@ -2549,14 +2550,14 @@ private void WriteMemberElementsIf(Member[] members, Member anyElement, string e } ilg.AndIf(); - WriteElement(member.ArraySource, member.ArrayName, member.ChoiceArraySource, e, choice, member.Mapping.CheckSpecified == SpecifiedAccessor.ReadWrite ? member.CheckSpecifiedSource : null, member.IsList && member.Mapping.TypeDesc.IsNullable, member.Mapping.ReadOnly, member.FixupIndex, j); + WriteElement(member.ArraySource, member.ArrayName, member.ChoiceArraySource, e, choice, member.Mapping.CheckSpecified == SpecifiedAccessor.ReadWrite ? member.CheckSpecifiedSource : null, member.IsList && member.Mapping.TypeDesc!.IsNullable, member.Mapping.ReadOnly, member.FixupIndex, j); if (member.Mapping.IsReturnValue) { MethodInfo XmlSerializationReader_set_IsReturnValue = typeof(XmlSerializationReader).GetMethod( "set_IsReturnValue", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(bool) } - ); + )!; ilg.Ldarg(0); ilg.Ldc(false); ilg.Call(XmlSerializationReader_set_IsReturnValue); @@ -2612,7 +2613,7 @@ private string GetArraySource(TypeDesc typeDesc, string arrayName, bool multiRef } if (typeDesc.IsArray) { - string arrayTypeFullName = typeDesc.ArrayElementTypeDesc.CSharpName; + string arrayTypeFullName = typeDesc.ArrayElementTypeDesc!.CSharpName; string castString = "(" + arrayTypeFullName + "[])"; init = init + a + " = " + castString + "EnsureArrayIndex(" + a + ", " + c + ", " + RaCodeGen.GetStringForTypeof(arrayTypeFullName) + ");"; @@ -2644,7 +2645,7 @@ private void WriteMemberEnd(Member[] members, bool soapRefs) if (member.IsArrayLike) { - TypeDesc typeDesc = member.Mapping.TypeDesc; + TypeDesc typeDesc = member.Mapping.TypeDesc!; if (typeDesc.IsArray) { @@ -2659,30 +2660,30 @@ private void WriteMemberEnd(Member[] members, bool soapRefs) "ShrinkArray", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(Array), typeof(int), typeof(Type), typeof(bool) } - ); + )!; ilg.Ldarg(0); ilg.Ldloc(ilg.GetLocal(a)); ilg.Ldloc(ilg.GetLocal(c)); - ilg.Ldc(typeDesc.ArrayElementTypeDesc.Type); + ilg.Ldc(typeDesc.ArrayElementTypeDesc!.Type!); ilg.Ldc(member.IsNullable); ilg.Call(XmlSerializationReader_ShrinkArray); - ilg.ConvertValue(XmlSerializationReader_ShrinkArray.ReturnType, typeDesc.Type); - WriteSourceEnd(member.Source, typeDesc.Type); + ilg.ConvertValue(XmlSerializationReader_ShrinkArray.ReturnType, typeDesc.Type!); + WriteSourceEnd(member.Source, typeDesc.Type!); if (member.Mapping.ChoiceIdentifier != null) { - WriteSourceBegin(member.ChoiceSource); + WriteSourceBegin(member.ChoiceSource!); a = member.ChoiceArrayName; c = "c" + a; ilg.Ldarg(0); ilg.Ldloc(ilg.GetLocal(a)); ilg.Ldloc(ilg.GetLocal(c)); - ilg.Ldc(member.Mapping.ChoiceIdentifier.Mapping.TypeDesc.Type); + ilg.Ldc(member.Mapping.ChoiceIdentifier.Mapping!.TypeDesc!.Type!); ilg.Ldc(member.IsNullable); ilg.Call(XmlSerializationReader_ShrinkArray); - ilg.ConvertValue(XmlSerializationReader_ShrinkArray.ReturnType, member.Mapping.ChoiceIdentifier.Mapping.TypeDesc.Type.MakeArrayType()); - WriteSourceEnd(member.ChoiceSource, member.Mapping.ChoiceIdentifier.Mapping.TypeDesc.Type.MakeArrayType()); + ilg.ConvertValue(XmlSerializationReader_ShrinkArray.ReturnType, member.Mapping.ChoiceIdentifier.Mapping.TypeDesc.Type!.MakeArrayType()); + WriteSourceEnd(member.ChoiceSource!, member.Mapping.ChoiceIdentifier.Mapping.TypeDesc.Type!.MakeArrayType()); } } else if (typeDesc.IsValueType) @@ -2696,14 +2697,14 @@ private void WriteMemberEnd(Member[] members, bool soapRefs) } } - private void WriteSourceBeginTyped(string source, TypeDesc typeDesc) + private void WriteSourceBeginTyped(string source, TypeDesc? typeDesc) { WriteSourceBegin(source); } private void WriteSourceBegin(string source) { - object variable; + object? variable; if (ilg.TryGetVariable(source, out variable)) { Type varType = ilg.GetVariableType(variable); @@ -2731,12 +2732,12 @@ private void WriteSourceBegin(string source) LocalBuilder localA = ilg.GetLocal(match.Groups["locA1"].Value); LocalBuilder localI = ilg.GetLocal(match.Groups["locI1"].Value); - Type arrayElementType = localA.LocalType.GetElementType(); + Type arrayElementType = localA.LocalType.GetElementType()!; MethodInfo XmlSerializationReader_EnsureArrayIndex = typeof(XmlSerializationReader).GetMethod( "EnsureArrayIndex", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(Array), typeof(int), typeof(Type) } - ); + )!; ilg.Ldarg(0); ilg.Ldloc(localA); ilg.Ldloc(localI); @@ -2786,13 +2787,13 @@ private void WriteSourceEnd(string source, Type elementType) } private void WriteSourceEnd(string source, Type elementType, Type stackType) { - object variable; + object? variable; if (ilg.TryGetVariable(source, out variable)) { Type varType = ilg.GetVariableType(variable); if (CodeGenerator.IsNullableGenericType(varType)) { - ilg.Call(varType.GetConstructor(varType.GetGenericArguments())); + ilg.Call(varType.GetConstructor(varType.GetGenericArguments())!); } else { @@ -2818,7 +2819,7 @@ private void WriteSourceEnd(string source, Type elementType, Type stackType) if (match.Success) { object oVar = ilg.GetVariable(match.Groups["locA1"].Value); - Type arrayElementType = ilg.GetVariableType(oVar).GetElementType(); + Type arrayElementType = ilg.GetVariableType(oVar).GetElementType()!; ilg.ConvertValue(elementType, arrayElementType); if (CodeGenerator.IsNullableGenericType(arrayElementType) || arrayElementType.IsValueType) { @@ -2840,7 +2841,7 @@ private void WriteSourceEnd(string source, Type elementType, Type stackType) "Add", CodeGenerator.InstanceBindingFlags, new Type[] { elementType } - ); + )!; Debug.Assert(Add != null); Type addParameterType = Add.GetParameters()[0].ParameterType; ilg.ConvertValue(stackType, addParameterType); @@ -2856,7 +2857,7 @@ private void WriteSourceEnd(string source, Type elementType, Type stackType) { Type varType = ilg.GetVariableType(ilg.GetVariable(match.Groups["a"].Value)); System.Diagnostics.Debug.Assert(varType.IsArray); - Type varElementType = varType.GetElementType(); + Type varElementType = varType.GetElementType()!; ilg.ConvertValue(stackType, varElementType); ilg.Stelem(varElementType); return; @@ -2864,13 +2865,13 @@ private void WriteSourceEnd(string source, Type elementType, Type stackType) throw Globals.NotSupported("Unexpected: " + source); } - private void WriteArray(string source, string arrayName, ArrayMapping arrayMapping, bool readOnly, bool isNullable, int fixupIndex, int elementIndex) + private void WriteArray(string source, string? arrayName, ArrayMapping arrayMapping, bool readOnly, bool isNullable, int fixupIndex, int elementIndex) { MethodInfo XmlSerializationReader_ReadNull = typeof(XmlSerializationReader).GetMethod( "ReadNull", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_ReadNull); ilg.IfNot(); @@ -2905,12 +2906,12 @@ private void WriteArray(string source, string arrayName, ArrayMapping arrayMappi "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_get_IsEmptyElement = typeof(XmlReader).GetMethod( "get_IsEmptyElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_IsEmptyElement); @@ -2926,7 +2927,7 @@ private void WriteArray(string source, string arrayName, ArrayMapping arrayMappi "Skip", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_Skip); @@ -2936,7 +2937,7 @@ private void WriteArray(string source, string arrayName, ArrayMapping arrayMappi "ReadStartElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_ReadStartElement); @@ -2948,7 +2949,7 @@ private void WriteArray(string source, string arrayName, ArrayMapping arrayMappi "MoveToContent", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_MoveToContent); @@ -2959,7 +2960,7 @@ private void WriteArray(string source, string arrayName, ArrayMapping arrayMappi "ReadEndElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_ReadEndElement); ilg.EndIf(); @@ -2976,7 +2977,7 @@ private void WriteArray(string source, string arrayName, ArrayMapping arrayMappi ilg.EndIf(); } - private void WriteElement(string source, string arrayName, string choiceSource, ElementAccessor element, ChoiceIdentifierAccessor choice, string checkSpecified, bool checkForNull, bool readOnly, int fixupIndex, int elementIndex) + private void WriteElement(string source, string? arrayName, string? choiceSource, ElementAccessor element, ChoiceIdentifierAccessor? choice, string? checkSpecified, bool checkForNull, bool readOnly, int fixupIndex, int elementIndex) { if (checkSpecified != null && checkSpecified.Length > 0) { @@ -2989,10 +2990,10 @@ private void WriteElement(string source, string arrayName, string choiceSource, } else if (element.Mapping is NullableMapping) { - string methodName = ReferenceMapping(element.Mapping); + string? methodName = ReferenceMapping(element.Mapping); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe - if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, element.Mapping.TypeDesc.Name)); + if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, element.Mapping.TypeDesc!.Name)); #endif WriteSourceBegin(source); ilg.Ldarg(0); @@ -3001,11 +3002,11 @@ private void WriteElement(string source, string arrayName, string choiceSource, methodName, CodeGenerator.PrivateMethodAttributes, // See WriteNullableMethod for different return type logic - element.Mapping.TypeDesc.Type, + element.Mapping.TypeDesc!.Type, new Type[] { typeof(bool) } ); ilg.Call(methodBuilder); - WriteSourceEnd(source, element.Mapping.TypeDesc.Type); + WriteSourceEnd(source, element.Mapping.TypeDesc.Type!); } else if (element.Mapping is PrimitiveMapping) { @@ -3016,12 +3017,12 @@ private void WriteElement(string source, string arrayName, string choiceSource, "ReadNull", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_ReadNull); ilg.If(); WriteSourceBegin(source); - if (element.Mapping.TypeDesc.IsValueType) + if (element.Mapping.TypeDesc!.IsValueType) { throw Globals.NotSupported("No such condition. PrimitiveMapping && IsNullable = String, XmlQualifiedName and never IsValueType"); } @@ -3029,22 +3030,22 @@ private void WriteElement(string source, string arrayName, string choiceSource, { ilg.Load(null); } - WriteSourceEnd(source, element.Mapping.TypeDesc.Type); + WriteSourceEnd(source, element.Mapping.TypeDesc.Type!); ilg.Else(); doEndIf = true; } - if (element.Default != null && element.Default != DBNull.Value && element.Mapping.TypeDesc.IsValueType) + if (element.Default != null && element.Default != DBNull.Value && element.Mapping.TypeDesc!.IsValueType) { MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_get_IsEmptyElement = typeof(XmlReader).GetMethod( "get_IsEmptyElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_IsEmptyElement); @@ -3053,7 +3054,7 @@ private void WriteElement(string source, string arrayName, string choiceSource, "Skip", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_Skip); @@ -3064,18 +3065,18 @@ private void WriteElement(string source, string arrayName, string choiceSource, { } - if (element.Mapping.TypeDesc.Type == typeof(TimeSpan)) + if (element.Mapping.TypeDesc!.Type == typeof(TimeSpan)) { MethodInfo XmlSerializationReader_get_Reader = typeof(XmlSerializationReader).GetMethod( "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_get_IsEmptyElement = typeof(XmlReader).GetMethod( "get_IsEmptyElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_get_IsEmptyElement); @@ -3085,7 +3086,7 @@ private void WriteElement(string source, string arrayName, string choiceSource, "Skip", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_Skip); @@ -3094,7 +3095,7 @@ private void WriteElement(string source, string arrayName, string choiceSource, null, new Type[] { typeof(long) }, null - ); + )!; ilg.Ldc(default(TimeSpan).Ticks); ilg.New(TimeSpan_ctor); WriteSourceEnd(source, element.Mapping.TypeDesc.Type); @@ -3113,7 +3114,7 @@ private void WriteElement(string source, string arrayName, string choiceSource, "ReadElementQualifiedName", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_ReadElementQualifiedName); } @@ -3133,7 +3134,7 @@ private void WriteElement(string source, string arrayName, string choiceSource, WritePrimitive(element.Mapping, readFunc); } - WriteSourceEnd(source, element.Mapping.TypeDesc.Type); + WriteSourceEnd(source, element.Mapping.TypeDesc.Type!); } if (doEndIf) @@ -3142,10 +3143,10 @@ private void WriteElement(string source, string arrayName, string choiceSource, else if (element.Mapping is StructMapping) { TypeMapping mapping = element.Mapping; - string methodName = ReferenceMapping(mapping); + string? methodName = ReferenceMapping(mapping); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe - if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc.Name)); + if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc!.Name)); #endif if (checkForNull) @@ -3154,13 +3155,13 @@ private void WriteElement(string source, string arrayName, string choiceSource, "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_Skip = typeof(XmlReader).GetMethod( "Skip", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); - ilg.Ldloc(arrayName); + )!; + ilg.Ldloc(arrayName!); ilg.Load(null); ilg.If(Cmp.EqualTo); ilg.Ldarg(0); @@ -3171,7 +3172,7 @@ private void WriteElement(string source, string arrayName, string choiceSource, WriteSourceBegin(source); List argTypes = new List(); ilg.Ldarg(0); - if (mapping.TypeDesc.IsNullable) + if (mapping.TypeDesc!.IsNullable) { ilg.Load(element.IsNullable); argTypes.Add(typeof(bool)); @@ -3185,7 +3186,7 @@ private void WriteElement(string source, string arrayName, string choiceSource, argTypes.ToArray() ); ilg.Call(methodBuilder); - WriteSourceEnd(source, mapping.TypeDesc.Type); + WriteSourceEnd(source, mapping.TypeDesc.Type!); if (checkForNull) // 'If' begins in checkForNull above ilg.EndIf(); @@ -3193,7 +3194,7 @@ private void WriteElement(string source, string arrayName, string choiceSource, else if (element.Mapping is SpecialMapping) { SpecialMapping special = (SpecialMapping)element.Mapping; - switch (special.TypeDesc.Kind) + switch (special.TypeDesc!.Kind) { case TypeKind.Node: bool isDoc = special.TypeDesc.FullName == typeof(XmlDocument).FullName; @@ -3202,14 +3203,14 @@ private void WriteElement(string source, string arrayName, string choiceSource, isDoc ? "ReadXmlDocument" : "ReadXmlNode", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(bool) } - ); + )!; ilg.Ldarg(0); ilg.Ldc(element.Any ? false : true); ilg.Call(XmlSerializationReader_ReadXmlXXX); // See logic in WriteSourceBeginTyped whether or not to castclass. if (special.TypeDesc != null) - ilg.Castclass(special.TypeDesc.Type); - WriteSourceEnd(source, special.TypeDesc.Type); + ilg.Castclass(special.TypeDesc.Type!); + WriteSourceEnd(source, special.TypeDesc!.Type!); break; case TypeKind.Serializable: SerializableMapping sm = (SerializableMapping)element.Mapping; @@ -3220,7 +3221,7 @@ private void WriteElement(string source, string arrayName, string choiceSource, "GetXsiType", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; Label labelTrue = ilg.DefineLabel(); Label labelEnd = ilg.DefineLabel(); LocalBuilder tserLoc = ilg.DeclareOrGetLocal(typeof(XmlQualifiedName), "tser"); @@ -3231,7 +3232,7 @@ private void WriteElement(string source, string arrayName, string choiceSource, ilg.Load(null); ilg.Ceq(); ilg.Brtrue(labelTrue); - WriteQNameEqual("tser", sm.XsiType.Name, sm.XsiType.Namespace); + WriteQNameEqual("tser", sm.XsiType!.Name, sm.XsiType.Namespace); ilg.Br_S(labelEnd); ilg.MarkLabel(labelTrue); @@ -3239,15 +3240,15 @@ private void WriteElement(string source, string arrayName, string choiceSource, ilg.MarkLabel(labelEnd); ilg.If(); } - WriteSourceBeginTyped(source, sm.TypeDesc); + WriteSourceBeginTyped(source, sm.TypeDesc!); bool isWrappedAny = !element.Any && IsWildcard(sm); MethodInfo XmlSerializationReader_ReadSerializable = typeof(XmlSerializationReader).GetMethod( "ReadSerializable", CodeGenerator.InstanceBindingFlags, isWrappedAny ? new Type[] { typeof(IXmlSerializable), typeof(bool) } : new Type[] { typeof(IXmlSerializable) } - ); + )!; ilg.Ldarg(0); - RaCodeGen.ILGenForCreateInstance(ilg, sm.TypeDesc.Type, sm.TypeDesc.CannotNew, false); + RaCodeGen.ILGenForCreateInstance(ilg, sm.TypeDesc!.Type!, sm.TypeDesc.CannotNew, false); if (sm.TypeDesc.CannotNew) ilg.ConvertValue(typeof(object), typeof(IXmlSerializable)); if (isWrappedAny) @@ -3255,8 +3256,8 @@ private void WriteElement(string source, string arrayName, string choiceSource, ilg.Call(XmlSerializationReader_ReadSerializable); // See logic in WriteSourceBeginTyped whether or not to castclass. if (sm.TypeDesc != null) - ilg.ConvertValue(typeof(IXmlSerializable), sm.TypeDesc.Type); - WriteSourceEnd(source, sm.TypeDesc.Type); + ilg.ConvertValue(typeof(IXmlSerializable), sm.TypeDesc.Type!); + WriteSourceEnd(source, sm.TypeDesc!.Type!); if (sm.DerivedMappings != null) { WriteDerivedSerializable(sm, sm, source, isWrappedAny); @@ -3279,17 +3280,17 @@ private void WriteElement(string source, string arrayName, string choiceSource, #endif WriteSourceBegin(choiceSource); - CodeIdentifier.CheckValidIdentifier(choice.MemberIds[elementIndex]); - RaCodeGen.ILGenForEnumMember(ilg, choice.Mapping.TypeDesc.Type, choice.MemberIds[elementIndex]); - WriteSourceEnd(choiceSource, choice.Mapping.TypeDesc.Type); + CodeIdentifier.CheckValidIdentifier(choice.MemberIds![elementIndex]); + RaCodeGen.ILGenForEnumMember(ilg, choice.Mapping!.TypeDesc!.Type!, choice.MemberIds[elementIndex]); + WriteSourceEnd(choiceSource, choice.Mapping.TypeDesc.Type!); } } - private void WriteDerivedSerializable(SerializableMapping head, SerializableMapping mapping, string source, bool isWrappedAny) + private void WriteDerivedSerializable(SerializableMapping head, SerializableMapping? mapping, string source, bool isWrappedAny) { if (mapping == null) return; - for (SerializableMapping derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) + for (SerializableMapping? derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) { Label labelTrue = ilg.DefineLabel(); Label labelEnd = ilg.DefineLabel(); @@ -3299,7 +3300,7 @@ private void WriteDerivedSerializable(SerializableMapping head, SerializableMapp ilg.Load(null); ilg.Ceq(); ilg.Brtrue(labelTrue); - WriteQNameEqual("tser", derived.XsiType.Name, derived.XsiType.Namespace); + WriteQNameEqual("tser", derived.XsiType!.Name, derived.XsiType.Namespace); ilg.Br_S(labelEnd); ilg.MarkLabel(labelTrue); @@ -3309,16 +3310,16 @@ private void WriteDerivedSerializable(SerializableMapping head, SerializableMapp if (derived.Type != null) { - if (head.Type.IsAssignableFrom(derived.Type)) + if (head.Type!.IsAssignableFrom(derived.Type)) { - WriteSourceBeginTyped(source, head.TypeDesc); + WriteSourceBeginTyped(source, head.TypeDesc!); MethodInfo XmlSerializationReader_ReadSerializable = typeof(XmlSerializationReader).GetMethod( "ReadSerializable", CodeGenerator.InstanceBindingFlags, isWrappedAny ? new Type[] { typeof(IXmlSerializable), typeof(bool) } : new Type[] { typeof(IXmlSerializable) } - ); + )!; ilg.Ldarg(0); - RaCodeGen.ILGenForCreateInstance(ilg, derived.TypeDesc.Type, derived.TypeDesc.CannotNew, false); + RaCodeGen.ILGenForCreateInstance(ilg, derived.TypeDesc!.Type!, derived.TypeDesc.CannotNew, false); if (derived.TypeDesc.CannotNew) ilg.ConvertValue(typeof(object), typeof(IXmlSerializable)); if (isWrappedAny) @@ -3326,8 +3327,8 @@ private void WriteDerivedSerializable(SerializableMapping head, SerializableMapp ilg.Call(XmlSerializationReader_ReadSerializable); // See logic in WriteSourceBeginTyped whether or not to castclass. if (head.TypeDesc != null) - ilg.ConvertValue(typeof(IXmlSerializable), head.TypeDesc.Type); - WriteSourceEnd(source, head.TypeDesc.Type); + ilg.ConvertValue(typeof(IXmlSerializable), head.TypeDesc.Type!); + WriteSourceEnd(source, head.TypeDesc!.Type!); } else { @@ -3335,11 +3336,11 @@ private void WriteDerivedSerializable(SerializableMapping head, SerializableMapp "CreateBadDerivationException", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string), typeof(string), typeof(string), typeof(string), typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Ldstr(GetCSharpString(derived.XsiType.Name)); ilg.Ldstr(GetCSharpString(derived.XsiType.Namespace)); - ilg.Ldstr(GetCSharpString(head.XsiType.Name)); + ilg.Ldstr(GetCSharpString(head.XsiType!.Name)); ilg.Ldstr(GetCSharpString(head.XsiType.Namespace)); ilg.Ldstr(GetCSharpString(derived.Type.FullName)); ilg.Ldstr(GetCSharpString(head.Type.FullName)); @@ -3353,11 +3354,11 @@ private void WriteDerivedSerializable(SerializableMapping head, SerializableMapp "CreateMissingIXmlSerializableType", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string), typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Ldstr(GetCSharpString(derived.XsiType.Name)); ilg.Ldstr(GetCSharpString(derived.XsiType.Namespace)); - ilg.Ldstr(GetCSharpString(head.Type.FullName)); + ilg.Ldstr(GetCSharpString(head.Type!.FullName)); ilg.Call(XmlSerializationReader_CreateMissingIXmlSerializableType); ilg.Throw(); } @@ -3373,12 +3374,12 @@ private void WriteWhileNotLoopStart() "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_MoveToContent = typeof(XmlReader).GetMethod( "MoveToContent", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_get_Reader); ilg.Call(XmlReader_MoveToContent); @@ -3398,12 +3399,12 @@ private void WriteWhileLoopEnd() "get_Reader", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlReader_get_NodeType = typeof(XmlReader).GetMethod( "get_NodeType", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; Label labelFalse = ilg.DefineLabel(); Label labelEnd = ilg.DefineLabel(); ilg.Ldarg(0); @@ -3434,18 +3435,18 @@ private void WriteParamsRead(int length) private void WriteCreateMapping(TypeMapping mapping, string local) { - string fullTypeName = mapping.TypeDesc.CSharpName; + string fullTypeName = mapping.TypeDesc!.CSharpName; bool ctorInaccessible = mapping.TypeDesc.CannotNew; LocalBuilder loc = ilg.DeclareLocal( - mapping.TypeDesc.Type, + mapping.TypeDesc.Type!, local); if (ctorInaccessible) { ilg.BeginExceptionBlock(); } - RaCodeGen.ILGenForCreateInstance(ilg, mapping.TypeDesc.Type, mapping.TypeDesc.CannotNew, true); + RaCodeGen.ILGenForCreateInstance(ilg, mapping.TypeDesc.Type!, mapping.TypeDesc.CannotNew, true); ilg.Stloc(loc); if (ctorInaccessible) { @@ -3455,7 +3456,7 @@ private void WriteCreateMapping(TypeMapping mapping, string local) "CreateInaccessibleConstructorException", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Ldstr(GetCSharpString(fullTypeName)); ilg.Call(XmlSerializationReader_CreateInaccessibleConstructorException); @@ -3466,7 +3467,7 @@ private void WriteCreateMapping(TypeMapping mapping, string local) "CreateCtorHasSecurityException", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Ldstr(GetCSharpString(fullTypeName)); ilg.Call(XmlSerializationReader_CreateCtorHasSecurityException); @@ -3500,12 +3501,12 @@ private void ILGenElseString(string elseString) "UnknownNode", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(object) } - ); + )!; MethodInfo XmlSerializationReader_UnknownNode2 = typeof(XmlSerializationReader).GetMethod( "UnknownNode", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(object), typeof(string) } - ); + )!; // UnknownNode(null, @":anyType"); Regex regex = NewRegex("UnknownNode[(]null, @[\"](?[^\"]*)[\"][)];"); Match match = regex.Match(elseString); @@ -3587,7 +3588,7 @@ private void ILGenElementElseString(string elementElseString) "CreateUnknownNodeException", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationReader_CreateUnknownNodeException); ilg.Throw(); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs index 0cfe356e676f5f..bdc840141edd83 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; @@ -18,26 +19,27 @@ namespace System.Xml.Serialization using System.Collections.Generic; using System.Xml.Serialization; using System.Xml; + using System.Diagnostics.CodeAnalysis; /// public abstract class XmlSerializationWriter : XmlSerializationGeneratedCode { - private XmlWriter _w; - private XmlSerializerNamespaces _namespaces; + private XmlWriter _w = null!; + private XmlSerializerNamespaces? _namespaces; private int _tempNamespacePrefix; - private HashSet _usedPrefixes; - private Hashtable _references; - private string _idBase; + private HashSet? _usedPrefixes; + private Hashtable? _references; + private string? _idBase; private int _nextId; - private Hashtable _typeEntries; - private ArrayList _referencesToWrite; - private Hashtable _objectsInUse; + private Hashtable? _typeEntries; + private ArrayList? _referencesToWrite; + private Hashtable? _objectsInUse; private readonly string _aliasBase = "q"; private bool _soap12; private bool _escapeName = true; // this method must be called before any generated serialization methods are called - internal void Init(XmlWriter w, XmlSerializerNamespaces namespaces, string encodingStyle, string idBase, TempAssembly tempAssembly) + internal void Init(XmlWriter w, XmlSerializerNamespaces? namespaces, string? encodingStyle, string? idBase, TempAssembly? tempAssembly) { _w = w; _namespaces = namespaces; @@ -73,7 +75,7 @@ protected XmlWriter Writer /// /// [To be supplied.] /// - protected ArrayList Namespaces + protected ArrayList? Namespaces { get { @@ -103,7 +105,7 @@ protected static byte[] FromByteArrayBase64(byte[] value) } /// - protected static Assembly ResolveDynamicAssembly(string assemblyFullName) + protected static Assembly? ResolveDynamicAssembly(string assemblyFullName) { return DynamicAssemblies.Get(assemblyFullName); } @@ -163,25 +165,25 @@ protected static string FromXmlNmTokens(string nmTokens) return XmlCustomFormatter.FromXmlNmTokens(nmTokens); } - protected void WriteXsiType(string name, string ns) + protected void WriteXsiType(string name, string? ns) { WriteAttribute("type", XmlSchema.InstanceNamespace, GetQualifiedName(name, ns)); } private XmlQualifiedName GetPrimitiveTypeName(Type type) { - return GetPrimitiveTypeName(type, true); + return GetPrimitiveTypeName(type, true)!; } - private XmlQualifiedName GetPrimitiveTypeName(Type type, bool throwIfUnknown) + private XmlQualifiedName? GetPrimitiveTypeName(Type type, bool throwIfUnknown) { - XmlQualifiedName qname = GetPrimitiveTypeNameInternal(type); + XmlQualifiedName? qname = GetPrimitiveTypeNameInternal(type); if (throwIfUnknown && qname == null) throw CreateUnknownTypeException(type); return qname; } - internal static XmlQualifiedName GetPrimitiveTypeNameInternal(Type type) + internal static XmlQualifiedName? GetPrimitiveTypeNameInternal(Type type) { string typeName; string typeNs = XmlSchema.Namespace; @@ -230,9 +232,9 @@ internal static XmlQualifiedName GetPrimitiveTypeNameInternal(Type type) return new XmlQualifiedName(typeName, typeNs); } - protected void WriteTypedPrimitive(string name, string ns, object o, bool xsiType) + protected void WriteTypedPrimitive(string? name, string? ns, object o, bool xsiType) { - string value = null; + string? value = null; string type; string typeNs = XmlSchema.Namespace; bool writeRaw = true; @@ -385,10 +387,10 @@ protected void WriteTypedPrimitive(string name, string ns, object o, bool xsiTyp _w.WriteEndElement(); } - private string GetQualifiedName(string name, string ns) + private string GetQualifiedName(string name, string? ns) { if (ns == null || ns.Length == 0) return name; - string prefix = _w.LookupPrefix(ns); + string? prefix = _w.LookupPrefix(ns); if (prefix == null) { if (ns == XmlReservedNs.NsXml) @@ -408,12 +410,13 @@ private string GetQualifiedName(string name, string ns) return prefix + ":" + name; } - protected string FromXmlQualifiedName(XmlQualifiedName xmlQualifiedName) + protected string? FromXmlQualifiedName(XmlQualifiedName? xmlQualifiedName) { return FromXmlQualifiedName(xmlQualifiedName, true); } - protected string FromXmlQualifiedName(XmlQualifiedName xmlQualifiedName, bool ignoreEmpty) + [return: NotNullIfNotNull("xmlQualifiedName")] + protected string? FromXmlQualifiedName(XmlQualifiedName? xmlQualifiedName, bool ignoreEmpty) { if (xmlQualifiedName == null) return null; if (xmlQualifiedName.IsEmpty && ignoreEmpty) return null; @@ -425,27 +428,27 @@ protected void WriteStartElement(string name) WriteStartElement(name, null, null, false, null); } - protected void WriteStartElement(string name, string ns) + protected void WriteStartElement(string name, string? ns) { WriteStartElement(name, ns, null, false, null); } - protected void WriteStartElement(string name, string ns, bool writePrefixed) + protected void WriteStartElement(string name, string? ns, bool writePrefixed) { WriteStartElement(name, ns, null, writePrefixed, null); } - protected void WriteStartElement(string name, string ns, object o) + protected void WriteStartElement(string name, string? ns, object? o) { WriteStartElement(name, ns, o, false, null); } - protected void WriteStartElement(string name, string ns, object o, bool writePrefixed) + protected void WriteStartElement(string name, string? ns, object? o, bool writePrefixed) { WriteStartElement(name, ns, o, writePrefixed, null); } - protected void WriteStartElement(string name, string ns, object o, bool writePrefixed, XmlSerializerNamespaces xmlns) + protected void WriteStartElement(string name, string? ns, object? o, bool writePrefixed, XmlSerializerNamespaces? xmlns) { if (o != null && _objectsInUse != null) { @@ -453,13 +456,13 @@ protected void WriteStartElement(string name, string ns, object o, bool writePre _objectsInUse.Add(o, o); } - string prefix = null; + string? prefix = null; bool needEmptyDefaultNamespace = false; if (_namespaces != null) { foreach (string alias in _namespaces.Namespaces.Keys) { - string aliasNs = (string)_namespaces.Namespaces[alias]; + string? aliasNs = (string?)_namespaces.Namespaces[alias]; if (alias.Length > 0 && aliasNs == ns) prefix = alias; @@ -492,7 +495,7 @@ protected void WriteStartElement(string name, string ns, object o, bool writePre { foreach (string alias in _namespaces.Namespaces.Keys) { - string aliasNs = (string)_namespaces.Namespaces[alias]; + string? aliasNs = (string?)_namespaces.Namespaces[alias]; if (alias.Length == 0 && (aliasNs == null || aliasNs.Length == 0)) continue; if (aliasNs == null || aliasNs.Length == 0) @@ -516,12 +519,12 @@ protected void WriteStartElement(string name, string ns, object o, bool writePre WriteNamespaceDeclarations(xmlns); } - private HashSet ListUsedPrefixes(Dictionary nsList, string prefix) + private HashSet? ListUsedPrefixes(Dictionary? nsList, string prefix) { var qnIndexes = new HashSet(); int prefixLength = prefix.Length; const string MaxInt32 = "2147483647"; - foreach (string alias in _namespaces.Namespaces.Keys) + foreach (string alias in _namespaces!.Namespaces.Keys) { string name; if (alias.Length > prefixLength) @@ -562,7 +565,7 @@ protected void WriteNullTagEncoded(string name) WriteNullTagEncoded(name, null); } - protected void WriteNullTagEncoded(string name, string ns) + protected void WriteNullTagEncoded(string? name, string? ns) { if (name == null || name.Length == 0) return; @@ -576,7 +579,7 @@ protected void WriteNullTagLiteral(string name) WriteNullTagLiteral(name, null); } - protected void WriteNullTagLiteral(string name, string ns) + protected void WriteNullTagLiteral(string? name, string? ns) { if (name == null || name.Length == 0) return; @@ -585,12 +588,12 @@ protected void WriteNullTagLiteral(string name, string ns) _w.WriteEndElement(); } - protected void WriteEmptyTag(string name) + protected void WriteEmptyTag(string? name) { WriteEmptyTag(name, null); } - protected void WriteEmptyTag(string name, string ns) + protected void WriteEmptyTag(string? name, string? ns) { if (name == null || name.Length == 0) return; @@ -603,7 +606,7 @@ protected void WriteEndElement() _w.WriteEndElement(); } - protected void WriteEndElement(object o) + protected void WriteEndElement(object? o) { _w.WriteEndElement(); @@ -618,12 +621,12 @@ protected void WriteEndElement(object o) } } - protected void WriteSerializable(IXmlSerializable serializable, string name, string ns, bool isNullable) + protected void WriteSerializable(IXmlSerializable? serializable, string name, string ns, bool isNullable) { WriteSerializable(serializable, name, ns, isNullable, true); } - protected void WriteSerializable(IXmlSerializable serializable, string name, string ns, bool isNullable, bool wrapped) + protected void WriteSerializable(IXmlSerializable? serializable, string name, string? ns, bool isNullable, bool wrapped) { if (serializable == null) { @@ -641,7 +644,7 @@ protected void WriteSerializable(IXmlSerializable serializable, string name, str } } - protected void WriteNullableStringEncoded(string name, string ns, string value, XmlQualifiedName xsiType) + protected void WriteNullableStringEncoded(string name, string? ns, string? value, XmlQualifiedName? xsiType) { if (value == null) WriteNullTagEncoded(name, ns); @@ -649,7 +652,7 @@ protected void WriteNullableStringEncoded(string name, string ns, string value, WriteElementString(name, ns, value, xsiType); } - protected void WriteNullableStringLiteral(string name, string ns, string value) + protected void WriteNullableStringLiteral(string name, string? ns, string? value) { if (value == null) WriteNullTagLiteral(name, ns); @@ -658,7 +661,7 @@ protected void WriteNullableStringLiteral(string name, string ns, string value) } - protected void WriteNullableStringEncodedRaw(string name, string ns, string value, XmlQualifiedName xsiType) + protected void WriteNullableStringEncodedRaw(string name, string? ns, string? value, XmlQualifiedName? xsiType) { if (value == null) WriteNullTagEncoded(name, ns); @@ -666,7 +669,7 @@ protected void WriteNullableStringEncodedRaw(string name, string ns, string valu WriteElementStringRaw(name, ns, value, xsiType); } - protected void WriteNullableStringEncodedRaw(string name, string ns, byte[] value, XmlQualifiedName xsiType) + protected void WriteNullableStringEncodedRaw(string name, string? ns, byte[]? value, XmlQualifiedName? xsiType) { if (value == null) WriteNullTagEncoded(name, ns); @@ -674,7 +677,7 @@ protected void WriteNullableStringEncodedRaw(string name, string ns, byte[] valu WriteElementStringRaw(name, ns, value, xsiType); } - protected void WriteNullableStringLiteralRaw(string name, string ns, string value) + protected void WriteNullableStringLiteralRaw(string name, string? ns, string? value) { if (value == null) WriteNullTagLiteral(name, ns); @@ -682,7 +685,7 @@ protected void WriteNullableStringLiteralRaw(string name, string ns, string valu WriteElementStringRaw(name, ns, value, null); } - protected void WriteNullableStringLiteralRaw(string name, string ns, byte[] value) + protected void WriteNullableStringLiteralRaw(string name, string? ns, byte[]? value) { if (value == null) WriteNullTagLiteral(name, ns); @@ -693,7 +696,7 @@ protected void WriteNullableStringLiteralRaw(string name, string ns, byte[] valu /// /// [To be supplied.] /// - protected void WriteNullableQualifiedNameEncoded(string name, string ns, XmlQualifiedName value, XmlQualifiedName xsiType) + protected void WriteNullableQualifiedNameEncoded(string name, string? ns, XmlQualifiedName? value, XmlQualifiedName? xsiType) { if (value == null) WriteNullTagEncoded(name, ns); @@ -704,7 +707,7 @@ protected void WriteNullableQualifiedNameEncoded(string name, string ns, XmlQual /// /// [To be supplied.] /// - protected void WriteNullableQualifiedNameLiteral(string name, string ns, XmlQualifiedName value) + protected void WriteNullableQualifiedNameLiteral(string name, string? ns, XmlQualifiedName? value) { if (value == null) WriteNullTagLiteral(name, ns); @@ -713,7 +716,7 @@ protected void WriteNullableQualifiedNameLiteral(string name, string ns, XmlQual } - protected void WriteElementEncoded(XmlNode node, string name, string ns, bool isNullable, bool any) + protected void WriteElementEncoded(XmlNode node, string name, string? ns, bool isNullable, bool any) { if (node == null) { @@ -723,7 +726,7 @@ protected void WriteElementEncoded(XmlNode node, string name, string ns, bool is WriteElement(node, name, ns, isNullable, any); } - protected void WriteElementLiteral(XmlNode node, string name, string ns, bool isNullable, bool any) + protected void WriteElementLiteral(XmlNode node, string name, string? ns, bool isNullable, bool any) { if (node == null) { @@ -733,13 +736,13 @@ protected void WriteElementLiteral(XmlNode node, string name, string ns, bool is WriteElement(node, name, ns, isNullable, any); } - private void WriteElement(XmlNode node, string name, string ns, bool isNullable, bool any) + private void WriteElement(XmlNode node, string name, string? ns, bool isNullable, bool any) { if (typeof(XmlAttribute).IsAssignableFrom(node.GetType())) throw new InvalidOperationException(SR.XmlNoAttributeHere); if (node is XmlDocument) { - node = ((XmlDocument)node).DocumentElement; + node = ((XmlDocument)node).DocumentElement!; if (node == null) { if (isNullable) WriteNullTagEncoded(name, ns); @@ -819,18 +822,20 @@ protected void WriteReferencingElement(string n, string ns, object o) WriteReferencingElement(n, ns, o, false); } - protected void WriteReferencingElement(string n, string ns, object o, bool isNullable) + protected void WriteReferencingElement(string n, string? ns, object? o, bool isNullable) { if (o == null) { if (isNullable) WriteNullTagEncoded(n, ns); return; } + WriteStartElement(n, ns, null, true); if (_soap12) _w.WriteAttributeString("ref", Soap12.Encoding, GetId(o, true)); else _w.WriteAttributeString("href", "#" + GetId(o, true)); + _w.WriteEndElement(); } @@ -847,12 +852,12 @@ private string GetId(object o, bool addToReferencesList) _references = new Hashtable(); _referencesToWrite = new ArrayList(); } - string id = (string)_references[o]; + string? id = (string?)_references[o]; if (id == null) { id = _idBase + "id" + (++_nextId).ToString(CultureInfo.InvariantCulture); _references.Add(o, id); - if (addToReferencesList) _referencesToWrite.Add(o); + if (addToReferencesList) _referencesToWrite!.Add(o); } return id; } @@ -875,9 +880,9 @@ protected void WriteXmlAttribute(XmlNode node) WriteXmlAttribute(node, null); } - protected void WriteXmlAttribute(XmlNode node, object container) + protected void WriteXmlAttribute(XmlNode node, object? container) { - XmlAttribute attr = node as XmlAttribute; + XmlAttribute? attr = node as XmlAttribute; if (attr == null) throw new InvalidOperationException(SR.XmlNeedAttributeHere); if (attr.Value != null) { @@ -898,7 +903,7 @@ protected void WriteXmlAttribute(XmlNode node, object container) } } - protected void WriteAttribute(string localName, string ns, string value) + protected void WriteAttribute(string localName, string? ns, string? value) { if (value == null) return; if (localName == "xmlns" || localName.StartsWith("xmlns:", StringComparison.Ordinal)) @@ -912,7 +917,7 @@ protected void WriteAttribute(string localName, string ns, string value) { if (ns == XmlReservedNs.NsXml) { - string prefix = _w.LookupPrefix(ns); + string? prefix = _w.LookupPrefix(ns); if (prefix == null || prefix.Length == 0) prefix = "xml"; _w.WriteAttributeString(prefix, localName, ns, value); @@ -930,7 +935,7 @@ protected void WriteAttribute(string localName, string ns, string value) } } - protected void WriteAttribute(string localName, string ns, byte[] value) + protected void WriteAttribute(string localName, string ns, byte[]? value) { if (value == null) return; if (localName == "xmlns" || localName.StartsWith("xmlns:", StringComparison.Ordinal)) @@ -944,7 +949,7 @@ protected void WriteAttribute(string localName, string ns, byte[] value) { if (ns == XmlReservedNs.NsXml) { - string prefix = _w.LookupPrefix(ns); + string? prefix = _w.LookupPrefix(ns); if (prefix == null || prefix.Length == 0) prefix = "xml"; _w.WriteStartAttribute("xml", localName, ns); @@ -956,7 +961,7 @@ protected void WriteAttribute(string localName, string ns, byte[] value) } else { - string prefix = _w.LookupPrefix(ns); + string? prefix = _w.LookupPrefix(ns); _w.WriteStartAttribute(prefix, localName.Substring(colon + 1), ns); } XmlCustomFormatter.WriteArrayBase64(_w, value, 0, value.Length); @@ -964,34 +969,34 @@ protected void WriteAttribute(string localName, string ns, byte[] value) } } - protected void WriteAttribute(string localName, string value) + protected void WriteAttribute(string localName, string? value) { if (value == null) return; _w.WriteAttributeString(localName, null, value); } - protected void WriteAttribute(string localName, byte[] value) + protected void WriteAttribute(string localName, byte[]? value) { if (value == null) return; - _w.WriteStartAttribute(null, localName, (string)null); + _w.WriteStartAttribute(null, localName, (string?)null); XmlCustomFormatter.WriteArrayBase64(_w, value, 0, value.Length); _w.WriteEndAttribute(); } - protected void WriteAttribute(string prefix, string localName, string ns, string value) + protected void WriteAttribute(string prefix, string localName, string? ns, string? value) { if (value == null) return; _w.WriteAttributeString(prefix, localName, null, value); } - protected void WriteValue(string value) + protected void WriteValue(string? value) { if (value == null) return; _w.WriteString(value); } - protected void WriteValue(byte[] value) + protected void WriteValue(byte[]? value) { if (value == null) return; XmlCustomFormatter.WriteArrayBase64(_w, value, 0, value.Length); @@ -1005,22 +1010,22 @@ protected void WriteStartDocument() } } - protected void WriteElementString(string localName, string value) + protected void WriteElementString(string localName, string? value) { WriteElementString(localName, null, value, null); } - protected void WriteElementString(string localName, string ns, string value) + protected void WriteElementString(string localName, string? ns, string? value) { WriteElementString(localName, ns, value, null); } - protected void WriteElementString(string localName, string value, XmlQualifiedName xsiType) + protected void WriteElementString(string localName, string? value, XmlQualifiedName? xsiType) { WriteElementString(localName, null, value, xsiType); } - protected void WriteElementString(string localName, string ns, string value, XmlQualifiedName xsiType) + protected void WriteElementString(string localName, string? ns, string? value, XmlQualifiedName? xsiType) { if (value == null) return; if (xsiType == null) @@ -1034,37 +1039,37 @@ protected void WriteElementString(string localName, string ns, string value, Xml } } - protected void WriteElementStringRaw(string localName, string value) + protected void WriteElementStringRaw(string localName, string? value) { WriteElementStringRaw(localName, null, value, null); } - protected void WriteElementStringRaw(string localName, byte[] value) + protected void WriteElementStringRaw(string localName, byte[]? value) { WriteElementStringRaw(localName, null, value, null); } - protected void WriteElementStringRaw(string localName, string ns, string value) + protected void WriteElementStringRaw(string localName, string? ns, string? value) { WriteElementStringRaw(localName, ns, value, null); } - protected void WriteElementStringRaw(string localName, string ns, byte[] value) + protected void WriteElementStringRaw(string localName, string? ns, byte[]? value) { WriteElementStringRaw(localName, ns, value, null); } - protected void WriteElementStringRaw(string localName, string value, XmlQualifiedName xsiType) + protected void WriteElementStringRaw(string localName, string? value, XmlQualifiedName? xsiType) { WriteElementStringRaw(localName, null, value, xsiType); } - protected void WriteElementStringRaw(string localName, byte[] value, XmlQualifiedName xsiType) + protected void WriteElementStringRaw(string localName, byte[]? value, XmlQualifiedName? xsiType) { WriteElementStringRaw(localName, null, value, xsiType); } - protected void WriteElementStringRaw(string localName, string ns, string value, XmlQualifiedName xsiType) + protected void WriteElementStringRaw(string localName, string? ns, string? value, XmlQualifiedName? xsiType) { if (value == null) return; _w.WriteStartElement(localName, ns); @@ -1074,7 +1079,7 @@ protected void WriteElementStringRaw(string localName, string ns, string value, _w.WriteEndElement(); } - protected void WriteElementStringRaw(string localName, string ns, byte[] value, XmlQualifiedName xsiType) + protected void WriteElementStringRaw(string localName, string? ns, byte[]? value, XmlQualifiedName? xsiType) { if (value == null) return; _w.WriteStartElement(localName, ns); @@ -1084,7 +1089,7 @@ protected void WriteElementStringRaw(string localName, string ns, byte[] value, _w.WriteEndElement(); } - protected void WriteRpcResult(string name, string ns) + protected void WriteRpcResult(string name, string? ns) { if (!_soap12) return; WriteElementQualifiedName(Soap12.RpcResult, Soap12.RpcNamespace, new XmlQualifiedName(name, ns), null); @@ -1093,12 +1098,12 @@ protected void WriteRpcResult(string name, string ns) /// /// [To be supplied.] /// - protected void WriteElementQualifiedName(string localName, XmlQualifiedName value) + protected void WriteElementQualifiedName(string localName, XmlQualifiedName? value) { WriteElementQualifiedName(localName, null, value, null); } - protected void WriteElementQualifiedName(string localName, XmlQualifiedName value, XmlQualifiedName xsiType) + protected void WriteElementQualifiedName(string localName, XmlQualifiedName? value, XmlQualifiedName? xsiType) { WriteElementQualifiedName(localName, null, value, xsiType); } @@ -1106,12 +1111,12 @@ protected void WriteElementQualifiedName(string localName, XmlQualifiedName valu /// /// [To be supplied.] /// - protected void WriteElementQualifiedName(string localName, string ns, XmlQualifiedName value) + protected void WriteElementQualifiedName(string localName, string? ns, XmlQualifiedName? value) { WriteElementQualifiedName(localName, ns, value, null); } - protected void WriteElementQualifiedName(string localName, string ns, XmlQualifiedName value, XmlQualifiedName xsiType) + protected void WriteElementQualifiedName(string localName, string? ns, XmlQualifiedName? value, XmlQualifiedName? xsiType) { if (value == null) return; if (value.Namespace == null || value.Namespace.Length == 0) @@ -1127,28 +1132,28 @@ protected void WriteElementQualifiedName(string localName, string ns, XmlQualifi _w.WriteEndElement(); } - protected void AddWriteCallback(Type type, string typeName, string typeNs, XmlSerializationWriteCallback callback) + protected void AddWriteCallback(Type type, string typeName, string? typeNs, XmlSerializationWriteCallback callback) { TypeEntry entry = new TypeEntry(); entry.typeName = typeName; entry.typeNs = typeNs; entry.type = type; entry.callback = callback; - _typeEntries[type] = entry; + _typeEntries![type] = entry; } - private void WriteArray(string name, string ns, object o, Type type) + private void WriteArray(string name, string? ns, object o, Type type) { - Type elementType = TypeScope.GetArrayElementType(type, null); + Type elementType = TypeScope.GetArrayElementType(type, null)!; string typeName; - string typeNs; + string? typeNs; StringBuilder arrayDims = new StringBuilder(); if (!_soap12) { while ((elementType.IsArray || typeof(IEnumerable).IsAssignableFrom(elementType)) && GetPrimitiveTypeName(elementType, false) == null) { - elementType = TypeScope.GetArrayElementType(elementType, null); + elementType = TypeScope.GetArrayElementType(elementType, null)!; arrayDims.Append("[]"); } } @@ -1160,15 +1165,15 @@ private void WriteArray(string name, string ns, object o, Type type) } else { - TypeEntry entry = GetTypeEntry(elementType); + TypeEntry? entry = GetTypeEntry(elementType); if (entry != null) { - typeName = entry.typeName; + typeName = entry.typeName!; typeNs = entry.typeNs; } else if (_soap12) { - XmlQualifiedName qualName = GetPrimitiveTypeName(elementType, false); + XmlQualifiedName? qualName = GetPrimitiveTypeName(elementType, false); if (qualName != null) { typeName = qualName.Name; @@ -1176,7 +1181,7 @@ private void WriteArray(string name, string ns, object o, Type type) } else { - Type elementBaseType = elementType.BaseType; + Type? elementBaseType = elementType.BaseType; while (elementBaseType != null) { entry = GetTypeEntry(elementBaseType); @@ -1185,7 +1190,7 @@ private void WriteArray(string name, string ns, object o, Type type) } if (entry != null) { - typeName = entry.typeName; + typeName = entry.typeName!; typeNs = entry.typeNs; } else @@ -1261,22 +1266,22 @@ private void WriteArray(string name, string ns, object o, Type type) } _w.WriteEndElement(); } - protected void WritePotentiallyReferencingElement(string n, string ns, object o) + protected void WritePotentiallyReferencingElement(string n, string? ns, object? o) { WritePotentiallyReferencingElement(n, ns, o, null, false, false); } - protected void WritePotentiallyReferencingElement(string n, string ns, object o, Type ambientType) + protected void WritePotentiallyReferencingElement(string n, string? ns, object? o, Type? ambientType) { WritePotentiallyReferencingElement(n, ns, o, ambientType, false, false); } - protected void WritePotentiallyReferencingElement(string n, string ns, object o, Type ambientType, bool suppressReference) + protected void WritePotentiallyReferencingElement(string n, string? ns, object? o, Type? ambientType, bool suppressReference) { WritePotentiallyReferencingElement(n, ns, o, ambientType, suppressReference, false); } - protected void WritePotentiallyReferencingElement(string n, string ns, object o, Type ambientType, bool suppressReference, bool isNullable) + protected void WritePotentiallyReferencingElement(string? n, string? ns, object? o, Type? ambientType, bool suppressReference, bool isNullable) { if (o == null) { @@ -1294,8 +1299,8 @@ protected void WritePotentiallyReferencingElement(string n, string ns, object o, { if (n == null) { - TypeEntry entry = GetTypeEntry(t); - WriteReferencingElement(entry.typeName, entry.typeNs, o, isNullable); + TypeEntry entry = GetTypeEntry(t)!; + WriteReferencingElement(entry.typeName!, entry.typeNs, o, isNullable); } else WriteReferencingElement(n, ns, o, isNullable); @@ -1305,16 +1310,16 @@ protected void WritePotentiallyReferencingElement(string n, string ns, object o, { // Enums always write xsi:type, so don't write it again here. bool needXsiType = t != ambientType && !t.IsEnum; - TypeEntry entry = GetTypeEntry(t); + TypeEntry? entry = GetTypeEntry(t); if (entry != null) { if (n == null) - WriteStartElement(entry.typeName, entry.typeNs, null, true); + WriteStartElement(entry.typeName!, entry.typeNs, null, true); else WriteStartElement(n, ns, null, true); - if (needXsiType) WriteXsiType(entry.typeName, entry.typeNs); - entry.callback(o); + if (needXsiType) WriteXsiType(entry.typeName!, entry.typeNs); + entry.callback!(o); _w.WriteEndElement(); } else @@ -1325,12 +1330,12 @@ protected void WritePotentiallyReferencingElement(string n, string ns, object o, } - private void WriteReferencedElement(object o, Type ambientType) + private void WriteReferencedElement(object o, Type? ambientType) { WriteReferencedElement(null, null, o, ambientType); } - private void WriteReferencedElement(string name, string ns, object o, Type ambientType) + private void WriteReferencedElement(string? name, string? ns, object o, Type? ambientType) { if (name == null) name = string.Empty; Type t = o.GetType(); @@ -1340,24 +1345,24 @@ private void WriteReferencedElement(string name, string ns, object o, Type ambie } else { - TypeEntry entry = GetTypeEntry(t); + TypeEntry? entry = GetTypeEntry(t); if (entry == null) throw CreateUnknownTypeException(t); - WriteStartElement(name.Length == 0 ? entry.typeName : name, ns == null ? entry.typeNs : ns, null, true); + WriteStartElement(name.Length == 0 ? entry.typeName! : name!, ns == null ? entry.typeNs : ns, null, true); WriteId(o, false); - if (ambientType != t) WriteXsiType(entry.typeName, entry.typeNs); - entry.callback(o); + if (ambientType != t) WriteXsiType(entry.typeName!, entry.typeNs); + entry.callback!(o); _w.WriteEndElement(); } } - private TypeEntry GetTypeEntry(Type t) + private TypeEntry? GetTypeEntry(Type t) { if (_typeEntries == null) { _typeEntries = new Hashtable(); InitCallbacks(); } - return (TypeEntry)_typeEntries[t]; + return (TypeEntry?)_typeEntries[t]; } protected abstract void InitCallbacks(); @@ -1368,7 +1373,7 @@ protected void WriteReferencedElements() for (int i = 0; i < _referencesToWrite.Count; i++) { - WriteReferencedElement(_referencesToWrite[i], null); + WriteReferencedElement(_referencesToWrite[i]!, null); } } @@ -1378,23 +1383,23 @@ protected void TopLevelElement() } /// - protected void WriteNamespaceDeclarations(XmlSerializerNamespaces xmlns) + protected void WriteNamespaceDeclarations(XmlSerializerNamespaces? xmlns) { if (xmlns != null) { - foreach (KeyValuePair entry in xmlns.Namespaces) + foreach (KeyValuePair entry in xmlns.Namespaces) { string prefix = (string)entry.Key; - string ns = (string)entry.Value; + string? ns = (string?)entry.Value; if (_namespaces != null) { - string oldNs; + string? oldNs; if (_namespaces.Namespaces.TryGetValue(prefix, out oldNs) && oldNs != null && oldNs != ns) { throw new InvalidOperationException(SR.Format(SR.XmlDuplicateNs, prefix, ns)); } } - string oldPrefix = (ns == null || ns.Length == 0) ? null : Writer.LookupPrefix(ns); + string? oldPrefix = (ns == null || ns.Length == 0) ? null : Writer.LookupPrefix(ns); if (oldPrefix == null || oldPrefix != prefix) { @@ -1402,6 +1407,7 @@ protected void WriteNamespaceDeclarations(XmlSerializerNamespaces xmlns) } } } + _namespaces = null; } @@ -1417,14 +1423,13 @@ private string NextPrefix() internal class TypeEntry { - internal XmlSerializationWriteCallback callback; - internal string typeNs; - internal string typeName; - internal Type type; + internal XmlSerializationWriteCallback? callback; + internal string? typeNs; + internal string? typeName; + internal Type? type; } } - /// public delegate void XmlSerializationWriteCallback(object o); @@ -1439,7 +1444,7 @@ internal static class DynamicAssemblies // It's OK to suppress the SxS warning. internal static bool IsTypeDynamic(Type type) { - object oIsTypeDynamic = s_tableIsTypeDynamic[type]; + object? oIsTypeDynamic = s_tableIsTypeDynamic[type]; if (oIsTypeDynamic == null) { Assembly assembly = type.Assembly; @@ -1448,7 +1453,7 @@ internal static bool IsTypeDynamic(Type type) { if (type.IsArray) { - isTypeDynamic = IsTypeDynamic(type.GetElementType()); + isTypeDynamic = IsTypeDynamic(type.GetElementType()!); } else if (type.IsGenericType) { @@ -1494,8 +1499,8 @@ internal static void Add(Assembly a) //already added return; } - Assembly oldAssembly = s_nameToAssemblyMap[a.FullName] as Assembly; - string key = null; + Assembly? oldAssembly = s_nameToAssemblyMap[a.FullName!] as Assembly; + string? key = null; if (oldAssembly == null) { key = a.FullName; @@ -1513,14 +1518,14 @@ internal static void Add(Assembly a) } } - internal static Assembly Get(string fullName) + internal static Assembly? Get(string fullName) { - return s_nameToAssemblyMap != null ? (Assembly)s_nameToAssemblyMap[fullName] : null; + return s_nameToAssemblyMap != null ? (Assembly?)s_nameToAssemblyMap[fullName] : null; } - internal static string GetName(Assembly a) + internal static string? GetName(Assembly a) { - return s_assemblyToNameMap != null ? (string)s_assemblyToNameMap[a] : null; + return s_assemblyToNameMap != null ? (string?)s_assemblyToNameMap[a] : null; } } @@ -1543,7 +1548,7 @@ internal class ReflectionAwareCodeGen // ArrayAccessor "0:"+CodeIdentifier.EscapedKeywords(typeof(Array).FullName) // MyCollectionAccessor "0:"+CodeIdentifier.EscapedKeywords(typeof(MyCollection).FullName) // ---------------------------------------------------------------------------------- - private Hashtable _reflectionVariables; + private Hashtable _reflectionVariables = null!; private int _nextReflectionVariableNumber; private readonly IndentedWriter _writer; internal ReflectionAwareCodeGen(IndentedWriter writer) @@ -1565,17 +1570,17 @@ private string WriteTypeInfo(TypeScope scope, TypeDesc typeDesc, Type type) { InitTheFirstTime(); string typeFullName = typeDesc.CSharpName; - string typeVariable = (string)_reflectionVariables[typeFullName]; + string? typeVariable = (string?)_reflectionVariables[typeFullName]; if (typeVariable != null) return typeVariable; if (type.IsArray) { typeVariable = GenerateVariableName("array", typeDesc.CSharpName); - TypeDesc elementTypeDesc = typeDesc.ArrayElementTypeDesc; + TypeDesc elementTypeDesc = typeDesc.ArrayElementTypeDesc!; if (elementTypeDesc.UseReflection) { - string elementTypeVariable = WriteTypeInfo(scope, elementTypeDesc, scope.GetTypeFromTypeDesc(elementTypeDesc)); + string elementTypeVariable = WriteTypeInfo(scope, elementTypeDesc, scope.GetTypeFromTypeDesc(elementTypeDesc)!); _writer.WriteLine("static " + typeof(Type).FullName + " " + typeVariable + " = " + elementTypeVariable + ".MakeArrayType();"); } else @@ -1590,7 +1595,7 @@ private string WriteTypeInfo(TypeScope scope, TypeDesc typeDesc, Type type) { typeVariable = GenerateVariableName(nameof(type), typeDesc.CSharpName); - Type parameterType = Nullable.GetUnderlyingType(type); + Type? parameterType = Nullable.GetUnderlyingType(type); if (parameterType != null) { string parameterTypeVariable = WriteTypeInfo(scope, scope.GetTypeDesc(parameterType), parameterType); @@ -1607,19 +1612,21 @@ private string WriteTypeInfo(TypeScope scope, TypeDesc typeDesc, Type type) _reflectionVariables.Add(typeFullName, typeVariable); - TypeMapping mapping = scope.GetTypeMappingFromTypeDesc(typeDesc); + TypeMapping? mapping = scope.GetTypeMappingFromTypeDesc(typeDesc); if (mapping != null) WriteMappingInfo(mapping, typeVariable, type); if (typeDesc.IsCollection || typeDesc.IsEnumerable) {// Arrays use the generic item_Array - TypeDesc elementTypeDesc = typeDesc.ArrayElementTypeDesc; + TypeDesc elementTypeDesc = typeDesc.ArrayElementTypeDesc!; if (elementTypeDesc.UseReflection) - WriteTypeInfo(scope, elementTypeDesc, scope.GetTypeFromTypeDesc(elementTypeDesc)); + WriteTypeInfo(scope, elementTypeDesc, scope.GetTypeFromTypeDesc(elementTypeDesc)!); WriteCollectionInfo(typeVariable, typeDesc, type); } + return typeVariable; } + [MemberNotNull(nameof(_reflectionVariables))] private void InitTheFirstTime() { if (_reflectionVariables == null) @@ -1629,17 +1636,17 @@ private void InitTheFirstTime() "object", "string", typeof(Type).FullName, typeof(FieldInfo).FullName, typeof(PropertyInfo).FullName)); - WriteDefaultIndexerInit(typeof(IList), typeof(Array).FullName, false, false); + WriteDefaultIndexerInit(typeof(IList), typeof(Array).FullName!, false, false); } } private void WriteMappingInfo(TypeMapping mapping, string typeVariable, Type type) { - string typeFullName = mapping.TypeDesc.CSharpName; + string typeFullName = mapping.TypeDesc!.CSharpName; if (mapping is StructMapping) { - StructMapping structMapping = mapping as StructMapping; - for (int i = 0; i < structMapping.Members.Length; i++) + StructMapping structMapping = (mapping as StructMapping)!; + for (int i = 0; i < structMapping.Members!.Length; i++) { MemberMapping member = structMapping.Members[i]; string memberVariable = WriteMemberInfo(type, typeFullName, typeVariable, member.Name); @@ -1655,7 +1662,7 @@ private void WriteMappingInfo(TypeMapping mapping, string typeVariable, Type typ } if (member.ChoiceIdentifier != null) { - string memberName = member.ChoiceIdentifier.MemberName; + string memberName = member.ChoiceIdentifier.MemberName!; memberVariable = WriteMemberInfo(type, typeFullName, typeVariable, memberName); } } @@ -1672,7 +1679,7 @@ private void WriteMappingInfo(TypeMapping mapping, string typeVariable, Type typ private void WriteCollectionInfo(string typeVariable, TypeDesc typeDesc, Type type) { string typeFullName = CodeIdentifier.GetCSharpName(type); - string elementTypeFullName = typeDesc.ArrayElementTypeDesc.CSharpName; + string elementTypeFullName = typeDesc.ArrayElementTypeDesc!.CSharpName; bool elementUseReflection = typeDesc.ArrayElementTypeDesc.UseReflection; if (typeDesc.IsCollection) { @@ -1694,8 +1701,8 @@ private void WriteCollectionInfo(string typeVariable, TypeDesc typeDesc, Type ty private string WriteAssemblyInfo(Type type) { - string assemblyFullName = type.Assembly.FullName; - string assemblyVariable = (string)_reflectionVariables[assemblyFullName]; + string assemblyFullName = type.Assembly.FullName!; + string? assemblyVariable = (string?)_reflectionVariables[assemblyFullName]; if (assemblyVariable == null) { int iComma = assemblyFullName.IndexOf(','); @@ -1744,7 +1751,7 @@ private string WriteMethodInfo(string escapedName, string typeVariable, string m WriteQuotedCSharpString(memberName); _writer.Write(", "); - string bindingFlags = typeof(BindingFlags).FullName; + string bindingFlags = typeof(BindingFlags).FullName!; _writer.Write(bindingFlags); _writer.Write(".Public | "); _writer.Write(bindingFlags); @@ -1797,14 +1804,14 @@ private string GenerateVariableName(string prefix, string fullName) return prefix + _nextReflectionVariableNumber + "_" + CodeIdentifier.MakeValidInternal(fullName.Replace('.', '_')); } - internal string GetReflectionVariable(string typeFullName, string memberName) + internal string? GetReflectionVariable(string typeFullName, string? memberName) { string key; if (memberName == null) key = typeFullName; else key = memberName + ":" + typeFullName; - return (string)_reflectionVariables[key]; + return (string?)_reflectionVariables[key]; } @@ -1843,9 +1850,9 @@ internal string GetStringForEnumCompare(EnumMapping mapping, string memberName, if (!useReflection) { CodeIdentifier.CheckValidIdentifier(memberName); - return mapping.TypeDesc.CSharpName + ".@" + memberName; + return mapping.TypeDesc!.CSharpName + ".@" + memberName; } - string memberAccess = GetStringForEnumMember(mapping.TypeDesc.CSharpName, memberName, useReflection); + string memberAccess = GetStringForEnumMember(mapping.TypeDesc!.CSharpName, memberName, useReflection); return GetStringForEnumLongValue(memberAccess, useReflection); } internal string GetStringForEnumLongValue(string variable, bool useReflection) @@ -1859,7 +1866,7 @@ internal string GetStringForTypeof(string typeFullName, bool useReflection) { if (useReflection) { - return GetReflectionVariable(typeFullName, null); + return GetReflectionVariable(typeFullName, null)!; } else { @@ -1875,11 +1882,11 @@ internal string GetStringForMember(string obj, string memberName, TypeDesc typeD while (typeDesc != null) { string typeFullName = typeDesc.CSharpName; - string memberInfoName = GetReflectionVariable(typeFullName, memberName); + string? memberInfoName = GetReflectionVariable(typeFullName, memberName); if (memberInfoName != null) return memberInfoName + "[" + obj + "]"; // member may be part of the basetype - typeDesc = typeDesc.BaseTypeDesc; + typeDesc = typeDesc.BaseTypeDesc!; if (typeDesc != null && !typeDesc.UseReflection) return "((" + typeDesc.CSharpName + ")" + obj + ").@" + memberName; } @@ -1909,17 +1916,18 @@ internal string GetStringForEnumMember(string typeFullName, string memberName, b if (!useReflection) return typeFullName + ".@" + memberName; - string memberInfoName = GetReflectionVariable(typeFullName, memberName); + string? memberInfoName = GetReflectionVariable(typeFullName, memberName); return memberInfoName + "[null]"; } + internal string GetStringForArrayMember(string arrayName, string subscript, TypeDesc arrayTypeDesc) { if (!arrayTypeDesc.UseReflection) { return arrayName + "[" + subscript + "]"; } - string typeFullName = arrayTypeDesc.IsCollection ? arrayTypeDesc.CSharpName : typeof(Array).FullName; - string arrayInfo = GetReflectionVariable(typeFullName, arrayMemberKey); + string typeFullName = arrayTypeDesc.IsCollection ? arrayTypeDesc.CSharpName : typeof(Array).FullName!; + string? arrayInfo = GetReflectionVariable(typeFullName, arrayMemberKey); return arrayInfo + "[" + arrayName + ", " + subscript + "]"; } internal string GetStringForMethod(string obj, string typeFullName, string memberName, bool useReflection) @@ -1927,7 +1935,7 @@ internal string GetStringForMethod(string obj, string typeFullName, string membe if (!useReflection) return obj + "." + memberName + "("; - string memberInfoName = GetReflectionVariable(typeFullName, memberName); + string? memberInfoName = GetReflectionVariable(typeFullName, memberName); return memberInfoName + ".Invoke(" + obj + ", new object[]{"; } internal string GetStringForCreateInstance(string escapedTypeName, bool useReflection, bool ctorInaccessible, bool cast) @@ -1942,7 +1950,7 @@ internal string GetStringForCreateInstance(string escapedTypeName, bool useRefle return GetStringForCreateInstance(GetStringForTypeof(escapedTypeName, useReflection), cast && !useReflection ? escapedTypeName : null, ctorInaccessible, arg); } - internal string GetStringForCreateInstance(string type, string cast, bool nonPublic, string arg) + internal string GetStringForCreateInstance(string type, string? cast, bool nonPublic, string? arg) { StringBuilder createInstance = new StringBuilder(); if (cast != null && cast.Length > 0) @@ -1955,7 +1963,7 @@ internal string GetStringForCreateInstance(string type, string cast, bool nonPub createInstance.Append(".CreateInstance("); createInstance.Append(type); createInstance.Append(", "); - string bindingFlags = typeof(BindingFlags).FullName; + string bindingFlags = typeof(BindingFlags).FullName!; createInstance.Append(bindingFlags); createInstance.Append(".Instance | "); createInstance.Append(bindingFlags); @@ -1969,6 +1977,7 @@ internal string GetStringForCreateInstance(string type, string cast, bool nonPub createInstance.Append(bindingFlags); createInstance.Append(".NonPublic"); } + if (arg == null || arg.Length == 0) { createInstance.Append(", null, new object[0], null)"); @@ -2025,16 +2034,16 @@ internal void WriteInstanceOf(string source, string escapedTypeName, bool useRef _writer.Write(".GetType())"); } - internal void WriteArrayLocalDecl(string typeName, string variableName, string initValue, TypeDesc arrayTypeDesc) + internal void WriteArrayLocalDecl(string typeName, string variableName, string? initValue, TypeDesc arrayTypeDesc) { if (arrayTypeDesc.UseReflection) { if (arrayTypeDesc.IsEnumerable) - typeName = typeof(IEnumerable).FullName; + typeName = typeof(IEnumerable).FullName!; else if (arrayTypeDesc.IsCollection) - typeName = typeof(ICollection).FullName; + typeName = typeof(ICollection).FullName!; else - typeName = typeof(Array).FullName; + typeName = typeof(Array).FullName!; } _writer.Write(typeName); _writer.Write(" "); @@ -2086,7 +2095,7 @@ internal void WriteArrayTypeCompare(string variable, string escapedTypeName, str WriteTypeCompare(variable + ".GetElementType()", elementTypeName, useReflection); } - internal static void WriteQuotedCSharpString(IndentedWriter writer, string value) + internal static void WriteQuotedCSharpString(IndentedWriter writer, string? value) { if (value == null) { @@ -2124,7 +2133,7 @@ internal static void WriteQuotedCSharpString(IndentedWriter writer, string value writer.Write("\""); } - internal void WriteQuotedCSharpString(string value) + internal void WriteQuotedCSharpString(string? value) { WriteQuotedCSharpString(_writer, value); } @@ -2198,9 +2207,10 @@ internal void GenerateBegin() { if (mapping is StructMapping || mapping is EnumMapping) { - MethodNames.Add(mapping, NextMethodName(mapping.TypeDesc.Name)); + MethodNames.Add(mapping, NextMethodName(mapping.TypeDesc!.Name)); } } + RaCodeGen.WriteReflectionInit(scope); } @@ -2243,7 +2253,7 @@ internal void GenerateEnd() Writer.WriteLine("}"); } - internal string GenerateElement(XmlMapping xmlMapping) + internal string? GenerateElement(XmlMapping xmlMapping) { if (!xmlMapping.IsWriteable) return null; @@ -2269,9 +2279,9 @@ private void GenerateInitCallbacksMethod() { if (typeMapping.IsSoap && (typeMapping is StructMapping || typeMapping is EnumMapping) && - !typeMapping.TypeDesc.IsRoot) + !typeMapping.TypeDesc!.IsRoot) { - string methodName = (string)MethodNames[typeMapping]; + string methodName = (string)MethodNames[typeMapping]!; Writer.Write("AddWriteCallback("); Writer.Write(RaCodeGen.GetStringForTypeof(typeMapping.TypeDesc.CSharpName, typeMapping.TypeDesc.UseReflection)); Writer.Write(", "); @@ -2286,16 +2296,17 @@ private void GenerateInitCallbacksMethod() } } } + Writer.Indent--; Writer.WriteLine("}"); } - private void WriteQualifiedNameElement(string name, string ns, object defaultValue, string source, bool nullable, bool IsSoap, TypeMapping mapping) + private void WriteQualifiedNameElement(string name, string? ns, object? defaultValue, string source, bool nullable, bool IsSoap, TypeMapping mapping) { bool hasDefault = defaultValue != null && defaultValue != DBNull.Value; if (hasDefault) { - WriteCheckDefault(mapping, source, defaultValue, nullable); + WriteCheckDefault(mapping, source, defaultValue!, nullable); Writer.WriteLine(" {"); Writer.Indent++; } @@ -2331,11 +2342,11 @@ private void WriteQualifiedNameElement(string name, string ns, object defaultVal private void WriteEnumValue(EnumMapping mapping, string source) { - string methodName = ReferenceMapping(mapping); + string? methodName = ReferenceMapping(mapping); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe - if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc.Name) + Environment.StackTrace); + if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc!.Name) + Environment.StackTrace); #endif Writer.Write(methodName); @@ -2372,21 +2383,21 @@ private void WritePrimitiveValue(TypeDesc typeDesc, string source, bool isElemen } } - private void WritePrimitive(string method, string name, string ns, object defaultValue, string source, TypeMapping mapping, bool writeXsiType, bool isElement, bool isNullable) + private void WritePrimitive(string method, string name, string? ns, object? defaultValue, string source, TypeMapping mapping, bool writeXsiType, bool isElement, bool isNullable) { - TypeDesc typeDesc = mapping.TypeDesc; - bool hasDefault = defaultValue != null && defaultValue != DBNull.Value && mapping.TypeDesc.HasDefaultSupport; + TypeDesc typeDesc = mapping.TypeDesc!; + bool hasDefault = defaultValue != null && defaultValue != DBNull.Value && mapping.TypeDesc!.HasDefaultSupport; if (hasDefault) { if (mapping is EnumMapping) { #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe - if (defaultValue.GetType() != typeof(string)) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, name + " has invalid default type " + defaultValue.GetType().Name)); + if (defaultValue!.GetType() != typeof(string)) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, name + " has invalid default type " + defaultValue.GetType().Name)); #endif Writer.Write("if ("); - if (mapping.TypeDesc.UseReflection) + if (mapping.TypeDesc!.UseReflection) Writer.Write(RaCodeGen.GetStringForEnumLongValue(source, mapping.TypeDesc.UseReflection)); else Writer.Write(source); @@ -2413,11 +2424,12 @@ private void WritePrimitive(string method, string name, string ns, object defaul } else { - WriteCheckDefault(mapping, source, defaultValue, isNullable); + WriteCheckDefault(mapping, source, defaultValue!, isNullable); } Writer.WriteLine(" {"); Writer.Indent++; } + Writer.Write(method); Writer.Write("("); WriteQuotedCSharpString(name); @@ -2426,6 +2438,7 @@ private void WritePrimitive(string method, string name, string ns, object defaul Writer.Write(", "); WriteQuotedCSharpString(ns); } + Writer.Write(", "); if (mapping is EnumMapping) @@ -2455,7 +2468,7 @@ private void WritePrimitive(string method, string name, string ns, object defaul } } - private void WriteTag(string methodName, string name, string ns) + private void WriteTag(string methodName, string name, string? ns) { Writer.Write(methodName); Writer.Write("("); @@ -2472,7 +2485,7 @@ private void WriteTag(string methodName, string name, string ns) Writer.WriteLine(");"); } - private void WriteTag(string methodName, string name, string ns, bool writePrefixed) + private void WriteTag(string methodName, string name, string? ns, bool writePrefixed) { Writer.Write(methodName); Writer.Write("("); @@ -2494,7 +2507,7 @@ private void WriteTag(string methodName, string name, string ns, bool writePrefi Writer.WriteLine(");"); } - private void WriteStartElement(string name, string ns, bool writePrefixed) + private void WriteStartElement(string name, string? ns, bool writePrefixed) { WriteTag("WriteStartElement", name, ns, writePrefixed); } @@ -2510,17 +2523,17 @@ private void WriteEndElement(string source) Writer.WriteLine(");"); } - private void WriteEncodedNullTag(string name, string ns) + private void WriteEncodedNullTag(string name, string? ns) { WriteTag("WriteNullTagEncoded", name, ns); } - private void WriteLiteralNullTag(string name, string ns) + private void WriteLiteralNullTag(string name, string? ns) { WriteTag("WriteNullTagLiteral", name, ns); } - private void WriteEmptyTag(string name, string ns) + private void WriteEmptyTag(string name, string? ns) { WriteTag("WriteEmptyTag", name, ns); } @@ -2528,7 +2541,7 @@ private void WriteEmptyTag(string name, string ns) private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) { ElementAccessor element = xmlMembersMapping.Accessor; - MembersMapping mapping = (MembersMapping)element.Mapping; + MembersMapping mapping = (MembersMapping)element.Mapping!; bool hasWrapperElement = mapping.HasWrapperElement; bool writeAccessors = mapping.WriteAccessors; bool isRpc = xmlMembersMapping.IsSoap && writeAccessors; @@ -2555,10 +2568,10 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) { WriteStartElement(element.Name, (element.Form == XmlSchemaForm.Qualified ? element.Namespace : ""), mapping.IsSoap); - int xmlnsMember = FindXmlnsIndex(mapping.Members); + int xmlnsMember = FindXmlnsIndex(mapping.Members!); if (xmlnsMember >= 0) { - MemberMapping member = mapping.Members[xmlnsMember]; + MemberMapping member = mapping.Members![xmlnsMember]; string source = "((" + typeof(System.Xml.Serialization.XmlSerializerNamespaces).FullName + ")p[" + xmlnsMember.ToString(CultureInfo.InvariantCulture) + "])"; Writer.Write("if (pLength > "); @@ -2570,7 +2583,7 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) Writer.WriteLine("}"); } - for (int i = 0; i < mapping.Members.Length; i++) + for (int i = 0; i < mapping.Members!.Length; i++) { MemberMapping member = mapping.Members[i]; @@ -2579,7 +2592,7 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) string index = i.ToString(CultureInfo.InvariantCulture); string source = "p[" + index + "]"; - string specifiedSource = null; + string? specifiedSource = null; int specifiedPosition = 0; if (member.CheckSpecified != SpecifiedAccessor.None) { @@ -2610,7 +2623,7 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) Writer.Indent++; } - WriteMember(source, member.Attribute, member.TypeDesc, "p"); + WriteMember(source, member.Attribute, member.TypeDesc!, "p"); if (specifiedSource != null) { @@ -2624,7 +2637,7 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) } } - for (int i = 0; i < mapping.Members.Length; i++) + for (int i = 0; i < mapping.Members!.Length; i++) { MemberMapping member = mapping.Members[i]; if (member.Xmlns != null) @@ -2632,7 +2645,7 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) if (member.Ignore) continue; - string specifiedSource = null; + string? specifiedSource = null; int specifiedPosition = 0; if (member.CheckSpecified != SpecifiedAccessor.None) { @@ -2666,17 +2679,17 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) } string source = "p[" + index + "]"; - string enumSource = null; + string? enumSource = null; if (member.ChoiceIdentifier != null) { for (int j = 0; j < mapping.Members.Length; j++) { if (mapping.Members[j].Name == member.ChoiceIdentifier.MemberName) { - if (member.ChoiceIdentifier.Mapping.TypeDesc.UseReflection) + if (member.ChoiceIdentifier.Mapping!.TypeDesc!.UseReflection) enumSource = "p[" + j.ToString(CultureInfo.InvariantCulture) + "]"; else - enumSource = "((" + mapping.Members[j].TypeDesc.CSharpName + ")p[" + j.ToString(CultureInfo.InvariantCulture) + "]" + ")"; + enumSource = "((" + mapping.Members[j].TypeDesc!.CSharpName + ")p[" + j.ToString(CultureInfo.InvariantCulture) + "]" + ")"; break; } } @@ -2687,7 +2700,7 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) #endif } - if (isRpc && member.IsReturnValue && member.Elements.Length > 0) + if (isRpc && member.IsReturnValue && member.Elements!.Length > 0) { Writer.Write("WriteRpcResult("); WriteQuotedCSharpString(member.Elements[0].Name); @@ -2697,7 +2710,7 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) } // override writeAccessors choice when we've written a wrapper element - WriteMember(source, enumSource, member.ElementsSortedByDerivation, member.Text, member.ChoiceIdentifier, member.TypeDesc, writeAccessors || hasWrapperElement); + WriteMember(source, enumSource, member.ElementsSortedByDerivation!, member.Text, member.ChoiceIdentifier, member.TypeDesc!, writeAccessors || hasWrapperElement); if (specifiedSource != null) { @@ -2738,7 +2751,7 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) private string GenerateTypeElement(XmlTypeMapping xmlTypeMapping) { ElementAccessor element = xmlTypeMapping.Accessor; - TypeMapping mapping = element.Mapping; + TypeMapping mapping = element.Mapping!; string methodName = NextMethodName(element.Name); Writer.WriteLine(); Writer.Write("public void "); @@ -2763,12 +2776,12 @@ private string GenerateTypeElement(XmlTypeMapping xmlTypeMapping) Writer.Indent--; Writer.WriteLine("}"); - if (!mapping.IsSoap && !mapping.TypeDesc.IsValueType && !mapping.TypeDesc.Type.IsPrimitive) + if (!mapping.IsSoap && !mapping.TypeDesc!.IsValueType && !mapping.TypeDesc.Type!.IsPrimitive) { Writer.WriteLine("TopLevelElement();"); } - WriteMember("o", null, new ElementAccessor[] { element }, null, null, mapping.TypeDesc, !element.IsSoap); + WriteMember("o", null, new ElementAccessor[] { element }, null, null, mapping.TypeDesc!, !element.IsSoap); if (mapping.IsSoap) { @@ -2786,9 +2799,9 @@ private string NextMethodName(string name) private void WriteEnumMethod(EnumMapping mapping) { - string methodName = (string)MethodNames[mapping]; + string methodName = (string)MethodNames[mapping]!; Writer.WriteLine(); - string fullTypeName = mapping.TypeDesc.CSharpName; + string fullTypeName = mapping.TypeDesc!.CSharpName; if (mapping.IsSoap) { Writer.Write("void "); @@ -2806,7 +2819,7 @@ private void WriteEnumMethod(EnumMapping mapping) } Writer.Indent++; Writer.WriteLine("string s = null;"); - ConstantMapping[] constants = mapping.Constants; + ConstantMapping[] constants = mapping.Constants!; if (constants.Length > 0) { @@ -2898,19 +2911,19 @@ private void WriteEnumMethod(EnumMapping mapping) private void WriteDerivedTypes(StructMapping mapping) { - for (StructMapping derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) + for (StructMapping? derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) { - string fullTypeName = derived.TypeDesc.CSharpName; + string fullTypeName = derived.TypeDesc!.CSharpName; Writer.Write("if ("); WriteTypeCompare("t", fullTypeName, derived.TypeDesc.UseReflection); Writer.WriteLine(") {"); Writer.Indent++; - string methodName = ReferenceMapping(derived); + string? methodName = ReferenceMapping(derived); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe - if (methodName == null) throw new InvalidOperationException("derived from " + mapping.TypeDesc.FullName + ", " + SR.Format(SR.XmlInternalErrorMethod, derived.TypeDesc.Name) + Environment.StackTrace); + if (methodName == null) throw new InvalidOperationException("derived from " + mapping.TypeDesc!.FullName + ", " + SR.Format(SR.XmlInternalErrorMethod, derived.TypeDesc.Name) + Environment.StackTrace); #endif Writer.Write(methodName); @@ -2938,13 +2951,13 @@ private void WriteEnumAndArrayTypes() if (m is EnumMapping && !m.IsSoap) { EnumMapping mapping = (EnumMapping)m; - string fullTypeName = mapping.TypeDesc.CSharpName; + string fullTypeName = mapping.TypeDesc!.CSharpName; Writer.Write("if ("); WriteTypeCompare("t", fullTypeName, mapping.TypeDesc.UseReflection); Writer.WriteLine(") {"); Writer.Indent++; - string methodName = ReferenceMapping(mapping); + string? methodName = ReferenceMapping(mapping); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe @@ -2968,12 +2981,12 @@ private void WriteEnumAndArrayTypes() } else if (m is ArrayMapping && !m.IsSoap) { - ArrayMapping mapping = m as ArrayMapping; + ArrayMapping? mapping = m as ArrayMapping; if (mapping == null || m.IsSoap) continue; - string fullTypeName = mapping.TypeDesc.CSharpName; + string fullTypeName = mapping.TypeDesc!.CSharpName; Writer.Write("if ("); if (mapping.TypeDesc.IsArray) - WriteArrayTypeCompare("t", fullTypeName, mapping.TypeDesc.ArrayElementTypeDesc.CSharpName, mapping.TypeDesc.UseReflection); + WriteArrayTypeCompare("t", fullTypeName, mapping.TypeDesc.ArrayElementTypeDesc!.CSharpName, mapping.TypeDesc.UseReflection); else WriteTypeCompare("t", fullTypeName, mapping.TypeDesc.UseReflection); Writer.WriteLine(") {"); @@ -2986,7 +2999,7 @@ private void WriteEnumAndArrayTypes() WriteQuotedCSharpString(mapping.Namespace); Writer.WriteLine(");"); - WriteMember("o", null, mapping.ElementsSortedByDerivation, null, null, mapping.TypeDesc, true); + WriteMember("o", null, mapping.ElementsSortedByDerivation!, null, null, mapping.TypeDesc, true); Writer.WriteLine("Writer.WriteEndElement();"); Writer.WriteLine("return;"); @@ -2999,14 +3012,14 @@ private void WriteEnumAndArrayTypes() private void WriteStructMethod(StructMapping mapping) { - if (mapping.IsSoap && mapping.TypeDesc.IsRoot) return; - string methodName = (string)MethodNames[mapping]; + if (mapping.IsSoap && mapping.TypeDesc!.IsRoot) return; + string? methodName = (string?)MethodNames[mapping]; Writer.WriteLine(); Writer.Write("void "); Writer.Write(methodName); - string fullTypeName = mapping.TypeDesc.CSharpName; + string fullTypeName = mapping.TypeDesc!.CSharpName; if (mapping.IsSoap) { @@ -3069,7 +3082,7 @@ private void WriteStructMethod(StructMapping mapping) Writer.WriteLine("EscapeName = false;"); } - string xmlnsSource = null; + string? xmlnsSource = null; MemberMapping[] members = TypeScope.GetAllMembers(mapping); int xmlnsMember = FindXmlnsIndex(members); if (xmlnsMember >= 0) @@ -3079,7 +3092,7 @@ private void WriteStructMethod(StructMapping mapping) xmlnsSource = RaCodeGen.GetStringForMember("o", member.Name, mapping.TypeDesc); if (mapping.TypeDesc.UseReflection) { - xmlnsSource = "((" + member.TypeDesc.CSharpName + ")" + xmlnsSource + ")"; + xmlnsSource = "((" + member.TypeDesc!.CSharpName + ")" + xmlnsSource + ")"; } } @@ -3129,7 +3142,7 @@ private void WriteStructMethod(StructMapping mapping) Writer.WriteLine(") {"); Writer.Indent++; } - WriteMember(RaCodeGen.GetStringForMember("o", m.Name, mapping.TypeDesc), m.Attribute, m.TypeDesc, "o"); + WriteMember(RaCodeGen.GetStringForMember("o", m.Name, mapping.TypeDesc), m.Attribute, m.TypeDesc!, "o"); if (m.CheckSpecified != SpecifiedAccessor.None) { @@ -3150,7 +3163,7 @@ private void WriteStructMethod(StructMapping mapping) if (m.Xmlns != null) continue; CodeIdentifier.CheckValidIdentifier(m.Name); - bool checkShouldPersist = m.CheckShouldPersist && (m.Elements.Length > 0 || m.Text != null); + bool checkShouldPersist = m.CheckShouldPersist && (m.Elements!.Length > 0 || m.Text != null); if (checkShouldPersist) { @@ -3171,13 +3184,13 @@ private void WriteStructMethod(StructMapping mapping) Writer.Indent++; } - string choiceSource = null; + string? choiceSource = null; if (m.ChoiceIdentifier != null) { CodeIdentifier.CheckValidIdentifier(m.ChoiceIdentifier.MemberName); choiceSource = RaCodeGen.GetStringForMember("o", m.ChoiceIdentifier.MemberName, mapping.TypeDesc); } - WriteMember(RaCodeGen.GetStringForMember("o", m.Name, mapping.TypeDesc), choiceSource, m.ElementsSortedByDerivation, m.Text, m.ChoiceIdentifier, m.TypeDesc, true); + WriteMember(RaCodeGen.GetStringForMember("o", m.Name, mapping.TypeDesc), choiceSource, m.ElementsSortedByDerivation!, m.Text, m.ChoiceIdentifier, m.TypeDesc!, true); if (m.CheckSpecified != SpecifiedAccessor.None) { @@ -3199,7 +3212,7 @@ private void WriteStructMethod(StructMapping mapping) Writer.WriteLine("}"); } - private bool CanOptimizeWriteListSequence(TypeDesc listElementTypeDesc) + private bool CanOptimizeWriteListSequence(TypeDesc? listElementTypeDesc) { // check to see if we can write values of the attribute sequentially // currently we have only one data type (XmlQualifiedName) that we can not write "inline", @@ -3229,7 +3242,7 @@ private void WriteMember(string source, AttributeAccessor attribute, TypeDesc me Writer.Write("Writer.WriteStartAttribute(null, "); WriteQuotedCSharpString(attribute.Name); Writer.Write(", "); - string ns = attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : string.Empty; + string? ns = attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : string.Empty; if (ns != null) { WriteQuotedCSharpString(ns); @@ -3248,7 +3261,7 @@ private void WriteMember(string source, AttributeAccessor attribute, TypeDesc me Writer.WriteLine("();"); } } - TypeDesc arrayElementTypeDesc = memberTypeDesc.ArrayElementTypeDesc; + TypeDesc arrayElementTypeDesc = memberTypeDesc.ArrayElementTypeDesc!; if (memberTypeDesc.IsEnumerable) { @@ -3353,7 +3366,7 @@ private void WriteMember(string source, AttributeAccessor attribute, TypeDesc me Writer.Write("WriteAttribute("); WriteQuotedCSharpString(attribute.Name); Writer.Write(", "); - string ns = attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : string.Empty; + string? ns = attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : string.Empty; if (ns != null) { WriteQuotedCSharpString(ns); @@ -3384,7 +3397,7 @@ private void WriteAttribute(string source, AttributeAccessor attribute, string p if (attribute.Mapping is SpecialMapping) { SpecialMapping special = (SpecialMapping)attribute.Mapping; - if (special.TypeDesc.Kind == TypeKind.Attribute || special.TypeDesc.CanBeAttributeValue) + if (special.TypeDesc!.Kind == TypeKind.Attribute || special.TypeDesc.CanBeAttributeValue) { Writer.Write("WriteXmlAttribute("); Writer.Write(source); @@ -3397,13 +3410,13 @@ private void WriteAttribute(string source, AttributeAccessor attribute, string p } else { - TypeDesc typeDesc = attribute.Mapping.TypeDesc; + TypeDesc typeDesc = attribute.Mapping!.TypeDesc!; if (!typeDesc.UseReflection) source = "((" + typeDesc.CSharpName + ")" + source + ")"; WritePrimitive("WriteAttribute", attribute.Name, attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : "", attribute.Default, source, attribute.Mapping, false, false, false); } } - private void WriteMember(string source, string choiceSource, ElementAccessor[] elements, TextAccessor text, ChoiceIdentifierAccessor choice, TypeDesc memberTypeDesc, bool writeAccessors) + private void WriteMember(string source, string? choiceSource, ElementAccessor[] elements, TextAccessor? text, ChoiceIdentifierAccessor? choice, TypeDesc memberTypeDesc, bool writeAccessors) { if (memberTypeDesc.IsArrayLike && !(elements.Length == 1 && elements[0].Mapping is ArrayMapping)) @@ -3413,7 +3426,7 @@ private void WriteMember(string source, string choiceSource, ElementAccessor[] e } - private void WriteArray(string source, string choiceSource, ElementAccessor[] elements, TextAccessor text, ChoiceIdentifierAccessor choice, TypeDesc arrayTypeDesc) + private void WriteArray(string source, string? choiceSource, ElementAccessor[] elements, TextAccessor? text, ChoiceIdentifierAccessor? choice, TypeDesc arrayTypeDesc) { if (elements.Length == 0 && text == null) return; Writer.WriteLine("{"); @@ -3428,7 +3441,7 @@ private void WriteArray(string source, string choiceSource, ElementAccessor[] el if (choice != null) { - bool choiceUseReflection = choice.Mapping.TypeDesc.UseReflection; + bool choiceUseReflection = choice.Mapping!.TypeDesc!.UseReflection; string choiceFullName = choice.Mapping.TypeDesc.CSharpName; WriteArrayLocalDecl(choiceFullName + "[]", "c", choiceSource, choice.Mapping.TypeDesc); // write check for the choice identifier array @@ -3453,9 +3466,9 @@ private void WriteArray(string source, string choiceSource, ElementAccessor[] el Writer.WriteLine("}"); } - private void WriteArrayItems(ElementAccessor[] elements, TextAccessor text, ChoiceIdentifierAccessor choice, TypeDesc arrayTypeDesc, string arrayName, string choiceName) + private void WriteArrayItems(ElementAccessor[] elements, TextAccessor? text, ChoiceIdentifierAccessor? choice, TypeDesc arrayTypeDesc, string arrayName, string? choiceName) { - TypeDesc arrayElementTypeDesc = arrayTypeDesc.ArrayElementTypeDesc; + TypeDesc arrayElementTypeDesc = arrayTypeDesc.ArrayElementTypeDesc!; if (arrayTypeDesc.IsEnumerable) { @@ -3540,8 +3553,8 @@ private void WriteArrayItems(ElementAccessor[] elements, TextAccessor text, Choi WriteLocalDecl(arrayTypeFullName, arrayName + "i", RaCodeGen.GetStringForArrayMember(arrayName, "i" + arrayName, arrayTypeDesc), arrayElementTypeDesc.UseReflection); if (choice != null) { - string choiceFullName = choice.Mapping.TypeDesc.CSharpName; - WriteLocalDecl(choiceFullName, choiceName + "i", RaCodeGen.GetStringForArrayMember(choiceName, "i" + arrayName, choice.Mapping.TypeDesc), choice.Mapping.TypeDesc.UseReflection); + string choiceFullName = choice.Mapping!.TypeDesc!.CSharpName; + WriteLocalDecl(choiceFullName, choiceName + "i", RaCodeGen.GetStringForArrayMember(choiceName!, "i" + arrayName, choice.Mapping.TypeDesc), choice.Mapping.TypeDesc.UseReflection); } WriteElements(arrayName + "i", choiceName + "i", elements, text, choice, arrayName + "a", true, arrayElementTypeDesc.IsNullable); } @@ -3554,18 +3567,18 @@ private void WriteArrayItems(ElementAccessor[] elements, TextAccessor text, Choi Writer.WriteLine("}"); } - private void WriteElements(string source, ElementAccessor[] elements, TextAccessor text, ChoiceIdentifierAccessor choice, string arrayName, bool writeAccessors, bool isNullable) + private void WriteElements(string source, ElementAccessor[] elements, TextAccessor? text, ChoiceIdentifierAccessor? choice, string arrayName, bool writeAccessors, bool isNullable) { WriteElements(source, null, elements, text, choice, arrayName, writeAccessors, isNullable); } - private void WriteElements(string source, string enumSource, ElementAccessor[] elements, TextAccessor text, ChoiceIdentifierAccessor choice, string arrayName, bool writeAccessors, bool isNullable) + private void WriteElements(string source, string? enumSource, ElementAccessor[] elements, TextAccessor? text, ChoiceIdentifierAccessor? choice, string arrayName, bool writeAccessors, bool isNullable) { if (elements.Length == 0 && text == null) return; if (elements.Length == 1 && text == null) { - TypeDesc td = elements[0].IsUnbounded ? elements[0].Mapping.TypeDesc.CreateArrayTypeDesc() : elements[0].Mapping.TypeDesc; - if (!elements[0].Any && !elements[0].Mapping.TypeDesc.UseReflection && !elements[0].Mapping.TypeDesc.IsOptionalValue) + TypeDesc td = elements[0].IsUnbounded ? elements[0].Mapping!.TypeDesc!.CreateArrayTypeDesc() : elements[0].Mapping!.TypeDesc!; + if (!elements[0].Any && !elements[0].Mapping!.TypeDesc!.UseReflection && !elements[0].Mapping!.TypeDesc!.IsOptionalValue) source = "((" + td.CSharpName + ")" + source + ")"; WriteElement(source, elements[0], arrayName, writeAccessors); } @@ -3581,9 +3594,9 @@ private void WriteElements(string source, string enumSource, ElementAccessor[] e Writer.Indent++; int anyCount = 0; ArrayList namedAnys = new ArrayList(); - ElementAccessor unnamedAny = null; // can only have one + ElementAccessor? unnamedAny = null; // can only have one bool wroteFirstIf = false; - string enumTypeName = choice == null ? null : choice.Mapping.TypeDesc.FullName; + string? enumTypeName = choice == null ? null : choice.Mapping!.TypeDesc!.FullName; for (int i = 0; i < elements.Length; i++) { @@ -3599,15 +3612,15 @@ private void WriteElements(string source, string enumSource, ElementAccessor[] e } else if (choice != null) { - bool useReflection = element.Mapping.TypeDesc.UseReflection; + bool useReflection = element.Mapping!.TypeDesc!.UseReflection; string fullTypeName = element.Mapping.TypeDesc.CSharpName; - bool enumUseReflection = choice.Mapping.TypeDesc.UseReflection; + bool enumUseReflection = choice.Mapping!.TypeDesc!.UseReflection; string enumFullName = (enumUseReflection ? "" : enumTypeName + ".@") + FindChoiceEnumValue(element, (EnumMapping)choice.Mapping, enumUseReflection); if (wroteFirstIf) Writer.Write("else "); else wroteFirstIf = true; Writer.Write("if ("); - Writer.Write(enumUseReflection ? RaCodeGen.GetStringForEnumLongValue(enumSource, enumUseReflection) : enumSource); + Writer.Write(enumUseReflection ? RaCodeGen.GetStringForEnumLongValue(enumSource!, enumUseReflection) : enumSource); Writer.Write(" == "); Writer.Write(enumFullName); if (isNullable && !element.IsNullable) @@ -3630,7 +3643,7 @@ private void WriteElements(string source, string enumSource, ElementAccessor[] e } else { - bool useReflection = element.Mapping.TypeDesc.UseReflection; + bool useReflection = element.Mapping!.TypeDesc!.UseReflection; TypeDesc td = element.IsUnbounded ? element.Mapping.TypeDesc.CreateArrayTypeDesc() : element.Mapping.TypeDesc; string fullTypeName = td.CSharpName; if (wroteFirstIf) Writer.Write("else "); @@ -3651,7 +3664,7 @@ private void WriteElements(string source, string enumSource, ElementAccessor[] e { if (elements.Length - anyCount > 0) Writer.Write("else "); - string fullTypeName = typeof(XmlElement).FullName; + string fullTypeName = typeof(XmlElement).FullName!; Writer.Write("if ("); Writer.Write(source); @@ -3673,15 +3686,15 @@ private void WriteElements(string source, string enumSource, ElementAccessor[] e { if (c++ > 0) Writer.Write("else "); - string enumFullName = null; + string? enumFullName = null; - bool useReflection = element.Mapping.TypeDesc.UseReflection; + bool useReflection = element.Mapping!.TypeDesc!.UseReflection; if (choice != null) { - bool enumUseReflection = choice.Mapping.TypeDesc.UseReflection; + bool enumUseReflection = choice.Mapping!.TypeDesc!.UseReflection; enumFullName = (enumUseReflection ? "" : enumTypeName + ".@") + FindChoiceEnumValue(element, (EnumMapping)choice.Mapping, enumUseReflection); Writer.Write("if ("); - Writer.Write(enumUseReflection ? RaCodeGen.GetStringForEnumLongValue(enumSource, enumUseReflection) : enumSource); + Writer.Write(enumUseReflection ? RaCodeGen.GetStringForEnumLongValue(enumSource!, enumUseReflection) : enumSource); Writer.Write(" == "); Writer.Write(enumFullName); if (isNullable && !element.IsNullable) @@ -3744,7 +3757,7 @@ private void WriteElements(string source, string enumSource, ElementAccessor[] e } if (text != null) { - bool useReflection = text.Mapping.TypeDesc.UseReflection; + bool useReflection = text.Mapping!.TypeDesc!.UseReflection; string fullTypeName = text.Mapping.TypeDesc.CSharpName; if (elements.Length > 0) { @@ -3806,14 +3819,14 @@ private void WriteText(string source, TextAccessor text) } else { - WritePrimitiveValue(mapping.TypeDesc, source, false); + WritePrimitiveValue(mapping.TypeDesc!, source, false); } Writer.WriteLine(");"); } else if (text.Mapping is SpecialMapping) { SpecialMapping mapping = (SpecialMapping)text.Mapping; - switch (mapping.TypeDesc.Kind) + switch (mapping.TypeDesc!.Kind) { case TypeKind.Node: Writer.Write(source); @@ -3827,15 +3840,15 @@ private void WriteText(string source, TextAccessor text) private void WriteElement(string source, ElementAccessor element, string arrayName, bool writeAccessor) { - string name = writeAccessor ? element.Name : element.Mapping.TypeName; - string ns = element.Any && element.Name.Length == 0 ? null : (element.Form == XmlSchemaForm.Qualified ? (writeAccessor ? element.Namespace : element.Mapping.Namespace) : ""); + string name = writeAccessor ? element.Name : element.Mapping!.TypeName!; + string? ns = element.Any && element.Name.Length == 0 ? null : (element.Form == XmlSchemaForm.Qualified ? (writeAccessor ? element.Namespace : element.Mapping!.Namespace) : ""); if (element.Mapping is NullableMapping) { Writer.Write("if ("); Writer.Write(source); Writer.WriteLine(" != null) {"); Writer.Indent++; - string fullTypeName = element.Mapping.TypeDesc.BaseTypeDesc.CSharpName; + string fullTypeName = element.Mapping.TypeDesc!.BaseTypeDesc!.CSharpName; string castedSource = source; if (!element.Mapping.TypeDesc.BaseTypeDesc.UseReflection) castedSource = "((" + fullTypeName + ")" + source + ")"; @@ -3867,7 +3880,7 @@ private void WriteElement(string source, ElementAccessor element, string arrayNa if (!writeAccessor) { Writer.Write(", "); - Writer.Write(RaCodeGen.GetStringForTypeof(mapping.TypeDesc.CSharpName, mapping.TypeDesc.UseReflection)); + Writer.Write(RaCodeGen.GetStringForTypeof(mapping.TypeDesc!.CSharpName, mapping.TypeDesc.UseReflection)); Writer.Write(", true, "); } else @@ -3879,7 +3892,7 @@ private void WriteElement(string source, ElementAccessor element, string arrayNa } else if (element.IsUnbounded) { - TypeDesc td = mapping.TypeDesc.CreateArrayTypeDesc(); + TypeDesc td = mapping.TypeDesc!.CreateArrayTypeDesc(); string fullTypeName = td.CSharpName; string elementArrayName = "el" + arrayName; string arrayIndex = "c" + elementArrayName; @@ -3940,7 +3953,7 @@ private void WriteElement(string source, ElementAccessor element, string arrayNa } else { - string fullTypeName = mapping.TypeDesc.CSharpName; + string fullTypeName = mapping.TypeDesc!.CSharpName; Writer.WriteLine("{"); Writer.Indent++; WriteArrayLocalDecl(fullTypeName, arrayName, source, mapping.TypeDesc); @@ -3960,7 +3973,7 @@ private void WriteElement(string source, ElementAccessor element, string arrayNa Writer.Indent++; } WriteStartElement(name, ns, false); - WriteArrayItems(mapping.ElementsSortedByDerivation, null, null, mapping.TypeDesc, arrayName, null); + WriteArrayItems(mapping.ElementsSortedByDerivation!, null, null, mapping.TypeDesc, arrayName, null); WriteEndElement(); Writer.Indent--; Writer.WriteLine("}"); @@ -3972,7 +3985,7 @@ private void WriteElement(string source, ElementAccessor element, string arrayNa { if (element.Mapping.IsSoap) { - string methodName = (string)MethodNames[element.Mapping]; + string methodName = (string)MethodNames[element.Mapping]!; Writer.Write("Writer.WriteStartElement("); WriteQuotedCSharpString(name); Writer.Write(", "); @@ -3997,7 +4010,7 @@ private void WriteElement(string source, ElementAccessor element, string arrayNa else { string suffixNullable = mapping.IsSoap ? "Encoded" : "Literal"; - string suffixRaw = mapping.TypeDesc.XmlEncodingNotRequired ? "Raw" : ""; + string suffixRaw = mapping.TypeDesc!.XmlEncodingNotRequired ? "Raw" : ""; WritePrimitive(element.IsNullable ? ("WriteNullableString" + suffixNullable + suffixRaw) : ("WriteElementString" + suffixRaw), name, ns, element.Default, source, mapping, mapping.IsSoap, true, element.IsNullable); } @@ -4017,7 +4030,7 @@ private void WriteElement(string source, ElementAccessor element, string arrayNa if (!writeAccessor) { Writer.Write(", "); - Writer.Write(RaCodeGen.GetStringForTypeof(mapping.TypeDesc.CSharpName, mapping.TypeDesc.UseReflection)); + Writer.Write(RaCodeGen.GetStringForTypeof(mapping.TypeDesc!.CSharpName, mapping.TypeDesc.UseReflection)); Writer.Write(", true, "); } else @@ -4028,11 +4041,11 @@ private void WriteElement(string source, ElementAccessor element, string arrayNa } else { - string methodName = ReferenceMapping(mapping); + string? methodName = ReferenceMapping(mapping); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe - if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc.Name) + Environment.StackTrace); + if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc!.Name) + Environment.StackTrace); #endif Writer.Write(methodName); Writer.Write("("); @@ -4046,7 +4059,7 @@ private void WriteElement(string source, ElementAccessor element, string arrayNa } Writer.Write(", "); Writer.Write(source); - if (mapping.TypeDesc.IsNullable) + if (mapping.TypeDesc!.IsNullable) { Writer.Write(", "); WriteValue(element.IsNullable); @@ -4058,7 +4071,7 @@ private void WriteElement(string source, ElementAccessor element, string arrayNa else if (element.Mapping is SpecialMapping) { SpecialMapping mapping = (SpecialMapping)element.Mapping; - bool useReflection = mapping.TypeDesc.UseReflection; + bool useReflection = mapping.TypeDesc!.UseReflection; TypeDesc td = mapping.TypeDesc; string fullTypeName = td.CSharpName; @@ -4101,7 +4114,7 @@ private void WriteElement(string source, ElementAccessor element, string arrayNa } } - private void WriteElementCall(string func, Type cast, string source, string name, string ns, bool isNullable, bool isAny) + private void WriteElementCall(string func, Type cast, string source, string name, string? ns, bool isNullable, bool isAny) { Writer.Write(func); Writer.Write("(("); @@ -4140,7 +4153,7 @@ private void WriteCheckDefault(TypeMapping mapping, string source, object value, Writer.Write("!"); Writer.Write(source); Writer.Write(".Equals("); - Type type = Type.GetType(mapping.TypeDesc.Type.FullName); + Type? type = Type.GetType(mapping.TypeDesc!.Type!.FullName!); WriteValue(type != null ? Convert.ChangeType(value, type) : value); Writer.Write(")"); } @@ -4148,7 +4161,7 @@ private void WriteCheckDefault(TypeMapping mapping, string source, object value, { Writer.Write(source); Writer.Write(" != "); - Type type = Type.GetType(mapping.TypeDesc.Type.FullName); + Type? type = Type.GetType(mapping.TypeDesc!.Type!.FullName!); WriteValue(type != null ? Convert.ChangeType(value, type) : value); } Writer.Write(")"); @@ -4335,7 +4348,7 @@ private void WriteLocalDecl(string typeName, string variableName, string initVal RaCodeGen.WriteLocalDecl(typeName, variableName, initValue, useReflection); } - private void WriteArrayLocalDecl(string typeName, string variableName, string initValue, TypeDesc arrayTypeDesc) + private void WriteArrayLocalDecl(string typeName, string variableName, string? initValue, TypeDesc arrayTypeDesc) { RaCodeGen.WriteArrayLocalDecl(typeName, variableName, initValue, arrayTypeDesc); } @@ -4359,9 +4372,9 @@ private void WriteEnumCase(string fullTypeName, ConstantMapping c, bool useRefle private string FindChoiceEnumValue(ElementAccessor element, EnumMapping choiceMapping, bool useReflection) { - string enumValue = null; + string? enumValue = null; - for (int i = 0; i < choiceMapping.Constants.Length; i++) + for (int i = 0; i < choiceMapping.Constants!.Length; i++) { string xmlName = choiceMapping.Constants[i].XmlName; @@ -4378,7 +4391,7 @@ private string FindChoiceEnumValue(ElementAccessor element, EnumMapping choiceMa continue; } int colon = xmlName.LastIndexOf(':'); - string choiceNs = colon < 0 ? choiceMapping.Namespace : xmlName.Substring(0, colon); + string? choiceNs = colon < 0 ? choiceMapping.Namespace : xmlName.Substring(0, colon); string choiceName = colon < 0 ? xmlName : xmlName.Substring(colon + 1); if (element.Name == choiceName) @@ -4398,10 +4411,10 @@ private string FindChoiceEnumValue(ElementAccessor element, EnumMapping choiceMa if (element.Any && element.Name.Length == 0) { // Type {0} is missing enumeration value '##any' for XmlAnyElementAttribute. - throw new InvalidOperationException(SR.Format(SR.XmlChoiceMissingAnyValue, choiceMapping.TypeDesc.FullName)); + throw new InvalidOperationException(SR.Format(SR.XmlChoiceMissingAnyValue, choiceMapping.TypeDesc!.FullName)); } // Type {0} is missing value for '{1}'. - throw new InvalidOperationException(SR.Format(SR.XmlChoiceMissingValue, choiceMapping.TypeDesc.FullName, element.Namespace + ":" + element.Name, element.Name, element.Namespace)); + throw new InvalidOperationException(SR.Format(SR.XmlChoiceMissingValue, choiceMapping.TypeDesc!.FullName, element.Namespace + ":" + element.Name, element.Name, element.Namespace)); } if (!useReflection) CodeIdentifier.CheckValidIdentifier(enumValue); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriterILGen.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriterILGen.cs index 99972df52fed01..ea5c9a376981ec 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriterILGen.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriterILGen.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; using System.Collections; using System.Collections.Generic; @@ -11,6 +12,7 @@ using System.Text; using System.Xml.Schema; using System.Xml.Extensions; +using System.Diagnostics.CodeAnalysis; namespace System.Xml.Serialization { @@ -36,7 +38,7 @@ internal void GenerateBegin() { if (mapping is StructMapping || mapping is EnumMapping) { - MethodNames.Add(mapping, NextMethodName(mapping.TypeDesc.Name)); + MethodNames.Add(mapping, NextMethodName(mapping.TypeDesc!.Name)); } } RaCodeGen.WriteReflectionInit(scope); @@ -63,10 +65,10 @@ internal Type GenerateEnd() GenerateInitCallbacksMethod(); this.typeBuilder.DefineDefaultConstructor( CodeGenerator.PublicMethodAttributes); - return this.typeBuilder.CreateTypeInfo().AsType(); + return this.typeBuilder.CreateTypeInfo()!.AsType(); } - internal string GenerateElement(XmlMapping xmlMapping) + internal string? GenerateElement(XmlMapping xmlMapping) { if (!xmlMapping.IsWriteable) return null; @@ -88,7 +90,7 @@ private void GenerateInitCallbacksMethod() ilg.EndMethod(); } - private void WriteQualifiedNameElement(string name, string ns, object defaultValue, SourceInfo source, bool nullable, TypeMapping mapping) + private void WriteQualifiedNameElement(string name, string? ns, object? defaultValue, SourceInfo source, bool nullable, TypeMapping mapping) { bool hasDefault = defaultValue != null && defaultValue != DBNull.Value; if (hasDefault) @@ -104,14 +106,14 @@ private void WriteQualifiedNameElement(string name, string ns, object defaultVal ilg.Ldstr(GetCSharpString(ns)); argTypes.Add(typeof(string)); } - source.Load(mapping.TypeDesc.Type); - argTypes.Add(mapping.TypeDesc.Type); + source.Load(mapping.TypeDesc!.Type!); + argTypes.Add(mapping.TypeDesc.Type!); MethodInfo XmlSerializationWriter_WriteXXX = typeof(XmlSerializationWriter).GetMethod( nullable ? ("WriteNullableQualifiedNameLiteral") : "WriteElementQualifiedName", CodeGenerator.InstanceBindingFlags, argTypes.ToArray() - ); + )!; ilg.Call(XmlSerializationWriter_WriteXXX); if (hasDefault) @@ -122,11 +124,11 @@ private void WriteQualifiedNameElement(string name, string ns, object defaultVal private void WriteEnumValue(EnumMapping mapping, SourceInfo source, out Type returnType) { - string methodName = ReferenceMapping(mapping); + string? methodName = ReferenceMapping(mapping); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe - if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc.Name)); + if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc!.Name)); #endif // For enum, its write method (eg. Write1_Gender) could be called multiple times @@ -135,9 +137,9 @@ private void WriteEnumValue(EnumMapping mapping, SourceInfo source, out Type ret methodName, CodeGenerator.PrivateMethodAttributes, typeof(string), - new Type[] { mapping.TypeDesc.Type }); + new Type[] { mapping.TypeDesc!.Type! }); ilg.Ldarg(0); - source.Load(mapping.TypeDesc.Type); + source.Load(mapping.TypeDesc.Type!); ilg.Call(methodBuilder); returnType = typeof(string); } @@ -146,14 +148,14 @@ private void WritePrimitiveValue(TypeDesc typeDesc, SourceInfo source, out Type { if (typeDesc == StringTypeDesc || typeDesc.FormatterName == "String") { - source.Load(typeDesc.Type); - returnType = typeDesc.Type; + source.Load(typeDesc.Type!); + returnType = typeDesc.Type!; } else { if (!typeDesc.HasCustomFormatter) { - Type argType = typeDesc.Type; + Type argType = typeDesc.Type!; // No ToString(Byte), compiler used ToString(Int16) instead. if (argType == typeof(byte)) argType = typeof(short); @@ -164,8 +166,8 @@ private void WritePrimitiveValue(TypeDesc typeDesc, SourceInfo source, out Type "ToString", CodeGenerator.StaticBindingFlags, new Type[] { argType } - ); - source.Load(typeDesc.Type); + )!; + source.Load(typeDesc.Type!); ilg.Call(XmlConvert_ToString); returnType = XmlConvert_ToString.ReturnType; } @@ -181,30 +183,30 @@ private void WritePrimitiveValue(TypeDesc typeDesc, SourceInfo source, out Type MethodInfo FromXXX = typeof(XmlSerializationWriter).GetMethod( "From" + typeDesc.FormatterName, bindingFlags, - new Type[] { typeDesc.Type } - ); - source.Load(typeDesc.Type); + new Type[] { typeDesc.Type! } + )!; + source.Load(typeDesc.Type!); ilg.Call(FromXXX); returnType = FromXXX.ReturnType; } } } - private void WritePrimitive(string method, string name, string ns, object defaultValue, SourceInfo source, TypeMapping mapping, bool writeXsiType, bool isElement, bool isNullable) + private void WritePrimitive(string method, string name, string? ns, object? defaultValue, SourceInfo source, TypeMapping mapping, bool writeXsiType, bool isElement, bool isNullable) { - TypeDesc typeDesc = mapping.TypeDesc; - bool hasDefault = defaultValue != null && defaultValue != DBNull.Value && mapping.TypeDesc.HasDefaultSupport; + TypeDesc typeDesc = mapping.TypeDesc!; + bool hasDefault = defaultValue != null && defaultValue != DBNull.Value && mapping.TypeDesc!.HasDefaultSupport; if (hasDefault) { if (mapping is EnumMapping) { #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe - if (defaultValue.GetType() != typeof(string)) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, name + " has invalid default type " + defaultValue.GetType().Name)); + if (defaultValue!.GetType() != typeof(string)) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, name + " has invalid default type " + defaultValue.GetType().Name)); #endif - source.Load(mapping.TypeDesc.Type); - string enumDefaultValue = null; + source.Load(mapping.TypeDesc!.Type!); + string? enumDefaultValue = null; if (((EnumMapping)mapping).IsFlags) { string[] values = ((string)defaultValue).Split(null); @@ -221,12 +223,12 @@ private void WritePrimitive(string method, string name, string ns, object defaul { enumDefaultValue = (string)defaultValue; } - ilg.Ldc(Enum.Parse(mapping.TypeDesc.Type, enumDefaultValue, false)); + ilg.Ldc(Enum.Parse(mapping.TypeDesc.Type!, enumDefaultValue!, false)); ilg.If(Cmp.NotEqualTo); // " != " } else { - WriteCheckDefault(source, defaultValue, isNullable); + WriteCheckDefault(source, defaultValue!, isNullable); } } List argTypes = new List(); @@ -257,7 +259,7 @@ private void WritePrimitive(string method, string name, string ns, object defaul ConstructorInfo XmlQualifiedName_ctor = typeof(XmlQualifiedName).GetConstructor( CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string) } - ); + )!; ilg.Ldstr(GetCSharpString(mapping.TypeName)); ilg.Ldstr(GetCSharpString(mapping.Namespace)); ilg.New(XmlQualifiedName_ctor); @@ -267,7 +269,7 @@ private void WritePrimitive(string method, string name, string ns, object defaul method, CodeGenerator.InstanceBindingFlags, argTypes.ToArray() - ); + )!; ilg.Call(XmlSerializationWriter_method); if (hasDefault) @@ -276,26 +278,26 @@ private void WritePrimitive(string method, string name, string ns, object defaul } } - private void WriteTag(string methodName, string name, string ns) + private void WriteTag(string methodName, string name, string? ns) { MethodInfo XmlSerializationWriter_Method = typeof(XmlSerializationWriter).GetMethod( methodName, CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Ldstr(GetCSharpString(name)); ilg.Ldstr(GetCSharpString(ns)); ilg.Call(XmlSerializationWriter_Method); } - private void WriteTag(string methodName, string name, string ns, bool writePrefixed) + private void WriteTag(string methodName, string name, string? ns, bool writePrefixed) { MethodInfo XmlSerializationWriter_Method = typeof(XmlSerializationWriter).GetMethod( methodName, CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string), typeof(object), typeof(bool) } - ); + )!; ilg.Ldarg(0); ilg.Ldstr(GetCSharpString(name)); ilg.Ldstr(GetCSharpString(ns)); @@ -304,7 +306,7 @@ private void WriteTag(string methodName, string name, string ns, bool writePrefi ilg.Call(XmlSerializationWriter_Method); } - private void WriteStartElement(string name, string ns, bool writePrefixed) + private void WriteStartElement(string name, string? ns, bool writePrefixed) { WriteTag("WriteStartElement", name, ns, writePrefixed); } @@ -315,7 +317,7 @@ private void WriteEndElement() "WriteEndElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationWriter_WriteEndElement); } @@ -325,7 +327,7 @@ private void WriteEndElement(string source) "WriteEndElement", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(object) } - ); + )!; object oVar = ilg.GetVariable(source); ilg.Ldarg(0); ilg.Load(oVar); @@ -333,12 +335,12 @@ private void WriteEndElement(string source) ilg.Call(XmlSerializationWriter_WriteEndElement); } - private void WriteLiteralNullTag(string name, string ns) + private void WriteLiteralNullTag(string name, string? ns) { WriteTag("WriteNullTagLiteral", name, ns); } - private void WriteEmptyTag(string name, string ns) + private void WriteEmptyTag(string name, string? ns) { WriteTag("WriteEmptyTag", name, ns); } @@ -346,7 +348,7 @@ private void WriteEmptyTag(string name, string ns) private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) { ElementAccessor element = xmlMembersMapping.Accessor; - MembersMapping mapping = (MembersMapping)element.Mapping; + MembersMapping mapping = (MembersMapping)element.Mapping!; bool hasWrapperElement = mapping.HasWrapperElement; bool writeAccessors = mapping.WriteAccessors; string methodName = NextMethodName(element.Name); @@ -363,7 +365,7 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) "WriteStartDocument", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationWriter_WriteStartDocument); @@ -371,7 +373,7 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) "TopLevelElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationWriter_TopLevelElement); @@ -387,10 +389,10 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) { WriteStartElement(element.Name, (element.Form == XmlSchemaForm.Qualified ? element.Namespace : ""), false); - int xmlnsMember = FindXmlnsIndex(mapping.Members); + int xmlnsMember = FindXmlnsIndex(mapping.Members!); if (xmlnsMember >= 0) { - MemberMapping member = mapping.Members[xmlnsMember]; + MemberMapping member = mapping.Members![xmlnsMember]; string source = "((" + typeof(XmlSerializerNamespaces).FullName + ")p[" + xmlnsMember.ToString(CultureInfo.InvariantCulture) + "])"; ilg.Ldloc(pLengthLoc); @@ -400,15 +402,15 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) ilg.EndIf(); } - for (int i = 0; i < mapping.Members.Length; i++) + for (int i = 0; i < mapping.Members!.Length; i++) { MemberMapping member = mapping.Members[i]; if (member.Attribute != null && !member.Ignore) { - SourceInfo source = new SourceInfo("p[" + i.ToString(CultureInfo.InvariantCulture) + "]", null, null, pLengthLoc.LocalType.GetElementType(), ilg); + SourceInfo source = new SourceInfo("p[" + i.ToString(CultureInfo.InvariantCulture) + "]", null, null, pLengthLoc.LocalType.GetElementType()!, ilg); - SourceInfo specifiedSource = null; + SourceInfo? specifiedSource = null; int specifiedPosition = 0; if (member.CheckSpecified != SpecifiedAccessor.None) { @@ -443,7 +445,7 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) ilg.If(); } - WriteMember(source, member.Attribute, member.TypeDesc, "p"); + WriteMember(source, member.Attribute, member.TypeDesc!, "p"); if (specifiedSource != null) { @@ -455,7 +457,7 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) } } - for (int i = 0; i < mapping.Members.Length; i++) + for (int i = 0; i < mapping.Members!.Length; i++) { MemberMapping member = mapping.Members[i]; if (member.Xmlns != null) @@ -463,7 +465,7 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) if (member.Ignore) continue; - SourceInfo specifiedSource = null; + SourceInfo? specifiedSource = null; int specifiedPosition = 0; if (member.CheckSpecified != SpecifiedAccessor.None) { @@ -500,14 +502,14 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) } string source = "p[" + i.ToString(CultureInfo.InvariantCulture) + "]"; - string enumSource = null; + string? enumSource = null; if (member.ChoiceIdentifier != null) { for (int j = 0; j < mapping.Members.Length; j++) { if (mapping.Members[j].Name == member.ChoiceIdentifier.MemberName) { - enumSource = "((" + mapping.Members[j].TypeDesc.CSharpName + ")p[" + j.ToString(CultureInfo.InvariantCulture) + "]" + ")"; + enumSource = "((" + mapping.Members[j].TypeDesc!.CSharpName + ")p[" + j.ToString(CultureInfo.InvariantCulture) + "]" + ")"; break; } } @@ -519,7 +521,7 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) } // override writeAccessors choice when we've written a wrapper element - WriteMember(new SourceInfo(source, source, null, null, ilg), enumSource, member.ElementsSortedByDerivation, member.Text, member.ChoiceIdentifier, member.TypeDesc, writeAccessors || hasWrapperElement); + WriteMember(new SourceInfo(source, source, null, null, ilg), enumSource, member.ElementsSortedByDerivation!, member.Text, member.ChoiceIdentifier, member.TypeDesc!, writeAccessors || hasWrapperElement); if (specifiedSource != null) { @@ -540,7 +542,7 @@ private string GenerateMembersElement(XmlMembersMapping xmlMembersMapping) private string GenerateTypeElement(XmlTypeMapping xmlTypeMapping) { ElementAccessor element = xmlTypeMapping.Accessor; - TypeMapping mapping = element.Mapping; + TypeMapping mapping = element.Mapping!; string methodName = NextMethodName(element.Name); ilg = new CodeGenerator(this.typeBuilder); ilg.BeginMethod( @@ -555,7 +557,7 @@ private string GenerateTypeElement(XmlTypeMapping xmlTypeMapping) "WriteStartDocument", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationWriter_WriteStartDocument); @@ -569,13 +571,13 @@ private string GenerateTypeElement(XmlTypeMapping xmlTypeMapping) ilg.GotoMethodEnd(); ilg.EndIf(); - if (!mapping.TypeDesc.IsValueType && !mapping.TypeDesc.Type.IsPrimitive) + if (!mapping.TypeDesc!.IsValueType && !mapping.TypeDesc.Type!.IsPrimitive) { MethodInfo XmlSerializationWriter_TopLevelElement = typeof(XmlSerializationWriter).GetMethod( "TopLevelElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationWriter_TopLevelElement); } @@ -593,23 +595,23 @@ private string NextMethodName(string name) private void WriteEnumMethod(EnumMapping mapping) { - string methodName; + string? methodName; MethodNames.TryGetValue(mapping, out methodName); List argTypes = new List(); List argNames = new List(); - argTypes.Add(mapping.TypeDesc.Type); + argTypes.Add(mapping.TypeDesc!.Type!); argNames.Add("v"); ilg = new CodeGenerator(this.typeBuilder); ilg.BeginMethod( typeof(string), - GetMethodBuilder(methodName), + GetMethodBuilder(methodName!), argTypes.ToArray(), argNames.ToArray(), CodeGenerator.PrivateMethodAttributes); LocalBuilder sLoc = ilg.DeclareLocal(typeof(string), "s"); ilg.Load(null); ilg.Stloc(sLoc); - ConstantMapping[] constants = mapping.Constants; + ConstantMapping[] constants = mapping.Constants!; if (constants.Length > 0) { @@ -619,7 +621,7 @@ private void WriteEnumMethod(EnumMapping mapping) Label defaultLabel = ilg.DefineLabel(); Label endSwitchLabel = ilg.DefineLabel(); // This local is necessary; otherwise, it becomes if/else - LocalBuilder localTmp = ilg.DeclareLocal(mapping.TypeDesc.Type, "localTmp"); + LocalBuilder localTmp = ilg.DeclareLocal(mapping.TypeDesc.Type!, "localTmp"); ilg.Ldarg("v"); ilg.Stloc(localTmp); for (int i = 0; i < constants.Length; i++) @@ -629,7 +631,7 @@ private void WriteEnumMethod(EnumMapping mapping) { Label caseLabel = ilg.DefineLabel(); ilg.Ldloc(localTmp); - ilg.Ldc(Enum.ToObject(mapping.TypeDesc.Type, c.Value)); + ilg.Ldc(Enum.ToObject(mapping.TypeDesc.Type!, c.Value)); ilg.Beq(caseLabel); caseLabels.Add(caseLabel); retValues.Add(GetCSharpString(c.XmlName)); @@ -679,7 +681,7 @@ private void WriteEnumMethod(EnumMapping mapping) "FromEnum", CodeGenerator.StaticBindingFlags, new Type[] { typeof(long), typeof(string[]), typeof(long[]), typeof(string) } - ); + )!; ilg.Call(XmlSerializationWriter_FromEnum); ilg.Stloc(sLoc); ilg.Br(endSwitchLabel); @@ -699,22 +701,22 @@ private void WriteEnumMethod(EnumMapping mapping) "get_InvariantCulture", CodeGenerator.StaticBindingFlags, Array.Empty() - ); + )!; MethodInfo Int64_ToString = typeof(long).GetMethod( "ToString", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(IFormatProvider) } - ); + )!; MethodInfo XmlSerializationWriter_CreateInvalidEnumValueException = typeof(XmlSerializationWriter).GetMethod( "CreateInvalidEnumValueException", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(object), typeof(string) } - ); + )!; // Default body ilg.MarkLabel(defaultLabel); ilg.Ldarg(0); ilg.Ldarg("v"); - ilg.ConvertValue(mapping.TypeDesc.Type, typeof(long)); + ilg.ConvertValue(mapping.TypeDesc.Type!, typeof(long)); LocalBuilder numLoc = ilg.DeclareLocal(typeof(long), "num"); ilg.Stloc(numLoc); // Invoke method on Value type need address @@ -733,17 +735,17 @@ private void WriteEnumMethod(EnumMapping mapping) private void WriteDerivedTypes(StructMapping mapping) { - for (StructMapping derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) + for (StructMapping? derived = mapping.DerivedMappings; derived != null; derived = derived.NextDerivedMapping) { ilg.InitElseIf(); - WriteTypeCompare("t", derived.TypeDesc.Type); + WriteTypeCompare("t", derived.TypeDesc!.Type!); ilg.AndIf(); - string methodName = ReferenceMapping(derived); + string? methodName = ReferenceMapping(derived); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe - if (methodName == null) throw new InvalidOperationException("derived from " + mapping.TypeDesc.FullName + ", " + SR.Format(SR.XmlInternalErrorMethod, derived.TypeDesc.Name)); + if (methodName == null) throw new InvalidOperationException("derived from " + mapping.TypeDesc!.FullName + ", " + SR.Format(SR.XmlInternalErrorMethod, derived.TypeDesc.Name)); #endif List argTypes = new List(); @@ -755,8 +757,8 @@ private void WriteDerivedTypes(StructMapping mapping) object oVar = ilg.GetVariable("o"); Type oType = ilg.GetVariableType(oVar); ilg.Load(oVar); - ilg.ConvertValue(oType, derived.TypeDesc.Type); - argTypes.Add(derived.TypeDesc.Type); + ilg.ConvertValue(oType, derived.TypeDesc.Type!); + argTypes.Add(derived.TypeDesc.Type!); if (derived.TypeDesc.IsNullable) { argTypes.Add(typeof(bool)); @@ -786,11 +788,11 @@ private void WriteEnumAndArrayTypes() { EnumMapping mapping = (EnumMapping)m; ilg.InitElseIf(); - WriteTypeCompare("t", mapping.TypeDesc.Type); + WriteTypeCompare("t", mapping.TypeDesc!.Type!); // WriteXXXTypeCompare leave bool on the stack ilg.AndIf(); - string methodName = ReferenceMapping(mapping); + string? methodName = ReferenceMapping(mapping); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe @@ -800,12 +802,12 @@ private void WriteEnumAndArrayTypes() "get_Writer", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlWriter_WriteStartElement = typeof(XmlWriter).GetMethod( "WriteStartElement", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationWriter_get_Writer); ilg.Ldarg("n"); @@ -815,7 +817,7 @@ private void WriteEnumAndArrayTypes() "WriteXsiType", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Ldstr(GetCSharpString(mapping.TypeName)); ilg.Ldstr(GetCSharpString(mapping.Namespace)); @@ -824,26 +826,26 @@ private void WriteEnumAndArrayTypes() methodName, CodeGenerator.PrivateMethodAttributes, typeof(string), - new Type[] { mapping.TypeDesc.Type } + new Type[] { mapping.TypeDesc.Type! } ); MethodInfo XmlWriter_WriteString = typeof(XmlWriter).GetMethod( "WriteString", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationWriter_get_Writer); object oVar = ilg.GetVariable("o"); ilg.Ldarg(0); ilg.Load(oVar); - ilg.ConvertValue(ilg.GetVariableType(oVar), mapping.TypeDesc.Type); + ilg.ConvertValue(ilg.GetVariableType(oVar), mapping.TypeDesc.Type!); ilg.Call(methodBuilder); ilg.Call(XmlWriter_WriteString); MethodInfo XmlWriter_WriteEndElement = typeof(XmlWriter).GetMethod( "WriteEndElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationWriter_get_Writer); ilg.Call(XmlWriter_WriteEndElement); @@ -851,13 +853,13 @@ private void WriteEnumAndArrayTypes() } else if (m is ArrayMapping) { - ArrayMapping mapping = m as ArrayMapping; + ArrayMapping? mapping = m as ArrayMapping; if (mapping == null) continue; ilg.InitElseIf(); - if (mapping.TypeDesc.IsArray) - WriteArrayTypeCompare("t", mapping.TypeDesc.Type); + if (mapping.TypeDesc!.IsArray) + WriteArrayTypeCompare("t", mapping.TypeDesc.Type!); else - WriteTypeCompare("t", mapping.TypeDesc.Type); + WriteTypeCompare("t", mapping.TypeDesc.Type!); // WriteXXXTypeCompare leave bool on the stack ilg.AndIf(); ilg.EnterScope(); @@ -866,12 +868,12 @@ private void WriteEnumAndArrayTypes() "get_Writer", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlWriter_WriteStartElement = typeof(XmlWriter).GetMethod( "WriteStartElement", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationWriter_get_Writer); ilg.Ldarg("n"); @@ -881,19 +883,19 @@ private void WriteEnumAndArrayTypes() "WriteXsiType", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Ldstr(GetCSharpString(mapping.TypeName)); ilg.Ldstr(GetCSharpString(mapping.Namespace)); ilg.Call(XmlSerializationWriter_WriteXsiType); - WriteMember(new SourceInfo("o", "o", null, null, ilg), null, mapping.ElementsSortedByDerivation, null, null, mapping.TypeDesc, true); + WriteMember(new SourceInfo("o", "o", null, null, ilg), null, mapping.ElementsSortedByDerivation!, null, null, mapping.TypeDesc, true); MethodInfo XmlWriter_WriteEndElement = typeof(XmlWriter).GetMethod( "WriteEndElement", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationWriter_get_Writer); ilg.Call(XmlWriter_WriteEndElement); @@ -906,7 +908,7 @@ private void WriteEnumAndArrayTypes() private void WriteStructMethod(StructMapping mapping) { - string methodName; + string? methodName; MethodNames.TryGetValue(mapping, out methodName); ilg = new CodeGenerator(this.typeBuilder); @@ -916,7 +918,7 @@ private void WriteStructMethod(StructMapping mapping) argNames.Add("n"); argTypes.Add(typeof(string)); argNames.Add("ns"); - argTypes.Add(mapping.TypeDesc.Type); + argTypes.Add(mapping.TypeDesc!.Type!); argNames.Add("o"); if (mapping.TypeDesc.IsNullable) { @@ -926,7 +928,7 @@ private void WriteStructMethod(StructMapping mapping) argTypes.Add(typeof(bool)); argNames.Add("needType"); ilg.BeginMethod(typeof(void), - GetMethodBuilder(methodName), + GetMethodBuilder(methodName!), argTypes.ToArray(), argNames.ToArray(), CodeGenerator.PrivateMethodAttributes); @@ -940,7 +942,7 @@ private void WriteStructMethod(StructMapping mapping) "WriteNullTagLiteral", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Ldarg("n"); ilg.Ldarg("ns"); @@ -958,13 +960,13 @@ private void WriteStructMethod(StructMapping mapping) "GetType", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ArgBuilder oArg = ilg.GetArg("o"); ilg.LdargAddress(oArg); ilg.ConvertAddress(oArg.ArgType, typeof(object)); ilg.Call(Object_GetType); ilg.Stloc(tLoc); - WriteTypeCompare("t", mapping.TypeDesc.Type); + WriteTypeCompare("t", mapping.TypeDesc.Type!); // Bool on the stack from WriteTypeCompare. ilg.If(); // if (t == typeof(...)) WriteDerivedTypes(mapping); @@ -977,7 +979,7 @@ private void WriteStructMethod(StructMapping mapping) "WriteTypedPrimitive", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string), typeof(object), typeof(bool) } - ); + )!; ilg.Ldarg(0); ilg.Ldarg("n"); ilg.Ldarg("ns"); @@ -992,7 +994,7 @@ private void WriteStructMethod(StructMapping mapping) "CreateUnknownTypeException", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(object) } - ); + )!; ilg.Ldarg(0); ilg.Ldarg(oArg); ilg.ConvertValue(oArg.ArgType, typeof(object)); @@ -1010,13 +1012,13 @@ private void WriteStructMethod(StructMapping mapping) "set_EscapeName", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(bool) } - ); + )!; ilg.Ldarg(0); ilg.Ldc(false); ilg.Call(XmlSerializationWriter_set_EscapeName); } - string xmlnsSource = null; + string? xmlnsSource = null; MemberMapping[] members = TypeScope.GetAllMembers(mapping, memberInfos); int xmlnsMember = FindXmlnsIndex(members); if (xmlnsMember >= 0) @@ -1045,7 +1047,7 @@ private void WriteStructMethod(StructMapping mapping) "WriteStartElement", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string), typeof(object), typeof(bool), typeof(XmlSerializerNamespaces) } - ); + )!; ilg.Call(XmlSerializationWriter_WriteStartElement); if (!mapping.TypeDesc.IsRoot) { @@ -1055,7 +1057,7 @@ private void WriteStructMethod(StructMapping mapping) "WriteXsiType", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Ldstr(GetCSharpString(mapping.TypeName)); ilg.Ldstr(GetCSharpString(mapping.Namespace)); @@ -1072,7 +1074,7 @@ private void WriteStructMethod(StructMapping mapping) if (m.CheckShouldPersist) { ilg.LdargAddress(oArg); - ilg.Call(m.CheckShouldPersistMethodInfo); + ilg.Call(m.CheckShouldPersistMethodInfo!); ilg.If(); } if (m.CheckSpecified != SpecifiedAccessor.None) @@ -1081,7 +1083,7 @@ private void WriteStructMethod(StructMapping mapping) ILGenLoad(memberGet); ilg.If(); } - WriteMember(RaCodeGen.GetSourceForMember("o", m, mapping.TypeDesc, ilg), m.Attribute, m.TypeDesc, "o"); + WriteMember(RaCodeGen.GetSourceForMember("o", m, mapping.TypeDesc, ilg), m.Attribute, m.TypeDesc!, "o"); if (m.CheckSpecified != SpecifiedAccessor.None) { @@ -1100,12 +1102,12 @@ private void WriteStructMethod(StructMapping mapping) if (m.Xmlns != null) continue; CodeIdentifier.CheckValidIdentifier(m.Name); - bool checkShouldPersist = m.CheckShouldPersist && (m.Elements.Length > 0 || m.Text != null); + bool checkShouldPersist = m.CheckShouldPersist && (m.Elements!.Length > 0 || m.Text != null); if (checkShouldPersist) { ilg.LdargAddress(oArg); - ilg.Call(m.CheckShouldPersistMethodInfo); + ilg.Call(m.CheckShouldPersistMethodInfo!); ilg.If(); } if (m.CheckSpecified != SpecifiedAccessor.None) @@ -1115,14 +1117,14 @@ private void WriteStructMethod(StructMapping mapping) ilg.If(); } - string choiceSource = null; + string? choiceSource = null; if (m.ChoiceIdentifier != null) { CodeIdentifier.CheckValidIdentifier(m.ChoiceIdentifier.MemberName); choiceSource = RaCodeGen.GetStringForMember("o", m.ChoiceIdentifier.MemberName, mapping.TypeDesc); } - WriteMember(RaCodeGen.GetSourceForMember("o", m, m.MemberInfo, mapping.TypeDesc, ilg), choiceSource, m.ElementsSortedByDerivation, m.Text, m.ChoiceIdentifier, m.TypeDesc, true); + WriteMember(RaCodeGen.GetSourceForMember("o", m, m.MemberInfo, mapping.TypeDesc, ilg), choiceSource, m.ElementsSortedByDerivation!, m.Text, m.ChoiceIdentifier, m.TypeDesc!, true); if (m.CheckSpecified != SpecifiedAccessor.None) { @@ -1138,7 +1140,7 @@ private void WriteStructMethod(StructMapping mapping) ilg.EndMethod(); } - private bool CanOptimizeWriteListSequence(TypeDesc listElementTypeDesc) + private bool CanOptimizeWriteListSequence(TypeDesc? listElementTypeDesc) { // check to see if we can write values of the attribute sequentially // currently we have only one data type (XmlQualifiedName) that we can not write "inline", @@ -1159,7 +1161,7 @@ private void WriteMember(SourceInfo source, AttributeAccessor attribute, TypeDes WriteArrayLocalDecl(fullTypeName, aVar, source, memberTypeDesc); if (memberTypeDesc.IsNullable) { - ilg.Ldloc(memberTypeDesc.Type, aVar); + ilg.Ldloc(memberTypeDesc.Type!, aVar); ilg.Load(null); ilg.If(Cmp.NotEqualTo); } @@ -1167,17 +1169,17 @@ private void WriteMember(SourceInfo source, AttributeAccessor attribute, TypeDes { if (CanOptimizeWriteListSequence(memberTypeDesc.ArrayElementTypeDesc)) { - string ns = attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : string.Empty; + string? ns = attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : string.Empty; MethodInfo XmlSerializationWriter_get_Writer = typeof(XmlSerializationWriter).GetMethod( "get_Writer", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlWriter_WriteStartAttribute = typeof(XmlWriter).GetMethod( "WriteStartAttribute", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string), typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationWriter_get_Writer); ilg.Load(null); @@ -1191,12 +1193,12 @@ private void WriteMember(SourceInfo source, AttributeAccessor attribute, TypeDes ConstructorInfo StringBuilder_ctor = typeof(StringBuilder).GetConstructor( CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.New(StringBuilder_ctor); ilg.Stloc(sbLoc); } } - TypeDesc arrayElementTypeDesc = memberTypeDesc.ArrayElementTypeDesc; + TypeDesc arrayElementTypeDesc = memberTypeDesc.ArrayElementTypeDesc!; if (memberTypeDesc.IsEnumerable) { @@ -1206,7 +1208,7 @@ private void WriteMember(SourceInfo source, AttributeAccessor attribute, TypeDes { LocalBuilder localI = ilg.DeclareOrGetLocal(typeof(int), iVar); ilg.For(localI, 0, ilg.GetLocal(aVar)); - WriteLocalDecl(aiVar, RaCodeGen.GetStringForArrayMember(aVar, iVar, memberTypeDesc), arrayElementTypeDesc.Type); + WriteLocalDecl(aiVar, RaCodeGen.GetStringForArrayMember(aVar, iVar, memberTypeDesc), arrayElementTypeDesc.Type!); } if (attribute.IsList) { @@ -1223,12 +1225,12 @@ private void WriteMember(SourceInfo source, AttributeAccessor attribute, TypeDes "get_Writer", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlWriter_WriteString = typeof(XmlWriter).GetMethod( "WriteString", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationWriter_get_Writer); ilg.Ldstr(" "); @@ -1244,7 +1246,7 @@ private void WriteMember(SourceInfo source, AttributeAccessor attribute, TypeDes "Append", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string) } - ); + )!; ilg.Ldloc(iVar); ilg.Ldc(0); ilg.If(Cmp.NotEqualTo); @@ -1265,7 +1267,7 @@ private void WriteMember(SourceInfo source, AttributeAccessor attribute, TypeDes methodName, CodeGenerator.InstanceBindingFlags, new Type[] { argType } - ); + )!; ilg.Call(method); if (method.ReturnType != typeof(void)) ilg.Pop(); @@ -1287,12 +1289,12 @@ private void WriteMember(SourceInfo source, AttributeAccessor attribute, TypeDes "get_Writer", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlWriter_WriteEndAttribute = typeof(XmlWriter).GetMethod( "WriteEndAttribute", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldarg(0); ilg.Call(XmlSerializationWriter_get_Writer); ilg.Call(XmlWriter_WriteEndAttribute); @@ -1303,7 +1305,7 @@ private void WriteMember(SourceInfo source, AttributeAccessor attribute, TypeDes "get_Length", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldloc("sb"); ilg.Call(StringBuilder_get_Length); ilg.Ldc(0); @@ -1313,7 +1315,7 @@ private void WriteMember(SourceInfo source, AttributeAccessor attribute, TypeDes ilg.Ldarg(0); ilg.Ldstr(GetCSharpString(attribute.Name)); argTypes.Add(typeof(string)); - string ns = attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : string.Empty; + string? ns = attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : string.Empty; if (ns != null) { ilg.Ldstr(GetCSharpString(ns)); @@ -1323,7 +1325,7 @@ private void WriteMember(SourceInfo source, AttributeAccessor attribute, TypeDes "ToString", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldloc("sb"); ilg.Call(Object_ToString); argTypes.Add(typeof(string)); @@ -1331,7 +1333,7 @@ private void WriteMember(SourceInfo source, AttributeAccessor attribute, TypeDes "WriteAttribute", CodeGenerator.InstanceBindingFlags, argTypes.ToArray() - ); + )!; ilg.Call(XmlSerializationWriter_WriteAttribute); ilg.EndIf(); } @@ -1353,14 +1355,14 @@ private void WriteAttribute(SourceInfo source, AttributeAccessor attribute, stri if (attribute.Mapping is SpecialMapping) { SpecialMapping special = (SpecialMapping)attribute.Mapping; - if (special.TypeDesc.Kind == TypeKind.Attribute || special.TypeDesc.CanBeAttributeValue) + if (special.TypeDesc!.Kind == TypeKind.Attribute || special.TypeDesc.CanBeAttributeValue) { System.Diagnostics.Debug.Assert(parent == "o" || parent == "p"); MethodInfo XmlSerializationWriter_WriteXmlAttribute = typeof(XmlSerializationWriter).GetMethod( "WriteXmlAttribute", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(XmlNode), typeof(object) } - ); + )!; ilg.Ldarg(0); ilg.Ldloc(source.Source); ilg.Ldarg(parent); @@ -1372,20 +1374,20 @@ private void WriteAttribute(SourceInfo source, AttributeAccessor attribute, stri } else { - TypeDesc typeDesc = attribute.Mapping.TypeDesc; + TypeDesc typeDesc = attribute.Mapping!.TypeDesc!; source = source.CastTo(typeDesc); WritePrimitive("WriteAttribute", attribute.Name, attribute.Form == XmlSchemaForm.Qualified ? attribute.Namespace : "", GetConvertedDefaultValue(source.Type, attribute.Default), source, attribute.Mapping, false, false, false); } } - private static object GetConvertedDefaultValue(Type targetType, object rawDefaultValue) + private static object? GetConvertedDefaultValue(Type? targetType, object? rawDefaultValue) { if (targetType == null) { return rawDefaultValue; } - object convertedDefaultValue; + object? convertedDefaultValue; if (!targetType.TryConvertTo(rawDefaultValue, out convertedDefaultValue)) { return rawDefaultValue; @@ -1394,7 +1396,7 @@ private static object GetConvertedDefaultValue(Type targetType, object rawDefaul return convertedDefaultValue; } - private void WriteMember(SourceInfo source, string choiceSource, ElementAccessor[] elements, TextAccessor text, ChoiceIdentifierAccessor choice, TypeDesc memberTypeDesc, bool writeAccessors) + private void WriteMember(SourceInfo source, string? choiceSource, ElementAccessor[] elements, TextAccessor? text, ChoiceIdentifierAccessor? choice, TypeDesc memberTypeDesc, bool writeAccessors) { if (memberTypeDesc.IsArrayLike && !(elements.Length == 1 && elements[0].Mapping is ArrayMapping)) @@ -1405,7 +1407,7 @@ private void WriteMember(SourceInfo source, string choiceSource, ElementAccessor } - private void WriteArray(SourceInfo source, string choiceSource, ElementAccessor[] elements, TextAccessor text, ChoiceIdentifierAccessor choice, TypeDesc arrayTypeDesc) + private void WriteArray(SourceInfo source, string? choiceSource, ElementAccessor[] elements, TextAccessor? text, ChoiceIdentifierAccessor? choice, TypeDesc arrayTypeDesc) { if (elements.Length == 0 && text == null) return; string arrayTypeName = arrayTypeDesc.CSharpName; @@ -1419,11 +1421,11 @@ private void WriteArray(SourceInfo source, string choiceSource, ElementAccessor[ ilg.If(Cmp.NotEqualTo); } - string cName = null; + string? cName = null; if (choice != null) { - string choiceFullName = choice.Mapping.TypeDesc.CSharpName; - SourceInfo choiceSourceInfo = new SourceInfo(choiceSource, null, choice.MemberInfo, null, ilg); + string choiceFullName = choice.Mapping!.TypeDesc!.CSharpName; + SourceInfo choiceSourceInfo = new SourceInfo(choiceSource!, null, choice.MemberInfo, null, ilg); cName = "c" + choice.Mapping.TypeDesc.Name; WriteArrayLocalDecl(choiceFullName + "[]", cName, choiceSourceInfo, choice.Mapping.TypeDesc); // write check for the choice identifier array @@ -1447,7 +1449,7 @@ private void WriteArray(SourceInfo source, string choiceSource, ElementAccessor[ "CreateInvalidChoiceIdentifierValueException", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Ldstr(GetCSharpString(choice.Mapping.TypeDesc.FullName)); ilg.Ldstr(GetCSharpString(choice.MemberName)); @@ -1456,16 +1458,16 @@ private void WriteArray(SourceInfo source, string choiceSource, ElementAccessor[ ilg.EndIf(); } - WriteArrayItems(elements, text, choice, arrayTypeDesc, aName, cName); + WriteArrayItems(elements, text, choice, arrayTypeDesc, aName, cName!); if (arrayTypeDesc.IsNullable) { ilg.EndIf(); } } - private void WriteArrayItems(ElementAccessor[] elements, TextAccessor text, ChoiceIdentifierAccessor choice, TypeDesc arrayTypeDesc, string arrayName, string choiceName) + private void WriteArrayItems(ElementAccessor[] elements, TextAccessor? text, ChoiceIdentifierAccessor? choice, TypeDesc arrayTypeDesc, string arrayName, string? choiceName) { - TypeDesc arrayElementTypeDesc = arrayTypeDesc.ArrayElementTypeDesc; + TypeDesc arrayElementTypeDesc = arrayTypeDesc.ArrayElementTypeDesc!; if (arrayTypeDesc.IsEnumerable) { @@ -1480,26 +1482,26 @@ private void WriteArrayItems(ElementAccessor[] elements, TextAccessor text, Choi getEnumeratorMethod = typeIEnumerable.GetMethod( "GetEnumerator", CodeGenerator.InstanceBindingFlags, - Array.Empty()); + Array.Empty())!; - ilg.ConvertValue(arrayTypeDesc.Type, typeIEnumerable); + ilg.ConvertValue(arrayTypeDesc.Type!, typeIEnumerable); } else if (arrayTypeDesc.IsGenericInterface) { - Type typeIEnumerable = typeof(IEnumerable<>).MakeGenericType(arrayElementTypeDesc.Type); + Type typeIEnumerable = typeof(IEnumerable<>).MakeGenericType(arrayElementTypeDesc.Type!); getEnumeratorMethod = typeIEnumerable.GetMethod( "GetEnumerator", CodeGenerator.InstanceBindingFlags, - Array.Empty()); + Array.Empty())!; - ilg.ConvertValue(arrayTypeDesc.Type, typeIEnumerable); + ilg.ConvertValue(arrayTypeDesc.Type!, typeIEnumerable); } else { - getEnumeratorMethod = arrayTypeDesc.Type.GetMethod( + getEnumeratorMethod = arrayTypeDesc.Type!.GetMethod( "GetEnumerator", - Array.Empty()); + Array.Empty())!; } ilg.Call(getEnumeratorMethod); ilg.ConvertValue(getEnumeratorMethod.ReturnType, typeof(IEnumerator)); @@ -1511,14 +1513,14 @@ private void WriteArrayItems(ElementAccessor[] elements, TextAccessor text, Choi ilg.WhileBegin(); string arrayNamePlusA = (arrayName).Replace(arrayTypeDesc.Name, "") + "a" + arrayElementTypeDesc.Name; string arrayNamePlusI = (arrayName).Replace(arrayTypeDesc.Name, "") + "i" + arrayElementTypeDesc.Name; - WriteLocalDecl(arrayNamePlusI, "e.Current", arrayElementTypeDesc.Type); + WriteLocalDecl(arrayNamePlusI, "e.Current", arrayElementTypeDesc.Type!); WriteElements(new SourceInfo(arrayNamePlusI, null, null, arrayElementTypeDesc.Type, ilg), choiceName + "i", elements, text, choice, arrayNamePlusA, true, true); ilg.WhileBeginCondition(); // while (e.MoveNext()) MethodInfo IEnumerator_MoveNext = typeof(IEnumerator).GetMethod( "MoveNext", CodeGenerator.InstanceBindingFlags, - Array.Empty()); + Array.Empty())!; ilg.Ldloc(eLoc); ilg.Call(IEnumerator_MoveNext); ilg.WhileEndCondition(); @@ -1537,10 +1539,10 @@ private void WriteArrayItems(ElementAccessor[] elements, TextAccessor text, Choi int count = elements.Length + (text == null ? 0 : 1); if (count > 1) { - WriteLocalDecl(arrayNamePlusI, RaCodeGen.GetStringForArrayMember(arrayName, iPlusArrayName, arrayTypeDesc), arrayElementTypeDesc.Type); + WriteLocalDecl(arrayNamePlusI, RaCodeGen.GetStringForArrayMember(arrayName, iPlusArrayName, arrayTypeDesc), arrayElementTypeDesc.Type!); if (choice != null) { - WriteLocalDecl(choiceName + "i", RaCodeGen.GetStringForArrayMember(choiceName, iPlusArrayName, choice.Mapping.TypeDesc), choice.Mapping.TypeDesc.Type); + WriteLocalDecl(choiceName + "i", RaCodeGen.GetStringForArrayMember(choiceName, iPlusArrayName, choice.Mapping!.TypeDesc!), choice.Mapping.TypeDesc!.Type!); } WriteElements(new SourceInfo(arrayNamePlusI, null, null, arrayElementTypeDesc.Type, ilg), choiceName + "i", elements, text, choice, arrayNamePlusA, true, arrayElementTypeDesc.IsNullable); } @@ -1552,13 +1554,13 @@ private void WriteArrayItems(ElementAccessor[] elements, TextAccessor text, Choi } } - private void WriteElements(SourceInfo source, string enumSource, ElementAccessor[] elements, TextAccessor text, ChoiceIdentifierAccessor choice, string arrayName, bool writeAccessors, bool isNullable) + private void WriteElements(SourceInfo source, string? enumSource, ElementAccessor[] elements, TextAccessor? text, ChoiceIdentifierAccessor? choice, string arrayName, bool writeAccessors, bool isNullable) { if (elements.Length == 0 && text == null) return; if (elements.Length == 1 && text == null) { - TypeDesc td = elements[0].IsUnbounded ? elements[0].Mapping.TypeDesc.CreateArrayTypeDesc() : elements[0].Mapping.TypeDesc; - if (!elements[0].Any && !elements[0].Mapping.TypeDesc.IsOptionalValue) + TypeDesc td = elements[0].IsUnbounded ? elements[0].Mapping!.TypeDesc!.CreateArrayTypeDesc() : elements[0].Mapping!.TypeDesc!; + if (!elements[0].Any && !elements[0].Mapping!.TypeDesc!.IsOptionalValue) source = source.CastTo(td); WriteElement(source, elements[0], arrayName, writeAccessors); } @@ -1574,9 +1576,9 @@ private void WriteElements(SourceInfo source, string enumSource, ElementAccessor } int anyCount = 0; var namedAnys = new List(); - ElementAccessor unnamedAny = null; // can only have one + ElementAccessor? unnamedAny = null; // can only have one bool wroteFirstIf = false; - string enumTypeName = choice == null ? null : choice.Mapping.TypeDesc.FullName; + string? enumTypeName = choice == null ? null : choice.Mapping!.TypeDesc!.FullName; for (int i = 0; i < elements.Length; i++) { @@ -1592,13 +1594,13 @@ private void WriteElements(SourceInfo source, string enumSource, ElementAccessor } else if (choice != null) { - string fullTypeName = element.Mapping.TypeDesc.CSharpName; - object enumValue; - string enumFullName = enumTypeName + ".@" + FindChoiceEnumValue(element, (EnumMapping)choice.Mapping, out enumValue); + string fullTypeName = element.Mapping!.TypeDesc!.CSharpName; + object? enumValue; + string enumFullName = enumTypeName + ".@" + FindChoiceEnumValue(element, (EnumMapping)choice.Mapping!, out enumValue); if (wroteFirstIf) ilg.InitElseIf(); else { wroteFirstIf = true; ilg.InitIf(); } - ILGenLoad(enumSource, choice == null ? null : choice.Mapping.TypeDesc.Type); + ILGenLoad(enumSource!, choice == null ? null : choice.Mapping!.TypeDesc!.Type); ilg.Load(enumValue); ilg.Ceq(); if (isNullable && !element.IsNullable) @@ -1616,7 +1618,7 @@ private void WriteElements(SourceInfo source, string enumSource, ElementAccessor } ilg.AndIf(); - WriteChoiceTypeCheck(source, fullTypeName, choice, enumFullName, element.Mapping.TypeDesc); + WriteChoiceTypeCheck(source, fullTypeName, choice!, enumFullName, element.Mapping.TypeDesc); SourceInfo castedSource = source; castedSource = source.CastTo(element.Mapping.TypeDesc); @@ -1624,11 +1626,11 @@ private void WriteElements(SourceInfo source, string enumSource, ElementAccessor } else { - TypeDesc td = element.IsUnbounded ? element.Mapping.TypeDesc.CreateArrayTypeDesc() : element.Mapping.TypeDesc; + TypeDesc td = element.IsUnbounded ? element.Mapping!.TypeDesc!.CreateArrayTypeDesc() : element.Mapping!.TypeDesc!; string fullTypeName = td.CSharpName; if (wroteFirstIf) ilg.InitElseIf(); else { wroteFirstIf = true; ilg.InitIf(); } - WriteInstanceOf(source, td.Type); + WriteInstanceOf(source, td.Type!); // WriteInstanceOf leave bool on the stack ilg.AndIf(); SourceInfo castedSource = source; @@ -1652,7 +1654,7 @@ private void WriteElements(SourceInfo source, string enumSource, ElementAccessor if (elements.Length - anyCount > 0) ilg.InitElseIf(); else ilg.InitIf(); - string fullTypeName = typeof(XmlElement).FullName; + string fullTypeName = typeof(XmlElement).FullName!; source.Load(typeof(object)); ilg.IsInst(typeof(XmlElement)); @@ -1671,16 +1673,16 @@ private void WriteElements(SourceInfo source, string enumSource, ElementAccessor if (c++ > 0) ilg.InitElseIf(); else ilg.InitIf(); - string enumFullName = null; + string? enumFullName = null; Label labelEnd, labelFalse; if (choice != null) { - object enumValue; - enumFullName = enumTypeName + ".@" + FindChoiceEnumValue(element, (EnumMapping)choice.Mapping, out enumValue); + object? enumValue; + enumFullName = enumTypeName + ".@" + FindChoiceEnumValue(element, (EnumMapping)choice.Mapping!, out enumValue); labelFalse = ilg.DefineLabel(); labelEnd = ilg.DefineLabel(); - ILGenLoad(enumSource, choice == null ? null : choice.Mapping.TypeDesc.Type); + ILGenLoad(enumSource!, choice == null ? null : choice.Mapping!.TypeDesc!.Type); ilg.Load(enumValue); ilg.Bne(labelFalse); if (isNullable && !element.IsNullable) @@ -1705,12 +1707,12 @@ private void WriteElements(SourceInfo source, string enumSource, ElementAccessor "get_Name", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlNode_get_NamespaceURI = typeof(XmlNode).GetMethod( "get_NamespaceURI", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Ldloc(elemLoc); ilg.Call(XmlNode_get_Name); ilg.Ldstr(GetCSharpString(element.Name)); @@ -1718,7 +1720,7 @@ private void WriteElements(SourceInfo source, string enumSource, ElementAccessor "op_Equality", CodeGenerator.StaticBindingFlags, new Type[] { typeof(string), typeof(string) } - ); + )!; ilg.Call(String_op_Equality); ilg.Brfalse(labelFalse); ilg.Ldloc(elemLoc); @@ -1741,7 +1743,7 @@ private void WriteElements(SourceInfo source, string enumSource, ElementAccessor "CreateChoiceIdentifierValueException", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string), typeof(string), typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Ldstr(GetCSharpString(enumFullName)); ilg.Ldstr(GetCSharpString(choice.MemberName)); @@ -1768,19 +1770,19 @@ private void WriteElements(SourceInfo source, string enumSource, ElementAccessor "CreateUnknownAnyElementException", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Ldloc(elemLoc); MethodInfo XmlNode_get_Name = typeof(XmlNode).GetMethod( "get_Name", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; MethodInfo XmlNode_get_NamespaceURI = typeof(XmlNode).GetMethod( "get_NamespaceURI", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; ilg.Call(XmlNode_get_Name); ilg.Ldloc(elemLoc); ilg.Call(XmlNode_get_NamespaceURI); @@ -1794,11 +1796,11 @@ private void WriteElements(SourceInfo source, string enumSource, ElementAccessor } if (text != null) { - string fullTypeName = text.Mapping.TypeDesc.CSharpName; + string fullTypeName = text.Mapping!.TypeDesc!.CSharpName; if (elements.Length > 0) { ilg.InitElseIf(); - WriteInstanceOf(source, text.Mapping.TypeDesc.Type); + WriteInstanceOf(source, text.Mapping.TypeDesc.Type!); ilg.AndIf(); SourceInfo castedSource = source.CastTo(text.Mapping.TypeDesc); WriteText(castedSource, text); @@ -1826,7 +1828,7 @@ private void WriteElements(SourceInfo source, string enumSource, ElementAccessor MethodInfo XmlSerializationWriter_CreateUnknownTypeException = typeof(XmlSerializationWriter).GetMethod( "CreateUnknownTypeException", CodeGenerator.InstanceBindingFlags, - new Type[] { typeof(object) }); + new Type[] { typeof(object) })!; ilg.Ldarg(0); source.Load(typeof(object)); ilg.Call(XmlSerializationWriter_CreateUnknownTypeException); @@ -1853,31 +1855,31 @@ private void WriteText(SourceInfo source, TextAccessor text) } else { - WritePrimitiveValue(mapping.TypeDesc, source, out argType); + WritePrimitiveValue(mapping.TypeDesc!, source, out argType); } MethodInfo XmlSerializationWriter_WriteValue = typeof(XmlSerializationWriter).GetMethod( "WriteValue", CodeGenerator.InstanceBindingFlags, new Type[] { argType } - ); + )!; ilg.Call(XmlSerializationWriter_WriteValue); } else if (text.Mapping is SpecialMapping) { SpecialMapping mapping = (SpecialMapping)text.Mapping; - switch (mapping.TypeDesc.Kind) + switch (mapping.TypeDesc!.Kind) { case TypeKind.Node: - MethodInfo WriteTo = source.Type.GetMethod( + MethodInfo WriteTo = source.Type!.GetMethod( "WriteTo", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(XmlWriter) } - ); + )!; MethodInfo XmlSerializationWriter_get_Writer = typeof(XmlSerializationWriter).GetMethod( "get_Writer", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; source.Load(source.Type); ilg.Ldarg(0); ilg.Call(XmlSerializationWriter_get_Writer); @@ -1891,17 +1893,17 @@ private void WriteText(SourceInfo source, TextAccessor text) private void WriteElement(SourceInfo source, ElementAccessor element, string arrayName, bool writeAccessor) { - string name = writeAccessor ? element.Name : element.Mapping.TypeName; - string ns = element.Any && element.Name.Length == 0 ? null : (element.Form == XmlSchemaForm.Qualified ? (writeAccessor ? element.Namespace : element.Mapping.Namespace) : ""); + string name = writeAccessor ? element.Name : element.Mapping!.TypeName!; + string? ns = element.Any && element.Name.Length == 0 ? null : (element.Form == XmlSchemaForm.Qualified ? (writeAccessor ? element.Namespace : element.Mapping!.Namespace) : ""); if (element.Mapping is NullableMapping) { - if (source.Type == element.Mapping.TypeDesc.Type) + if (source.Type == element.Mapping.TypeDesc!.Type) { - MethodInfo Nullable_get_HasValue = element.Mapping.TypeDesc.Type.GetMethod( + MethodInfo Nullable_get_HasValue = element.Mapping.TypeDesc.Type!.GetMethod( "get_HasValue", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; source.LoadAddress(element.Mapping.TypeDesc.Type); ilg.Call(Nullable_get_HasValue); } @@ -1912,7 +1914,7 @@ private void WriteElement(SourceInfo source, ElementAccessor element, string arr ilg.Cne(); } ilg.If(); - string fullTypeName = element.Mapping.TypeDesc.BaseTypeDesc.CSharpName; + string fullTypeName = element.Mapping.TypeDesc.BaseTypeDesc!.CSharpName; SourceInfo castedSource = source.CastTo(element.Mapping.TypeDesc.BaseTypeDesc); ElementAccessor e = element.Clone(); e.Mapping = ((NullableMapping)element.Mapping).BaseMapping; @@ -1934,7 +1936,7 @@ private void WriteElement(SourceInfo source, ElementAccessor element, string arr else { ilg.EnterScope(); - string fullTypeName = mapping.TypeDesc.CSharpName; + string fullTypeName = mapping.TypeDesc!.CSharpName; WriteArrayLocalDecl(fullTypeName, arrayName, source, mapping.TypeDesc); if (element.IsNullable) { @@ -1950,7 +1952,7 @@ private void WriteElement(SourceInfo source, ElementAccessor element, string arr } } WriteStartElement(name, ns, false); - WriteArrayItems(mapping.ElementsSortedByDerivation, null, null, mapping.TypeDesc, arrayName, null); + WriteArrayItems(mapping.ElementsSortedByDerivation!, null, null, mapping.TypeDesc, arrayName, null); WriteEndElement(); if (element.IsNullable) { @@ -1977,7 +1979,7 @@ private void WriteElement(SourceInfo source, ElementAccessor element, string arr WriteQualifiedNameElement(name, ns, GetConvertedDefaultValue(source.Type, element.Default), source, element.IsNullable, mapping); else { - string suffixRaw = mapping.TypeDesc.XmlEncodingNotRequired ? "Raw" : ""; + string suffixRaw = mapping.TypeDesc!.XmlEncodingNotRequired ? "Raw" : ""; WritePrimitive(element.IsNullable ? ("WriteNullableStringLiteral" + suffixRaw) : ("WriteElementString" + suffixRaw), name, ns, GetConvertedDefaultValue(source.Type, element.Default), source, mapping, false, true, element.IsNullable); } @@ -1986,11 +1988,11 @@ private void WriteElement(SourceInfo source, ElementAccessor element, string arr { StructMapping mapping = (StructMapping)element.Mapping; - string methodName = ReferenceMapping(mapping); + string? methodName = ReferenceMapping(mapping); #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe - if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc.Name)); + if (methodName == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorMethod, mapping.TypeDesc!.Name)); #endif List argTypes = new List(); ilg.Ldarg(0); @@ -1998,8 +2000,8 @@ private void WriteElement(SourceInfo source, ElementAccessor element, string arr argTypes.Add(typeof(string)); ilg.Ldstr(GetCSharpString(ns)); argTypes.Add(typeof(string)); - source.Load(mapping.TypeDesc.Type); - argTypes.Add(mapping.TypeDesc.Type); + source.Load(mapping.TypeDesc!.Type); + argTypes.Add(mapping.TypeDesc.Type!); if (mapping.TypeDesc.IsNullable) { ilg.Ldc(element.IsNullable); @@ -2017,7 +2019,7 @@ private void WriteElement(SourceInfo source, ElementAccessor element, string arr else if (element.Mapping is SpecialMapping) { SpecialMapping mapping = (SpecialMapping)element.Mapping; - TypeDesc td = mapping.TypeDesc; + TypeDesc td = mapping.TypeDesc!; string fullTypeName = td.CSharpName; @@ -2050,7 +2052,7 @@ private void WriteElement(SourceInfo source, ElementAccessor element, string arr "CreateInvalidAnyTypeException", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(object) } - ); + )!; ilg.Ldarg(0); source.Load(null); ilg.Call(XmlSerializationWriter_CreateInvalidAnyTypeException); @@ -2065,13 +2067,13 @@ private void WriteElement(SourceInfo source, ElementAccessor element, string arr } } - private void WriteElementCall(string func, Type cast, SourceInfo source, string name, string ns, bool isNullable, bool isAny) + private void WriteElementCall(string func, Type cast, SourceInfo source, string? name, string? ns, bool isNullable, bool isAny) { MethodInfo XmlSerializationWriter_func = typeof(XmlSerializationWriter).GetMethod( func, CodeGenerator.InstanceBindingFlags, new Type[] { cast, typeof(string), typeof(string), typeof(bool), typeof(bool) } - ); + )!; ilg.Ldarg(0); source.Load(cast); ilg.Ldstr(GetCSharpString(name)); @@ -2100,7 +2102,7 @@ private void WriteCheckDefault(SourceInfo source, object value, bool isNullable) "get_Length", CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; source.Load(typeof(string)); ilg.Call(String_get_Length); ilg.Ldc(0); @@ -2130,7 +2132,7 @@ private void WriteCheckDefault(SourceInfo source, object value, bool isNullable) else if (value.GetType().IsPrimitive) { source.Load(null); - ilg.Ldc(Convert.ChangeType(value, source.Type, CultureInfo.InvariantCulture)); + ilg.Ldc(Convert.ChangeType(value, source.Type!, CultureInfo.InvariantCulture)); ilg.Cne(); } else @@ -2142,7 +2144,7 @@ private void WriteCheckDefault(SourceInfo source, object value, bool isNullable) "op_Inequality", CodeGenerator.StaticBindingFlags, new Type[] { valueType, valueType } - ); + )!; if (op_Inequality != null) ilg.Call(op_Inequality); else @@ -2159,7 +2161,7 @@ private void WriteChoiceTypeCheck(SourceInfo source, string fullTypeName, Choice source.Load(typeof(object)); ilg.Load(null); ilg.Beq(labelFalse); - WriteInstanceOf(source, typeDesc.Type); + WriteInstanceOf(source, typeDesc.Type!); // Negative ilg.Ldc(false); ilg.Ceq(); @@ -2172,7 +2174,7 @@ private void WriteChoiceTypeCheck(SourceInfo source, string fullTypeName, Choice "CreateMismatchChoiceException", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(string), typeof(string), typeof(string) } - ); + )!; ilg.Ldarg(0); ilg.Ldstr(GetCSharpString(typeDesc.FullName)); ilg.Ldstr(GetCSharpString(choice.MemberName)); @@ -2200,7 +2202,7 @@ private void WriteNamespaces(string source) "WriteNamespaceDeclarations", CodeGenerator.InstanceBindingFlags, new Type[] { typeof(XmlSerializerNamespaces) } - ); + )!; ilg.Ldarg(0); ILGenLoad(source, typeof(XmlSerializerNamespaces)); ilg.Call(XmlSerializationWriter_WriteNamespaceDeclarations); @@ -2241,12 +2243,12 @@ private void WriteArrayTypeCompare(string variable, Type arrayType) } - private string FindChoiceEnumValue(ElementAccessor element, EnumMapping choiceMapping, out object eValue) + private string FindChoiceEnumValue(ElementAccessor element, EnumMapping choiceMapping, out object? eValue) { - string enumValue = null; + string? enumValue = null; eValue = null; - for (int i = 0; i < choiceMapping.Constants.Length; i++) + for (int i = 0; i < choiceMapping.Constants!.Length; i++) { string xmlName = choiceMapping.Constants[i].XmlName; @@ -2255,13 +2257,13 @@ private string FindChoiceEnumValue(ElementAccessor element, EnumMapping choiceMa if (xmlName == "##any:") { enumValue = choiceMapping.Constants[i].Name; - eValue = Enum.ToObject(choiceMapping.TypeDesc.Type, choiceMapping.Constants[i].Value); + eValue = Enum.ToObject(choiceMapping.TypeDesc!.Type!, choiceMapping.Constants[i].Value); break; } continue; } int colon = xmlName.LastIndexOf(':'); - string choiceNs = colon < 0 ? choiceMapping.Namespace : xmlName.Substring(0, colon); + string? choiceNs = colon < 0 ? choiceMapping.Namespace : xmlName.Substring(0, colon); string choiceName = colon < 0 ? xmlName : xmlName.Substring(colon + 1); if (element.Name == choiceName) @@ -2269,7 +2271,7 @@ private string FindChoiceEnumValue(ElementAccessor element, EnumMapping choiceMa if ((element.Form == XmlSchemaForm.Unqualified && string.IsNullOrEmpty(choiceNs)) || element.Namespace == choiceNs) { enumValue = choiceMapping.Constants[i].Name; - eValue = Enum.ToObject(choiceMapping.TypeDesc.Type, choiceMapping.Constants[i].Value); + eValue = Enum.ToObject(choiceMapping.TypeDesc!.Type!, choiceMapping.Constants[i].Value); break; } } @@ -2279,10 +2281,10 @@ private string FindChoiceEnumValue(ElementAccessor element, EnumMapping choiceMa if (element.Any && element.Name.Length == 0) { // Type {0} is missing enumeration value '##any' for XmlAnyElementAttribute. - throw new InvalidOperationException(SR.Format(SR.XmlChoiceMissingAnyValue, choiceMapping.TypeDesc.FullName)); + throw new InvalidOperationException(SR.Format(SR.XmlChoiceMissingAnyValue, choiceMapping.TypeDesc!.FullName)); } // Type {0} is missing value for '{1}'. - throw new InvalidOperationException(SR.Format(SR.XmlChoiceMissingValue, choiceMapping.TypeDesc.FullName, element.Namespace + ":" + element.Name, element.Name, element.Namespace)); + throw new InvalidOperationException(SR.Format(SR.XmlChoiceMissingValue, choiceMapping.TypeDesc!.FullName, element.Namespace + ":" + element.Name, element.Name, element.Namespace)); } CodeIdentifier.CheckValidIdentifier(enumValue); return enumValue; @@ -2338,16 +2340,16 @@ internal SourceInfo GetSourceForMember(string obj, MemberMapping member, TypeDes { return GetSourceForMember(obj, member, member.MemberInfo, typeDesc, ilg); } - internal SourceInfo GetSourceForMember(string obj, MemberMapping member, MemberInfo memberInfo, TypeDesc typeDesc, CodeGenerator ilg) + internal SourceInfo GetSourceForMember(string obj, MemberMapping member, MemberInfo? memberInfo, TypeDesc typeDesc, CodeGenerator ilg) { - return new SourceInfo(GetStringForMember(obj, member.Name, typeDesc), obj, memberInfo, member.TypeDesc.Type, ilg); + return new SourceInfo(GetStringForMember(obj, member.Name, typeDesc), obj, memberInfo, member.TypeDesc!.Type, ilg); } internal void ILGenForEnumMember(CodeGenerator ilg, Type type, string memberName) { ilg.Ldc(Enum.Parse(type, memberName, false)); } - internal string GetStringForArrayMember(string arrayName, string subscript, TypeDesc arrayTypeDesc) + internal string GetStringForArrayMember(string? arrayName, string subscript, TypeDesc arrayTypeDesc) { { return arrayName + "[" + subscript + "]"; @@ -2364,7 +2366,7 @@ internal void ILGenForCreateInstance(CodeGenerator ilg, Type type, bool ctorInac ConstructorInfo ctor = type.GetConstructor( CodeGenerator.InstanceBindingFlags, Array.Empty() - ); + )!; if (ctor != null) ilg.New(ctor); else @@ -2380,12 +2382,12 @@ internal void ILGenForCreateInstance(CodeGenerator ilg, Type type, bool ctorInac ILGenForCreateInstance(ilg, type, cast ? type : null, ctorInaccessible); } - internal void ILGenForCreateInstance(CodeGenerator ilg, Type type, Type cast, bool nonPublic) + internal void ILGenForCreateInstance(CodeGenerator ilg, Type type, Type? cast, bool nonPublic) { // Special case DBNull if (type == typeof(DBNull)) { - FieldInfo DBNull_Value = type.GetField("Value", CodeGenerator.StaticBindingFlags); + FieldInfo DBNull_Value = type.GetField("Value", CodeGenerator.StaticBindingFlags)!; ilg.LoadMember(DBNull_Value); return; } @@ -2394,18 +2396,18 @@ internal void ILGenForCreateInstance(CodeGenerator ilg, Type type, Type cast, bo // codegen the same as 'internal XElement : this("default") { }' if (type.FullName == "System.Xml.Linq.XElement") { - Type xName = type.Assembly.GetType("System.Xml.Linq.XName"); + Type? xName = type.Assembly.GetType("System.Xml.Linq.XName"); if (xName != null) { MethodInfo XName_op_Implicit = xName.GetMethod( "op_Implicit", CodeGenerator.StaticBindingFlags, new Type[] { typeof(string) } - ); + )!; ConstructorInfo XElement_ctor = type.GetConstructor( CodeGenerator.InstanceBindingFlags, new Type[] { xName } - ); + )!; if (XName_op_Implicit != null && XElement_ctor != null) { ilg.Ldstr("default"); @@ -2426,20 +2428,20 @@ internal void ILGenForCreateInstance(CodeGenerator ilg, Type type, Type cast, bo "GetTypeInfo", CodeGenerator.StaticBindingFlags, new[] { typeof(Type) } - ); + )!; ilg.Call(getTypeInfoMehod); // IEnumerator e = typeInfo.DeclaredConstructors.GetEnumerator(); LocalBuilder enumerator = ilg.DeclareLocal(typeof(IEnumerator<>).MakeGenericType(typeof(ConstructorInfo)), "e"); - MethodInfo getDeclaredConstructors = typeof(TypeInfo).GetMethod("get_DeclaredConstructors"); - MethodInfo getEnumerator = typeof(IEnumerable<>).MakeGenericType(typeof(ConstructorInfo)).GetMethod("GetEnumerator"); + MethodInfo getDeclaredConstructors = typeof(TypeInfo).GetMethod("get_DeclaredConstructors")!; + MethodInfo getEnumerator = typeof(IEnumerable<>).MakeGenericType(typeof(ConstructorInfo)).GetMethod("GetEnumerator")!; ilg.Call(getDeclaredConstructors); ilg.Call(getEnumerator); ilg.Stloc(enumerator); ilg.WhileBegin(); // ConstructorInfo constructorInfo = e.Current(); - MethodInfo enumeratorCurrent = typeof(IEnumerator).GetMethod("get_Current"); + MethodInfo enumeratorCurrent = typeof(IEnumerator).GetMethod("get_Current")!; ilg.Ldloc(enumerator); ilg.Call(enumeratorCurrent); LocalBuilder constructorInfo = ilg.DeclareLocal(typeof(ConstructorInfo), "constructorInfo"); @@ -2447,11 +2449,11 @@ internal void ILGenForCreateInstance(CodeGenerator ilg, Type type, Type cast, bo // if (!constructorInfo.IsStatic && constructorInfo.GetParameters.Length() == 0) ilg.Ldloc(constructorInfo); - MethodInfo constructorIsStatic = typeof(ConstructorInfo).GetMethod("get_IsStatic"); + MethodInfo constructorIsStatic = typeof(ConstructorInfo).GetMethod("get_IsStatic")!; ilg.Call(constructorIsStatic); ilg.Brtrue(labelEndIf); ilg.Ldloc(constructorInfo); - MethodInfo constructorGetParameters = typeof(ConstructorInfo).GetMethod("GetParameters"); + MethodInfo constructorGetParameters = typeof(ConstructorInfo).GetMethod("GetParameters")!; ilg.Call(constructorGetParameters); ilg.Ldlen(); ilg.Ldc(0); @@ -2459,7 +2461,7 @@ internal void ILGenForCreateInstance(CodeGenerator ilg, Type type, Type cast, bo ilg.Brtrue(labelEndIf); // constructorInfo.Invoke(null); - MethodInfo constructorInvoke = typeof(ConstructorInfo).GetMethod("Invoke", new Type[] { typeof(object[]) }); + MethodInfo constructorInvoke = typeof(ConstructorInfo).GetMethod("Invoke", new Type[] { typeof(object[]) })!; ilg.Ldloc(constructorInfo); ilg.Load(null); ilg.Call(constructorInvoke); @@ -2470,7 +2472,7 @@ internal void ILGenForCreateInstance(CodeGenerator ilg, Type type, Type cast, bo MethodInfo IEnumeratorMoveNext = typeof(IEnumerator).GetMethod( "MoveNext", CodeGenerator.InstanceBindingFlags, - Array.Empty()); + Array.Empty())!; ilg.Ldloc(enumerator); ilg.Call(IEnumeratorMoveNext); ilg.WhileEndCondition(); @@ -2480,7 +2482,7 @@ internal void ILGenForCreateInstance(CodeGenerator ilg, Type type, Type cast, bo "CreateInstance", CodeGenerator.StaticBindingFlags, new Type[] { typeof(Type) } - ); + )!; ilg.Ldc(type); ilg.Call(Activator_CreateInstance); ilg.MarkLabel(labelReturn); @@ -2490,7 +2492,7 @@ internal void ILGenForCreateInstance(CodeGenerator ilg, Type type, Type cast, bo internal void WriteLocalDecl(string variableName, SourceInfo initValue) { - Type localType = initValue.Type; + Type localType = initValue.Type!; LocalBuilder localA = initValue.ILG.DeclareOrGetLocal(localType, variableName); if (initValue.Source != null) { @@ -2514,7 +2516,7 @@ internal void WriteLocalDecl(string variableName, SourceInfo initValue) { string[] vars = initValue.Source.Split('.'); object fixup = initValue.ILG.GetVariable(vars[0]); - PropertyInfo propInfo = initValue.ILG.GetVariableType(fixup).GetProperty(vars[1]); + PropertyInfo propInfo = initValue.ILG.GetVariableType(fixup).GetProperty(vars[1])!; initValue.ILG.LoadMember(fixup, propInfo); initValue.ILG.ConvertValue(propInfo.PropertyType, localA.LocalType); } @@ -2549,7 +2551,7 @@ internal void WriteInstanceOf(SourceInfo source, Type type, CodeGenerator ilg) internal void WriteArrayLocalDecl(string typeName, string variableName, SourceInfo initValue, TypeDesc arrayTypeDesc) { Debug.Assert(typeName == arrayTypeDesc.CSharpName || typeName == arrayTypeDesc.CSharpName + "[]"); - Type localType = (typeName == arrayTypeDesc.CSharpName) ? arrayTypeDesc.Type : arrayTypeDesc.Type.MakeArrayType(); + Type localType = (typeName == arrayTypeDesc.CSharpName) ? arrayTypeDesc.Type! : arrayTypeDesc.Type!.MakeArrayType(); // This may need reused variable to get code compat? LocalBuilder local = initValue.ILG.DeclareOrGetLocal(localType, variableName); if (initValue != null) @@ -2578,7 +2580,8 @@ internal void WriteArrayTypeCompare(string variable, Type arrayType, CodeGenerat } } - internal static string GetQuotedCSharpString(string value) + [return: NotNullIfNotNull("value")] + internal static string? GetQuotedCSharpString(string? value) { if (value == null) { @@ -2591,7 +2594,8 @@ internal static string GetQuotedCSharpString(string value) return writer.ToString(); } - internal static string GetCSharpString(string value) + [return: NotNullIfNotNull("value")] + internal static string? GetCSharpString(string? value) { if (value == null) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs index 32e7571198a148..55aa23007248af 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System.Reflection; @@ -21,13 +22,13 @@ namespace System.Xml.Serialization public struct XmlDeserializationEvents { - private XmlNodeEventHandler _onUnknownNode; - private XmlAttributeEventHandler _onUnknownAttribute; - private XmlElementEventHandler _onUnknownElement; - private UnreferencedObjectEventHandler _onUnreferencedObject; - internal object sender; + private XmlNodeEventHandler? _onUnknownNode; + private XmlAttributeEventHandler? _onUnknownAttribute; + private XmlElementEventHandler? _onUnknownElement; + private UnreferencedObjectEventHandler? _onUnreferencedObject; + internal object? sender; - public XmlNodeEventHandler OnUnknownNode + public XmlNodeEventHandler? OnUnknownNode { get { @@ -40,7 +41,7 @@ public XmlNodeEventHandler OnUnknownNode } } - public XmlAttributeEventHandler OnUnknownAttribute + public XmlAttributeEventHandler? OnUnknownAttribute { get { @@ -52,7 +53,7 @@ public XmlAttributeEventHandler OnUnknownAttribute } } - public XmlElementEventHandler OnUnknownElement + public XmlElementEventHandler? OnUnknownElement { get { @@ -64,7 +65,7 @@ public XmlElementEventHandler OnUnknownElement } } - public UnreferencedObjectEventHandler OnUnreferencedObject + public UnreferencedObjectEventHandler? OnUnreferencedObject { get { @@ -118,19 +119,19 @@ private static bool ReflectionMethodEnabled } } - private TempAssembly _tempAssembly; + private TempAssembly? _tempAssembly; #pragma warning disable 0414 private bool _typedSerializer; #pragma warning restore 0414 - private readonly Type _primitiveType; - private XmlMapping _mapping; + private readonly Type? _primitiveType; + private XmlMapping _mapping = null!; private XmlDeserializationEvents _events; - internal string DefaultNamespace; - private Type _rootType; + internal string? DefaultNamespace; + private Type _rootType = null!; private bool _isReflectionBasedSerializer; private static readonly TempAssemblyCache s_cache = new TempAssemblyCache(); - private static volatile XmlSerializerNamespaces s_defaultNamespaces; + private static volatile XmlSerializerNamespaces? s_defaultNamespaces; private static XmlSerializerNamespaces DefaultNamespaces { get @@ -181,11 +182,11 @@ public XmlSerializer(XmlTypeMapping xmlTypeMapping) _mapping = xmlTypeMapping; } - public XmlSerializer(Type type) : this(type, (string)null) + public XmlSerializer(Type type) : this(type, (string?)null) { } - public XmlSerializer(Type type, string defaultNamespace) + public XmlSerializer(Type type, string? defaultNamespace) { if (type == null) throw new ArgumentNullException(nameof(type)); @@ -193,7 +194,7 @@ public XmlSerializer(Type type, string defaultNamespace) DefaultNamespace = defaultNamespace; _rootType = type; - _mapping = GetKnownMapping(type, defaultNamespace); + _mapping = GetKnownMapping(type, defaultNamespace)!; if (_mapping != null) { _primitiveType = type; @@ -208,8 +209,8 @@ public XmlSerializer(Type type, string defaultNamespace) if (_tempAssembly == null) { { - XmlSerializerImplementation contract = null; - Assembly assembly = TempAssembly.LoadGeneratedAssembly(type, defaultNamespace, out contract); + XmlSerializerImplementation? contract = null; + Assembly? assembly = TempAssembly.LoadGeneratedAssembly(type, defaultNamespace, out contract); if (assembly == null) { if (Mode == SerializationMode.PreGenOnly) @@ -222,7 +223,7 @@ public XmlSerializer(Type type, string defaultNamespace) // need to reflect and generate new serialization assembly XmlReflectionImporter importer = new XmlReflectionImporter(defaultNamespace); _mapping = importer.ImportTypeMapping(type, null, defaultNamespace); - _tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace); + _tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace)!; } else { @@ -242,7 +243,7 @@ public XmlSerializer(Type type, string defaultNamespace) } } - public XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace, string location) + public XmlSerializer(Type type, XmlAttributeOverrides? overrides, Type[]? extraTypes, XmlRootAttribute? root, string? defaultNamespace, string? location) { if (type == null) throw new ArgumentNullException(nameof(type)); @@ -253,7 +254,7 @@ public XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTyp _tempAssembly = GenerateTempAssembly(_mapping, type, defaultNamespace, location); } - private XmlTypeMapping GenerateXmlTypeMapping(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace) + private XmlTypeMapping GenerateXmlTypeMapping(Type type, XmlAttributeOverrides? overrides, Type[]? extraTypes, XmlRootAttribute? root, string? defaultNamespace) { XmlReflectionImporter importer = new XmlReflectionImporter(overrides, defaultNamespace); if (extraTypes != null) @@ -265,17 +266,17 @@ private XmlTypeMapping GenerateXmlTypeMapping(Type type, XmlAttributeOverrides o return importer.ImportTypeMapping(type, root, defaultNamespace); } - internal static TempAssembly GenerateTempAssembly(XmlMapping xmlMapping) + internal static TempAssembly? GenerateTempAssembly(XmlMapping xmlMapping) { return GenerateTempAssembly(xmlMapping, null, null); } - internal static TempAssembly GenerateTempAssembly(XmlMapping xmlMapping, Type type, string defaultNamespace) + internal static TempAssembly? GenerateTempAssembly(XmlMapping xmlMapping, Type? type, string? defaultNamespace) { return GenerateTempAssembly(xmlMapping, type, defaultNamespace, null); } - internal static TempAssembly GenerateTempAssembly(XmlMapping xmlMapping, Type type, string defaultNamespace, string location) + internal static TempAssembly? GenerateTempAssembly(XmlMapping xmlMapping, Type? type, string? defaultNamespace, string? location) { if (xmlMapping == null) { @@ -288,7 +289,7 @@ internal static TempAssembly GenerateTempAssembly(XmlMapping xmlMapping, Type ty return null; } - return new TempAssembly(new XmlMapping[] { xmlMapping }, new Type[] { type }, defaultNamespace, location); + return new TempAssembly(new XmlMapping[] { xmlMapping }, new Type?[] { type }, defaultNamespace, location); } public void Serialize(TextWriter textWriter, object o) @@ -296,7 +297,7 @@ public void Serialize(TextWriter textWriter, object o) Serialize(textWriter, o, null); } - public void Serialize(TextWriter textWriter, object o, XmlSerializerNamespaces namespaces) + public void Serialize(TextWriter textWriter, object o, XmlSerializerNamespaces? namespaces) { XmlTextWriter xmlWriter = new XmlTextWriter(textWriter); xmlWriter.Formatting = Formatting.Indented; @@ -309,7 +310,7 @@ public void Serialize(Stream stream, object o) Serialize(stream, o, null); } - public void Serialize(Stream stream, object o, XmlSerializerNamespaces namespaces) + public void Serialize(Stream stream, object o, XmlSerializerNamespaces? namespaces) { XmlTextWriter xmlWriter = new XmlTextWriter(stream, null); xmlWriter.Formatting = Formatting.Indented; @@ -322,17 +323,17 @@ public void Serialize(XmlWriter xmlWriter, object o) Serialize(xmlWriter, o, null); } - public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces) + public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces? namespaces) { Serialize(xmlWriter, o, namespaces, null); } - public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle) + public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces? namespaces, string? encodingStyle) { Serialize(xmlWriter, o, namespaces, encodingStyle, null); } - public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle, string id) + public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces? namespaces, string? encodingStyle, string? id) { try { @@ -365,7 +366,7 @@ public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces nam else _tempAssembly.InvokeWriter(_mapping, xmlWriter, o, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id); } - catch (Exception e) + catch (Exception? e) { if (e is TargetInvocationException) e = e.InnerException; @@ -374,7 +375,7 @@ public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces nam xmlWriter.Flush(); } - private void SerializeUsingReflection(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces, string encodingStyle, string id) + private void SerializeUsingReflection(XmlWriter xmlWriter, object o, XmlSerializerNamespaces? namespaces, string? encodingStyle, string? id) { XmlMapping mapping = GetMapping(); var writer = new ReflectionXmlSerializationWriter(mapping, xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id); @@ -391,7 +392,7 @@ private XmlMapping GetMapping() return _mapping; } - public object Deserialize(Stream stream) + public object? Deserialize(Stream stream) { XmlTextReader xmlReader = new XmlTextReader(stream); xmlReader.WhitespaceHandling = WhitespaceHandling.Significant; @@ -400,7 +401,7 @@ public object Deserialize(Stream stream) return Deserialize(xmlReader, null); } - public object Deserialize(TextReader textReader) + public object? Deserialize(TextReader textReader) { XmlTextReader xmlReader = new XmlTextReader(textReader); xmlReader.WhitespaceHandling = WhitespaceHandling.Significant; @@ -409,22 +410,22 @@ public object Deserialize(TextReader textReader) return Deserialize(xmlReader, null); } - public object Deserialize(XmlReader xmlReader) + public object? Deserialize(XmlReader xmlReader) { return Deserialize(xmlReader, null); } - public object Deserialize(XmlReader xmlReader, XmlDeserializationEvents events) + public object? Deserialize(XmlReader xmlReader, XmlDeserializationEvents events) { return Deserialize(xmlReader, null, events); } - public object Deserialize(XmlReader xmlReader, string encodingStyle) + public object? Deserialize(XmlReader xmlReader, string? encodingStyle) { return Deserialize(xmlReader, encodingStyle, _events); } - public object Deserialize(XmlReader xmlReader, string encodingStyle, XmlDeserializationEvents events) + public object? Deserialize(XmlReader xmlReader, string? encodingStyle, XmlDeserializationEvents events) { events.sender = this; try @@ -459,7 +460,7 @@ public object Deserialize(XmlReader xmlReader, string encodingStyle, XmlDeserial return _tempAssembly.InvokeReader(_mapping, xmlReader, events, encodingStyle); } } - catch (Exception e) + catch (Exception? e) { if (e is TargetInvocationException) e = e.InnerException; @@ -476,7 +477,7 @@ public object Deserialize(XmlReader xmlReader, string encodingStyle, XmlDeserial } } - private object DeserializeUsingReflection(XmlReader xmlReader, string encodingStyle, XmlDeserializationEvents events) + private object? DeserializeUsingReflection(XmlReader xmlReader, string? encodingStyle, XmlDeserializationEvents events) { XmlMapping mapping = GetMapping(); var reader = new ReflectionXmlSerializationReader(mapping, xmlReader, events, encodingStyle); @@ -493,8 +494,8 @@ public virtual bool CanDeserialize(XmlReader xmlReader) { if (_primitiveType != null) { - TypeDesc typeDesc = (TypeDesc)TypeScope.PrimtiveTypes[_primitiveType]; - return xmlReader.IsStartElement(typeDesc.DataType.Name, string.Empty); + TypeDesc typeDesc = (TypeDesc)TypeScope.PrimtiveTypes[_primitiveType]!; + return xmlReader.IsStartElement(typeDesc.DataType!.Name!, string.Empty); } else if (_tempAssembly != null) { @@ -508,10 +509,10 @@ public virtual bool CanDeserialize(XmlReader xmlReader) public static XmlSerializer[] FromMappings(XmlMapping[] mappings) { - return FromMappings(mappings, (Type)null); + return FromMappings(mappings, (Type?)null); } - public static XmlSerializer[] FromMappings(XmlMapping[] mappings, Type type) + public static XmlSerializer[] FromMappings(XmlMapping[] mappings, Type? type) { if (mappings == null || mappings.Length == 0) return Array.Empty(); bool anySoapMapping = false; @@ -525,18 +526,18 @@ public static XmlSerializer[] FromMappings(XmlMapping[] mappings, Type type) if ((anySoapMapping && ReflectionMethodEnabled) || Mode == SerializationMode.ReflectionOnly) { - XmlSerializer[] serializers = GetReflectionBasedSerializers(mappings, type); + XmlSerializer[] serializers = GetReflectionBasedSerializers(mappings, type!); return serializers; } - XmlSerializerImplementation contract = null; - Assembly assembly = type == null ? null : TempAssembly.LoadGeneratedAssembly(type, null, out contract); - TempAssembly tempAssembly = null; + XmlSerializerImplementation? contract = null; + Assembly? assembly = type == null ? null : TempAssembly.LoadGeneratedAssembly(type, null, out contract); + TempAssembly? tempAssembly = null; if (assembly == null) { if (Mode == SerializationMode.PreGenOnly) { - AssemblyName name = type.Assembly.GetName(); + AssemblyName name = type!.Assembly.GetName(); string serializerName = Compiler.GetTempAssemblyName(name, null); throw new FileLoadException(SR.Format(SR.FailLoadAssemblyUnderPregenMode, serializerName)); } @@ -549,14 +550,14 @@ public static XmlSerializer[] FromMappings(XmlMapping[] mappings, Type type) { if (type == null) { - tempAssembly = new TempAssembly(mappings, new Type[] { type }, null, null); + tempAssembly = new TempAssembly(mappings, new Type?[] { type }, null, null); XmlSerializer[] serializers = new XmlSerializer[mappings.Length]; contract = tempAssembly.Contract; for (int i = 0; i < serializers.Length; i++) { - serializers[i] = (XmlSerializer)contract.TypedSerializers[mappings[i].Key]; + serializers[i] = (XmlSerializer)contract.TypedSerializers[mappings[i].Key!]!; serializers[i].SetTempAssembly(tempAssembly, mappings[i]); } @@ -573,7 +574,7 @@ public static XmlSerializer[] FromMappings(XmlMapping[] mappings, Type type) { XmlSerializer[] serializers = new XmlSerializer[mappings.Length]; for (int i = 0; i < serializers.Length; i++) - serializers[i] = (XmlSerializer)contract.TypedSerializers[mappings[i].Key]; + serializers[i] = (XmlSerializer)contract!.TypedSerializers[mappings[i].Key!]!; return serializers; } } @@ -592,7 +593,7 @@ private static XmlSerializer[] GetReflectionBasedSerializers(XmlMapping[] mappin return serializers; } - internal static bool GenerateSerializer(Type[] types, XmlMapping[] mappings, Stream stream) + internal static bool GenerateSerializer(Type[]? types, XmlMapping[] mappings, Stream stream) { if (types == null || types.Length == 0) return false; @@ -608,7 +609,7 @@ internal static bool GenerateSerializer(Type[] types, XmlMapping[] mappings, Str throw new InvalidOperationException(SR.XmlMelformMapping); } - Assembly assembly = null; + Assembly? assembly = null; for (int i = 0; i < types.Length; i++) { Type type = types[i]; @@ -632,9 +633,9 @@ internal static bool GenerateSerializer(Type[] types, XmlMapping[] mappings, Str private static XmlSerializer[] GetSerializersFromCache(XmlMapping[] mappings, Type type) { - XmlSerializer[] serializers = new XmlSerializer[mappings.Length]; + XmlSerializer?[] serializers = new XmlSerializer?[mappings.Length]; - Dictionary typedMappingTable = null; + Dictionary? typedMappingTable = null; lock (s_xmlSerializerTable) { if (!s_xmlSerializerTable.TryGetValue(type, out typedMappingTable)) @@ -671,15 +672,15 @@ private static XmlSerializer[] GetSerializersFromCache(XmlMapping[] mappings, Ty foreach (XmlSerializerMappingKey mappingKey in pendingKeys.Keys) { index = pendingKeys[mappingKey]; - serializers[index] = (XmlSerializer)contract.TypedSerializers[mappingKey.Mapping.Key]; - serializers[index].SetTempAssembly(tempAssembly, mappingKey.Mapping); + serializers[index] = (XmlSerializer)contract.TypedSerializers[mappingKey.Mapping.Key!]!; + serializers[index]!.SetTempAssembly(tempAssembly, mappingKey.Mapping); - typedMappingTable[mappingKey] = serializers[index]; + typedMappingTable[mappingKey] = serializers[index]!; } } } - return serializers; + return serializers!; } public static XmlSerializer[] FromTypes(Type[] types) @@ -701,7 +702,7 @@ public static string GetXmlSerializerAssemblyName(Type type) return GetXmlSerializerAssemblyName(type, null); } - public static string GetXmlSerializerAssemblyName(Type type, string defaultNamespace) + public static string GetXmlSerializerAssemblyName(Type type, string? defaultNamespace) { if (type == null) { @@ -773,25 +774,25 @@ internal void SetTempAssembly(TempAssembly tempAssembly, XmlMapping mapping) _typedSerializer = true; } - private static XmlTypeMapping GetKnownMapping(Type type, string ns) + private static XmlTypeMapping? GetKnownMapping(Type type, string? ns) { if (ns != null && ns != string.Empty) return null; - TypeDesc typeDesc = (TypeDesc)TypeScope.PrimtiveTypes[type]; + TypeDesc? typeDesc = (TypeDesc?)TypeScope.PrimtiveTypes[type]; if (typeDesc == null) return null; ElementAccessor element = new ElementAccessor(); - element.Name = typeDesc.DataType.Name; + element.Name = typeDesc.DataType!.Name; XmlTypeMapping mapping = new XmlTypeMapping(null, element); mapping.SetKeyInternal(XmlMapping.GenerateKey(type, null, null)); return mapping; } - private void SerializePrimitive(XmlWriter xmlWriter, object o, XmlSerializerNamespaces namespaces) + private void SerializePrimitive(XmlWriter xmlWriter, object? o, XmlSerializerNamespaces? namespaces) { XmlSerializationPrimitiveWriter writer = new XmlSerializationPrimitiveWriter(); writer.Init(xmlWriter, namespaces, null, null, null); - switch (_primitiveType.GetTypeCode()) + switch (_primitiveType!.GetTypeCode()) { case TypeCode.String: writer.Write_string(o); @@ -858,18 +859,18 @@ private void SerializePrimitive(XmlWriter xmlWriter, object o, XmlSerializerName } else { - throw new InvalidOperationException(SR.Format(SR.XmlUnxpectedType, _primitiveType.FullName)); + throw new InvalidOperationException(SR.Format(SR.XmlUnxpectedType, _primitiveType!.FullName)); } break; } } - private object DeserializePrimitive(XmlReader xmlReader, XmlDeserializationEvents events) + private object? DeserializePrimitive(XmlReader xmlReader, XmlDeserializationEvents events) { XmlSerializationPrimitiveReader reader = new XmlSerializationPrimitiveReader(); reader.Init(xmlReader, events, null, null); - object o; - switch (_primitiveType.GetTypeCode()) + object? o; + switch (_primitiveType!.GetTypeCode()) { case TypeCode.String: o = reader.Read_string(); @@ -936,7 +937,7 @@ private object DeserializePrimitive(XmlReader xmlReader, XmlDeserializationEvent } else { - throw new InvalidOperationException(SR.Format(SR.XmlUnxpectedType, _primitiveType.FullName)); + throw new InvalidOperationException(SR.Format(SR.XmlUnxpectedType, _primitiveType!.FullName)); } break; } @@ -951,9 +952,9 @@ public XmlSerializerMappingKey(XmlMapping mapping) this.Mapping = mapping; } - public override bool Equals(object obj) + public override bool Equals(object? obj) { - XmlSerializerMappingKey other = obj as XmlSerializerMappingKey; + XmlSerializerMappingKey? other = obj as XmlSerializerMappingKey; if (other == null) return false; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerAssemblyAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerAssemblyAttribute.cs index e194dbfd5fd3ec..77490dfff29484 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerAssemblyAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerAssemblyAttribute.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; @@ -8,26 +9,26 @@ namespace System.Xml.Serialization [AttributeUsage(AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Struct, AllowMultiple = false)] public sealed class XmlSerializerAssemblyAttribute : System.Attribute { - private string _assemblyName; - private string _codeBase; + private string? _assemblyName; + private string? _codeBase; public XmlSerializerAssemblyAttribute() : this(null, null) { } - public XmlSerializerAssemblyAttribute(string assemblyName) : this(assemblyName, null) { } + public XmlSerializerAssemblyAttribute(string? assemblyName) : this(assemblyName, null) { } - public XmlSerializerAssemblyAttribute(string assemblyName, string codeBase) + public XmlSerializerAssemblyAttribute(string? assemblyName, string? codeBase) { _assemblyName = assemblyName; _codeBase = codeBase; } - public string CodeBase + public string? CodeBase { get { return _codeBase; } set { _codeBase = value; } } - public string AssemblyName + public string? AssemblyName { get { return _assemblyName; } set { _assemblyName = value; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerFactory.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerFactory.cs index 76eae175d35a1d..35cf451e09cae6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerFactory.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerFactory.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System.Reflection; @@ -17,22 +18,22 @@ namespace System.Xml.Serialization public class XmlSerializerFactory { - public XmlSerializer CreateSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace) + public XmlSerializer CreateSerializer(Type type, XmlAttributeOverrides? overrides, Type[]? extraTypes, XmlRootAttribute? root, string? defaultNamespace) { return CreateSerializer(type, overrides, extraTypes, root, defaultNamespace, null); } - public XmlSerializer CreateSerializer(Type type, XmlRootAttribute root) + public XmlSerializer CreateSerializer(Type type, XmlRootAttribute? root) { return CreateSerializer(type, null, Array.Empty(), root, null, null); } - public XmlSerializer CreateSerializer(Type type, Type[] extraTypes) + public XmlSerializer CreateSerializer(Type type, Type[]? extraTypes) { return CreateSerializer(type, null, extraTypes, null, null, null); } - public XmlSerializer CreateSerializer(Type type, XmlAttributeOverrides overrides) + public XmlSerializer CreateSerializer(Type type, XmlAttributeOverrides? overrides) { return CreateSerializer(type, overrides, Array.Empty(), null, null, null); } @@ -44,15 +45,15 @@ public XmlSerializer CreateSerializer(XmlTypeMapping xmlTypeMapping) public XmlSerializer CreateSerializer(Type type) { - return CreateSerializer(type, (string)null); + return CreateSerializer(type, (string?)null); } - public XmlSerializer CreateSerializer(Type type, string defaultNamespace) + public XmlSerializer CreateSerializer(Type type, string? defaultNamespace) { return new XmlSerializer(type, defaultNamespace); } - public XmlSerializer CreateSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace, string location) + public XmlSerializer CreateSerializer(Type type, XmlAttributeOverrides? overrides, Type[]? extraTypes, XmlRootAttribute? root, string? defaultNamespace, string? location) { return new XmlSerializer(type, overrides, extraTypes, root, defaultNamespace, location); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerNamespaces.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerNamespaces.cs index bd4c75d9807b03..567018494bc5da 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerNamespaces.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerNamespaces.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System.Reflection; @@ -11,13 +12,14 @@ namespace System.Xml.Serialization using System.Collections.Generic; using System.Xml.Extensions; using System.Xml; + using System.Diagnostics.CodeAnalysis; /// /// [To be supplied.] /// public class XmlSerializerNamespaces { - private Dictionary _namespaces; + private Dictionary? _namespaces; /// /// [To be supplied.] @@ -33,7 +35,7 @@ public XmlSerializerNamespaces() /// public XmlSerializerNamespaces(XmlSerializerNamespaces namespaces) { - _namespaces = new Dictionary(namespaces.Namespaces); + _namespaces = new Dictionary(namespaces.Namespaces); } /// @@ -51,7 +53,7 @@ public XmlSerializerNamespaces(XmlQualifiedName[] namespaces) /// /// [To be supplied.] /// - public void Add(string prefix, string ns) + public void Add(string prefix, string? ns) { // parameter value check if (prefix != null && prefix.Length > 0) @@ -59,10 +61,10 @@ public void Add(string prefix, string ns) if (ns != null && ns.Length > 0) ExtensionMethods.ToUri(ns); - AddInternal(prefix, ns); + AddInternal(prefix!, ns); } - internal void AddInternal(string prefix, string ns) + internal void AddInternal(string prefix, string? ns) { Namespaces[prefix] = ns; } @@ -85,7 +87,7 @@ public int Count get { return Namespaces.Count; } } - internal ArrayList NamespaceList + internal ArrayList? NamespaceList { get { @@ -94,24 +96,25 @@ internal ArrayList NamespaceList ArrayList namespaceList = new ArrayList(); foreach (string key in Namespaces.Keys) { - namespaceList.Add(new XmlQualifiedName(key, (string)Namespaces[key])); + namespaceList.Add(new XmlQualifiedName(key, (string?)Namespaces[key])); } return namespaceList; } } - internal Dictionary Namespaces + [AllowNull] + internal Dictionary Namespaces { get { if (_namespaces == null) - _namespaces = new Dictionary(); + _namespaces = new Dictionary(); return _namespaces; } set { _namespaces = value; } } - internal string LookupPrefix(string ns) + internal string? LookupPrefix(string? ns) { if (string.IsNullOrEmpty(ns)) return null; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerVersionAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerVersionAttribute.cs index 747559aa9d3735..5a7c6716930342 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerVersionAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializerVersionAttribute.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; @@ -8,40 +9,40 @@ namespace System.Xml.Serialization [AttributeUsage(AttributeTargets.Assembly)] public sealed class XmlSerializerVersionAttribute : System.Attribute { - private string _mvid; - private string _serializerVersion; - private string _ns; - private Type _type; + private string? _mvid; + private string? _serializerVersion; + private string? _ns; + private Type? _type; public XmlSerializerVersionAttribute() { } - public XmlSerializerVersionAttribute(Type type) + public XmlSerializerVersionAttribute(Type? type) { _type = type; } - public string ParentAssemblyId + public string? ParentAssemblyId { get { return _mvid; } set { _mvid = value; } } - public string Version + public string? Version { get { return _serializerVersion; } set { _serializerVersion = value; } } - public string Namespace + public string? Namespace { get { return _ns; } set { _ns = value; } } - public Type Type + public Type? Type { get { return _type; } set { _type = value; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlTextAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlTextAttribute.cs index 32a117a7d1ff7d..aad49a49b260e9 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlTextAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlTextAttribute.cs @@ -1,8 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; - +using System.Diagnostics.CodeAnalysis; namespace System.Xml.Serialization { @@ -12,8 +13,8 @@ namespace System.Xml.Serialization [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue)] public class XmlTextAttribute : System.Attribute { - private Type _type; - private string _dataType; + private Type? _type; + private string? _dataType; /// /// [To be supplied.] @@ -25,7 +26,7 @@ public XmlTextAttribute() /// /// [To be supplied.] /// - public XmlTextAttribute(Type type) + public XmlTextAttribute(Type? type) { _type = type; } @@ -33,7 +34,7 @@ public XmlTextAttribute(Type type) /// /// [To be supplied.] /// - public Type Type + public Type? Type { get { return _type; } set { _type = value; } @@ -42,6 +43,7 @@ public Type Type /// /// [To be supplied.] /// + [AllowNull] public string DataType { get { return _dataType == null ? string.Empty : _dataType; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlTypeAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlTypeAttribute.cs index 880615dfdeab79..3fd98ce8cc8af4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlTypeAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlTypeAttribute.cs @@ -1,8 +1,9 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System; - +using System.Diagnostics.CodeAnalysis; namespace System.Xml.Serialization { @@ -14,8 +15,8 @@ public class XmlTypeAttribute : System.Attribute { private bool _includeInSchema = true; private bool _anonymousType; - private string _ns; - private string _typeName; + private string? _ns; + private string? _typeName; /// /// [To be supplied.] @@ -53,6 +54,7 @@ public bool IncludeInSchema /// /// [To be supplied.] /// + [AllowNull] public string TypeName { get { return _typeName == null ? string.Empty : _typeName; } @@ -62,7 +64,7 @@ public string TypeName /// /// [To be supplied.] /// - public string Namespace + public string? Namespace { get { return _ns; } set { _ns = value; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlTypeMapping.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlTypeMapping.cs index 4d96050a8a5c74..fbc74d40862979 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlTypeMapping.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlTypeMapping.cs @@ -1,10 +1,10 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable using System.Reflection; using System; - namespace System.Xml.Serialization { /// @@ -12,11 +12,11 @@ namespace System.Xml.Serialization /// public class XmlTypeMapping : XmlMapping { - internal XmlTypeMapping(TypeScope scope, ElementAccessor accessor) : base(scope, accessor) + internal XmlTypeMapping(TypeScope? scope, ElementAccessor accessor) : base(scope, accessor) { } - internal TypeMapping Mapping + internal TypeMapping? Mapping { get { return Accessor.Mapping; } } @@ -28,7 +28,7 @@ public string TypeName { get { - return Mapping.TypeDesc.Name; + return Mapping!.TypeDesc!.Name; } } @@ -39,29 +39,29 @@ public string TypeFullName { get { - return Mapping.TypeDesc.FullName; + return Mapping!.TypeDesc!.FullName; } } /// /// [To be supplied.] /// - public string XsdTypeName + public string? XsdTypeName { get { - return Mapping.TypeName; + return Mapping!.TypeName; } } /// /// [To be supplied.] /// - public string XsdTypeNamespace + public string? XsdTypeNamespace { get { - return Mapping.Namespace; + return Mapping!.Namespace; } } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Xmlcustomformatter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Xmlcustomformatter.cs index 2450890af55692..e8195d91d98689 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Xmlcustomformatter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Xmlcustomformatter.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System; @@ -33,7 +34,9 @@ private static DateTimeSerializationSection.DateTimeSerializationMode Mode } } private XmlCustomFormatter() { } - internal static string FromDefaultValue(object value, string formatter) + + [return: NotNullIfNotNull("value")] + internal static string? FromDefaultValue(object? value, string formatter) { if (value == null) return null; Type type = value.GetType(); @@ -124,7 +127,8 @@ internal static string FromXmlNmToken(string nmToken) return XmlConvert.EncodeNmToken(nmToken); } - internal static string FromXmlNmTokens(string nmTokens) + [return: NotNullIfNotNull("nmTokens")] + internal static string? FromXmlNmTokens(string? nmTokens) { if (nmTokens == null) return null; @@ -152,7 +156,8 @@ internal static void WriteArrayBase64(XmlWriter writer, byte[] inData, int start writer.WriteBase64(inData, start, count); } - internal static string FromByteArrayHex(byte[] value) + [return: NotNullIfNotNull("value")] + internal static string? FromByteArrayHex(byte[]? value) { if (value == null) return null; @@ -162,7 +167,7 @@ internal static string FromByteArrayHex(byte[] value) return XmlConvert.ToBinHexString(value); } - internal static string FromEnum(long val, string[] vals, long[] ids, string typeName) + internal static string FromEnum(long val, string[] vals, long[] ids, string? typeName) { #if DEBUG // use exception in the place of Debug.Assert to avoid throwing asserts from a server process such as aspnet_ewp.exe @@ -413,7 +418,8 @@ internal static string ToXmlNmTokens(string value) return XmlConvert.DecodeName(CollapseWhitespace(value)); } - internal static byte[] ToByteArrayBase64(string value) + [return: NotNullIfNotNull("value")] + internal static byte[]? ToByteArrayBase64(string? value) { if (value == null) return null; value = value.Trim(); @@ -421,20 +427,22 @@ internal static byte[] ToByteArrayBase64(string value) return Array.Empty(); return Convert.FromBase64String(value); } - internal static byte[] ToByteArrayHex(string value) + + [return: NotNullIfNotNull("value")] + internal static byte[]? ToByteArrayHex(string? value) { if (value == null) return null; value = value.Trim(); return XmlConvert.FromBinHexString(value); } - internal static long ToEnum(string val, Hashtable vals, string typeName, bool validate) + internal static long ToEnum(string val, Hashtable vals, string? typeName, bool validate) { long value = 0; string[] parts = val.Split(null); for (int i = 0; i < parts.Length; i++) { - object id = vals[parts[i]]; + object? id = vals[parts[i]]; if (id != null) value |= (long)id; else if (validate && parts[i].Length > 0) @@ -443,7 +451,8 @@ internal static long ToEnum(string val, Hashtable vals, string typeName, bool va return value; } - private static string CollapseWhitespace(string value) + [return: NotNullIfNotNull("value")] + private static string? CollapseWhitespace(string? value) { if (value == null) return null; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/_Events.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/_Events.cs index 0dbffd395f16f4..2ec21b84552ebb 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/_Events.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/_Events.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System.IO; @@ -9,18 +10,18 @@ namespace System.Xml.Serialization using System.ComponentModel; using System.Xml; - public delegate void XmlAttributeEventHandler(object sender, XmlAttributeEventArgs e); + public delegate void XmlAttributeEventHandler(object? sender, XmlAttributeEventArgs e); public class XmlAttributeEventArgs : EventArgs { - private readonly object _o; + private readonly object? _o; private readonly XmlAttribute _attr; - private readonly string _qnames; + private readonly string? _qnames; private readonly int _lineNumber; private readonly int _linePosition; - internal XmlAttributeEventArgs(XmlAttribute attr, int lineNumber, int linePosition, object o, string qnames) + internal XmlAttributeEventArgs(XmlAttribute attr, int lineNumber, int linePosition, object? o, string? qnames) { _attr = attr; _o = o; @@ -29,7 +30,7 @@ internal XmlAttributeEventArgs(XmlAttribute attr, int lineNumber, int linePositi _linePosition = linePosition; } - public object ObjectBeingDeserialized + public object? ObjectBeingDeserialized { get { return _o; } } @@ -64,17 +65,17 @@ public string ExpectedAttributes } } - public delegate void XmlElementEventHandler(object sender, XmlElementEventArgs e); + public delegate void XmlElementEventHandler(object? sender, XmlElementEventArgs e); public class XmlElementEventArgs : EventArgs { - private readonly object _o; + private readonly object? _o; private readonly XmlElement _elem; - private readonly string _qnames; + private readonly string? _qnames; private readonly int _lineNumber; private readonly int _linePosition; - internal XmlElementEventArgs(XmlElement elem, int lineNumber, int linePosition, object o, string qnames) + internal XmlElementEventArgs(XmlElement elem, int lineNumber, int linePosition, object? o, string? qnames) { _elem = elem; _o = o; @@ -83,7 +84,7 @@ internal XmlElementEventArgs(XmlElement elem, int lineNumber, int linePosition, _linePosition = linePosition; } - public object ObjectBeingDeserialized + public object? ObjectBeingDeserialized { get { return _o; } } @@ -112,18 +113,18 @@ public string ExpectedElements } } - public delegate void XmlNodeEventHandler(object sender, XmlNodeEventArgs e); + public delegate void XmlNodeEventHandler(object? sender, XmlNodeEventArgs e); public class XmlNodeEventArgs : EventArgs { - private readonly object _o; + private readonly object? _o; private readonly XmlNode _xmlNode; private readonly int _lineNumber; private readonly int _linePosition; - internal XmlNodeEventArgs(XmlNode xmlNode, int lineNumber, int linePosition, object o) + internal XmlNodeEventArgs(XmlNode xmlNode, int lineNumber, int linePosition, object? o) { _o = o; _xmlNode = xmlNode; @@ -131,7 +132,7 @@ internal XmlNodeEventArgs(XmlNode xmlNode, int lineNumber, int linePosition, obj _linePosition = linePosition; } - public object ObjectBeingDeserialized + public object? ObjectBeingDeserialized { get { return _o; } } @@ -156,7 +157,7 @@ public string NamespaceURI get { return _xmlNode.NamespaceURI; } } - public string Text + public string? Text { get { return _xmlNode.Value; } } @@ -178,25 +179,25 @@ public int LinePosition } } - public delegate void UnreferencedObjectEventHandler(object sender, UnreferencedObjectEventArgs e); + public delegate void UnreferencedObjectEventHandler(object? sender, UnreferencedObjectEventArgs e); public class UnreferencedObjectEventArgs : EventArgs { - private readonly object _o; - private readonly string _id; + private readonly object? _o; + private readonly string? _id; - public UnreferencedObjectEventArgs(object o, string id) + public UnreferencedObjectEventArgs(object? o, string? id) { _o = o; _id = id; } - public object UnreferencedObject + public object? UnreferencedObject { get { return _o; } } - public string UnreferencedId + public string? UnreferencedId { get { return _id; } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/indentedWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/indentedWriter.cs index 1711118e8bd543..c45f0b74e3d257 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/indentedWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/indentedWriter.cs @@ -1,6 +1,7 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +#nullable enable namespace System.Xml.Serialization { using System.IO; @@ -33,7 +34,7 @@ internal int Indent } } - internal void Write(string s) + internal void Write(string? s) { if (_needIndent) WriteIndent(); _writer.Write(s); @@ -45,7 +46,7 @@ internal void Write(char c) _writer.Write(c); } - internal void WriteLine(string s) + internal void WriteLine(string? s) { if (_needIndent) WriteIndent(); _writer.WriteLine(s); From 2359abc015ec24974a4a1d8a182003d27f099d54 Mon Sep 17 00:00:00 2001 From: Krzysztof Wicher Date: Mon, 24 Aug 2020 20:36:11 +0200 Subject: [PATCH 2/5] Fix build errors on Release (ifdef-ed code) --- .../System/Xml/Serialization/XmlSchemaExporter.cs | 2 +- .../Xml/Serialization/XmlSerializationReaderILGen.cs | 12 ++++++------ .../Xml/Serialization/XmlSerializationWriter.cs | 4 ++-- .../Xml/Serialization/XmlSerializationWriterILGen.cs | 12 ++++++------ 4 files changed, 15 insertions(+), 15 deletions(-) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaExporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaExporter.cs index 96420be17f9f96..5fc9a6f451b035 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaExporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaExporter.cs @@ -939,7 +939,7 @@ private void ExportElementAccessor(XmlSchemaGroupBase group, ElementAccessor acc return (string)value; Type formatter = typeof(XmlConvert); - System.Reflection.MethodInfo? format = formatter.GetMethod("ToString", new Type[] { pm.TypeDesc.Type }); + System.Reflection.MethodInfo? format = formatter.GetMethod("ToString", new Type[] { pm.TypeDesc.Type! }); if (format != null) return (string)format.Invoke(formatter, new object[] { value })!; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs index 833f2cf86579b9..872dcbfc47570d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReaderILGen.cs @@ -1162,7 +1162,7 @@ private void WriteDerivedTypes(StructMapping mapping, bool isTypedReturn, string argTypes.Add(typeof(bool)); MethodBuilder methodBuilder = EnsureMethodBuilder(typeBuilder, - methodName, + methodName!, CodeGenerator.PrivateMethodAttributes, derived.TypeDesc.Type, argTypes.ToArray() @@ -1208,7 +1208,7 @@ private void WriteEnumAndArrayTypes() #endif LocalBuilder eLoc = ilg.DeclareOrGetLocal(typeof(object), "e"); MethodBuilder methodBuilder = EnsureMethodBuilder(typeBuilder, - methodName, + methodName!, CodeGenerator.PrivateMethodAttributes, mapping.TypeDesc!.Type, new Type[] { typeof(string) } @@ -2999,7 +2999,7 @@ private void WriteElement(string source, string? arrayName, string? choiceSource ilg.Ldarg(0); ilg.Ldc(true); MethodBuilder methodBuilder = EnsureMethodBuilder(typeBuilder, - methodName, + methodName!, CodeGenerator.PrivateMethodAttributes, // See WriteNullableMethod for different return type logic element.Mapping.TypeDesc!.Type, @@ -3180,7 +3180,7 @@ private void WriteElement(string source, string? arrayName, string? choiceSource ilg.Ldc(true); argTypes.Add(typeof(bool)); MethodBuilder methodBuilder = EnsureMethodBuilder(typeBuilder, - methodName, + methodName!, CodeGenerator.PrivateMethodAttributes, mapping.TypeDesc.Type, argTypes.ToArray() @@ -3279,10 +3279,10 @@ private void WriteElement(string source, string? arrayName, string? choiceSource if (choiceSource == null) throw new InvalidOperationException(SR.Format(SR.XmlInternalErrorDetails, "need parent for the " + source)); #endif - WriteSourceBegin(choiceSource); + WriteSourceBegin(choiceSource!); CodeIdentifier.CheckValidIdentifier(choice.MemberIds![elementIndex]); RaCodeGen.ILGenForEnumMember(ilg, choice.Mapping!.TypeDesc!.Type!, choice.MemberIds[elementIndex]); - WriteSourceEnd(choiceSource, choice.Mapping.TypeDesc.Type!); + WriteSourceEnd(choiceSource!, choice.Mapping.TypeDesc.Type!); } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs index bdc840141edd83..33f69ded431486 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs @@ -2405,7 +2405,7 @@ private void WritePrimitive(string method, string name, string? ns, object? defa if (((EnumMapping)mapping).IsFlags) { Writer.Write("("); - string[] values = ((string)defaultValue).Split(null); + string[] values = ((string)defaultValue!).Split(null); for (int i = 0; i < values.Length; i++) { if (values[i] == null || values[i].Length == 0) @@ -2418,7 +2418,7 @@ private void WritePrimitive(string method, string name, string? ns, object? defa } else { - Writer.Write(RaCodeGen.GetStringForEnumCompare((EnumMapping)mapping, (string)defaultValue, mapping.TypeDesc.UseReflection)); + Writer.Write(RaCodeGen.GetStringForEnumCompare((EnumMapping)mapping, (string)defaultValue!, mapping.TypeDesc.UseReflection)); } Writer.Write(")"); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriterILGen.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriterILGen.cs index ea5c9a376981ec..e907ffc6471e24 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriterILGen.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriterILGen.cs @@ -134,7 +134,7 @@ private void WriteEnumValue(EnumMapping mapping, SourceInfo source, out Type ret // For enum, its write method (eg. Write1_Gender) could be called multiple times // prior to its declaration. MethodBuilder methodBuilder = EnsureMethodBuilder(typeBuilder, - methodName, + methodName!, CodeGenerator.PrivateMethodAttributes, typeof(string), new Type[] { mapping.TypeDesc!.Type! }); @@ -209,7 +209,7 @@ private void WritePrimitive(string method, string name, string? ns, object? defa string? enumDefaultValue = null; if (((EnumMapping)mapping).IsFlags) { - string[] values = ((string)defaultValue).Split(null); + string[] values = ((string)defaultValue!).Split(null); for (int i = 0; i < values.Length; i++) { if (values[i] == null || values[i].Length == 0) @@ -221,7 +221,7 @@ private void WritePrimitive(string method, string name, string? ns, object? defa } else { - enumDefaultValue = (string)defaultValue; + enumDefaultValue = (string)defaultValue!; } ilg.Ldc(Enum.Parse(mapping.TypeDesc.Type!, enumDefaultValue!, false)); ilg.If(Cmp.NotEqualTo); // " != " @@ -767,7 +767,7 @@ private void WriteDerivedTypes(StructMapping mapping) argTypes.Add(typeof(bool)); ilg.Ldc(true); MethodInfo methodBuilder = EnsureMethodBuilder(typeBuilder, - methodName, + methodName!, CodeGenerator.PrivateMethodAttributes, typeof(void), argTypes.ToArray()); @@ -823,7 +823,7 @@ private void WriteEnumAndArrayTypes() ilg.Ldstr(GetCSharpString(mapping.Namespace)); ilg.Call(XmlSerializationWriter_WriteXsiType); MethodBuilder methodBuilder = EnsureMethodBuilder(typeBuilder, - methodName, + methodName!, CodeGenerator.PrivateMethodAttributes, typeof(string), new Type[] { mapping.TypeDesc.Type! } @@ -2010,7 +2010,7 @@ private void WriteElement(SourceInfo source, ElementAccessor element, string arr ilg.Ldc(false); argTypes.Add(typeof(bool)); MethodBuilder methodBuilder = EnsureMethodBuilder(typeBuilder, - methodName, + methodName!, CodeGenerator.PrivateMethodAttributes, typeof(void), argTypes.ToArray()); From ca7e8886321ecf2715be375f7ac9b227580fcb80 Mon Sep 17 00:00:00 2001 From: Krzysztof Wicher Date: Tue, 25 Aug 2020 07:02:24 +0200 Subject: [PATCH 3/5] fix incidental product bug --- .../Xml/Serialization/ReflectionXmlSerializationWriter.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs index 9edc0cff47ef4c..bef118ae1823d3 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs @@ -202,7 +202,7 @@ private void WriteElements(object? o, object? enumSource, ElementAccessor[] elem int anyCount = 0; var namedAnys = new List(); ElementAccessor? unnamedAny = null; // can only have one - string? enumTypeName = choice?.Mapping!.TypeDesc!.FullName; + string? enumTypeName = (choice != null) ? choice.Mapping!.TypeDesc!.FullName : null; for (int i = 0; i < elements.Length; i++) { @@ -250,7 +250,7 @@ private void WriteElements(object? o, object? enumSource, ElementAccessor[] elem if (choice != null) { - throw CreateChoiceIdentifierValueException(choice.Mapping.TypeDesc!.FullName, choice.MemberName!, elem.Name, elem.NamespaceURI); + throw CreateChoiceIdentifierValueException(choice.Mapping!.TypeDesc!.FullName, choice.MemberName!, elem.Name, elem.NamespaceURI); } if (unnamedAny != null) From 5663496b35e542fb4bc3a866536e7b09cf5587d6 Mon Sep 17 00:00:00 2001 From: Krzysztof Wicher Date: Wed, 26 Aug 2020 15:43:34 +0200 Subject: [PATCH 4/5] address PR feedback --- .../src/System/Xml/Schema/XmlSchema.cs | 2 +- .../src/System/Xml/Schema/XmlSchemaElement.cs | 3 ++ .../Xml/Serialization/CodeIdentifiers.cs | 4 +- .../ReflectionXmlSerializationReader.cs | 4 +- .../ReflectionXmlSerializationWriter.cs | 6 +-- .../Serialization/SoapAttributeOverrides.cs | 4 +- .../Serialization/SoapReflectionImporter.cs | 14 +++--- .../Xml/Serialization/SoapSchemamember.cs | 4 +- .../Xml/Serialization/SoapTypeAttribute.cs | 4 +- .../Serialization/XmlAnyElementAttribute.cs | 4 +- .../Serialization/XmlArrayItemAttribute.cs | 6 +-- .../Serialization/XmlAttributeAttribute.cs | 6 +-- .../Serialization/XmlAttributeOverrides.cs | 10 ++-- .../XmlChoiceIdentifierAttribute.cs | 2 +- .../Serialization/XmlReflectionImporter.cs | 16 +++--- .../Xml/Serialization/XmlSchemaExporter.cs | 2 +- .../Xml/Serialization/XmlSchemaImporter.cs | 6 +-- .../System/Xml/Serialization/XmlSchemas.cs | 4 +- .../XmlSerializationGeneratedCode.cs | 2 +- .../Serialization/XmlSerializationReader.cs | 49 ++++++++++--------- .../Serialization/XmlSerializationWriter.cs | 34 +++++++------ .../System/Xml/Serialization/XmlSerializer.cs | 34 ++++++------- .../Xml/Serialization/XmlTypeAttribute.cs | 2 +- .../Xml/Serialization/Xmlcustomformatter.cs | 21 +++++--- 24 files changed, 131 insertions(+), 112 deletions(-) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchema.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchema.cs index ccc9d028e3536c..5cb23353c26be7 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchema.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchema.cs @@ -174,7 +174,7 @@ public void Compile(ValidationEventHandler? validationEventHandler) } [Obsolete("Use System.Xml.Schema.XmlSchemaSet for schema compilation and validation. https://go.microsoft.com/fwlink/?linkid=14202")] - public void Compile(ValidationEventHandler? validationEventHandler, XmlResolver resolver) + public void Compile(ValidationEventHandler? validationEventHandler, XmlResolver? resolver) { SchemaInfo sInfo = new SchemaInfo(); sInfo.SchemaType = SchemaType.XSD; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaElement.cs b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaElement.cs index 7ea0845bf01b9f..58c68160b5584e 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaElement.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Schema/XmlSchemaElement.cs @@ -112,6 +112,7 @@ internal bool HasAbstractAttribute } [XmlAttribute("ref")] + [AllowNull] public XmlQualifiedName RefName { get { return _refName; } @@ -119,6 +120,7 @@ public XmlQualifiedName RefName } [XmlAttribute("substitutionGroup")] + [AllowNull] public XmlQualifiedName SubstitutionGroup { get { return _substitutionGroup; } @@ -126,6 +128,7 @@ public XmlQualifiedName SubstitutionGroup } [XmlAttribute("type")] + [AllowNull] public XmlQualifiedName SchemaTypeName { get { return _typeName; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeIdentifiers.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeIdentifiers.cs index a19b6774398882..66f28c88e857b3 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeIdentifiers.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/CodeIdentifiers.cs @@ -132,7 +132,7 @@ public void RemoveReserved(string identifier) /// /// [To be supplied.] /// - public string AddUnique(string identifier, object value) + public string AddUnique(string identifier, object? value) { identifier = MakeUnique(identifier); Add(identifier, value); @@ -150,7 +150,7 @@ public bool IsInUse(string identifier) /// /// [To be supplied.] /// - public void Add(string identifier, object value) + public void Add(string identifier, object? value) { _identifiers.Add(identifier, value); _list.Add(value); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationReader.cs index 908ea01deb8ae4..e39e7bf796d6e6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationReader.cs @@ -1327,7 +1327,7 @@ private Hashtable WriteHashtable(EnumMapping mapping, string name) if (structMapping.TypeDesc.IsAbstract) { - throw CreateAbstractTypeException(structMapping.TypeName, structMapping.Namespace); + throw CreateAbstractTypeException(structMapping.TypeName!, structMapping.Namespace); } else { @@ -1553,7 +1553,7 @@ private XmlSerializationCollectionFixupCallback GetCreateCollectionOfObjectsCall } else if (structMapping.TypeDesc.IsAbstract) { - throw CreateAbstractTypeException(structMapping.TypeName, structMapping.Namespace); + throw CreateAbstractTypeException(structMapping.TypeName!, structMapping.Namespace); } else { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs index bef118ae1823d3..5258ec2c1cc615 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/ReflectionXmlSerializationWriter.cs @@ -60,7 +60,7 @@ protected override void InitCallbacks() } } - public void WriteObject(object o) + public void WriteObject(object? o) { XmlMapping xmlMapping = _mapping; if (xmlMapping is XmlTypeMapping xmlTypeMapping) @@ -69,11 +69,11 @@ public void WriteObject(object o) } else if (xmlMapping is XmlMembersMapping xmlMembersMapping) { - GenerateMembersElement(o, xmlMembersMapping); + GenerateMembersElement(o!, xmlMembersMapping); } } - private void WriteObjectOfTypeElement(object o, XmlTypeMapping mapping) + private void WriteObjectOfTypeElement(object? o, XmlTypeMapping mapping) { GenerateTypeElement(o, mapping); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapAttributeOverrides.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapAttributeOverrides.cs index cc2538ebedf319..f9fb5d7de763f4 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapAttributeOverrides.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapAttributeOverrides.cs @@ -15,12 +15,12 @@ public class SoapAttributeOverrides { private readonly Hashtable _types = new Hashtable(); - public void Add(Type type, SoapAttributes attributes) + public void Add(Type type, SoapAttributes? attributes) { Add(type, string.Empty, attributes); } - public void Add(Type type, string member, SoapAttributes attributes) + public void Add(Type type, string member, SoapAttributes? attributes) { Hashtable? members = (Hashtable?)_types[type]; if (members == null) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapReflectionImporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapReflectionImporter.cs index 4963f64508a799..bc1ef880ff13ef 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapReflectionImporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapReflectionImporter.cs @@ -92,22 +92,22 @@ public XmlTypeMapping ImportTypeMapping(Type type, string? defaultNamespace) return xmlMapping; } - public XmlMembersMapping ImportMembersMapping(string elementName, string ns, XmlReflectionMember[] members) + public XmlMembersMapping ImportMembersMapping(string? elementName, string? ns, XmlReflectionMember[] members) { return ImportMembersMapping(elementName, ns, members, true, true, false); } - public XmlMembersMapping ImportMembersMapping(string elementName, string ns, XmlReflectionMember[] members, bool hasWrapperElement, bool writeAccessors) + public XmlMembersMapping ImportMembersMapping(string? elementName, string? ns, XmlReflectionMember[] members, bool hasWrapperElement, bool writeAccessors) { return ImportMembersMapping(elementName, ns, members, hasWrapperElement, writeAccessors, false); } - public XmlMembersMapping ImportMembersMapping(string elementName, string ns, XmlReflectionMember[] members, bool hasWrapperElement, bool writeAccessors, bool validate) + public XmlMembersMapping ImportMembersMapping(string? elementName, string? ns, XmlReflectionMember[] members, bool hasWrapperElement, bool writeAccessors, bool validate) { return ImportMembersMapping(elementName, ns, members, hasWrapperElement, writeAccessors, validate, XmlMappingAccess.Read | XmlMappingAccess.Write); } - public XmlMembersMapping ImportMembersMapping(string elementName, string ns, XmlReflectionMember[] members, bool hasWrapperElement, bool writeAccessors, bool validate, XmlMappingAccess access) + public XmlMembersMapping ImportMembersMapping(string? elementName, string? ns, XmlReflectionMember[] members, bool hasWrapperElement, bool writeAccessors, bool validate, XmlMappingAccess access) { ElementAccessor element = new ElementAccessor(); element.IsSoap = true; @@ -230,7 +230,7 @@ private StructMapping GetRootMapping() return _root; } - private TypeMapping? GetTypeMapping(string typeName, string ns, TypeDesc typeDesc) + private TypeMapping? GetTypeMapping(string typeName, string? ns, TypeDesc typeDesc) { TypeMapping? mapping = (TypeMapping?)_types[typeName, ns]; if (mapping == null) return null; @@ -586,7 +586,7 @@ private EnumMapping ImportEnumMapping(EnumModel model) return constant; } - private MembersMapping ImportMembersMapping(XmlReflectionMember[] xmlReflectionMembers, string ns, bool hasWrapperElement, bool writeAccessors, bool validateWrapperElement, RecursionLimiter limiter) + private MembersMapping ImportMembersMapping(XmlReflectionMember[] xmlReflectionMembers, string? ns, bool hasWrapperElement, bool writeAccessors, bool validateWrapperElement, RecursionLimiter limiter) { MembersMapping members = new MembersMapping(); members.TypeDesc = _typeScope.GetTypeDesc(typeof(object[])); @@ -626,7 +626,7 @@ private MembersMapping ImportMembersMapping(XmlReflectionMember[] xmlReflectionM return members; } - private MemberMapping? ImportMemberMapping(XmlReflectionMember xmlReflectionMember, string ns, XmlReflectionMember[] xmlReflectionMembers, XmlSchemaForm form, RecursionLimiter limiter) + private MemberMapping? ImportMemberMapping(XmlReflectionMember xmlReflectionMember, string? ns, XmlReflectionMember[] xmlReflectionMembers, XmlSchemaForm form, RecursionLimiter limiter) { SoapAttributes a = xmlReflectionMember.SoapAttributes; if (a.SoapIgnore) return null; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapSchemamember.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapSchemamember.cs index 8eba2817bfcee9..afeb107a56ec92 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapSchemamember.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapSchemamember.cs @@ -11,9 +11,9 @@ namespace System.Xml.Serialization public class SoapSchemaMember { private string? _memberName; - private XmlQualifiedName _type = XmlQualifiedName.Empty; + private XmlQualifiedName? _type = XmlQualifiedName.Empty; - public XmlQualifiedName MemberType + public XmlQualifiedName? MemberType { get { return _type; } set { _type = value; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapTypeAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapTypeAttribute.cs index b19407178c68cd..b816a34d4db3a0 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapTypeAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/SoapTypeAttribute.cs @@ -18,12 +18,12 @@ public SoapTypeAttribute() { } - public SoapTypeAttribute(string typeName) + public SoapTypeAttribute(string? typeName) { _typeName = typeName; } - public SoapTypeAttribute(string typeName, string ns) + public SoapTypeAttribute(string? typeName, string? ns) { _typeName = typeName; _ns = ns; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAnyElementAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAnyElementAttribute.cs index 9308f5c8d4ac68..8c146c15abd881 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAnyElementAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAnyElementAttribute.cs @@ -29,7 +29,7 @@ public XmlAnyElementAttribute() /// /// [To be supplied.] /// - public XmlAnyElementAttribute(string name) + public XmlAnyElementAttribute(string? name) { _name = name; } @@ -37,7 +37,7 @@ public XmlAnyElementAttribute(string name) /// /// [To be supplied.] /// - public XmlAnyElementAttribute(string name, string ns) + public XmlAnyElementAttribute(string? name, string? ns) { _name = name; _ns = ns; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlArrayItemAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlArrayItemAttribute.cs index c1d9719c6e5746..b3bd0d98551212 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlArrayItemAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlArrayItemAttribute.cs @@ -33,7 +33,7 @@ public XmlArrayItemAttribute() /// /// [To be supplied.] /// - public XmlArrayItemAttribute(string elementName) + public XmlArrayItemAttribute(string? elementName) { _elementName = elementName; } @@ -41,7 +41,7 @@ public XmlArrayItemAttribute(string elementName) /// /// [To be supplied.] /// - public XmlArrayItemAttribute(Type type) + public XmlArrayItemAttribute(Type? type) { _type = type; } @@ -49,7 +49,7 @@ public XmlArrayItemAttribute(Type type) /// /// [To be supplied.] /// - public XmlArrayItemAttribute(string elementName, Type type) + public XmlArrayItemAttribute(string? elementName, Type? type) { _elementName = elementName; _type = type; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributeAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributeAttribute.cs index 24b8fa6a48cd82..a0b8eb7d9ad3ce 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributeAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributeAttribute.cs @@ -30,7 +30,7 @@ public XmlAttributeAttribute() /// /// [To be supplied.] /// - public XmlAttributeAttribute(string attributeName) + public XmlAttributeAttribute(string? attributeName) { _attributeName = attributeName; } @@ -38,7 +38,7 @@ public XmlAttributeAttribute(string attributeName) /// /// [To be supplied.] /// - public XmlAttributeAttribute(Type type) + public XmlAttributeAttribute(Type? type) { _type = type; } @@ -46,7 +46,7 @@ public XmlAttributeAttribute(Type type) /// /// [To be supplied.] /// - public XmlAttributeAttribute(string attributeName, Type type) + public XmlAttributeAttribute(string? attributeName, Type? type) { _attributeName = attributeName; _type = type; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributeOverrides.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributeOverrides.cs index 63af70435d88d8..115a07e0d2589b 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributeOverrides.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlAttributeOverrides.cs @@ -17,7 +17,7 @@ namespace System.Xml.Serialization /// public class XmlAttributeOverrides { - private readonly Dictionary> _types = new Dictionary>(); + private readonly Dictionary> _types = new Dictionary>(); /// /// [To be supplied.] @@ -30,12 +30,12 @@ public void Add(Type type, XmlAttributes attributes) /// /// [To be supplied.] /// - public void Add(Type type, string member, XmlAttributes attributes) + public void Add(Type type, string member, XmlAttributes? attributes) { - Dictionary? members; + Dictionary? members; if (!_types.TryGetValue(type, out members)) { - members = new Dictionary(); + members = new Dictionary(); _types.Add(type, members); } else if (members.ContainsKey(member)) @@ -63,7 +63,7 @@ public XmlAttributes? this[Type type] { get { - Dictionary? members; + Dictionary? members; XmlAttributes? attributes; return _types.TryGetValue(type, out members) && members.TryGetValue(member, out attributes) ? attributes diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlChoiceIdentifierAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlChoiceIdentifierAttribute.cs index 054f6a7c840baa..982badde112fad 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlChoiceIdentifierAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlChoiceIdentifierAttribute.cs @@ -28,7 +28,7 @@ public XmlChoiceIdentifierAttribute() /// /// [To be supplied.] /// - public XmlChoiceIdentifierAttribute(string name) + public XmlChoiceIdentifierAttribute(string? name) { _name = name; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs index 65d7e022213107..3fd048f33fab3f 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlReflectionImporter.cs @@ -141,7 +141,7 @@ public XmlTypeMapping ImportTypeMapping(Type type) /// /// [To be supplied.] /// - public XmlTypeMapping ImportTypeMapping(Type type, string defaultNamespace) + public XmlTypeMapping ImportTypeMapping(Type type, string? defaultNamespace) { return ImportTypeMapping(type, null, defaultNamespace); } @@ -149,7 +149,7 @@ public XmlTypeMapping ImportTypeMapping(Type type, string defaultNamespace) /// /// [To be supplied.] /// - public XmlTypeMapping ImportTypeMapping(Type type, XmlRootAttribute root) + public XmlTypeMapping ImportTypeMapping(Type type, XmlRootAttribute? root) { return ImportTypeMapping(type, root, null); } @@ -170,7 +170,7 @@ public XmlTypeMapping ImportTypeMapping(Type type, XmlRootAttribute? root, strin /// /// [To be supplied.] /// - public XmlMembersMapping ImportMembersMapping(string elementName, string ns, XmlReflectionMember[] members, bool hasWrapperElement) + public XmlMembersMapping ImportMembersMapping(string? elementName, string? ns, XmlReflectionMember[] members, bool hasWrapperElement) { return ImportMembersMapping(elementName, ns, members, hasWrapperElement, false); } @@ -178,7 +178,7 @@ public XmlMembersMapping ImportMembersMapping(string elementName, string ns, Xml /// /// [To be supplied.] /// - public XmlMembersMapping ImportMembersMapping(string elementName, string ns, XmlReflectionMember[] members, bool hasWrapperElement, bool rpc) + public XmlMembersMapping ImportMembersMapping(string? elementName, string? ns, XmlReflectionMember[] members, bool hasWrapperElement, bool rpc) { return ImportMembersMapping(elementName, ns, members, hasWrapperElement, rpc, false); } @@ -187,7 +187,7 @@ public XmlMembersMapping ImportMembersMapping(string elementName, string ns, Xml /// [To be supplied.] /// /// - public XmlMembersMapping ImportMembersMapping(string elementName, string ns, XmlReflectionMember[] members, bool hasWrapperElement, bool rpc, bool openModel) + public XmlMembersMapping ImportMembersMapping(string? elementName, string? ns, XmlReflectionMember[] members, bool hasWrapperElement, bool rpc, bool openModel) { return ImportMembersMapping(elementName, ns, members, hasWrapperElement, rpc, openModel, XmlMappingAccess.Read | XmlMappingAccess.Write); } @@ -196,7 +196,7 @@ public XmlMembersMapping ImportMembersMapping(string elementName, string ns, Xml /// [To be supplied.] /// /// - public XmlMembersMapping ImportMembersMapping(string elementName, string ns, XmlReflectionMember[] members, bool hasWrapperElement, bool rpc, bool openModel, XmlMappingAccess access) + public XmlMembersMapping ImportMembersMapping(string? elementName, string? ns, XmlReflectionMember[] members, bool hasWrapperElement, bool rpc, bool openModel, XmlMappingAccess access) { ElementAccessor element = new ElementAccessor(); element.Name = elementName == null || elementName.Length == 0 ? elementName : XmlConvert.EncodeLocalName(elementName); @@ -1215,7 +1215,7 @@ private EnumMapping ImportEnumMapping(EnumModel model, string? ns, bool repeats) return constant; } - private MembersMapping ImportMembersMapping(XmlReflectionMember[] xmlReflectionMembers, string ns, bool hasWrapperElement, bool rpc, bool openModel, RecursionLimiter limiter) + private MembersMapping ImportMembersMapping(XmlReflectionMember[] xmlReflectionMembers, string? ns, bool hasWrapperElement, bool rpc, bool openModel, RecursionLimiter limiter) { MembersMapping members = new MembersMapping(); members.TypeDesc = _typeScope.GetTypeDesc(typeof(object[])); @@ -1292,7 +1292,7 @@ private MembersMapping ImportMembersMapping(XmlReflectionMember[] xmlReflectionM return members; } - private MemberMapping ImportMemberMapping(XmlReflectionMember xmlReflectionMember, string ns, XmlReflectionMember[] xmlReflectionMembers, bool rpc, bool openModel, RecursionLimiter limiter) + private MemberMapping ImportMemberMapping(XmlReflectionMember xmlReflectionMember, string? ns, XmlReflectionMember[] xmlReflectionMembers, bool rpc, bool openModel, RecursionLimiter limiter) { XmlSchemaForm form = rpc ? XmlSchemaForm.Unqualified : XmlSchemaForm.Qualified; XmlAttributes a = xmlReflectionMember.XmlAttributes; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaExporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaExporter.cs index 5fc9a6f451b035..20662550ed0082 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaExporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaExporter.cs @@ -133,7 +133,7 @@ private static bool IsAnyType(XmlSchemaType schemaType, bool mixed, bool unbound return false; } - public string ExportAnyType(string ns) + public string ExportAnyType(string? ns) { string name = "any"; int i = 0; diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaImporter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaImporter.cs index 4eb6bc8ac1ea18..a4b64f5bf587cc 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaImporter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemaImporter.cs @@ -22,7 +22,7 @@ public class XmlSchemaImporter : SchemaImporter { public XmlSchemaImporter(XmlSchemas schemas) : base(schemas, CodeGenerationOptions.GenerateProperties, new ImportContext()) { } - public XmlSchemaImporter(XmlSchemas schemas, CodeIdentifiers typeIdentifiers) : base(schemas, CodeGenerationOptions.GenerateProperties, new ImportContext(typeIdentifiers, false)) { } + public XmlSchemaImporter(XmlSchemas schemas, CodeIdentifiers? typeIdentifiers) : base(schemas, CodeGenerationOptions.GenerateProperties, new ImportContext(typeIdentifiers, false)) { } public XmlTypeMapping ImportDerivedTypeMapping(XmlQualifiedName name, Type? baseType) { @@ -73,7 +73,7 @@ public XmlTypeMapping ImportSchemaType(XmlQualifiedName typeName) return ImportSchemaType(typeName, null, false); } - public XmlTypeMapping ImportSchemaType(XmlQualifiedName typeName, Type baseType) + public XmlTypeMapping ImportSchemaType(XmlQualifiedName typeName, Type? baseType) { return ImportSchemaType(typeName, baseType, false); } @@ -197,7 +197,7 @@ public XmlMembersMapping ImportMembersMapping(XmlQualifiedName[] names, Type? ba return new XmlMembersMapping(Scope, element, XmlMappingAccess.Read | XmlMappingAccess.Write); } - public XmlMembersMapping ImportMembersMapping(string name, string ns, SoapSchemaMember[] members) + public XmlMembersMapping ImportMembersMapping(string name, string? ns, SoapSchemaMember[] members) { XmlSchemaComplexType type = new XmlSchemaComplexType(); XmlSchemaSequence seq = new XmlSchemaSequence(); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemas.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemas.cs index 241c9a84bbaf67..e0e3f2cb5810a6 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemas.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSchemas.cs @@ -120,7 +120,7 @@ public int Add(XmlSchema schema) return List.Add(schema); } - public int Add(XmlSchema schema, Uri baseUri) + public int Add(XmlSchema schema, Uri? baseUri) { if (List.Contains(schema)) return List.IndexOf(schema); @@ -157,7 +157,7 @@ public bool Contains(XmlSchema schema) return List.Contains(schema); } - public bool Contains(string targetNamespace) + public bool Contains(string? targetNamespace) { return SchemaSet.Contains(targetNamespace); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationGeneratedCode.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationGeneratedCode.cs index cb4c44d1f5af5c..8cd499f58ddf77 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationGeneratedCode.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationGeneratedCode.cs @@ -360,7 +360,7 @@ private void GenerateGetSerializer(Hashtable serializers, XmlMapping[] xmlMappin _writer.Write("if (type == typeof("); _writer.Write(CodeIdentifier.GetCSharpName(type)); _writer.Write(")) return new "); - _writer.Write((string)serializers[xmlMappings[i].Key!]!); + _writer.Write((string?)serializers[xmlMappings[i].Key!]); _writer.WriteLine("();"); } } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs index 63ad40f71fce5c..828104e74a1048 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationReader.cs @@ -20,7 +20,7 @@ public abstract class XmlSerializationReader : XmlSerializationGeneratedCode { private XmlReader _r = null!; private XmlDocument? _d; - private Hashtable _callbacks = null!; + private Hashtable? _callbacks; private Hashtable _types = null!; private Hashtable _typesReverse = null!; private XmlDeserializationEvents _events; @@ -908,7 +908,8 @@ protected XmlQualifiedName ReadElementQualifiedName() return node; } - protected static byte[] ToByteArrayBase64(string value) + [return: NotNullIfNotNull("value")] + protected static byte[]? ToByteArrayBase64(string? value) { return XmlCustomFormatter.ToByteArrayBase64(value); } @@ -1115,27 +1116,31 @@ protected static long ToEnum(string value, Hashtable h, string typeName) return XmlCustomFormatter.ToEnum(value, h, typeName, true); } - protected static string ToXmlName(string value) + [return: NotNullIfNotNull("value")] + protected static string? ToXmlName(string? value) { return XmlCustomFormatter.ToXmlName(value); } - protected static string ToXmlNCName(string value) + [return: NotNullIfNotNull("value")] + protected static string? ToXmlNCName(string? value) { return XmlCustomFormatter.ToXmlNCName(value); } - protected static string ToXmlNmToken(string value) + [return: NotNullIfNotNull("value")] + protected static string? ToXmlNmToken(string? value) { return XmlCustomFormatter.ToXmlNmToken(value); } - protected static string ToXmlNmTokens(string value) + [return: NotNullIfNotNull("value")] + protected static string? ToXmlNmTokens(string? value) { return XmlCustomFormatter.ToXmlNmTokens(value); } - protected XmlQualifiedName ToXmlQualifiedName(string value) + protected XmlQualifiedName ToXmlQualifiedName(string? value) { return ToXmlQualifiedName(value, DecodeName); } @@ -1166,7 +1171,7 @@ internal XmlQualifiedName ToXmlQualifiedName(string? value, bool decodeName) return new XmlQualifiedName(_r.NameTable.Add(localName), ns); } } - protected void UnknownAttribute(object o, XmlAttribute attr) + protected void UnknownAttribute(object? o, XmlAttribute attr) { UnknownAttribute(o, attr, null); } @@ -1264,7 +1269,7 @@ private void GetCurrentPosition(out int lineNumber, out int linePosition) lineNumber = linePosition = -1; } - protected void UnreferencedObject(string? id, object o) + protected void UnreferencedObject(string? id, object? o) { if (_events.OnUnreferencedObject != null) { @@ -1290,22 +1295,22 @@ protected Exception CreateUnknownTypeException(XmlQualifiedName type) return new InvalidOperationException(SR.Format(SR.XmlUnknownType, type.Name, type.Namespace, CurrentTag())); } - protected Exception CreateReadOnlyCollectionException(string? name) + protected Exception CreateReadOnlyCollectionException(string name) { return new InvalidOperationException(SR.Format(SR.XmlReadOnlyCollection, name)); } - protected Exception CreateAbstractTypeException(string? name, string? ns) + protected Exception CreateAbstractTypeException(string name, string? ns) { return new InvalidOperationException(SR.Format(SR.XmlAbstractType, name, ns, CurrentTag())); } - protected Exception CreateInaccessibleConstructorException(string? typeName) + protected Exception CreateInaccessibleConstructorException(string typeName) { return new InvalidOperationException(SR.Format(SR.XmlConstructorInaccessible, typeName)); } - protected Exception CreateCtorHasSecurityException(string? typeName) + protected Exception CreateCtorHasSecurityException(string typeName) { return new InvalidOperationException(SR.Format(SR.XmlConstructorHasSecurityAttributes, typeName)); } @@ -1462,15 +1467,13 @@ protected void AddTarget(string? id, object? o) } } - - - protected void AddFixup(Fixup fixup) + protected void AddFixup(Fixup? fixup) { if (_fixups == null) _fixups = new ArrayList(); _fixups.Add(fixup); } - protected void AddFixup(CollectionFixup fixup) + protected void AddFixup(CollectionFixup? fixup) { if (_collectionFixups == null) _collectionFixups = new ArrayList(); _collectionFixups.Add(fixup); @@ -1537,7 +1540,7 @@ private void DoFixups() protected void FixupArrayRefs(object fixup) { - Fixup f = (Fixup)fixup!; + Fixup f = (Fixup)fixup; Array array = (Array)f.Source!; for (int i = 0; i < array.Length; i++) { @@ -1791,6 +1794,7 @@ protected void ReadReferencedElements() return ReadReferencingElement(name, ns, false, out fixupReference); } + [MemberNotNull(nameof(_callbacks))] protected object? ReadReferencingElement(string? name, string? ns, bool elementCanBeType, out string? fixupReference) { object? o = null; @@ -1828,6 +1832,7 @@ protected void ReadReferencedElements() return o; } + [MemberNotNull(nameof(_callbacks))] internal void EnsureCallbackTables() { if (_callbacks == null) @@ -1845,7 +1850,7 @@ internal void EnsureCallbackTables() protected void AddReadCallback(string name, string ns, Type type, XmlSerializationReadCallback read) { XmlQualifiedName typeName = new XmlQualifiedName(_r.NameTable.Add(name), _r.NameTable.Add(ns)); - _callbacks[typeName] = read; + _callbacks![typeName] = read; _types[typeName] = type; _typesReverse[type] = typeName; } @@ -1958,14 +1963,14 @@ protected class Fixup { private readonly XmlSerializationFixupCallback _callback; private object? _source; - private readonly string[]? _ids; + private readonly string?[]? _ids; public Fixup(object? o, XmlSerializationFixupCallback callback, int count) : this(o, callback, new string[count]) { } - public Fixup(object? o, XmlSerializationFixupCallback callback, string[]? ids) + public Fixup(object? o, XmlSerializationFixupCallback callback, string?[]? ids) { _callback = callback; this.Source = o; @@ -2024,7 +2029,7 @@ public object CollectionItems /// - public delegate void XmlSerializationCollectionFixupCallback(object? collection, object collectionItems); + public delegate void XmlSerializationCollectionFixupCallback(object? collection, object? collectionItems); /// public delegate object? XmlSerializationReadCallback(); diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs index 33f69ded431486..50a1632df0678d 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializationWriter.cs @@ -110,7 +110,8 @@ protected static byte[] FromByteArrayBase64(byte[] value) return DynamicAssemblies.Get(assemblyFullName); } - protected static string FromByteArrayHex(byte[] value) + [return: NotNullIfNotNull("value")] + protected static string? FromByteArrayHex(byte[]? value) { return XmlCustomFormatter.FromByteArrayHex(value); } @@ -145,22 +146,26 @@ protected static string FromEnum(long value, string[] values, long[] ids, string return XmlCustomFormatter.FromEnum(value, values, ids, typeName); } - protected static string FromXmlName(string name) + [return: NotNullIfNotNull("name")] + protected static string? FromXmlName(string? name) { return XmlCustomFormatter.FromXmlName(name); } - protected static string FromXmlNCName(string ncName) + [return: NotNullIfNotNull("ncName")] + protected static string? FromXmlNCName(string? ncName) { return XmlCustomFormatter.FromXmlNCName(ncName); } - protected static string FromXmlNmToken(string nmToken) + [return: NotNullIfNotNull("nmToken")] + protected static string? FromXmlNmToken(string? nmToken) { return XmlCustomFormatter.FromXmlNmToken(nmToken); } - protected static string FromXmlNmTokens(string nmTokens) + [return: NotNullIfNotNull("nmTokens")] + protected static string? FromXmlNmTokens(string? nmTokens) { return XmlCustomFormatter.FromXmlNmTokens(nmTokens); } @@ -415,7 +420,6 @@ private string GetQualifiedName(string name, string? ns) return FromXmlQualifiedName(xmlQualifiedName, true); } - [return: NotNullIfNotNull("xmlQualifiedName")] protected string? FromXmlQualifiedName(XmlQualifiedName? xmlQualifiedName, bool ignoreEmpty) { if (xmlQualifiedName == null) return null; @@ -560,7 +564,7 @@ protected void WriteStartElement(string name, string? ns, object? o, bool writeP return null; } - protected void WriteNullTagEncoded(string name) + protected void WriteNullTagEncoded(string? name) { WriteNullTagEncoded(name, null); } @@ -574,7 +578,7 @@ protected void WriteNullTagEncoded(string? name, string? ns) _w.WriteEndElement(); } - protected void WriteNullTagLiteral(string name) + protected void WriteNullTagLiteral(string? name) { WriteNullTagLiteral(name, null); } @@ -716,7 +720,7 @@ protected void WriteNullableQualifiedNameLiteral(string name, string? ns, XmlQua } - protected void WriteElementEncoded(XmlNode node, string name, string? ns, bool isNullable, bool any) + protected void WriteElementEncoded(XmlNode? node, string name, string? ns, bool isNullable, bool any) { if (node == null) { @@ -726,7 +730,7 @@ protected void WriteElementEncoded(XmlNode node, string name, string? ns, bool i WriteElement(node, name, ns, isNullable, any); } - protected void WriteElementLiteral(XmlNode node, string name, string? ns, bool isNullable, bool any) + protected void WriteElementLiteral(XmlNode? node, string name, string? ns, bool isNullable, bool any) { if (node == null) { @@ -817,7 +821,7 @@ protected Exception CreateInvalidAnyTypeException(Type type) return new InvalidOperationException(SR.Format(SR.XmlIllegalAnyElement, type.FullName)); } - protected void WriteReferencingElement(string n, string ns, object o) + protected void WriteReferencingElement(string n, string? ns, object? o) { WriteReferencingElement(n, ns, o, false); } @@ -891,7 +895,7 @@ protected void WriteXmlAttribute(XmlNode node, object? container) string dims; XmlQualifiedName qname = TypeScope.ParseWsdlArrayType(attr.Value, out dims, (container is XmlSchemaObject) ? (XmlSchemaObject)container : null); - string value = FromXmlQualifiedName(qname, true) + dims; + string? value = FromXmlQualifiedName(qname, true) + dims; // WriteAttribute(Wsdl.ArrayType, Wsdl.Namespace, value); @@ -984,7 +988,7 @@ protected void WriteAttribute(string localName, byte[]? value) _w.WriteEndAttribute(); } - protected void WriteAttribute(string prefix, string localName, string? ns, string? value) + protected void WriteAttribute(string? prefix, string localName, string? ns, string? value) { if (value == null) return; _w.WriteAttributeString(prefix, localName, null, value); @@ -1266,12 +1270,12 @@ private void WriteArray(string name, string? ns, object o, Type type) } _w.WriteEndElement(); } - protected void WritePotentiallyReferencingElement(string n, string? ns, object? o) + protected void WritePotentiallyReferencingElement(string? n, string? ns, object? o) { WritePotentiallyReferencingElement(n, ns, o, null, false, false); } - protected void WritePotentiallyReferencingElement(string n, string? ns, object? o, Type? ambientType) + protected void WritePotentiallyReferencingElement(string? n, string? ns, object? o, Type? ambientType) { WritePotentiallyReferencingElement(n, ns, o, ambientType, false, false); } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs index 55aa23007248af..01dbe4317d5aec 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs @@ -156,20 +156,20 @@ protected XmlSerializer() { } - public XmlSerializer(Type type, XmlAttributeOverrides overrides, Type[] extraTypes, XmlRootAttribute root, string defaultNamespace) : + public XmlSerializer(Type type, XmlAttributeOverrides? overrides, Type[]? extraTypes, XmlRootAttribute? root, string? defaultNamespace) : this(type, overrides, extraTypes, root, defaultNamespace, null) { } - public XmlSerializer(Type type, XmlRootAttribute root) : this(type, null, Array.Empty(), root, null, null) + public XmlSerializer(Type type, XmlRootAttribute? root) : this(type, null, Array.Empty(), root, null, null) { } - public XmlSerializer(Type type, Type[] extraTypes) : this(type, null, extraTypes, null, null, null) + public XmlSerializer(Type type, Type[]? extraTypes) : this(type, null, extraTypes, null, null, null) { } - public XmlSerializer(Type type, XmlAttributeOverrides overrides) : this(type, overrides, Array.Empty(), null, null, null) + public XmlSerializer(Type type, XmlAttributeOverrides? overrides) : this(type, overrides, Array.Empty(), null, null, null) { } @@ -292,12 +292,12 @@ private XmlTypeMapping GenerateXmlTypeMapping(Type type, XmlAttributeOverrides? return new TempAssembly(new XmlMapping[] { xmlMapping }, new Type?[] { type }, defaultNamespace, location); } - public void Serialize(TextWriter textWriter, object o) + public void Serialize(TextWriter textWriter, object? o) { Serialize(textWriter, o, null); } - public void Serialize(TextWriter textWriter, object o, XmlSerializerNamespaces? namespaces) + public void Serialize(TextWriter textWriter, object? o, XmlSerializerNamespaces? namespaces) { XmlTextWriter xmlWriter = new XmlTextWriter(textWriter); xmlWriter.Formatting = Formatting.Indented; @@ -305,12 +305,12 @@ public void Serialize(TextWriter textWriter, object o, XmlSerializerNamespaces? Serialize(xmlWriter, o, namespaces); } - public void Serialize(Stream stream, object o) + public void Serialize(Stream stream, object? o) { Serialize(stream, o, null); } - public void Serialize(Stream stream, object o, XmlSerializerNamespaces? namespaces) + public void Serialize(Stream stream, object? o, XmlSerializerNamespaces? namespaces) { XmlTextWriter xmlWriter = new XmlTextWriter(stream, null); xmlWriter.Formatting = Formatting.Indented; @@ -318,22 +318,22 @@ public void Serialize(Stream stream, object o, XmlSerializerNamespaces? namespac Serialize(xmlWriter, o, namespaces); } - public void Serialize(XmlWriter xmlWriter, object o) + public void Serialize(XmlWriter xmlWriter, object? o) { Serialize(xmlWriter, o, null); } - public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces? namespaces) + public void Serialize(XmlWriter xmlWriter, object? o, XmlSerializerNamespaces? namespaces) { Serialize(xmlWriter, o, namespaces, null); } - public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces? namespaces, string? encodingStyle) + public void Serialize(XmlWriter xmlWriter, object? o, XmlSerializerNamespaces? namespaces, string? encodingStyle) { Serialize(xmlWriter, o, namespaces, encodingStyle, null); } - public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces? namespaces, string? encodingStyle, string? id) + public void Serialize(XmlWriter xmlWriter, object? o, XmlSerializerNamespaces? namespaces, string? encodingStyle, string? id) { try { @@ -375,7 +375,7 @@ public void Serialize(XmlWriter xmlWriter, object o, XmlSerializerNamespaces? na xmlWriter.Flush(); } - private void SerializeUsingReflection(XmlWriter xmlWriter, object o, XmlSerializerNamespaces? namespaces, string? encodingStyle, string? id) + private void SerializeUsingReflection(XmlWriter xmlWriter, object? o, XmlSerializerNamespaces? namespaces, string? encodingStyle, string? id) { XmlMapping mapping = GetMapping(); var writer = new ReflectionXmlSerializationWriter(mapping, xmlWriter, namespaces == null || namespaces.Count == 0 ? DefaultNamespaces : namespaces, encodingStyle, id); @@ -507,12 +507,12 @@ public virtual bool CanDeserialize(XmlReader xmlReader) } } - public static XmlSerializer[] FromMappings(XmlMapping[] mappings) + public static XmlSerializer[] FromMappings(XmlMapping[]? mappings) { return FromMappings(mappings, (Type?)null); } - public static XmlSerializer[] FromMappings(XmlMapping[] mappings, Type? type) + public static XmlSerializer[] FromMappings(XmlMapping[]? mappings, Type? type) { if (mappings == null || mappings.Length == 0) return Array.Empty(); bool anySoapMapping = false; @@ -683,7 +683,7 @@ private static XmlSerializer[] GetSerializersFromCache(XmlMapping[] mappings, Ty return serializers!; } - public static XmlSerializer[] FromTypes(Type[] types) + public static XmlSerializer[] FromTypes(Type[]? types) { if (types == null) return Array.Empty(); @@ -765,7 +765,7 @@ public event UnreferencedObjectEventHandler UnreferencedObject protected virtual XmlSerializationWriter CreateWriter() { throw new NotImplementedException(); } - protected virtual void Serialize(object o, XmlSerializationWriter writer) { throw new NotImplementedException(); } + protected virtual void Serialize(object? o, XmlSerializationWriter writer) { throw new NotImplementedException(); } internal void SetTempAssembly(TempAssembly tempAssembly, XmlMapping mapping) { diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlTypeAttribute.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlTypeAttribute.cs index 3fd98ce8cc8af4..de408389ce4a8c 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlTypeAttribute.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlTypeAttribute.cs @@ -28,7 +28,7 @@ public XmlTypeAttribute() /// /// [To be supplied.] /// - public XmlTypeAttribute(string typeName) + public XmlTypeAttribute(string? typeName) { _typeName = typeName; } diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Xmlcustomformatter.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Xmlcustomformatter.cs index e8195d91d98689..719eab1c0df102 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Xmlcustomformatter.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/Xmlcustomformatter.cs @@ -112,17 +112,20 @@ internal static string FromChar(char value) return XmlConvert.ToString((ushort)value); } - internal static string FromXmlName(string name) + [return: NotNullIfNotNull("name")] + internal static string? FromXmlName(string? name) { return XmlConvert.EncodeName(name); } - internal static string FromXmlNCName(string ncName) + [return: NotNullIfNotNull("ncName")] + internal static string? FromXmlNCName(string? ncName) { return XmlConvert.EncodeLocalName(ncName); } - internal static string FromXmlNmToken(string nmToken) + [return: NotNullIfNotNull("nmToken")] + internal static string? FromXmlNmToken(string? nmToken) { return XmlConvert.EncodeNmToken(nmToken); } @@ -398,22 +401,26 @@ internal static char ToChar(string value) return (char)XmlConvert.ToUInt16(value); } - internal static string ToXmlName(string value) + [return: NotNullIfNotNull("value")] + internal static string? ToXmlName(string? value) { return XmlConvert.DecodeName(CollapseWhitespace(value)); } - internal static string ToXmlNCName(string value) + [return: NotNullIfNotNull("value")] + internal static string? ToXmlNCName(string? value) { return XmlConvert.DecodeName(CollapseWhitespace(value)); } - internal static string ToXmlNmToken(string value) + [return: NotNullIfNotNull("value")] + internal static string? ToXmlNmToken(string? value) { return XmlConvert.DecodeName(CollapseWhitespace(value)); } - internal static string ToXmlNmTokens(string value) + [return: NotNullIfNotNull("value")] + internal static string? ToXmlNmTokens(string? value) { return XmlConvert.DecodeName(CollapseWhitespace(value)); } From a9d34d3e927c92b3a1fc9b8e56de598899aea472 Mon Sep 17 00:00:00 2001 From: Krzysztof Wicher Date: Thu, 27 Aug 2020 00:10:06 +0200 Subject: [PATCH 5/5] Make XmlSerializer._rootType nullable --- .../src/System/Xml/Serialization/XmlSerializer.cs | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs index 01dbe4317d5aec..a017863bef8983 100644 --- a/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs +++ b/src/libraries/System.Private.Xml/src/System/Xml/Serialization/XmlSerializer.cs @@ -127,7 +127,7 @@ private static bool ReflectionMethodEnabled private XmlMapping _mapping = null!; private XmlDeserializationEvents _events; internal string? DefaultNamespace; - private Type _rootType = null!; + private Type? _rootType; private bool _isReflectionBasedSerializer; private static readonly TempAssemblyCache s_cache = new TempAssemblyCache(); @@ -386,7 +386,7 @@ private XmlMapping GetMapping() { if (_mapping == null || !_mapping.GenerateSerializer) { - _mapping = GenerateXmlTypeMapping(_rootType, null, null, null, DefaultNamespace); + _mapping = GenerateXmlTypeMapping(_rootType!, null, null, null, DefaultNamespace); } return _mapping; @@ -526,7 +526,7 @@ public static XmlSerializer[] FromMappings(XmlMapping[]? mappings, Type? type) if ((anySoapMapping && ReflectionMethodEnabled) || Mode == SerializationMode.ReflectionOnly) { - XmlSerializer[] serializers = GetReflectionBasedSerializers(mappings, type!); + XmlSerializer[] serializers = GetReflectionBasedSerializers(mappings, type); return serializers; } @@ -579,7 +579,7 @@ public static XmlSerializer[] FromMappings(XmlMapping[]? mappings, Type? type) } } - private static XmlSerializer[] GetReflectionBasedSerializers(XmlMapping[] mappings, Type type) + private static XmlSerializer[] GetReflectionBasedSerializers(XmlMapping[] mappings, Type? type) { var serializers = new XmlSerializer[mappings.Length]; for (int i = 0; i < serializers.Length; i++)